“47cdbac47d78fa0663bc0d648301dea14ba1fb5a”上不存在“tests/virjsontest.c”
node_device_udev.c 54.4 KB
Newer Older
1 2 3
/*
 * node_device_udev.c: node device enumeration - libudev implementation
 *
4
 * Copyright (C) 2009-2015 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23 24
 *
 * Author: Dave Allan <dallan@redhat.com>
 */

#include <config.h>
#include <libudev.h>
25
#include <pciaccess.h>
26 27 28
#include <scsi/scsi.h>
#include <c-ctype.h>

29
#include "dirname.h"
30
#include "node_device_conf.h"
31
#include "node_device_event.h"
32
#include "node_device_driver.h"
33 34 35
#include "node_device_linux_sysfs.h"
#include "node_device_udev.h"
#include "virerror.h"
36 37
#include "driver.h"
#include "datatypes.h"
38
#include "virlog.h"
39
#include "viralloc.h"
40
#include "viruuid.h"
41
#include "virbuffer.h"
42
#include "virfile.h"
43
#include "virpci.h"
44
#include "virstring.h"
45
#include "virnetdev.h"
46
#include "virmdev.h"
47 48 49

#define VIR_FROM_THIS VIR_FROM_NODEDEV

50 51
VIR_LOG_INIT("node_device.node_device_udev");

52 53 54 55
#ifndef TYPE_RAID
# define TYPE_RAID 12
#endif

56 57 58 59 60 61
typedef struct _udevEventData udevEventData;
typedef udevEventData *udevEventDataPtr;

struct _udevEventData {
    virObjectLockable parent;

62 63 64 65
    struct udev_monitor *udev_monitor;
    int watch;
};

66 67 68 69 70 71 72 73 74 75 76 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
static virClassPtr udevEventDataClass;

static void
udevEventDataDispose(void *obj)
{
    struct udev *udev = NULL;
    udevEventDataPtr priv = obj;

    if (priv->watch != -1)
        virEventRemoveHandle(priv->watch);

    if (!priv->udev_monitor)
        return;

    udev = udev_monitor_get_udev(priv->udev_monitor);
    udev_monitor_unref(priv->udev_monitor);
    udev_unref(udev);
}


static int
udevEventDataOnceInit(void)
{
    if (!(udevEventDataClass = virClassNew(virClassForObjectLockable(),
                                           "udevEventData",
                                           sizeof(udevEventData),
                                           udevEventDataDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(udevEventData)

static udevEventDataPtr
udevEventDataNew(void)
{
    udevEventDataPtr ret = NULL;

    if (udevEventDataInitialize() < 0)
        return NULL;

    if (!(ret = virObjectLockableNew(udevEventDataClass)))
        return NULL;

    ret->watch = -1;
    return ret;
}

115

J
Ján Tomko 已提交
116 117 118 119 120 121 122 123 124 125 126
static bool
udevHasDeviceProperty(struct udev_device *dev,
                      const char *key)
{
    if (udev_device_get_property_value(dev, key))
        return true;

    return false;
}


127 128 129
static const char *
udevGetDeviceProperty(struct udev_device *udev_device,
                      const char *property_key)
130
{
131
    const char *ret = NULL;
132

133
    ret = udev_device_get_property_value(udev_device, property_key);
134

135 136
    VIR_DEBUG("Found property key '%s' value '%s' for device with sysname '%s'",
              property_key, NULLSTR(ret), udev_device_get_sysname(udev_device));
137 138 139 140 141

    return ret;
}


142 143 144 145
static int
udevGetStringProperty(struct udev_device *udev_device,
                      const char *property_key,
                      char **value)
146
{
147 148
    if (VIR_STRDUP(*value,
                   udevGetDeviceProperty(udev_device, property_key)) < 0)
149
        return -1;
150

151
    return 0;
152 153 154
}


155 156 157 158 159
static int
udevGetIntProperty(struct udev_device *udev_device,
                   const char *property_key,
                   int *value,
                   int base)
160
{
161
    const char *str = NULL;
162

163
    str = udevGetDeviceProperty(udev_device, property_key);
164

165
    if (str && virStrToLong_i(str, NULL, base, value) < 0) {
166 167
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
168
        return -1;
169
    }
170
    return 0;
171 172 173
}


174 175 176 177 178
static int
udevGetUintProperty(struct udev_device *udev_device,
                    const char *property_key,
                    unsigned int *value,
                    int base)
179
{
180
    const char *str = NULL;
181

182
    str = udevGetDeviceProperty(udev_device, property_key);
183

184
    if (str && virStrToLong_ui(str, NULL, base, value) < 0) {
185 186
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
187
        return -1;
188
    }
189
    return 0;
190 191 192
}


193 194 195
static const char *
udevGetDeviceSysfsAttr(struct udev_device *udev_device,
                       const char *attr_name)
196
{
197
    const char *ret = NULL;
198

199
    ret = udev_device_get_sysattr_value(udev_device, attr_name);
200 201

    VIR_DEBUG("Found sysfs attribute '%s' value '%s' "
202
              "for device with sysname '%s'",
203
              attr_name, NULLSTR(ret),
204 205 206 207 208
              udev_device_get_sysname(udev_device));
    return ret;
}


209 210 211 212
static int
udevGetStringSysfsAttr(struct udev_device *udev_device,
                       const char *attr_name,
                       char **value)
213
{
214
    if (VIR_STRDUP(*value, udevGetDeviceSysfsAttr(udev_device, attr_name)) < 0)
215
        return -1;
216

217
    virStringStripControlChars(*value);
218

219 220
    if (*value != NULL && (STREQ(*value, "")))
        VIR_FREE(*value);
221

222
    return 0;
223 224 225
}


226 227 228 229 230
static int
udevGetIntSysfsAttr(struct udev_device *udev_device,
                    const char *attr_name,
                    int *value,
                    int base)
231
{
232
    const char *str = NULL;
233

234
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
235

236
    if (str && virStrToLong_i(str, NULL, base, value) < 0) {
237 238
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
239
        return -1;
240 241
    }

242
    return 0;
243 244 245
}


246 247 248 249 250
static int
udevGetUintSysfsAttr(struct udev_device *udev_device,
                     const char *attr_name,
                     unsigned int *value,
                     int base)
251
{
252
    const char *str = NULL;
253

254
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
255

256
    if (str && virStrToLong_ui(str, NULL, base, value) < 0) {
257 258
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to unsigned int"), str);
259
        return -1;
260 261
    }

262
    return 0;
263 264 265
}


266 267 268 269
static int
udevGetUint64SysfsAttr(struct udev_device *udev_device,
                       const char *attr_name,
                       unsigned long long *value)
270
{
271
    const char *str = NULL;
272

273
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
274

275
    if (str && virStrToLong_ull(str, NULL, 0, value) < 0) {
276 277
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to unsigned long long"), str);
J
Ján Tomko 已提交
278
        return -1;
279 280
    }

J
Ján Tomko 已提交
281
    return 0;
282 283 284
}


285 286 287 288
static int
udevGenerateDeviceName(struct udev_device *device,
                       virNodeDeviceDefPtr def,
                       const char *s)
289
{
290
    size_t i;
291 292
    virBuffer buf = VIR_BUFFER_INITIALIZER;

293
    virBufferAsprintf(&buf, "%s_%s",
294 295 296
                      udev_device_get_subsystem(device),
                      udev_device_get_sysname(device));

297
    if (s != NULL)
298
        virBufferAsprintf(&buf, "_%s", s);
299

300 301
    if (virBufferCheckError(&buf) < 0)
        return -1;
302 303 304

    def->name = virBufferContentAndReset(&buf);

305
    for (i = 0; i < strlen(def->name); i++) {
306
        if (!(c_isalnum(*(def->name + i))))
307 308 309
            *(def->name + i) = '_';
    }

310
    return 0;
311 312
}

313

314
#if HAVE_UDEV_LOGGING
315 316 317 318 319 320 321 322
typedef void
(*udevLogFunctionPtr)(struct udev *udev,
                      int priority,
                      const char *file,
                      int line,
                      const char *fn,
                      const char *format,
                      va_list args);
J
Ján Tomko 已提交
323 324

static void
325
ATTRIBUTE_FMT_PRINTF(6, 0)
J
Ján Tomko 已提交
326 327 328 329 330 331 332
udevLogFunction(struct udev *udev ATTRIBUTE_UNUSED,
                int priority,
                const char *file,
                int line,
                const char *fn,
                const char *fmt,
                va_list args)
333
{
J
Ján Tomko 已提交
334
    virBuffer buf = VIR_BUFFER_INITIALIZER;
335
    char *format = NULL;
J
Ján Tomko 已提交
336 337 338 339 340 341

    virBufferAdd(&buf, fmt, -1);
    virBufferTrim(&buf, "\n", -1);

    format = virBufferContentAndReset(&buf);

342
    virLogVMessage(&virLogSelf,
J
Ján Tomko 已提交
343 344 345 346
                   virLogPriorityFromSyslog(priority),
                   file, line, fn, NULL, format ? format : fmt, args);

    VIR_FREE(format);
347
}
348
#endif
349 350


351 352 353 354 355
static int
udevTranslatePCIIds(unsigned int vendor,
                    unsigned int product,
                    char **vendor_string,
                    char **product_string)
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
{
    struct pci_id_match m;
    const char *vendor_name = NULL, *device_name = NULL;

    m.vendor_id = vendor;
    m.device_id = product;
    m.subvendor_id = PCI_MATCH_ANY;
    m.subdevice_id = PCI_MATCH_ANY;
    m.device_class = 0;
    m.device_class_mask = 0;
    m.match_data = 0;

    /* pci_get_strings returns void */
    pci_get_strings(&m,
                    &device_name,
371
                    &vendor_name,
372 373 374
                    NULL,
                    NULL);

375
    if (VIR_STRDUP(*vendor_string, vendor_name) < 0 ||
376
        VIR_STRDUP(*product_string, device_name) < 0)
377
        return -1;
378

379
    return 0;
380 381 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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 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 491 492 493 494 495
static int
udevFillMdevType(struct udev_device *device,
                 const char *dir,
                 virNodeDevCapMdevTypePtr type)
{
    int ret = -1;
    char *attrpath = NULL;

#define MDEV_GET_SYSFS_ATTR(attr_name, cb, ...)                             \
    do {                                                                    \
        if (virAsprintf(&attrpath, "%s/%s", dir, #attr_name) < 0)           \
            goto cleanup;                                                   \
                                                                            \
        if (cb(device, attrpath, __VA_ARGS__) < 0)                          \
            goto cleanup;                                                   \
                                                                            \
        VIR_FREE(attrpath);                                                 \
    } while (0)                                                             \

    if (VIR_STRDUP(type->id, last_component(dir)) < 0)
        goto cleanup;

    /* query udev for the attributes under subdirectories using the relative
     * path stored in @dir, i.e. 'mdev_supported_types/<type_id>'
     */
    MDEV_GET_SYSFS_ATTR(name, udevGetStringSysfsAttr, &type->name);
    MDEV_GET_SYSFS_ATTR(device_api, udevGetStringSysfsAttr, &type->device_api);
    MDEV_GET_SYSFS_ATTR(available_instances, udevGetUintSysfsAttr,
                        &type->available_instances, 10);

#undef MDEV_GET_SYSFS_ATTR

    ret = 0;
 cleanup:
    VIR_FREE(attrpath);
    return ret;
}


static int
udevPCIGetMdevTypesCap(struct udev_device *device,
                       virNodeDevCapPCIDevPtr pcidata)
{
    int ret = -1;
    int dirret = -1;
    DIR *dir = NULL;
    struct dirent *entry;
    char *path = NULL;
    char *tmppath = NULL;
    virNodeDevCapMdevTypePtr type = NULL;
    virNodeDevCapMdevTypePtr *types = NULL;
    size_t ntypes = 0;
    size_t i;

    if (virAsprintf(&path, "%s/mdev_supported_types",
                    udev_device_get_syspath(device)) < 0)
        return -1;

    if ((dirret = virDirOpenIfExists(&dir, path)) < 0)
        goto cleanup;

    if (dirret == 0) {
        ret = 0;
        goto cleanup;
    }

    if (VIR_ALLOC(types) < 0)
        goto cleanup;

    /* UDEV doesn't report attributes under subdirectories by default but is
     * able to query them if the path to the attribute is relative to the
     * device's base path, e.g. /sys/devices/../0000:00:01.0/ is the device's
     * base path as udev reports it, but we're interested in attributes under
     * /sys/devices/../0000:00:01.0/mdev_supported_types/<type>/. So, we need to
     * scan the subdirectories ourselves.
     */
    while ((dirret = virDirRead(dir, &entry, path)) > 0) {
        if (VIR_ALLOC(type) < 0)
            goto cleanup;

        /* construct the relative mdev type path bit for udev */
        if (virAsprintf(&tmppath, "mdev_supported_types/%s", entry->d_name) < 0)
            goto cleanup;

        if (udevFillMdevType(device, tmppath, type) < 0)
            goto cleanup;

        if (VIR_APPEND_ELEMENT(types, ntypes, type) < 0)
            goto cleanup;

        VIR_FREE(tmppath);
    }

    if (dirret < 0)
        goto cleanup;

    VIR_STEAL_PTR(pcidata->mdev_types, types);
    pcidata->nmdev_types = ntypes;
    pcidata->flags |= VIR_NODE_DEV_CAP_FLAG_PCI_MDEV;
    ntypes = 0;
    ret = 0;
 cleanup:
    virNodeDevCapMdevTypeFree(type);
    for (i = 0; i < ntypes; i++)
        virNodeDevCapMdevTypeFree(types[i]);
    VIR_FREE(types);
    VIR_FREE(path);
    VIR_FREE(tmppath);
    VIR_DIR_CLOSE(dir);
    return ret;
}


496 497 498
static int
udevProcessPCI(struct udev_device *device,
               virNodeDeviceDefPtr def)
499
{
500
    virNodeDevCapPCIDevPtr pci_dev = &def->caps->data.pci_dev;
501 502
    virPCIEDeviceInfoPtr pci_express = NULL;
    virPCIDevicePtr pciDev = NULL;
503
    int ret = -1;
504
    char *p;
505 506 507 508 509
    bool privileged;

    nodeDeviceLock();
    privileged = driver->privileged;
    nodeDeviceUnlock();
510

511
    if (udevGetUintProperty(device, "PCI_CLASS", &pci_dev->class, 16) < 0)
512
        goto cleanup;
513

514
    if ((p = strrchr(def->sysfs_path, '/')) == NULL ||
515 516 517 518
        virStrToLong_ui(p + 1, &p, 16, &pci_dev->domain) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 16, &pci_dev->bus) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 16, &pci_dev->slot) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 16, &pci_dev->function) < 0) {
519 520
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the PCI address from sysfs path: '%s'"),
521
                       def->sysfs_path);
522
        goto cleanup;
523 524
    }

525
    if (udevGetUintSysfsAttr(device, "vendor", &pci_dev->vendor, 16) < 0)
526
        goto cleanup;
527

528
    if (udevGetUintSysfsAttr(device, "device", &pci_dev->product, 16) < 0)
529
        goto cleanup;
530

531 532 533 534
    if (udevTranslatePCIIds(pci_dev->vendor,
                            pci_dev->product,
                            &pci_dev->vendor_name,
                            &pci_dev->product_name) != 0) {
535
        goto cleanup;
536
    }
537

538
    if (udevGenerateDeviceName(device, def, NULL) != 0)
539
        goto cleanup;
540

541 542
    /* The default value is -1, because it can't be 0
     * as zero is valid node number. */
543
    pci_dev->numa_node = -1;
544
    if (udevGetIntSysfsAttr(device, "numa_node",
545
                            &pci_dev->numa_node, 10) < 0)
546
        goto cleanup;
547

548
    if (nodeDeviceSysfsGetPCIRelatedDevCaps(def->sysfs_path, pci_dev) < 0)
549
        goto cleanup;
550

551 552 553 554
    if (!(pciDev = virPCIDeviceNew(pci_dev->domain,
                                   pci_dev->bus,
                                   pci_dev->slot,
                                   pci_dev->function)))
555
        goto cleanup;
556

557
    /* We need to be root to read PCI device configs */
558
    if (privileged) {
559
        if (virPCIGetHeaderType(pciDev, &pci_dev->hdrType) < 0)
560
            goto cleanup;
561

562 563
        if (virPCIDeviceIsPCIExpress(pciDev) > 0) {
            if (VIR_ALLOC(pci_express) < 0)
564
                goto cleanup;
565

566 567 568
            if (virPCIDeviceHasPCIExpressLink(pciDev) > 0) {
                if (VIR_ALLOC(pci_express->link_cap) < 0 ||
                    VIR_ALLOC(pci_express->link_sta) < 0)
569
                    goto cleanup;
570 571 572 573 574 575 576

                if (virPCIDeviceGetLinkCapSta(pciDev,
                                              &pci_express->link_cap->port,
                                              &pci_express->link_cap->speed,
                                              &pci_express->link_cap->width,
                                              &pci_express->link_sta->speed,
                                              &pci_express->link_sta->width) < 0)
577
                    goto cleanup;
578 579 580

                pci_express->link_sta->port = -1; /* PCIe can't negotiate port. Yet :) */
            }
581 582
            pci_dev->flags |= VIR_NODE_DEV_CAP_FLAG_PCIE;
            pci_dev->pci_express = pci_express;
583
            pci_express = NULL;
584 585 586
        }
    }

587 588 589 590 591 592
    /* check whether the device is mediated devices framework capable, if so,
     * process it
     */
    if (udevPCIGetMdevTypesCap(device, pci_dev) < 0)
        goto cleanup;

593 594
    ret = 0;

595
 cleanup:
596
    virPCIDeviceFree(pciDev);
597
    virPCIEDeviceInfoFree(pci_express);
598 599 600
    return ret;
}

601 602 603

static int
drmGetMinorType(int minor)
M
Marc-André Lureau 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
{
    int type = minor >> 6;

    if (minor < 0)
        return -1;

    switch (type) {
    case VIR_NODE_DEV_DRM_PRIMARY:
    case VIR_NODE_DEV_DRM_CONTROL:
    case VIR_NODE_DEV_DRM_RENDER:
        return type;
    default:
        return -1;
    }
}

620 621 622 623

static int
udevProcessDRMDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
M
Marc-André Lureau 已提交
624
{
625
    virNodeDevCapDRMPtr drm = &def->caps->data.drm;
M
Marc-André Lureau 已提交
626 627 628 629 630 631 632 633 634 635 636
    int minor;

    if (udevGenerateDeviceName(device, def, NULL) != 0)
        return -1;

    if (udevGetIntProperty(device, "MINOR", &minor, 10) < 0)
        return -1;

    if ((minor = drmGetMinorType(minor)) == -1)
        return -1;

637
    drm->type = minor;
M
Marc-André Lureau 已提交
638 639 640

    return 0;
}
641

642 643 644 645

static int
udevProcessUSBDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
646
{
647
    virNodeDevCapUSBDevPtr usb_dev = &def->caps->data.usb_dev;
648

649
    if (udevGetUintProperty(device, "BUSNUM", &usb_dev->bus, 10) < 0)
650
        return -1;
651
    if (udevGetUintProperty(device, "DEVNUM", &usb_dev->device, 10) < 0)
652
        return -1;
653
    if (udevGetUintProperty(device, "ID_VENDOR_ID", &usb_dev->vendor, 16) < 0)
654
        return -1;
655

656 657
    if (udevGetStringProperty(device,
                              "ID_VENDOR_FROM_DATABASE",
658
                              &usb_dev->vendor_name) < 0)
659
        return -1;
660

661
    if (!usb_dev->vendor_name &&
662
        udevGetStringSysfsAttr(device, "manufacturer",
663
                               &usb_dev->vendor_name) < 0)
664
        return -1;
665

666
    if (udevGetUintProperty(device, "ID_MODEL_ID", &usb_dev->product, 16) < 0)
667
        return -1;
668

669 670
    if (udevGetStringProperty(device,
                              "ID_MODEL_FROM_DATABASE",
671
                              &usb_dev->product_name) < 0)
672
        return -1;
673

674
    if (!usb_dev->product_name &&
675
        udevGetStringSysfsAttr(device, "product",
676
                               &usb_dev->product_name) < 0)
677
        return -1;
678

679
    if (udevGenerateDeviceName(device, def, NULL) != 0)
680
        return -1;
681

682
    return 0;
683 684 685
}


686 687 688
static int
udevProcessUSBInterface(struct udev_device *device,
                        virNodeDeviceDefPtr def)
689
{
690
    virNodeDevCapUSBIfPtr usb_if = &def->caps->data.usb_if;
691

692
    if (udevGetUintSysfsAttr(device, "bInterfaceNumber",
693
                             &usb_if->number, 16) < 0)
694
        return -1;
695

696
    if (udevGetUintSysfsAttr(device, "bInterfaceClass",
697
                             &usb_if->_class, 16) < 0)
698
        return -1;
699

700
    if (udevGetUintSysfsAttr(device, "bInterfaceSubClass",
701
                             &usb_if->subclass, 16) < 0)
702
        return -1;
703

704
    if (udevGetUintSysfsAttr(device, "bInterfaceProtocol",
705
                             &usb_if->protocol, 16) < 0)
706
        return -1;
707

708
    if (udevGenerateDeviceName(device, def, NULL) != 0)
709
        return -1;
710

711
    return 0;
712 713 714
}


715 716 717
static int
udevProcessNetworkInterface(struct udev_device *device,
                            virNodeDeviceDefPtr def)
718
{
D
David Allan 已提交
719
    const char *devtype = udev_device_get_devtype(device);
720
    virNodeDevCapNetPtr net = &def->caps->data.net;
721

D
David Allan 已提交
722
    if (devtype && STREQ(devtype, "wlan")) {
723
        net->subtype = VIR_NODE_DEV_CAP_NET_80211;
D
David Allan 已提交
724
    } else {
725
        net->subtype = VIR_NODE_DEV_CAP_NET_80203;
D
David Allan 已提交
726 727
    }

728 729
    if (udevGetStringProperty(device,
                              "INTERFACE",
730
                              &net->ifname) < 0)
731
        return -1;
732

733
    if (udevGetStringSysfsAttr(device, "address",
734
                               &net->address) < 0)
735
        return -1;
736

737
    if (udevGetUintSysfsAttr(device, "addr_len", &net->address_len, 0) < 0)
738
        return -1;
739

740
    if (udevGenerateDeviceName(device, def, net->address) != 0)
741
        return -1;
742

743
    if (virNetDevGetLinkInfo(net->ifname, &net->lnk) < 0)
744
        return -1;
745

746
    if (virNetDevGetFeatures(net->ifname, &net->features) < 0)
747
        return -1;
748

749
    return 0;
750 751 752
}


753 754 755
static int
udevProcessSCSIHost(struct udev_device *device ATTRIBUTE_UNUSED,
                    virNodeDeviceDefPtr def)
756
{
757
    virNodeDevCapSCSIHostPtr scsi_host = &def->caps->data.scsi_host;
758
    char *filename = NULL;
J
Ján Tomko 已提交
759
    char *str;
760

761
    filename = last_component(def->sysfs_path);
762

763
    if (!(str = STRSKIP(filename, "host")) ||
764
        virStrToLong_ui(str, NULL, 0, &scsi_host->host) < 0) {
765 766 767
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse SCSI host '%s'"),
                       filename);
768
        return -1;
769 770
    }

771
    nodeDeviceSysfsGetSCSIHostCaps(&def->caps->data.scsi_host);
772

773
    if (udevGenerateDeviceName(device, def, NULL) != 0)
774
        return -1;
775

776
    return 0;
777 778 779
}


780 781 782
static int
udevProcessSCSITarget(struct udev_device *device,
                      virNodeDeviceDefPtr def)
D
David Allan 已提交
783 784
{
    const char *sysname = NULL;
785
    virNodeDevCapSCSITargetPtr scsi_target = &def->caps->data.scsi_target;
D
David Allan 已提交
786 787 788

    sysname = udev_device_get_sysname(device);

789
    if (VIR_STRDUP(scsi_target->name, sysname) < 0)
790
        return -1;
D
David Allan 已提交
791

792 793
    nodeDeviceSysfsGetSCSITargetCaps(def->sysfs_path, &def->caps->data.scsi_target);

794
    if (udevGenerateDeviceName(device, def, NULL) != 0)
795
        return -1;
D
David Allan 已提交
796

797
    return 0;
D
David Allan 已提交
798 799 800
}


801 802 803 804
static int
udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED,
                unsigned int type,
                char **typestring)
805 806 807 808 809 810 811 812
{
    int ret = 0;
    int foundtype = 1;

    *typestring = NULL;

    switch (type) {
    case TYPE_DISK:
813
        ignore_value(VIR_STRDUP(*typestring, "disk"));
814 815
        break;
    case TYPE_TAPE:
816
        ignore_value(VIR_STRDUP(*typestring, "tape"));
817 818
        break;
    case TYPE_PROCESSOR:
819
        ignore_value(VIR_STRDUP(*typestring, "processor"));
820 821
        break;
    case TYPE_WORM:
822
        ignore_value(VIR_STRDUP(*typestring, "worm"));
823 824
        break;
    case TYPE_ROM:
825
        ignore_value(VIR_STRDUP(*typestring, "cdrom"));
826 827
        break;
    case TYPE_SCANNER:
828
        ignore_value(VIR_STRDUP(*typestring, "scanner"));
829 830
        break;
    case TYPE_MOD:
831
        ignore_value(VIR_STRDUP(*typestring, "mod"));
832 833
        break;
    case TYPE_MEDIUM_CHANGER:
834
        ignore_value(VIR_STRDUP(*typestring, "changer"));
835 836
        break;
    case TYPE_ENCLOSURE:
837
        ignore_value(VIR_STRDUP(*typestring, "enclosure"));
838
        break;
839
    case TYPE_RAID:
840
        ignore_value(VIR_STRDUP(*typestring, "raid"));
841
        break;
842 843 844 845 846 847 848 849 850 851
    case TYPE_NO_LUN:
    default:
        foundtype = 0;
        break;
    }

    if (*typestring == NULL) {
        if (foundtype == 1) {
            ret = -1;
        } else {
852 853
            VIR_DEBUG("Failed to find SCSI device type %d for %s",
                      type, def->sysfs_path);
854 855 856 857 858 859 860
        }
    }

    return ret;
}


861 862 863
static int
udevProcessSCSIDevice(struct udev_device *device ATTRIBUTE_UNUSED,
                      virNodeDeviceDefPtr def)
864 865 866
{
    int ret = -1;
    unsigned int tmp = 0;
867
    virNodeDevCapSCSIPtr scsi = &def->caps->data.scsi;
868 869
    char *filename = NULL, *p = NULL;

870
    filename = last_component(def->sysfs_path);
871

872 873 874 875
    if (virStrToLong_ui(filename, &p, 10, &scsi->host) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 10, &scsi->bus) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 10, &scsi->target) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 10, &scsi->lun) < 0) {
876 877 878 879
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the SCSI address from filename: '%s'"),
                       filename);
        return -1;
880 881
    }

882 883
    if (udev_device_get_sysattr_value(device, "type")) {
        if (udevGetUintSysfsAttr(device, "type", &tmp, 0) < 0)
884
            goto cleanup;
885

886
        if (udevGetSCSIType(def, tmp, &scsi->type) < 0)
887
            goto cleanup;
888 889
    }

890
    if (udevGenerateDeviceName(device, def, NULL) != 0)
891
        goto cleanup;
892 893 894

    ret = 0;

895
 cleanup:
896
    if (ret != 0) {
897 898 899
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to process SCSI device with sysfs path '%s'"),
                       def->sysfs_path);
900 901 902 903 904
    }
    return ret;
}


905 906 907
static int
udevProcessDisk(struct udev_device *device,
                virNodeDeviceDefPtr def)
908
{
909
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
910

911
    if (udevGetUint64SysfsAttr(device, "size", &storage->num_blocks) < 0)
912
        return -1;
913

J
Ján Tomko 已提交
914
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
915
                               &storage->logical_block_size) < 0)
916
        return -1;
917

918
    storage->size = storage->num_blocks * storage->logical_block_size;
919

920
    return 0;
921 922 923
}


924 925 926 927
static int
udevProcessRemoveableMedia(struct udev_device *device,
                           virNodeDeviceDefPtr def,
                           int has_media)
928
{
929
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
J
Ján Tomko 已提交
930
    int is_removable = 0;
931

932 933 934
    if (udevGetIntSysfsAttr(device, "removable", &is_removable, 0) < 0)
        return -1;
    if (is_removable == 1)
935 936
        def->caps->data.storage.flags |= VIR_NODE_DEV_CAP_STORAGE_REMOVABLE;

J
Ján Tomko 已提交
937 938
    if (!has_media)
        return 0;
939

J
Ján Tomko 已提交
940 941
    def->caps->data.storage.flags |=
        VIR_NODE_DEV_CAP_STORAGE_REMOVABLE_MEDIA_AVAILABLE;
942

J
Ján Tomko 已提交
943
    if (udevGetStringProperty(device, "ID_FS_LABEL",
944
                              &storage->media_label) < 0)
J
Ján Tomko 已提交
945
        return -1;
946

J
Ján Tomko 已提交
947
    if (udevGetUint64SysfsAttr(device, "size",
948
                               &storage->num_blocks) < 0)
J
Ján Tomko 已提交
949
        return -1;
950

J
Ján Tomko 已提交
951
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
952
                               &storage->logical_block_size) < 0)
J
Ján Tomko 已提交
953
        return -1;
954

J
Ján Tomko 已提交
955 956 957 958 959 960 961
    /* XXX This calculation is wrong for the qemu virtual cdrom
     * which reports the size in 512 byte blocks, but the logical
     * block size as 2048.  I don't have a physical cdrom on a
     * devel system to see how they behave. */
    def->caps->data.storage.removable_media_size =
        def->caps->data.storage.num_blocks *
        def->caps->data.storage.logical_block_size;
962

J
Ján Tomko 已提交
963
    return 0;
964 965
}

966 967 968 969

static int
udevProcessCDROM(struct udev_device *device,
                 virNodeDeviceDefPtr def)
970 971 972 973 974 975 976 977
{
    int has_media = 0;

    /* NB: the drive_type string provided by udev is different from
     * that provided by HAL; now it's "cd" instead of "cdrom" We
     * change it to cdrom to preserve compatibility with earlier
     * versions of libvirt.  */
    VIR_FREE(def->caps->data.storage.drive_type);
978
    if (VIR_STRDUP(def->caps->data.storage.drive_type, "cdrom") < 0)
979
        return -1;
980

981 982
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA") &&
        udevGetIntProperty(device, "ID_CDROM_MEDIA", &has_media, 0) < 0)
983
        return -1;
984

985
    return udevProcessRemoveableMedia(device, def, has_media);
986 987
}

988 989 990 991

static int
udevProcessFloppy(struct udev_device *device,
                  virNodeDeviceDefPtr def)
992 993 994
{
    int has_media = 0;

995
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA")) {
996
        /* USB floppy */
997 998
        if (udevGetIntProperty(device, "DKD_MEDIA_AVAILABLE", &has_media, 0) < 0)
            return -1;
999
    } else if (udevHasDeviceProperty(device, "ID_FS_LABEL")) {
1000 1001 1002 1003 1004 1005
        /* Legacy floppy */
        has_media = 1;
    }

    return udevProcessRemoveableMedia(device, def, has_media);
}
1006

1007

1008 1009 1010
static int
udevProcessSD(struct udev_device *device,
              virNodeDeviceDefPtr def)
1011
{
1012
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
1013

J
Ján Tomko 已提交
1014
    if (udevGetUint64SysfsAttr(device, "size",
1015
                               &storage->num_blocks) < 0)
1016
        return -1;
1017

J
Ján Tomko 已提交
1018
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
1019
                               &storage->logical_block_size) < 0)
1020
        return -1;
1021

1022
    storage->size = storage->num_blocks * storage->logical_block_size;
1023

1024
    return 0;
1025 1026 1027
}


1028 1029 1030 1031
/* This function exists to deal with the case in which a driver does
 * not provide a device type in the usual place, but udev told us it's
 * a storage device, and we can make a good guess at what kind of
 * storage device it is from other information that is provided. */
1032 1033
static int
udevKludgeStorageType(virNodeDeviceDefPtr def)
1034
{
1035 1036 1037
    VIR_DEBUG("Could not find definitive storage type for device "
              "with sysfs path '%s', trying to guess it",
              def->sysfs_path);
1038

1039 1040 1041
    /* virtio disk */
    if (STRPREFIX(def->caps->data.storage.block, "/dev/vd") &&
        VIR_STRDUP(def->caps->data.storage.drive_type, "disk") > 0) {
1042
        VIR_DEBUG("Found storage type '%s' for device "
1043
                  "with sysfs path '%s'",
1044 1045
                  def->caps->data.storage.drive_type,
                  def->sysfs_path);
1046
        return 0;
1047
    }
1048 1049 1050
    VIR_DEBUG("Could not determine storage type "
              "for device with sysfs path '%s'", def->sysfs_path);
    return -1;
1051 1052 1053
}


1054 1055 1056
static int
udevProcessStorage(struct udev_device *device,
                   virNodeDeviceDefPtr def)
1057
{
1058
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
1059
    int ret = -1;
1060
    const char* devnode;
1061

1062
    devnode = udev_device_get_devnode(device);
1063
    if (!devnode) {
1064
        VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device));
1065
        goto cleanup;
1066
    }
1067

1068
    if (VIR_STRDUP(storage->block, devnode) < 0)
1069
        goto cleanup;
1070

1071
    if (udevGetStringProperty(device, "ID_BUS", &storage->bus) < 0)
1072
        goto cleanup;
1073
    if (udevGetStringProperty(device, "ID_SERIAL", &storage->serial) < 0)
1074
        goto cleanup;
1075

1076
    if (udevGetStringSysfsAttr(device, "device/vendor", &storage->vendor) < 0)
1077
        goto cleanup;
1078 1079 1080
    if (def->caps->data.storage.vendor)
        virTrimSpaces(def->caps->data.storage.vendor, NULL);

1081
    if (udevGetStringSysfsAttr(device, "device/model", &storage->model) < 0)
1082
        goto cleanup;
1083 1084
    if (def->caps->data.storage.model)
        virTrimSpaces(def->caps->data.storage.model, NULL);
1085 1086 1087 1088 1089
    /* There is no equivalent of the hotpluggable property in libudev,
     * but storage is going toward a world in which hotpluggable is
     * expected, so I don't see a problem with not having a property
     * for it. */

1090
    if (udevGetStringProperty(device, "ID_TYPE", &storage->drive_type) < 0)
1091
        goto cleanup;
1092

1093
    if (!storage->drive_type ||
1094
        STREQ(def->caps->data.storage.drive_type, "generic")) {
1095 1096
        int val = 0;
        const char *str = NULL;
1097 1098 1099

        /* All floppy drives have the ID_DRIVE_FLOPPY prop. This is
         * needed since legacy floppies don't have a drive_type */
1100
        if (udevGetIntProperty(device, "ID_DRIVE_FLOPPY", &val, 0) < 0)
1101
            goto cleanup;
1102 1103
        else if (val == 1)
            str = "floppy";
1104

1105
        if (!str) {
1106
            if (udevGetIntProperty(device, "ID_CDROM", &val, 0) < 0)
1107
                goto cleanup;
1108 1109 1110
            else if (val == 1)
                str = "cd";
        }
1111

1112
        if (!str) {
1113
            if (udevGetIntProperty(device, "ID_DRIVE_FLASH_SD", &val, 0) < 0)
1114
                goto cleanup;
1115 1116 1117
            if (val == 1)
                str = "sd";
        }
1118

1119
        if (str) {
1120
            if (VIR_STRDUP(storage->drive_type, str) < 0)
1121
                goto cleanup;
1122 1123
        } else {
            /* If udev doesn't have it, perhaps we can guess it. */
1124
            if (udevKludgeStorageType(def) != 0)
1125
                goto cleanup;
1126 1127 1128 1129 1130 1131 1132
        }
    }

    if (STREQ(def->caps->data.storage.drive_type, "cd")) {
        ret = udevProcessCDROM(device, def);
    } else if (STREQ(def->caps->data.storage.drive_type, "disk")) {
        ret = udevProcessDisk(device, def);
1133 1134
    } else if (STREQ(def->caps->data.storage.drive_type, "floppy")) {
        ret = udevProcessFloppy(device, def);
1135 1136
    } else if (STREQ(def->caps->data.storage.drive_type, "sd")) {
        ret = udevProcessSD(device, def);
1137
    } else {
1138 1139
        VIR_DEBUG("Unsupported storage type '%s'",
                  def->caps->data.storage.drive_type);
1140
        goto cleanup;
1141 1142
    }

1143
    if (udevGenerateDeviceName(device, def, storage->serial) != 0)
1144
        goto cleanup;
1145

1146
 cleanup:
1147
    VIR_DEBUG("Storage ret=%d", ret);
1148 1149 1150
    return ret;
}

1151

1152
static int
1153
udevProcessSCSIGeneric(struct udev_device *dev,
1154 1155
                       virNodeDeviceDefPtr def)
{
1156 1157
    if (udevGetStringProperty(dev, "DEVNAME", &def->caps->data.sg.path) < 0 ||
        !def->caps->data.sg.path)
1158 1159 1160 1161 1162 1163 1164 1165
        return -1;

    if (udevGenerateDeviceName(dev, def, NULL) != 0)
        return -1;

    return 0;
}

1166

1167 1168 1169 1170 1171 1172 1173 1174
static int
udevProcessMediatedDevice(struct udev_device *dev,
                          virNodeDeviceDefPtr def)
{
    int ret = -1;
    const char *uuidstr = NULL;
    int iommugrp = -1;
    char *linkpath = NULL;
1175
    char *canonicalpath = NULL;
1176 1177 1178 1179 1180
    virNodeDevCapMdevPtr data = &def->caps->data.mdev;

    if (virAsprintf(&linkpath, "%s/mdev_type", udev_device_get_syspath(dev)) < 0)
        goto cleanup;

1181 1182
    if (virFileResolveLink(linkpath, &canonicalpath) < 0) {
        virReportSystemError(errno, _("failed to resolve '%s'"), linkpath);
1183
        goto cleanup;
1184
    }
1185

1186
    if (VIR_STRDUP(data->type, last_component(canonicalpath)) < 0)
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
        goto cleanup;

    uuidstr = udev_device_get_sysname(dev);
    if ((iommugrp = virMediatedDeviceGetIOMMUGroupNum(uuidstr)) < 0)
        goto cleanup;

    if (udevGenerateDeviceName(dev, def, NULL) != 0)
        goto cleanup;

    data->iommuGroupNumber = iommugrp;

    ret = 0;
 cleanup:
    VIR_FREE(linkpath);
1201
    VIR_FREE(canonicalpath);
1202 1203 1204
    return ret;
}

B
Bjoern Walk 已提交
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

static int
udevProcessCCW(struct udev_device *device,
               virNodeDeviceDefPtr def)
{
    int online;
    char *p;
    virNodeDevCapDataPtr data = &def->caps->data;

    /* process only online devices to keep the list sane */
    if (udevGetIntSysfsAttr(device, "online", &online, 0) < 0 || online != 1)
        return -1;

    if ((p = strrchr(def->sysfs_path, '/')) == NULL ||
        virStrToLong_ui(p + 1, &p, 16, &data->ccw_dev.cssid) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 16, &data->ccw_dev.ssid) < 0 || p == NULL ||
        virStrToLong_ui(p + 1, &p, 16, &data->ccw_dev.devno) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the CCW address from sysfs path: '%s'"),
                       def->sysfs_path);
        return -1;
    }

    if (udevGenerateDeviceName(device, def, NULL) != 0)
        return -1;

    return 0;
}


1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
static int
udevGetDeviceNodes(struct udev_device *device,
                   virNodeDeviceDefPtr def)
{
    const char *devnode = NULL;
    struct udev_list_entry *list_entry = NULL;
    int n = 0;

    devnode = udev_device_get_devnode(device);

    if (VIR_STRDUP(def->devnode, devnode) < 0)
        return -1;

    udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device))
        n++;

    if (VIR_ALLOC_N(def->devlinks, n + 1) < 0)
        return -1;

    n = 0;
    udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device)) {
        if (VIR_STRDUP(def->devlinks[n++], udev_list_entry_get_name(list_entry)) < 0)
            return -1;
    }

    return 0;
}

1263

1264 1265
static int
udevGetDeviceType(struct udev_device *device,
1266
                  virNodeDevCapType *type)
1267 1268
{
    const char *devtype = NULL;
1269
    char *subsystem = NULL;
1270
    int ret = -1;
D
David Allan 已提交
1271

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    devtype = udev_device_get_devtype(device);
    *type = 0;

    if (devtype) {
        if (STREQ(devtype, "usb_device"))
            *type = VIR_NODE_DEV_CAP_USB_DEV;
        else if (STREQ(devtype, "usb_interface"))
            *type = VIR_NODE_DEV_CAP_USB_INTERFACE;
        else if (STREQ(devtype, "scsi_host"))
            *type = VIR_NODE_DEV_CAP_SCSI_HOST;
        else if (STREQ(devtype, "scsi_target"))
            *type = VIR_NODE_DEV_CAP_SCSI_TARGET;
        else if (STREQ(devtype, "scsi_device"))
            *type = VIR_NODE_DEV_CAP_SCSI;
        else if (STREQ(devtype, "disk"))
            *type = VIR_NODE_DEV_CAP_STORAGE;
        else if (STREQ(devtype, "wlan"))
            *type = VIR_NODE_DEV_CAP_NET;
M
Marc-André Lureau 已提交
1290 1291
        else if (STREQ(devtype, "drm_minor"))
            *type = VIR_NODE_DEV_CAP_DRM;
1292 1293
    } else {
        /* PCI devices don't set the DEVTYPE property. */
1294
        if (udevHasDeviceProperty(device, "PCI_CLASS"))
1295
            *type = VIR_NODE_DEV_CAP_PCI_DEV;
1296

1297 1298 1299 1300
        /* Wired network interfaces don't set the DEVTYPE property,
         * USB devices also have an INTERFACE property, but they do
         * set DEVTYPE, so if devtype is NULL and the INTERFACE
         * property exists, we have a network device. */
1301
        if (udevHasDeviceProperty(device, "INTERFACE"))
1302
            *type = VIR_NODE_DEV_CAP_NET;
1303

B
Bjoern Walk 已提交
1304 1305
        /* The following devices do not set the DEVTYPE property, therefore
         * we need to rely on the SUBSYSTEM property */
1306 1307 1308 1309
        if (udevGetStringProperty(device, "SUBSYSTEM", &subsystem) < 0)
            return -1;

        if (STREQ_NULLABLE(subsystem, "scsi_generic"))
1310
            *type = VIR_NODE_DEV_CAP_SCSI_GENERIC;
1311 1312
        else if (STREQ_NULLABLE(subsystem, "mdev"))
            *type = VIR_NODE_DEV_CAP_MDEV;
B
Bjoern Walk 已提交
1313 1314
        else if (STREQ_NULLABLE(subsystem, "ccw"))
            *type = VIR_NODE_DEV_CAP_CCW_DEV;
1315

1316
        VIR_FREE(subsystem);
1317 1318
    }

1319 1320 1321 1322 1323 1324
    if (!*type)
        VIR_DEBUG("Could not determine device type for device "
                  "with sysfs name '%s'",
                  udev_device_get_sysname(device));
    else
        ret = 0;
1325 1326 1327 1328 1329

    return ret;
}


1330 1331 1332
static int
udevGetDeviceDetails(struct udev_device *device,
                     virNodeDeviceDefPtr def)
1333
{
1334
    switch (def->caps->data.type) {
1335
    case VIR_NODE_DEV_CAP_PCI_DEV:
1336
        return udevProcessPCI(device, def);
1337
    case VIR_NODE_DEV_CAP_USB_DEV:
1338
        return udevProcessUSBDevice(device, def);
1339
    case VIR_NODE_DEV_CAP_USB_INTERFACE:
1340
        return udevProcessUSBInterface(device, def);
1341
    case VIR_NODE_DEV_CAP_NET:
1342
        return udevProcessNetworkInterface(device, def);
1343
    case VIR_NODE_DEV_CAP_SCSI_HOST:
1344
        return udevProcessSCSIHost(device, def);
D
David Allan 已提交
1345
    case VIR_NODE_DEV_CAP_SCSI_TARGET:
1346
        return udevProcessSCSITarget(device, def);
1347
    case VIR_NODE_DEV_CAP_SCSI:
1348
        return udevProcessSCSIDevice(device, def);
1349
    case VIR_NODE_DEV_CAP_STORAGE:
1350
        return udevProcessStorage(device, def);
1351
    case VIR_NODE_DEV_CAP_SCSI_GENERIC:
1352
        return udevProcessSCSIGeneric(device, def);
M
Marc-André Lureau 已提交
1353
    case VIR_NODE_DEV_CAP_DRM:
1354
        return udevProcessDRMDevice(device, def);
1355
    case VIR_NODE_DEV_CAP_MDEV:
1356
        return udevProcessMediatedDevice(device, def);
B
Bjoern Walk 已提交
1357 1358
    case VIR_NODE_DEV_CAP_CCW_DEV:
        return udevProcessCCW(device, def);
1359
    case VIR_NODE_DEV_CAP_MDEV_TYPES:
1360 1361 1362 1363
    case VIR_NODE_DEV_CAP_SYSTEM:
    case VIR_NODE_DEV_CAP_FC_HOST:
    case VIR_NODE_DEV_CAP_VPORTS:
    case VIR_NODE_DEV_CAP_LAST:
1364 1365 1366
        break;
    }

1367
    return 0;
1368 1369 1370
}


1371 1372
static int
udevRemoveOneDevice(struct udev_device *device)
1373
{
1374
    virNodeDeviceObjPtr obj = NULL;
1375
    virNodeDeviceDefPtr def;
1376
    virObjectEventPtr event = NULL;
1377 1378 1379
    const char *name = NULL;

    name = udev_device_get_syspath(device);
1380
    if (!(obj = virNodeDeviceObjListFindBySysfsPath(driver->devs, name))) {
1381 1382
        VIR_DEBUG("Failed to find device to remove that has udev name '%s'",
                  name);
1383
        return -1;
1384
    }
1385
    def = virNodeDeviceObjGetDef(obj);
1386

1387
    event = virNodeDeviceEventLifecycleNew(def->name,
1388 1389 1390 1391
                                           VIR_NODE_DEVICE_EVENT_DELETED,
                                           0);

    VIR_DEBUG("Removing device '%s' with sysfs path '%s'",
1392
              def->name, name);
1393
    virNodeDeviceObjListRemove(driver->devs, obj);
1394
    virObjectUnref(obj);
1395 1396 1397

    if (event)
        virObjectEventStateQueue(driver->nodeDeviceEventState, event);
1398
    return 0;
1399 1400 1401
}


1402 1403 1404
static int
udevSetParent(struct udev_device *device,
              virNodeDeviceDefPtr def)
1405 1406 1407
{
    struct udev_device *parent_device = NULL;
    const char *parent_sysfs_path = NULL;
1408
    virNodeDeviceObjPtr obj = NULL;
1409
    virNodeDeviceDefPtr objdef;
1410 1411
    int ret = -1;

1412 1413
    parent_device = device;
    do {
1414

1415
        parent_device = udev_device_get_parent(parent_device);
1416
        if (parent_device == NULL)
1417
            break;
1418

1419 1420
        parent_sysfs_path = udev_device_get_syspath(parent_device);
        if (parent_sysfs_path == NULL) {
1421 1422 1423
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get syspath for parent of '%s'"),
                           udev_device_get_syspath(parent_device));
1424
            goto cleanup;
1425 1426
        }

1427 1428
        if ((obj = virNodeDeviceObjListFindBySysfsPath(driver->devs,
                                                       parent_sysfs_path))) {
1429
            objdef = virNodeDeviceObjGetDef(obj);
1430
            if (VIR_STRDUP(def->parent, objdef->name) < 0) {
1431
                virNodeDeviceObjEndAPI(&obj);
1432
                goto cleanup;
1433
            }
1434
            virNodeDeviceObjEndAPI(&obj);
1435

1436
            if (VIR_STRDUP(def->parent_sysfs_path, parent_sysfs_path) < 0)
1437
                goto cleanup;
1438 1439 1440 1441
        }

    } while (def->parent == NULL && parent_device != NULL);

1442
    if (!def->parent && VIR_STRDUP(def->parent, "computer") < 0)
1443
        goto cleanup;
1444 1445 1446

    ret = 0;

1447
 cleanup:
1448 1449 1450 1451
    return ret;
}


1452 1453
static int
udevAddOneDevice(struct udev_device *device)
1454 1455
{
    virNodeDeviceDefPtr def = NULL;
1456
    virNodeDeviceObjPtr obj = NULL;
1457
    virNodeDeviceDefPtr objdef;
1458 1459
    virObjectEventPtr event = NULL;
    bool new_device = true;
1460 1461
    int ret = -1;

1462
    if (VIR_ALLOC(def) != 0)
1463
        goto cleanup;
1464

1465
    if (VIR_STRDUP(def->sysfs_path, udev_device_get_syspath(device)) < 0)
1466
        goto cleanup;
1467

1468
    if (udevGetStringProperty(device, "DRIVER", &def->driver) < 0)
1469
        goto cleanup;
1470

1471
    if (VIR_ALLOC(def->caps) != 0)
1472
        goto cleanup;
1473

1474
    if (udevGetDeviceType(device, &def->caps->data.type) != 0)
1475
        goto cleanup;
1476

1477 1478 1479
    if (udevGetDeviceNodes(device, def) != 0)
        goto cleanup;

1480
    if (udevGetDeviceDetails(device, def) != 0)
1481
        goto cleanup;
1482

1483
    if (udevSetParent(device, def) != 0)
1484
        goto cleanup;
1485

1486
    if ((obj = virNodeDeviceObjListFindByName(driver->devs, def->name))) {
1487
        virNodeDeviceObjEndAPI(&obj);
1488 1489 1490
        new_device = false;
    }

1491 1492
    /* If this is a device change, the old definition will be freed
     * and the current definition will take its place. */
1493
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1494
        goto cleanup;
1495
    objdef = virNodeDeviceObjGetDef(obj);
1496

1497
    if (new_device)
1498
        event = virNodeDeviceEventLifecycleNew(objdef->name,
1499 1500
                                               VIR_NODE_DEVICE_EVENT_CREATED,
                                               0);
1501
    else
1502
        event = virNodeDeviceEventUpdateNew(objdef->name);
1503

1504
    virNodeDeviceObjEndAPI(&obj);
1505 1506 1507

    ret = 0;

1508
 cleanup:
1509 1510 1511
    if (event)
        virObjectEventStateQueue(driver->nodeDeviceEventState, event);

1512
    if (ret != 0) {
1513
        VIR_DEBUG("Discarding device %d %p %s", ret, def,
1514
                  def ? NULLSTR(def->sysfs_path) : "");
1515 1516 1517
        virNodeDeviceDefFree(def);
    }

1518 1519 1520 1521
    return ret;
}


1522 1523 1524
static int
udevProcessDeviceListEntry(struct udev *udev,
                           struct udev_list_entry *list_entry)
1525 1526 1527 1528 1529 1530 1531 1532
{
    struct udev_device *device;
    const char *name = NULL;
    int ret = -1;

    name = udev_list_entry_get_name(list_entry);

    device = udev_device_new_from_syspath(udev, name);
1533

1534 1535
    if (device != NULL) {
        if (udevAddOneDevice(device) != 0) {
1536 1537
            VIR_DEBUG("Failed to create node device for udev device '%s'",
                      name);
1538 1539 1540 1541
        }
        ret = 0;
    }

1542 1543
    udev_device_unref(device);

1544 1545 1546 1547
    return ret;
}


1548 1549 1550 1551 1552 1553 1554 1555
/* We do not care about every device (see udevGetDeviceType).
 * Do not bother enumerating over subsystems that do not
 * contain interesting devices.
 */
const char *subsystem_blacklist[] = {
    "acpi", "tty", "vc", "i2c",
};

1556 1557
static int
udevEnumerateAddMatches(struct udev_enumerate *udev_enumerate)
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
{
    size_t i;

    for (i = 0; i < ARRAY_CARDINALITY(subsystem_blacklist); i++) {
        const char *s = subsystem_blacklist[i];
        if (udev_enumerate_add_nomatch_subsystem(udev_enumerate, s) < 0) {
            virReportSystemError(errno, "%s", _("failed to add susbsystem filter"));
            return -1;
        }
    }
    return 0;
}


1572 1573
static int
udevEnumerateDevices(struct udev *udev)
1574 1575 1576
{
    struct udev_enumerate *udev_enumerate = NULL;
    struct udev_list_entry *list_entry = NULL;
1577
    int ret = -1;
1578 1579

    udev_enumerate = udev_enumerate_new(udev);
1580 1581
    if (udevEnumerateAddMatches(udev_enumerate) < 0)
        goto cleanup;
1582 1583

    ret = udev_enumerate_scan_devices(udev_enumerate);
1584
    if (ret != 0) {
1585 1586 1587
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("udev scan devices returned %d"),
                       ret);
1588
        goto cleanup;
1589 1590 1591 1592 1593 1594 1595 1596
    }

    udev_list_entry_foreach(list_entry,
                            udev_enumerate_get_list_entry(udev_enumerate)) {

        udevProcessDeviceListEntry(udev, list_entry);
    }

1597
 cleanup:
1598 1599 1600 1601 1602
    udev_enumerate_unref(udev_enumerate);
    return ret;
}


1603 1604
static void
udevPCITranslateDeinit(void)
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
{
#if defined __s390__ || defined __s390x_
    /* Nothing was initialized, nothing needs to be cleaned up */
#else
    /* pci_system_cleanup returns void */
    pci_system_cleanup();
#endif
    return;
}


1616 1617
static int
nodeStateCleanup(void)
1618
{
J
Ján Tomko 已提交
1619 1620
    if (!driver)
        return -1;
1621

1622
    virObjectUnref(driver->privateData);
1623
    virObjectUnref(driver->nodeDeviceEventState);
1624

1625
    virNodeDeviceObjListFree(driver->devs);
J
Ján Tomko 已提交
1626 1627
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
1628

J
Ján Tomko 已提交
1629 1630
    udevPCITranslateDeinit();
    return 0;
1631 1632 1633
}


1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
static int
udevHandleOneDevice(struct udev_device *device)
{
    const char *action = udev_device_get_action(device);

    VIR_DEBUG("udev action: '%s'", action);

    if (STREQ(action, "add") || STREQ(action, "change"))
        return udevAddOneDevice(device);

    if (STREQ(action, "remove"))
        return udevRemoveOneDevice(device);

    return 0;
}


1651 1652 1653
/* the caller must be holding the udevEventData object lock prior to calling
 * this function
 */
1654
static bool
1655
udevEventMonitorSanityCheck(udevEventDataPtr priv,
1656
                            int fd)
1657
{
1658
    int rc = -1;
1659

1660
    rc = udev_monitor_get_fd(priv->udev_monitor);
1661
    if (fd != rc) {
1662 1663 1664
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("File descriptor returned by udev %d does not "
                         "match node device file descriptor %d"),
1665
                       fd, rc);
1666 1667 1668 1669 1670 1671 1672 1673

        /* this is a non-recoverable error, let's remove the handle, so that we
         * don't get in here again because of some spurious behaviour and report
         * the same error multiple times
         */
        virEventRemoveHandle(priv->watch);
        priv->watch = -1;

1674
        return false;
1675 1676
    }

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
    return true;
}


static void
udevEventHandleCallback(int watch ATTRIBUTE_UNUSED,
                        int fd,
                        int events ATTRIBUTE_UNUSED,
                        void *data ATTRIBUTE_UNUSED)
{
1687
    udevEventDataPtr priv = driver->privateData;
1688 1689
    struct udev_device *device = NULL;

1690
    virObjectLock(priv);
1691

1692 1693
    if (!udevEventMonitorSanityCheck(priv, fd)) {
        virObjectUnlock(priv);
1694
        return;
1695 1696 1697 1698
    }

    device = udev_monitor_receive_device(priv->udev_monitor);
    virObjectUnlock(priv);
1699

1700
    if (device == NULL) {
1701 1702
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("udev_monitor_receive_device returned NULL"));
1703
        return;
1704 1705
    }

1706
    udevHandleOneDevice(device);
1707
    udev_device_unref(device);
1708 1709 1710
}


1711 1712
/* DMI is intel-compatible specific */
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1713
static void
1714
udevGetDMIData(virNodeDevCapSystemPtr syscap)
1715
{
1716
    udevEventDataPtr priv = driver->privateData;
1717 1718
    struct udev *udev = NULL;
    struct udev_device *device = NULL;
1719 1720
    virNodeDevCapSystemHardwarePtr hardware = &syscap->hardware;
    virNodeDevCapSystemFirmwarePtr firmware = &syscap->firmware;
1721

1722
    udev = udev_monitor_get_udev(priv->udev_monitor);
1723

1724 1725
    device = udev_device_new_from_syspath(udev, DMI_DEVPATH);
    if (device == NULL) {
1726 1727
        device = udev_device_new_from_syspath(udev, DMI_DEVPATH_FALLBACK);
        if (device == NULL) {
1728 1729 1730
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to get udev device for syspath '%s' or '%s'"),
                           DMI_DEVPATH, DMI_DEVPATH_FALLBACK);
1731
            return;
1732
        }
1733 1734
    }

1735
    if (udevGetStringSysfsAttr(device, "product_name",
1736
                               &syscap->product_name) < 0)
1737
        goto cleanup;
1738
    if (udevGetStringSysfsAttr(device, "sys_vendor",
1739
                               &hardware->vendor_name) < 0)
1740
        goto cleanup;
1741
    if (udevGetStringSysfsAttr(device, "product_version",
1742
                               &hardware->version) < 0)
1743
        goto cleanup;
1744
    if (udevGetStringSysfsAttr(device, "product_serial",
1745
                               &hardware->serial) < 0)
1746
        goto cleanup;
1747

1748
    if (virGetHostUUID(hardware->uuid))
1749
        goto cleanup;
1750

1751
    if (udevGetStringSysfsAttr(device, "bios_vendor",
1752
                               &firmware->vendor_name) < 0)
1753
        goto cleanup;
1754
    if (udevGetStringSysfsAttr(device, "bios_version",
1755
                               &firmware->version) < 0)
1756
        goto cleanup;
1757
    if (udevGetStringSysfsAttr(device, "bios_date",
1758
                               &firmware->release_date) < 0)
1759
        goto cleanup;
1760

1761
 cleanup:
1762
    if (device != NULL)
1763 1764 1765
        udev_device_unref(device);
    return;
}
1766
#endif
1767 1768


1769 1770
static int
udevSetupSystemDev(void)
1771 1772
{
    virNodeDeviceDefPtr def = NULL;
1773
    virNodeDeviceObjPtr obj = NULL;
1774 1775
    int ret = -1;

1776 1777
    if (VIR_ALLOC(def) < 0)
        return -1;
1778

1779
    if (VIR_STRDUP(def->name, "computer") < 0)
1780
        goto cleanup;
1781

1782
    if (VIR_ALLOC(def->caps) != 0)
1783
        goto cleanup;
1784

1785
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1786
    udevGetDMIData(&def->caps->data.system);
1787
#endif
1788

1789
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1790
        goto cleanup;
1791

1792
    virNodeDeviceObjEndAPI(&obj);
1793 1794 1795

    ret = 0;

1796
 cleanup:
1797
    if (ret == -1)
1798 1799
        virNodeDeviceDefFree(def);

1800 1801 1802
    return ret;
}

1803 1804 1805

static int
udevPCITranslateInit(bool privileged ATTRIBUTE_UNUSED)
1806
{
1807 1808 1809 1810
#if defined __s390__ || defined __s390x_
    /* On s390(x) system there is no PCI bus.
     * Therefore there is nothing to initialize here. */
#else
1811
    int rc;
1812

1813
    if ((rc = pci_system_init()) != 0) {
1814 1815 1816
        /* Ignore failure as non-root; udev is not as helpful in that
         * situation, but a non-privileged user won't benefit much
         * from udev in the first place.  */
1817
        if (errno != ENOENT && (privileged  || errno != EACCES)) {
1818 1819
            virReportSystemError(rc, "%s",
                                 _("Failed to initialize libpciaccess"));
1820
            return -1;
1821
        }
1822
    }
1823
#endif
1824 1825 1826
    return 0;
}

1827 1828 1829 1830 1831

static int
nodeStateInitialize(bool privileged,
                    virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                    void *opaque ATTRIBUTE_UNUSED)
1832
{
1833
    udevEventDataPtr priv = NULL;
1834 1835
    struct udev *udev = NULL;

1836
    if (VIR_ALLOC(driver) < 0)
1837
        return -1;
1838

1839
    if (virMutexInit(&driver->lock) < 0) {
1840 1841
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to initialize mutex"));
1842
        VIR_FREE(driver);
1843
        return -1;
1844 1845
    }

1846 1847
    if (!(driver->devs = virNodeDeviceObjListNew()) ||
        !(priv = udevEventDataNew()))
1848
        goto cleanup;
1849

1850
    driver->privateData = priv;
1851
    driver->nodeDeviceEventState = virObjectEventStateNew();
1852

1853
    if (udevPCITranslateInit(privileged) < 0)
1854
        goto cleanup;
1855

1856
    udev = udev_new();
1857 1858 1859
    if (!udev) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create udev context"));
1860
        goto cleanup;
1861
    }
1862
#if HAVE_UDEV_LOGGING
J
Ján Tomko 已提交
1863 1864
    /* cast to get rid of missing-format-attribute warning */
    udev_set_log_fn(udev, (udevLogFunctionPtr) udevLogFunction);
1865
#endif
1866

1867 1868
    virObjectLock(priv);

1869
    priv->udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
1870
    if (!priv->udev_monitor) {
1871 1872
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("udev_monitor_new_from_netlink returned NULL"));
1873
        goto unlock;
1874 1875
    }

1876
    udev_monitor_enable_receiving(priv->udev_monitor);
1877

1878
#if HAVE_UDEV_MONITOR_SET_RECEIVE_BUFFER_SIZE
1879 1880 1881 1882 1883 1884
    /* mimic udevd's behaviour and override the systems rmem_max limit in case
     * there's a significant number of device 'add' events
     */
    if (geteuid() == 0)
        udev_monitor_set_receive_buffer_size(priv->udev_monitor,
                                             128 * 1024 * 1024);
1885
#endif
1886

1887 1888 1889 1890 1891 1892 1893 1894
    /* We register the monitor with the event callback so we are
     * notified by udev of device changes before we enumerate existing
     * devices because libvirt will simply recreate the device if we
     * try to register it twice, i.e., if the device appears between
     * the time we register the callback and the time we begin
     * enumeration.  The alternative is to register the callback after
     * we enumerate, in which case we will fail to create any devices
     * that appear while the enumeration is taking place.  */
1895 1896 1897
    priv->watch = virEventAddHandle(udev_monitor_get_fd(priv->udev_monitor),
                                    VIR_EVENT_HANDLE_READABLE,
                                    udevEventHandleCallback, NULL, NULL);
1898
    if (priv->watch == -1)
1899
        goto unlock;
1900 1901

    /* Create a fictional 'computer' device to root the device tree. */
1902
    if (udevSetupSystemDev() != 0)
1903
        goto unlock;
1904

1905
    virObjectUnlock(priv);
1906

1907
    /* Populate with known devices */
1908
    if (udevEnumerateDevices(udev) != 0)
1909
        goto cleanup;
1910

1911
    return 0;
1912

1913
 cleanup:
1914 1915
    nodeStateCleanup();
    return -1;
1916 1917

 unlock:
1918
    virObjectUnlock(priv);
1919
    goto cleanup;
1920 1921 1922
}


1923 1924
static int
nodeStateReload(void)
1925 1926 1927 1928 1929
{
    return 0;
}


1930
static virNodeDeviceDriver udevNodeDeviceDriver = {
1931
    .name = "udev",
1932 1933
    .nodeNumOfDevices = nodeNumOfDevices, /* 0.7.3 */
    .nodeListDevices = nodeListDevices, /* 0.7.3 */
1934
    .connectListAllNodeDevices = nodeConnectListAllNodeDevices, /* 0.10.2 */
1935 1936
    .connectNodeDeviceEventRegisterAny = nodeConnectNodeDeviceEventRegisterAny, /* 2.2.0 */
    .connectNodeDeviceEventDeregisterAny = nodeConnectNodeDeviceEventDeregisterAny, /* 2.2.0 */
1937 1938 1939 1940 1941 1942 1943 1944
    .nodeDeviceLookupByName = nodeDeviceLookupByName, /* 0.7.3 */
    .nodeDeviceLookupSCSIHostByWWN = nodeDeviceLookupSCSIHostByWWN, /* 1.0.2 */
    .nodeDeviceGetXMLDesc = nodeDeviceGetXMLDesc, /* 0.7.3 */
    .nodeDeviceGetParent = nodeDeviceGetParent, /* 0.7.3 */
    .nodeDeviceNumOfCaps = nodeDeviceNumOfCaps, /* 0.7.3 */
    .nodeDeviceListCaps = nodeDeviceListCaps, /* 0.7.3 */
    .nodeDeviceCreateXML = nodeDeviceCreateXML, /* 0.7.3 */
    .nodeDeviceDestroy = nodeDeviceDestroy, /* 0.7.3 */
1945 1946 1947
};

static virStateDriver udevStateDriver = {
M
Matthias Bolte 已提交
1948
    .name = "udev",
1949 1950 1951
    .stateInitialize = nodeStateInitialize, /* 0.7.3 */
    .stateCleanup = nodeStateCleanup, /* 0.7.3 */
    .stateReload = nodeStateReload, /* 0.7.3 */
1952 1953
};

1954 1955 1956

int
udevNodeRegister(void)
1957
{
1958
    VIR_DEBUG("Registering udev node device backend");
1959

1960
    if (virSetSharedNodeDeviceDriver(&udevNodeDeviceDriver) < 0)
1961 1962 1963 1964
        return -1;

    return virRegisterStateDriver(&udevStateDriver);
}