Don't use magic sizes, actually calculate them.
[wine/wine64.git] / server / fd.c
blob534867002b37d583e0516b2a27a093ebdc2c2290
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_SYS_POLL_H
34 #include <sys/poll.h>
35 #endif
36 #ifdef HAVE_STDINT_H
37 #include <stdint.h>
38 #endif
39 #ifdef HAVE_SYS_EPOLL_H
40 #include <sys/epoll.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 # define USE_EPOLL
59 #endif
61 /* Because of the stupid Posix locking semantics, we need to keep
62 * track of all file descriptors referencing a given file, and not
63 * close a single one until all the locks are gone (sigh).
66 /* file descriptor object */
68 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
69 struct closed_fd
71 struct list entry; /* entry in inode closed list */
72 int fd; /* the unix file descriptor */
73 char unlink[1]; /* name to unlink on close (if any) */
76 struct fd
78 struct object obj; /* object header */
79 const struct fd_ops *fd_ops; /* file descriptor operations */
80 struct inode *inode; /* inode that this fd belongs to */
81 struct list inode_entry; /* entry in inode fd list */
82 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
83 struct object *user; /* object using this file descriptor */
84 struct list locks; /* list of locks on this fd */
85 unsigned int access; /* file access (GENERIC_READ/WRITE) */
86 unsigned int sharing; /* file sharing mode */
87 int unix_fd; /* unix file descriptor */
88 int fs_locks; /* can we use filesystem locks for this fd? */
89 int poll_index; /* index of fd in poll array */
92 static void fd_dump( struct object *obj, int verbose );
93 static void fd_destroy( struct object *obj );
95 static const struct object_ops fd_ops =
97 sizeof(struct fd), /* size */
98 fd_dump, /* dump */
99 no_add_queue, /* add_queue */
100 NULL, /* remove_queue */
101 NULL, /* signaled */
102 NULL, /* satisfied */
103 no_get_fd, /* get_fd */
104 fd_destroy /* destroy */
107 /* inode object */
109 struct inode
111 struct object obj; /* object header */
112 struct list entry; /* inode hash list entry */
113 unsigned int hash; /* hashing code */
114 dev_t dev; /* device number */
115 ino_t ino; /* inode number */
116 struct list open; /* list of open file descriptors */
117 struct list locks; /* list of file locks */
118 struct list closed; /* list of file descriptors to close at destroy time */
121 static void inode_dump( struct object *obj, int verbose );
122 static void inode_destroy( struct object *obj );
124 static const struct object_ops inode_ops =
126 sizeof(struct inode), /* size */
127 inode_dump, /* dump */
128 no_add_queue, /* add_queue */
129 NULL, /* remove_queue */
130 NULL, /* signaled */
131 NULL, /* satisfied */
132 no_get_fd, /* get_fd */
133 inode_destroy /* destroy */
136 /* file lock object */
138 struct file_lock
140 struct object obj; /* object header */
141 struct fd *fd; /* fd owning this lock */
142 struct list fd_entry; /* entry in list of locks on a given fd */
143 struct list inode_entry; /* entry in inode list of locks */
144 int shared; /* shared lock? */
145 file_pos_t start; /* locked region is interval [start;end) */
146 file_pos_t end;
147 struct process *process; /* process owning this lock */
148 struct list proc_entry; /* entry in list of locks owned by the process */
151 static void file_lock_dump( struct object *obj, int verbose );
152 static int file_lock_signaled( struct object *obj, struct thread *thread );
154 static const struct object_ops file_lock_ops =
156 sizeof(struct file_lock), /* size */
157 file_lock_dump, /* dump */
158 add_queue, /* add_queue */
159 remove_queue, /* remove_queue */
160 file_lock_signaled, /* signaled */
161 no_satisfied, /* satisfied */
162 no_get_fd, /* get_fd */
163 no_destroy /* destroy */
167 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
168 #define FILE_POS_T_MAX (~(file_pos_t)0)
170 static file_pos_t max_unix_offset = OFF_T_MAX;
172 #define DUMP_LONG_LONG(val) do { \
173 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
174 fprintf( stderr, "%lx%08lx", (unsigned long)((val) >> 32), (unsigned long)(val) ); \
175 else \
176 fprintf( stderr, "%lx", (unsigned long)(val) ); \
177 } while (0)
181 /****************************************************************/
182 /* timeouts support */
184 struct timeout_user
186 struct list entry; /* entry in sorted timeout list */
187 struct timeval when; /* timeout expiry (absolute time) */
188 timeout_callback callback; /* callback function */
189 void *private; /* callback private data */
192 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
194 /* add a timeout user */
195 struct timeout_user *add_timeout_user( struct timeval *when, timeout_callback func, void *private )
197 struct timeout_user *user;
198 struct list *ptr;
200 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
201 user->when = *when;
202 user->callback = func;
203 user->private = private;
205 /* Now insert it in the linked list */
207 LIST_FOR_EACH( ptr, &timeout_list )
209 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
210 if (!time_before( &timeout->when, when )) break;
212 list_add_before( ptr, &user->entry );
213 return user;
216 /* remove a timeout user */
217 void remove_timeout_user( struct timeout_user *user )
219 list_remove( &user->entry );
220 free( user );
223 /* add a timeout in milliseconds to an absolute time */
224 void add_timeout( struct timeval *when, int timeout )
226 if (timeout)
228 long sec = timeout / 1000;
229 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
231 when->tv_usec -= 1000000;
232 when->tv_sec++;
234 when->tv_sec += sec;
239 /****************************************************************/
240 /* poll support */
242 static struct fd **poll_users; /* users array */
243 static struct pollfd *pollfd; /* poll fd array */
244 static int nb_users; /* count of array entries actually in use */
245 static int active_users; /* current number of active users */
246 static int allocated_users; /* count of allocated entries in the array */
247 static struct fd **freelist; /* list of free entries in the array */
249 #ifdef USE_EPOLL
251 static int epoll_fd;
252 static struct epoll_event *epoll_events;
254 /* set the events that epoll waits for on this fd; helper for set_fd_events */
255 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
257 struct epoll_event ev;
258 int ctl;
260 if (epoll_fd == -1) return;
262 if (events == -1) /* stop waiting on this fd completely */
264 if (pollfd[user].fd == -1) return; /* already removed */
265 ctl = EPOLL_CTL_DEL;
267 else if (pollfd[user].fd == -1)
269 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
270 ctl = EPOLL_CTL_ADD;
272 else
274 if (pollfd[user].events == events) return; /* nothing to do */
275 ctl = EPOLL_CTL_MOD;
278 ev.events = events;
279 ev.data.u32 = user;
281 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
283 if (errno == ENOMEM) /* not enough memory, give up on epoll */
285 close( epoll_fd );
286 epoll_fd = -1;
288 else perror( "epoll_ctl" ); /* should not happen */
292 #else /* USE_EPOLL */
294 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
298 #endif /* USE_EPOLL */
301 /* add a user in the poll array and return its index, or -1 on failure */
302 static int add_poll_user( struct fd *fd )
304 int ret;
305 if (freelist)
307 ret = freelist - poll_users;
308 freelist = (struct fd **)poll_users[ret];
310 else
312 if (nb_users == allocated_users)
314 struct fd **newusers;
315 struct pollfd *newpoll;
316 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
317 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
318 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
320 if (allocated_users)
321 poll_users = newusers;
322 else
323 free( newusers );
324 return -1;
326 poll_users = newusers;
327 pollfd = newpoll;
328 #ifdef USE_EPOLL
329 if (!allocated_users) epoll_fd = epoll_create( new_count );
330 if (epoll_fd != -1)
332 struct epoll_event *new_events;
333 if (!(new_events = realloc( epoll_events, new_count * sizeof(*epoll_events) )))
334 return -1;
335 epoll_events = new_events;
337 #endif
338 allocated_users = new_count;
340 ret = nb_users++;
342 pollfd[ret].fd = -1;
343 pollfd[ret].events = 0;
344 pollfd[ret].revents = 0;
345 poll_users[ret] = fd;
346 active_users++;
347 return ret;
350 /* remove a user from the poll list */
351 static void remove_poll_user( struct fd *fd, int user )
353 assert( user >= 0 );
354 assert( poll_users[user] == fd );
356 #ifdef USE_EPOLL
357 if (epoll_fd != -1 && pollfd[user].fd != -1)
359 struct epoll_event dummy;
360 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
362 #endif
363 pollfd[user].fd = -1;
364 pollfd[user].events = 0;
365 pollfd[user].revents = 0;
366 poll_users[user] = (struct fd *)freelist;
367 freelist = &poll_users[user];
368 active_users--;
371 /* process pending timeouts and return the time until the next timeout, in milliseconds */
372 static int get_next_timeout(void)
374 if (!list_empty( &timeout_list ))
376 struct list expired_list, *ptr;
377 struct timeval now;
379 gettimeofday( &now, NULL );
381 /* first remove all expired timers from the list */
383 list_init( &expired_list );
384 while ((ptr = list_head( &timeout_list )) != NULL)
386 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
388 if (!time_before( &now, &timeout->when ))
390 list_remove( &timeout->entry );
391 list_add_tail( &expired_list, &timeout->entry );
393 else break;
396 /* now call the callback for all the removed timers */
398 while ((ptr = list_head( &expired_list )) != NULL)
400 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
401 list_remove( &timeout->entry );
402 timeout->callback( timeout->private );
403 free( timeout );
406 if ((ptr = list_head( &timeout_list )) != NULL)
408 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
409 int diff = (timeout->when.tv_sec - now.tv_sec) * 1000
410 + (timeout->when.tv_usec - now.tv_usec) / 1000;
411 if (diff < 0) diff = 0;
412 return diff;
415 return -1; /* no pending timeouts */
418 /* server main poll() loop */
419 void main_loop(void)
421 int i, ret, timeout;
423 #ifdef USE_EPOLL
424 assert( POLLIN == EPOLLIN );
425 assert( POLLOUT == EPOLLOUT );
426 assert( POLLERR == EPOLLERR );
427 assert( POLLHUP == EPOLLHUP );
429 if (epoll_fd != -1)
431 while (active_users)
433 timeout = get_next_timeout();
435 if (!active_users) break; /* last user removed by a timeout */
436 if (epoll_fd == -1) break; /* an error occurred with epoll */
438 ret = epoll_wait( epoll_fd, epoll_events, allocated_users, timeout );
440 /* put the events into the pollfd array first, like poll does */
441 for (i = 0; i < ret; i++)
443 int user = epoll_events[i].data.u32;
444 pollfd[user].revents = epoll_events[i].events;
447 /* read events from the pollfd array, as set_fd_events may modify them */
448 for (i = 0; i < ret; i++)
450 int user = epoll_events[i].data.u32;
451 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
455 /* fall through to normal poll loop */
456 #endif /* USE_EPOLL */
458 while (active_users)
460 timeout = get_next_timeout();
462 if (!active_users) break; /* last user removed by a timeout */
464 ret = poll( pollfd, nb_users, timeout );
465 if (ret > 0)
467 for (i = 0; i < nb_users; i++)
469 if (pollfd[i].revents)
471 fd_poll_event( poll_users[i], pollfd[i].revents );
472 if (!--ret) break;
480 /****************************************************************/
481 /* inode functions */
483 #define HASH_SIZE 37
485 static struct list inode_hash[HASH_SIZE];
487 /* close all pending file descriptors in the closed list */
488 static void inode_close_pending( struct inode *inode )
490 struct list *ptr = list_head( &inode->closed );
492 while (ptr)
494 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
495 struct list *next = list_next( &inode->closed, ptr );
497 if (fd->fd != -1)
499 close( fd->fd );
500 fd->fd = -1;
502 if (!fd->unlink) /* get rid of it unless there's an unlink pending on that file */
504 list_remove( ptr );
505 free( fd );
507 ptr = next;
512 static void inode_dump( struct object *obj, int verbose )
514 struct inode *inode = (struct inode *)obj;
515 fprintf( stderr, "Inode dev=" );
516 DUMP_LONG_LONG( inode->dev );
517 fprintf( stderr, " ino=" );
518 DUMP_LONG_LONG( inode->ino );
519 fprintf( stderr, "\n" );
522 static void inode_destroy( struct object *obj )
524 struct inode *inode = (struct inode *)obj;
525 struct list *ptr;
527 assert( list_empty(&inode->open) );
528 assert( list_empty(&inode->locks) );
530 list_remove( &inode->entry );
532 while ((ptr = list_head( &inode->closed )))
534 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
535 list_remove( ptr );
536 if (fd->fd != -1) close( fd->fd );
537 if (fd->unlink[0])
539 /* make sure it is still the same file */
540 struct stat st;
541 if (!stat( fd->unlink, &st ) && st.st_dev == inode->dev && st.st_ino == inode->ino)
543 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
544 else unlink( fd->unlink );
547 free( fd );
551 /* retrieve the inode object for a given fd, creating it if needed */
552 static struct inode *get_inode( dev_t dev, ino_t ino )
554 struct list *ptr;
555 struct inode *inode;
556 unsigned int hash = (dev ^ ino) % HASH_SIZE;
558 if (inode_hash[hash].next)
560 LIST_FOR_EACH( ptr, &inode_hash[hash] )
562 inode = LIST_ENTRY( ptr, struct inode, entry );
563 if (inode->dev == dev && inode->ino == ino)
564 return (struct inode *)grab_object( inode );
567 else list_init( &inode_hash[hash] );
569 /* not found, create it */
570 if ((inode = alloc_object( &inode_ops )))
572 inode->hash = hash;
573 inode->dev = dev;
574 inode->ino = ino;
575 list_init( &inode->open );
576 list_init( &inode->locks );
577 list_init( &inode->closed );
578 list_add_head( &inode_hash[hash], &inode->entry );
580 return inode;
583 /* add fd to the indoe list of file descriptors to close */
584 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
586 if (!list_empty( &inode->locks ))
588 list_add_head( &inode->closed, &fd->entry );
590 else if (fd->unlink[0]) /* close the fd but keep the structure around for unlink */
592 close( fd->fd );
593 fd->fd = -1;
594 list_add_head( &inode->closed, &fd->entry );
596 else /* no locks on this inode and no unlink, get rid of the fd */
598 close( fd->fd );
599 free( fd );
604 /****************************************************************/
605 /* file lock functions */
607 static void file_lock_dump( struct object *obj, int verbose )
609 struct file_lock *lock = (struct file_lock *)obj;
610 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
611 lock->shared ? "shared" : "excl", lock->fd, lock->process );
612 DUMP_LONG_LONG( lock->start );
613 fprintf( stderr, " end=" );
614 DUMP_LONG_LONG( lock->end );
615 fprintf( stderr, "\n" );
618 static int file_lock_signaled( struct object *obj, struct thread *thread )
620 struct file_lock *lock = (struct file_lock *)obj;
621 /* lock is signaled if it has lost its owner */
622 return !lock->process;
625 /* set (or remove) a Unix lock if possible for the given range */
626 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
628 struct flock fl;
630 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
631 for (;;)
633 if (start == end) return 1; /* can't set zero-byte lock */
634 if (start > max_unix_offset) return 1; /* ignore it */
635 fl.l_type = type;
636 fl.l_whence = SEEK_SET;
637 fl.l_start = start;
638 if (!end || end > max_unix_offset) fl.l_len = 0;
639 else fl.l_len = end - start;
640 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
642 switch(errno)
644 case EACCES:
645 /* check whether locks work at all on this file system */
646 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
648 set_error( STATUS_FILE_LOCK_CONFLICT );
649 return 0;
651 /* fall through */
652 case EIO:
653 case ENOLCK:
654 /* no locking on this fs, just ignore it */
655 fd->fs_locks = 0;
656 return 1;
657 case EAGAIN:
658 set_error( STATUS_FILE_LOCK_CONFLICT );
659 return 0;
660 case EBADF:
661 /* this can happen if we try to set a write lock on a read-only file */
662 /* we just ignore that error */
663 if (fl.l_type == F_WRLCK) return 1;
664 set_error( STATUS_ACCESS_DENIED );
665 return 0;
666 #ifdef EOVERFLOW
667 case EOVERFLOW:
668 #endif
669 case EINVAL:
670 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
671 /* in that case we shrink the limit and retry */
672 if (max_unix_offset > INT_MAX)
674 max_unix_offset = INT_MAX;
675 break; /* retry */
677 /* fall through */
678 default:
679 file_set_error();
680 return 0;
685 /* check if interval [start;end) overlaps the lock */
686 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
688 if (lock->end && start >= lock->end) return 0;
689 if (end && lock->start >= end) return 0;
690 return 1;
693 /* remove Unix locks for all bytes in the specified area that are no longer locked */
694 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
696 struct hole
698 struct hole *next;
699 struct hole *prev;
700 file_pos_t start;
701 file_pos_t end;
702 } *first, *cur, *next, *buffer;
704 struct list *ptr;
705 int count = 0;
707 if (!fd->inode) return;
708 if (!fd->fs_locks) return;
709 if (start == end || start > max_unix_offset) return;
710 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
712 /* count the number of locks overlapping the specified area */
714 LIST_FOR_EACH( ptr, &fd->inode->locks )
716 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
717 if (lock->start == lock->end) continue;
718 if (lock_overlaps( lock, start, end )) count++;
721 if (!count) /* no locks at all, we can unlock everything */
723 set_unix_lock( fd, start, end, F_UNLCK );
724 return;
727 /* allocate space for the list of holes */
728 /* max. number of holes is number of locks + 1 */
730 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
731 first = buffer;
732 first->next = NULL;
733 first->prev = NULL;
734 first->start = start;
735 first->end = end;
736 next = first + 1;
738 /* build a sorted list of unlocked holes in the specified area */
740 LIST_FOR_EACH( ptr, &fd->inode->locks )
742 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
743 if (lock->start == lock->end) continue;
744 if (!lock_overlaps( lock, start, end )) continue;
746 /* go through all the holes touched by this lock */
747 for (cur = first; cur; cur = cur->next)
749 if (cur->end <= lock->start) continue; /* hole is before start of lock */
750 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
752 /* now we know that lock is overlapping hole */
754 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
756 cur->start = lock->end;
757 if (cur->start && cur->start < cur->end) break; /* done with this lock */
758 /* now hole is empty, remove it */
759 if (cur->next) cur->next->prev = cur->prev;
760 if (cur->prev) cur->prev->next = cur->next;
761 else if (!(first = cur->next)) goto done; /* no more holes at all */
763 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
765 cur->end = lock->start;
766 assert( cur->start < cur->end );
768 else /* lock is in the middle of hole, split hole in two */
770 next->prev = cur;
771 next->next = cur->next;
772 cur->next = next;
773 next->start = lock->end;
774 next->end = cur->end;
775 cur->end = lock->start;
776 assert( next->start < next->end );
777 assert( cur->end < next->start );
778 next++;
779 break; /* done with this lock */
784 /* clear Unix locks for all the holes */
786 for (cur = first; cur; cur = cur->next)
787 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
789 done:
790 free( buffer );
793 /* create a new lock on a fd */
794 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
796 struct file_lock *lock;
798 if (!fd->inode) /* not a regular file */
800 set_error( STATUS_INVALID_HANDLE );
801 return NULL;
804 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
805 lock->shared = shared;
806 lock->start = start;
807 lock->end = end;
808 lock->fd = fd;
809 lock->process = current->process;
811 /* now try to set a Unix lock */
812 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
814 release_object( lock );
815 return NULL;
817 list_add_head( &fd->locks, &lock->fd_entry );
818 list_add_head( &fd->inode->locks, &lock->inode_entry );
819 list_add_head( &lock->process->locks, &lock->proc_entry );
820 return lock;
823 /* remove an existing lock */
824 static void remove_lock( struct file_lock *lock, int remove_unix )
826 struct inode *inode = lock->fd->inode;
828 list_remove( &lock->fd_entry );
829 list_remove( &lock->inode_entry );
830 list_remove( &lock->proc_entry );
831 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
832 if (list_empty( &inode->locks )) inode_close_pending( inode );
833 lock->process = NULL;
834 wake_up( &lock->obj, 0 );
835 release_object( lock );
838 /* remove all locks owned by a given process */
839 void remove_process_locks( struct process *process )
841 struct list *ptr;
843 while ((ptr = list_head( &process->locks )))
845 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
846 remove_lock( lock, 1 ); /* this removes it from the list */
850 /* remove all locks on a given fd */
851 static void remove_fd_locks( struct fd *fd )
853 file_pos_t start = FILE_POS_T_MAX, end = 0;
854 struct list *ptr;
856 while ((ptr = list_head( &fd->locks )))
858 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
859 if (lock->start < start) start = lock->start;
860 if (!lock->end || lock->end > end) end = lock->end - 1;
861 remove_lock( lock, 0 );
863 if (start < end) remove_unix_locks( fd, start, end + 1 );
866 /* add a lock on an fd */
867 /* returns handle to wait on */
868 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
870 struct list *ptr;
871 file_pos_t end = start + count;
873 /* don't allow wrapping locks */
874 if (end && end < start)
876 set_error( STATUS_INVALID_PARAMETER );
877 return 0;
880 /* check if another lock on that file overlaps the area */
881 LIST_FOR_EACH( ptr, &fd->inode->locks )
883 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
884 if (!lock_overlaps( lock, start, end )) continue;
885 if (lock->shared && shared) continue;
886 /* found one */
887 if (!wait)
889 set_error( STATUS_FILE_LOCK_CONFLICT );
890 return 0;
892 set_error( STATUS_PENDING );
893 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
896 /* not found, add it */
897 if (add_lock( fd, shared, start, end )) return 0;
898 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
900 /* Unix lock conflict -> tell client to wait and retry */
901 if (wait) set_error( STATUS_PENDING );
903 return 0;
906 /* remove a lock on an fd */
907 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
909 struct list *ptr;
910 file_pos_t end = start + count;
912 /* find an existing lock with the exact same parameters */
913 LIST_FOR_EACH( ptr, &fd->locks )
915 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
916 if ((lock->start == start) && (lock->end == end))
918 remove_lock( lock, 1 );
919 return;
922 set_error( STATUS_FILE_LOCK_CONFLICT );
926 /****************************************************************/
927 /* file descriptor functions */
929 static void fd_dump( struct object *obj, int verbose )
931 struct fd *fd = (struct fd *)obj;
932 fprintf( stderr, "Fd unix_fd=%d user=%p unlink='%s'\n",
933 fd->unix_fd, fd->user, fd->closed->unlink );
936 static void fd_destroy( struct object *obj )
938 struct fd *fd = (struct fd *)obj;
940 remove_fd_locks( fd );
941 list_remove( &fd->inode_entry );
942 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
943 if (fd->inode)
945 inode_add_closed_fd( fd->inode, fd->closed );
946 release_object( fd->inode );
948 else /* no inode, close it right away */
950 if (fd->unix_fd != -1) close( fd->unix_fd );
954 /* set the events that select waits for on this fd */
955 void set_fd_events( struct fd *fd, int events )
957 int user = fd->poll_index;
958 assert( poll_users[user] == fd );
960 set_fd_epoll_events( fd, user, events );
962 if (events == -1) /* stop waiting on this fd completely */
964 pollfd[user].fd = -1;
965 pollfd[user].events = POLLERR;
966 pollfd[user].revents = 0;
968 else if (pollfd[user].fd != -1 || !pollfd[user].events)
970 pollfd[user].fd = fd->unix_fd;
971 pollfd[user].events = events;
975 /* allocate an fd object, without setting the unix fd yet */
976 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
978 struct fd *fd = alloc_object( &fd_ops );
980 if (!fd) return NULL;
982 fd->fd_ops = fd_user_ops;
983 fd->user = user;
984 fd->inode = NULL;
985 fd->closed = NULL;
986 fd->access = 0;
987 fd->sharing = 0;
988 fd->unix_fd = -1;
989 fd->fs_locks = 1;
990 fd->poll_index = -1;
991 list_init( &fd->inode_entry );
992 list_init( &fd->locks );
994 if ((fd->poll_index = add_poll_user( fd )) == -1)
996 release_object( fd );
997 return NULL;
999 return fd;
1002 /* check if the desired access is possible without violating */
1003 /* the sharing mode of other opens of the same file */
1004 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1006 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1007 unsigned int existing_access = 0;
1008 int unlink = 0;
1009 struct list *ptr;
1011 /* if access mode is 0, sharing mode is ignored */
1012 if (!access) sharing = existing_sharing;
1013 fd->access = access;
1014 fd->sharing = sharing;
1016 LIST_FOR_EACH( ptr, &fd->inode->open )
1018 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1019 if (fd_ptr != fd)
1021 existing_sharing &= fd_ptr->sharing;
1022 existing_access |= fd_ptr->access;
1023 if (fd_ptr->closed->unlink[0]) unlink = 1;
1027 if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1028 if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1029 if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
1030 if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
1031 if (fd->closed->unlink[0] && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1032 if (unlink && !(sharing & FILE_SHARE_DELETE)) return 0;
1033 return 1;
1036 /* open() wrapper using a struct fd */
1037 /* the fd must have been created with alloc_fd */
1038 /* on error the fd object is released */
1039 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
1040 unsigned int access, unsigned int sharing, unsigned int options )
1042 struct stat st;
1043 struct closed_fd *closed_fd;
1044 const char *unlink_name = "";
1046 assert( fd->unix_fd == -1 );
1048 if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1049 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1051 release_object( fd );
1052 return NULL;
1054 /* create the directory if needed */
1055 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1057 if (mkdir( name, 0777 ) == -1)
1059 if (errno != EEXIST || (flags & O_EXCL))
1061 file_set_error();
1062 release_object( fd );
1063 free( closed_fd );
1064 return NULL;
1067 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1069 if ((fd->unix_fd = open( name, flags & ~O_TRUNC, *mode )) == -1)
1071 file_set_error();
1072 release_object( fd );
1073 free( closed_fd );
1074 return NULL;
1076 closed_fd->fd = fd->unix_fd;
1077 closed_fd->unlink[0] = 0;
1078 fstat( fd->unix_fd, &st );
1079 *mode = st.st_mode;
1081 /* only bother with an inode for normal files and directories */
1082 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1084 struct inode *inode = get_inode( st.st_dev, st.st_ino );
1086 if (!inode)
1088 /* we can close the fd because there are no others open on the same file,
1089 * otherwise we wouldn't have failed to allocate a new inode
1091 goto error;
1093 fd->inode = inode;
1094 fd->closed = closed_fd;
1095 list_add_head( &inode->open, &fd->inode_entry );
1097 /* check directory options */
1098 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1100 release_object( fd );
1101 set_error( STATUS_NOT_A_DIRECTORY );
1102 return NULL;
1104 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1106 release_object( fd );
1107 set_error( STATUS_FILE_IS_A_DIRECTORY );
1108 return NULL;
1110 if (!check_sharing( fd, access, sharing ))
1112 release_object( fd );
1113 set_error( STATUS_SHARING_VIOLATION );
1114 return NULL;
1116 strcpy( closed_fd->unlink, unlink_name );
1117 if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1119 else /* special file */
1121 if (options & FILE_DIRECTORY_FILE)
1123 set_error( STATUS_NOT_A_DIRECTORY );
1124 goto error;
1126 if (unlink_name[0]) /* we can't unlink special files */
1128 set_error( STATUS_INVALID_PARAMETER );
1129 goto error;
1131 free( closed_fd );
1133 return fd;
1135 error:
1136 release_object( fd );
1137 free( closed_fd );
1138 return NULL;
1141 /* create an fd for an anonymous file */
1142 /* if the function fails the unix fd is closed */
1143 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
1145 struct fd *fd = alloc_fd( fd_user_ops, user );
1147 if (fd)
1149 fd->unix_fd = unix_fd;
1150 return fd;
1152 close( unix_fd );
1153 return NULL;
1156 /* retrieve the object that is using an fd */
1157 void *get_fd_user( struct fd *fd )
1159 return fd->user;
1162 /* retrieve the unix fd for an object */
1163 int get_unix_fd( struct fd *fd )
1165 return fd->unix_fd;
1168 /* check if two file descriptors point to the same file */
1169 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1171 return fd1->inode == fd2->inode;
1174 /* callback for event happening in the main poll() loop */
1175 void fd_poll_event( struct fd *fd, int event )
1177 return fd->fd_ops->poll_event( fd, event );
1180 /* check if events are pending and if yes return which one(s) */
1181 int check_fd_events( struct fd *fd, int events )
1183 struct pollfd pfd;
1185 pfd.fd = fd->unix_fd;
1186 pfd.events = events;
1187 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1188 return pfd.revents;
1191 /* default add_queue() routine for objects that poll() on an fd */
1192 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
1194 struct fd *fd = get_obj_fd( obj );
1196 if (!fd) return 0;
1197 if (!obj->head) /* first on the queue */
1198 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1199 add_queue( obj, entry );
1200 release_object( fd );
1201 return 1;
1204 /* default remove_queue() routine for objects that poll() on an fd */
1205 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
1207 struct fd *fd = get_obj_fd( obj );
1209 grab_object( obj );
1210 remove_queue( obj, entry );
1211 if (!obj->head) /* last on the queue is gone */
1212 set_fd_events( fd, 0 );
1213 release_object( obj );
1214 release_object( fd );
1217 /* default signaled() routine for objects that poll() on an fd */
1218 int default_fd_signaled( struct object *obj, struct thread *thread )
1220 struct fd *fd = get_obj_fd( obj );
1221 int events = fd->fd_ops->get_poll_events( fd );
1222 int ret = check_fd_events( fd, events ) != 0;
1224 if (ret)
1225 set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1226 else if (obj->head)
1227 set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1229 release_object( fd );
1230 return ret;
1233 /* default handler for poll() events */
1234 void default_poll_event( struct fd *fd, int event )
1236 /* an error occurred, stop polling this fd to avoid busy-looping */
1237 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1238 wake_up( fd->user, 0 );
1241 /* default flush() routine */
1242 int no_flush( struct fd *fd, struct event **event )
1244 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1245 return 0;
1248 /* default get_file_info() routine */
1249 int no_get_file_info( struct fd *fd )
1251 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1252 return 0;
1255 /* default queue_async() routine */
1256 void no_queue_async( struct fd *fd, void* ptr, unsigned int status, int type, int count )
1258 set_error( STATUS_OBJECT_TYPE_MISMATCH );
1261 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1262 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1263 unsigned int access )
1265 struct fd *fd = NULL;
1266 struct object *obj;
1268 if ((obj = get_handle_obj( process, handle, access, NULL )))
1270 fd = get_obj_fd( obj );
1271 release_object( obj );
1273 return fd;
1276 /* flush a file buffers */
1277 DECL_HANDLER(flush_file)
1279 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1280 struct event * event = NULL;
1282 if (fd)
1284 fd->fd_ops->flush( fd, &event );
1285 if( event )
1287 reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1289 release_object( fd );
1293 /* get a Unix fd to access a file */
1294 DECL_HANDLER(get_handle_fd)
1296 struct fd *fd;
1298 reply->fd = -1;
1300 if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1302 int unix_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1303 if (unix_fd != -1) reply->fd = unix_fd;
1304 else if (!get_error())
1306 assert( fd->unix_fd != -1 );
1307 send_client_fd( current->process, fd->unix_fd, req->handle );
1309 reply->flags = fd->fd_ops->get_file_info( fd );
1310 release_object( fd );
1314 /* create / reschedule an async I/O */
1315 DECL_HANDLER(register_async)
1317 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1320 * The queue_async method must do the following:
1322 * 1. Get the async_queue for the request of given type.
1323 * 2. Call find_async() to look for the specific client request in the queue (=> NULL if not found).
1324 * 3. If status is STATUS_PENDING:
1325 * a) If no async request found in step 2 (new request): call create_async() to initialize one.
1326 * b) Set request's status to STATUS_PENDING.
1327 * c) If the "queue" field of the async request is NULL: call async_insert() to put it into the queue.
1328 * Otherwise:
1329 * If the async request was found in step 2, destroy it by calling destroy_async().
1330 * 4. Carry out any operations necessary to adjust the object's poll events
1331 * Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1333 * See also the implementations in file.c, serial.c, and sock.c.
1336 if (fd)
1338 fd->fd_ops->queue_async( fd, req->overlapped, req->status, req->type, req->count );
1339 release_object( fd );