node_device_udev.c 54.5 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
 */

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

27
#include "dirname.h"
28
#include "node_device_conf.h"
29
#include "node_device_event.h"
30
#include "node_device_driver.h"
31 32
#include "node_device_udev.h"
#include "virerror.h"
33 34
#include "driver.h"
#include "datatypes.h"
35
#include "virlog.h"
36
#include "viralloc.h"
37
#include "viruuid.h"
38
#include "virbuffer.h"
39
#include "virfile.h"
40
#include "virpci.h"
41
#include "virstring.h"
42
#include "virnetdev.h"
43
#include "virmdev.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 56 57 58
typedef struct _udevEventData udevEventData;
typedef udevEventData *udevEventDataPtr;

struct _udevEventData {
    virObjectLockable parent;

59 60
    struct udev_monitor *udev_monitor;
    int watch;
61 62 63 64 65 66

    /* Thread data */
    virThread th;
    virCond threadCond;
    bool threadQuit;
    bool dataReady;
67 68
};

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
static virClassPtr udevEventDataClass;

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

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

    if (!priv->udev_monitor)
        return;

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

    virCondDestroy(&priv->threadCond);
88 89 90 91 92 93
}


static int
udevEventDataOnceInit(void)
{
94
    if (!VIR_CLASS_NEW(udevEventData, virClassForObjectLockable()))
95 96 97 98 99
        return -1;

    return 0;
}

100
VIR_ONCE_GLOBAL_INIT(udevEventData);
101 102 103 104 105 106 107 108 109 110 111 112

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

    if (udevEventDataInitialize() < 0)
        return NULL;

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

113 114 115 116 117
    if (virCondInit(&ret->threadCond) < 0) {
        virObjectUnref(ret);
        return NULL;
    }

118 119 120 121
    ret->watch = -1;
    return ret;
}

122

J
Ján Tomko 已提交
123 124 125 126 127 128 129 130 131 132 133
static bool
udevHasDeviceProperty(struct udev_device *dev,
                      const char *key)
{
    if (udev_device_get_property_value(dev, key))
        return true;

    return false;
}


134 135 136
static const char *
udevGetDeviceProperty(struct udev_device *udev_device,
                      const char *property_key)
137
{
138
    const char *ret = NULL;
139

140
    ret = udev_device_get_property_value(udev_device, property_key);
141

142 143
    VIR_DEBUG("Found property key '%s' value '%s' for device with sysname '%s'",
              property_key, NULLSTR(ret), udev_device_get_sysname(udev_device));
144 145 146 147 148

    return ret;
}


149 150 151 152
static int
udevGetStringProperty(struct udev_device *udev_device,
                      const char *property_key,
                      char **value)
153
{
154 155
    if (VIR_STRDUP(*value,
                   udevGetDeviceProperty(udev_device, property_key)) < 0)
156
        return -1;
157

158
    return 0;
159 160 161
}


162 163 164 165 166
static int
udevGetIntProperty(struct udev_device *udev_device,
                   const char *property_key,
                   int *value,
                   int base)
167
{
168
    const char *str = NULL;
169

170
    str = udevGetDeviceProperty(udev_device, property_key);
171

172
    if (str && virStrToLong_i(str, NULL, base, value) < 0) {
173 174
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
175
        return -1;
176
    }
177
    return 0;
178 179 180
}


181 182 183 184 185
static int
udevGetUintProperty(struct udev_device *udev_device,
                    const char *property_key,
                    unsigned int *value,
                    int base)
186
{
187
    const char *str = NULL;
188

189
    str = udevGetDeviceProperty(udev_device, property_key);
190

191
    if (str && virStrToLong_ui(str, NULL, base, value) < 0) {
192 193
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
194
        return -1;
195
    }
196
    return 0;
197 198 199
}


200 201 202
static const char *
udevGetDeviceSysfsAttr(struct udev_device *udev_device,
                       const char *attr_name)
203
{
204
    const char *ret = NULL;
205

206
    ret = udev_device_get_sysattr_value(udev_device, attr_name);
207 208

    VIR_DEBUG("Found sysfs attribute '%s' value '%s' "
209
              "for device with sysname '%s'",
210
              attr_name, NULLSTR(ret),
211 212 213 214 215
              udev_device_get_sysname(udev_device));
    return ret;
}


216 217 218 219
static int
udevGetStringSysfsAttr(struct udev_device *udev_device,
                       const char *attr_name,
                       char **value)
220
{
221
    if (VIR_STRDUP(*value, udevGetDeviceSysfsAttr(udev_device, attr_name)) < 0)
222
        return -1;
223

224
    virStringStripControlChars(*value);
225

226 227
    if (*value != NULL && (STREQ(*value, "")))
        VIR_FREE(*value);
228

229
    return 0;
230 231 232
}


233 234 235 236 237
static int
udevGetIntSysfsAttr(struct udev_device *udev_device,
                    const char *attr_name,
                    int *value,
                    int base)
238
{
239
    const char *str = NULL;
240

241
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
242

243
    if (str && virStrToLong_i(str, NULL, base, value) < 0) {
244 245
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to int"), str);
246
        return -1;
247 248
    }

249
    return 0;
250 251 252
}


253 254 255 256 257
static int
udevGetUintSysfsAttr(struct udev_device *udev_device,
                     const char *attr_name,
                     unsigned int *value,
                     int base)
258
{
259
    const char *str = NULL;
260

261
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
262

263
    if (str && virStrToLong_ui(str, NULL, base, value) < 0) {
264 265
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to unsigned int"), str);
266
        return -1;
267 268
    }

269
    return 0;
270 271 272
}


273 274 275 276
static int
udevGetUint64SysfsAttr(struct udev_device *udev_device,
                       const char *attr_name,
                       unsigned long long *value)
277
{
278
    const char *str = NULL;
279

280
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
281

282
    if (str && virStrToLong_ull(str, NULL, 0, value) < 0) {
283 284
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to convert '%s' to unsigned long long"), str);
J
Ján Tomko 已提交
285
        return -1;
286 287
    }

J
Ján Tomko 已提交
288
    return 0;
289 290 291
}


292 293 294 295
static int
udevGenerateDeviceName(struct udev_device *device,
                       virNodeDeviceDefPtr def,
                       const char *s)
296
{
297
    size_t i;
298 299
    virBuffer buf = VIR_BUFFER_INITIALIZER;

300
    virBufferAsprintf(&buf, "%s_%s",
301 302 303
                      udev_device_get_subsystem(device),
                      udev_device_get_sysname(device));

304
    if (s != NULL)
305
        virBufferAsprintf(&buf, "_%s", s);
306

307 308
    if (virBufferCheckError(&buf) < 0)
        return -1;
309 310 311

    def->name = virBufferContentAndReset(&buf);

312
    for (i = 0; i < strlen(def->name); i++) {
313
        if (!(c_isalnum(*(def->name + i))))
314 315 316
            *(def->name + i) = '_';
    }

317
    return 0;
318 319
}

320 321 322 323 324 325

static int
udevTranslatePCIIds(unsigned int vendor,
                    unsigned int product,
                    char **vendor_string,
                    char **product_string)
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
{
    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,
341
                    &vendor_name,
342 343 344
                    NULL,
                    NULL);

345
    if (VIR_STRDUP(*vendor_string, vendor_name) < 0 ||
346
        VIR_STRDUP(*product_string, device_name) < 0)
347
        return -1;
348

349
    return 0;
350 351 352
}


353 354 355
static int
udevProcessPCI(struct udev_device *device,
               virNodeDeviceDefPtr def)
356
{
357
    virNodeDevCapPCIDevPtr pci_dev = &def->caps->data.pci_dev;
358 359
    virPCIEDeviceInfoPtr pci_express = NULL;
    virPCIDevicePtr pciDev = NULL;
360
    int ret = -1;
361
    char *p;
362 363 364 365 366
    bool privileged;

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

368 369
    pci_dev->klass = -1;
    if (udevGetIntProperty(device, "PCI_CLASS", &pci_dev->klass, 16) < 0)
370
        goto cleanup;
371

372
    if ((p = strrchr(def->sysfs_path, '/')) == NULL ||
373 374 375 376
        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) {
377 378
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the PCI address from sysfs path: '%s'"),
379
                       def->sysfs_path);
380
        goto cleanup;
381 382
    }

383
    if (udevGetUintSysfsAttr(device, "vendor", &pci_dev->vendor, 16) < 0)
384
        goto cleanup;
385

386
    if (udevGetUintSysfsAttr(device, "device", &pci_dev->product, 16) < 0)
387
        goto cleanup;
388

389 390 391 392
    if (udevTranslatePCIIds(pci_dev->vendor,
                            pci_dev->product,
                            &pci_dev->vendor_name,
                            &pci_dev->product_name) != 0) {
393
        goto cleanup;
394
    }
395

396
    if (udevGenerateDeviceName(device, def, NULL) != 0)
397
        goto cleanup;
398

399 400
    /* The default value is -1, because it can't be 0
     * as zero is valid node number. */
401
    pci_dev->numa_node = -1;
402
    if (udevGetIntSysfsAttr(device, "numa_node",
403
                            &pci_dev->numa_node, 10) < 0)
404
        goto cleanup;
405

406
    if (virNodeDeviceGetPCIDynamicCaps(def->sysfs_path, pci_dev) < 0)
407
        goto cleanup;
408

409 410 411 412
    if (!(pciDev = virPCIDeviceNew(pci_dev->domain,
                                   pci_dev->bus,
                                   pci_dev->slot,
                                   pci_dev->function)))
413
        goto cleanup;
414

415
    /* We need to be root to read PCI device configs */
416
    if (privileged) {
417
        if (virPCIGetHeaderType(pciDev, &pci_dev->hdrType) < 0)
418
            goto cleanup;
419

420 421
        if (virPCIDeviceIsPCIExpress(pciDev) > 0) {
            if (VIR_ALLOC(pci_express) < 0)
422
                goto cleanup;
423

424 425 426
            if (virPCIDeviceHasPCIExpressLink(pciDev) > 0) {
                if (VIR_ALLOC(pci_express->link_cap) < 0 ||
                    VIR_ALLOC(pci_express->link_sta) < 0)
427
                    goto cleanup;
428 429 430 431 432 433 434

                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)
435
                    goto cleanup;
436 437 438

                pci_express->link_sta->port = -1; /* PCIe can't negotiate port. Yet :) */
            }
439 440
            pci_dev->flags |= VIR_NODE_DEV_CAP_FLAG_PCIE;
            pci_dev->pci_express = pci_express;
441
            pci_express = NULL;
442 443 444
        }
    }

445 446
    ret = 0;

447
 cleanup:
448
    virPCIDeviceFree(pciDev);
449
    virPCIEDeviceInfoFree(pci_express);
450 451 452
    return ret;
}

453 454 455

static int
drmGetMinorType(int minor)
M
Marc-André Lureau 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
{
    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;
    }
}

472 473 474 475

static int
udevProcessDRMDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
M
Marc-André Lureau 已提交
476
{
477
    virNodeDevCapDRMPtr drm = &def->caps->data.drm;
M
Marc-André Lureau 已提交
478 479 480 481 482 483 484 485 486 487 488
    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;

489
    drm->type = minor;
M
Marc-André Lureau 已提交
490 491 492

    return 0;
}
493

494 495 496 497

static int
udevProcessUSBDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
498
{
499
    virNodeDevCapUSBDevPtr usb_dev = &def->caps->data.usb_dev;
500

501
    if (udevGetUintProperty(device, "BUSNUM", &usb_dev->bus, 10) < 0)
502
        return -1;
503
    if (udevGetUintProperty(device, "DEVNUM", &usb_dev->device, 10) < 0)
504
        return -1;
505
    if (udevGetUintProperty(device, "ID_VENDOR_ID", &usb_dev->vendor, 16) < 0)
506
        return -1;
507

508 509
    if (udevGetStringProperty(device,
                              "ID_VENDOR_FROM_DATABASE",
510
                              &usb_dev->vendor_name) < 0)
511
        return -1;
512

513
    if (!usb_dev->vendor_name &&
514
        udevGetStringSysfsAttr(device, "manufacturer",
515
                               &usb_dev->vendor_name) < 0)
516
        return -1;
517

518
    if (udevGetUintProperty(device, "ID_MODEL_ID", &usb_dev->product, 16) < 0)
519
        return -1;
520

521 522
    if (udevGetStringProperty(device,
                              "ID_MODEL_FROM_DATABASE",
523
                              &usb_dev->product_name) < 0)
524
        return -1;
525

526
    if (!usb_dev->product_name &&
527
        udevGetStringSysfsAttr(device, "product",
528
                               &usb_dev->product_name) < 0)
529
        return -1;
530

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

534
    return 0;
535 536 537
}


538 539 540
static int
udevProcessUSBInterface(struct udev_device *device,
                        virNodeDeviceDefPtr def)
541
{
542
    virNodeDevCapUSBIfPtr usb_if = &def->caps->data.usb_if;
543

544
    if (udevGetUintSysfsAttr(device, "bInterfaceNumber",
545
                             &usb_if->number, 16) < 0)
546
        return -1;
547

548
    if (udevGetUintSysfsAttr(device, "bInterfaceClass",
549
                             &usb_if->klass, 16) < 0)
550
        return -1;
551

552
    if (udevGetUintSysfsAttr(device, "bInterfaceSubClass",
553
                             &usb_if->subclass, 16) < 0)
554
        return -1;
555

556
    if (udevGetUintSysfsAttr(device, "bInterfaceProtocol",
557
                             &usb_if->protocol, 16) < 0)
558
        return -1;
559

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

563
    return 0;
564 565 566
}


567 568 569
static int
udevProcessNetworkInterface(struct udev_device *device,
                            virNodeDeviceDefPtr def)
570
{
D
David Allan 已提交
571
    const char *devtype = udev_device_get_devtype(device);
572
    virNodeDevCapNetPtr net = &def->caps->data.net;
573

D
David Allan 已提交
574
    if (devtype && STREQ(devtype, "wlan")) {
575
        net->subtype = VIR_NODE_DEV_CAP_NET_80211;
D
David Allan 已提交
576
    } else {
577
        net->subtype = VIR_NODE_DEV_CAP_NET_80203;
D
David Allan 已提交
578 579
    }

580 581
    if (udevGetStringProperty(device,
                              "INTERFACE",
582
                              &net->ifname) < 0)
583
        return -1;
584

585
    if (udevGetStringSysfsAttr(device, "address",
586
                               &net->address) < 0)
587
        return -1;
588

589
    if (udevGetUintSysfsAttr(device, "addr_len", &net->address_len, 0) < 0)
590
        return -1;
591

592
    if (udevGenerateDeviceName(device, def, net->address) != 0)
593
        return -1;
594

595
    if (virNetDevGetLinkInfo(net->ifname, &net->lnk) < 0)
596
        return -1;
597

598
    if (virNetDevGetFeatures(net->ifname, &net->features) < 0)
599
        return -1;
600

601
    return 0;
602 603 604
}


605 606 607
static int
udevProcessSCSIHost(struct udev_device *device ATTRIBUTE_UNUSED,
                    virNodeDeviceDefPtr def)
608
{
609
    virNodeDevCapSCSIHostPtr scsi_host = &def->caps->data.scsi_host;
610
    char *filename = NULL;
J
Ján Tomko 已提交
611
    char *str;
612

613
    filename = last_component(def->sysfs_path);
614

615
    if (!(str = STRSKIP(filename, "host")) ||
616
        virStrToLong_ui(str, NULL, 0, &scsi_host->host) < 0) {
617 618 619
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse SCSI host '%s'"),
                       filename);
620
        return -1;
621 622
    }

623
    virNodeDeviceGetSCSIHostCaps(&def->caps->data.scsi_host);
624

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

628
    return 0;
629 630 631
}


632 633 634
static int
udevProcessSCSITarget(struct udev_device *device,
                      virNodeDeviceDefPtr def)
D
David Allan 已提交
635 636
{
    const char *sysname = NULL;
637
    virNodeDevCapSCSITargetPtr scsi_target = &def->caps->data.scsi_target;
D
David Allan 已提交
638 639 640

    sysname = udev_device_get_sysname(device);

641
    if (VIR_STRDUP(scsi_target->name, sysname) < 0)
642
        return -1;
D
David Allan 已提交
643

644
    virNodeDeviceGetSCSITargetCaps(def->sysfs_path, &def->caps->data.scsi_target);
645

646
    if (udevGenerateDeviceName(device, def, NULL) != 0)
647
        return -1;
D
David Allan 已提交
648

649
    return 0;
D
David Allan 已提交
650 651 652
}


653 654 655 656
static int
udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED,
                unsigned int type,
                char **typestring)
657 658 659 660 661 662 663 664
{
    int ret = 0;
    int foundtype = 1;

    *typestring = NULL;

    switch (type) {
    case TYPE_DISK:
665
        ignore_value(VIR_STRDUP(*typestring, "disk"));
666 667
        break;
    case TYPE_TAPE:
668
        ignore_value(VIR_STRDUP(*typestring, "tape"));
669 670
        break;
    case TYPE_PROCESSOR:
671
        ignore_value(VIR_STRDUP(*typestring, "processor"));
672 673
        break;
    case TYPE_WORM:
674
        ignore_value(VIR_STRDUP(*typestring, "worm"));
675 676
        break;
    case TYPE_ROM:
677
        ignore_value(VIR_STRDUP(*typestring, "cdrom"));
678 679
        break;
    case TYPE_SCANNER:
680
        ignore_value(VIR_STRDUP(*typestring, "scanner"));
681 682
        break;
    case TYPE_MOD:
683
        ignore_value(VIR_STRDUP(*typestring, "mod"));
684 685
        break;
    case TYPE_MEDIUM_CHANGER:
686
        ignore_value(VIR_STRDUP(*typestring, "changer"));
687 688
        break;
    case TYPE_ENCLOSURE:
689
        ignore_value(VIR_STRDUP(*typestring, "enclosure"));
690
        break;
691
    case TYPE_RAID:
692
        ignore_value(VIR_STRDUP(*typestring, "raid"));
693
        break;
694 695 696 697 698 699 700 701 702 703
    case TYPE_NO_LUN:
    default:
        foundtype = 0;
        break;
    }

    if (*typestring == NULL) {
        if (foundtype == 1) {
            ret = -1;
        } else {
704 705
            VIR_DEBUG("Failed to find SCSI device type %d for %s",
                      type, def->sysfs_path);
706 707 708 709 710 711 712
        }
    }

    return ret;
}


713 714 715
static int
udevProcessSCSIDevice(struct udev_device *device ATTRIBUTE_UNUSED,
                      virNodeDeviceDefPtr def)
716 717 718
{
    int ret = -1;
    unsigned int tmp = 0;
719
    virNodeDevCapSCSIPtr scsi = &def->caps->data.scsi;
720 721
    char *filename = NULL, *p = NULL;

722
    filename = last_component(def->sysfs_path);
723

724 725 726 727
    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) {
728 729 730 731
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the SCSI address from filename: '%s'"),
                       filename);
        return -1;
732 733
    }

734 735
    if (udev_device_get_sysattr_value(device, "type")) {
        if (udevGetUintSysfsAttr(device, "type", &tmp, 0) < 0)
736
            goto cleanup;
737

738
        if (udevGetSCSIType(def, tmp, &scsi->type) < 0)
739
            goto cleanup;
740 741
    }

742
    if (udevGenerateDeviceName(device, def, NULL) != 0)
743
        goto cleanup;
744 745 746

    ret = 0;

747
 cleanup:
748
    if (ret != 0) {
749 750 751
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to process SCSI device with sysfs path '%s'"),
                       def->sysfs_path);
752 753 754 755 756
    }
    return ret;
}


757 758 759
static int
udevProcessDisk(struct udev_device *device,
                virNodeDeviceDefPtr def)
760
{
761
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
762

763
    if (udevGetUint64SysfsAttr(device, "size", &storage->num_blocks) < 0)
764
        return -1;
765

J
Ján Tomko 已提交
766
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
767
                               &storage->logical_block_size) < 0)
768
        return -1;
769

770
    storage->size = storage->num_blocks * storage->logical_block_size;
771

772
    return 0;
773 774 775
}


776 777 778 779
static int
udevProcessRemoveableMedia(struct udev_device *device,
                           virNodeDeviceDefPtr def,
                           int has_media)
780
{
781
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
J
Ján Tomko 已提交
782
    int is_removable = 0;
783

784 785 786
    if (udevGetIntSysfsAttr(device, "removable", &is_removable, 0) < 0)
        return -1;
    if (is_removable == 1)
787 788
        def->caps->data.storage.flags |= VIR_NODE_DEV_CAP_STORAGE_REMOVABLE;

J
Ján Tomko 已提交
789 790
    if (!has_media)
        return 0;
791

J
Ján Tomko 已提交
792 793
    def->caps->data.storage.flags |=
        VIR_NODE_DEV_CAP_STORAGE_REMOVABLE_MEDIA_AVAILABLE;
794

J
Ján Tomko 已提交
795
    if (udevGetStringProperty(device, "ID_FS_LABEL",
796
                              &storage->media_label) < 0)
J
Ján Tomko 已提交
797
        return -1;
798

J
Ján Tomko 已提交
799
    if (udevGetUint64SysfsAttr(device, "size",
800
                               &storage->num_blocks) < 0)
J
Ján Tomko 已提交
801
        return -1;
802

J
Ján Tomko 已提交
803
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
804
                               &storage->logical_block_size) < 0)
J
Ján Tomko 已提交
805
        return -1;
806

J
Ján Tomko 已提交
807 808 809 810 811 812 813
    /* 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;
814

J
Ján Tomko 已提交
815
    return 0;
816 817
}

818 819 820 821

static int
udevProcessCDROM(struct udev_device *device,
                 virNodeDeviceDefPtr def)
822 823 824 825 826 827 828 829
{
    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);
830
    if (VIR_STRDUP(def->caps->data.storage.drive_type, "cdrom") < 0)
831
        return -1;
832

833 834
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA") &&
        udevGetIntProperty(device, "ID_CDROM_MEDIA", &has_media, 0) < 0)
835
        return -1;
836

837
    return udevProcessRemoveableMedia(device, def, has_media);
838 839
}

840 841 842 843

static int
udevProcessFloppy(struct udev_device *device,
                  virNodeDeviceDefPtr def)
844 845 846
{
    int has_media = 0;

847
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA")) {
848
        /* USB floppy */
849 850
        if (udevGetIntProperty(device, "DKD_MEDIA_AVAILABLE", &has_media, 0) < 0)
            return -1;
851
    } else if (udevHasDeviceProperty(device, "ID_FS_LABEL")) {
852 853 854 855 856 857
        /* Legacy floppy */
        has_media = 1;
    }

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

859

860 861 862
static int
udevProcessSD(struct udev_device *device,
              virNodeDeviceDefPtr def)
863
{
864
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
865

J
Ján Tomko 已提交
866
    if (udevGetUint64SysfsAttr(device, "size",
867
                               &storage->num_blocks) < 0)
868
        return -1;
869

J
Ján Tomko 已提交
870
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
871
                               &storage->logical_block_size) < 0)
872
        return -1;
873

874
    storage->size = storage->num_blocks * storage->logical_block_size;
875

876
    return 0;
877 878 879
}


880 881 882 883
/* 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. */
884 885
static int
udevKludgeStorageType(virNodeDeviceDefPtr def)
886
{
887 888 889
    VIR_DEBUG("Could not find definitive storage type for device "
              "with sysfs path '%s', trying to guess it",
              def->sysfs_path);
890

891 892 893
    /* virtio disk */
    if (STRPREFIX(def->caps->data.storage.block, "/dev/vd") &&
        VIR_STRDUP(def->caps->data.storage.drive_type, "disk") > 0) {
894
        VIR_DEBUG("Found storage type '%s' for device "
895
                  "with sysfs path '%s'",
896 897
                  def->caps->data.storage.drive_type,
                  def->sysfs_path);
898
        return 0;
899
    }
900 901 902
    VIR_DEBUG("Could not determine storage type "
              "for device with sysfs path '%s'", def->sysfs_path);
    return -1;
903 904 905
}


906 907 908
static int
udevProcessStorage(struct udev_device *device,
                   virNodeDeviceDefPtr def)
909
{
910
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
911
    int ret = -1;
912
    const char* devnode;
913

914
    devnode = udev_device_get_devnode(device);
915
    if (!devnode) {
916
        VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device));
917
        goto cleanup;
918
    }
919

920
    if (VIR_STRDUP(storage->block, devnode) < 0)
921
        goto cleanup;
922

923
    if (udevGetStringProperty(device, "ID_BUS", &storage->bus) < 0)
924
        goto cleanup;
925
    if (udevGetStringProperty(device, "ID_SERIAL", &storage->serial) < 0)
926
        goto cleanup;
927

928
    if (udevGetStringSysfsAttr(device, "device/vendor", &storage->vendor) < 0)
929
        goto cleanup;
930 931 932
    if (def->caps->data.storage.vendor)
        virTrimSpaces(def->caps->data.storage.vendor, NULL);

933
    if (udevGetStringSysfsAttr(device, "device/model", &storage->model) < 0)
934
        goto cleanup;
935 936
    if (def->caps->data.storage.model)
        virTrimSpaces(def->caps->data.storage.model, NULL);
937 938 939 940 941
    /* 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. */

942
    if (udevGetStringProperty(device, "ID_TYPE", &storage->drive_type) < 0)
943
        goto cleanup;
944

945
    if (!storage->drive_type ||
946
        STREQ(def->caps->data.storage.drive_type, "generic")) {
947 948
        int val = 0;
        const char *str = NULL;
949 950 951

        /* All floppy drives have the ID_DRIVE_FLOPPY prop. This is
         * needed since legacy floppies don't have a drive_type */
952
        if (udevGetIntProperty(device, "ID_DRIVE_FLOPPY", &val, 0) < 0)
953
            goto cleanup;
954 955
        else if (val == 1)
            str = "floppy";
956

957
        if (!str) {
958
            if (udevGetIntProperty(device, "ID_CDROM", &val, 0) < 0)
959
                goto cleanup;
960 961 962
            else if (val == 1)
                str = "cd";
        }
963

964
        if (!str) {
965
            if (udevGetIntProperty(device, "ID_DRIVE_FLASH_SD", &val, 0) < 0)
966
                goto cleanup;
967 968 969
            if (val == 1)
                str = "sd";
        }
970

971
        if (str) {
972
            if (VIR_STRDUP(storage->drive_type, str) < 0)
973
                goto cleanup;
974 975
        } else {
            /* If udev doesn't have it, perhaps we can guess it. */
976
            if (udevKludgeStorageType(def) != 0)
977
                goto cleanup;
978 979 980 981 982 983 984
        }
    }

    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);
985 986
    } else if (STREQ(def->caps->data.storage.drive_type, "floppy")) {
        ret = udevProcessFloppy(device, def);
987 988
    } else if (STREQ(def->caps->data.storage.drive_type, "sd")) {
        ret = udevProcessSD(device, def);
989
    } else {
990 991
        VIR_DEBUG("Unsupported storage type '%s'",
                  def->caps->data.storage.drive_type);
992
        goto cleanup;
993 994
    }

995
    if (udevGenerateDeviceName(device, def, storage->serial) != 0)
996
        goto cleanup;
997

998
 cleanup:
999
    VIR_DEBUG("Storage ret=%d", ret);
1000 1001 1002
    return ret;
}

1003

1004
static int
1005
udevProcessSCSIGeneric(struct udev_device *dev,
1006 1007
                       virNodeDeviceDefPtr def)
{
1008 1009
    if (udevGetStringProperty(dev, "DEVNAME", &def->caps->data.sg.path) < 0 ||
        !def->caps->data.sg.path)
1010 1011 1012 1013 1014 1015 1016 1017
        return -1;

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

    return 0;
}

1018

1019 1020 1021 1022 1023 1024 1025 1026
static int
udevProcessMediatedDevice(struct udev_device *dev,
                          virNodeDeviceDefPtr def)
{
    int ret = -1;
    const char *uuidstr = NULL;
    int iommugrp = -1;
    char *linkpath = NULL;
1027
    char *canonicalpath = NULL;
1028 1029
    virNodeDevCapMdevPtr data = &def->caps->data.mdev;

1030 1031 1032 1033 1034 1035 1036 1037
    /* Because of a kernel uevent race, we might get the 'add' event prior to
     * the sysfs tree being ready, so any attempt to access any sysfs attribute
     * would result in ENOENT and us dropping the device, so let's work around
     * it by waiting for the attributes to become available.
     */

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

1040 1041 1042 1043 1044 1045 1046
    if (virFileWaitForExists(linkpath, 1, 100) < 0) {
        virReportSystemError(errno,
                             _("failed to wait for file '%s' to appear"),
                             linkpath);
        goto cleanup;
    }

1047 1048
    if (virFileResolveLink(linkpath, &canonicalpath) < 0) {
        virReportSystemError(errno, _("failed to resolve '%s'"), linkpath);
1049
        goto cleanup;
1050
    }
1051

1052
    if (VIR_STRDUP(data->type, last_component(canonicalpath)) < 0)
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
        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);
1067
    VIR_FREE(canonicalpath);
1068 1069 1070
    return ret;
}

B
Bjoern Walk 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

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


1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
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;
}

1129

1130 1131
static int
udevGetDeviceType(struct udev_device *device,
1132
                  virNodeDevCapType *type)
1133 1134
{
    const char *devtype = NULL;
1135
    char *subsystem = NULL;
1136
    int ret = -1;
D
David Allan 已提交
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
    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 已提交
1156 1157
        else if (STREQ(devtype, "drm_minor"))
            *type = VIR_NODE_DEV_CAP_DRM;
1158 1159
    } else {
        /* PCI devices don't set the DEVTYPE property. */
1160
        if (udevHasDeviceProperty(device, "PCI_CLASS"))
1161
            *type = VIR_NODE_DEV_CAP_PCI_DEV;
1162

1163 1164 1165 1166
        /* 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. */
1167
        if (udevHasDeviceProperty(device, "INTERFACE"))
1168
            *type = VIR_NODE_DEV_CAP_NET;
1169

B
Bjoern Walk 已提交
1170 1171
        /* The following devices do not set the DEVTYPE property, therefore
         * we need to rely on the SUBSYSTEM property */
1172 1173 1174 1175
        if (udevGetStringProperty(device, "SUBSYSTEM", &subsystem) < 0)
            return -1;

        if (STREQ_NULLABLE(subsystem, "scsi_generic"))
1176
            *type = VIR_NODE_DEV_CAP_SCSI_GENERIC;
1177 1178
        else if (STREQ_NULLABLE(subsystem, "mdev"))
            *type = VIR_NODE_DEV_CAP_MDEV;
B
Bjoern Walk 已提交
1179 1180
        else if (STREQ_NULLABLE(subsystem, "ccw"))
            *type = VIR_NODE_DEV_CAP_CCW_DEV;
1181

1182
        VIR_FREE(subsystem);
1183 1184
    }

1185 1186 1187 1188 1189 1190
    if (!*type)
        VIR_DEBUG("Could not determine device type for device "
                  "with sysfs name '%s'",
                  udev_device_get_sysname(device));
    else
        ret = 0;
1191 1192 1193 1194 1195

    return ret;
}


1196 1197 1198
static int
udevGetDeviceDetails(struct udev_device *device,
                     virNodeDeviceDefPtr def)
1199
{
1200
    switch (def->caps->data.type) {
1201
    case VIR_NODE_DEV_CAP_PCI_DEV:
1202
        return udevProcessPCI(device, def);
1203
    case VIR_NODE_DEV_CAP_USB_DEV:
1204
        return udevProcessUSBDevice(device, def);
1205
    case VIR_NODE_DEV_CAP_USB_INTERFACE:
1206
        return udevProcessUSBInterface(device, def);
1207
    case VIR_NODE_DEV_CAP_NET:
1208
        return udevProcessNetworkInterface(device, def);
1209
    case VIR_NODE_DEV_CAP_SCSI_HOST:
1210
        return udevProcessSCSIHost(device, def);
D
David Allan 已提交
1211
    case VIR_NODE_DEV_CAP_SCSI_TARGET:
1212
        return udevProcessSCSITarget(device, def);
1213
    case VIR_NODE_DEV_CAP_SCSI:
1214
        return udevProcessSCSIDevice(device, def);
1215
    case VIR_NODE_DEV_CAP_STORAGE:
1216
        return udevProcessStorage(device, def);
1217
    case VIR_NODE_DEV_CAP_SCSI_GENERIC:
1218
        return udevProcessSCSIGeneric(device, def);
M
Marc-André Lureau 已提交
1219
    case VIR_NODE_DEV_CAP_DRM:
1220
        return udevProcessDRMDevice(device, def);
1221
    case VIR_NODE_DEV_CAP_MDEV:
1222
        return udevProcessMediatedDevice(device, def);
B
Bjoern Walk 已提交
1223 1224
    case VIR_NODE_DEV_CAP_CCW_DEV:
        return udevProcessCCW(device, def);
1225
    case VIR_NODE_DEV_CAP_MDEV_TYPES:
1226 1227 1228 1229
    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:
1230 1231 1232
        break;
    }

1233
    return 0;
1234 1235 1236
}


1237 1238
static int
udevRemoveOneDevice(struct udev_device *device)
1239
{
1240
    virNodeDeviceObjPtr obj = NULL;
1241
    virNodeDeviceDefPtr def;
1242
    virObjectEventPtr event = NULL;
1243 1244 1245
    const char *name = NULL;

    name = udev_device_get_syspath(device);
1246
    if (!(obj = virNodeDeviceObjListFindBySysfsPath(driver->devs, name))) {
1247 1248
        VIR_DEBUG("Failed to find device to remove that has udev name '%s'",
                  name);
1249
        return -1;
1250
    }
1251
    def = virNodeDeviceObjGetDef(obj);
1252

1253
    event = virNodeDeviceEventLifecycleNew(def->name,
1254 1255 1256 1257
                                           VIR_NODE_DEVICE_EVENT_DELETED,
                                           0);

    VIR_DEBUG("Removing device '%s' with sysfs path '%s'",
1258
              def->name, name);
1259
    virNodeDeviceObjListRemove(driver->devs, obj);
1260
    virObjectUnref(obj);
1261

1262
    virObjectEventStateQueue(driver->nodeDeviceEventState, event);
1263
    return 0;
1264 1265 1266
}


1267 1268 1269
static int
udevSetParent(struct udev_device *device,
              virNodeDeviceDefPtr def)
1270 1271 1272
{
    struct udev_device *parent_device = NULL;
    const char *parent_sysfs_path = NULL;
1273
    virNodeDeviceObjPtr obj = NULL;
1274
    virNodeDeviceDefPtr objdef;
1275 1276
    int ret = -1;

1277 1278
    parent_device = device;
    do {
1279

1280
        parent_device = udev_device_get_parent(parent_device);
1281
        if (parent_device == NULL)
1282
            break;
1283

1284 1285
        parent_sysfs_path = udev_device_get_syspath(parent_device);
        if (parent_sysfs_path == NULL) {
1286 1287 1288
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get syspath for parent of '%s'"),
                           udev_device_get_syspath(parent_device));
1289
            goto cleanup;
1290 1291
        }

1292 1293
        if ((obj = virNodeDeviceObjListFindBySysfsPath(driver->devs,
                                                       parent_sysfs_path))) {
1294
            objdef = virNodeDeviceObjGetDef(obj);
1295
            if (VIR_STRDUP(def->parent, objdef->name) < 0) {
1296
                virNodeDeviceObjEndAPI(&obj);
1297
                goto cleanup;
1298
            }
1299
            virNodeDeviceObjEndAPI(&obj);
1300

1301
            if (VIR_STRDUP(def->parent_sysfs_path, parent_sysfs_path) < 0)
1302
                goto cleanup;
1303 1304 1305 1306
        }

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

1307
    if (!def->parent && VIR_STRDUP(def->parent, "computer") < 0)
1308
        goto cleanup;
1309 1310 1311

    ret = 0;

1312
 cleanup:
1313 1314 1315 1316
    return ret;
}


1317 1318
static int
udevAddOneDevice(struct udev_device *device)
1319 1320
{
    virNodeDeviceDefPtr def = NULL;
1321
    virNodeDeviceObjPtr obj = NULL;
1322
    virNodeDeviceDefPtr objdef;
1323 1324
    virObjectEventPtr event = NULL;
    bool new_device = true;
1325 1326
    int ret = -1;

1327
    if (VIR_ALLOC(def) != 0)
1328
        goto cleanup;
1329

1330
    if (VIR_STRDUP(def->sysfs_path, udev_device_get_syspath(device)) < 0)
1331
        goto cleanup;
1332

1333
    if (udevGetStringProperty(device, "DRIVER", &def->driver) < 0)
1334
        goto cleanup;
1335

1336
    if (VIR_ALLOC(def->caps) != 0)
1337
        goto cleanup;
1338

1339
    if (udevGetDeviceType(device, &def->caps->data.type) != 0)
1340
        goto cleanup;
1341

1342 1343 1344
    if (udevGetDeviceNodes(device, def) != 0)
        goto cleanup;

1345
    if (udevGetDeviceDetails(device, def) != 0)
1346
        goto cleanup;
1347

1348
    if (udevSetParent(device, def) != 0)
1349
        goto cleanup;
1350

1351
    if ((obj = virNodeDeviceObjListFindByName(driver->devs, def->name))) {
1352
        virNodeDeviceObjEndAPI(&obj);
1353 1354 1355
        new_device = false;
    }

1356 1357
    /* If this is a device change, the old definition will be freed
     * and the current definition will take its place. */
1358
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1359
        goto cleanup;
1360
    objdef = virNodeDeviceObjGetDef(obj);
1361

1362
    if (new_device)
1363
        event = virNodeDeviceEventLifecycleNew(objdef->name,
1364 1365
                                               VIR_NODE_DEVICE_EVENT_CREATED,
                                               0);
1366
    else
1367
        event = virNodeDeviceEventUpdateNew(objdef->name);
1368

1369
    virNodeDeviceObjEndAPI(&obj);
1370 1371 1372

    ret = 0;

1373
 cleanup:
1374
    virObjectEventStateQueue(driver->nodeDeviceEventState, event);
1375

1376
    if (ret != 0) {
1377
        VIR_DEBUG("Discarding device %d %p %s", ret, def,
1378
                  def ? NULLSTR(def->sysfs_path) : "");
1379 1380 1381
        virNodeDeviceDefFree(def);
    }

1382 1383 1384 1385
    return ret;
}


1386 1387 1388
static int
udevProcessDeviceListEntry(struct udev *udev,
                           struct udev_list_entry *list_entry)
1389 1390 1391 1392 1393 1394 1395 1396
{
    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);
1397

1398 1399
    if (device != NULL) {
        if (udevAddOneDevice(device) != 0) {
1400 1401
            VIR_DEBUG("Failed to create node device for udev device '%s'",
                      name);
1402 1403 1404 1405
        }
        ret = 0;
    }

1406 1407
    udev_device_unref(device);

1408 1409 1410 1411
    return ret;
}


1412 1413 1414 1415 1416 1417 1418 1419
/* 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",
};

1420 1421
static int
udevEnumerateAddMatches(struct udev_enumerate *udev_enumerate)
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
{
    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;
}


1436 1437
static int
udevEnumerateDevices(struct udev *udev)
1438 1439 1440
{
    struct udev_enumerate *udev_enumerate = NULL;
    struct udev_list_entry *list_entry = NULL;
1441
    int ret = -1;
1442 1443

    udev_enumerate = udev_enumerate_new(udev);
1444 1445
    if (udevEnumerateAddMatches(udev_enumerate) < 0)
        goto cleanup;
1446

1447 1448
    if (udev_enumerate_scan_devices(udev_enumerate) < 0)
        VIR_WARN("udev scan devices failed");
1449 1450 1451 1452 1453 1454 1455

    udev_list_entry_foreach(list_entry,
                            udev_enumerate_get_list_entry(udev_enumerate)) {

        udevProcessDeviceListEntry(udev, list_entry);
    }

1456
    ret = 0;
1457
 cleanup:
1458 1459 1460 1461 1462
    udev_enumerate_unref(udev_enumerate);
    return ret;
}


1463 1464
static void
udevPCITranslateDeinit(void)
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
{
#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;
}


1476 1477
static int
nodeStateCleanup(void)
1478
{
1479 1480
    udevEventDataPtr priv = NULL;

J
Ján Tomko 已提交
1481 1482
    if (!driver)
        return -1;
1483

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    priv = driver->privateData;
    if (priv) {
        virObjectLock(priv);
        priv->threadQuit = true;
        virCondSignal(&priv->threadCond);
        virObjectUnlock(priv);
        virThreadJoin(&priv->th);
    }

    virObjectUnref(priv);
1494
    virObjectUnref(driver->nodeDeviceEventState);
1495

1496
    virNodeDeviceObjListFree(driver->devs);
J
Ján Tomko 已提交
1497 1498
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
1499

J
Ján Tomko 已提交
1500 1501
    udevPCITranslateDeinit();
    return 0;
1502 1503 1504
}


1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
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;
}


1522 1523 1524
/* the caller must be holding the udevEventData object lock prior to calling
 * this function
 */
1525
static bool
1526
udevEventMonitorSanityCheck(udevEventDataPtr priv,
1527
                            int fd)
1528
{
1529
    int rc = -1;
1530

1531
    rc = udev_monitor_get_fd(priv->udev_monitor);
1532
    if (fd != rc) {
1533 1534 1535
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("File descriptor returned by udev %d does not "
                         "match node device file descriptor %d"),
1536
                       fd, rc);
1537 1538 1539 1540 1541 1542 1543 1544

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

1545
        return false;
1546 1547
    }

1548 1549 1550 1551
    return true;
}


1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
/**
 * udevEventHandleThread
 * @opaque: unused
 *
 * Thread to handle the udevEventHandleCallback processing when udev
 * tells us there's a device change for us (add, modify, delete, etc).
 *
 * Once notified there is data to be processed, the actual @device
 * data retrieval by libudev may be delayed due to how threads are
 * scheduled. In fact, the event loop could be scheduled earlier than
 * the handler thread, thus potentially emitting the very same event
 * the handler thread is currently trying to process, simply because
 * the data hadn't been retrieved from the socket.
 *
 * NB: Some older distros, such as CentOS 6, libudev opens sockets
 * without the NONBLOCK flag which might cause issues with event
 * based algorithm. Although the issue can be mitigated by resetting
 * priv->dataReady for each event found; however, the scheduler issues
 * would still come into play.
 */
1572
static void
1573
udevEventHandleThread(void *opaque ATTRIBUTE_UNUSED)
1574
{
1575
    udevEventDataPtr priv = driver->privateData;
1576 1577
    struct udev_device *device = NULL;

1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    /* continue rather than break from the loop on non-fatal errors */
    while (1) {
        virObjectLock(priv);
        while (!priv->dataReady && !priv->threadQuit) {
            if (virCondWait(&priv->threadCond, &priv->parent.lock)) {
                virReportSystemError(errno, "%s",
                                     _("handler failed to wait on condition"));
                virObjectUnlock(priv);
                return;
            }
        }

        if (priv->threadQuit) {
            virObjectUnlock(priv);
            return;
        }
1594

1595 1596
        errno = 0;
        device = udev_monitor_receive_device(priv->udev_monitor);
1597 1598
        virObjectUnlock(priv);

1599 1600 1601 1602 1603 1604
        if (!device) {
            if (errno == 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to receive device from udev monitor"));
                return;
            }
1605

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
            /* POSIX allows both EAGAIN and EWOULDBLOCK to be used
             * interchangeably when the read would block or timeout was fired
             */
            VIR_WARNINGS_NO_WLOGICALOP_EQUAL_EXPR
            if (errno != EAGAIN && errno != EWOULDBLOCK) {
            VIR_WARNINGS_RESET
                virReportSystemError(errno, "%s",
                                     _("failed to receive device from udev "
                                       "monitor"));
                return;
            }
1617

1618 1619 1620
            /* Trying to move the reset of the @priv->dataReady flag to
             * after the udev_monitor_receive_device wouldn't help much
             * due to event mgmt and scheduler timing. */
1621 1622 1623 1624 1625 1626 1627 1628 1629
            virObjectLock(priv);
            priv->dataReady = false;
            virObjectUnlock(priv);

            continue;
        }

        udevHandleOneDevice(device);
        udev_device_unref(device);
1630 1631 1632 1633 1634

        /* Instead of waiting for the next event after processing @device
         * data, let's keep reading from the udev monitor and only wait
         * for the next event once either a EAGAIN or a EWOULDBLOCK error
         * is encountered. */
1635
    }
1636 1637 1638
}


1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
static void
udevEventHandleCallback(int watch ATTRIBUTE_UNUSED,
                        int fd,
                        int events ATTRIBUTE_UNUSED,
                        void *data ATTRIBUTE_UNUSED)
{
    udevEventDataPtr priv = driver->privateData;

    virObjectLock(priv);

1649 1650 1651 1652 1653 1654 1655
    if (!udevEventMonitorSanityCheck(priv, fd))
        priv->threadQuit = true;
    else
        priv->dataReady = true;

    virCondSignal(&priv->threadCond);
    virObjectUnlock(priv);
1656 1657 1658
}


1659 1660
/* DMI is intel-compatible specific */
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1661
static void
1662
udevGetDMIData(virNodeDevCapSystemPtr syscap)
1663
{
1664
    udevEventDataPtr priv = driver->privateData;
1665 1666
    struct udev *udev = NULL;
    struct udev_device *device = NULL;
1667 1668
    virNodeDevCapSystemHardwarePtr hardware = &syscap->hardware;
    virNodeDevCapSystemFirmwarePtr firmware = &syscap->firmware;
1669

1670
    virObjectLock(priv);
1671
    udev = udev_monitor_get_udev(priv->udev_monitor);
1672

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

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

1699
    if (virGetHostUUID(hardware->uuid))
1700
        goto cleanup;
1701

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

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


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

1727 1728
    if (VIR_ALLOC(def) < 0)
        return -1;
1729

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

1733
    if (VIR_ALLOC(def->caps) != 0)
1734
        goto cleanup;
1735

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

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

1743
    virNodeDeviceObjEndAPI(&obj);
1744 1745 1746

    ret = 0;

1747
 cleanup:
1748
    if (ret == -1)
1749 1750
        virNodeDeviceDefFree(def);

1751 1752 1753
    return ret;
}

1754

1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
static void
nodeStateInitializeEnumerate(void *opaque)
{
    struct udev *udev = opaque;
    udevEventDataPtr priv = driver->privateData;

    /* Populate with known devices */
    if (udevEnumerateDevices(udev) != 0)
        goto error;

    return;

 error:
    virObjectLock(priv);
1769 1770
    ignore_value(virEventRemoveHandle(priv->watch));
    priv->watch = -1;
1771
    priv->threadQuit = true;
1772
    virCondSignal(&priv->threadCond);
1773 1774 1775 1776
    virObjectUnlock(priv);
}


1777 1778
static int
udevPCITranslateInit(bool privileged ATTRIBUTE_UNUSED)
1779
{
1780 1781 1782 1783
#if defined __s390__ || defined __s390x_
    /* On s390(x) system there is no PCI bus.
     * Therefore there is nothing to initialize here. */
#else
1784
    int rc;
1785

1786
    if ((rc = pci_system_init()) != 0) {
1787 1788 1789
        /* 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.  */
1790
        if (errno != ENOENT && (privileged  || errno != EACCES)) {
1791 1792
            virReportSystemError(rc, "%s",
                                 _("Failed to initialize libpciaccess"));
1793
            return -1;
1794
        }
1795
    }
1796
#endif
1797 1798 1799
    return 0;
}

1800 1801 1802 1803 1804

static int
nodeStateInitialize(bool privileged,
                    virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                    void *opaque ATTRIBUTE_UNUSED)
1805
{
1806
    udevEventDataPtr priv = NULL;
1807
    struct udev *udev = NULL;
1808
    virThread enumThread;
1809

1810
    if (VIR_ALLOC(driver) < 0)
1811
        return -1;
1812

1813
    if (virMutexInit(&driver->lock) < 0) {
1814 1815
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to initialize mutex"));
1816
        VIR_FREE(driver);
1817
        return -1;
1818 1819
    }

1820 1821
    driver->privileged = privileged;

1822 1823
    if (!(driver->devs = virNodeDeviceObjListNew()) ||
        !(priv = udevEventDataNew()))
1824
        goto cleanup;
1825

1826
    driver->privateData = priv;
1827
    driver->nodeDeviceEventState = virObjectEventStateNew();
1828

1829
    if (udevPCITranslateInit(privileged) < 0)
1830
        goto cleanup;
1831

1832
    udev = udev_new();
1833 1834 1835
    if (!udev) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create udev context"));
1836
        goto cleanup;
1837
    }
1838

1839 1840
    virObjectLock(priv);

1841
    priv->udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
1842
    if (!priv->udev_monitor) {
1843 1844
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("udev_monitor_new_from_netlink returned NULL"));
1845
        goto unlock;
1846 1847
    }

1848
    udev_monitor_enable_receiving(priv->udev_monitor);
1849

1850 1851 1852 1853 1854 1855 1856
    /* 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);

1857 1858 1859 1860 1861 1862
    if (virThreadCreate(&priv->th, true, udevEventHandleThread, NULL) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to create udev handler thread"));
        goto unlock;
    }

1863 1864 1865 1866 1867 1868 1869 1870
    /* 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.  */
1871 1872 1873
    priv->watch = virEventAddHandle(udev_monitor_get_fd(priv->udev_monitor),
                                    VIR_EVENT_HANDLE_READABLE,
                                    udevEventHandleCallback, NULL, NULL);
1874
    if (priv->watch == -1)
1875
        goto unlock;
1876

1877 1878
    virObjectUnlock(priv);

1879
    /* Create a fictional 'computer' device to root the device tree. */
1880
    if (udevSetupSystemDev() != 0)
1881
        goto cleanup;
1882

1883 1884 1885 1886
    if (virThreadCreate(&enumThread, false, nodeStateInitializeEnumerate,
                        udev) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to create udev enumerate thread"));
1887
        goto cleanup;
1888
    }
1889

1890
    return 0;
1891

1892
 cleanup:
1893 1894
    nodeStateCleanup();
    return -1;
1895 1896

 unlock:
1897
    virObjectUnlock(priv);
1898
    goto cleanup;
1899 1900 1901
}


1902 1903
static int
nodeStateReload(void)
1904 1905 1906 1907 1908
{
    return 0;
}


1909
static virNodeDeviceDriver udevNodeDeviceDriver = {
1910
    .name = "udev",
1911 1912
    .nodeNumOfDevices = nodeNumOfDevices, /* 0.7.3 */
    .nodeListDevices = nodeListDevices, /* 0.7.3 */
1913
    .connectListAllNodeDevices = nodeConnectListAllNodeDevices, /* 0.10.2 */
1914 1915
    .connectNodeDeviceEventRegisterAny = nodeConnectNodeDeviceEventRegisterAny, /* 2.2.0 */
    .connectNodeDeviceEventDeregisterAny = nodeConnectNodeDeviceEventDeregisterAny, /* 2.2.0 */
1916 1917 1918 1919 1920 1921 1922 1923
    .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 */
1924 1925
};

1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937

static virHypervisorDriver udevHypervisorDriver = {
    .name = "nodedev",
    .connectOpen = nodeConnectOpen, /* 4.1.0 */
    .connectClose = nodeConnectClose, /* 4.1.0 */
    .connectIsEncrypted = nodeConnectIsEncrypted, /* 4.1.0 */
    .connectIsSecure = nodeConnectIsSecure, /* 4.1.0 */
    .connectIsAlive = nodeConnectIsAlive, /* 4.1.0 */
};


static virConnectDriver udevConnectDriver = {
1938
    .localOnly = true,
1939
    .uriSchemes = (const char *[]){ "nodedev", NULL },
1940 1941 1942 1943 1944
    .hypervisorDriver = &udevHypervisorDriver,
    .nodeDeviceDriver = &udevNodeDeviceDriver,
};


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

1952 1953 1954

int
udevNodeRegister(void)
1955
{
1956
    VIR_DEBUG("Registering udev node device backend");
1957

1958 1959
    if (virRegisterConnectDriver(&udevConnectDriver, false) < 0)
        return -1;
1960
    if (virSetSharedNodeDeviceDriver(&udevNodeDeviceDriver) < 0)
1961 1962 1963 1964
        return -1;

    return virRegisterStateDriver(&udevStateDriver);
}