virpcimock.c 26.2 KB
Newer Older
M
Michal Privoznik 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * 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, see
 * <http://www.gnu.org/licenses/>.
 *
 * Author: Michal Privoznik <mprivozn@redhat.com>
 */

#include <config.h>

23
#if defined(__linux__) || defined(__FreeBSD__)
24
# include "virmock.h"
M
Michal Privoznik 已提交
25 26 27 28 29
# include <stdlib.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <stdarg.h>
30
# include <dirent.h>
M
Michal Privoznik 已提交
31 32 33
# include "viralloc.h"
# include "virstring.h"
# include "virfile.h"
34
# include "dirname.h"
M
Michal Privoznik 已提交
35

36 37 38 39 40 41 42 43
static int (*real_access)(const char *path, int mode);
static int (*real_lstat)(const char *path, struct stat *sb);
static int (*real___lxstat)(int ver, const char *path, struct stat *sb);
static int (*real_stat)(const char *path, struct stat *sb);
static int (*real___xstat)(int ver, const char *path, struct stat *sb);
static int (*real_open)(const char *path, int flags, ...);
static int (*real_close)(int fd);
static DIR * (*real_opendir)(const char *name);
44
static char *(*real_virFileCanonicalizePath)(const char *path);
M
Michal Privoznik 已提交
45 46 47 48 49

/* Don't make static, since it causes problems with clang
 * when passed as an arg to virAsprintf()
 * vircgroupmock.c:462:22: error: static variable 'fakesysfsdir' is used in an inline function with external linkage [-Werror,-Wstatic-in-inline]
 */
50
char *fakerootdir;
51
char *fakesysfspcidir;
M
Michal Privoznik 已提交
52

53
# define SYSFS_PCI_PREFIX "/sys/bus/pci/"
M
Michal Privoznik 已提交
54

55 56 57 58 59 60 61 62 63
# define STDERR(...) \
    fprintf(stderr, "%s %zu: ", __FUNCTION__, (size_t) __LINE__); \
    fprintf(stderr, __VA_ARGS__); \
    fprintf(stderr, "\n"); \

# define ABORT(...) \
    do { \
        STDERR(__VA_ARGS__); \
        abort(); \
M
Michal Privoznik 已提交
64 65
    } while (0)

66
# define ABORT_OOM() \
M
Michal Privoznik 已提交
67 68 69 70 71
    ABORT("Out of memory")
/*
 * The plan:
 *
 * Mock some file handling functions. Redirect them into a stub tree passed via
72
 * LIBVIRT_FAKE_ROOT_DIR env variable. All files and links within stub tree is
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
 * created by us. There are some actions that we must take if some special
 * files are written to. Here's the list of files we watch:
 *
 * /sys/bus/pci/drivers/<driver>/new_id:
 *   Learn the driver new vendor and device combination.
 *   Data in format "VVVV DDDD".
 *
 * /sys/bus/pci/drivers/<driver>/remove_id
 *   Make the driver forget about vendor and device.
 *   Data in format "VVVV DDDD".
 *
 * /sys/bus/pci/drivers/<driver>/bind
 *   Check if driver supports the device and bind driver to it (create symlink
 *   called 'driver' pointing to the /sys/but/pci/drivers/<driver>).
 *   Data in format "DDDD:BB:DD.F" (Domain:Bus:Device.Function).
 *
 * /sys/bus/pci/drivers/<driver>/unbind
 *   Unbind driver from the device.
 *   Data in format "DDDD:BB:DD.F" (Domain:Bus:Device.Function).
 *
93 94 95 96
 * /sys/bus/pci/drivers_probe
 *   Probe for a driver that handles the specified device.
 *   Data in format "DDDD:BB:DD.F" (Domain:Bus:Device.Function).
 *
97 98 99 100
 * As a little hack, we are not mocking write to these files, but close()
 * instead. The advantage is we don't need any self growing array to hold the
 * partial writes and construct them back. We can let all the writes finish,
 * and then just read the file content back.
M
Michal Privoznik 已提交
101 102 103 104 105 106 107 108
 */

/*
 *
 * Functions to model kernel behavior
 *
 */

109 110 111 112 113 114 115
enum driverActions {
    PCI_ACTION_BIND         = 1 << 0,
    PCI_ACTION_UNBIND       = 1 << 1,
    PCI_ACTION_NEW_ID       = 1 << 2,
    PCI_ACTION_REMOVE_ID    = 1 << 3,
};

116 117 118 119 120
struct pciDriver {
    char *name;
    int *vendor;        /* List of vendor:device IDs the driver can handle */
    int *device;
    size_t len;            /* @len is used for both @vendor and @device */
121
    unsigned int fail;  /* Bitwise-OR of driverActions that should fail */
122 123
};

M
Michal Privoznik 已提交
124 125 126 127
struct pciDevice {
    char *id;
    int vendor;
    int device;
128
    int class;
A
Andrea Bolognani 已提交
129
    int iommuGroup;
130 131 132 133 134 135
    struct pciDriver *driver;   /* Driver attached. NULL if attached to no driver */
};

struct fdCallback {
    int fd;
    char *path;
M
Michal Privoznik 已提交
136 137 138
};

struct pciDevice **pciDevices = NULL;
139
size_t nPCIDevices = 0;
M
Michal Privoznik 已提交
140

141
struct pciDriver **pciDrivers = NULL;
142
size_t nPCIDrivers = 0;
143 144 145 146

struct fdCallback *callbacks = NULL;
size_t nCallbacks = 0;

M
Michal Privoznik 已提交
147 148
static void init_env(void);

149
static int pci_device_autobind(struct pciDevice *dev);
M
Michal Privoznik 已提交
150
static void pci_device_new_from_stub(const struct pciDevice *data);
151 152 153
static struct pciDevice *pci_device_find_by_id(const char *id);
static struct pciDevice *pci_device_find_by_content(const char *path);

154
static void pci_driver_new(const char *name, int fail, ...);
155 156 157 158 159 160 161 162 163
static struct pciDriver *pci_driver_find_by_dev(struct pciDevice *dev);
static struct pciDriver *pci_driver_find_by_path(const char *path);
static int pci_driver_bind(struct pciDriver *driver, struct pciDevice *dev);
static int pci_driver_unbind(struct pciDriver *driver, struct pciDevice *dev);
static int pci_driver_handle_change(int fd, const char *path);
static int pci_driver_handle_bind(const char *path);
static int pci_driver_handle_unbind(const char *path);
static int pci_driver_handle_new_id(const char *path);
static int pci_driver_handle_remove_id(const char *path);
M
Michal Privoznik 已提交
164 165 166 167 168 169 170 171


/*
 * Helper functions
 */
static void
make_file(const char *path,
          const char *name,
172 173
          const char *value,
          ssize_t len)
M
Michal Privoznik 已提交
174 175 176
{
    int fd = -1;
    char *filepath = NULL;
177 178
    if (value && len == -1)
        len = strlen(value);
M
Michal Privoznik 已提交
179 180 181 182

    if (virAsprintfQuiet(&filepath, "%s/%s", path, name) < 0)
        ABORT_OOM();

183
    if ((fd = real_open(filepath, O_CREAT|O_WRONLY, 0666)) < 0)
M
Michal Privoznik 已提交
184 185
        ABORT("Unable to open: %s", filepath);

186
    if (value && safewrite(fd, value, len) != len)
M
Michal Privoznik 已提交
187 188 189 190 191 192
        ABORT("Unable to write: %s", filepath);

    VIR_FORCE_CLOSE(fd);
    VIR_FREE(filepath);
}

A
Andrea Bolognani 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
static void
make_symlink(const char *path,
          const char *name,
          const char *target)
{
    char *filepath = NULL;

    if (virAsprintfQuiet(&filepath, "%s/%s", path, name) < 0)
        ABORT_OOM();

    if (symlink(target, filepath) < 0)
        ABORT("Unable to create symlink filepath -> target");

    VIR_FREE(filepath);
}

209 210 211 212 213 214 215 216 217 218
static int
pci_read_file(const char *path,
              char *buf,
              size_t buf_size)
{
    int ret = -1;
    int fd = -1;
    char *newpath;

    if (virAsprintfQuiet(&newpath, "%s/%s",
219 220
                         fakesysfspcidir,
                         path + strlen(SYSFS_PCI_PREFIX)) < 0) {
221 222 223 224
        errno = ENOMEM;
        goto cleanup;
    }

225
    if ((fd = real_open(newpath, O_RDWR)) < 0)
226 227 228 229 230 231 232 233 234 235 236 237
        goto cleanup;

    bzero(buf, buf_size);
    if (saferead(fd, buf, buf_size - 1) < 0) {
        STDERR("Unable to read from %s", newpath);
        goto cleanup;
    }

    if (ftruncate(fd, 0) < 0)
        goto cleanup;

    ret = 0;
238
 cleanup:
239
    VIR_FREE(newpath);
240
    real_close(fd);
241 242 243
    return ret;
}

M
Michal Privoznik 已提交
244 245 246 247
static int
getrealpath(char **newpath,
            const char *path)
{
248
    init_env();
M
Michal Privoznik 已提交
249

250
    if (STRPREFIX(path, SYSFS_PCI_PREFIX)) {
M
Michal Privoznik 已提交
251
        if (virAsprintfQuiet(newpath, "%s/%s",
252 253
                             fakesysfspcidir,
                             path + strlen(SYSFS_PCI_PREFIX)) < 0) {
M
Michal Privoznik 已提交
254 255 256 257 258 259 260 261 262 263 264
            errno = ENOMEM;
            return -1;
        }
    } else {
        if (VIR_STRDUP_QUIET(*newpath, path) < 0)
            return -1;
    }

    return 0;
}

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
static bool
find_fd(int fd, size_t *indx)
{
    size_t i;

    for (i = 0; i < nCallbacks; i++) {
        if (callbacks[i].fd == fd) {
            if (indx)
                *indx = i;
            return true;
        }
    }

    return false;
}

static int
add_fd(int fd, const char *path)
{
    int ret = -1;
    size_t i;

    if (find_fd(fd, &i)) {
        struct fdCallback cb = callbacks[i];
        ABORT("FD %d %s already present in the array as %d %s",
              fd, path, cb.fd, cb.path);
    }

    if (VIR_REALLOC_N_QUIET(callbacks, nCallbacks + 1) < 0 ||
        VIR_STRDUP_QUIET(callbacks[nCallbacks].path, path) < 0) {
        errno = ENOMEM;
        goto cleanup;
    }

    callbacks[nCallbacks++].fd = fd;
    ret = 0;
301
 cleanup:
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    return ret;
}

static int
remove_fd(int fd)
{
    int ret = -1;
    size_t i;

    if (find_fd(fd, &i)) {
        struct fdCallback cb = callbacks[i];

        if (pci_driver_handle_change(cb.fd, cb.path) < 0)
            goto cleanup;

        VIR_FREE(cb.path);
        if (VIR_DELETE_ELEMENT(callbacks, i, nCallbacks) < 0) {
            errno = EINVAL;
            goto cleanup;
        }
    }

    ret = 0;
325
 cleanup:
326 327 328
    return ret;
}

M
Michal Privoznik 已提交
329 330 331 332 333 334 335 336 337

/*
 * PCI Device functions
 */
static void
pci_device_new_from_stub(const struct pciDevice *data)
{
    struct pciDevice *dev;
    char *devpath;
338 339
    char *id;
    char *c;
340
    char *configSrc;
A
Andrea Bolognani 已提交
341
    char tmp[256];
342
    struct stat sb;
343
    bool configSrcExists = false;
M
Michal Privoznik 已提交
344

345 346 347 348 349 350 351 352 353 354 355 356 357 358
    if (VIR_STRDUP_QUIET(id, data->id) < 0)
        ABORT_OOM();

    /* Replace ':' with '-' to create the config filename from the
     * device ID. The device ID cannot be used directly as filename
     * because it contains ':' and Windows does not allow ':' in
     * filenames. */
    c = strchr(id, ':');

    while (c) {
        *c = '-';
        c = strchr(c, ':');
    }

M
Michal Privoznik 已提交
359
    if (VIR_ALLOC_QUIET(dev) < 0 ||
360
        virAsprintfQuiet(&configSrc, "%s/virpcitestdata/%s.config",
361
                         abs_srcdir, id) < 0 ||
362
        virAsprintfQuiet(&devpath, "%s/devices/%s", fakesysfspcidir, data->id) < 0)
M
Michal Privoznik 已提交
363 364
        ABORT_OOM();

365
    VIR_FREE(id);
M
Michal Privoznik 已提交
366 367 368 369 370
    memcpy(dev, data, sizeof(*dev));

    if (virFileMakePath(devpath) < 0)
        ABORT("Unable to create: %s", devpath);

371 372 373 374 375 376 377 378 379
    if (real_stat && real_stat(configSrc, &sb) == 0)
        configSrcExists = true;

# ifdef HAVE___XSTAT
    if (!configSrcExists &&
        real___xstat && real___xstat(_STAT_VER, configSrc, &sb) == 0)
        configSrcExists = true;
# endif

380 381
    /* If there is a config file for the device within virpcitestdata dir,
     * symlink it. Otherwise create a dummy config file. */
382
    if (configSrcExists) {
383 384 385 386 387 388 389 390 391 392 393 394 395
        /* On success, copy @configSrc into the destination (a copy,
         * rather than a symlink, is required since we write into the
         * file, and parallel VPATH builds must not stomp on the
         * original; besides, 'make distcheck' requires the original
         * to be read-only */
        char *buf;
        ssize_t len;

        if ((len = virFileReadAll(configSrc, 4096, &buf)) < 0)
            ABORT("Unable to read config file '%s'", configSrc);

        make_file(devpath, "config", buf, len);
        VIR_FREE(buf);
396 397 398
    } else {
        /* If there's no config data in the virpcitestdata dir, create a dummy
         * config file */
399
        make_file(devpath, "config", "some dummy config", -1);
400
    }
M
Michal Privoznik 已提交
401 402 403

    if (snprintf(tmp, sizeof(tmp),  "0x%.4x", dev->vendor) < 0)
        ABORT("@tmp overflow");
404
    make_file(devpath, "vendor", tmp, -1);
M
Michal Privoznik 已提交
405 406 407

    if (snprintf(tmp, sizeof(tmp),  "0x%.4x", dev->device) < 0)
        ABORT("@tmp overflow");
408
    make_file(devpath, "device", tmp, -1);
M
Michal Privoznik 已提交
409

410 411 412 413
    if (snprintf(tmp, sizeof(tmp),  "0x%.4x", dev->class) < 0)
        ABORT("@tmp overflow");
    make_file(devpath, "class", tmp, -1);

A
Andrea Bolognani 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427
    if (snprintf(tmp, sizeof(tmp),
                 "%s/../../../kernel/iommu_groups/%d",
                 devpath, dev->iommuGroup) < 0) {
        ABORT("@tmp overflow");
    }
    if (virFileMakePath(tmp) < 0)
        ABORT("Unable to create %s", tmp);

    if (snprintf(tmp, sizeof(tmp),
                 "../../../kernel/iommu_groups/%d", dev->iommuGroup) < 0) {
        ABORT("@tmp overflow");
    }
    make_symlink(devpath, "iommu_group", tmp);

428 429 430
    if (pci_device_autobind(dev) < 0)
        ABORT("Unable to bind: %s", data->id);

431
    if (VIR_APPEND_ELEMENT_QUIET(pciDevices, nPCIDevices, dev) < 0)
M
Michal Privoznik 已提交
432 433 434
        ABORT_OOM();

    VIR_FREE(devpath);
435
    VIR_FREE(configSrc);
M
Michal Privoznik 已提交
436 437
}

438 439 440 441
static struct pciDevice *
pci_device_find_by_id(const char *id)
{
    size_t i;
442
    for (i = 0; i < nPCIDevices; i++) {
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
        struct pciDevice *dev = pciDevices[i];

        if (STREQ(dev->id, id))
            return dev;
    }

    return NULL;
}

static struct pciDevice *
pci_device_find_by_content(const char *path)
{
    char tmp[32];

    if (pci_read_file(path, tmp, sizeof(tmp)) < 0)
        return NULL;

    return pci_device_find_by_id(tmp);
}

static int
pci_device_autobind(struct pciDevice *dev)
{
    struct pciDriver *driver = pci_driver_find_by_dev(dev);

    if (!driver) {
        /* No driver found. Nothing to do */
        return 0;
    }

    return pci_driver_bind(driver, dev);
}


/*
 * PCI Driver functions
 */
static void
481
pci_driver_new(const char *name, int fail, ...)
482 483 484 485 486 487 488 489
{
    struct pciDriver *driver;
    va_list args;
    int vendor, device;
    char *driverpath;

    if (VIR_ALLOC_QUIET(driver) < 0 ||
        VIR_STRDUP_QUIET(driver->name, name) < 0 ||
490
        virAsprintfQuiet(&driverpath, "%s/drivers/%s", fakesysfspcidir, name) < 0)
491 492
        ABORT_OOM();

493 494
    driver->fail = fail;

495 496 497
    if (virFileMakePath(driverpath) < 0)
        ABORT("Unable to create: %s", driverpath);

498
    va_start(args, fail);
499 500 501 502 503 504 505 506 507 508 509 510 511 512

    while ((vendor = va_arg(args, int)) != -1) {
        if ((device = va_arg(args, int)) == -1)
            ABORT("Invalid vendor device pair for driver %s", name);

        if (VIR_REALLOC_N_QUIET(driver->vendor, driver->len + 1) < 0 ||
            VIR_REALLOC_N_QUIET(driver->device, driver->len + 1) < 0)
            ABORT_OOM();

        driver->vendor[driver->len] = vendor;
        driver->device[driver->len] = device;
        driver->len++;
    }

513 514
    va_end(args);

515 516 517 518
    make_file(driverpath, "bind", NULL, -1);
    make_file(driverpath, "unbind", NULL, -1);
    make_file(driverpath, "new_id", NULL, -1);
    make_file(driverpath, "remove_id", NULL, -1);
519

520
    if (VIR_APPEND_ELEMENT_QUIET(pciDrivers, nPCIDrivers, driver) < 0)
521
        ABORT_OOM();
522 523

    VIR_FREE(driverpath);
524 525 526 527 528 529 530
}

static struct pciDriver *
pci_driver_find_by_dev(struct pciDevice *dev)
{
    size_t i;

531
    for (i = 0; i < nPCIDrivers; i++) {
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        struct pciDriver *driver = pciDrivers[i];
        size_t j;

        for (j = 0; j < driver->len; j++) {
            if (driver->vendor[j] == dev->vendor &&
                driver->device[j] == dev->device)
                return driver;
        }
    }

    return NULL;
}

static struct pciDriver *
pci_driver_find_by_path(const char *path)
{
    size_t i;

550
    for (i = 0; i < nPCIDrivers; i++) {
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
        struct pciDriver *driver = pciDrivers[i];

        if (strstr(path, driver->name))
            return driver;
    }

    return NULL;
}

static int
pci_driver_bind(struct pciDriver *driver,
                struct pciDevice *dev)
{
    int ret = -1;
    char *devpath = NULL, *driverpath = NULL;

567 568
    if (dev->driver || PCI_ACTION_BIND & driver->fail) {
        /* Device already bound or failing driver requested */
569 570 571 572 573 574
        errno = ENODEV;
        return ret;
    }

    /* Make symlink under device tree */
    if (virAsprintfQuiet(&devpath, "%s/devices/%s/driver",
575
                         fakesysfspcidir, dev->id) < 0 ||
576
        virAsprintfQuiet(&driverpath, "%s/drivers/%s",
577
                         fakesysfspcidir, driver->name) < 0) {
578 579 580 581 582 583 584 585 586 587 588
        errno = ENOMEM;
        goto cleanup;
    }

    if (symlink(driverpath, devpath) < 0)
        goto cleanup;

    /* Make symlink under driver tree */
    VIR_FREE(devpath);
    VIR_FREE(driverpath);
    if (virAsprintfQuiet(&devpath, "%s/devices/%s",
589
                         fakesysfspcidir, dev->id) < 0 ||
590
        virAsprintfQuiet(&driverpath, "%s/drivers/%s/%s",
591
                         fakesysfspcidir, driver->name, dev->id) < 0) {
592 593 594 595 596 597 598 599 600
        errno = ENOMEM;
        goto cleanup;
    }

    if (symlink(devpath, driverpath) < 0)
        goto cleanup;

    dev->driver = driver;
    ret = 0;
601
 cleanup:
602 603 604 605 606 607 608 609 610 611 612 613
    VIR_FREE(devpath);
    VIR_FREE(driverpath);
    return ret;
}

static int
pci_driver_unbind(struct pciDriver *driver,
                  struct pciDevice *dev)
{
    int ret = -1;
    char *devpath = NULL, *driverpath = NULL;

614 615
    if (dev->driver != driver || PCI_ACTION_UNBIND & driver->fail) {
        /* Device not bound to the @driver or failing driver used */
616 617 618 619 620 621
        errno = ENODEV;
        return ret;
    }

    /* Make symlink under device tree */
    if (virAsprintfQuiet(&devpath, "%s/devices/%s/driver",
622
                         fakesysfspcidir, dev->id) < 0 ||
623
        virAsprintfQuiet(&driverpath, "%s/drivers/%s/%s",
624
                         fakesysfspcidir, driver->name, dev->id) < 0) {
625 626 627 628 629 630 631 632 633 634
        errno = ENOMEM;
        goto cleanup;
    }

    if (unlink(devpath) < 0 ||
        unlink(driverpath) < 0)
        goto cleanup;

    dev->driver = NULL;
    ret = 0;
635
 cleanup:
636 637 638 639 640
    VIR_FREE(devpath);
    VIR_FREE(driverpath);
    return ret;
}

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
static int
pci_driver_handle_drivers_probe(const char *path)
{
    struct pciDevice *dev;

    if (!(dev = pci_device_find_by_content(path))) {
        errno = ENODEV;
        return -1;
    }

    if (dev->driver)
        return 0;

    return pci_device_autobind(dev);
}

657 658 659 660 661 662
static int
pci_driver_handle_change(int fd ATTRIBUTE_UNUSED, const char *path)
{
    int ret;
    const char *file = last_component(path);

663
    if (STREQ(file, "bind"))
664
        ret = pci_driver_handle_bind(path);
665
    else if (STREQ(file, "unbind"))
666
        ret = pci_driver_handle_unbind(path);
667
    else if (STREQ(file, "new_id"))
668
        ret = pci_driver_handle_new_id(path);
669
    else if (STREQ(file, "remove_id"))
670
        ret = pci_driver_handle_remove_id(path);
671 672 673
    else if (STREQ(file, "drivers_probe"))
        ret = pci_driver_handle_drivers_probe(path);
    else
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        ABORT("Not handled write to: %s", path);
    return ret;
}

static int
pci_driver_handle_bind(const char *path)
{
    int ret = -1;
    struct pciDevice *dev = pci_device_find_by_content(path);
    struct pciDriver *driver = pci_driver_find_by_path(path);

    if (!driver || !dev) {
        /* This should never happen (TM) */
        errno = ENODEV;
        goto cleanup;
    }

    ret = pci_driver_bind(driver, dev);
692
 cleanup:
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
    return ret;
}

static int
pci_driver_handle_unbind(const char *path)
{
    int ret = -1;
    struct pciDevice *dev = pci_device_find_by_content(path);

    if (!dev || !dev->driver) {
        /* This should never happen (TM) */
        errno = ENODEV;
        goto cleanup;
    }

    ret = pci_driver_unbind(dev->driver, dev);
709
 cleanup:
710 711 712 713 714 715 716 717 718 719 720
    return ret;
}
static int
pci_driver_handle_new_id(const char *path)
{
    int ret = -1;
    struct pciDriver *driver = pci_driver_find_by_path(path);
    size_t i;
    int vendor, device;
    char buf[32];

721
    if (!driver || PCI_ACTION_NEW_ID & driver->fail) {
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        errno = ENODEV;
        goto cleanup;
    }

    if (pci_read_file(path, buf, sizeof(buf)) < 0)
        goto cleanup;

    if (sscanf(buf, "%x %x", &vendor, &device) < 2) {
        errno = EINVAL;
        goto cleanup;
    }

    for (i = 0; i < driver->len; i++) {
        if (driver->vendor[i] == vendor &&
            driver->device[i] == device)
            break;
    }

    if (i == driver->len) {
        if (VIR_REALLOC_N_QUIET(driver->vendor, driver->len + 1) < 0 ||
            VIR_REALLOC_N_QUIET(driver->device, driver->len + 1) < 0) {
            errno = ENOMEM;
            goto cleanup;
        }

        driver->vendor[driver->len] = vendor;
        driver->device[driver->len] = device;
        driver->len++;
    }

752
    for (i = 0; i < nPCIDevices; i++) {
753 754 755 756 757 758 759 760 761 762
        struct pciDevice *dev = pciDevices[i];

        if (!dev->driver &&
            dev->vendor == vendor &&
            dev->device == device &&
            pci_driver_bind(driver, dev) < 0)
                goto cleanup;
    }

    ret = 0;
763
 cleanup:
764 765 766 767 768 769 770 771 772 773 774 775
    return ret;
}

static int
pci_driver_handle_remove_id(const char *path)
{
    int ret = -1;
    struct pciDriver *driver = pci_driver_find_by_path(path);
    size_t i;
    int vendor, device;
    char buf[32];

776
    if (!driver || PCI_ACTION_REMOVE_ID & driver->fail) {
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
        errno = ENODEV;
        goto cleanup;
    }

    if (pci_read_file(path, buf, sizeof(buf)) < 0)
        goto cleanup;

    if (sscanf(buf, "%x %x", &vendor, &device) < 2) {
        errno = EINVAL;
        goto cleanup;
    }

    for (i = 0; i < driver->len; i++) {
        if (driver->vendor[i] == vendor &&
            driver->device[i] == device)
            continue;
    }

    if (i != driver->len) {
        if (VIR_DELETE_ELEMENT(driver->vendor, i, driver->len) < 0)
            goto cleanup;
        driver->len++;
        if (VIR_DELETE_ELEMENT(driver->device, i, driver->len) < 0)
            goto cleanup;
    }

    ret = 0;
804
 cleanup:
805 806 807
    return ret;
}

M
Michal Privoznik 已提交
808 809 810 811 812 813 814

/*
 * Functions to load the symbols and init the environment
 */
static void
init_syms(void)
{
815
    if (real_access)
M
Michal Privoznik 已提交
816 817
        return;

818 819 820 821 822 823
    VIR_MOCK_REAL_INIT(access);
    VIR_MOCK_REAL_INIT_ALT(lstat, __lxstat);
    VIR_MOCK_REAL_INIT_ALT(stat, __xstat);
    VIR_MOCK_REAL_INIT(open);
    VIR_MOCK_REAL_INIT(close);
    VIR_MOCK_REAL_INIT(opendir);
824
    VIR_MOCK_REAL_INIT(virFileCanonicalizePath);
M
Michal Privoznik 已提交
825 826 827 828 829
}

static void
init_env(void)
{
830
    if (fakerootdir && fakesysfspcidir)
M
Michal Privoznik 已提交
831 832
        return;

833 834
    if (!(fakerootdir = getenv("LIBVIRT_FAKE_ROOT_DIR")))
        ABORT("Missing LIBVIRT_FAKE_ROOT_DIR env variable\n");
M
Michal Privoznik 已提交
835

836 837
    if (virAsprintfQuiet(&fakesysfspcidir, "%s%s",
                         fakerootdir, SYSFS_PCI_PREFIX) < 0)
838 839
        ABORT_OOM();

840 841
    if (virFileMakePath(fakesysfspcidir) < 0)
        ABORT("Unable to create: %s", fakesysfspcidir);
842

843
    make_file(fakesysfspcidir, "drivers_probe", NULL, -1);
844

845
# define MAKE_PCI_DRIVER(name, ...) \
846
    pci_driver_new(name, 0, __VA_ARGS__, -1, -1)
847 848 849 850

    MAKE_PCI_DRIVER("iwlwifi", 0x8086, 0x0044);
    MAKE_PCI_DRIVER("i915", 0x8086, 0x0046, 0x8086, 0x0047);
    MAKE_PCI_DRIVER("pci-stub", -1, -1);
851
    pci_driver_new("vfio-pci", PCI_ACTION_BIND, -1, -1);
852

853 854 855 856 857
# define MAKE_PCI_DEVICE(Id, Vendor, Device, ...) \
    do { \
        struct pciDevice dev = {.id = (char *)Id, .vendor = Vendor, \
                                .device = Device, __VA_ARGS__}; \
        pci_device_new_from_stub(&dev); \
M
Michal Privoznik 已提交
858 859 860
    } while (0)

    MAKE_PCI_DEVICE("0000:00:00.0", 0x8086, 0x0044);
861 862 863
    MAKE_PCI_DEVICE("0000:00:01.0", 0x8086, 0x0044);
    MAKE_PCI_DEVICE("0000:00:02.0", 0x8086, 0x0046);
    MAKE_PCI_DEVICE("0000:00:03.0", 0x8086, 0x0048);
864
    MAKE_PCI_DEVICE("0001:00:00.0", 0x1014, 0x03b9, .class = 0x060400);
A
Andrea Bolognani 已提交
865 866
    MAKE_PCI_DEVICE("0001:01:00.0", 0x8086, 0x105e, .iommuGroup = 0);
    MAKE_PCI_DEVICE("0001:01:00.1", 0x8086, 0x105e, .iommuGroup = 0);
867
    MAKE_PCI_DEVICE("0005:80:00.0", 0x10b5, 0x8112, .class = 0x060400);
A
Andrea Bolognani 已提交
868 869 870
    MAKE_PCI_DEVICE("0005:90:01.0", 0x1033, 0x0035, .iommuGroup = 1);
    MAKE_PCI_DEVICE("0005:90:01.1", 0x1033, 0x0035, .iommuGroup = 1);
    MAKE_PCI_DEVICE("0005:90:01.2", 0x1033, 0x00e0, .iommuGroup = 1);
871 872 873
    MAKE_PCI_DEVICE("0000:0a:01.0", 0x8086, 0x0047);
    MAKE_PCI_DEVICE("0000:0a:02.0", 0x8286, 0x0048);
    MAKE_PCI_DEVICE("0000:0a:03.0", 0x8386, 0x0048);
M
Michal Privoznik 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
}


/*
 *
 * Mocked functions
 *
 */

int
access(const char *path, int mode)
{
    int ret;

    init_syms();

890
    if (STRPREFIX(path, SYSFS_PCI_PREFIX)) {
M
Michal Privoznik 已提交
891 892 893
        char *newpath;
        if (getrealpath(&newpath, path) < 0)
            return -1;
894
        ret = real_access(newpath, mode);
M
Michal Privoznik 已提交
895 896
        VIR_FREE(newpath);
    } else {
897
        ret = real_access(path, mode);
M
Michal Privoznik 已提交
898 899 900 901
    }
    return ret;
}

902
# ifdef HAVE___LXSTAT
M
Michal Privoznik 已提交
903 904 905 906 907 908 909
int
__lxstat(int ver, const char *path, struct stat *sb)
{
    int ret;

    init_syms();

910
    if (STRPREFIX(path, SYSFS_PCI_PREFIX)) {
M
Michal Privoznik 已提交
911 912 913
        char *newpath;
        if (getrealpath(&newpath, path) < 0)
            return -1;
914
        ret = real___lxstat(ver, newpath, sb);
M
Michal Privoznik 已提交
915 916
        VIR_FREE(newpath);
    } else {
917
        ret = real___lxstat(ver, path, sb);
M
Michal Privoznik 已提交
918 919 920
    }
    return ret;
}
921
# endif /* HAVE___LXSTAT */
M
Michal Privoznik 已提交
922 923 924 925 926 927 928 929

int
lstat(const char *path, struct stat *sb)
{
    int ret;

    init_syms();

930
    if (STRPREFIX(path, SYSFS_PCI_PREFIX)) {
M
Michal Privoznik 已提交
931 932 933
        char *newpath;
        if (getrealpath(&newpath, path) < 0)
            return -1;
934
        ret = real_lstat(newpath, sb);
M
Michal Privoznik 已提交
935 936
        VIR_FREE(newpath);
    } else {
937
        ret = real_lstat(path, sb);
M
Michal Privoznik 已提交
938 939 940 941
    }
    return ret;
}

942
# ifdef HAVE___XSTAT
943 944 945 946 947 948 949
int
__xstat(int ver, const char *path, struct stat *sb)
{
    int ret;

    init_syms();

950
    if (STRPREFIX(path, SYSFS_PCI_PREFIX)) {
951 952 953
        char *newpath;
        if (getrealpath(&newpath, path) < 0)
            return -1;
954
        ret = real___xstat(ver, newpath, sb);
955 956
        VIR_FREE(newpath);
    } else {
957
        ret = real___xstat(ver, path, sb);
958 959 960
    }
    return ret;
}
961
# endif /* HAVE___XSTAT */
962 963 964 965 966 967 968 969

int
stat(const char *path, struct stat *sb)
{
    int ret;

    init_syms();

970
    if (STRPREFIX(path, SYSFS_PCI_PREFIX)) {
971 972 973
        char *newpath;
        if (getrealpath(&newpath, path) < 0)
            return -1;
974
        ret = real_stat(newpath, sb);
975 976
        VIR_FREE(newpath);
    } else {
977
        ret = real_stat(path, sb);
978 979 980 981
    }
    return ret;
}

M
Michal Privoznik 已提交
982 983 984 985 986 987 988 989
int
open(const char *path, int flags, ...)
{
    int ret;
    char *newpath = NULL;

    init_syms();

990
    if (STRPREFIX(path, SYSFS_PCI_PREFIX) &&
M
Michal Privoznik 已提交
991 992 993 994 995 996 997
        getrealpath(&newpath, path) < 0)
        return -1;

    if (flags & O_CREAT) {
        va_list ap;
        mode_t mode;
        va_start(ap, flags);
998
        mode = (mode_t) va_arg(ap, int);
M
Michal Privoznik 已提交
999
        va_end(ap);
1000
        ret = real_open(newpath ? newpath : path, flags, mode);
M
Michal Privoznik 已提交
1001
    } else {
1002
        ret = real_open(newpath ? newpath : path, flags);
M
Michal Privoznik 已提交
1003
    }
1004 1005 1006

    /* Catch both: /sys/bus/pci/drivers/... and
     * /sys/bus/pci/device/.../driver/... */
1007
    if (ret >= 0 && STRPREFIX(path, SYSFS_PCI_PREFIX) &&
1008
        strstr(path, "driver") && add_fd(ret, path) < 0) {
1009
        real_close(ret);
1010 1011 1012
        ret = -1;
    }

M
Michal Privoznik 已提交
1013 1014 1015 1016
    VIR_FREE(newpath);
    return ret;
}

1017 1018 1019 1020 1021 1022 1023 1024
DIR *
opendir(const char *path)
{
    DIR *ret;
    char *newpath = NULL;

    init_syms();

1025
    if (STRPREFIX(path, SYSFS_PCI_PREFIX) &&
1026 1027 1028
        getrealpath(&newpath, path) < 0)
        return NULL;

1029
    ret = real_opendir(newpath ? newpath : path);
1030 1031 1032 1033 1034

    VIR_FREE(newpath);
    return ret;
}

1035 1036 1037 1038 1039
int
close(int fd)
{
    if (remove_fd(fd) < 0)
        return -1;
1040
    return real_close(fd);
1041
}
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

char *
virFileCanonicalizePath(const char *path)
{
    char *ret;

    init_syms();

    if (STRPREFIX(path, SYSFS_PCI_PREFIX)) {
        char *newpath;

        if (getrealpath(&newpath, path) < 0)
            return NULL;

        ret = real_virFileCanonicalizePath(newpath);
        VIR_FREE(newpath);
    } else {
        ret = real_virFileCanonicalizePath(path);
    }

    return ret;
}
M
Michal Privoznik 已提交
1064
#else
1065
/* Nothing to override on this platform */
M
Michal Privoznik 已提交
1066
#endif