node_device_udev.c 52.9 KB
Newer Older
1 2 3
/*
 * node_device_udev.c: node device enumeration - libudev implementation
 *
4
 * Copyright (C) 2009-2014 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_udev.h"
31
#include "virerror.h"
32 33 34 35
#include "node_device_conf.h"
#include "node_device_driver.h"
#include "driver.h"
#include "datatypes.h"
36
#include "virlog.h"
37
#include "viralloc.h"
38
#include "viruuid.h"
39
#include "virbuffer.h"
40
#include "virfile.h"
41
#include "virpci.h"
42
#include "virstring.h"
43
#include "virnetdev.h"
44 45 46

#define VIR_FROM_THIS VIR_FROM_NODEDEV

47 48
VIR_LOG_INIT("node_device.node_device_udev");

49 50 51 52
#ifndef TYPE_RAID
# define TYPE_RAID 12
#endif

53 54 55
struct _udevPrivate {
    struct udev_monitor *udev_monitor;
    int watch;
56
    bool privileged;
57 58
};

59
static virNodeDeviceDriverStatePtr driverState;
60 61 62 63 64 65 66 67 68 69

static int udevStrToLong_ull(char const *s,
                             char **end_ptr,
                             int base,
                             unsigned long long *result)
{
    int ret = 0;

    ret = virStrToLong_ull(s, end_ptr, base, result);
    if (ret != 0) {
70
        VIR_ERROR(_("Failed to convert '%s' to unsigned long long"), s);
71
    } else {
72
        VIR_DEBUG("Converted '%s' to unsigned long %llu", s, *result);
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    }

    return ret;
}


static int udevStrToLong_ui(char const *s,
                            char **end_ptr,
                            int base,
                            unsigned int *result)
{
    int ret = 0;

    ret = virStrToLong_ui(s, end_ptr, base, result);
    if (ret != 0) {
88
        VIR_ERROR(_("Failed to convert '%s' to unsigned int"), s);
89
    } else {
90
        VIR_DEBUG("Converted '%s' to unsigned int %u", s, *result);
91 92 93 94 95 96 97 98 99 100 101 102 103 104
    }

    return ret;
}

static int udevStrToLong_i(char const *s,
                           char **end_ptr,
                           int base,
                           int *result)
{
    int ret = 0;

    ret = virStrToLong_i(s, end_ptr, base, result);
    if (ret != 0) {
105
        VIR_ERROR(_("Failed to convert '%s' to int"), s);
106
    } else {
107
        VIR_DEBUG("Converted '%s' to int %u", s, *result);
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    }

    return ret;
}

/* This function allocates memory from the heap for the property
 * value.  That memory must be later freed by some other code. */
static int udevGetDeviceProperty(struct udev_device *udev_device,
                                 const char *property_key,
                                 char **property_value)
{
    const char *udev_value = NULL;
    int ret = PROPERTY_FOUND;

    udev_value = udev_device_get_property_value(udev_device, property_key);
    if (udev_value == NULL) {
124 125
        VIR_DEBUG("udev reports device '%s' does not have property '%s'",
                  udev_device_get_sysname(udev_device), property_key);
126 127 128 129 130 131
        ret = PROPERTY_MISSING;
        goto out;
    }

    /* If this allocation is changed, the comment at the beginning
     * of the function must also be changed. */
132
    if (VIR_STRDUP(*property_value, udev_value) < 0) {
133 134
        VIR_ERROR(_("Failed to allocate memory for property value for "
                    "property key '%s' on device with sysname '%s'"),
135 136 137 138 139 140
                  property_key, udev_device_get_sysname(udev_device));
        ret = PROPERTY_ERROR;
        goto out;
    }

    VIR_DEBUG("Found property key '%s' value '%s' "
141
              "for device with sysname '%s'",
142 143 144
              property_key, *property_value,
              udev_device_get_sysname(udev_device));

145
 out:
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    return ret;
}


static int udevGetStringProperty(struct udev_device *udev_device,
                                 const char *property_key,
                                 char **value)
{
    return udevGetDeviceProperty(udev_device, property_key, value);
}


static int udevGetIntProperty(struct udev_device *udev_device,
                              const char *property_key,
                              int *value,
                              int base)
{
    char *udev_value = NULL;
    int ret = PROPERTY_FOUND;

    ret = udevGetDeviceProperty(udev_device, property_key, &udev_value);

    if (ret == PROPERTY_FOUND) {
169
        if (udevStrToLong_i(udev_value, NULL, base, value) != 0)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
            ret = PROPERTY_ERROR;
    }

    VIR_FREE(udev_value);
    return ret;
}


static int udevGetUintProperty(struct udev_device *udev_device,
                               const char *property_key,
                               unsigned int *value,
                               int base)
{
    char *udev_value = NULL;
    int ret = PROPERTY_FOUND;

    ret = udevGetDeviceProperty(udev_device, property_key, &udev_value);

    if (ret == PROPERTY_FOUND) {
189
        if (udevStrToLong_ui(udev_value, NULL, base, value) != 0)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
            ret = PROPERTY_ERROR;
    }

    VIR_FREE(udev_value);
    return ret;
}


/* This function allocates memory from the heap for the property
 * value.  That memory must be later freed by some other code. */
static int udevGetDeviceSysfsAttr(struct udev_device *udev_device,
                                  const char *attr_name,
                                  char **attr_value)
{
    const char *udev_value = NULL;
    int ret = PROPERTY_FOUND;

    udev_value = udev_device_get_sysattr_value(udev_device, attr_name);
    if (udev_value == NULL) {
209 210
        VIR_DEBUG("udev reports device '%s' does not have sysfs attr '%s'",
                  udev_device_get_sysname(udev_device), attr_name);
211 212 213 214 215 216
        ret = PROPERTY_MISSING;
        goto out;
    }

    /* If this allocation is changed, the comment at the beginning
     * of the function must also be changed. */
217
    if (VIR_STRDUP(*attr_value, udev_value) < 0) {
218 219
        VIR_ERROR(_("Failed to allocate memory for sysfs attribute value for "
                    "sysfs attribute '%s' on device with sysname '%s'"),
220 221 222 223 224 225
                  attr_name, udev_device_get_sysname(udev_device));
        ret = PROPERTY_ERROR;
        goto out;
    }

    VIR_DEBUG("Found sysfs attribute '%s' value '%s' "
226
              "for device with sysname '%s'",
227 228 229
              attr_name, *attr_value,
              udev_device_get_sysname(udev_device));

230
 out:
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    return ret;
}


static int udevGetStringSysfsAttr(struct udev_device *udev_device,
                                  const char *attr_name,
                                  char **value)
{
    char *tmp = NULL;
    int ret = PROPERTY_MISSING;

    ret = udevGetDeviceSysfsAttr(udev_device, attr_name, &tmp);

    if (tmp != NULL && (STREQ(tmp, ""))) {
        VIR_FREE(tmp);
        tmp = NULL;
        ret = PROPERTY_MISSING;
    }

    *value = tmp;

    return ret;
}


static int udevGetIntSysfsAttr(struct udev_device *udev_device,
                               const char *attr_name,
                               int *value,
                               int base)
{
    char *udev_value = NULL;
    int ret = PROPERTY_FOUND;

    ret = udevGetDeviceSysfsAttr(udev_device, attr_name, &udev_value);

    if (ret == PROPERTY_FOUND) {
267
        if (udevStrToLong_i(udev_value, NULL, base, value) != 0)
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
            ret = PROPERTY_ERROR;
    }

    VIR_FREE(udev_value);
    return ret;
}


static int udevGetUintSysfsAttr(struct udev_device *udev_device,
                                const char *attr_name,
                                unsigned int *value,
                                int base)
{
    char *udev_value = NULL;
    int ret = PROPERTY_FOUND;

    ret = udevGetDeviceSysfsAttr(udev_device, attr_name, &udev_value);

    if (ret == PROPERTY_FOUND) {
287
        if (udevStrToLong_ui(udev_value, NULL, base, value) != 0)
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
            ret = PROPERTY_ERROR;
    }

    VIR_FREE(udev_value);
    return ret;
}


static int udevGetUint64SysfsAttr(struct udev_device *udev_device,
                                  const char *attr_name,
                                  unsigned long long *value)
{
    char *udev_value = NULL;
    int ret = PROPERTY_FOUND;

    ret = udevGetDeviceSysfsAttr(udev_device, attr_name, &udev_value);

    if (ret == PROPERTY_FOUND) {
306
        if (udevStrToLong_ull(udev_value, NULL, 0, value) != 0)
307 308 309 310 311 312 313 314 315 316 317 318
            ret = PROPERTY_ERROR;
    }

    VIR_FREE(udev_value);
    return ret;
}


static int udevGenerateDeviceName(struct udev_device *device,
                                  virNodeDeviceDefPtr def,
                                  const char *s)
{
319 320
    int ret = 0;
    size_t i;
321 322
    virBuffer buf = VIR_BUFFER_INITIALIZER;

323
    virBufferAsprintf(&buf, "%s_%s",
324 325 326
                      udev_device_get_subsystem(device),
                      udev_device_get_sysname(device));

327
    if (s != NULL)
328
        virBufferAsprintf(&buf, "_%s", s);
329

330 331
    if (virBufferCheckError(&buf) < 0)
        return -1;
332 333 334

    def->name = virBufferContentAndReset(&buf);

335
    for (i = 0; i < strlen(def->name); i++) {
336
        if (!(c_isalnum(*(def->name + i))))
337 338 339 340 341 342
            *(def->name + i) = '_';
    }

    return ret;
}

343
#if HAVE_UDEV_LOGGING
J
Ján Tomko 已提交
344 345 346 347 348 349 350 351 352
typedef void (*udevLogFunctionPtr)(struct udev *udev,
                                   int priority,
                                   const char *file,
                                   int line,
                                   const char *fn,
                                   const char *format,
                                   va_list args);

static void
353
ATTRIBUTE_FMT_PRINTF(6, 0)
J
Ján Tomko 已提交
354 355 356 357 358 359 360
udevLogFunction(struct udev *udev ATTRIBUTE_UNUSED,
                int priority,
                const char *file,
                int line,
                const char *fn,
                const char *fmt,
                va_list args)
361
{
J
Ján Tomko 已提交
362
    virBuffer buf = VIR_BUFFER_INITIALIZER;
363
    char *format = NULL;
J
Ján Tomko 已提交
364 365 366 367 368 369

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

    format = virBufferContentAndReset(&buf);

370
    virLogVMessage(&virLogSelf,
J
Ján Tomko 已提交
371 372 373 374
                   virLogPriorityFromSyslog(priority),
                   file, line, fn, NULL, format ? format : fmt, args);

    VIR_FREE(format);
375
}
376
#endif
377 378


379 380 381 382 383
static int udevTranslatePCIIds(unsigned int vendor,
                               unsigned int product,
                               char **vendor_string,
                               char **product_string)
{
384
    int ret = -1;
385 386 387 388 389 390 391 392 393 394 395 396 397 398
    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,
399
                    &vendor_name,
400 401 402
                    NULL,
                    NULL);

403 404 405
    if (VIR_STRDUP(*vendor_string, vendor_name) < 0||
        VIR_STRDUP(*product_string, device_name) < 0)
        goto out;
406 407 408

    ret = 0;

409
 out:
410 411 412 413
    return ret;
}


414 415 416
static int udevProcessPCI(struct udev_device *device,
                          virNodeDeviceDefPtr def)
{
417
    const char *syspath = NULL;
418
    union _virNodeDevCapData *data = &def->caps->data;
419
    virPCIDeviceAddress addr;
420 421
    virPCIEDeviceInfoPtr pci_express = NULL;
    virPCIDevicePtr pciDev = NULL;
422
    udevPrivate *priv = driverState->privateData;
423
    int tmpGroup, ret = -1;
424
    char *p;
425
    int rc;
426

427
    syspath = udev_device_get_syspath(device);
428 429 430 431 432 433 434 435

    if (udevGetUintProperty(device,
                            "PCI_CLASS",
                            &data->pci_dev.class,
                            16) == PROPERTY_ERROR) {
        goto out;
    }

436
    p = strrchr(syspath, '/');
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

    if ((p == NULL) || (udevStrToLong_ui(p+1,
                                         &p,
                                         16,
                                         &data->pci_dev.domain) == -1)) {
        goto out;
    }

    if ((p == NULL) || (udevStrToLong_ui(p+1,
                                         &p,
                                         16,
                                         &data->pci_dev.bus) == -1)) {
        goto out;
    }

    if ((p == NULL) || (udevStrToLong_ui(p+1,
                                         &p,
                                         16,
                                         &data->pci_dev.slot) == -1)) {
        goto out;
    }

    if ((p == NULL) || (udevStrToLong_ui(p+1,
                                         &p,
                                         16,
                                         &data->pci_dev.function) == -1)) {
        goto out;
    }

    if (udevGetUintSysfsAttr(device,
                             "vendor",
                             &data->pci_dev.vendor,
469
                             16) == PROPERTY_ERROR) {
470 471 472 473 474 475
        goto out;
    }

    if (udevGetUintSysfsAttr(device,
                             "device",
                             &data->pci_dev.product,
476
                             16) == PROPERTY_ERROR) {
477 478 479
        goto out;
    }

480 481 482 483 484 485
    if (udevTranslatePCIIds(data->pci_dev.vendor,
                            data->pci_dev.product,
                            &data->pci_dev.vendor_name,
                            &data->pci_dev.product_name) != 0) {
        goto out;
    }
486

487
    if (udevGenerateDeviceName(device, def, NULL) != 0)
488 489
        goto out;

490 491 492 493 494 495 496 497 498 499 500 501
    rc = udevGetIntSysfsAttr(device,
                            "numa_node",
                            &data->pci_dev.numa_node,
                            10);
    if (rc == PROPERTY_ERROR) {
        goto out;
    } else if (rc == PROPERTY_MISSING) {
        /* The default value is -1, because it can't be 0
         * as zero is valid node number. */
        data->pci_dev.numa_node = -1;
    }

502
    if (!virPCIGetPhysicalFunction(syspath, &data->pci_dev.physical_function))
503 504
        data->pci_dev.flags |= VIR_NODE_DEV_CAP_FLAG_PCI_PHYSICAL_FUNCTION;

505 506 507 508 509 510 511
    rc = virPCIGetVirtualFunctions(syspath,
                                   &data->pci_dev.virtual_functions,
                                   &data->pci_dev.num_virtual_functions);
    /* Out of memory */
    if (rc < 0)
        goto out;
    else if (!rc && (data->pci_dev.num_virtual_functions > 0))
512
        data->pci_dev.flags |= VIR_NODE_DEV_CAP_FLAG_PCI_VIRTUAL_FUNCTION;
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    /* iommu group */
    addr.domain = data->pci_dev.domain;
    addr.bus = data->pci_dev.bus;
    addr.slot = data->pci_dev.slot;
    addr.function = data->pci_dev.function;
    tmpGroup = virPCIDeviceAddressGetIOMMUGroupNum(&addr);
    if (tmpGroup == -1) {
        /* error was already reported */
        goto out;
        /* -2 return means there is no iommu_group data */
    } else if (tmpGroup >= 0) {
        if (virPCIDeviceAddressGetIOMMUGroupAddresses(&addr, &data->pci_dev.iommuGroupDevices,
                                                      &data->pci_dev.nIommuGroupDevices) < 0)
            goto out;
        data->pci_dev.iommuGroupNumber = tmpGroup;
    }

531 532 533 534 535 536
    if (!(pciDev = virPCIDeviceNew(data->pci_dev.domain,
                                   data->pci_dev.bus,
                                   data->pci_dev.slot,
                                   data->pci_dev.function)))
        goto out;

537 538
    /* We need to be root to read PCI device configs */
    if (priv->privileged && virPCIDeviceIsPCIExpress(pciDev) > 0) {
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
        if (VIR_ALLOC(pci_express) < 0)
            goto out;

        if (virPCIDeviceHasPCIExpressLink(pciDev) > 0) {
            if (VIR_ALLOC(pci_express->link_cap) < 0 ||
                VIR_ALLOC(pci_express->link_sta) < 0)
                goto out;

            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)
                goto out;

            pci_express->link_sta->port = -1; /* PCIe can't negotiate port. Yet :) */
        }
        data->pci_dev.flags |= VIR_NODE_DEV_CAP_FLAG_PCIE;
        data->pci_dev.pci_express = pci_express;
        pci_express = NULL;
    }

562 563
    ret = 0;

564
 out:
565
    virPCIDeviceFree(pciDev);
566
    virPCIEDeviceInfoFree(pci_express);
567 568 569 570 571 572 573 574 575
    return ret;
}


static int udevProcessUSBDevice(struct udev_device *device,
                                virNodeDeviceDefPtr def)
{
    union _virNodeDevCapData *data = &def->caps->data;
    int ret = -1;
576
    int err;
577 578 579 580

    if (udevGetUintProperty(device,
                            "BUSNUM",
                            &data->usb_dev.bus,
581
                            10) == PROPERTY_ERROR) {
582 583 584 585 586 587
        goto out;
    }

    if (udevGetUintProperty(device,
                            "DEVNUM",
                            &data->usb_dev.device,
588
                            10) == PROPERTY_ERROR) {
589 590 591 592 593 594 595 596 597 598
        goto out;
    }

    if (udevGetUintProperty(device,
                            "ID_VENDOR_ID",
                            &data->usb_dev.vendor,
                            16) == PROPERTY_ERROR) {
        goto out;
    }

599 600 601 602
    err = udevGetStringProperty(device,
                                "ID_VENDOR_FROM_DATABASE",
                                &data->usb_dev.vendor_name);
    if (err == PROPERTY_ERROR)
603
        goto out;
604 605 606 607 608 609
    if (err == PROPERTY_MISSING) {
        if (udevGetStringSysfsAttr(device,
                                  "manufacturer",
                                  &data->usb_dev.vendor_name) == PROPERTY_ERROR) {
            goto out;
        }
610 611 612 613 614
    }

    if (udevGetUintProperty(device,
                            "ID_MODEL_ID",
                            &data->usb_dev.product,
615
                            16) == PROPERTY_ERROR) {
616 617 618
        goto out;
    }

619 620 621 622
    err = udevGetStringProperty(device,
                                "ID_MODEL_FROM_DATABASE",
                                &data->usb_dev.product_name);
    if (err == PROPERTY_ERROR)
623
        goto out;
624 625 626 627 628 629
    if (err == PROPERTY_MISSING) {
        if (udevGetStringSysfsAttr(device,
                                  "product",
                                  &data->usb_dev.product_name) == PROPERTY_ERROR) {
            goto out;
        }
630 631
    }

632
    if (udevGenerateDeviceName(device, def, NULL) != 0)
633 634 635 636
        goto out;

    ret = 0;

637
 out:
638 639 640 641 642 643 644 645 646 647 648 649 650
    return ret;
}


static int udevProcessUSBInterface(struct udev_device *device,
                                   virNodeDeviceDefPtr def)
{
    int ret = -1;
    union _virNodeDevCapData *data = &def->caps->data;

    if (udevGetUintSysfsAttr(device,
                             "bInterfaceNumber",
                             &data->usb_if.number,
651
                             16) == PROPERTY_ERROR) {
652 653 654 655 656 657
        goto out;
    }

    if (udevGetUintSysfsAttr(device,
                             "bInterfaceClass",
                             &data->usb_if._class,
658
                             16) == PROPERTY_ERROR) {
659 660 661 662 663 664
        goto out;
    }

    if (udevGetUintSysfsAttr(device,
                             "bInterfaceSubClass",
                             &data->usb_if.subclass,
665
                             16) == PROPERTY_ERROR) {
666 667 668 669 670 671
        goto out;
    }

    if (udevGetUintSysfsAttr(device,
                             "bInterfaceProtocol",
                             &data->usb_if.protocol,
672
                             16) == PROPERTY_ERROR) {
673 674 675
        goto out;
    }

676
    if (udevGenerateDeviceName(device, def, NULL) != 0)
677 678 679 680
        goto out;

    ret = 0;

681
 out:
682 683 684 685 686 687 688 689
    return ret;
}


static int udevProcessNetworkInterface(struct udev_device *device,
                                       virNodeDeviceDefPtr def)
{
    int ret = -1;
D
David Allan 已提交
690
    const char *devtype = udev_device_get_devtype(device);
691 692
    union _virNodeDevCapData *data = &def->caps->data;

D
David Allan 已提交
693 694 695 696 697 698
    if (devtype && STREQ(devtype, "wlan")) {
        data->net.subtype = VIR_NODE_DEV_CAP_NET_80211;
    } else {
        data->net.subtype = VIR_NODE_DEV_CAP_NET_80203;
    }

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
    if (udevGetStringProperty(device,
                              "INTERFACE",
                              &data->net.ifname) == PROPERTY_ERROR) {
        goto out;
    }

    if (udevGetStringSysfsAttr(device,
                               "address",
                               &data->net.address) == PROPERTY_ERROR) {
        goto out;
    }

    if (udevGetUintSysfsAttr(device,
                             "addr_len",
                             &data->net.address_len,
                             0) == PROPERTY_ERROR) {
        goto out;
    }

718
    if (udevGenerateDeviceName(device, def, data->net.address) != 0)
719 720
        goto out;

721 722 723
    if (virNetDevGetLinkInfo(data->net.ifname, &data->net.lnk) < 0)
        goto out;

724 725
    ret = 0;

726
 out:
727 728 729 730 731 732 733 734 735 736 737
    return ret;
}


static int udevProcessSCSIHost(struct udev_device *device ATTRIBUTE_UNUSED,
                               virNodeDeviceDefPtr def)
{
    int ret = -1;
    union _virNodeDevCapData *data = &def->caps->data;
    char *filename = NULL;

738
    filename = last_component(def->sysfs_path);
739 740

    if (!STRPREFIX(filename, "host")) {
741 742
        VIR_ERROR(_("SCSI host found, but its udev name '%s' does "
                    "not begin with 'host'"), filename);
743 744 745 746 747 748 749 750 751 752
        goto out;
    }

    if (udevStrToLong_ui(filename + strlen("host"),
                         NULL,
                         0,
                         &data->scsi_host.host) == -1) {
        goto out;
    }

O
Osier Yang 已提交
753
    detect_scsi_host_caps(&def->caps->data);
754

755
    if (udevGenerateDeviceName(device, def, NULL) != 0)
756 757 758 759
        goto out;

    ret = 0;

760
 out:
761 762 763 764
    return ret;
}


D
David Allan 已提交
765 766 767 768 769 770 771 772 773
static int udevProcessSCSITarget(struct udev_device *device ATTRIBUTE_UNUSED,
                                 virNodeDeviceDefPtr def)
{
    int ret = -1;
    const char *sysname = NULL;
    union _virNodeDevCapData *data = &def->caps->data;

    sysname = udev_device_get_sysname(device);

774
    if (VIR_STRDUP(data->scsi_target.name, sysname) < 0)
D
David Allan 已提交
775 776
        goto out;

777
    if (udevGenerateDeviceName(device, def, NULL) != 0)
D
David Allan 已提交
778 779 780 781
        goto out;

    ret = 0;

782
 out:
D
David Allan 已提交
783 784 785 786
    return ret;
}


787
static int udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED,
788
                           unsigned int type, char **typestring)
789 790 791 792 793 794 795 796
{
    int ret = 0;
    int foundtype = 1;

    *typestring = NULL;

    switch (type) {
    case TYPE_DISK:
797
        ignore_value(VIR_STRDUP(*typestring, "disk"));
798 799
        break;
    case TYPE_TAPE:
800
        ignore_value(VIR_STRDUP(*typestring, "tape"));
801 802
        break;
    case TYPE_PROCESSOR:
803
        ignore_value(VIR_STRDUP(*typestring, "processor"));
804 805
        break;
    case TYPE_WORM:
806
        ignore_value(VIR_STRDUP(*typestring, "worm"));
807 808
        break;
    case TYPE_ROM:
809
        ignore_value(VIR_STRDUP(*typestring, "cdrom"));
810 811
        break;
    case TYPE_SCANNER:
812
        ignore_value(VIR_STRDUP(*typestring, "scanner"));
813 814
        break;
    case TYPE_MOD:
815
        ignore_value(VIR_STRDUP(*typestring, "mod"));
816 817
        break;
    case TYPE_MEDIUM_CHANGER:
818
        ignore_value(VIR_STRDUP(*typestring, "changer"));
819 820
        break;
    case TYPE_ENCLOSURE:
821
        ignore_value(VIR_STRDUP(*typestring, "enclosure"));
822
        break;
823
    case TYPE_RAID:
824
        ignore_value(VIR_STRDUP(*typestring, "raid"));
825
        break;
826 827 828 829 830 831 832 833 834 835
    case TYPE_NO_LUN:
    default:
        foundtype = 0;
        break;
    }

    if (*typestring == NULL) {
        if (foundtype == 1) {
            ret = -1;
        } else {
836 837
            VIR_DEBUG("Failed to find SCSI device type %d for %s",
                      type, def->sysfs_path);
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
        }
    }

    return ret;
}


static int udevProcessSCSIDevice(struct udev_device *device ATTRIBUTE_UNUSED,
                                 virNodeDeviceDefPtr def)
{
    int ret = -1;
    unsigned int tmp = 0;
    union _virNodeDevCapData *data = &def->caps->data;
    char *filename = NULL, *p = NULL;

853
    filename = last_component(def->sysfs_path);
854

855
    if (udevStrToLong_ui(filename, &p, 10, &data->scsi.host) == -1)
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
        goto out;

    if ((p == NULL) || (udevStrToLong_ui(p+1,
                                         &p,
                                         10,
                                         &data->scsi.bus) == -1)) {
        goto out;
    }

    if ((p == NULL) || (udevStrToLong_ui(p+1,
                                         &p,
                                         10,
                                         &data->scsi.target) == -1)) {
        goto out;
    }

    if ((p == NULL) || (udevStrToLong_ui(p+1,
                                         &p,
                                         10,
                                         &data->scsi.lun) == -1)) {
        goto out;
    }

    switch (udevGetUintSysfsAttr(device, "type", &tmp, 0)) {
    case PROPERTY_FOUND:
881
        if (udevGetSCSIType(def, tmp, &data->scsi.type) == -1)
882 883 884 885 886 887 888 889 890 891
            goto out;
        break;
    case PROPERTY_MISSING:
        break; /* No type is not an error */
    case PROPERTY_ERROR:
    default:
        goto out;
        break;
    }

892
    if (udevGenerateDeviceName(device, def, NULL) != 0)
893 894 895 896
        goto out;

    ret = 0;

897
 out:
898
    if (ret != 0) {
899
        VIR_ERROR(_("Failed to process SCSI device with sysfs path '%s'"),
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
                  def->sysfs_path);
    }
    return ret;
}


static int udevProcessDisk(struct udev_device *device,
                           virNodeDeviceDefPtr def)
{
    union _virNodeDevCapData *data = &def->caps->data;
    int ret = 0;

    if (udevGetUint64SysfsAttr(device,
                               "size",
                               &data->storage.num_blocks) == PROPERTY_ERROR) {
        goto out;
    }

    if (udevGetUint64SysfsAttr(device,
                               "queue/logical_block_size",
                               &data->storage.logical_block_size)
        == PROPERTY_ERROR) {
        goto out;
    }

    data->storage.size = data->storage.num_blocks *
        data->storage.logical_block_size;

928
 out:
929 930 931 932
    return ret;
}


933 934 935
static int udevProcessRemoveableMedia(struct udev_device *device,
                                      virNodeDeviceDefPtr def,
                                      int has_media)
936 937 938 939 940 941 942 943 944
{
    union _virNodeDevCapData *data = &def->caps->data;
    int tmp_int = 0, ret = 0;

    if ((udevGetIntSysfsAttr(device, "removable", &tmp_int, 0) == PROPERTY_FOUND) &&
        (tmp_int == 1)) {
        def->caps->data.storage.flags |= VIR_NODE_DEV_CAP_STORAGE_REMOVABLE;
    }

945
    if (has_media) {
946 947 948 949

        def->caps->data.storage.flags |=
            VIR_NODE_DEV_CAP_STORAGE_REMOVABLE_MEDIA_AVAILABLE;

950 951 952 953 954
        if (udevGetStringProperty(device, "ID_FS_LABEL",
                                  &data->storage.media_label) == PROPERTY_ERROR) {
            goto out;
        }

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
        if (udevGetUint64SysfsAttr(device,
                                   "size",
                                   &data->storage.num_blocks) == PROPERTY_ERROR) {
            goto out;
        }

        if (udevGetUint64SysfsAttr(device,
                                   "queue/logical_block_size",
                                   &data->storage.logical_block_size) == PROPERTY_ERROR) {
            goto out;
        }

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

976
 out:
977 978 979
    return ret;
}

980 981 982 983 984 985 986 987 988 989 990 991
static int udevProcessCDROM(struct udev_device *device,
                            virNodeDeviceDefPtr def)
{
    int ret = -1;
    int tmp_int = 0;
    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);
992
    if (VIR_STRDUP(def->caps->data.storage.drive_type, "cdrom") < 0)
993 994 995 996 997 998 999
        goto out;

    if ((udevGetIntProperty(device, "ID_CDROM_MEDIA",
                            &tmp_int, 0) == PROPERTY_FOUND))
        has_media = tmp_int;

    ret = udevProcessRemoveableMedia(device, def, has_media);
1000
 out:
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    return ret;
}

static int udevProcessFloppy(struct udev_device *device,
                             virNodeDeviceDefPtr def)
{
    int tmp_int = 0;
    int has_media = 0;
    char *tmp_str = NULL;

    if ((udevGetIntProperty(device, "DKD_MEDIA_AVAILABLE",
                            &tmp_int, 0) == PROPERTY_FOUND))
        /* USB floppy */
        has_media = tmp_int;
    else if (udevGetStringProperty(device, "ID_FS_LABEL",
                                   &tmp_str) == PROPERTY_FOUND) {
        /* Legacy floppy */
        has_media = 1;
        VIR_FREE(tmp_str);
    }

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

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

static int udevProcessSD(struct udev_device *device,
                         virNodeDeviceDefPtr def)
{
    union _virNodeDevCapData *data = &def->caps->data;
    int ret = 0;

    if (udevGetUint64SysfsAttr(device,
                               "size",
                               &data->storage.num_blocks) == PROPERTY_ERROR) {
        goto out;
    }

    if (udevGetUint64SysfsAttr(device,
                               "queue/logical_block_size",
                               &data->storage.logical_block_size)
        == PROPERTY_ERROR) {
        goto out;
    }

    data->storage.size = data->storage.num_blocks *
        data->storage.logical_block_size;

1048
 out:
1049 1050 1051 1052 1053
    return ret;
}



1054 1055 1056 1057 1058 1059 1060 1061
/* 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. */
static int udevKludgeStorageType(virNodeDeviceDefPtr def)
{
    int ret = -1;

1062 1063 1064
    VIR_DEBUG("Could not find definitive storage type for device "
              "with sysfs path '%s', trying to guess it",
              def->sysfs_path);
1065 1066 1067

    if (STRPREFIX(def->caps->data.storage.block, "/dev/vd")) {
        /* virtio disk */
1068
        ret = VIR_STRDUP(def->caps->data.storage.drive_type, "disk");
1069 1070 1071
    }

    if (ret != 0) {
1072 1073
        VIR_DEBUG("Could not determine storage type for device "
                  "with sysfs path '%s'", def->sysfs_path);
1074 1075
    } else {
        VIR_DEBUG("Found storage type '%s' for device "
1076
                  "with sysfs path '%s'",
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
                  def->caps->data.storage.drive_type,
                  def->sysfs_path);
    }

    return ret;
}


static void udevStripSpaces(char *s)
{
1087
    if (s == NULL)
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
        return;

    while (virFileStripSuffix(s, " ")) {
        /* do nothing */
        ;
    }

    return;
}


static int udevProcessStorage(struct udev_device *device,
                              virNodeDeviceDefPtr def)
{
    union _virNodeDevCapData *data = &def->caps->data;
    int ret = -1;
1104
    const char* devnode;
1105

1106
    devnode = udev_device_get_devnode(device);
1107
    if (!devnode) {
1108
        VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device));
1109 1110
        goto out;
    }
1111 1112 1113

    if (VIR_STRDUP(data->storage.block, devnode) < 0)
        goto out;
1114

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    if (udevGetStringProperty(device,
                              "ID_BUS",
                              &data->storage.bus) == PROPERTY_ERROR) {
        goto out;
    }
    if (udevGetStringProperty(device,
                              "ID_SERIAL",
                              &data->storage.serial) == PROPERTY_ERROR) {
        goto out;
    }
    if (udevGetStringSysfsAttr(device,
                               "device/vendor",
                               &data->storage.vendor) == PROPERTY_ERROR) {
        goto out;
    }
    udevStripSpaces(def->caps->data.storage.vendor);
    if (udevGetStringSysfsAttr(device,
                               "device/model",
                               &data->storage.model) == PROPERTY_ERROR) {
        goto out;
    }
    udevStripSpaces(def->caps->data.storage.model);
    /* 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. */

    if (udevGetStringProperty(device,
                              "ID_TYPE",
1144 1145
                              &data->storage.drive_type) != PROPERTY_FOUND ||
        STREQ(def->caps->data.storage.drive_type, "generic")) {
1146 1147 1148 1149
        int tmp_int = 0;

        /* All floppy drives have the ID_DRIVE_FLOPPY prop. This is
         * needed since legacy floppies don't have a drive_type */
1150 1151 1152
        if (udevGetIntProperty(device, "ID_DRIVE_FLOPPY",
                               &tmp_int, 0) == PROPERTY_FOUND &&
            tmp_int == 1) {
1153

1154
            if (VIR_STRDUP(data->storage.drive_type, "floppy") < 0)
1155
                goto out;
1156 1157 1158 1159 1160 1161 1162 1163 1164
        } else if (udevGetIntProperty(device, "ID_CDROM",
                                      &tmp_int, 0) == PROPERTY_FOUND &&
                   tmp_int == 1) {

            if (VIR_STRDUP(data->storage.drive_type, "cd") < 0)
                goto out;
        } else if (udevGetIntProperty(device, "ID_DRIVE_FLASH_SD",
                                      &tmp_int, 0) == PROPERTY_FOUND &&
                   tmp_int == 1) {
1165

1166
            if (VIR_STRDUP(data->storage.drive_type, "sd") < 0)
1167
                goto out;
1168 1169 1170
        } else {

            /* If udev doesn't have it, perhaps we can guess it. */
1171
            if (udevKludgeStorageType(def) != 0)
1172
                goto out;
1173 1174 1175 1176 1177 1178 1179
        }
    }

    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);
1180 1181
    } else if (STREQ(def->caps->data.storage.drive_type, "floppy")) {
        ret = udevProcessFloppy(device, def);
1182 1183
    } else if (STREQ(def->caps->data.storage.drive_type, "sd")) {
        ret = udevProcessSD(device, def);
1184
    } else {
1185 1186
        VIR_DEBUG("Unsupported storage type '%s'",
                  def->caps->data.storage.drive_type);
1187 1188 1189
        goto out;
    }

1190
    if (udevGenerateDeviceName(device, def, data->storage.serial) != 0)
1191 1192
        goto out;

1193
 out:
1194
    VIR_DEBUG("Storage ret=%d", ret);
1195 1196 1197
    return ret;
}

1198
static int
1199
udevProcessSCSIGeneric(struct udev_device *dev,
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
                       virNodeDeviceDefPtr def)
{
    if (udevGetStringProperty(dev,
                              "DEVNAME",
                              &def->caps->data.sg.path) != PROPERTY_FOUND)
        return -1;

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

    return 0;
}

1213
static bool
1214
udevHasDeviceProperty(struct udev_device *dev,
1215
                      const char *key)
1216
{
1217 1218
    if (udev_device_get_property_value(dev, key))
        return true;
1219

1220
    return false;
1221
}
1222

1223 1224
static int
udevGetDeviceType(struct udev_device *device,
1225
                  virNodeDevCapType *type)
1226 1227
{
    const char *devtype = NULL;
1228
    char *subsystem = NULL;
1229
    int ret = -1;
D
David Allan 已提交
1230

1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    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;
    } else {
        /* PCI devices don't set the DEVTYPE property. */
1251
        if (udevHasDeviceProperty(device, "PCI_CLASS"))
1252
            *type = VIR_NODE_DEV_CAP_PCI_DEV;
1253

1254 1255 1256 1257
        /* 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. */
1258
        if (udevHasDeviceProperty(device, "INTERFACE"))
1259
            *type = VIR_NODE_DEV_CAP_NET;
1260 1261 1262 1263 1264 1265 1266

        /* SCSI generic device doesn't set DEVTYPE property */
        if (udevGetStringProperty(device, "SUBSYSTEM", &subsystem) ==
            PROPERTY_FOUND &&
            STREQ(subsystem, "scsi_generic"))
            *type = VIR_NODE_DEV_CAP_SCSI_GENERIC;
        VIR_FREE(subsystem);
1267 1268
    }

1269 1270 1271 1272 1273 1274
    if (!*type)
        VIR_DEBUG("Could not determine device type for device "
                  "with sysfs name '%s'",
                  udev_device_get_sysname(device));
    else
        ret = 0;
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303

    return ret;
}


static int udevGetDeviceDetails(struct udev_device *device,
                                virNodeDeviceDefPtr def)
{
    int ret = 0;

    switch (def->caps->type) {
    case VIR_NODE_DEV_CAP_SYSTEM:
        /* There's no libudev equivalent of system, so ignore it. */
        break;
    case VIR_NODE_DEV_CAP_PCI_DEV:
        ret = udevProcessPCI(device, def);
        break;
    case VIR_NODE_DEV_CAP_USB_DEV:
        ret = udevProcessUSBDevice(device, def);
        break;
    case VIR_NODE_DEV_CAP_USB_INTERFACE:
        ret = udevProcessUSBInterface(device, def);
        break;
    case VIR_NODE_DEV_CAP_NET:
        ret = udevProcessNetworkInterface(device, def);
        break;
    case VIR_NODE_DEV_CAP_SCSI_HOST:
        ret = udevProcessSCSIHost(device, def);
        break;
D
David Allan 已提交
1304 1305 1306
    case VIR_NODE_DEV_CAP_SCSI_TARGET:
        ret = udevProcessSCSITarget(device, def);
        break;
1307 1308 1309 1310 1311 1312
    case VIR_NODE_DEV_CAP_SCSI:
        ret = udevProcessSCSIDevice(device, def);
        break;
    case VIR_NODE_DEV_CAP_STORAGE:
        ret = udevProcessStorage(device, def);
        break;
1313
    case VIR_NODE_DEV_CAP_SCSI_GENERIC:
1314
        ret = udevProcessSCSIGeneric(device, def);
1315
        break;
1316
    default:
1317
        VIR_ERROR(_("Unknown device type %d"), def->caps->type);
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
        ret = -1;
        break;
    }

    return ret;
}


static int udevRemoveOneDevice(struct udev_device *device)
{
    virNodeDeviceObjPtr dev = NULL;
    const char *name = NULL;
    int ret = 0;

    name = udev_device_get_syspath(device);
    dev = virNodeDeviceFindBySysfsPath(&driverState->devs, name);
1334

1335
    if (dev != NULL) {
1336
        VIR_DEBUG("Removing device '%s' with sysfs path '%s'",
1337 1338 1339
                  dev->def->name, name);
        virNodeDeviceObjRemove(&driverState->devs, dev);
    } else {
1340 1341
        VIR_DEBUG("Failed to find device to remove that has udev name '%s'",
                  name);
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
        ret = -1;
    }

    return ret;
}


static int udevSetParent(struct udev_device *device,
                         virNodeDeviceDefPtr def)
{
    struct udev_device *parent_device = NULL;
    const char *parent_sysfs_path = NULL;
    virNodeDeviceObjPtr dev = NULL;
    int ret = -1;

1357 1358
    parent_device = device;
    do {
1359

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

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

        dev = virNodeDeviceFindBySysfsPath(&driverState->devs,
                                           parent_sysfs_path);
        if (dev != NULL) {
1375 1376
            if (VIR_STRDUP(def->parent, dev->def->name) < 0) {
                virNodeDeviceObjUnlock(dev);
1377 1378
                goto out;
            }
1379
            virNodeDeviceObjUnlock(dev);
1380

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

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

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

    ret = 0;

1392
 out:
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    return ret;
}


static int udevAddOneDevice(struct udev_device *device)
{
    virNodeDeviceDefPtr def = NULL;
    virNodeDeviceObjPtr dev = NULL;
    int ret = -1;

1403
    if (VIR_ALLOC(def) != 0)
1404 1405
        goto out;

1406 1407 1408
    if (VIR_STRDUP(def->sysfs_path, udev_device_get_syspath(device)) < 0)
        goto out;

1409 1410 1411 1412 1413 1414
    if (udevGetStringProperty(device,
                              "DRIVER",
                              &def->driver) == PROPERTY_ERROR) {
        goto out;
    }

1415
    if (VIR_ALLOC(def->caps) != 0)
1416 1417
        goto out;

1418
    if (udevGetDeviceType(device, &def->caps->type) != 0)
1419 1420
        goto out;

1421
    if (udevGetDeviceDetails(device, def) != 0)
1422 1423
        goto out;

1424
    if (udevSetParent(device, def) != 0)
1425 1426
        goto out;

1427 1428
    /* If this is a device change, the old definition will be freed
     * and the current definition will take its place. */
1429
    dev = virNodeDeviceAssignDef(&driverState->devs, def);
1430

1431
    if (dev == NULL) {
1432
        VIR_ERROR(_("Failed to create device for '%s'"), def->name);
1433 1434 1435 1436 1437 1438 1439
        goto out;
    }

    virNodeDeviceObjUnlock(dev);

    ret = 0;

1440
 out:
1441
    if (ret != 0) {
1442
        VIR_DEBUG("Discarding device %d %p %s", ret, def,
1443
                  def ? NULLSTR(def->sysfs_path) : "");
1444 1445 1446
        virNodeDeviceDefFree(def);
    }

1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    return ret;
}


static int udevProcessDeviceListEntry(struct udev *udev,
                                      struct udev_list_entry *list_entry)
{
    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);
1461

1462 1463
    if (device != NULL) {
        if (udevAddOneDevice(device) != 0) {
1464 1465
            VIR_DEBUG("Failed to create node device for udev device '%s'",
                      name);
1466 1467 1468 1469
        }
        ret = 0;
    }

1470 1471
    udev_device_unref(device);

1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
    return ret;
}


static int udevEnumerateDevices(struct udev *udev)
{
    struct udev_enumerate *udev_enumerate = NULL;
    struct udev_list_entry *list_entry = NULL;
    int ret = 0;

    udev_enumerate = udev_enumerate_new(udev);

    ret = udev_enumerate_scan_devices(udev_enumerate);
    if (0 != ret) {
1486
        VIR_ERROR(_("udev scan devices returned %d"), ret);
1487 1488 1489 1490 1491 1492 1493 1494 1495
        goto out;
    }

    udev_list_entry_foreach(list_entry,
                            udev_enumerate_get_list_entry(udev_enumerate)) {

        udevProcessDeviceListEntry(udev, list_entry);
    }

1496
 out:
1497 1498 1499 1500 1501
    udev_enumerate_unref(udev_enumerate);
    return ret;
}


1502
static int nodeStateCleanup(void)
1503 1504 1505
{
    int ret = 0;

1506
    udevPrivate *priv = NULL;
1507 1508 1509 1510 1511
    struct udev_monitor *udev_monitor = NULL;
    struct udev *udev = NULL;

    if (driverState) {
        nodeDeviceLock(driverState);
1512 1513 1514 1515 1516 1517

        priv = driverState->privateData;

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

1518 1519 1520 1521 1522 1523 1524
        udev_monitor = DRV_STATE_UDEV_MONITOR(driverState);

        if (udev_monitor != NULL) {
            udev = udev_monitor_get_udev(udev_monitor);
            udev_monitor_unref(udev_monitor);
        }

1525
        if (udev != NULL)
1526 1527 1528 1529 1530 1531
            udev_unref(udev);

        virNodeDeviceObjListFree(&driverState->devs);
        nodeDeviceUnlock(driverState);
        virMutexDestroy(&driverState->lock);
        VIR_FREE(driverState);
1532
        VIR_FREE(priv);
1533 1534 1535 1536
    } else {
        ret = -1;
    }

1537 1538 1539
#if defined __s390__ || defined __s390x_
    /* Nothing was initialized, nothing needs to be cleaned up */
#else
1540 1541
    /* pci_system_cleanup returns void */
    pci_system_cleanup();
1542
#endif
1543

1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
    return ret;
}


static void udevEventHandleCallback(int watch ATTRIBUTE_UNUSED,
                                    int fd,
                                    int events ATTRIBUTE_UNUSED,
                                    void *data ATTRIBUTE_UNUSED)
{
    struct udev_device *device = NULL;
    struct udev_monitor *udev_monitor = DRV_STATE_UDEV_MONITOR(driverState);
    const char *action = NULL;
    int udev_fd = -1;

1558
    nodeDeviceLock(driverState);
1559 1560
    udev_fd = udev_monitor_get_fd(udev_monitor);
    if (fd != udev_fd) {
1561 1562
        VIR_ERROR(_("File descriptor returned by udev %d does not "
                    "match node device file descriptor %d"), fd, udev_fd);
1563 1564 1565 1566 1567
        goto out;
    }

    device = udev_monitor_receive_device(udev_monitor);
    if (device == NULL) {
1568
        VIR_ERROR(_("udev_monitor_receive_device returned NULL"));
1569 1570 1571 1572
        goto out;
    }

    action = udev_device_get_action(device);
1573
    VIR_DEBUG("udev action: '%s'", action);
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584

    if (STREQ(action, "add") || STREQ(action, "change")) {
        udevAddOneDevice(device);
        goto out;
    }

    if (STREQ(action, "remove")) {
        udevRemoveOneDevice(device);
        goto out;
    }

1585
 out:
1586
    udev_device_unref(device);
1587
    nodeDeviceUnlock(driverState);
1588 1589 1590 1591
    return;
}


1592 1593
/* DMI is intel-compatible specific */
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1594 1595
static void
udevGetDMIData(union _virNodeDevCapData *data)
1596 1597 1598 1599 1600 1601
{
    struct udev *udev = NULL;
    struct udev_device *device = NULL;
    char *tmp = NULL;

    udev = udev_monitor_get_udev(DRV_STATE_UDEV_MONITOR(driverState));
1602

1603 1604
    device = udev_device_new_from_syspath(udev, DMI_DEVPATH);
    if (device == NULL) {
1605 1606
        device = udev_device_new_from_syspath(udev, DMI_DEVPATH_FALLBACK);
        if (device == NULL) {
1607
            VIR_ERROR(_("Failed to get udev device for syspath '%s' or '%s'"),
1608
                      DMI_DEVPATH, DMI_DEVPATH_FALLBACK);
1609 1610
            goto out;
        }
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    }

    if (udevGetStringSysfsAttr(device,
                               "product_name",
                               &data->system.product_name) == PROPERTY_ERROR) {
        goto out;
    }
    if (udevGetStringSysfsAttr(device,
                               "sys_vendor",
                               &data->system.hardware.vendor_name)
        == PROPERTY_ERROR) {
        goto out;
    }
    if (udevGetStringSysfsAttr(device,
                               "product_version",
                               &data->system.hardware.version)
        == PROPERTY_ERROR) {
        goto out;
    }
    if (udevGetStringSysfsAttr(device,
                               "product_serial",
                               &data->system.hardware.serial)
        == PROPERTY_ERROR) {
        goto out;
    }

1637
    if (virGetHostUUID(data->system.hardware.uuid))
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
        goto out;

    if (udevGetStringSysfsAttr(device,
                               "bios_vendor",
                               &data->system.firmware.vendor_name)
        == PROPERTY_ERROR) {
        goto out;
    }
    if (udevGetStringSysfsAttr(device,
                               "bios_version",
                               &data->system.firmware.version)
        == PROPERTY_ERROR) {
        goto out;
    }
    if (udevGetStringSysfsAttr(device,
                               "bios_date",
                               &data->system.firmware.release_date)
        == PROPERTY_ERROR) {
        goto out;
    }

1659
 out:
1660
    VIR_FREE(tmp);
1661
    if (device != NULL)
1662 1663 1664
        udev_device_unref(device);
    return;
}
1665
#endif
1666 1667 1668 1669 1670 1671 1672 1673


static int udevSetupSystemDev(void)
{
    virNodeDeviceDefPtr def = NULL;
    virNodeDeviceObjPtr dev = NULL;
    int ret = -1;

1674
    if (VIR_ALLOC(def) != 0)
1675 1676
        goto out;

1677
    if (VIR_STRDUP(def->name, "computer") < 0)
1678 1679
        goto out;

1680
    if (VIR_ALLOC(def->caps) != 0)
1681 1682
        goto out;

1683
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1684
    udevGetDMIData(&def->caps->data);
1685
#endif
1686

1687
    dev = virNodeDeviceAssignDef(&driverState->devs, def);
1688
    if (dev == NULL) {
1689
        VIR_ERROR(_("Failed to create device for '%s'"), def->name);
1690 1691 1692 1693 1694 1695 1696
        goto out;
    }

    virNodeDeviceObjUnlock(dev);

    ret = 0;

1697
 out:
1698
    if (ret == -1)
1699 1700
        virNodeDeviceDefFree(def);

1701 1702 1703
    return ret;
}

1704
static int nodeStateInitialize(bool privileged,
1705 1706
                               virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                               void *opaque ATTRIBUTE_UNUSED)
1707
{
1708
    udevPrivate *priv = NULL;
1709 1710
    struct udev *udev = NULL;
    int ret = 0;
1711 1712 1713 1714 1715

#if defined __s390__ || defined __s390x_
    /* On s390(x) system there is no PCI bus.
     * Therefore there is nothing to initialize here. */
#else
1716 1717 1718
    int pciret;

    if ((pciret = pci_system_init()) != 0) {
1719 1720 1721
        /* 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.  */
1722
        if (errno != ENOENT && (privileged  || errno != EACCES)) {
1723 1724
            char ebuf[256];
            VIR_ERROR(_("Failed to initialize libpciaccess: %s"),
1725
                      virStrerror(pciret, ebuf, sizeof(ebuf)));
1726 1727 1728
            ret = -1;
            goto out;
        }
1729
    }
1730
#endif
1731

1732 1733 1734 1735 1736 1737
    if (VIR_ALLOC(priv) < 0) {
        ret = -1;
        goto out;
    }

    priv->watch = -1;
1738
    priv->privileged = privileged;
1739

1740
    if (VIR_ALLOC(driverState) < 0) {
1741
        VIR_FREE(priv);
1742 1743 1744 1745 1746
        ret = -1;
        goto out;
    }

    if (virMutexInit(&driverState->lock) < 0) {
1747
        VIR_ERROR(_("Failed to initialize mutex for driverState"));
1748
        VIR_FREE(priv);
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
        VIR_FREE(driverState);
        ret = -1;
        goto out;
    }

    nodeDeviceLock(driverState);

    /*
     * http://www.kernel.org/pub/linux/utils/kernel/hotplug/libudev/libudev-udev.html#udev-new
     *
     * indicates no return value other than success, so we don't check
     * its return value.
     */
    udev = udev_new();
1763
#if HAVE_UDEV_LOGGING
J
Ján Tomko 已提交
1764 1765
    /* cast to get rid of missing-format-attribute warning */
    udev_set_log_fn(udev, (udevLogFunctionPtr) udevLogFunction);
1766
#endif
1767

1768 1769 1770
    priv->udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
    if (priv->udev_monitor == NULL) {
        VIR_FREE(priv);
1771
        VIR_ERROR(_("udev_monitor_new_from_netlink returned NULL"));
1772
        ret = -1;
1773
        goto out_unlock;
1774 1775
    }

1776
    udev_monitor_enable_receiving(priv->udev_monitor);
1777 1778

    /* udev can be retrieved from udev_monitor */
1779
    driverState->privateData = priv;
1780 1781 1782 1783 1784 1785 1786 1787 1788

    /* 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.  */
1789 1790 1791 1792
    priv->watch = virEventAddHandle(udev_monitor_get_fd(priv->udev_monitor),
                                    VIR_EVENT_HANDLE_READABLE,
                                    udevEventHandleCallback, NULL, NULL);
    if (priv->watch == -1) {
1793
        ret = -1;
1794
        goto out_unlock;
1795 1796 1797 1798 1799
    }

    /* Create a fictional 'computer' device to root the device tree. */
    if (udevSetupSystemDev() != 0) {
        ret = -1;
1800
        goto out_unlock;
1801 1802 1803 1804 1805 1806
    }

    /* Populate with known devices */

    if (udevEnumerateDevices(udev) != 0) {
        ret = -1;
1807
        goto out_unlock;
1808 1809
    }

1810
 out_unlock:
1811 1812
    nodeDeviceUnlock(driverState);

1813
 out:
1814
    if (ret == -1)
1815
        nodeStateCleanup();
1816 1817 1818 1819
    return ret;
}


1820
static int nodeStateReload(void)
1821 1822 1823 1824 1825
{
    return 0;
}


1826 1827 1828
static virDrvOpenStatus nodeDeviceOpen(virConnectPtr conn,
                                       virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                       unsigned int flags)
1829
{
E
Eric Blake 已提交
1830 1831
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1832
    if (driverState == NULL)
1833 1834
        return VIR_DRV_OPEN_DECLINED;

1835
    conn->nodeDevicePrivateData = driverState;
1836 1837 1838 1839

    return VIR_DRV_OPEN_SUCCESS;
}

1840
static int nodeDeviceClose(virConnectPtr conn)
1841
{
1842
    conn->nodeDevicePrivateData = NULL;
1843 1844 1845
    return 0;
}

1846 1847
static virNodeDeviceDriver udevNodeDeviceDriver = {
    .name = "udevNodeDeviceDriver",
1848 1849
    .nodeDeviceOpen = nodeDeviceOpen, /* 0.7.3 */
    .nodeDeviceClose = nodeDeviceClose, /* 0.7.3 */
1850 1851
    .nodeNumOfDevices = nodeNumOfDevices, /* 0.7.3 */
    .nodeListDevices = nodeListDevices, /* 0.7.3 */
1852
    .connectListAllNodeDevices = nodeConnectListAllNodeDevices, /* 0.10.2 */
1853 1854 1855 1856 1857 1858 1859 1860
    .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 */
1861 1862 1863
};

static virStateDriver udevStateDriver = {
M
Matthias Bolte 已提交
1864
    .name = "udev",
1865 1866 1867
    .stateInitialize = nodeStateInitialize, /* 0.7.3 */
    .stateCleanup = nodeStateCleanup, /* 0.7.3 */
    .stateReload = nodeStateReload, /* 0.7.3 */
1868 1869 1870 1871
};

int udevNodeRegister(void)
{
1872
    VIR_DEBUG("Registering udev node device backend");
1873

1874
    if (virRegisterNodeDeviceDriver(&udevNodeDeviceDriver) < 0)
1875 1876 1877 1878
        return -1;

    return virRegisterStateDriver(&udevStateDriver);
}