inputthread.c 14.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
/* inputthread.c -- Threaded generation of input events.
 *
 * Copyright © 2007-2008 Tiago Vignatti <vignatti at freedesktop org>
 * Copyright © 2010 Nokia
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Authors: Fernando Carrijo <fcarrijo at freedesktop org>
 *          Tiago Vignatti <vignatti at freedesktop org>
 */

#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "inputstr.h"
#include "opaque.h"
#include "osdep.h"

#if INPUTTHREAD

Bool InputThreadEnable = TRUE;

/**
 * An input device as seen by the threaded input facility
 */
49 50 51 52 53 54 55

typedef enum _InputDeviceState {
    device_state_added,
    device_state_running,
    device_state_removed
} InputDeviceState;

56 57 58 59 60
typedef struct _InputThreadDevice {
    struct xorg_list node;
    NotifyFdProcPtr readInputProc;
    void *readInputArgs;
    int fd;
61
    InputDeviceState state;
62 63 64 65 66 67 68 69 70 71
} InputThreadDevice;

/**
 * The threaded input facility.
 *
 * For now, we have one instance for all input devices.
 */
typedef struct {
    pthread_t thread;
    struct xorg_list devs;
72
    struct ospoll *fds;
73 74
    int readPipe;
    int writePipe;
75 76
    Bool changed;
    Bool running;
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
} InputThreadInfo;

static InputThreadInfo *inputThreadInfo;

static int hotplugPipeRead = -1;
static int hotplugPipeWrite = -1;

static int input_mutex_count;

#ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
static pthread_mutex_t input_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
#else
static pthread_mutex_t input_mutex;
static Bool input_mutex_initialized;
#endif

void
input_lock(void)
{
#ifndef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
    if (!input_mutex_initialized) {
        pthread_mutexattr_t mutex_attr;

        input_mutex_initialized = TRUE;
        pthread_mutexattr_init(&mutex_attr);
        pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&input_mutex, &mutex_attr);
    }
#endif
    pthread_mutex_lock(&input_mutex);
    ++input_mutex_count;
}

void
input_unlock(void)
{
    --input_mutex_count;
    pthread_mutex_unlock(&input_mutex);
}

void
input_force_unlock(void)
{
    if (pthread_mutex_trylock(&input_mutex) == 0) {
121
        input_mutex_count++;
122
        /* unlock +1 times for the trylock */
123 124
        while (input_mutex_count > 0)
            input_unlock();
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    }
}

/**
 * Notify a thread about the availability of new asynchronously enqueued input
 * events.
 *
 * @see WaitForSomething()
 */
static void
InputThreadFillPipe(int writeHead)
{
    int ret;
    char byte = 0;

140
    do {
141
        ret = write(writeHead, &byte, 1);
142
    } while (ret < 0 && ETEST(errno));
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
}

/**
 * Consume eventual notifications left by a thread.
 *
 * @see WaitForSomething()
 * @see InputThreadFillPipe()
 */
static int
InputThreadReadPipe(int readHead)
{
    int ret, array[10];

    ret = read(readHead, &array, sizeof(array));
    if (ret >= 0)
        return ret;

    if (errno != EAGAIN)
        FatalError("input-thread: draining pipe (%d)", errno);

    return 1;
}

166 167 168 169 170 171 172 173 174 175 176
static void
InputReady(int fd, int xevents, void *data)
{
    InputThreadDevice *dev = data;

    input_lock();
    if (dev->state == device_state_running)
        dev->readInputProc(fd, xevents, dev->readInputArgs);
    input_unlock();
}

177 178 179 180 181 182 183 184 185 186 187 188 189 190
/**
 * Register an input device in the threaded input facility
 *
 * @param fd File descriptor which identifies the input device
 * @param readInputProc Procedure used to read input from the device
 * @param readInputArgs Arguments to be consumed by the above procedure
 *
 * return 1 if success; 0 otherwise.
 */
int
InputThreadRegisterDev(int fd,
                       NotifyFdProcPtr readInputProc,
                       void *readInputArgs)
{
191
    InputThreadDevice *dev, *old;
192 193 194 195

    if (!inputThreadInfo)
        return SetNotifyFd(fd, readInputProc, X_NOTIFY_READ, readInputArgs);

196
    input_lock();
197

198 199 200 201 202 203 204
    dev = NULL;
    xorg_list_for_each_entry(old, &inputThreadInfo->devs, node) {
        if (old->fd == fd) {
            dev = old;
            break;
        }
    }
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    if (dev) {
        dev->readInputProc = readInputProc;
        dev->readInputArgs = readInputArgs;
    } else {
        dev = calloc(1, sizeof(InputThreadDevice));
        if (dev == NULL) {
            DebugF("input-thread: could not register device\n");
            input_unlock();
            return 0;
        }

        dev->fd = fd;
        dev->readInputProc = readInputProc;
        dev->readInputArgs = readInputArgs;
        dev->state = device_state_added;
        xorg_list_append(&dev->node, &inputThreadInfo->devs);
    }
223

224
    inputThreadInfo->changed = TRUE;
225

226
    input_unlock();
227

228 229 230
    DebugF("input-thread: registered device %d\n", fd);
    InputThreadFillPipe(hotplugPipeWrite);

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    return 1;
}

/**
 * Unregister a device in the threaded input facility
 *
 * @param fd File descriptor which identifies the input device
 *
 * @return 1 if success; 0 otherwise.
 */
int
InputThreadUnregisterDev(int fd)
{
    InputThreadDevice *dev;
    Bool found_device = FALSE;

    /* return silently if input thread is already finished (e.g., at
     * DisableDevice time, evdev tries to call this function again through
     * xf86RemoveEnabledDevice) */
    if (!inputThreadInfo) {
        RemoveNotifyFd(fd);
        return 1;
    }

255
    input_lock();
256 257 258 259 260 261 262
    xorg_list_for_each_entry(dev, &inputThreadInfo->devs, node)
        if (dev->fd == fd) {
            found_device = TRUE;
            break;
        }

    /* fd didn't match any registered device. */
263 264
    if (!found_device) {
        input_unlock();
265
        return 0;
266
    }
267

268 269
    dev->state = device_state_removed;
    inputThreadInfo->changed = TRUE;
270 271 272

    input_unlock();

273 274 275 276 277 278
    InputThreadFillPipe(hotplugPipeWrite);
    DebugF("input-thread: unregistered device: %d\n", fd);

    return 1;
}

279 280 281 282 283 284 285 286 287
static void
InputThreadPipeNotify(int fd, int revents, void *data)
{
    /* Empty pending input, shut down if the pipe has been closed */
    if (InputThreadReadPipe(hotplugPipeRead) == 0) {
        inputThreadInfo->running = FALSE;
    }
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
/**
 * The workhorse of threaded input event generation.
 *
 * Or if you prefer: The WaitForSomething for input devices. :)
 *
 * Runs in parallel with the server main thread, listening to input devices in
 * an endless loop. Whenever new input data is made available, calls the
 * proper device driver's routines which are ultimately responsible for the
 * generation of input events.
 *
 * @see InputThreadPreInit()
 * @see InputThreadInit()
 */

static void*
InputThreadDoWork(void *arg)
{
    sigset_t set;

    /* Don't handle any signals on this thread */
    sigfillset(&set);
    pthread_sigmask(SIG_BLOCK, &set, NULL);

311
    inputThreadInfo->running = TRUE;
312

313 314 315 316 317 318
#if defined(HAVE_PTHREAD_SETNAME_NP_WITH_TID)
    pthread_setname_np (pthread_self(), "InputThread");
#elif defined(HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID)
    pthread_setname_np ("InputThread");
#endif

319 320 321 322 323
    ospoll_add(inputThreadInfo->fds, hotplugPipeRead,
               ospoll_trigger_level,
               InputThreadPipeNotify,
               NULL);
    ospoll_listen(inputThreadInfo->fds, hotplugPipeRead, X_NOTIFY_READ);
324

325 326
    while (inputThreadInfo->running)
    {
327 328
        DebugF("input-thread: %s waiting for devices\n", __func__);

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
        /* Check for hotplug changes and modify the ospoll structure to suit */
        if (inputThreadInfo->changed) {
            InputThreadDevice *dev, *tmp;

            input_lock();
            inputThreadInfo->changed = FALSE;
            xorg_list_for_each_entry_safe(dev, tmp, &inputThreadInfo->devs, node) {
                switch (dev->state) {
                case device_state_added:
                    ospoll_add(inputThreadInfo->fds, dev->fd,
                               ospoll_trigger_level,
                               InputReady,
                               dev);
                    ospoll_listen(inputThreadInfo->fds, dev->fd, X_NOTIFY_READ);
                    dev->state = device_state_running;
                    break;
                case device_state_running:
                    break;
                case device_state_removed:
                    ospoll_remove(inputThreadInfo->fds, dev->fd);
                    xorg_list_del(&dev->node);
                    free(dev);
                    break;
                }
            }
            input_unlock();
        }

        if (ospoll_wait(inputThreadInfo->fds, -1) < 0) {
358 359 360 361 362 363 364 365 366 367
            if (errno == EINVAL)
                FatalError("input-thread: %s (%s)", __func__, strerror(errno));
            else if (errno != EINTR)
                ErrorF("input-thread: %s (%s)\n", __func__, strerror(errno));
        }

        /* Kick main thread to process the generated input events and drain
         * events from hotplug pipe */
        InputThreadFillPipe(inputThreadInfo->writePipe);
    }
368 369 370

    ospoll_remove(inputThreadInfo->fds, hotplugPipeRead);

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    return NULL;
}

static void
InputThreadNotifyPipe(int fd, int mask, void *data)
{
    InputThreadReadPipe(fd);
}

/**
 * Pre-initialize the facility used for threaded generation of input events
 *
 */
void
InputThreadPreInit(void)
{
    int fds[2], hotplugPipe[2];
388
    int flags;
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

    if (!InputThreadEnable)
        return;

    if (pipe(fds) < 0)
        FatalError("input-thread: could not create pipe");

     if (pipe(hotplugPipe) < 0)
        FatalError("input-thread: could not create pipe");

    inputThreadInfo = malloc(sizeof(InputThreadInfo));
    if (!inputThreadInfo)
        FatalError("input-thread: could not allocate memory");

    inputThreadInfo->thread = 0;
    xorg_list_init(&inputThreadInfo->devs);
405
    inputThreadInfo->fds = ospoll_create();
406 407 408 409 410 411

    /* By making read head non-blocking, we ensure that while the main thread
     * is busy servicing client requests, the dedicated input thread can work
     * in parallel.
     */
    inputThreadInfo->readPipe = fds[0];
412 413 414 415 416 417
    fcntl(inputThreadInfo->readPipe, F_SETFL, O_NONBLOCK);
    flags = fcntl(inputThreadInfo->readPipe, F_GETFD);
    if (flags != -1) {
        flags |= FD_CLOEXEC;
        (void)fcntl(inputThreadInfo->readPipe, F_SETFD, &flags);
    }
418 419 420 421 422
    SetNotifyFd(inputThreadInfo->readPipe, InputThreadNotifyPipe, X_NOTIFY_READ, NULL);

    inputThreadInfo->writePipe = fds[1];

    hotplugPipeRead = hotplugPipe[0];
423 424 425 426 427 428
    fcntl(hotplugPipeRead, F_SETFL, O_NONBLOCK);
    flags = fcntl(hotplugPipeRead, F_GETFD);
    if (flags != -1) {
        flags |= FD_CLOEXEC;
        (void)fcntl(hotplugPipeRead, F_SETFD, &flags);
    }
429
    hotplugPipeWrite = hotplugPipe[1];
430

431 432 433 434 435 436
#if defined(HAVE_PTHREAD_SETNAME_NP_WITH_TID)
    pthread_setname_np (pthread_self(), "MainThread");
#elif defined(HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID)
    pthread_setname_np ("MainThread");
#endif

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
}

/**
 * Start the threaded generation of input events. This routine complements what
 * was previously done by InputThreadPreInit(), being only responsible for
 * creating the dedicated input thread.
 *
 */
void
InputThreadInit(void)
{
    pthread_attr_t attr;

    /* If the driver hasn't asked for input thread support by calling
     * InputThreadPreInit, then do nothing here
     */
    if (!inputThreadInfo)
        return;

    pthread_attr_init(&attr);

    /* For OSes that differentiate between processes and threads, the following
     * lines have sense. Linux uses the 1:1 thread model. The scheduler handles
     * every thread as a normal process. Therefore this probably has no meaning
     * if we are under Linux.
     */
    if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0)
        ErrorF("input-thread: error setting thread scope\n");

    DebugF("input-thread: creating thread\n");
    pthread_create(&inputThreadInfo->thread, &attr,
                   &InputThreadDoWork, NULL);

    pthread_attr_destroy (&attr);
}

/**
 * Stop the threaded generation of input events
 *
 * This function is supposed to be called at server shutdown time only.
 */
void
InputThreadFini(void)
{
    InputThreadDevice *dev, *next;

    if (!inputThreadInfo)
        return;

    /* Close the pipe to get the input thread to shut down */
    close(hotplugPipeWrite);
    pthread_join(inputThreadInfo->thread, NULL);

    xorg_list_for_each_entry_safe(dev, next, &inputThreadInfo->devs, node) {
491
        ospoll_remove(inputThreadInfo->fds, dev->fd);
492 493 494
        free(dev);
    }
    xorg_list_init(&inputThreadInfo->devs);
495
    ospoll_destroy(inputThreadInfo->fds);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

    RemoveNotifyFd(inputThreadInfo->readPipe);
    close(inputThreadInfo->readPipe);
    close(inputThreadInfo->writePipe);
    inputThreadInfo->readPipe = -1;
    inputThreadInfo->writePipe = -1;

    close(hotplugPipeRead);
    hotplugPipeRead = -1;
    hotplugPipeWrite = -1;

    free(inputThreadInfo);
    inputThreadInfo = NULL;
}

int xthread_sigmask(int how, const sigset_t *set, sigset_t *oldset)
{
    return pthread_sigmask(how, set, oldset);
}

#else /* INPUTTHREAD */

Bool InputThreadEnable = FALSE;

void input_lock(void) {}
void input_unlock(void) {}
void input_force_unlock(void) {}

void InputThreadPreInit(void) {}
void InputThreadInit(void) {}
void InputThreadFini(void) {}

int InputThreadRegisterDev(int fd,
                           NotifyFdProcPtr readInputProc,
                           void *readInputArgs)
{
    return SetNotifyFd(fd, readInputProc, X_NOTIFY_READ, readInputArgs);
}

extern int InputThreadUnregisterDev(int fd)
{
    RemoveNotifyFd(fd);
    return 1;
}

int xthread_sigmask(int how, const sigset_t *set, sigset_t *oldset)
{
    return sigprocmask(how, set, oldset);
}

#endif