fd.c 84.4 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 <dirent.h>
27
#include <errno.h>
28
#include <fcntl.h>
29
#include <limits.h>
30
#include <signal.h>
31
#include <stdarg.h>
32 33 34
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
35 36 37
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
38 39 40
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
41 42 43 44 45 46 47
#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
48
/* Work around a conflict with Solaris' system list defined in sys/list.h. */
49 50 51 52 53 54 55
#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
56
#include <sys/vfs.h>
57 58 59 60 61 62 63
#undef list
#undef list_next
#undef list_prev
#undef list_head
#undef list_tail
#undef list_move_tail
#undef list_remove
64
#endif
65 66 67
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
68 69 70 71 72 73
#ifdef HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#ifdef HAVE_SYS_STATFS_H
#include <sys/statfs.h>
#endif
74 75 76
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
77 78 79 80 81
#ifdef HAVE_SYS_EVENT_H
#include <sys/event.h>
#undef LIST_INIT
#undef LIST_ENTRY
#endif
82 83 84
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
85
#include <sys/stat.h>
86
#include <sys/time.h>
87 88 89 90 91
#ifdef MAJOR_IN_MKDEV
#include <sys/mkdev.h>
#elif defined(MAJOR_IN_SYSMACROS)
#include <sys/sysmacros.h>
#endif
92
#include <sys/types.h>
93
#include <unistd.h>
94 95 96
#ifdef HAVE_SYS_SYSCALL_H
#include <sys/syscall.h>
#endif
97

98 99
#include "ntstatus.h"
#define WIN32_NO_STATUS
100 101 102 103 104 105
#include "object.h"
#include "file.h"
#include "handle.h"
#include "process.h"
#include "request.h"

106
#include "winternl.h"
107
#include "winioctl.h"
108
#include "ddk/wdm.h"
109

110
#if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
111
# include <sys/epoll.h>
112
# define USE_EPOLL
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;
};

static inline int epoll_create( int size )
{
139
    return syscall( 254 /*NR_epoll_create*/, size );
140 141 142 143
}

static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
{
144
    return syscall( 255 /*NR_epoll_ctl*/, epfd, op, fd, event );
145 146 147 148
}

static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
{
149
    return syscall( 256 /*NR_epoll_wait*/, epfd, events, maxevents, timeout );
150 151 152 153
}

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

154 155 156 157
#if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
# include <port.h>
# define USE_EVENT_PORTS
#endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
158

159 160 161 162 163
/* 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).
 */

164 165 166 167 168
/* file descriptor object */

/* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
struct closed_fd
{
169
    struct list entry;       /* entry in inode closed list */
170
    int         unix_fd;     /* the unix file descriptor */
171
    int         unlink;      /* whether to unlink on close: -1 - implicit FILE_DELETE_ON_CLOSE, 1 - explicit disposition */
172
    char       *unix_name;   /* name to unlink on close, points to parent fd unix_name */
173 174
};

175 176
struct fd
{
177 178 179 180 181 182
    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 */
183
    struct list          locks;       /* list of locks on this fd */
184
    unsigned int         access;      /* file access (FILE_READ_DATA etc.) */
185
    unsigned int         options;     /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
186
    unsigned int         sharing;     /* file sharing mode */
187
    char                *unix_name;   /* unix file name */
188
    int                  unix_fd;     /* unix file descriptor */
189
    unsigned int         no_fd_status;/* status to return when unix_fd is -1 */
190
    unsigned int         cacheable :1;/* can the fd be cached on the client side? */
191 192
    unsigned int         signaled :1; /* is the fd signaled? */
    unsigned int         fs_locks :1; /* can we use filesystem locks for this fd? */
193
    int                  poll_index;  /* index of fd in poll array */
194 195 196
    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 */
197
    struct completion   *completion;  /* completion object attached to this fd */
198
    apc_param_t          comp_key;    /* completion key to set in completion events */
199
    unsigned int         comp_flags;  /* completion flags */
200 201 202 203 204 205 206 207 208
};

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 */
209
    no_get_type,              /* get_type */
210 211 212 213
    no_add_queue,             /* add_queue */
    NULL,                     /* remove_queue */
    NULL,                     /* signaled */
    NULL,                     /* satisfied */
214
    no_signal,                /* signal */
215
    no_get_fd,                /* get_fd */
216
    no_map_access,            /* map_access */
217 218
    default_get_sd,           /* get_sd */
    default_set_sd,           /* set_sd */
219
    no_get_full_name,         /* get_full_name */
220
    no_lookup_name,           /* lookup_name */
221 222
    no_link_name,             /* link_name */
    NULL,                     /* unlink_name */
223
    no_open_file,             /* open_file */
224
    no_kernel_obj_list,       /* get_kernel_obj_list */
225
    no_close_handle,          /* close_handle */
226 227 228
    fd_destroy                /* destroy */
};

229 230 231 232 233 234 235 236 237 238
/* 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 */
239
    int                 removable;  /* removable device? (or -1 if unknown) */
240 241 242 243 244 245 246 247 248 249
    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 */
250
    no_get_type,              /* get_type */
251 252 253 254 255 256
    no_add_queue,             /* add_queue */
    NULL,                     /* remove_queue */
    NULL,                     /* signaled */
    NULL,                     /* satisfied */
    no_signal,                /* signal */
    no_get_fd,                /* get_fd */
257
    no_map_access,            /* map_access */
258 259
    default_get_sd,           /* get_sd */
    default_set_sd,           /* set_sd */
260
    no_get_full_name,         /* get_full_name */
261
    no_lookup_name,           /* lookup_name */
262 263
    no_link_name,             /* link_name */
    NULL,                     /* unlink_name */
264
    no_open_file,             /* open_file */
265
    no_kernel_obj_list,       /* get_kernel_obj_list */
266 267 268 269
    no_close_handle,          /* close_handle */
    device_destroy            /* destroy */
};

270 271 272 273 274 275
/* inode object */

struct inode
{
    struct object       obj;        /* object header */
    struct list         entry;      /* inode hash list entry */
276
    struct device      *device;     /* device containing this inode */
277 278
    ino_t               ino;        /* inode number */
    struct list         open;       /* list of open file descriptors */
279
    struct list         locks;      /* list of file locks */
280
    struct list         closed;     /* list of file descriptors to close at destroy time */
281 282 283 284 285 286 287 288 289
};

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 */
290
    no_get_type,              /* get_type */
291 292 293 294
    no_add_queue,             /* add_queue */
    NULL,                     /* remove_queue */
    NULL,                     /* signaled */
    NULL,                     /* satisfied */
295
    no_signal,                /* signal */
296
    no_get_fd,                /* get_fd */
297
    no_map_access,            /* map_access */
298 299
    default_get_sd,           /* get_sd */
    default_set_sd,           /* set_sd */
300
    no_get_full_name,         /* get_full_name */
301
    no_lookup_name,           /* lookup_name */
302 303
    no_link_name,             /* link_name */
    NULL,                     /* unlink_name */
304
    no_open_file,             /* open_file */
305
    no_kernel_obj_list,       /* get_kernel_obj_list */
306
    no_close_handle,          /* close_handle */
307 308 309
    inode_destroy             /* destroy */
};

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
/* 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 );
326
static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
327 328 329 330 331

static const struct object_ops file_lock_ops =
{
    sizeof(struct file_lock),   /* size */
    file_lock_dump,             /* dump */
332
    no_get_type,                /* get_type */
333 334 335 336
    add_queue,                  /* add_queue */
    remove_queue,               /* remove_queue */
    file_lock_signaled,         /* signaled */
    no_satisfied,               /* satisfied */
337
    no_signal,                  /* signal */
338
    no_get_fd,                  /* get_fd */
339
    no_map_access,              /* map_access */
340 341
    default_get_sd,             /* get_sd */
    default_set_sd,             /* set_sd */
342
    no_get_full_name,           /* get_full_name */
343
    no_lookup_name,             /* lookup_name */
344 345
    no_link_name,               /* link_name */
    NULL,                       /* unlink_name */
346
    no_open_file,               /* open_file */
347
    no_kernel_obj_list,         /* get_kernel_obj_list */
348
    no_close_handle,            /* close_handle */
349 350 351 352 353 354 355 356 357
    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;

358 359
#define DUMP_LONG_LONG(val) do { \
    if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
360
        fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
361 362 363 364 365
    else \
        fprintf( stderr, "%lx", (unsigned long)(val) ); \
  } while (0)


366

367 368 369 370 371
/****************************************************************/
/* timeouts support */

struct timeout_user
{
372
    struct list           entry;      /* entry in sorted timeout list */
373
    abstime_t             when;       /* timeout expiry */
374 375 376 377
    timeout_callback      callback;   /* callback function */
    void                 *private;    /* callback private data */
};

378 379
static struct list abs_timeout_list = LIST_INIT(abs_timeout_list); /* sorted absolute timeouts list */
static struct list rel_timeout_list = LIST_INIT(rel_timeout_list); /* sorted relative timeouts list */
380
timeout_t current_time;
381
timeout_t monotonic_time;
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
struct _KUSER_SHARED_DATA *user_shared_data = NULL;
static const int user_shared_data_timeout = 16;

static void set_user_shared_data_time(void)
{
    timeout_t tick_count = monotonic_time / 10000;

    /* on X86 there should be total store order guarantees, so volatile is enough
     * to ensure the stores aren't reordered by the compiler, and then they will
     * always be seen in-order from other CPUs. On other archs, we need atomic
     * intrinsics to guarantee that. */
#if defined(__i386__) || defined(__x86_64__)
    user_shared_data->SystemTime.High2Time = current_time >> 32;
    user_shared_data->SystemTime.LowPart   = current_time;
    user_shared_data->SystemTime.High1Time = current_time >> 32;

    user_shared_data->InterruptTime.High2Time = monotonic_time >> 32;
    user_shared_data->InterruptTime.LowPart   = monotonic_time;
    user_shared_data->InterruptTime.High1Time = monotonic_time >> 32;

    user_shared_data->TickCount.High2Time = tick_count >> 32;
    user_shared_data->TickCount.LowPart   = tick_count;
    user_shared_data->TickCount.High1Time = tick_count >> 32;
    *(volatile ULONG *)&user_shared_data->TickCountLowDeprecated = tick_count;
#else
    __atomic_store_n(&user_shared_data->SystemTime.High2Time, current_time >> 32, __ATOMIC_SEQ_CST);
    __atomic_store_n(&user_shared_data->SystemTime.LowPart, current_time, __ATOMIC_SEQ_CST);
    __atomic_store_n(&user_shared_data->SystemTime.High1Time, current_time >> 32, __ATOMIC_SEQ_CST);

    __atomic_store_n(&user_shared_data->InterruptTime.High2Time, monotonic_time >> 32, __ATOMIC_SEQ_CST);
    __atomic_store_n(&user_shared_data->InterruptTime.LowPart, monotonic_time, __ATOMIC_SEQ_CST);
    __atomic_store_n(&user_shared_data->InterruptTime.High1Time, monotonic_time >> 32, __ATOMIC_SEQ_CST);

    __atomic_store_n(&user_shared_data->TickCount.High2Time, tick_count >> 32, __ATOMIC_SEQ_CST);
    __atomic_store_n(&user_shared_data->TickCount.LowPart, tick_count, __ATOMIC_SEQ_CST);
    __atomic_store_n(&user_shared_data->TickCount.High1Time, tick_count >> 32, __ATOMIC_SEQ_CST);
    __atomic_store_n(&user_shared_data->TickCountLowDeprecated, tick_count, __ATOMIC_SEQ_CST);
#endif
}

423
void set_current_time(void)
424 425 426 427 428
{
    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;
429
    monotonic_time = monotonic_counter();
430
    if (user_shared_data) set_user_shared_data_time();
431
}
432 433

/* add a timeout user */
434
struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
435 436
{
    struct timeout_user *user;
437
    struct list *ptr;
438 439

    if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
440
    user->when     = timeout_to_abstime( when );
441 442 443 444 445
    user->callback = func;
    user->private  = private;

    /* Now insert it in the linked list */

446
    if (user->when > 0)
447
    {
448 449 450 451 452 453 454 455 456 457 458 459 460
        LIST_FOR_EACH( ptr, &abs_timeout_list )
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
            if (timeout->when >= user->when) break;
        }
    }
    else
    {
        LIST_FOR_EACH( ptr, &rel_timeout_list )
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
            if (timeout->when <= user->when) break;
        }
461
    }
462
    list_add_before( ptr, &user->entry );
463 464 465 466 467 468
    return user;
}

/* remove a timeout user */
void remove_timeout_user( struct timeout_user *user )
{
469
    list_remove( &user->entry );
470 471 472
    free( user );
}

473 474
/* return a text description of a timeout for debugging purposes */
const char *get_timeout_str( timeout_t timeout )
475
{
476 477 478 479 480 481 482 483 484 485 486 487 488
    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 */
489
    {
490 491 492
        secs = (timeout - current_time) / TICKS_PER_SEC;
        nsecs = (timeout - current_time) % TICKS_PER_SEC;
        if (nsecs < 0)
493
        {
494 495
            nsecs += TICKS_PER_SEC;
            secs--;
496
        }
497 498 499 500 501 502 503
        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 );
504
    }
505
    return buffer;
506 507 508 509 510 511 512 513 514 515 516 517 518
}


/****************************************************************/
/* 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 */

519 520
static int get_next_timeout(void);

521 522 523 524 525
static inline void fd_poll_event( struct fd *fd, int event )
{
    fd->fd_ops->poll_event( fd, event );
}

526 527
#ifdef USE_EPOLL

528
static int epoll_fd = -1;
529 530 531 532 533

static inline void init_epoll(void)
{
    epoll_fd = epoll_create( 128 );
}
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

/* 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;
560
    memset(&ev.data, 0, sizeof(ev.data));
561 562 563 564 565 566 567 568 569 570 571 572 573
    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 */
    }
}

574 575 576
static inline void remove_epoll_user( struct fd *fd, int user )
{
    if (epoll_fd == -1) return;
577

578 579 580 581 582 583 584 585
    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)
586
{
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    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 */

604
        ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
605
        set_current_time();
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620

        /* 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 );
        }
    }
621 622
}

623 624 625 626 627 628
#elif defined(HAVE_KQUEUE)

static int kqueue_fd = -1;

static inline void init_epoll(void)
{
629 630 631 632 633 634 635 636 637
#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;
638
#endif
639
    kqueue_fd = kqueue();
640 641 642 643 644 645 646 647
}

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

    if (kqueue_fd == -1) return;

648 649
    EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
    EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
650 651 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 679 680 681 682 683 684 685 686 687 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

    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;
715
            ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
716
        }
717
        else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
718

719
        set_current_time();
720

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
        /* 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;
        }
    }
}

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
#elif defined(USE_EVENT_PORTS)

static int port_fd = -1;

static inline void init_epoll(void)
{
    port_fd = port_create();
}

static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
{
    int ret;

    if (port_fd == -1) return;

    if (events == -1)  /* stop waiting on this fd completely */
    {
        if (pollfd[user].fd == -1) return;  /* already removed */
        port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
    }
    else if (pollfd[user].fd == -1)
    {
        if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
        ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
    }
    else
    {
        if (pollfd[user].events == events) return;  /* nothing to do */
        ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
    }

    if (ret == -1)
    {
        if (errno == ENOMEM)  /* not enough memory, give up on port_associate */
        {
            close( port_fd );
            port_fd = -1;
        }
        else perror( "port_associate" );  /* should not happen */
    }
}

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

    if (pollfd[user].fd != -1)
    {
        port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
    }
}

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

    if (port_fd == -1) return;

    while (active_users)
    {
        timeout = get_next_timeout();
        nget = 1;

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

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

            ts.tv_sec = timeout / 1000;
            ts.tv_nsec = (timeout % 1000) * 1000000;
819
            ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
820
        }
821
        else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846

	if (ret == -1) break;  /* an error occurred with event completion */

        set_current_time();

        /* put the events into the pollfd array first, like poll does */
        for (i = 0; i < nget; i++)
        {
            long user = (long)events[i].portev_user;
            pollfd[user].revents = events[i].portev_events;
        }

        /* read events from the pollfd array, as set_fd_events may modify them */
        for (i = 0; i < nget; i++)
        {
            long user = (long)events[i].portev_user;
            if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
            /* if we are still interested, reassociate the fd */
            if (pollfd[user].fd != -1) {
                port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
            }
        }
    }
}

847
#else /* HAVE_KQUEUE */
848 849 850 851 852 853

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) { }

854 855 856
#endif /* USE_EPOLL */


857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
/* 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;
884
            if (!allocated_users) init_epoll();
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
            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 );
902

903
    remove_epoll_user( fd, user );
904 905 906 907 908 909 910 911
    pollfd[user].fd = -1;
    pollfd[user].events = 0;
    pollfd[user].revents = 0;
    poll_users[user] = (struct fd *)freelist;
    freelist = &poll_users[user];
    active_users--;
}

912 913
/* process pending timeouts and return the time until the next timeout, in milliseconds */
static int get_next_timeout(void)
914
{
915 916
    int ret = user_shared_data ? user_shared_data_timeout : -1;

917
    if (!list_empty( &abs_timeout_list ) || !list_empty( &rel_timeout_list ))
918
    {
919
        struct list expired_list, *ptr;
920

921
        /* first remove all expired timers from the list */
922

923
        list_init( &expired_list );
924
        while ((ptr = list_head( &abs_timeout_list )) != NULL)
925 926
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
927

928
            if (timeout->when <= current_time)
929
            {
930
                list_remove( &timeout->entry );
931
                list_add_tail( &expired_list, &timeout->entry );
932
            }
933 934
            else break;
        }
935 936 937 938 939 940 941 942 943 944 945
        while ((ptr = list_head( &rel_timeout_list )) != NULL)
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );

            if (-timeout->when <= monotonic_time)
            {
                list_remove( &timeout->entry );
                list_add_tail( &expired_list, &timeout->entry );
            }
            else break;
        }
946

947
        /* now call the callback for all the removed timers */
948

949 950 951 952 953 954 955 956
        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 );
        }

957
        if ((ptr = list_head( &abs_timeout_list )) != NULL)
958 959
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
960 961 962
            timeout_t diff = (timeout->when - current_time + 9999) / 10000;
            if (diff > INT_MAX) diff = INT_MAX;
            else if (diff < 0) diff = 0;
963
            if (ret == -1 || diff < ret) ret = diff;
964 965 966 967 968
        }

        if ((ptr = list_head( &rel_timeout_list )) != NULL)
        {
            struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
969 970 971
            timeout_t diff = (-timeout->when - monotonic_time + 9999) / 10000;
            if (diff > INT_MAX) diff = INT_MAX;
            else if (diff < 0) diff = 0;
972
            if (ret == -1 || diff < ret) ret = diff;
973
        }
974
    }
975
    return ret;
976 977 978 979 980 981 982
}

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

983 984
    set_current_time();
    server_start_time = current_time;
985

986
    main_loop_epoll();
987 988
    /* fall through to normal poll loop */

989 990 991 992 993
    while (active_users)
    {
        timeout = get_next_timeout();

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

995
        ret = poll( pollfd, nb_users, timeout );
996
        set_current_time();
997

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
        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;
                }
            }
        }
    }
}

1012 1013

/****************************************************************/
1014 1015 1016 1017
/* device functions */

static struct list device_hash[DEVICE_HASH_SIZE];

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
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 */
1030
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
1031 1032 1033
    struct statfs stfs;

    if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1034
    return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1035 1036 1037 1038
#elif defined(__NetBSD__)
    struct statvfs stfs;

    if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
1039
    return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
#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
}

1055
/* retrieve the device object for a given fd, creating it if needed */
1056
static struct device *get_device( dev_t dev, int unix_fd )
1057 1058 1059
{
    struct device *device;
    unsigned int i, hash = dev % DEVICE_HASH_SIZE;
1060

1061 1062 1063 1064 1065 1066 1067 1068
    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 */
1069

1070
    if (unix_fd == -1) return NULL;
1071 1072 1073
    if ((device = alloc_object( &device_ops )))
    {
        device->dev = dev;
1074
        device->removable = is_device_removable( dev, unix_fd );
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
        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" );
}
1088

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
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 */
1103

1104
/* close all pending file descriptors in the closed list */
1105
static void inode_close_pending( struct inode *inode, int keep_unlinks )
1106
{
1107 1108 1109
    struct list *ptr = list_head( &inode->closed );

    while (ptr)
1110
    {
1111 1112 1113
        struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
        struct list *next = list_next( &inode->closed, ptr );

1114
        if (fd->unix_fd != -1)
1115
        {
1116 1117
            close( fd->unix_fd );
            fd->unix_fd = -1;
1118
        }
1119
        if (!keep_unlinks || !fd->unlink)  /* get rid of it unless there's an unlink pending on that file */
1120 1121
        {
            list_remove( ptr );
1122
            free( fd->unix_name );
1123 1124 1125
            free( fd );
        }
        ptr = next;
1126 1127 1128
    }
}

1129 1130 1131
static void inode_dump( struct object *obj, int verbose )
{
    struct inode *inode = (struct inode *)obj;
1132
    fprintf( stderr, "Inode device=%p ino=", inode->device );
1133 1134 1135 1136 1137 1138 1139
    DUMP_LONG_LONG( inode->ino );
    fprintf( stderr, "\n" );
}

static void inode_destroy( struct object *obj )
{
    struct inode *inode = (struct inode *)obj;
1140
    struct list *ptr;
1141

1142 1143
    assert( list_empty(&inode->open) );
    assert( list_empty(&inode->locks) );
1144 1145

    list_remove( &inode->entry );
1146 1147 1148 1149 1150

    while ((ptr = list_head( &inode->closed )))
    {
        struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
        list_remove( ptr );
1151
        if (fd->unix_fd != -1) close( fd->unix_fd );
1152
        if (fd->unlink)
1153 1154 1155
        {
            /* make sure it is still the same file */
            struct stat st;
1156
            if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1157
            {
1158 1159
                if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
                else unlink( fd->unix_name );
1160
            }
1161
        }
1162
        free( fd->unix_name );
1163 1164
        free( fd );
    }
1165
    release_object( inode->device );
1166 1167 1168
}

/* retrieve the inode object for a given fd, creating it if needed */
1169
static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1170
{
1171
    struct device *device;
1172
    struct inode *inode;
1173
    unsigned int hash = ino % INODE_HASH_SIZE;
1174

1175
    if (!(device = get_device( dev, unix_fd ))) return NULL;
1176 1177

    LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1178
    {
1179
        if (inode->ino == ino)
1180
        {
1181 1182
            release_object( device );
            return (struct inode *)grab_object( inode );
1183 1184 1185 1186 1187 1188
        }
    }

    /* not found, create it */
    if ((inode = alloc_object( &inode_ops )))
    {
1189
        inode->device = device;
1190 1191
        inode->ino    = ino;
        list_init( &inode->open );
1192
        list_init( &inode->locks );
1193
        list_init( &inode->closed );
1194
        list_add_head( &device->inode_hash[hash], &inode->entry );
1195
    }
1196 1197
    else release_object( device );

1198 1199 1200
    return inode;
}

1201
/* add fd to the inode list of file descriptors to close */
1202 1203
static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
{
1204 1205
    if (!list_empty( &inode->locks ))
    {
1206
        list_add_head( &inode->closed, &fd->entry );
1207
    }
1208
    else if (fd->unlink)  /* close the fd but keep the structure around for unlink */
1209
    {
1210 1211
        if (fd->unix_fd != -1) close( fd->unix_fd );
        fd->unix_fd = -1;
1212 1213 1214
        list_add_head( &inode->closed, &fd->entry );
    }
    else  /* no locks on this inode and no unlink, get rid of the fd */
1215
    {
1216
        if (fd->unix_fd != -1) close( fd->unix_fd );
1217
        free( fd->unix_name );
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        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" );
}

1237
static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1238 1239 1240 1241 1242 1243 1244
{
    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 */
1245
static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1246 1247 1248
{
    struct flock fl;

1249
    if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    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)
        {
1263 1264 1265 1266 1267 1268 1269 1270
        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 */
1271 1272
        case EIO:
        case ENOLCK:
1273
        case ENOTSUP:
1274
            /* no locking on this fs, just ignore it */
1275
            fd->fs_locks = 0;
1276
            return 1;
1277 1278 1279
        case EAGAIN:
            set_error( STATUS_FILE_LOCK_CONFLICT );
            return 0;
1280 1281
        case EBADF:
            /* this can happen if we try to set a write lock on a read-only file */
1282 1283 1284 1285 1286 1287
            /* try to at least grab a read lock */
            if (fl.l_type == F_WRLCK)
            {
                type = F_RDLCK;
                break; /* retry */
            }
1288 1289
            set_error( STATUS_ACCESS_DENIED );
            return 0;
1290
#ifdef EOVERFLOW
1291
        case EOVERFLOW:
1292
#endif
1293
        case EINVAL:
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
            /* 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 */
1310
static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1311 1312 1313 1314 1315 1316 1317
{
    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 */
1318
static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
{
    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;
1332
    if (!fd->fs_locks) return;
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    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;
    }
1435 1436 1437
    list_add_tail( &fd->locks, &lock->fd_entry );
    list_add_tail( &fd->inode->locks, &lock->inode_entry );
    list_add_tail( &lock->process->locks, &lock->proc_entry );
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
    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 );
1450
    if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    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;

1491 1492 1493 1494 1495 1496
    if (!fd->inode)  /* not a regular file */
    {
        set_error( STATUS_INVALID_DEVICE_REQUEST );
        return 0;
    }

1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
    /* 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;
1509
        if (shared && (lock->shared || lock->fd == fd)) continue;
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
        /* 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 );
1547 1548 1549
}


1550 1551 1552
/****************************************************************/
/* file descriptor functions */

1553 1554 1555
static void fd_dump( struct object *obj, int verbose )
{
    struct fd *fd = (struct fd *)obj;
1556
    fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1557
    if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1558
    fprintf( stderr, "\n" );
1559 1560 1561 1562 1563
}

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

1565 1566 1567
    free_async_queue( &fd->read_q );
    free_async_queue( &fd->write_q );
    free_async_queue( &fd->wait_q );
1568

1569
    if (fd->completion) release_object( fd->completion );
1570
    remove_fd_locks( fd );
1571
    list_remove( &fd->inode_entry );
1572
    if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1573 1574 1575 1576 1577 1578 1579 1580
    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 );
1581
        free( fd->unix_name );
1582
    }
1583 1584
}

1585 1586 1587 1588 1589
/* check if the desired access is possible without violating */
/* the sharing mode of other opens of the same file */
static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
                                   unsigned int open_flags, unsigned int options )
{
1590 1591 1592 1593 1594
    /* only a few access bits are meaningful wrt sharing */
    const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
    const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
    const unsigned int all_access = read_access | write_access | DELETE;

1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
    unsigned int existing_access = 0;
    struct list *ptr;

    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)
        {
            /* if access mode is 0, sharing mode is ignored */
1608 1609
            if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
            existing_access |= fd_ptr->access;
1610 1611 1612
        }
    }

1613 1614
    if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
        ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1615 1616 1617
        ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
        return STATUS_SHARING_VIOLATION;
    if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1618
        ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1619 1620 1621 1622 1623
        return STATUS_SHARING_VIOLATION;
    if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
        return STATUS_CANNOT_DELETE;
    if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
        return STATUS_USER_MAPPED_FILE;
1624 1625 1626 1627
    if (!(access & all_access))
        return 0;  /* if access mode is 0, sharing mode is ignored (except for mappings) */
    if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
        ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1628 1629 1630 1631 1632
        ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
        return STATUS_SHARING_VIOLATION;
    return 0;
}

1633 1634 1635 1636 1637
/* 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 );
1638 1639 1640

    set_fd_epoll_events( fd, user, events );

1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
    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;
    }
}

1654 1655 1656 1657 1658
/* prepare an fd for unmounting its corresponding device */
static inline void unmount_fd( struct fd *fd )
{
    assert( fd->inode );

1659 1660
    async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
    async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1661 1662 1663 1664 1665 1666

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

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

    fd->unix_fd = -1;
1667
    fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1668
    fd->closed->unix_fd = -1;
1669
    fd->closed->unlink = 0;
1670 1671 1672 1673 1674

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

1675
/* allocate an fd object, without setting the unix fd yet */
1676
static struct fd *alloc_fd_object(void)
1677
{
1678
    struct fd *fd = alloc_object( &fd_ops );
1679

1680 1681
    if (!fd) return NULL;

1682 1683
    fd->fd_ops     = NULL;
    fd->user       = NULL;
1684 1685
    fd->inode      = NULL;
    fd->closed     = NULL;
1686
    fd->access     = 0;
1687
    fd->options    = 0;
1688
    fd->sharing    = 0;
1689
    fd->unix_fd    = -1;
1690
    fd->unix_name  = NULL;
1691
    fd->cacheable  = 0;
1692
    fd->signaled   = 1;
1693
    fd->fs_locks   = 1;
1694
    fd->poll_index = -1;
1695
    fd->completion = NULL;
1696
    fd->comp_flags = 0;
1697 1698 1699
    init_async_queue( &fd->read_q );
    init_async_queue( &fd->write_q );
    init_async_queue( &fd->wait_q );
1700
    list_init( &fd->inode_entry );
1701
    list_init( &fd->locks );
1702 1703 1704 1705 1706 1707 1708 1709 1710

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

1711
/* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1712
struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
{
    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;
1723
    fd->options    = options;
1724
    fd->sharing    = 0;
1725
    fd->unix_name  = NULL;
1726
    fd->unix_fd    = -1;
1727
    fd->cacheable  = 0;
1728
    fd->signaled   = 0;
1729 1730
    fd->fs_locks   = 0;
    fd->poll_index = -1;
1731
    fd->completion = NULL;
1732
    fd->comp_flags = 0;
1733
    fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1734 1735 1736
    init_async_queue( &fd->read_q );
    init_async_queue( &fd->write_q );
    init_async_queue( &fd->wait_q );
1737 1738 1739 1740 1741
    list_init( &fd->inode_entry );
    list_init( &fd->locks );
    return fd;
}

1742
/* duplicate an fd object for a different user */
1743
struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1744
{
1745
    unsigned int err;
1746
    struct fd *fd = alloc_fd_object();
1747 1748 1749

    if (!fd) return NULL;

1750
    fd->options    = options;
1751
    fd->cacheable  = orig->cacheable;
1752

1753 1754 1755 1756 1757
    if (orig->unix_name)
    {
        if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
        strcpy( fd->unix_name, orig->unix_name );
    }
1758 1759 1760 1761 1762 1763 1764

    if (orig->inode)
    {
        struct closed_fd *closed = mem_alloc( sizeof(*closed) );
        if (!closed) goto failed;
        if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
        {
1765
            file_set_error();
1766 1767 1768 1769
            free( closed );
            goto failed;
        }
        closed->unix_fd = fd->unix_fd;
1770 1771
        closed->unlink = 0;
        closed->unix_name = fd->unix_name;
1772 1773 1774
        fd->closed = closed;
        fd->inode = (struct inode *)grab_object( orig->inode );
        list_add_head( &fd->inode->open, &fd->inode_entry );
1775 1776 1777 1778 1779
        if ((err = check_sharing( fd, access, sharing, 0, options )))
        {
            set_error( err );
            goto failed;
        }
1780
    }
1781 1782 1783 1784 1785
    else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
    {
        file_set_error();
        goto failed;
    }
1786 1787 1788 1789 1790 1791 1792
    return fd;

failed:
    release_object( fd );
    return NULL;
}

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
/* find an existing fd object that can be reused for a mapping */
struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
{
    struct fd *fd_ptr;

    if (!fd->inode) return NULL;

    LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
        if (fd_ptr->access == access && fd_ptr->sharing == sharing)
            return (struct fd *)grab_object( fd_ptr );

    return NULL;
}

1807 1808 1809 1810 1811 1812 1813 1814
/* 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;
}

1815
char *dup_fd_name( struct fd *root, const char *name )
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
{
    char *ret;

    if (!root) return strdup( name );
    if (!root->unix_name) return NULL;

    /* skip . prefix */
    if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;

    if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
    {
        strcpy( ret, root->unix_name );
        if (name[0] && name[0] != '/') strcat( ret, "/" );
        strcat( ret, name );
    }
    return ret;
}

1834
/* open() wrapper that returns a struct fd with no fd user set */
1835
struct fd *open_fd( struct fd *root, const char *name, int flags, mode_t *mode, unsigned int access,
1836
                    unsigned int sharing, unsigned int options )
1837 1838 1839
{
    struct stat st;
    struct closed_fd *closed_fd;
1840
    struct fd *fd;
1841
    int root_fd = -1;
1842
    int rw_mode;
1843
    char *path;
1844

1845 1846
    if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
        ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1847 1848 1849 1850 1851
    {
        set_error( STATUS_INVALID_PARAMETER );
        return NULL;
    }

1852
    if (!(fd = alloc_fd_object())) return NULL;
1853

1854
    fd->options = options;
1855
    if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1856 1857 1858 1859
    {
        release_object( fd );
        return NULL;
    }
1860

1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
    if (root)
    {
        if ((root_fd = get_unix_fd( root )) == -1) goto error;
        if (fchdir( root_fd ) == -1)
        {
            file_set_error();
            root_fd = -1;
            goto error;
        }
    }

1872 1873 1874
    /* create the directory if needed */
    if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
    {
1875
        if (mkdir( name, *mode ) == -1)
1876 1877 1878 1879
        {
            if (errno != EEXIST || (flags & O_EXCL))
            {
                file_set_error();
1880
                goto error;
1881 1882 1883 1884
            }
        }
        flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
    }
1885 1886 1887 1888 1889 1890 1891 1892 1893

    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)
1894
    {
1895
        /* if we tried to open a directory for write access, retry read-only */
1896 1897 1898 1899 1900 1901 1902
        if (errno == EISDIR)
        {
            if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
                fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
        }

        if (fd->unix_fd == -1)
1903 1904 1905 1906
        {
            file_set_error();
            goto error;
        }
1907
    }
1908

1909 1910 1911 1912 1913 1914 1915
    fd->unix_name = NULL;
    if ((path = dup_fd_name( root, name )))
    {
        fd->unix_name = realpath( path, NULL );
        free( path );
    }

1916
    closed_fd->unix_fd = fd->unix_fd;
1917 1918
    closed_fd->unlink = 0;
    closed_fd->unix_name = fd->unix_name;
1919 1920 1921
    fstat( fd->unix_fd, &st );
    *mode = st.st_mode;

1922 1923
    /* only bother with an inode for normal files and directories */
    if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1924
    {
1925
        unsigned int err;
1926
        struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1927 1928 1929 1930 1931 1932

        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
             */
1933
            goto error;
1934 1935 1936
        }
        fd->inode = inode;
        fd->closed = closed_fd;
1937
        fd->cacheable = !inode->device->removable;
1938
        list_add_head( &inode->open, &fd->inode_entry );
1939
        closed_fd = NULL;
1940 1941 1942 1943 1944

        /* check directory options */
        if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
        {
            set_error( STATUS_NOT_A_DIRECTORY );
1945
            goto error;
1946 1947 1948 1949
        }
        if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
        {
            set_error( STATUS_FILE_IS_A_DIRECTORY );
1950
            goto error;
1951
        }
1952
        if ((err = check_sharing( fd, access, sharing, flags, options )))
1953
        {
1954
            set_error( err );
1955
            goto error;
1956
        }
1957 1958 1959 1960 1961 1962 1963 1964 1965

        /* can't unlink files if we don't have permission to access */
        if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
            !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
        {
            set_error( STATUS_CANNOT_DELETE );
            goto error;
        }

1966
        fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) ? -1 : 0;
1967 1968 1969 1970 1971
        if (flags & O_TRUNC)
        {
            if (S_ISDIR(st.st_mode))
            {
                set_error( STATUS_OBJECT_NAME_COLLISION );
1972
                goto error;
1973 1974 1975
            }
            ftruncate( fd->unix_fd, 0 );
        }
1976
    }
1977
    else  /* special file */
1978
    {
1979
        if (options & FILE_DELETE_ON_CLOSE)  /* we can't unlink special files */
1980 1981
        {
            set_error( STATUS_INVALID_PARAMETER );
1982
            goto error;
1983
        }
1984
        free( closed_fd );
1985
        fd->cacheable = 1;
1986
    }
1987
    if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1988
    return fd;
1989 1990 1991 1992

error:
    release_object( fd );
    free( closed_fd );
1993
    if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1994
    return NULL;
1995 1996
}

1997 1998
/* create an fd for an anonymous file */
/* if the function fails the unix fd is closed */
1999 2000
struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
                                unsigned int options )
2001
{
2002
    struct fd *fd = alloc_fd_object();
2003 2004 2005

    if (fd)
    {
2006
        set_fd_user( fd, fd_user_ops, user );
2007
        fd->unix_fd = unix_fd;
2008
        fd->options = options;
2009 2010 2011 2012 2013 2014
        return fd;
    }
    close( unix_fd );
    return NULL;
}

2015 2016
/* retrieve the object that is using an fd */
void *get_fd_user( struct fd *fd )
2017
{
2018 2019
    return fd->user;
}
2020

2021 2022 2023 2024 2025 2026
/* retrieve the opening options for the fd */
unsigned int get_fd_options( struct fd *fd )
{
    return fd->options;
}

2027 2028 2029 2030 2031 2032
/* check if fd is in overlapped mode */
int is_fd_overlapped( struct fd *fd )
{
    return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
}

2033 2034 2035
/* retrieve the unix fd for an object */
int get_unix_fd( struct fd *fd )
{
2036
    if (fd->unix_fd == -1) set_error( fd->no_fd_status );
2037
    return fd->unix_fd;
2038 2039
}

2040 2041 2042 2043 2044 2045
/* 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;
}

2046 2047 2048 2049 2050 2051
/* allow the fd to be cached (can't be reset once set) */
void allow_fd_caching( struct fd *fd )
{
    fd->cacheable = 1;
}

2052 2053 2054 2055 2056 2057
/* check if fd is on a removable device */
int is_fd_removable( struct fd *fd )
{
    return (fd->inode && fd->inode->device->removable);
}

2058 2059 2060
/* set or clear the fd signaled state */
void set_fd_signaled( struct fd *fd, int signaled )
{
2061
    if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2062 2063 2064 2065
    fd->signaled = signaled;
    if (signaled) wake_up( fd->user, 0 );
}

2066 2067 2068 2069 2070 2071
/* 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);
}

2072 2073 2074 2075 2076
/* check if events are pending and if yes return which one(s) */
int check_fd_events( struct fd *fd, int events )
{
    struct pollfd pfd;

2077
    if (fd->unix_fd == -1) return POLLERR;
2078
    if (fd->inode) return events;  /* regular files are always signaled */
2079

2080 2081 2082 2083
    pfd.fd     = fd->unix_fd;
    pfd.events = events;
    if (poll( &pfd, 1, 0 ) <= 0) return 0;
    return pfd.revents;
2084 2085 2086
}

/* default signaled() routine for objects that poll() on an fd */
2087
int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2088
{
2089
    struct fd *fd = get_obj_fd( obj );
2090
    int ret = fd->signaled;
2091 2092
    release_object( fd );
    return ret;
2093 2094
}

2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
/* 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);
}

2105 2106 2107 2108
int default_fd_get_poll_events( struct fd *fd )
{
    int events = 0;

2109 2110
    if (async_waiting( &fd->read_q )) events |= POLLIN;
    if (async_waiting( &fd->write_q )) events |= POLLOUT;
2111 2112 2113
    return events;
}

2114 2115 2116
/* default handler for poll() events */
void default_poll_event( struct fd *fd, int event )
{
2117 2118
    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 );
2119 2120

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

2125
void fd_queue_async( struct fd *fd, struct async *async, int type )
2126
{
2127
    struct async_queue *queue;
2128 2129 2130 2131

    switch (type)
    {
    case ASYNC_TYPE_READ:
2132
        queue = &fd->read_q;
2133 2134
        break;
    case ASYNC_TYPE_WRITE:
2135
        queue = &fd->write_q;
2136
        break;
2137
    case ASYNC_TYPE_WAIT:
2138
        queue = &fd->wait_q;
2139
        break;
2140
    default:
2141
        queue = NULL;
2142
        assert(0);
2143 2144
    }

2145 2146 2147
    queue_async( queue, async );

    if (type != ASYNC_TYPE_WAIT)
2148
    {
2149 2150 2151 2152
        if (!fd->inode)
            set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
        else  /* regular files are always ready for read and write */
            async_wake_up( queue, STATUS_ALERTED );
2153
    }
2154 2155
}

2156
void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2157 2158 2159 2160
{
    switch (type)
    {
    case ASYNC_TYPE_READ:
2161
        async_wake_up( &fd->read_q, status );
2162 2163
        break;
    case ASYNC_TYPE_WRITE:
2164
        async_wake_up( &fd->write_q, status );
2165 2166
        break;
    case ASYNC_TYPE_WAIT:
2167
        async_wake_up( &fd->wait_q, status );
2168 2169 2170 2171 2172 2173
        break;
    default:
        assert(0);
    }
}

2174 2175 2176 2177 2178
void fd_reselect_async( struct fd *fd, struct async_queue *queue )
{
    fd->fd_ops->reselect_async( fd, queue );
}

2179
void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2180 2181 2182 2183
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
}

2184
void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2185
{
2186 2187
    fd_queue_async( fd, async, type );
    set_error( STATUS_PENDING );
2188 2189
}

2190 2191 2192
/* default reselect_async() fd routine */
void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
{
2193
    if (queue == &fd->read_q || queue == &fd->write_q)
2194 2195 2196 2197 2198 2199 2200 2201
    {
        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 );
    }
}

2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
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
}

2212
/* close all Unix file descriptors on a device to allow unmounting it */
2213
static void unmount_device( struct fd *device_fd )
2214 2215
{
    unsigned int i;
2216 2217
    struct stat st;
    struct device *device;
2218 2219
    struct inode *inode;
    struct fd *fd;
2220
    int unix_fd = get_unix_fd( device_fd );
2221

2222 2223
    if (unix_fd == -1) return;

2224
    if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2225 2226 2227 2228 2229
    {
        set_error( STATUS_INVALID_PARAMETER );
        return;
    }

2230
    if (!(device = get_device( st.st_rdev, -1 ))) return;
2231

2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
    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 );
2246
    release_object( device );
2247 2248
}

2249
/* default read() routine */
2250
int no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2251 2252 2253 2254 2255 2256
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
    return 0;
}

/* default write() routine */
2257
int no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2258 2259 2260 2261 2262 2263
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
    return 0;
}

/* default flush() routine */
2264
int no_fd_flush( struct fd *fd, struct async *async )
2265 2266
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
2267
    return 0;
2268 2269
}

2270
/* default get_file_info() routine */
2271
void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2272 2273 2274 2275
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
}

2276 2277 2278
/* default get_file_info() routine */
void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
{
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
    switch (info_class)
    {
    case FileAccessInformation:
        {
            FILE_ACCESS_INFORMATION info;
            if (get_reply_max_size() < sizeof(info))
            {
                set_error( STATUS_INFO_LENGTH_MISMATCH );
                return;
            }
            info.AccessFlags = get_handle_access( current->process, handle );
            set_reply_data( &info, sizeof(info) );
            break;
        }
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
    case FileModeInformation:
        {
            FILE_MODE_INFORMATION info;
            if (get_reply_max_size() < sizeof(info))
            {
                set_error( STATUS_INFO_LENGTH_MISMATCH );
                return;
            }
            info.Mode = fd->options & ( FILE_WRITE_THROUGH
                                      | FILE_SEQUENTIAL_ONLY
                                      | FILE_NO_INTERMEDIATE_BUFFERING
                                      | FILE_SYNCHRONOUS_IO_ALERT
                                      | FILE_SYNCHRONOUS_IO_NONALERT );
            set_reply_data( &info, sizeof(info) );
            break;
        }
2309 2310 2311 2312 2313 2314 2315 2316
    case FileIoCompletionNotificationInformation:
        {
            FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
            if (get_reply_max_size() < sizeof(info))
            {
                set_error( STATUS_INFO_LENGTH_MISMATCH );
                return;
            }
2317
            info.Flags = fd->comp_flags;
2318 2319 2320
            set_reply_data( &info, sizeof(info) );
            break;
        }
2321 2322 2323
    default:
        set_error( STATUS_NOT_IMPLEMENTED );
    }
2324 2325
}

2326 2327 2328 2329 2330 2331
/* default get_volume_info() routine */
void no_fd_get_volume_info( struct fd *fd, unsigned int info_class )
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
}

2332
/* default ioctl() routine */
2333
int no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2334 2335 2336 2337 2338
{
    set_error( STATUS_OBJECT_TYPE_MISMATCH );
    return 0;
}

2339
/* default ioctl() routine */
2340
int default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2341 2342 2343 2344 2345
{
    switch(code)
    {
    case FSCTL_DISMOUNT_VOLUME:
        unmount_device( fd );
2346
        return 1;
2347 2348
    default:
        set_error( STATUS_NOT_SUPPORTED );
2349
        return 0;
2350 2351 2352
    }
}

2353 2354 2355 2356 2357 2358 2359
/* 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;

2360
    if ((obj = get_handle_obj( process, handle, access, NULL )))
2361
    {
2362
        fd = get_obj_fd( obj );
2363 2364 2365 2366 2367
        release_object( obj );
    }
    return fd;
}

2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
static int is_dir_empty( int fd )
{
    DIR *dir;
    int empty;
    struct dirent *de;

    if ((fd = dup( fd )) == -1)
        return -1;

    if (!(dir = fdopendir( fd )))
    {
        close( fd );
        return -1;
    }

    empty = 1;
    while (empty && (de = readdir( dir )))
    {
        if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
        empty = 0;
    }
    closedir( dir );
    return empty;
}

2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
/* set disposition for the fd */
static void set_fd_disposition( struct fd *fd, int unlink )
{
    struct stat st;

    if (!fd->inode)
    {
        set_error( STATUS_OBJECT_TYPE_MISMATCH );
        return;
    }

    if (fd->unix_fd == -1)
    {
        set_error( fd->no_fd_status );
        return;
    }

2410
    if (unlink)
2411
    {
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
        if (fstat( fd->unix_fd, &st ) == -1)
        {
            file_set_error();
            return;
        }
        if (S_ISREG( st.st_mode ))  /* can't unlink files we don't have permission to write */
        {
            if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
            {
                set_error( STATUS_CANNOT_DELETE );
                return;
            }
        }
        else if (S_ISDIR( st.st_mode ))  /* can't remove non-empty directories */
        {
            switch (is_dir_empty( fd->unix_fd ))
            {
            case -1:
                file_set_error();
                return;
            case 0:
                set_error( STATUS_DIRECTORY_NOT_EMPTY );
                return;
            }
        }
        else  /* can't unlink special files */
        {
            set_error( STATUS_INVALID_PARAMETER );
            return;
        }
2442 2443
    }

2444 2445 2446
    fd->closed->unlink = unlink ? 1 : 0;
    if (fd->options & FILE_DELETE_ON_CLOSE)
        fd->closed->unlink = -1;
2447 2448
}

2449
/* set new name for the fd */
2450
static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr,
2451
                         data_size_t len, int create_link, int replace )
2452 2453
{
    struct inode *inode;
2454
    struct stat st, st2;
2455 2456 2457 2458 2459 2460 2461
    char *name;

    if (!fd->inode || !fd->unix_name)
    {
        set_error( STATUS_OBJECT_TYPE_MISMATCH );
        return;
    }
2462 2463 2464 2465 2466 2467
    if (fd->unix_fd == -1)
    {
        set_error( fd->no_fd_status );
        return;
    }

2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    if (!len || ((nameptr[0] == '/') ^ !root))
    {
        set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
        return;
    }
    if (!(name = mem_alloc( len + 1 ))) return;
    memcpy( name, nameptr, len );
    name[len] = 0;

    if (root)
    {
        char *combined_name = dup_fd_name( root, name );
        if (!combined_name)
        {
            set_error( STATUS_NO_MEMORY );
            goto failed;
        }
        free( name );
        name = combined_name;
    }

2489
    /* when creating a hard link, source cannot be a dir */
2490
    if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2491 2492 2493 2494 2495
    {
        set_error( STATUS_FILE_IS_A_DIRECTORY );
        goto failed;
    }

2496 2497
    if (!stat( name, &st ))
    {
2498 2499 2500 2501 2502 2503 2504
        if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
        {
            if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
            free( name );
            return;
        }

2505 2506 2507 2508 2509 2510
        if (!replace)
        {
            set_error( STATUS_OBJECT_NAME_COLLISION );
            goto failed;
        }

2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
        /* can't replace directories or special files */
        if (!S_ISREG( st.st_mode ))
        {
            set_error( STATUS_ACCESS_DENIED );
            goto failed;
        }

        /* can't replace an opened file */
        if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
        {
            int is_empty = list_empty( &inode->open );
            release_object( inode );
            if (!is_empty)
            {
                set_error( STATUS_ACCESS_DENIED );
                goto failed;
            }
        }

2530
        /* link() expects that the target doesn't exist */
2531
        /* rename() cannot replace files with directories */
2532
        if (create_link || S_ISDIR( st2.st_mode ))
2533
        {
2534 2535 2536 2537 2538
            if (unlink( name ))
            {
                file_set_error();
                goto failed;
            }
2539 2540 2541
        }
    }

2542 2543 2544 2545 2546 2547 2548 2549
    if (create_link)
    {
        if (link( fd->unix_name, name ))
            file_set_error();
        free( name );
        return;
    }

2550 2551 2552 2553 2554 2555
    if (rename( fd->unix_name, name ))
    {
        file_set_error();
        goto failed;
    }

2556 2557
    if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
    {
2558
        if (is_file_executable( name ))
2559 2560 2561 2562 2563 2564 2565
            /* set executable bit where read bit is set */
            st.st_mode |= (st.st_mode & 0444) >> 2;
        else
            st.st_mode &= ~0111;
        fchmod( fd->unix_fd, st.st_mode );
    }

2566
    free( fd->unix_name );
2567 2568 2569 2570
    fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
    free( name );
    if (!fd->unix_name)
        set_error( STATUS_NO_MEMORY );
2571 2572 2573 2574 2575 2576
    return;

failed:
    free( name );
}

2577
struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2578
{
2579
    *p_key = fd->comp_key;
2580 2581 2582 2583 2584 2585 2586
    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 );
2587
    dst->comp_flags = src->comp_flags;
2588 2589
}

2590
/* flush a file buffers */
2591
DECL_HANDLER(flush)
2592
{
2593
    struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2594
    struct async *async;
2595

2596 2597
    if (!fd) return;

2598
    if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2599
    {
2600
        reply->event = async_handoff( async, fd->fd_ops->flush( fd, async ), NULL, 1 );
2601
        release_object( async );
2602
    }
2603
    release_object( fd );
2604 2605
}

2606 2607 2608 2609 2610 2611 2612
/* query file info */
DECL_HANDLER(get_file_info)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );

    if (fd)
    {
2613
        fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2614 2615 2616 2617
        release_object( fd );
    }
}

2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
/* query volume info */
DECL_HANDLER(get_volume_info)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );

    if (fd)
    {
        fd->fd_ops->get_volume_info( fd, req->info_class );
        release_object( fd );
    }
}

2630 2631 2632
/* open a file object */
DECL_HANDLER(open_file_object)
{
2633
    struct unicode_str name = get_req_unicode_str();
2634
    struct object *obj, *result, *root = NULL;
2635

2636 2637 2638 2639 2640
    if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;

    obj = open_named_object( root, NULL, &name, req->attributes );
    if (root) release_object( root );
    if (!obj) return;
2641

2642 2643 2644 2645 2646 2647
    if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
    {
        reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
        release_object( result );
    }
    release_object( obj );
2648 2649
}

2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
/* get the Unix name from a file handle */
DECL_HANDLER(get_handle_unix_name)
{
    struct fd *fd;

    if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
    {
        if (fd->unix_name)
        {
            data_size_t name_len = strlen( fd->unix_name );
            reply->name_len = name_len;
            if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
            else set_error( STATUS_BUFFER_OVERFLOW );
        }
2664
        else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2665 2666 2667 2668
        release_object( fd );
    }
}

2669 2670 2671 2672 2673
/* get a Unix fd to access a file */
DECL_HANDLER(get_handle_fd)
{
    struct fd *fd;

2674
    if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2675
    {
2676
        int unix_fd = get_unix_fd( fd );
2677
        reply->cacheable = fd->cacheable;
2678
        if (unix_fd != -1)
2679
        {
2680 2681 2682
            reply->type = fd->fd_ops->get_fd_type( fd );
            reply->options = fd->options;
            reply->access = get_handle_access( current->process, req->handle );
2683
            send_client_fd( current->process, unix_fd, req->handle );
2684
        }
2685 2686 2687 2688
        release_object( fd );
    }
}

2689 2690 2691 2692
/* perform a read on a file object */
DECL_HANDLER(read)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2693
    struct async *async;
2694

2695 2696
    if (!fd) return;

2697
    if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2698
    {
2699
        reply->wait    = async_handoff( async, fd->fd_ops->read( fd, async, req->pos ), NULL, 0 );
2700 2701
        reply->options = fd->options;
        release_object( async );
2702
    }
2703
    release_object( fd );
2704 2705 2706 2707 2708 2709
}

/* perform a write on a file object */
DECL_HANDLER(write)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2710
    struct async *async;
2711

2712 2713
    if (!fd) return;

2714
    if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2715
    {
2716
        reply->wait    = async_handoff( async, fd->fd_ops->write( fd, async, req->pos ), &reply->size, 0 );
2717 2718
        reply->options = fd->options;
        release_object( async );
2719
    }
2720
    release_object( fd );
2721 2722
}

2723 2724 2725 2726
/* perform an ioctl on a file */
DECL_HANDLER(ioctl)
{
    unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2727
    struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2728
    struct async *async;
2729

2730 2731
    if (!fd) return;

2732
    if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2733
    {
2734
        reply->wait    = async_handoff( async, fd->fd_ops->ioctl( fd, req->code, async ), NULL, 0 );
2735 2736
        reply->options = fd->options;
        release_object( async );
2737
    }
2738
    release_object( fd );
2739 2740
}

2741 2742 2743
/* create / reschedule an async I/O */
DECL_HANDLER(register_async)
{
2744
    unsigned int access;
2745
    struct async *async;
2746
    struct fd *fd;
2747

2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
    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;
    }
2760

2761
    if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2762
    {
2763
        if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2764 2765 2766 2767
        {
            fd->fd_ops->queue_async( fd, async, req->type, req->count );
            release_object( async );
        }
2768 2769 2770
        release_object( fd );
    }
}
2771

2772 2773 2774 2775 2776 2777 2778
/* 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)
    {
2779
        if (is_fd_overlapped( fd ) && !fd->completion)
2780 2781 2782 2783 2784 2785 2786 2787
        {
            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 );
    }
}
2788 2789 2790 2791 2792 2793 2794

/* 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)
    {
2795
        if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2796
            add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2797 2798 2799
        release_object( fd );
    }
}
2800

2801 2802 2803 2804 2805 2806
/* set fd completion information */
DECL_HANDLER(set_fd_completion_mode)
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
    if (fd)
    {
2807
        if (is_fd_overlapped( fd ))
2808
        {
2809 2810 2811
            if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
                set_fd_signaled( fd, 0 );
            /* removing flags is not allowed */
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821
            fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
                                           | FILE_SKIP_SET_EVENT_ON_HANDLE
                                           | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
        }
        else
            set_error( STATUS_INVALID_PARAMETER );
        release_object( fd );
    }
}

2822 2823
/* set fd disposition information */
DECL_HANDLER(set_fd_disp_info)
2824 2825 2826 2827 2828 2829 2830 2831
{
    struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
    if (fd)
    {
        set_fd_disposition( fd, req->unlink );
        release_object( fd );
    }
}
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849

/* set fd name information */
DECL_HANDLER(set_fd_name_info)
{
    struct fd *fd, *root_fd = NULL;

    if (req->rootdir)
    {
        struct dir *root;

        if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
        root_fd = get_obj_fd( (struct object *)root );
        release_object( root );
        if (!root_fd) return;
    }

    if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
    {
2850
        set_fd_name( fd, root_fd, get_req_data(), get_req_data_size(), req->link, req->replace );
2851 2852 2853 2854
        release_object( fd );
    }
    if (root_fd) release_object( root_fd );
}