node_device_udev.c 53.6 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
struct _udevPrivate {
    struct udev_monitor *udev_monitor;
    int watch;
};

61

J
Ján Tomko 已提交
62 63 64 65 66 67 68 69 70 71 72
static bool
udevHasDeviceProperty(struct udev_device *dev,
                      const char *key)
{
    if (udev_device_get_property_value(dev, key))
        return true;

    return false;
}


73 74 75
static const char *
udevGetDeviceProperty(struct udev_device *udev_device,
                      const char *property_key)
76
{
77
    const char *ret = NULL;
78

79
    ret = udev_device_get_property_value(udev_device, property_key);
80

81 82
    VIR_DEBUG("Found property key '%s' value '%s' for device with sysname '%s'",
              property_key, NULLSTR(ret), udev_device_get_sysname(udev_device));
83 84 85 86 87

    return ret;
}


88 89 90 91
static int
udevGetStringProperty(struct udev_device *udev_device,
                      const char *property_key,
                      char **value)
92
{
93 94
    if (VIR_STRDUP(*value,
                   udevGetDeviceProperty(udev_device, property_key)) < 0)
95
        return -1;
96

97
    return 0;
98 99 100
}


101 102 103 104 105
static int
udevGetIntProperty(struct udev_device *udev_device,
                   const char *property_key,
                   int *value,
                   int base)
106
{
107
    const char *str = NULL;
108

109
    str = udevGetDeviceProperty(udev_device, property_key);
110

111
    if (str && virStrToLong_i(str, NULL, base, value) < 0) {
112 113
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
114
        return -1;
115
    }
116
    return 0;
117 118 119
}


120 121 122 123 124
static int
udevGetUintProperty(struct udev_device *udev_device,
                    const char *property_key,
                    unsigned int *value,
                    int base)
125
{
126
    const char *str = NULL;
127

128
    str = udevGetDeviceProperty(udev_device, property_key);
129

130
    if (str && virStrToLong_ui(str, NULL, base, value) < 0) {
131 132
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
133
        return -1;
134
    }
135
    return 0;
136 137 138
}


139 140 141
static const char *
udevGetDeviceSysfsAttr(struct udev_device *udev_device,
                       const char *attr_name)
142
{
143
    const char *ret = NULL;
144

145
    ret = udev_device_get_sysattr_value(udev_device, attr_name);
146 147

    VIR_DEBUG("Found sysfs attribute '%s' value '%s' "
148
              "for device with sysname '%s'",
149
              attr_name, NULLSTR(ret),
150 151 152 153 154
              udev_device_get_sysname(udev_device));
    return ret;
}


155 156 157 158
static int
udevGetStringSysfsAttr(struct udev_device *udev_device,
                       const char *attr_name,
                       char **value)
159
{
160
    if (VIR_STRDUP(*value, udevGetDeviceSysfsAttr(udev_device, attr_name)) < 0)
161
        return -1;
162

163
    virStringStripControlChars(*value);
164

165 166
    if (*value != NULL && (STREQ(*value, "")))
        VIR_FREE(*value);
167

168
    return 0;
169 170 171
}


172 173 174 175 176
static int
udevGetIntSysfsAttr(struct udev_device *udev_device,
                    const char *attr_name,
                    int *value,
                    int base)
177
{
178
    const char *str = NULL;
179

180
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
181

182
    if (str && virStrToLong_i(str, NULL, base, value) < 0) {
183 184
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
185
        return -1;
186 187
    }

188
    return 0;
189 190 191
}


192 193 194 195 196
static int
udevGetUintSysfsAttr(struct udev_device *udev_device,
                     const char *attr_name,
                     unsigned int *value,
                     int base)
197
{
198
    const char *str = NULL;
199

200
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
201

202
    if (str && virStrToLong_ui(str, NULL, base, value) < 0) {
203 204
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to unsigned int"), str);
205
        return -1;
206 207
    }

208
    return 0;
209 210 211
}


212 213 214 215
static int
udevGetUint64SysfsAttr(struct udev_device *udev_device,
                       const char *attr_name,
                       unsigned long long *value)
216
{
217
    const char *str = NULL;
218

219
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
220

221
    if (str && virStrToLong_ull(str, NULL, 0, value) < 0) {
222 223
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to unsigned long long"), str);
J
Ján Tomko 已提交
224
        return -1;
225 226
    }

J
Ján Tomko 已提交
227
    return 0;
228 229 230
}


231 232 233 234
static int
udevGenerateDeviceName(struct udev_device *device,
                       virNodeDeviceDefPtr def,
                       const char *s)
235
{
236
    size_t i;
237 238
    virBuffer buf = VIR_BUFFER_INITIALIZER;

239
    virBufferAsprintf(&buf, "%s_%s",
240 241 242
                      udev_device_get_subsystem(device),
                      udev_device_get_sysname(device));

243
    if (s != NULL)
244
        virBufferAsprintf(&buf, "_%s", s);
245

246 247
    if (virBufferCheckError(&buf) < 0)
        return -1;
248 249 250

    def->name = virBufferContentAndReset(&buf);

251
    for (i = 0; i < strlen(def->name); i++) {
252
        if (!(c_isalnum(*(def->name + i))))
253 254 255
            *(def->name + i) = '_';
    }

256
    return 0;
257 258
}

259

260
#if HAVE_UDEV_LOGGING
261 262 263 264 265 266 267 268
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 已提交
269 270

static void
271
ATTRIBUTE_FMT_PRINTF(6, 0)
J
Ján Tomko 已提交
272 273 274 275 276 277 278
udevLogFunction(struct udev *udev ATTRIBUTE_UNUSED,
                int priority,
                const char *file,
                int line,
                const char *fn,
                const char *fmt,
                va_list args)
279
{
J
Ján Tomko 已提交
280
    virBuffer buf = VIR_BUFFER_INITIALIZER;
281
    char *format = NULL;
J
Ján Tomko 已提交
282 283 284 285 286 287

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

    format = virBufferContentAndReset(&buf);

288
    virLogVMessage(&virLogSelf,
J
Ján Tomko 已提交
289 290 291 292
                   virLogPriorityFromSyslog(priority),
                   file, line, fn, NULL, format ? format : fmt, args);

    VIR_FREE(format);
293
}
294
#endif
295 296


297 298 299 300 301
static int
udevTranslatePCIIds(unsigned int vendor,
                    unsigned int product,
                    char **vendor_string,
                    char **product_string)
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
{
    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,
317
                    &vendor_name,
318 319 320
                    NULL,
                    NULL);

321
    if (VIR_STRDUP(*vendor_string, vendor_name) < 0 ||
322
        VIR_STRDUP(*product_string, device_name) < 0)
323
        return -1;
324

325
    return 0;
326 327 328
}


329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 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
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;
}


442 443 444
static int
udevProcessPCI(struct udev_device *device,
               virNodeDeviceDefPtr def)
445
{
446
    virNodeDevCapPCIDevPtr pci_dev = &def->caps->data.pci_dev;
447 448
    virPCIEDeviceInfoPtr pci_express = NULL;
    virPCIDevicePtr pciDev = NULL;
449
    int ret = -1;
450
    char *p;
451 452 453 454 455
    bool privileged;

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

457
    if (udevGetUintProperty(device, "PCI_CLASS", &pci_dev->class, 16) < 0)
458
        goto cleanup;
459

460
    if ((p = strrchr(def->sysfs_path, '/')) == NULL ||
461 462 463 464
        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) {
465 466
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the PCI address from sysfs path: '%s'"),
467
                       def->sysfs_path);
468
        goto cleanup;
469 470
    }

471
    if (udevGetUintSysfsAttr(device, "vendor", &pci_dev->vendor, 16) < 0)
472
        goto cleanup;
473

474
    if (udevGetUintSysfsAttr(device, "device", &pci_dev->product, 16) < 0)
475
        goto cleanup;
476

477 478 479 480
    if (udevTranslatePCIIds(pci_dev->vendor,
                            pci_dev->product,
                            &pci_dev->vendor_name,
                            &pci_dev->product_name) != 0) {
481
        goto cleanup;
482
    }
483

484
    if (udevGenerateDeviceName(device, def, NULL) != 0)
485
        goto cleanup;
486

487 488
    /* The default value is -1, because it can't be 0
     * as zero is valid node number. */
489
    pci_dev->numa_node = -1;
490
    if (udevGetIntSysfsAttr(device, "numa_node",
491
                            &pci_dev->numa_node, 10) < 0)
492
        goto cleanup;
493

494
    if (nodeDeviceSysfsGetPCIRelatedDevCaps(def->sysfs_path, pci_dev) < 0)
495
        goto cleanup;
496

497 498 499 500
    if (!(pciDev = virPCIDeviceNew(pci_dev->domain,
                                   pci_dev->bus,
                                   pci_dev->slot,
                                   pci_dev->function)))
501
        goto cleanup;
502

503
    /* We need to be root to read PCI device configs */
504
    if (privileged) {
505
        if (virPCIGetHeaderType(pciDev, &pci_dev->hdrType) < 0)
506
            goto cleanup;
507

508 509
        if (virPCIDeviceIsPCIExpress(pciDev) > 0) {
            if (VIR_ALLOC(pci_express) < 0)
510
                goto cleanup;
511

512 513 514
            if (virPCIDeviceHasPCIExpressLink(pciDev) > 0) {
                if (VIR_ALLOC(pci_express->link_cap) < 0 ||
                    VIR_ALLOC(pci_express->link_sta) < 0)
515
                    goto cleanup;
516 517 518 519 520 521 522

                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)
523
                    goto cleanup;
524 525 526

                pci_express->link_sta->port = -1; /* PCIe can't negotiate port. Yet :) */
            }
527 528
            pci_dev->flags |= VIR_NODE_DEV_CAP_FLAG_PCIE;
            pci_dev->pci_express = pci_express;
529
            pci_express = NULL;
530 531 532
        }
    }

533 534 535 536 537 538
    /* check whether the device is mediated devices framework capable, if so,
     * process it
     */
    if (udevPCIGetMdevTypesCap(device, pci_dev) < 0)
        goto cleanup;

539 540
    ret = 0;

541
 cleanup:
542
    virPCIDeviceFree(pciDev);
543
    virPCIEDeviceInfoFree(pci_express);
544 545 546
    return ret;
}

547 548 549

static int
drmGetMinorType(int minor)
M
Marc-André Lureau 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
{
    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;
    }
}

566 567 568 569

static int
udevProcessDRMDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
M
Marc-André Lureau 已提交
570
{
571
    virNodeDevCapDRMPtr drm = &def->caps->data.drm;
M
Marc-André Lureau 已提交
572 573 574 575 576 577 578 579 580 581 582
    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;

583
    drm->type = minor;
M
Marc-André Lureau 已提交
584 585 586

    return 0;
}
587

588 589 590 591

static int
udevProcessUSBDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
592
{
593
    virNodeDevCapUSBDevPtr usb_dev = &def->caps->data.usb_dev;
594

595
    if (udevGetUintProperty(device, "BUSNUM", &usb_dev->bus, 10) < 0)
596
        return -1;
597
    if (udevGetUintProperty(device, "DEVNUM", &usb_dev->device, 10) < 0)
598
        return -1;
599
    if (udevGetUintProperty(device, "ID_VENDOR_ID", &usb_dev->vendor, 16) < 0)
600
        return -1;
601

602 603
    if (udevGetStringProperty(device,
                              "ID_VENDOR_FROM_DATABASE",
604
                              &usb_dev->vendor_name) < 0)
605
        return -1;
606

607
    if (!usb_dev->vendor_name &&
608
        udevGetStringSysfsAttr(device, "manufacturer",
609
                               &usb_dev->vendor_name) < 0)
610
        return -1;
611

612
    if (udevGetUintProperty(device, "ID_MODEL_ID", &usb_dev->product, 16) < 0)
613
        return -1;
614

615 616
    if (udevGetStringProperty(device,
                              "ID_MODEL_FROM_DATABASE",
617
                              &usb_dev->product_name) < 0)
618
        return -1;
619

620
    if (!usb_dev->product_name &&
621
        udevGetStringSysfsAttr(device, "product",
622
                               &usb_dev->product_name) < 0)
623
        return -1;
624

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

628
    return 0;
629 630 631
}


632 633 634
static int
udevProcessUSBInterface(struct udev_device *device,
                        virNodeDeviceDefPtr def)
635
{
636
    virNodeDevCapUSBIfPtr usb_if = &def->caps->data.usb_if;
637

638
    if (udevGetUintSysfsAttr(device, "bInterfaceNumber",
639
                             &usb_if->number, 16) < 0)
640
        return -1;
641

642
    if (udevGetUintSysfsAttr(device, "bInterfaceClass",
643
                             &usb_if->_class, 16) < 0)
644
        return -1;
645

646
    if (udevGetUintSysfsAttr(device, "bInterfaceSubClass",
647
                             &usb_if->subclass, 16) < 0)
648
        return -1;
649

650
    if (udevGetUintSysfsAttr(device, "bInterfaceProtocol",
651
                             &usb_if->protocol, 16) < 0)
652
        return -1;
653

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

657
    return 0;
658 659 660
}


661 662 663
static int
udevProcessNetworkInterface(struct udev_device *device,
                            virNodeDeviceDefPtr def)
664
{
D
David Allan 已提交
665
    const char *devtype = udev_device_get_devtype(device);
666
    virNodeDevCapNetPtr net = &def->caps->data.net;
667

D
David Allan 已提交
668
    if (devtype && STREQ(devtype, "wlan")) {
669
        net->subtype = VIR_NODE_DEV_CAP_NET_80211;
D
David Allan 已提交
670
    } else {
671
        net->subtype = VIR_NODE_DEV_CAP_NET_80203;
D
David Allan 已提交
672 673
    }

674 675
    if (udevGetStringProperty(device,
                              "INTERFACE",
676
                              &net->ifname) < 0)
677
        return -1;
678

679
    if (udevGetStringSysfsAttr(device, "address",
680
                               &net->address) < 0)
681
        return -1;
682

683
    if (udevGetUintSysfsAttr(device, "addr_len", &net->address_len, 0) < 0)
684
        return -1;
685

686
    if (udevGenerateDeviceName(device, def, net->address) != 0)
687
        return -1;
688

689
    if (virNetDevGetLinkInfo(net->ifname, &net->lnk) < 0)
690
        return -1;
691

692
    if (virNetDevGetFeatures(net->ifname, &net->features) < 0)
693
        return -1;
694

695
    return 0;
696 697 698
}


699 700 701
static int
udevProcessSCSIHost(struct udev_device *device ATTRIBUTE_UNUSED,
                    virNodeDeviceDefPtr def)
702
{
703
    virNodeDevCapSCSIHostPtr scsi_host = &def->caps->data.scsi_host;
704
    char *filename = NULL;
J
Ján Tomko 已提交
705
    char *str;
706

707
    filename = last_component(def->sysfs_path);
708

709
    if (!(str = STRSKIP(filename, "host")) ||
710
        virStrToLong_ui(str, NULL, 0, &scsi_host->host) < 0) {
711 712 713
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse SCSI host '%s'"),
                       filename);
714
        return -1;
715 716
    }

717
    nodeDeviceSysfsGetSCSIHostCaps(&def->caps->data.scsi_host);
718

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

722
    return 0;
723 724 725
}


726 727 728
static int
udevProcessSCSITarget(struct udev_device *device,
                      virNodeDeviceDefPtr def)
D
David Allan 已提交
729 730
{
    const char *sysname = NULL;
731
    virNodeDevCapSCSITargetPtr scsi_target = &def->caps->data.scsi_target;
D
David Allan 已提交
732 733 734

    sysname = udev_device_get_sysname(device);

735
    if (VIR_STRDUP(scsi_target->name, sysname) < 0)
736
        return -1;
D
David Allan 已提交
737

738 739
    nodeDeviceSysfsGetSCSITargetCaps(def->sysfs_path, &def->caps->data.scsi_target);

740
    if (udevGenerateDeviceName(device, def, NULL) != 0)
741
        return -1;
D
David Allan 已提交
742

743
    return 0;
D
David Allan 已提交
744 745 746
}


747 748 749 750
static int
udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED,
                unsigned int type,
                char **typestring)
751 752 753 754 755 756 757 758
{
    int ret = 0;
    int foundtype = 1;

    *typestring = NULL;

    switch (type) {
    case TYPE_DISK:
759
        ignore_value(VIR_STRDUP(*typestring, "disk"));
760 761
        break;
    case TYPE_TAPE:
762
        ignore_value(VIR_STRDUP(*typestring, "tape"));
763 764
        break;
    case TYPE_PROCESSOR:
765
        ignore_value(VIR_STRDUP(*typestring, "processor"));
766 767
        break;
    case TYPE_WORM:
768
        ignore_value(VIR_STRDUP(*typestring, "worm"));
769 770
        break;
    case TYPE_ROM:
771
        ignore_value(VIR_STRDUP(*typestring, "cdrom"));
772 773
        break;
    case TYPE_SCANNER:
774
        ignore_value(VIR_STRDUP(*typestring, "scanner"));
775 776
        break;
    case TYPE_MOD:
777
        ignore_value(VIR_STRDUP(*typestring, "mod"));
778 779
        break;
    case TYPE_MEDIUM_CHANGER:
780
        ignore_value(VIR_STRDUP(*typestring, "changer"));
781 782
        break;
    case TYPE_ENCLOSURE:
783
        ignore_value(VIR_STRDUP(*typestring, "enclosure"));
784
        break;
785
    case TYPE_RAID:
786
        ignore_value(VIR_STRDUP(*typestring, "raid"));
787
        break;
788 789 790 791 792 793 794 795 796 797
    case TYPE_NO_LUN:
    default:
        foundtype = 0;
        break;
    }

    if (*typestring == NULL) {
        if (foundtype == 1) {
            ret = -1;
        } else {
798 799
            VIR_DEBUG("Failed to find SCSI device type %d for %s",
                      type, def->sysfs_path);
800 801 802 803 804 805 806
        }
    }

    return ret;
}


807 808 809
static int
udevProcessSCSIDevice(struct udev_device *device ATTRIBUTE_UNUSED,
                      virNodeDeviceDefPtr def)
810 811 812
{
    int ret = -1;
    unsigned int tmp = 0;
813
    virNodeDevCapSCSIPtr scsi = &def->caps->data.scsi;
814 815
    char *filename = NULL, *p = NULL;

816
    filename = last_component(def->sysfs_path);
817

818 819 820 821
    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) {
822 823 824 825
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the SCSI address from filename: '%s'"),
                       filename);
        return -1;
826 827
    }

828 829
    if (udev_device_get_sysattr_value(device, "type")) {
        if (udevGetUintSysfsAttr(device, "type", &tmp, 0) < 0)
830
            goto cleanup;
831

832
        if (udevGetSCSIType(def, tmp, &scsi->type) < 0)
833
            goto cleanup;
834 835
    }

836
    if (udevGenerateDeviceName(device, def, NULL) != 0)
837
        goto cleanup;
838 839 840

    ret = 0;

841
 cleanup:
842
    if (ret != 0) {
843 844 845
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to process SCSI device with sysfs path '%s'"),
                       def->sysfs_path);
846 847 848 849 850
    }
    return ret;
}


851 852 853
static int
udevProcessDisk(struct udev_device *device,
                virNodeDeviceDefPtr def)
854
{
855
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
856

857
    if (udevGetUint64SysfsAttr(device, "size", &storage->num_blocks) < 0)
858
        return -1;
859

J
Ján Tomko 已提交
860
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
861
                               &storage->logical_block_size) < 0)
862
        return -1;
863

864
    storage->size = storage->num_blocks * storage->logical_block_size;
865

866
    return 0;
867 868 869
}


870 871 872 873
static int
udevProcessRemoveableMedia(struct udev_device *device,
                           virNodeDeviceDefPtr def,
                           int has_media)
874
{
875
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
J
Ján Tomko 已提交
876
    int is_removable = 0;
877

878 879 880
    if (udevGetIntSysfsAttr(device, "removable", &is_removable, 0) < 0)
        return -1;
    if (is_removable == 1)
881 882
        def->caps->data.storage.flags |= VIR_NODE_DEV_CAP_STORAGE_REMOVABLE;

J
Ján Tomko 已提交
883 884
    if (!has_media)
        return 0;
885

J
Ján Tomko 已提交
886 887
    def->caps->data.storage.flags |=
        VIR_NODE_DEV_CAP_STORAGE_REMOVABLE_MEDIA_AVAILABLE;
888

J
Ján Tomko 已提交
889
    if (udevGetStringProperty(device, "ID_FS_LABEL",
890
                              &storage->media_label) < 0)
J
Ján Tomko 已提交
891
        return -1;
892

J
Ján Tomko 已提交
893
    if (udevGetUint64SysfsAttr(device, "size",
894
                               &storage->num_blocks) < 0)
J
Ján Tomko 已提交
895
        return -1;
896

J
Ján Tomko 已提交
897
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
898
                               &storage->logical_block_size) < 0)
J
Ján Tomko 已提交
899
        return -1;
900

J
Ján Tomko 已提交
901 902 903 904 905 906 907
    /* 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;
908

J
Ján Tomko 已提交
909
    return 0;
910 911
}

912 913 914 915

static int
udevProcessCDROM(struct udev_device *device,
                 virNodeDeviceDefPtr def)
916 917 918 919 920 921 922 923
{
    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);
924
    if (VIR_STRDUP(def->caps->data.storage.drive_type, "cdrom") < 0)
925
        return -1;
926

927 928
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA") &&
        udevGetIntProperty(device, "ID_CDROM_MEDIA", &has_media, 0) < 0)
929
        return -1;
930

931
    return udevProcessRemoveableMedia(device, def, has_media);
932 933
}

934 935 936 937

static int
udevProcessFloppy(struct udev_device *device,
                  virNodeDeviceDefPtr def)
938 939 940
{
    int has_media = 0;

941
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA")) {
942
        /* USB floppy */
943 944
        if (udevGetIntProperty(device, "DKD_MEDIA_AVAILABLE", &has_media, 0) < 0)
            return -1;
945
    } else if (udevHasDeviceProperty(device, "ID_FS_LABEL")) {
946 947 948 949 950 951
        /* Legacy floppy */
        has_media = 1;
    }

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

953

954 955 956
static int
udevProcessSD(struct udev_device *device,
              virNodeDeviceDefPtr def)
957
{
958
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
959

J
Ján Tomko 已提交
960
    if (udevGetUint64SysfsAttr(device, "size",
961
                               &storage->num_blocks) < 0)
962
        return -1;
963

J
Ján Tomko 已提交
964
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
965
                               &storage->logical_block_size) < 0)
966
        return -1;
967

968
    storage->size = storage->num_blocks * storage->logical_block_size;
969

970
    return 0;
971 972 973
}


974 975 976 977
/* 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. */
978 979
static int
udevKludgeStorageType(virNodeDeviceDefPtr def)
980
{
981 982 983
    VIR_DEBUG("Could not find definitive storage type for device "
              "with sysfs path '%s', trying to guess it",
              def->sysfs_path);
984

985 986 987
    /* virtio disk */
    if (STRPREFIX(def->caps->data.storage.block, "/dev/vd") &&
        VIR_STRDUP(def->caps->data.storage.drive_type, "disk") > 0) {
988
        VIR_DEBUG("Found storage type '%s' for device "
989
                  "with sysfs path '%s'",
990 991
                  def->caps->data.storage.drive_type,
                  def->sysfs_path);
992
        return 0;
993
    }
994 995 996
    VIR_DEBUG("Could not determine storage type "
              "for device with sysfs path '%s'", def->sysfs_path);
    return -1;
997 998 999
}


1000 1001 1002
static int
udevProcessStorage(struct udev_device *device,
                   virNodeDeviceDefPtr def)
1003
{
1004
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
1005
    int ret = -1;
1006
    const char* devnode;
1007

1008
    devnode = udev_device_get_devnode(device);
1009
    if (!devnode) {
1010
        VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device));
1011
        goto cleanup;
1012
    }
1013

1014
    if (VIR_STRDUP(storage->block, devnode) < 0)
1015
        goto cleanup;
1016

1017
    if (udevGetStringProperty(device, "ID_BUS", &storage->bus) < 0)
1018
        goto cleanup;
1019
    if (udevGetStringProperty(device, "ID_SERIAL", &storage->serial) < 0)
1020
        goto cleanup;
1021

1022
    if (udevGetStringSysfsAttr(device, "device/vendor", &storage->vendor) < 0)
1023
        goto cleanup;
1024 1025 1026
    if (def->caps->data.storage.vendor)
        virTrimSpaces(def->caps->data.storage.vendor, NULL);

1027
    if (udevGetStringSysfsAttr(device, "device/model", &storage->model) < 0)
1028
        goto cleanup;
1029 1030
    if (def->caps->data.storage.model)
        virTrimSpaces(def->caps->data.storage.model, NULL);
1031 1032 1033 1034 1035
    /* 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. */

1036
    if (udevGetStringProperty(device, "ID_TYPE", &storage->drive_type) < 0)
1037
        goto cleanup;
1038

1039
    if (!storage->drive_type ||
1040
        STREQ(def->caps->data.storage.drive_type, "generic")) {
1041 1042
        int val = 0;
        const char *str = NULL;
1043 1044 1045

        /* All floppy drives have the ID_DRIVE_FLOPPY prop. This is
         * needed since legacy floppies don't have a drive_type */
1046
        if (udevGetIntProperty(device, "ID_DRIVE_FLOPPY", &val, 0) < 0)
1047
            goto cleanup;
1048 1049
        else if (val == 1)
            str = "floppy";
1050

1051
        if (!str) {
1052
            if (udevGetIntProperty(device, "ID_CDROM", &val, 0) < 0)
1053
                goto cleanup;
1054 1055 1056
            else if (val == 1)
                str = "cd";
        }
1057

1058
        if (!str) {
1059
            if (udevGetIntProperty(device, "ID_DRIVE_FLASH_SD", &val, 0) < 0)
1060
                goto cleanup;
1061 1062 1063
            if (val == 1)
                str = "sd";
        }
1064

1065
        if (str) {
1066
            if (VIR_STRDUP(storage->drive_type, str) < 0)
1067
                goto cleanup;
1068 1069
        } else {
            /* If udev doesn't have it, perhaps we can guess it. */
1070
            if (udevKludgeStorageType(def) != 0)
1071
                goto cleanup;
1072 1073 1074 1075 1076 1077 1078
        }
    }

    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);
1079 1080
    } else if (STREQ(def->caps->data.storage.drive_type, "floppy")) {
        ret = udevProcessFloppy(device, def);
1081 1082
    } else if (STREQ(def->caps->data.storage.drive_type, "sd")) {
        ret = udevProcessSD(device, def);
1083
    } else {
1084 1085
        VIR_DEBUG("Unsupported storage type '%s'",
                  def->caps->data.storage.drive_type);
1086
        goto cleanup;
1087 1088
    }

1089
    if (udevGenerateDeviceName(device, def, storage->serial) != 0)
1090
        goto cleanup;
1091

1092
 cleanup:
1093
    VIR_DEBUG("Storage ret=%d", ret);
1094 1095 1096
    return ret;
}

1097

1098
static int
1099
udevProcessSCSIGeneric(struct udev_device *dev,
1100 1101
                       virNodeDeviceDefPtr def)
{
1102 1103
    if (udevGetStringProperty(dev, "DEVNAME", &def->caps->data.sg.path) < 0 ||
        !def->caps->data.sg.path)
1104 1105 1106 1107 1108 1109 1110 1111
        return -1;

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

    return 0;
}

1112

1113 1114 1115 1116 1117 1118 1119 1120
static int
udevProcessMediatedDevice(struct udev_device *dev,
                          virNodeDeviceDefPtr def)
{
    int ret = -1;
    const char *uuidstr = NULL;
    int iommugrp = -1;
    char *linkpath = NULL;
1121
    char *canonicalpath = NULL;
1122 1123 1124 1125 1126
    virNodeDevCapMdevPtr data = &def->caps->data.mdev;

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

1127 1128
    if (virFileResolveLink(linkpath, &canonicalpath) < 0) {
        virReportSystemError(errno, _("failed to resolve '%s'"), linkpath);
1129
        goto cleanup;
1130
    }
1131

1132
    if (VIR_STRDUP(data->type, last_component(canonicalpath)) < 0)
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
        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);
1147
    VIR_FREE(canonicalpath);
1148 1149 1150
    return ret;
}

B
Bjoern Walk 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

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;
}


1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
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;
}

1209

1210 1211
static int
udevGetDeviceType(struct udev_device *device,
1212
                  virNodeDevCapType *type)
1213 1214
{
    const char *devtype = NULL;
1215
    char *subsystem = NULL;
1216
    int ret = -1;
D
David Allan 已提交
1217

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    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 已提交
1236 1237
        else if (STREQ(devtype, "drm_minor"))
            *type = VIR_NODE_DEV_CAP_DRM;
1238 1239
    } else {
        /* PCI devices don't set the DEVTYPE property. */
1240
        if (udevHasDeviceProperty(device, "PCI_CLASS"))
1241
            *type = VIR_NODE_DEV_CAP_PCI_DEV;
1242

1243 1244 1245 1246
        /* 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. */
1247
        if (udevHasDeviceProperty(device, "INTERFACE"))
1248
            *type = VIR_NODE_DEV_CAP_NET;
1249

B
Bjoern Walk 已提交
1250 1251
        /* The following devices do not set the DEVTYPE property, therefore
         * we need to rely on the SUBSYSTEM property */
1252 1253 1254 1255
        if (udevGetStringProperty(device, "SUBSYSTEM", &subsystem) < 0)
            return -1;

        if (STREQ_NULLABLE(subsystem, "scsi_generic"))
1256
            *type = VIR_NODE_DEV_CAP_SCSI_GENERIC;
1257 1258
        else if (STREQ_NULLABLE(subsystem, "mdev"))
            *type = VIR_NODE_DEV_CAP_MDEV;
B
Bjoern Walk 已提交
1259 1260
        else if (STREQ_NULLABLE(subsystem, "ccw"))
            *type = VIR_NODE_DEV_CAP_CCW_DEV;
1261

1262
        VIR_FREE(subsystem);
1263 1264
    }

1265 1266 1267 1268 1269 1270
    if (!*type)
        VIR_DEBUG("Could not determine device type for device "
                  "with sysfs name '%s'",
                  udev_device_get_sysname(device));
    else
        ret = 0;
1271 1272 1273 1274 1275

    return ret;
}


1276 1277 1278
static int
udevGetDeviceDetails(struct udev_device *device,
                     virNodeDeviceDefPtr def)
1279
{
1280
    switch (def->caps->data.type) {
1281
    case VIR_NODE_DEV_CAP_PCI_DEV:
1282
        return udevProcessPCI(device, def);
1283
    case VIR_NODE_DEV_CAP_USB_DEV:
1284
        return udevProcessUSBDevice(device, def);
1285
    case VIR_NODE_DEV_CAP_USB_INTERFACE:
1286
        return udevProcessUSBInterface(device, def);
1287
    case VIR_NODE_DEV_CAP_NET:
1288
        return udevProcessNetworkInterface(device, def);
1289
    case VIR_NODE_DEV_CAP_SCSI_HOST:
1290
        return udevProcessSCSIHost(device, def);
D
David Allan 已提交
1291
    case VIR_NODE_DEV_CAP_SCSI_TARGET:
1292
        return udevProcessSCSITarget(device, def);
1293
    case VIR_NODE_DEV_CAP_SCSI:
1294
        return udevProcessSCSIDevice(device, def);
1295
    case VIR_NODE_DEV_CAP_STORAGE:
1296
        return udevProcessStorage(device, def);
1297
    case VIR_NODE_DEV_CAP_SCSI_GENERIC:
1298
        return udevProcessSCSIGeneric(device, def);
M
Marc-André Lureau 已提交
1299
    case VIR_NODE_DEV_CAP_DRM:
1300
        return udevProcessDRMDevice(device, def);
1301
    case VIR_NODE_DEV_CAP_MDEV:
1302
        return udevProcessMediatedDevice(device, def);
B
Bjoern Walk 已提交
1303 1304
    case VIR_NODE_DEV_CAP_CCW_DEV:
        return udevProcessCCW(device, def);
1305
    case VIR_NODE_DEV_CAP_MDEV_TYPES:
1306 1307 1308 1309
    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:
1310 1311 1312
        break;
    }

1313
    return 0;
1314 1315 1316
}


1317 1318
static int
udevRemoveOneDevice(struct udev_device *device)
1319
{
1320
    virNodeDeviceObjPtr obj = NULL;
1321
    virNodeDeviceDefPtr def;
1322
    virObjectEventPtr event = NULL;
1323 1324 1325
    const char *name = NULL;

    name = udev_device_get_syspath(device);
1326
    if (!(obj = virNodeDeviceObjListFindBySysfsPath(driver->devs, name))) {
1327 1328
        VIR_DEBUG("Failed to find device to remove that has udev name '%s'",
                  name);
1329
        return -1;
1330
    }
1331
    def = virNodeDeviceObjGetDef(obj);
1332

1333
    event = virNodeDeviceEventLifecycleNew(def->name,
1334 1335 1336 1337
                                           VIR_NODE_DEVICE_EVENT_DELETED,
                                           0);

    VIR_DEBUG("Removing device '%s' with sysfs path '%s'",
1338
              def->name, name);
1339
    virNodeDeviceObjListRemove(driver->devs, obj);
1340
    virObjectUnref(obj);
1341 1342 1343

    if (event)
        virObjectEventStateQueue(driver->nodeDeviceEventState, event);
1344
    return 0;
1345 1346 1347
}


1348 1349 1350
static int
udevSetParent(struct udev_device *device,
              virNodeDeviceDefPtr def)
1351 1352 1353
{
    struct udev_device *parent_device = NULL;
    const char *parent_sysfs_path = NULL;
1354
    virNodeDeviceObjPtr obj = NULL;
1355
    virNodeDeviceDefPtr objdef;
1356 1357
    int ret = -1;

1358 1359
    parent_device = device;
    do {
1360

1361
        parent_device = udev_device_get_parent(parent_device);
1362
        if (parent_device == NULL)
1363
            break;
1364

1365 1366
        parent_sysfs_path = udev_device_get_syspath(parent_device);
        if (parent_sysfs_path == NULL) {
1367 1368 1369
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get syspath for parent of '%s'"),
                           udev_device_get_syspath(parent_device));
1370
            goto cleanup;
1371 1372
        }

1373 1374
        if ((obj = virNodeDeviceObjListFindBySysfsPath(driver->devs,
                                                       parent_sysfs_path))) {
1375
            objdef = virNodeDeviceObjGetDef(obj);
1376
            if (VIR_STRDUP(def->parent, objdef->name) < 0) {
1377
                virNodeDeviceObjEndAPI(&obj);
1378
                goto cleanup;
1379
            }
1380
            virNodeDeviceObjEndAPI(&obj);
1381

1382
            if (VIR_STRDUP(def->parent_sysfs_path, parent_sysfs_path) < 0)
1383
                goto cleanup;
1384 1385 1386 1387
        }

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

1388
    if (!def->parent && VIR_STRDUP(def->parent, "computer") < 0)
1389
        goto cleanup;
1390 1391 1392

    ret = 0;

1393
 cleanup:
1394 1395 1396 1397
    return ret;
}


1398 1399
static int
udevAddOneDevice(struct udev_device *device)
1400 1401
{
    virNodeDeviceDefPtr def = NULL;
1402
    virNodeDeviceObjPtr obj = NULL;
1403
    virNodeDeviceDefPtr objdef;
1404 1405
    virObjectEventPtr event = NULL;
    bool new_device = true;
1406 1407
    int ret = -1;

1408
    if (VIR_ALLOC(def) != 0)
1409
        goto cleanup;
1410

1411
    if (VIR_STRDUP(def->sysfs_path, udev_device_get_syspath(device)) < 0)
1412
        goto cleanup;
1413

1414
    if (udevGetStringProperty(device, "DRIVER", &def->driver) < 0)
1415
        goto cleanup;
1416

1417
    if (VIR_ALLOC(def->caps) != 0)
1418
        goto cleanup;
1419

1420
    if (udevGetDeviceType(device, &def->caps->data.type) != 0)
1421
        goto cleanup;
1422

1423 1424 1425
    if (udevGetDeviceNodes(device, def) != 0)
        goto cleanup;

1426
    if (udevGetDeviceDetails(device, def) != 0)
1427
        goto cleanup;
1428

1429
    if (udevSetParent(device, def) != 0)
1430
        goto cleanup;
1431

1432
    if ((obj = virNodeDeviceObjListFindByName(driver->devs, def->name))) {
1433
        virNodeDeviceObjEndAPI(&obj);
1434 1435 1436
        new_device = false;
    }

1437 1438
    /* If this is a device change, the old definition will be freed
     * and the current definition will take its place. */
1439
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1440
        goto cleanup;
1441
    objdef = virNodeDeviceObjGetDef(obj);
1442

1443
    if (new_device)
1444
        event = virNodeDeviceEventLifecycleNew(objdef->name,
1445 1446
                                               VIR_NODE_DEVICE_EVENT_CREATED,
                                               0);
1447
    else
1448
        event = virNodeDeviceEventUpdateNew(objdef->name);
1449

1450
    virNodeDeviceObjEndAPI(&obj);
1451 1452 1453

    ret = 0;

1454
 cleanup:
1455 1456 1457
    if (event)
        virObjectEventStateQueue(driver->nodeDeviceEventState, event);

1458
    if (ret != 0) {
1459
        VIR_DEBUG("Discarding device %d %p %s", ret, def,
1460
                  def ? NULLSTR(def->sysfs_path) : "");
1461 1462 1463
        virNodeDeviceDefFree(def);
    }

1464 1465 1466 1467
    return ret;
}


1468 1469 1470
static int
udevProcessDeviceListEntry(struct udev *udev,
                           struct udev_list_entry *list_entry)
1471 1472 1473 1474 1475 1476 1477 1478
{
    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);
1479

1480 1481
    if (device != NULL) {
        if (udevAddOneDevice(device) != 0) {
1482 1483
            VIR_DEBUG("Failed to create node device for udev device '%s'",
                      name);
1484 1485 1486 1487
        }
        ret = 0;
    }

1488 1489
    udev_device_unref(device);

1490 1491 1492 1493
    return ret;
}


1494 1495 1496 1497 1498 1499 1500 1501
/* 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",
};

1502 1503
static int
udevEnumerateAddMatches(struct udev_enumerate *udev_enumerate)
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
{
    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;
}


1518 1519
static int
udevEnumerateDevices(struct udev *udev)
1520 1521 1522
{
    struct udev_enumerate *udev_enumerate = NULL;
    struct udev_list_entry *list_entry = NULL;
1523
    int ret = -1;
1524 1525

    udev_enumerate = udev_enumerate_new(udev);
1526 1527
    if (udevEnumerateAddMatches(udev_enumerate) < 0)
        goto cleanup;
1528 1529

    ret = udev_enumerate_scan_devices(udev_enumerate);
1530
    if (ret != 0) {
1531 1532 1533
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("udev scan devices returned %d"),
                       ret);
1534
        goto cleanup;
1535 1536 1537 1538 1539 1540 1541 1542
    }

    udev_list_entry_foreach(list_entry,
                            udev_enumerate_get_list_entry(udev_enumerate)) {

        udevProcessDeviceListEntry(udev, list_entry);
    }

1543
 cleanup:
1544 1545 1546 1547 1548
    udev_enumerate_unref(udev_enumerate);
    return ret;
}


1549 1550
static void
udevPCITranslateDeinit(void)
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
{
#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;
}


1562 1563
static int
nodeStateCleanup(void)
1564
{
1565
    udevPrivate *priv = NULL;
1566 1567 1568
    struct udev_monitor *udev_monitor = NULL;
    struct udev *udev = NULL;

J
Ján Tomko 已提交
1569 1570
    if (!driver)
        return -1;
1571

J
Ján Tomko 已提交
1572
    nodeDeviceLock();
1573

1574
    virObjectUnref(driver->nodeDeviceEventState);
1575

J
Ján Tomko 已提交
1576
    priv = driver->privateData;
1577

1578 1579 1580
    if (priv) {
        if (priv->watch != -1)
            virEventRemoveHandle(priv->watch);
1581

1582
        udev_monitor = DRV_STATE_UDEV_MONITOR(driver);
1583

1584 1585 1586 1587
        if (udev_monitor != NULL) {
            udev = udev_monitor_get_udev(udev_monitor);
            udev_monitor_unref(udev_monitor);
        }
J
Ján Tomko 已提交
1588
    }
1589

J
Ján Tomko 已提交
1590 1591
    if (udev != NULL)
        udev_unref(udev);
1592

1593
    virNodeDeviceObjListFree(driver->devs);
J
Ján Tomko 已提交
1594 1595 1596 1597
    nodeDeviceUnlock();
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
    VIR_FREE(priv);
1598

J
Ján Tomko 已提交
1599 1600
    udevPCITranslateDeinit();
    return 0;
1601 1602 1603
}


1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
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;
}


1621 1622 1623 1624 1625
static void
udevEventHandleCallback(int watch ATTRIBUTE_UNUSED,
                        int fd,
                        int events ATTRIBUTE_UNUSED,
                        void *data ATTRIBUTE_UNUSED)
1626 1627
{
    struct udev_device *device = NULL;
1628
    struct udev_monitor *udev_monitor = DRV_STATE_UDEV_MONITOR(driver);
1629 1630 1631 1632
    int udev_fd = -1;

    udev_fd = udev_monitor_get_fd(udev_monitor);
    if (fd != udev_fd) {
1633 1634
        udevPrivate *priv = driver->privateData;

1635 1636 1637 1638
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("File descriptor returned by udev %d does not "
                         "match node device file descriptor %d"),
                       fd, udev_fd);
1639 1640 1641 1642 1643 1644 1645 1646

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

1647
        goto cleanup;
1648 1649 1650 1651
    }

    device = udev_monitor_receive_device(udev_monitor);
    if (device == NULL) {
1652 1653
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("udev_monitor_receive_device returned NULL"));
1654
        goto cleanup;
1655 1656
    }

1657
    udevHandleOneDevice(device);
1658

1659
 cleanup:
1660
    udev_device_unref(device);
1661 1662 1663 1664
    return;
}


1665 1666
/* DMI is intel-compatible specific */
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1667
static void
1668
udevGetDMIData(virNodeDevCapSystemPtr syscap)
1669 1670 1671
{
    struct udev *udev = NULL;
    struct udev_device *device = NULL;
1672 1673
    virNodeDevCapSystemHardwarePtr hardware = &syscap->hardware;
    virNodeDevCapSystemFirmwarePtr firmware = &syscap->firmware;
1674

1675
    udev = udev_monitor_get_udev(DRV_STATE_UDEV_MONITOR(driver));
1676

1677 1678
    device = udev_device_new_from_syspath(udev, DMI_DEVPATH);
    if (device == NULL) {
1679 1680
        device = udev_device_new_from_syspath(udev, DMI_DEVPATH_FALLBACK);
        if (device == NULL) {
1681 1682 1683
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to get udev device for syspath '%s' or '%s'"),
                           DMI_DEVPATH, DMI_DEVPATH_FALLBACK);
1684
            return;
1685
        }
1686 1687
    }

1688
    if (udevGetStringSysfsAttr(device, "product_name",
1689
                               &syscap->product_name) < 0)
1690
        goto cleanup;
1691
    if (udevGetStringSysfsAttr(device, "sys_vendor",
1692
                               &hardware->vendor_name) < 0)
1693
        goto cleanup;
1694
    if (udevGetStringSysfsAttr(device, "product_version",
1695
                               &hardware->version) < 0)
1696
        goto cleanup;
1697
    if (udevGetStringSysfsAttr(device, "product_serial",
1698
                               &hardware->serial) < 0)
1699
        goto cleanup;
1700

1701
    if (virGetHostUUID(hardware->uuid))
1702
        goto cleanup;
1703

1704
    if (udevGetStringSysfsAttr(device, "bios_vendor",
1705
                               &firmware->vendor_name) < 0)
1706
        goto cleanup;
1707
    if (udevGetStringSysfsAttr(device, "bios_version",
1708
                               &firmware->version) < 0)
1709
        goto cleanup;
1710
    if (udevGetStringSysfsAttr(device, "bios_date",
1711
                               &firmware->release_date) < 0)
1712
        goto cleanup;
1713

1714
 cleanup:
1715
    if (device != NULL)
1716 1717 1718
        udev_device_unref(device);
    return;
}
1719
#endif
1720 1721


1722 1723
static int
udevSetupSystemDev(void)
1724 1725
{
    virNodeDeviceDefPtr def = NULL;
1726
    virNodeDeviceObjPtr obj = NULL;
1727 1728
    int ret = -1;

1729 1730
    if (VIR_ALLOC(def) < 0)
        return -1;
1731

1732
    if (VIR_STRDUP(def->name, "computer") < 0)
1733
        goto cleanup;
1734

1735
    if (VIR_ALLOC(def->caps) != 0)
1736
        goto cleanup;
1737

1738
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1739
    udevGetDMIData(&def->caps->data.system);
1740
#endif
1741

1742
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1743
        goto cleanup;
1744

1745
    virNodeDeviceObjEndAPI(&obj);
1746 1747 1748

    ret = 0;

1749
 cleanup:
1750
    if (ret == -1)
1751 1752
        virNodeDeviceDefFree(def);

1753 1754 1755
    return ret;
}

1756 1757 1758

static int
udevPCITranslateInit(bool privileged ATTRIBUTE_UNUSED)
1759
{
1760 1761 1762 1763
#if defined __s390__ || defined __s390x_
    /* On s390(x) system there is no PCI bus.
     * Therefore there is nothing to initialize here. */
#else
1764
    int rc;
1765

1766
    if ((rc = pci_system_init()) != 0) {
1767 1768 1769
        /* 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.  */
1770
        if (errno != ENOENT && (privileged  || errno != EACCES)) {
1771 1772
            virReportSystemError(rc, "%s",
                                 _("Failed to initialize libpciaccess"));
1773
            return -1;
1774
        }
1775
    }
1776
#endif
1777 1778 1779
    return 0;
}

1780 1781 1782 1783 1784

static int
nodeStateInitialize(bool privileged,
                    virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                    void *opaque ATTRIBUTE_UNUSED)
1785 1786 1787 1788
{
    udevPrivate *priv = NULL;
    struct udev *udev = NULL;

1789
    if (VIR_ALLOC(priv) < 0)
1790
        return -1;
1791 1792 1793

    priv->watch = -1;

1794
    if (VIR_ALLOC(driver) < 0) {
1795
        VIR_FREE(priv);
1796
        return -1;
1797 1798
    }

1799
    if (virMutexInit(&driver->lock) < 0) {
1800 1801
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to initialize mutex"));
1802
        VIR_FREE(priv);
1803
        VIR_FREE(driver);
1804
        return -1;
1805 1806
    }

1807
    driver->privileged = privileged;
1808
    driver->privateData = priv;
1809
    nodeDeviceLock();
1810 1811

    if (!(driver->devs = virNodeDeviceObjListNew()))
1812
        goto unlock;
1813

1814
    driver->nodeDeviceEventState = virObjectEventStateNew();
1815

1816
    if (udevPCITranslateInit(privileged) < 0)
1817
        goto unlock;
1818

1819
    udev = udev_new();
1820 1821 1822
    if (!udev) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create udev context"));
1823
        goto unlock;
1824
    }
1825
#if HAVE_UDEV_LOGGING
J
Ján Tomko 已提交
1826 1827
    /* cast to get rid of missing-format-attribute warning */
    udev_set_log_fn(udev, (udevLogFunctionPtr) udevLogFunction);
1828
#endif
1829

1830 1831
    priv->udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
    if (priv->udev_monitor == NULL) {
1832 1833
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("udev_monitor_new_from_netlink returned NULL"));
1834
        goto unlock;
1835 1836
    }

1837
    udev_monitor_enable_receiving(priv->udev_monitor);
1838

1839
#if HAVE_UDEV_MONITOR_SET_RECEIVE_BUFFER_SIZE
1840 1841 1842 1843 1844 1845
    /* 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);
1846
#endif
1847

1848 1849 1850 1851 1852 1853 1854 1855
    /* 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.  */
1856 1857 1858
    priv->watch = virEventAddHandle(udev_monitor_get_fd(priv->udev_monitor),
                                    VIR_EVENT_HANDLE_READABLE,
                                    udevEventHandleCallback, NULL, NULL);
1859
    if (priv->watch == -1)
1860
        goto unlock;
1861 1862

    /* Create a fictional 'computer' device to root the device tree. */
1863
    if (udevSetupSystemDev() != 0)
1864
        goto unlock;
1865

1866
    nodeDeviceUnlock();
1867

1868
    /* Populate with known devices */
1869
    if (udevEnumerateDevices(udev) != 0)
1870
        goto cleanup;
1871

1872
    return 0;
1873

1874
 cleanup:
1875 1876
    nodeStateCleanup();
    return -1;
1877 1878 1879 1880

 unlock:
    nodeDeviceUnlock();
    goto cleanup;
1881 1882 1883
}


1884 1885
static int
nodeStateReload(void)
1886 1887 1888 1889 1890
{
    return 0;
}


1891
static virNodeDeviceDriver udevNodeDeviceDriver = {
1892
    .name = "udev",
1893 1894
    .nodeNumOfDevices = nodeNumOfDevices, /* 0.7.3 */
    .nodeListDevices = nodeListDevices, /* 0.7.3 */
1895
    .connectListAllNodeDevices = nodeConnectListAllNodeDevices, /* 0.10.2 */
1896 1897
    .connectNodeDeviceEventRegisterAny = nodeConnectNodeDeviceEventRegisterAny, /* 2.2.0 */
    .connectNodeDeviceEventDeregisterAny = nodeConnectNodeDeviceEventDeregisterAny, /* 2.2.0 */
1898 1899 1900 1901 1902 1903 1904 1905
    .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 */
1906 1907 1908
};

static virStateDriver udevStateDriver = {
M
Matthias Bolte 已提交
1909
    .name = "udev",
1910 1911 1912
    .stateInitialize = nodeStateInitialize, /* 0.7.3 */
    .stateCleanup = nodeStateCleanup, /* 0.7.3 */
    .stateReload = nodeStateReload, /* 0.7.3 */
1913 1914
};

1915 1916 1917

int
udevNodeRegister(void)
1918
{
1919
    VIR_DEBUG("Registering udev node device backend");
1920

1921
    if (virSetSharedNodeDeviceDriver(&udevNodeDeviceDriver) < 0)
1922 1923 1924 1925
        return -1;

    return virRegisterStateDriver(&udevStateDriver);
}