fd.c 62.3 KB
Newer Older
1 2 3
/*
 * Server-side file descriptor management
 *
4
 * Copyright (C) 2000, 2003 Alexandre Julliard
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21 22
 */


#include "config.h"
23
#include "wine/port.h"
24 25

#include <assert.h>
26
#include <errno.h>
27
#include <fcntl.h>
28
#include <limits.h>
29
#include <signal.h>
30
#include <stdarg.h>
31 32 33
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
34 35 36
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
37 38 39
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
40 41 42 43 44 45 46
#ifdef HAVE_LINUX_MAJOR_H
#include <linux/major.h>
#endif
#ifdef HAVE_SYS_STATVFS_H
#include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_VFS_H
47 48 49 50 51 52 53 54 55 56 57
/*
 * Solaris defines its system list in sys/list.h.
 * This need to be workaround it here.
 */
#define list SYSLIST
#define list_next SYSLIST_NEXT
#define list_prev SYSLIST_PREV
#define list_head SYSLIST_HEAD
#define list_tail SYSLIST_TAIL
#define list_move_tail SYSLIST_MOVE_TAIL
#define list_remove SYSLIST_REMOVE
58
#include <sys/vfs.h>
59 60 61 62 63 64 65
#undef list
#undef list_next
#undef list_prev
#undef list_head
#undef list_tail
#undef list_move_tail
#undef list_remove
66
#endif
67 68 69
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
70 71 72 73 74 75
#ifdef HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#ifdef HAVE_SYS_STATFS_H
#include <sys/statfs.h>
#endif
76 77 78
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
79 80 81 82 83
#ifdef HAVE_SYS_EVENT_H
#include <sys/event.h>
#undef LIST_INIT
#undef LIST_ENTRY
#endif
84 85 86
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
87
#include <sys/stat.h>
88 89
#include <sys/time.h>
#include <sys/types.h>
90 91
#include <unistd.h>

92 93
#include "ntstatus.h"
#define WIN32_NO_STATUS
94 95 96 97 98 99
#include "object.h"
#include "file.h"
#include "handle.h"
#include "process.h"
#include "request.h"

100
#include "winternl.h"
101
#include "winioctl.h"
102

103
#if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
104
# include <sys/epoll.h>
105
# define USE_EPOLL
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
#elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
# define USE_EPOLL
# define EPOLLIN POLLIN
# define EPOLLOUT POLLOUT
# define EPOLLERR POLLERR
# define EPOLLHUP POLLHUP
# define EPOLL_CTL_ADD 1
# define EPOLL_CTL_DEL 2
# define EPOLL_CTL_MOD 3

typedef union epoll_data
{
  void *ptr;
  int fd;
  uint32_t u32;
  uint64_t u64;
} epoll_data_t;

struct epoll_event
{
  uint32_t events;
  epoll_data_t data;
};

#define SYSCALL_RET(ret) do { \
        if (ret < 0) { errno = -ret; ret = -1; } \
        return ret; \
    } while(0)

static inline int epoll_create( int size )
{
    int ret;
    __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
139
             : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
140 141 142 143 144 145 146 147
    SYSCALL_RET(ret);
}

static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
{
    int ret;
    __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
             : "=a" (ret)
148
             : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
149 150 151 152 153 154 155 156
    SYSCALL_RET(ret);
}

static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
{
    int ret;
    __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
             : "=a" (ret)
157
             : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
158 159 160 161 162 163 164
             : "memory" );
    SYSCALL_RET(ret);
}
#undef SYSCALL_RET

#endif /* linux && __i386__ && HAVE_STDINT_H */

165

166 167 168 169 170
/* Because of the stupid Posix locking semantics, we need to keep
 * track of all file descriptors referencing a given file, and not
 * close a single one until all the locks are gone (sigh).
 */

171 172 173 174 175
/* file descriptor object */

/* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
struct closed_fd
{
176
    struct list entry;       /* entry in inode closed list */
177
    int         unix_fd;     /* the unix file descriptor */
178
    char        unlink[1];   /* name to unlink on close (if any) */
179 180
};

181 182
struct fd
{
183 184 185 186 187 188
    struct object        obj;         /* object header */
    const struct fd_ops *fd_ops;      /* file descriptor operations */
    struct inode        *inode;       /* inode that this fd belongs to */
    struct list          inode_entry; /* entry in inode fd list */
    struct closed_fd    *closed;      /* structure to store the unix fd at destroy time */
    struct object       *user;        /* object using this file descriptor */
189
    struct list          locks;       /* list of locks on this fd */
190
    unsigned int         access;      /* file access (FILE_READ_DATA etc.) */
191
    unsigned int         options;     /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
192
    unsigned int         sharing;     /* file sharing mode */
193
    int                  unix_fd;     /* unix file descriptor */
194
    unsigned int         no_fd_status;/* status to return when unix_fd is -1 */
195
    int                  signaled :1; /* is the fd signaled? */
196
    int                  fs_locks :1; /* can we use filesystem locks for this fd? */
197
    int                  poll_index;  /* index of fd in poll array */
198 199 200
    struct async_queue  *read_q;      /* async readers of this fd */
    struct async_queue  *write_q;     /* async writers of this fd */
    struct async_queue  *wait_q;      /* other async waiters of this fd */
201
    struct completion   *completion;  /* completion object attached to this fd */
202
    apc_param_t          comp_key;    /* completion key to set in completion events */
203 204 205 206 207 208 209 210 211
};

static void fd_dump( struct object *obj, int verbose );
static void fd_destroy( struct object *obj );

static const struct object_ops fd_ops =
{
    sizeof(struct fd),        /* size */
    fd_dump,                  /* dump */
212
    no_get_type,              /* get_type */
213 214 215 216
    no_add_queue,             /* add_queue */
    NULL,                     /* remove_queue */
    NULL,                     /* signaled */
    NULL,                     /* satisfied */
217
    no_signal,                /* signal */
218
    no_get_fd,                /* get_fd */
219
    no_map_access,            /* map_access */
220 221
    default_get_sd,           /* get_sd */
    default_set_sd,           /* set_sd */
222
    no_lookup_name,           /* lookup_name */
223
    no_open_file,             /* open_file */
224
    no_close_handle,          /* close_handle */
225 226 227
    fd_destroy                /* destroy */
};

228 229 230 231 232 233 234 235 236 237
/* device object */

#define DEVICE_HASH_SIZE 7
#define INODE_HASH_SIZE 17

struct device
{
    struct object       obj;        /* object header */
    struct list         entry;      /* entry in device hash list */
    dev_t               dev;        /* device number */
238
    int                 removable;  /* removable device? (or -1 if unknown) */
239 240 241 242 243 244 245 246 247 248
    struct list         inode_hash[INODE_HASH_SIZE];  /* inodes hash table */
};

static void device_dump( struct object *obj, int verbose );
static void device_destroy( struct object *obj );

static const struct object_ops device_ops =
{
    sizeof(struct device),    /* size */
    device_dump,              /* dump */
249
    no_get_type,              /* get_type */
250 251 252 253 254 255
    no_add_queue,             /* add_queue */
    NULL,                     /* remove_queue */
    NULL,                     /* signaled */
    NULL,                     /* satisfied */
    no_signal,                /* signal */
    no_get_fd,                /* get_fd */
256
    no_map_access,            /* map_access */
257 258
    default_get_sd,           /* get_sd */
    default_set_sd,           /* set_sd */
259
    no_lookup_name,           /* lookup_name */
260
    no_open_file,             /* open_file */
261 262 263 264
    no_close_handle,          /* close_handle */
    device_destroy            /* destroy */
};

265 266 267 268 269 270
/* inode object */

struct inode
{
    struct object       obj;        /* object header */
    struct list         entry;      /* inode hash list entry */
271
    struct device      *device;     /* device containing this inode */
272 273
    ino_t               ino;        /* inode number */
    struct list         open;       /* list of open file descriptors */
274
    struct list         locks;      /* list of file locks */
275
    struct list         closed;     /* list of file descriptors to close at destroy time */
276 277 278 279 280 281 282 283 284
};

static void inode_dump( struct object *obj, int verbose );
static void inode_destroy( struct object *obj );

static const struct object_ops inode_ops =
{
    sizeof(struct inode),     /* size */
    inode_dump,               /* dump */
285
    no_get_type,              /* get_type */
286 287 288 289
    no_add_queue,             /* add_queue */
    NULL,                     /* remove_queue */
    NULL,                     /* signaled */
    NULL,                     /* satisfied */
290
    no_signal,                /* signal */
291
    no_get_fd,                /* get_fd */
292
    no_map_access,            /* map_access */
293 294
    default_get_sd,           /* get_sd */
    default_set_sd,           /* set_sd */
295
    no_lookup_name,           /* lookup_name */
296
    no_open_file,             /* open_file */
297
    no_close_handle,          /* close_handle */
298 299 300
    inode_destroy             /* destroy */
};

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
/* file lock object */

struct file_lock
{
    struct object       obj;         /* object header */
    struct fd          *fd;          /* fd owning this lock */
    struct list         fd_entry;    /* entry in list of locks on a given fd */
    struct list         inode_entry; /* entry in inode list of locks */
    int                 shared;      /* shared lock? */
    file_pos_t          start;       /* locked region is interval [start;end) */
    file_pos_t          end;
    struct process     *process;     /* process owning this lock */
    struct list         proc_entry;  /* entry in list of locks owned by the process */
};

static void file_lock_dump( struct object *obj, int verbose );
static int file_lock_signaled( struct object *obj, struct thread *thread );

static const struct object_ops file_lock_ops =
{
    sizeof(struct file_lock),   /* size */
    file_lock_dump,             /* dump */
323
    no_get_type,                /* get_type */
324 325 326 327
    add_queue,                  /* add_queue */
    remove_queue,               /* remove_queue */
    file_lock_signaled,         /* signaled */
    no_satisfied,               /* satisfied */
328
    no_signal,                  /* signal */
329
    no_get_fd,                  /* get_fd */
330
    no_map_access,              /* map_access */
331 332
    default_get_sd,             /* get_sd */
    default_set_sd,             /* set_sd */
333
    no_lookup_name,             /* lookup_name */
334
    no_open_file,               /* open_file */
335
    no_close_handle,            /* close_handle */
336 337 338 339 340 341 342 343 344
    no_destroy                  /* destroy */
};


#define OFF_T_MAX       (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
#define FILE_POS_T_MAX  (~(file_pos_t)0)

static file_pos_t max_unix_offset = OFF_T_MAX;

345 346
#define DUMP_LONG_LONG(val) do { \
    if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
347
        fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
348 349 350 351 352
    else \
        fprintf( stderr, "%lx", (unsigned long)(val) ); \
  } while (0)


353

354 355 356 357 358
/****************************************************************/
/* timeouts support */

struct timeout_user
{
359
    struct list           entry;      /* entry in sorted timeout list */
360
    timeout_t             when;       /* timeout expiry (absolute time) */
361 362 363 364
    timeout_callback      callback;   /* callback function */
    void                 *private;    /* callback private data */
};

365
static struct list timeout_list = LIST_INIT(timeout_list);   /* sorted timeouts list */
366 367 368 369 370 371 372 373 374
timeout_t current_time;

static inline void set_current_time(void)
{
    static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
    struct timeval now;
    gettimeofday( &now, NULL );
    current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
}
375 376

/* add a timeout user */
377
struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
378 379
{
    struct timeout_user *user;
380
    struct list *ptr;
381 382

    if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
383
    user->when     = (when > 0) ? when : current_time - when;
384 385 386 387 388
    user->callback = func;
    user->private  = private;

    /* Now insert it in the linked list */

389
    LIST_FOR_EACH( ptr, &timeout_list )
390
    {
391
        struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
392
        if (timeout->when >= user->when) break;
393
    }
394
    list_add_before( ptr, &user->entry );
395 396 397 398 399 400
    return user;
}

/* remove a timeout user */
void remove_timeout_user( struct timeout_user *user )
{
401
    list_remove( &user->entry );
402 403 404
    free( user );
}

405 406
/* return a text description of a timeout for debugging purposes */
const char *get_timeout_str( timeout_t timeout )
407
{
408 409 410 411 412 413 414 415 416 417 418 419 420
    static char buffer[64];
    long secs, nsecs;

    if (!timeout) return "0";
    if (timeout == TIMEOUT_INFINITE) return "infinite";

    if (timeout < 0)  /* relative */
    {
        secs = -timeout / TICKS_PER_SEC;
        nsecs = -timeout % TICKS_PER_SEC;
        sprintf( buffer, "+%ld.%07ld", secs, nsecs );
    }
    else  /* absolute */
421
    {
422 423 424
        secs = (timeout - current_time) / TICKS_PER_SEC;
        nsecs = (timeout - current_time) % TICKS_PER_SEC;
        if (nsecs < 0)
425
        {
426 427
            nsecs += TICKS_PER_SEC;
            secs--;
428
        }
429 430 431 432 433 434 435
        if (secs >= 0)
            sprintf( buffer, "%x%08x (+%ld.%07ld)",
                     (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
        else
            sprintf( buffer, "%x%08x (-%ld.%07ld)",
                     (unsigned int)(timeout >> 32), (unsigned int)timeout,
                     -(secs + 1), TICKS_PER_SEC - nsecs );
436
    }
437
    return buffer;
438 439 440 441 442 443 444 445 446 447 448 449 450
}


/****************************************************************/
/* poll support */

static struct fd **poll_users;              /* users array */
static struct pollfd *pollfd;               /* poll fd array */
static int nb_users;                        /* count of array entries actually in use */
static int active_users;                    /* current number of active users */
static int allocated_users;                 /* count of allocated entries in the array */
static struct fd **freelist;                /* list of free entries in the array */

451 452
static int get_next_timeout(void);

453 454 455 456 457
static inline void fd_poll_event( struct fd *fd, int event )
{
    fd->fd_ops->poll_event( fd, event );
}

458 459
#ifdef USE_EPOLL

460
static int epoll_fd = -1;
461 462 463 464 465

static inline void init_epoll(void)
{
    epoll_fd = epoll_create( 128 );
}
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

/* set the events that epoll waits for on this fd; helper for set_fd_events */
static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
{
    struct epoll_event ev;
    int ctl;

    if (epoll_fd == -1) return;

    if (events == -1)  /* stop waiting on this fd completely */
    {
        if (pollfd[user].fd == -1) return;  /* already removed */
        ctl = EPOLL_CTL_DEL;
    }
    else if (pollfd[user].fd == -1)
    {
        if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
        ctl = EPOLL_CTL_ADD;
    }
    else
    {
        if (pollfd[user].events == events) return;  /* nothing to do */
        ctl = EPOLL_CTL_MOD;
    }

    ev.events = events;
492
    memset(&ev.data, 0, sizeof(ev.data));
493 494 495 496 497 498 499 500 501 502 503 504 505
    ev.data.u32 = user;

    if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
    {
        if (errno == ENOMEM)  /* not enough memory, give up on epoll */
        {
            close( epoll_fd );
            epoll_fd = -1;
        }
        else perror( "epoll_ctl" );  /* should not happen */
    }
}

506 507 508
static inline void remove_epoll_user( struct fd *fd, int user )
{
    if (epoll_fd == -1) return;
509

510 511 512 513 514 515 516 517
    if (pollfd[user].fd != -1)
    {
        struct epoll_event dummy;
        epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
    }
}

static inline void main_loop_epoll(void)
518
{
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    int i, ret, timeout;
    struct epoll_event events[128];

    assert( POLLIN == EPOLLIN );
    assert( POLLOUT == EPOLLOUT );
    assert( POLLERR == EPOLLERR );
    assert( POLLHUP == EPOLLHUP );

    if (epoll_fd == -1) return;

    while (active_users)
    {
        timeout = get_next_timeout();

        if (!active_users) break;  /* last user removed by a timeout */
        if (epoll_fd == -1) break;  /* an error occurred with epoll */

        ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
537
        set_current_time();
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

        /* put the events into the pollfd array first, like poll does */
        for (i = 0; i < ret; i++)
        {
            int user = events[i].data.u32;
            pollfd[user].revents = events[i].events;
        }

        /* read events from the pollfd array, as set_fd_events may modify them */
        for (i = 0; i < ret; i++)
        {
            int user = events[i].data.u32;
            if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
        }
    }
553 554
}

555 556 557 558 559 560
#elif defined(HAVE_KQUEUE)

static int kqueue_fd = -1;

static inline void init_epoll(void)
{
561 562 563 564 565 566 567 568 569
#ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
    int mib[2];
    char release[32];
    size_t len = sizeof(release);

    mib[0] = CTL_KERN;
    mib[1] = KERN_OSRELEASE;
    if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
    if (atoi(release) < 9) return;
570
#endif
571
    kqueue_fd = kqueue();
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
}

static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
{
    struct kevent ev[2];

    if (kqueue_fd == -1) return;

    EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
    EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );

    if (events == -1)  /* stop waiting on this fd completely */
    {
        if (pollfd[user].fd == -1) return;  /* already removed */
        ev[0].flags |= EV_DELETE;
        ev[1].flags |= EV_DELETE;
    }
    else if (pollfd[user].fd == -1)
    {
        if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
        ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
        ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
    }
    else
    {
        if (pollfd[user].events == events) return;  /* nothing to do */
        ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
        ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
    }

    if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
    {
        if (errno == ENOMEM)  /* not enough memory, give up on kqueue */
        {
            close( kqueue_fd );
            kqueue_fd = -1;
        }
        else perror( "kevent" );  /* should not happen */
    }
}

static inline void remove_epoll_user( struct fd *fd, int user )
{
    if (kqueue_fd == -1) return;

    if (pollfd[user].fd != -1)
    {
        struct kevent ev[2];

        EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
        EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
        kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
    }
}

static inline void main_loop_epoll(void)
{
    int i, ret, timeout;
    struct kevent events[128];

    if (kqueue_fd == -1) return;

    while (active_users)
    {
        timeout = get_next_timeout();

        if (!active_users) break;  /* last user removed by a timeout */
        if (kqueue_fd == -1) break;  /* an error occurred with kqueue */

        if (timeout != -1)
        {
            struct timespec ts;

            ts.tv_sec = timeout / 1000;
            ts.tv_nsec = (timeout % 1000) * 1000000;
            ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
        }
        else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );

651
        set_current_time();
652

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
        /* put the events into the pollfd array first, like poll does */
        for (i = 0; i < ret; i++)
        {
            long user = (long)events[i].udata;
            pollfd[user].revents = 0;
        }
        for (i = 0; i < ret; i++)
        {
            long user = (long)events[i].udata;
            if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
            else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
            if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
            if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
        }

        /* read events from the pollfd array, as set_fd_events may modify them */
        for (i = 0; i < ret; i++)
        {
            long user = (long)events[i].udata;
            if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
            pollfd[user].revents = 0;
        }
    }
}

#else /* HAVE_KQUEUE */
679 680 681 682 683 684

static inline void init_epoll(void) { }
static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
static inline void remove_epoll_user( struct fd *fd, int user ) { }
static inline void main_loop_epoll(void) { }

685 686 687
#endif /* USE_EPOLL */


688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
/* add a user in the poll array and return its index, or -1 on failure */
static int add_poll_user( struct fd *fd )
{
    int ret;
    if (freelist)
    {
        ret = freelist - poll_users;
        freelist = (struct fd **)poll_users[ret];
    }
    else
    {
        if (nb_users == allocated_users)
        {
            struct fd **newusers;
            struct pollfd *newpoll;
            int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
            if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
            if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
            {
                if (allocated_users)
                    poll_users = newusers;
                else
                    free( newusers );
                return -1;
            }
            poll_users = newusers;
            pollfd = newpoll;
715
            if (!allocated_users) init_epoll();
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
            allocated_users = new_count;
        }
        ret = nb_users++;
    }
    pollfd[ret].fd = -1;
    pollfd[ret].events = 0;
    pollfd[ret].revents = 0;
    poll_users[ret] = fd;
    active_users++;
    return ret;
}

/* remove a user from the poll list */
static void remove_poll_user( struct fd *fd, int user )
{
    assert( user >= 0 );
    assert( poll_users[user] == fd );
733

734
    remove_epoll_user( fd, user );
735 736 737 738 739 740 741 742
    pollfd[user].fd = -1;
    pollfd[user].events = 0;
    pollfd[user].revents = 0;
    poll_users[user] = (struct fd *)freelist;
    freelist = &poll_users[user];
    active_users--;
}

743 744
/* process pending timeouts and return the time until the next timeout, in milliseconds */
static int get_next_timeout(void)
745
{
746
    if (!list_empty( &timeout_list ))
747
    {
748
        struct list expired_list, *ptr;
749

750
        /* first remove all expired timers from the list */
751

752 753 754 755
        list_init( &expired_list );
        while ((ptr = list_head( &timeout_list )) != NULL)
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
756

757
            if (timeout->when <= current_time)
758
            {
759
                list_remove( &timeout->entry );
760
                list_add_tail( &expired_list, &timeout->entry );
761
            }
762 763
            else break;
        }
764

765
        /* now call the callback for all the removed timers */
766

767 768 769 770 771 772 773 774 775 776 777
        while ((ptr = list_head( &expired_list )) != NULL)
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
            list_remove( &timeout->entry );
            timeout->callback( timeout->private );
            free( timeout );
        }

        if ((ptr = list_head( &timeout_list )) != NULL)
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
778
            int diff = (timeout->when - current_time + 9999) / 10000;
779 780
            if (diff < 0) diff = 0;
            return diff;
781
        }
782 783 784 785 786 787 788 789 790
    }
    return -1;  /* no pending timeouts */
}

/* server main poll() loop */
void main_loop(void)
{
    int i, ret, timeout;

791 792
    set_current_time();
    server_start_time = current_time;
793

794
    main_loop_epoll();
795 796
    /* fall through to normal poll loop */

797 798 799 800 801
    while (active_users)
    {
        timeout = get_next_timeout();

        if (!active_users) break;  /* last user removed by a timeout */
802

803
        ret = poll( pollfd, nb_users, timeout );
804
        set_current_time();
805

806 807 808 809 810 811 812 813 814 815 816 817 818 819
        if (ret > 0)
        {
            for (i = 0; i < nb_users; i++)
            {
                if (pollfd[i].revents)
                {
                    fd_poll_event( poll_users[i], pollfd[i].revents );
                    if (!--ret) break;
                }
            }
        }
    }
}

820 821

/****************************************************************/
822 823 824 825
/* device functions */

static struct list device_hash[DEVICE_HASH_SIZE];

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
static int is_device_removable( dev_t dev, int unix_fd )
{
#if defined(linux) && defined(HAVE_FSTATFS)
    struct statfs stfs;

    /* check for floppy disk */
    if (major(dev) == FLOPPY_MAJOR) return 1;

    if (fstatfs( unix_fd, &stfs ) == -1) return 0;
    return (stfs.f_type == 0x9660 ||    /* iso9660 */
            stfs.f_type == 0x9fa1 ||    /* supermount */
            stfs.f_type == 0x15013346); /* udf */
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
    struct statfs stfs;

    if (fstatfs( unix_fd, &stfs ) == -1) return 0;
842
    return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
843 844 845 846
#elif defined(__NetBSD__)
    struct statvfs stfs;

    if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
847
    return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
#elif defined(sun)
# include <sys/dkio.h>
# include <sys/vtoc.h>
    struct dk_cinfo dkinf;
    if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
    return (dkinf.dki_ctype == DKC_CDROM ||
            dkinf.dki_ctype == DKC_NCRFLOPPY ||
            dkinf.dki_ctype == DKC_SMSFLOPPY ||
            dkinf.dki_ctype == DKC_INTEL82072 ||
            dkinf.dki_ctype == DKC_INTEL82077);
#else
    return 0;
#endif
}

863
/* retrieve the device object for a given fd, creating it if needed */
864
static struct device *get_device( dev_t dev, int unix_fd )
865 866 867
{
    struct device *device;
    unsigned int i, hash = dev % DEVICE_HASH_SIZE;
868

869 870 871 872 873 874 875 876
    if (device_hash[hash].next)
    {
        LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
            if (device->dev == dev) return (struct device *)grab_object( device );
    }
    else list_init( &device_hash[hash] );

    /* not found, create it */
877

878
    if (unix_fd == -1) return NULL;
879 880 881
    if ((device = alloc_object( &device_ops )))
    {
        device->dev = dev;
882
        device->removable = is_device_removable( dev, unix_fd );
883 884 885 886 887 888 889 890 891 892 893 894 895
        for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
        list_add_head( &device_hash[hash], &device->entry );
    }
    return device;
}

static void device_dump( struct object *obj, int verbose )
{
    struct device *device = (struct device *)obj;
    fprintf( stderr, "Device dev=" );
    DUMP_LONG_LONG( device->dev );
    fprintf( stderr, "\n" );
}
896

897 898 899 900 901 902 903 904 905 906 907 908 909 910
static void device_destroy( struct object *obj )
{
    struct device *device = (struct device *)obj;
    unsigned int i;

    for (i = 0; i < INODE_HASH_SIZE; i++)
        assert( list_empty(&device->inode_hash[i]) );

    list_remove( &device->entry );  /* remove it from the hash table */
}


/****************************************************************/
/* inode functions */
911

912
/* close all pending file descriptors in the closed list */
913
static void inode_close_pending( struct inode *inode, int keep_unlinks )
914
{
915 916 917
    struct list *ptr = list_head( &inode->closed );

    while (ptr)
918
    {
919 920 921
        struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
        struct list *next = list_next( &inode->closed, ptr );

922
        if (fd->unix_fd != -1)
923
        {
924 925
            close( fd->unix_fd );
            fd->unix_fd = -1;
926
        }
927
        if (!keep_unlinks || !fd->unlink[0])  /* get rid of it unless there's an unlink pending on that file */
928 929 930 931 932
        {
            list_remove( ptr );
            free( fd );
        }
        ptr = next;
933 934 935
    }
}

936 937 938
static void inode_dump( struct object *obj, int verbose )
{
    struct inode *inode = (struct inode *)obj;
939
    fprintf( stderr, "Inode device=%p ino=", inode->device );
940 941 942 943 944 945 946
    DUMP_LONG_LONG( inode->ino );
    fprintf( stderr, "\n" );
}

static void inode_destroy( struct object *obj )
{
    struct inode *inode = (struct inode *)obj;
947
    struct list *ptr;
948

949 950
    assert( list_empty(&inode->open) );
    assert( list_empty(&inode->locks) );
951 952

    list_remove( &inode->entry );
953 954 955 956 957

    while ((ptr = list_head( &inode->closed )))
    {
        struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
        list_remove( ptr );
958
        if (fd->unix_fd != -1) close( fd->unix_fd );
959 960 961 962
        if (fd->unlink[0])
        {
            /* make sure it is still the same file */
            struct stat st;
963
            if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
964 965 966 967
            {
                if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
                else unlink( fd->unlink );
            }
968 969 970
        }
        free( fd );
    }
971
    release_object( inode->device );
972 973 974
}

/* retrieve the inode object for a given fd, creating it if needed */
975
static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
976
{
977
    struct device *device;
978
    struct inode *inode;
979
    unsigned int hash = ino % INODE_HASH_SIZE;
980

981
    if (!(device = get_device( dev, unix_fd ))) return NULL;
982 983

    LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
984
    {
985
        if (inode->ino == ino)
986
        {
987 988
            release_object( device );
            return (struct inode *)grab_object( inode );
989 990 991 992 993 994
        }
    }

    /* not found, create it */
    if ((inode = alloc_object( &inode_ops )))
    {
995
        inode->device = device;
996 997
        inode->ino    = ino;
        list_init( &inode->open );
998
        list_init( &inode->locks );
999
        list_init( &inode->closed );
1000
        list_add_head( &device->inode_hash[hash], &inode->entry );
1001
    }
1002 1003
    else release_object( device );

1004 1005 1006
    return inode;
}

1007
/* add fd to the inode list of file descriptors to close */
1008 1009
static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
{
1010 1011
    if (!list_empty( &inode->locks ))
    {
1012
        list_add_head( &inode->closed, &fd->entry );
1013
    }
1014 1015
    else if (fd->unlink[0])  /* close the fd but keep the structure around for unlink */
    {
1016 1017
        if (fd->unix_fd != -1) close( fd->unix_fd );
        fd->unix_fd = -1;
1018 1019 1020
        list_add_head( &inode->closed, &fd->entry );
    }
    else  /* no locks on this inode and no unlink, get rid of the fd */
1021
    {
1022
        if (fd->unix_fd != -1) close( fd->unix_fd );
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        free( fd );
    }
}


/****************************************************************/
/* file lock functions */

static void file_lock_dump( struct object *obj, int verbose )
{
    struct file_lock *lock = (struct file_lock *)obj;
    fprintf( stderr, "Lock %s fd=%p proc=%p start=",
             lock->shared ? "shared" : "excl", lock->fd, lock->process );
    DUMP_LONG_LONG( lock->start );
    fprintf( stderr, " end=" );
    DUMP_LONG_LONG( lock->end );
    fprintf( stderr, "\n" );
}

static int file_lock_signaled( struct object *obj, struct thread *thread )
{
    struct file_lock *lock = (struct file_lock *)obj;
    /* lock is signaled if it has lost its owner */
    return !lock->process;
}

/* set (or remove) a Unix lock if possible for the given range */
1050
static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1051 1052 1053
{
    struct flock fl;

1054
    if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    for (;;)
    {
        if (start == end) return 1;  /* can't set zero-byte lock */
        if (start > max_unix_offset) return 1;  /* ignore it */
        fl.l_type   = type;
        fl.l_whence = SEEK_SET;
        fl.l_start  = start;
        if (!end || end > max_unix_offset) fl.l_len = 0;
        else fl.l_len = end - start;
        if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;

        switch(errno)
        {
1068 1069 1070 1071 1072 1073 1074 1075
        case EACCES:
            /* check whether locks work at all on this file system */
            if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
            {
                set_error( STATUS_FILE_LOCK_CONFLICT );
                return 0;
            }
            /* fall through */
1076 1077 1078
        case EIO:
        case ENOLCK:
            /* no locking on this fs, just ignore it */
1079
            fd->fs_locks = 0;
1080
            return 1;
1081 1082 1083
        case EAGAIN:
            set_error( STATUS_FILE_LOCK_CONFLICT );
            return 0;
1084 1085 1086 1087 1088 1089
        case EBADF:
            /* this can happen if we try to set a write lock on a read-only file */
            /* we just ignore that error */
            if (fl.l_type == F_WRLCK) return 1;
            set_error( STATUS_ACCESS_DENIED );
            return 0;
1090
#ifdef EOVERFLOW
1091
        case EOVERFLOW:
1092
#endif
1093
        case EINVAL:
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
            /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
            /* in that case we shrink the limit and retry */
            if (max_unix_offset > INT_MAX)
            {
                max_unix_offset = INT_MAX;
                break;  /* retry */
            }
            /* fall through */
        default:
            file_set_error();
            return 0;
        }
    }
}

/* check if interval [start;end) overlaps the lock */
1110
static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1111 1112 1113 1114 1115 1116 1117
{
    if (lock->end && start >= lock->end) return 0;
    if (end && lock->start >= end) return 0;
    return 1;
}

/* remove Unix locks for all bytes in the specified area that are no longer locked */
1118
static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
{
    struct hole
    {
        struct hole *next;
        struct hole *prev;
        file_pos_t   start;
        file_pos_t   end;
    } *first, *cur, *next, *buffer;

    struct list *ptr;
    int count = 0;

    if (!fd->inode) return;
1132
    if (!fd->fs_locks) return;
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    if (start == end || start > max_unix_offset) return;
    if (!end || end > max_unix_offset) end = max_unix_offset + 1;

    /* count the number of locks overlapping the specified area */

    LIST_FOR_EACH( ptr, &fd->inode->locks )
    {
        struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
        if (lock->start == lock->end) continue;
        if (lock_overlaps( lock, start, end )) count++;
    }

    if (!count)  /* no locks at all, we can unlock everything */
    {
        set_unix_lock( fd, start, end, F_UNLCK );
        return;
    }

    /* allocate space for the list of holes */
    /* max. number of holes is number of locks + 1 */

    if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
    first = buffer;
    first->next  = NULL;
    first->prev  = NULL;
    first->start = start;
    first->end   = end;
    next = first + 1;

    /* build a sorted list of unlocked holes in the specified area */

    LIST_FOR_EACH( ptr, &fd->inode->locks )
    {
        struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
        if (lock->start == lock->end) continue;
        if (!lock_overlaps( lock, start, end )) continue;

        /* go through all the holes touched by this lock */
        for (cur = first; cur; cur = cur->next)
        {
            if (cur->end <= lock->start) continue; /* hole is before start of lock */
            if (lock->end && cur->start >= lock->end) break;  /* hole is after end of lock */

            /* now we know that lock is overlapping hole */

            if (cur->start >= lock->start)  /* lock starts before hole, shrink from start */
            {
                cur->start = lock->end;
                if (cur->start && cur->start < cur->end) break;  /* done with this lock */
                /* now hole is empty, remove it */
                if (cur->next) cur->next->prev = cur->prev;
                if (cur->prev) cur->prev->next = cur->next;
                else if (!(first = cur->next)) goto done;  /* no more holes at all */
            }
            else if (!lock->end || cur->end <= lock->end)  /* lock larger than hole, shrink from end */
            {
                cur->end = lock->start;
                assert( cur->start < cur->end );
            }
            else  /* lock is in the middle of hole, split hole in two */
            {
                next->prev = cur;
                next->next = cur->next;
                cur->next = next;
                next->start = lock->end;
                next->end = cur->end;
                cur->end = lock->start;
                assert( next->start < next->end );
                assert( cur->end < next->start );
                next++;
                break;  /* done with this lock */
            }
        }
    }

    /* clear Unix locks for all the holes */

    for (cur = first; cur; cur = cur->next)
        set_unix_lock( fd, cur->start, cur->end, F_UNLCK );

 done:
    free( buffer );
}

/* create a new lock on a fd */
static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
{
    struct file_lock *lock;

    if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
    lock->shared  = shared;
    lock->start   = start;
    lock->end     = end;
    lock->fd      = fd;
    lock->process = current->process;

    /* now try to set a Unix lock */
    if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
    {
        release_object( lock );
        return NULL;
    }
    list_add_head( &fd->locks, &lock->fd_entry );
    list_add_head( &fd->inode->locks, &lock->inode_entry );
    list_add_head( &lock->process->locks, &lock->proc_entry );
    return lock;
}

/* remove an existing lock */
static void remove_lock( struct file_lock *lock, int remove_unix )
{
    struct inode *inode = lock->fd->inode;

    list_remove( &lock->fd_entry );
    list_remove( &lock->inode_entry );
    list_remove( &lock->proc_entry );
    if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1250
    if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
    lock->process = NULL;
    wake_up( &lock->obj, 0 );
    release_object( lock );
}

/* remove all locks owned by a given process */
void remove_process_locks( struct process *process )
{
    struct list *ptr;

    while ((ptr = list_head( &process->locks )))
    {
        struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
        remove_lock( lock, 1 );  /* this removes it from the list */
    }
}

/* remove all locks on a given fd */
static void remove_fd_locks( struct fd *fd )
{
    file_pos_t start = FILE_POS_T_MAX, end = 0;
    struct list *ptr;

    while ((ptr = list_head( &fd->locks )))
    {
        struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
        if (lock->start < start) start = lock->start;
        if (!lock->end || lock->end > end) end = lock->end - 1;
        remove_lock( lock, 0 );
    }
    if (start < end) remove_unix_locks( fd, start, end + 1 );
}

/* add a lock on an fd */
/* returns handle to wait on */
obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
{
    struct list *ptr;
    file_pos_t end = start + count;

1291 1292 1293 1294 1295 1296
    if (!fd->inode)  /* not a regular file */
    {
        set_error( STATUS_INVALID_DEVICE_REQUEST );
        return 0;
    }

1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    /* don't allow wrapping locks */
    if (end && end < start)
    {
        set_error( STATUS_INVALID_PARAMETER );
        return 0;
    }

    /* check if another lock on that file overlaps the area */
    LIST_FOR_EACH( ptr, &fd->inode->locks )
    {
        struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
        if (!lock_overlaps( lock, start, end )) continue;
        if (lock->shared && shared) continue;
        /* found one */
        if (!wait)
        {
            set_error( STATUS_FILE_LOCK_CONFLICT );
            return 0;
        }
        set_error( STATUS_PENDING );
        return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
    }

    /* not found, add it */
    if (add_lock( fd, shared, start, end )) return 0;
    if (get_error() == STATUS_FILE_LOCK_CONFLICT)
    {
        /* Unix lock conflict -> tell client to wait and retry */
        if (wait) set_error( STATUS_PENDING );
    }
    return 0;
}

/* remove a lock on an fd */
void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
{
    struct list *ptr;
    file_pos_t end = start + count;

    /* find an existing lock with the exact same parameters */
    LIST_FOR_EACH( ptr, &fd->locks )
    {
        struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
        if ((lock->start == start) && (lock->end == end))
        {
            remove_lock( lock, 1 );
            return;
        }
    }
    set_error( STATUS_FILE_LOCK_CONFLICT );
1347 1348 1349
}


1350 1351 1352
/****************************************************************/
/* file descriptor functions */

1353 1354 1355
static void fd_dump( struct object *obj, int verbose )
{
    struct fd *fd = (struct fd *)obj;
1356
    fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1357 1358
    if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
    fprintf( stderr, "\n" );
1359 1360 1361 1362 1363
}

static void fd_destroy( struct object *obj )
{
    struct fd *fd = (struct fd *)obj;
1364

1365 1366 1367
    free_async_queue( fd->read_q );
    free_async_queue( fd->write_q );
    free_async_queue( fd->wait_q );
1368

1369
    if (fd->completion) release_object( fd->completion );
1370
    remove_fd_locks( fd );
1371
    list_remove( &fd->inode_entry );
1372
    if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1373 1374 1375 1376 1377 1378 1379 1380 1381
    if (fd->inode)
    {
        inode_add_closed_fd( fd->inode, fd->closed );
        release_object( fd->inode );
    }
    else  /* no inode, close it right away */
    {
        if (fd->unix_fd != -1) close( fd->unix_fd );
    }
1382 1383
}

1384 1385 1386 1387 1388
/* set the events that select waits for on this fd */
void set_fd_events( struct fd *fd, int events )
{
    int user = fd->poll_index;
    assert( poll_users[user] == fd );
1389 1390 1391

    set_fd_epoll_events( fd, user, events );

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    if (events == -1)  /* stop waiting on this fd completely */
    {
        pollfd[user].fd = -1;
        pollfd[user].events = POLLERR;
        pollfd[user].revents = 0;
    }
    else if (pollfd[user].fd != -1 || !pollfd[user].events)
    {
        pollfd[user].fd = fd->unix_fd;
        pollfd[user].events = events;
    }
}

1405 1406 1407 1408 1409
/* prepare an fd for unmounting its corresponding device */
static inline void unmount_fd( struct fd *fd )
{
    assert( fd->inode );

1410 1411
    async_wake_up( fd->read_q, STATUS_VOLUME_DISMOUNTED );
    async_wake_up( fd->write_q, STATUS_VOLUME_DISMOUNTED );
1412 1413 1414 1415 1416 1417

    if (fd->poll_index != -1) set_fd_events( fd, -1 );

    if (fd->unix_fd != -1) close( fd->unix_fd );

    fd->unix_fd = -1;
1418
    fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1419 1420 1421 1422 1423 1424 1425
    fd->closed->unix_fd = -1;
    fd->closed->unlink[0] = 0;

    /* stop using Unix locks on this fd (existing locks have been removed by close) */
    fd->fs_locks = 0;
}

1426
/* allocate an fd object, without setting the unix fd yet */
1427
static struct fd *alloc_fd_object(void)
1428
{
1429
    struct fd *fd = alloc_object( &fd_ops );
1430

1431 1432
    if (!fd) return NULL;

1433 1434
    fd->fd_ops     = NULL;
    fd->user       = NULL;
1435 1436
    fd->inode      = NULL;
    fd->closed     = NULL;
1437
    fd->access     = 0;
1438
    fd->options    = 0;
1439
    fd->sharing    = 0;
1440
    fd->unix_fd    = -1;
1441
    fd->signaled   = 1;
1442
    fd->fs_locks   = 1;
1443
    fd->poll_index = -1;
1444 1445 1446
    fd->read_q     = NULL;
    fd->write_q    = NULL;
    fd->wait_q     = NULL;
1447
    fd->completion = NULL;
1448
    list_init( &fd->inode_entry );
1449
    list_init( &fd->locks );
1450 1451 1452 1453 1454 1455 1456 1457 1458

    if ((fd->poll_index = add_poll_user( fd )) == -1)
    {
        release_object( fd );
        return NULL;
    }
    return fd;
}

1459
/* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1460
struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
{
    struct fd *fd = alloc_object( &fd_ops );

    if (!fd) return NULL;

    fd->fd_ops     = fd_user_ops;
    fd->user       = user;
    fd->inode      = NULL;
    fd->closed     = NULL;
    fd->access     = 0;
1471
    fd->options    = options;
1472 1473
    fd->sharing    = 0;
    fd->unix_fd    = -1;
1474
    fd->signaled   = 0;
1475 1476
    fd->fs_locks   = 0;
    fd->poll_index = -1;
1477 1478 1479
    fd->read_q     = NULL;
    fd->write_q    = NULL;
    fd->wait_q     = NULL;
1480
    fd->completion = NULL;
1481
    fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1482 1483 1484 1485 1486
    list_init( &fd->inode_entry );
    list_init( &fd->locks );
    return fd;
}

1487 1488 1489 1490 1491 1492
/* set the status to return when the fd has no associated unix fd */
void set_no_fd_status( struct fd *fd, unsigned int status )
{
    fd->no_fd_status = status;
}

1493 1494 1495 1496
/* check if the desired access is possible without violating */
/* the sharing mode of other opens of the same file */
static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
{
1497
    unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1498 1499 1500 1501
    unsigned int existing_access = 0;
    struct list *ptr;

    /* if access mode is 0, sharing mode is ignored */
1502
    if (!access) sharing = existing_sharing;
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    fd->access = access;
    fd->sharing = sharing;

    LIST_FOR_EACH( ptr, &fd->inode->open )
    {
        struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
        if (fd_ptr != fd)
        {
            existing_sharing &= fd_ptr->sharing;
            existing_access  |= fd_ptr->access;
        }
    }

1516 1517
    if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
    if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1518
    if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1519 1520
    if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
    if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1521
    if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1522 1523 1524
    return 1;
}

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
/* sets the user of an fd that previously had no user */
void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
{
    assert( fd->fd_ops == NULL );
    fd->fd_ops = user_ops;
    fd->user   = user;
}

/* open() wrapper that returns a struct fd with no fd user set */
struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
                    unsigned int sharing, unsigned int options )
1536 1537 1538
{
    struct stat st;
    struct closed_fd *closed_fd;
1539
    struct fd *fd;
1540
    const char *unlink_name = "";
1541
    int rw_mode;
1542

1543 1544 1545 1546 1547 1548
    if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
    {
        set_error( STATUS_INVALID_PARAMETER );
        return NULL;
    }

1549
    if (!(fd = alloc_fd_object())) return NULL;
1550

1551
    fd->options = options;
1552
    if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1553
    if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1554 1555 1556 1557
    {
        release_object( fd );
        return NULL;
    }
1558

1559 1560 1561 1562 1563 1564 1565 1566
    /* create the directory if needed */
    if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
    {
        if (mkdir( name, 0777 ) == -1)
        {
            if (errno != EEXIST || (flags & O_EXCL))
            {
                file_set_error();
1567
                goto error;
1568 1569 1570 1571
            }
        }
        flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
    }
1572 1573 1574 1575 1576 1577 1578 1579 1580

    if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
    {
        if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
        else rw_mode = O_WRONLY;
    }
    else rw_mode = O_RDONLY;

    if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1581
    {
1582 1583 1584
        /* if we tried to open a directory for write access, retry read-only */
        if (errno != EISDIR ||
            !(access & FILE_UNIX_WRITE_ACCESS) ||
1585
            (fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode )) == -1)
1586 1587 1588 1589
        {
            file_set_error();
            goto error;
        }
1590
    }
1591

1592
    closed_fd->unix_fd = fd->unix_fd;
1593
    closed_fd->unlink[0] = 0;
1594 1595 1596
    fstat( fd->unix_fd, &st );
    *mode = st.st_mode;

1597 1598
    /* only bother with an inode for normal files and directories */
    if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1599
    {
1600
        struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1601 1602 1603 1604 1605 1606

        if (!inode)
        {
            /* we can close the fd because there are no others open on the same file,
             * otherwise we wouldn't have failed to allocate a new inode
             */
1607
            goto error;
1608 1609 1610 1611
        }
        fd->inode = inode;
        fd->closed = closed_fd;
        list_add_head( &inode->open, &fd->inode_entry );
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625

        /* check directory options */
        if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
        {
            release_object( fd );
            set_error( STATUS_NOT_A_DIRECTORY );
            return NULL;
        }
        if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
        {
            release_object( fd );
            set_error( STATUS_FILE_IS_A_DIRECTORY );
            return NULL;
        }
1626 1627 1628 1629 1630 1631
        if (!check_sharing( fd, access, sharing ))
        {
            release_object( fd );
            set_error( STATUS_SHARING_VIOLATION );
            return NULL;
        }
1632
        strcpy( closed_fd->unlink, unlink_name );
1633
        if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1634
    }
1635
    else  /* special file */
1636
    {
1637 1638 1639 1640 1641
        if (options & FILE_DIRECTORY_FILE)
        {
            set_error( STATUS_NOT_A_DIRECTORY );
            goto error;
        }
1642 1643 1644
        if (unlink_name[0])  /* we can't unlink special files */
        {
            set_error( STATUS_INVALID_PARAMETER );
1645
            goto error;
1646
        }
1647
        free( closed_fd );
1648
    }
1649
    return fd;
1650 1651 1652 1653 1654

error:
    release_object( fd );
    free( closed_fd );
    return NULL;
1655 1656
}

1657 1658
/* create an fd for an anonymous file */
/* if the function fails the unix fd is closed */
1659 1660
struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
                                unsigned int options )
1661
{
1662
    struct fd *fd = alloc_fd_object();
1663 1664 1665

    if (fd)
    {
1666
        set_fd_user( fd, fd_user_ops, user );
1667
        fd->unix_fd = unix_fd;
1668
        fd->options = options;
1669 1670 1671 1672 1673 1674
        return fd;
    }
    close( unix_fd );
    return NULL;
}

1675 1676
/* retrieve the object that is using an fd */
void *get_fd_user( struct fd *fd )
1677
{
1678 1679
    return fd->user;
}
1680

1681 1682 1683 1684 1685 1686
/* retrieve the opening options for the fd */
unsigned int get_fd_options( struct fd *fd )
{
    return fd->options;
}

1687 1688 1689
/* retrieve the unix fd for an object */
int get_unix_fd( struct fd *fd )
{
1690
    if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1691
    return fd->unix_fd;
1692 1693
}

1694 1695 1696 1697 1698 1699
/* check if two file descriptors point to the same file */
int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
{
    return fd1->inode == fd2->inode;
}

1700 1701 1702 1703 1704 1705
/* check if fd is on a removable device */
int is_fd_removable( struct fd *fd )
{
    return (fd->inode && fd->inode->device->removable);
}

1706 1707 1708 1709 1710 1711 1712
/* set or clear the fd signaled state */
void set_fd_signaled( struct fd *fd, int signaled )
{
    fd->signaled = signaled;
    if (signaled) wake_up( fd->user, 0 );
}

1713 1714 1715 1716 1717 1718
/* set or clear the fd signaled state */
int is_fd_signaled( struct fd *fd )
{
    return fd->signaled;
}

1719 1720 1721 1722 1723 1724
/* handler for close_handle that refuses to close fd-associated handles in other processes */
int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
{
    return (!current || current->process == process);
}

1725 1726 1727 1728 1729
/* check if events are pending and if yes return which one(s) */
int check_fd_events( struct fd *fd, int events )
{
    struct pollfd pfd;

1730
    if (fd->unix_fd == -1) return POLLERR;
1731
    if (fd->inode) return events;  /* regular files are always signaled */
1732

1733 1734 1735 1736
    pfd.fd     = fd->unix_fd;
    pfd.events = events;
    if (poll( &pfd, 1, 0 ) <= 0) return 0;
    return pfd.revents;
1737 1738 1739 1740 1741
}

/* default signaled() routine for objects that poll() on an fd */
int default_fd_signaled( struct object *obj, struct thread *thread )
{
1742
    struct fd *fd = get_obj_fd( obj );
1743
    int ret = fd->signaled;
1744 1745
    release_object( fd );
    return ret;
1746 1747
}

1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
/* default map_access() routine for objects that behave like an fd */
unsigned int default_fd_map_access( struct object *obj, unsigned int access )
{
    if (access & GENERIC_READ)    access |= FILE_GENERIC_READ;
    if (access & GENERIC_WRITE)   access |= FILE_GENERIC_WRITE;
    if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
    if (access & GENERIC_ALL)     access |= FILE_ALL_ACCESS;
    return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
}

1758 1759 1760 1761
int default_fd_get_poll_events( struct fd *fd )
{
    int events = 0;

1762 1763
    if (async_waiting( fd->read_q )) events |= POLLIN;
    if (async_waiting( fd->write_q )) events |= POLLOUT;
1764 1765 1766
    return events;
}

1767 1768 1769
/* default handler for poll() events */
void default_poll_event( struct fd *fd, int event )
{
1770 1771
    if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( fd->read_q, STATUS_ALERTED );
    if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( fd->write_q, STATUS_ALERTED );
1772 1773

    /* if an error occurred, stop polling this fd to avoid busy-looping */
1774
    if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1775
    else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1776 1777
}

1778
struct async *fd_queue_async( struct fd *fd, const async_data_t *data, int type )
1779
{
1780
    struct async_queue *queue;
1781
    struct async *async;
1782 1783 1784 1785

    switch (type)
    {
    case ASYNC_TYPE_READ:
1786
        if (!fd->read_q && !(fd->read_q = create_async_queue( fd ))) return NULL;
1787
        queue = fd->read_q;
1788 1789
        break;
    case ASYNC_TYPE_WRITE:
1790
        if (!fd->write_q && !(fd->write_q = create_async_queue( fd ))) return NULL;
1791
        queue = fd->write_q;
1792
        break;
1793
    case ASYNC_TYPE_WAIT:
1794
        if (!fd->wait_q && !(fd->wait_q = create_async_queue( fd ))) return NULL;
1795
        queue = fd->wait_q;
1796
        break;
1797
    default:
1798
        queue = NULL;
1799
        assert(0);
1800 1801
    }

1802
    if ((async = create_async( current, queue, data )) && type != ASYNC_TYPE_WAIT)
1803 1804 1805 1806
    {
        if (!fd->inode)
            set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
        else  /* regular files are always ready for read and write */
1807
            async_wake_up( queue, STATUS_ALERTED );
1808 1809
    }
    return async;
1810 1811
}

1812
void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
1813 1814 1815 1816
{
    switch (type)
    {
    case ASYNC_TYPE_READ:
1817
        async_wake_up( fd->read_q, status );
1818 1819
        break;
    case ASYNC_TYPE_WRITE:
1820
        async_wake_up( fd->write_q, status );
1821 1822
        break;
    case ASYNC_TYPE_WAIT:
1823
        async_wake_up( fd->wait_q, status );
1824 1825 1826 1827 1828 1829
        break;
    default:
        assert(0);
    }
}

1830 1831 1832 1833 1834
void fd_reselect_async( struct fd *fd, struct async_queue *queue )
{
    fd->fd_ops->reselect_async( fd, queue );
}

1835
void default_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
1836
{
1837
    struct async *async;
1838

1839
    if ((async = fd_queue_async( fd, data, type )))
1840 1841 1842 1843
    {
        release_object( async );
        set_error( STATUS_PENDING );
    }
1844 1845
}

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
/* default reselect_async() fd routine */
void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
{
    if (queue != fd->wait_q)
    {
        int poll_events = fd->fd_ops->get_poll_events( fd );
        int events = check_fd_events( fd, poll_events );
        if (events) fd->fd_ops->poll_event( fd, events );
        else set_fd_events( fd, poll_events );
    }
}

/* default cancel_async() fd routine */
1859
void default_fd_cancel_async( struct fd *fd, struct process *process, struct thread *thread, client_ptr_t iosb )
1860
{
1861 1862 1863 1864 1865 1866 1867
    int n = 0;

    n += async_wake_up_by( fd->read_q, process, thread, iosb, STATUS_CANCELLED );
    n += async_wake_up_by( fd->write_q, process, thread, iosb, STATUS_CANCELLED );
    n += async_wake_up_by( fd->wait_q, process, thread, iosb, STATUS_CANCELLED );
    if (!n && iosb)
        set_error( STATUS_NOT_FOUND );
1868 1869
}

1870
/* default flush() routine */
1871
void no_flush( struct fd *fd, struct event **event )
1872 1873 1874 1875
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
}

1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
static inline int is_valid_mounted_device( struct stat *st )
{
#if defined(linux) || defined(__sun__)
    return S_ISBLK( st->st_mode );
#else
    /* disks are char devices on *BSD */
    return S_ISCHR( st->st_mode );
#endif
}

1886
/* close all Unix file descriptors on a device to allow unmounting it */
1887
static void unmount_device( struct fd *device_fd )
1888 1889
{
    unsigned int i;
1890 1891
    struct stat st;
    struct device *device;
1892 1893
    struct inode *inode;
    struct fd *fd;
1894
    int unix_fd = get_unix_fd( device_fd );
1895

1896 1897
    if (unix_fd == -1) return;

1898
    if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
1899 1900 1901 1902 1903
    {
        set_error( STATUS_INVALID_PARAMETER );
        return;
    }

1904
    if (!(device = get_device( st.st_rdev, -1 ))) return;
1905

1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
    for (i = 0; i < INODE_HASH_SIZE; i++)
    {
        LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
        {
            LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
            {
                unmount_fd( fd );
            }
            inode_close_pending( inode, 0 );
        }
    }
    /* remove it from the hash table */
    list_remove( &device->entry );
    list_init( &device->entry );
1920
    release_object( device );
1921 1922
}

1923
/* default ioctl() routine */
1924
obj_handle_t default_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async,
1925
                               int blocking, const void *data, data_size_t size )
1926 1927 1928 1929 1930
{
    switch(code)
    {
    case FSCTL_DISMOUNT_VOLUME:
        unmount_device( fd );
1931
        return 0;
1932 1933
    default:
        set_error( STATUS_NOT_SUPPORTED );
1934
        return 0;
1935 1936 1937
    }
}

1938 1939 1940 1941 1942 1943 1944
/* same as get_handle_obj but retrieve the struct fd associated to the object */
static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
                                     unsigned int access )
{
    struct fd *fd = NULL;
    struct object *obj;

1945
    if ((obj = get_handle_obj( process, handle, access, NULL )))
1946
    {
1947
        fd = get_obj_fd( obj );
1948 1949 1950 1951 1952
        release_object( obj );
    }
    return fd;
}

1953
struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
1954
{
1955
    *p_key = fd->comp_key;
1956 1957 1958 1959 1960 1961 1962
    return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
}

void fd_copy_completion( struct fd *src, struct fd *dst )
{
    assert( !dst->completion );
    dst->completion = fd_get_completion( src, &dst->comp_key );
1963 1964
}

1965 1966 1967 1968
/* flush a file buffers */
DECL_HANDLER(flush_file)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1969
    struct event * event = NULL;
1970 1971 1972

    if (fd)
    {
1973
        fd->fd_ops->flush( fd, &event );
1974
        if ( event )
1975 1976 1977
        {
            reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
        }
1978 1979 1980 1981
        release_object( fd );
    }
}

1982 1983 1984 1985 1986
/* open a file object */
DECL_HANDLER(open_file_object)
{
    struct unicode_str name;
    struct directory *root = NULL;
1987
    struct object *obj, *result;
1988 1989 1990 1991 1992 1993 1994

    get_req_unicode_str( &name );
    if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
        return;

    if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
    {
1995
        if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
1996
        {
1997 1998
            reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
            release_object( result );
1999 2000 2001 2002 2003 2004 2005
        }
        release_object( obj );
    }

    if (root) release_object( root );
}

2006 2007 2008 2009 2010
/* get a Unix fd to access a file */
DECL_HANDLER(get_handle_fd)
{
    struct fd *fd;

2011
    if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2012
    {
2013 2014
        int unix_fd = get_unix_fd( fd );
        if (unix_fd != -1)
2015
        {
2016 2017 2018 2019
            reply->type = fd->fd_ops->get_fd_type( fd );
            reply->removable = is_fd_removable(fd);
            reply->options = fd->options;
            reply->access = get_handle_access( current->process, req->handle );
2020
            send_client_fd( current->process, unix_fd, req->handle );
2021
        }
2022 2023 2024 2025
        release_object( fd );
    }
}

2026 2027 2028 2029
/* perform an ioctl on a file */
DECL_HANDLER(ioctl)
{
    unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2030
    struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2031 2032 2033

    if (fd)
    {
2034
        reply->wait = fd->fd_ops->ioctl( fd, req->code, &req->async, req->blocking,
2035 2036
                                         get_req_data(), get_req_data_size() );
        reply->options = fd->options;
2037 2038 2039 2040
        release_object( fd );
    }
}

2041 2042 2043
/* create / reschedule an async I/O */
DECL_HANDLER(register_async)
{
2044 2045
    unsigned int access;
    struct fd *fd;
2046

2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
    switch(req->type)
    {
    case ASYNC_TYPE_READ:
        access = FILE_READ_DATA;
        break;
    case ASYNC_TYPE_WRITE:
        access = FILE_WRITE_DATA;
        break;
    default:
        set_error( STATUS_INVALID_PARAMETER );
        return;
    }
2059

2060
    if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2061
    {
2062
        if (get_unix_fd( fd ) != -1) fd->fd_ops->queue_async( fd, &req->async, req->type, req->count );
2063 2064 2065
        release_object( fd );
    }
}
2066 2067 2068 2069 2070

/* cancels all async I/O */
DECL_HANDLER(cancel_async)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2071
    struct thread *thread = req->only_thread ? current : NULL;
2072

2073 2074
    if (fd)
    {
2075
        if (get_unix_fd( fd ) != -1) fd->fd_ops->cancel_async( fd, current->process, thread, req->iosb );
2076
        release_object( fd );
2077
    }
2078
}
2079 2080 2081 2082 2083 2084 2085 2086

/* attach completion object to a fd */
DECL_HANDLER(set_completion_info)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );

    if (fd)
    {
2087
        if (!(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) && !fd->completion)
2088 2089 2090 2091 2092 2093 2094 2095
        {
            fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
            fd->comp_key = req->ckey;
        }
        else set_error( STATUS_INVALID_PARAMETER );
        release_object( fd );
    }
}
2096 2097 2098 2099 2100 2101 2102

/* push new completion msg into a completion queue attached to the fd */
DECL_HANDLER(add_fd_completion)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
    if (fd)
    {
2103 2104
        if (fd->completion)
            add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2105 2106 2107
        release_object( fd );
    }
}