node_device_udev.c 54.7 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 "node_device_conf.h"
27
#include "node_device_event.h"
28
#include "node_device_driver.h"
29 30
#include "node_device_udev.h"
#include "virerror.h"
31 32
#include "driver.h"
#include "datatypes.h"
33
#include "virlog.h"
34
#include "viralloc.h"
35
#include "viruuid.h"
36
#include "virbuffer.h"
37
#include "virfile.h"
38
#include "virpci.h"
39
#include "virpidfile.h"
40
#include "virstring.h"
41
#include "virnetdev.h"
42
#include "virmdev.h"
43

44 45
#include "configmake.h"

46 47
#define VIR_FROM_THIS VIR_FROM_NODEDEV

48 49
VIR_LOG_INIT("node_device.node_device_udev");

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

54 55 56 57 58 59
typedef struct _udevEventData udevEventData;
typedef udevEventData *udevEventDataPtr;

struct _udevEventData {
    virObjectLockable parent;

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

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

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
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);
87 88

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


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

    return 0;
}

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

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

    if (udevEventDataInitialize() < 0)
        return NULL;

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

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

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

123

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

    return false;
}


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

141
    ret = udev_device_get_property_value(udev_device, property_key);
142

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

    return ret;
}


150 151 152 153
static int
udevGetStringProperty(struct udev_device *udev_device,
                      const char *property_key,
                      char **value)
154
{
155
    *value = g_strdup(udevGetDeviceProperty(udev_device, property_key));
156

157
    return 0;
158 159 160
}


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

169
    str = udevGetDeviceProperty(udev_device, property_key);
170

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


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

188
    str = udevGetDeviceProperty(udev_device, property_key);
189

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


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

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

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


215 216 217 218
static int
udevGetStringSysfsAttr(struct udev_device *udev_device,
                       const char *attr_name,
                       char **value)
219
{
220
    *value = g_strdup(udevGetDeviceSysfsAttr(udev_device, attr_name));
221

222
    virStringStripControlChars(*value);
223

224 225
    if (*value != NULL && (STREQ(*value, "")))
        VIR_FREE(*value);
226

227
    return 0;
228 229 230
}


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

239
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
240

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

247
    return 0;
248 249 250
}


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

259
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
260

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

267
    return 0;
268 269 270
}


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

278
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
279

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

J
Ján Tomko 已提交
286
    return 0;
287 288 289
}


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

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

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

    def->name = virBufferContentAndReset(&buf);

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

312
    return 0;
313 314
}

315 316 317 318 319 320

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

340 341
    *vendor_string = g_strdup(vendor_name);
    *product_string = g_strdup(device_name);
342

343
    return 0;
344 345 346
}


347 348 349
static int
udevProcessPCI(struct udev_device *device,
               virNodeDeviceDefPtr def)
350
{
351
    virNodeDevCapPCIDevPtr pci_dev = &def->caps->data.pci_dev;
352 353
    virPCIEDeviceInfoPtr pci_express = NULL;
    virPCIDevicePtr pciDev = NULL;
354
    int ret = -1;
355
    char *p;
356 357 358 359 360
    bool privileged;

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

362 363
    pci_dev->klass = -1;
    if (udevGetIntProperty(device, "PCI_CLASS", &pci_dev->klass, 16) < 0)
364
        goto cleanup;
365

366
    if ((p = strrchr(def->sysfs_path, '/')) == NULL ||
367 368 369 370
        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) {
371 372
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the PCI address from sysfs path: '%s'"),
373
                       def->sysfs_path);
374
        goto cleanup;
375 376
    }

377
    if (udevGetUintSysfsAttr(device, "vendor", &pci_dev->vendor, 16) < 0)
378
        goto cleanup;
379

380
    if (udevGetUintSysfsAttr(device, "device", &pci_dev->product, 16) < 0)
381
        goto cleanup;
382

383 384 385 386
    if (udevTranslatePCIIds(pci_dev->vendor,
                            pci_dev->product,
                            &pci_dev->vendor_name,
                            &pci_dev->product_name) != 0) {
387
        goto cleanup;
388
    }
389

390
    if (udevGenerateDeviceName(device, def, NULL) != 0)
391
        goto cleanup;
392

393 394
    /* The default value is -1, because it can't be 0
     * as zero is valid node number. */
395
    pci_dev->numa_node = -1;
396
    if (udevGetIntSysfsAttr(device, "numa_node",
397
                            &pci_dev->numa_node, 10) < 0)
398
        goto cleanup;
399

400
    if (virNodeDeviceGetPCIDynamicCaps(def->sysfs_path, pci_dev) < 0)
401
        goto cleanup;
402

403 404 405 406
    if (!(pciDev = virPCIDeviceNew(pci_dev->domain,
                                   pci_dev->bus,
                                   pci_dev->slot,
                                   pci_dev->function)))
407
        goto cleanup;
408

409
    /* We need to be root to read PCI device configs */
410
    if (privileged) {
411
        if (virPCIGetHeaderType(pciDev, &pci_dev->hdrType) < 0)
412
            goto cleanup;
413

414 415
        if (virPCIDeviceIsPCIExpress(pciDev) > 0) {
            if (VIR_ALLOC(pci_express) < 0)
416
                goto cleanup;
417

418 419 420
            if (virPCIDeviceHasPCIExpressLink(pciDev) > 0) {
                if (VIR_ALLOC(pci_express->link_cap) < 0 ||
                    VIR_ALLOC(pci_express->link_sta) < 0)
421
                    goto cleanup;
422 423 424 425 426 427 428

                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)
429
                    goto cleanup;
430 431 432

                pci_express->link_sta->port = -1; /* PCIe can't negotiate port. Yet :) */
            }
433 434
            pci_dev->flags |= VIR_NODE_DEV_CAP_FLAG_PCIE;
            pci_dev->pci_express = pci_express;
435
            pci_express = NULL;
436 437 438
        }
    }

439 440
    ret = 0;

441
 cleanup:
442
    virPCIDeviceFree(pciDev);
443
    virPCIEDeviceInfoFree(pci_express);
444 445 446
    return ret;
}

447 448 449

static int
drmGetMinorType(int minor)
M
Marc-André Lureau 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
{
    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;
    }
}

466 467 468 469

static int
udevProcessDRMDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
M
Marc-André Lureau 已提交
470
{
471
    virNodeDevCapDRMPtr drm = &def->caps->data.drm;
M
Marc-André Lureau 已提交
472 473 474 475 476 477 478 479 480 481 482
    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;

483
    drm->type = minor;
M
Marc-André Lureau 已提交
484 485 486

    return 0;
}
487

488 489 490 491

static int
udevProcessUSBDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
492
{
493
    virNodeDevCapUSBDevPtr usb_dev = &def->caps->data.usb_dev;
494

495
    if (udevGetUintProperty(device, "BUSNUM", &usb_dev->bus, 10) < 0)
496
        return -1;
497
    if (udevGetUintProperty(device, "DEVNUM", &usb_dev->device, 10) < 0)
498
        return -1;
499
    if (udevGetUintProperty(device, "ID_VENDOR_ID", &usb_dev->vendor, 16) < 0)
500
        return -1;
501

502 503
    if (udevGetStringProperty(device,
                              "ID_VENDOR_FROM_DATABASE",
504
                              &usb_dev->vendor_name) < 0)
505
        return -1;
506

507
    if (!usb_dev->vendor_name &&
508
        udevGetStringSysfsAttr(device, "manufacturer",
509
                               &usb_dev->vendor_name) < 0)
510
        return -1;
511

512
    if (udevGetUintProperty(device, "ID_MODEL_ID", &usb_dev->product, 16) < 0)
513
        return -1;
514

515 516
    if (udevGetStringProperty(device,
                              "ID_MODEL_FROM_DATABASE",
517
                              &usb_dev->product_name) < 0)
518
        return -1;
519

520
    if (!usb_dev->product_name &&
521
        udevGetStringSysfsAttr(device, "product",
522
                               &usb_dev->product_name) < 0)
523
        return -1;
524

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

528
    return 0;
529 530 531
}


532 533 534
static int
udevProcessUSBInterface(struct udev_device *device,
                        virNodeDeviceDefPtr def)
535
{
536
    virNodeDevCapUSBIfPtr usb_if = &def->caps->data.usb_if;
537

538
    if (udevGetUintSysfsAttr(device, "bInterfaceNumber",
539
                             &usb_if->number, 16) < 0)
540
        return -1;
541

542
    if (udevGetUintSysfsAttr(device, "bInterfaceClass",
543
                             &usb_if->klass, 16) < 0)
544
        return -1;
545

546
    if (udevGetUintSysfsAttr(device, "bInterfaceSubClass",
547
                             &usb_if->subclass, 16) < 0)
548
        return -1;
549

550
    if (udevGetUintSysfsAttr(device, "bInterfaceProtocol",
551
                             &usb_if->protocol, 16) < 0)
552
        return -1;
553

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

557
    return 0;
558 559 560
}


561 562 563
static int
udevProcessNetworkInterface(struct udev_device *device,
                            virNodeDeviceDefPtr def)
564
{
D
David Allan 已提交
565
    const char *devtype = udev_device_get_devtype(device);
566
    virNodeDevCapNetPtr net = &def->caps->data.net;
567

D
David Allan 已提交
568
    if (devtype && STREQ(devtype, "wlan")) {
569
        net->subtype = VIR_NODE_DEV_CAP_NET_80211;
D
David Allan 已提交
570
    } else {
571
        net->subtype = VIR_NODE_DEV_CAP_NET_80203;
D
David Allan 已提交
572 573
    }

574 575
    if (udevGetStringProperty(device,
                              "INTERFACE",
576
                              &net->ifname) < 0)
577
        return -1;
578

579
    if (udevGetStringSysfsAttr(device, "address",
580
                               &net->address) < 0)
581
        return -1;
582

583
    if (udevGetUintSysfsAttr(device, "addr_len", &net->address_len, 0) < 0)
584
        return -1;
585

586
    if (udevGenerateDeviceName(device, def, net->address) != 0)
587
        return -1;
588

589
    if (virNetDevGetLinkInfo(net->ifname, &net->lnk) < 0)
590
        return -1;
591

592
    if (virNetDevGetFeatures(net->ifname, &net->features) < 0)
593
        return -1;
594

595
    return 0;
596 597 598
}


599
static int
J
Ján Tomko 已提交
600
udevProcessSCSIHost(struct udev_device *device G_GNUC_UNUSED,
601
                    virNodeDeviceDefPtr def)
602
{
603
    virNodeDevCapSCSIHostPtr scsi_host = &def->caps->data.scsi_host;
604
    g_autofree char *filename = NULL;
J
Ján Tomko 已提交
605
    char *str;
606

607
    filename = g_path_get_basename(def->sysfs_path);
608

609
    if (!(str = STRSKIP(filename, "host")) ||
610
        virStrToLong_ui(str, NULL, 0, &scsi_host->host) < 0) {
611 612 613
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse SCSI host '%s'"),
                       filename);
614
        return -1;
615 616
    }

617
    virNodeDeviceGetSCSIHostCaps(&def->caps->data.scsi_host);
618

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

622
    return 0;
623 624 625
}


626 627 628
static int
udevProcessSCSITarget(struct udev_device *device,
                      virNodeDeviceDefPtr def)
D
David Allan 已提交
629 630
{
    const char *sysname = NULL;
631
    virNodeDevCapSCSITargetPtr scsi_target = &def->caps->data.scsi_target;
D
David Allan 已提交
632 633 634

    sysname = udev_device_get_sysname(device);

635
    scsi_target->name = g_strdup(sysname);
D
David Allan 已提交
636

637
    virNodeDeviceGetSCSITargetCaps(def->sysfs_path, &def->caps->data.scsi_target);
638

639
    if (udevGenerateDeviceName(device, def, NULL) != 0)
640
        return -1;
D
David Allan 已提交
641

642
    return 0;
D
David Allan 已提交
643 644 645
}


646
static int
J
Ján Tomko 已提交
647
udevGetSCSIType(virNodeDeviceDefPtr def G_GNUC_UNUSED,
648 649
                unsigned int type,
                char **typestring)
650 651 652 653 654 655 656 657
{
    int ret = 0;
    int foundtype = 1;

    *typestring = NULL;

    switch (type) {
    case TYPE_DISK:
658
        *typestring = g_strdup("disk");
659 660
        break;
    case TYPE_TAPE:
661
        *typestring = g_strdup("tape");
662 663
        break;
    case TYPE_PROCESSOR:
664
        *typestring = g_strdup("processor");
665 666
        break;
    case TYPE_WORM:
667
        *typestring = g_strdup("worm");
668 669
        break;
    case TYPE_ROM:
670
        *typestring = g_strdup("cdrom");
671 672
        break;
    case TYPE_SCANNER:
673
        *typestring = g_strdup("scanner");
674 675
        break;
    case TYPE_MOD:
676
        *typestring = g_strdup("mod");
677 678
        break;
    case TYPE_MEDIUM_CHANGER:
679
        *typestring = g_strdup("changer");
680 681
        break;
    case TYPE_ENCLOSURE:
682
        *typestring = g_strdup("enclosure");
683
        break;
684
    case TYPE_RAID:
685
        *typestring = g_strdup("raid");
686
        break;
687 688 689 690 691 692 693 694 695 696
    case TYPE_NO_LUN:
    default:
        foundtype = 0;
        break;
    }

    if (*typestring == NULL) {
        if (foundtype == 1) {
            ret = -1;
        } else {
697 698
            VIR_DEBUG("Failed to find SCSI device type %d for %s",
                      type, def->sysfs_path);
699 700 701 702 703 704 705
        }
    }

    return ret;
}


706
static int
J
Ján Tomko 已提交
707
udevProcessSCSIDevice(struct udev_device *device G_GNUC_UNUSED,
708
                      virNodeDeviceDefPtr def)
709 710 711
{
    int ret = -1;
    unsigned int tmp = 0;
712
    virNodeDevCapSCSIPtr scsi = &def->caps->data.scsi;
713 714
    g_autofree char *filename = NULL;
    char *p = NULL;
715

716
    filename = g_path_get_basename(def->sysfs_path);
717

718 719 720 721
    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) {
722 723 724 725
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the SCSI address from filename: '%s'"),
                       filename);
        return -1;
726 727
    }

728 729
    if (udev_device_get_sysattr_value(device, "type")) {
        if (udevGetUintSysfsAttr(device, "type", &tmp, 0) < 0)
730
            goto cleanup;
731

732
        if (udevGetSCSIType(def, tmp, &scsi->type) < 0)
733
            goto cleanup;
734 735
    }

736
    if (udevGenerateDeviceName(device, def, NULL) != 0)
737
        goto cleanup;
738 739 740

    ret = 0;

741
 cleanup:
742
    if (ret != 0) {
743 744 745
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to process SCSI device with sysfs path '%s'"),
                       def->sysfs_path);
746 747 748 749 750
    }
    return ret;
}


751 752 753
static int
udevProcessDisk(struct udev_device *device,
                virNodeDeviceDefPtr def)
754
{
755
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
756

757
    if (udevGetUint64SysfsAttr(device, "size", &storage->num_blocks) < 0)
758
        return -1;
759

J
Ján Tomko 已提交
760
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
761
                               &storage->logical_block_size) < 0)
762
        return -1;
763

764
    storage->size = storage->num_blocks * storage->logical_block_size;
765

766
    return 0;
767 768 769
}


770 771 772 773
static int
udevProcessRemoveableMedia(struct udev_device *device,
                           virNodeDeviceDefPtr def,
                           int has_media)
774
{
775
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
J
Ján Tomko 已提交
776
    int is_removable = 0;
777

778 779 780
    if (udevGetIntSysfsAttr(device, "removable", &is_removable, 0) < 0)
        return -1;
    if (is_removable == 1)
781 782
        def->caps->data.storage.flags |= VIR_NODE_DEV_CAP_STORAGE_REMOVABLE;

J
Ján Tomko 已提交
783 784
    if (!has_media)
        return 0;
785

J
Ján Tomko 已提交
786 787
    def->caps->data.storage.flags |=
        VIR_NODE_DEV_CAP_STORAGE_REMOVABLE_MEDIA_AVAILABLE;
788

J
Ján Tomko 已提交
789
    if (udevGetStringProperty(device, "ID_FS_LABEL",
790
                              &storage->media_label) < 0)
J
Ján Tomko 已提交
791
        return -1;
792

J
Ján Tomko 已提交
793
    if (udevGetUint64SysfsAttr(device, "size",
794
                               &storage->num_blocks) < 0)
J
Ján Tomko 已提交
795
        return -1;
796

J
Ján Tomko 已提交
797
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
798
                               &storage->logical_block_size) < 0)
J
Ján Tomko 已提交
799
        return -1;
800

J
Ján Tomko 已提交
801 802 803 804 805 806 807
    /* 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;
808

J
Ján Tomko 已提交
809
    return 0;
810 811
}

812 813 814 815

static int
udevProcessCDROM(struct udev_device *device,
                 virNodeDeviceDefPtr def)
816 817 818 819 820 821 822 823
{
    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);
824
    def->caps->data.storage.drive_type = g_strdup("cdrom");
825

826 827
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA") &&
        udevGetIntProperty(device, "ID_CDROM_MEDIA", &has_media, 0) < 0)
828
        return -1;
829

830
    return udevProcessRemoveableMedia(device, def, has_media);
831 832
}

833 834 835 836

static int
udevProcessFloppy(struct udev_device *device,
                  virNodeDeviceDefPtr def)
837 838 839
{
    int has_media = 0;

840
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA")) {
841
        /* USB floppy */
842 843
        if (udevGetIntProperty(device, "DKD_MEDIA_AVAILABLE", &has_media, 0) < 0)
            return -1;
844
    } else if (udevHasDeviceProperty(device, "ID_FS_LABEL")) {
845 846 847 848 849 850
        /* Legacy floppy */
        has_media = 1;
    }

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

852

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

J
Ján Tomko 已提交
859
    if (udevGetUint64SysfsAttr(device, "size",
860
                               &storage->num_blocks) < 0)
861
        return -1;
862

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

867
    storage->size = storage->num_blocks * storage->logical_block_size;
868

869
    return 0;
870 871 872
}


873 874 875 876
/* 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. */
877 878
static int
udevKludgeStorageType(virNodeDeviceDefPtr def)
879
{
880 881 882
    VIR_DEBUG("Could not find definitive storage type for device "
              "with sysfs path '%s', trying to guess it",
              def->sysfs_path);
883

884
    /* virtio disk */
885 886
    if (STRPREFIX(def->caps->data.storage.block, "/dev/vd")) {
        def->caps->data.storage.drive_type = g_strdup("disk");
887
        VIR_DEBUG("Found storage type '%s' for device "
888
                  "with sysfs path '%s'",
889 890
                  def->caps->data.storage.drive_type,
                  def->sysfs_path);
891
        return 0;
892
    }
893 894 895
    VIR_DEBUG("Could not determine storage type "
              "for device with sysfs path '%s'", def->sysfs_path);
    return -1;
896 897 898
}


899 900 901
static int
udevProcessStorage(struct udev_device *device,
                   virNodeDeviceDefPtr def)
902
{
903
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
904
    int ret = -1;
905
    const char* devnode;
906

907
    devnode = udev_device_get_devnode(device);
908
    if (!devnode) {
909
        VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device));
910
        goto cleanup;
911
    }
912

913
    storage->block = g_strdup(devnode);
914

915
    if (udevGetStringProperty(device, "ID_BUS", &storage->bus) < 0)
916
        goto cleanup;
917
    if (udevGetStringProperty(device, "ID_SERIAL", &storage->serial) < 0)
918
        goto cleanup;
919

920
    if (udevGetStringSysfsAttr(device, "device/vendor", &storage->vendor) < 0)
921
        goto cleanup;
922 923 924
    if (def->caps->data.storage.vendor)
        virTrimSpaces(def->caps->data.storage.vendor, NULL);

925
    if (udevGetStringSysfsAttr(device, "device/model", &storage->model) < 0)
926
        goto cleanup;
927 928
    if (def->caps->data.storage.model)
        virTrimSpaces(def->caps->data.storage.model, NULL);
929 930 931 932 933
    /* 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. */

934
    if (udevGetStringProperty(device, "ID_TYPE", &storage->drive_type) < 0)
935
        goto cleanup;
936

937
    if (!storage->drive_type ||
938
        STREQ(def->caps->data.storage.drive_type, "generic")) {
939 940
        int val = 0;
        const char *str = NULL;
941 942 943

        /* All floppy drives have the ID_DRIVE_FLOPPY prop. This is
         * needed since legacy floppies don't have a drive_type */
944
        if (udevGetIntProperty(device, "ID_DRIVE_FLOPPY", &val, 0) < 0)
945
            goto cleanup;
946 947
        else if (val == 1)
            str = "floppy";
948

949
        if (!str) {
950
            if (udevGetIntProperty(device, "ID_CDROM", &val, 0) < 0)
951
                goto cleanup;
952 953 954
            else if (val == 1)
                str = "cd";
        }
955

956
        if (!str) {
957
            if (udevGetIntProperty(device, "ID_DRIVE_FLASH_SD", &val, 0) < 0)
958
                goto cleanup;
959 960 961
            if (val == 1)
                str = "sd";
        }
962

963
        if (str) {
964
            storage->drive_type = g_strdup(str);
965 966
        } else {
            /* If udev doesn't have it, perhaps we can guess it. */
967
            if (udevKludgeStorageType(def) != 0)
968
                goto cleanup;
969 970 971 972 973 974 975
        }
    }

    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);
976 977
    } else if (STREQ(def->caps->data.storage.drive_type, "floppy")) {
        ret = udevProcessFloppy(device, def);
978 979
    } else if (STREQ(def->caps->data.storage.drive_type, "sd")) {
        ret = udevProcessSD(device, def);
980
    } else {
981 982
        VIR_DEBUG("Unsupported storage type '%s'",
                  def->caps->data.storage.drive_type);
983
        goto cleanup;
984 985
    }

986
    if (udevGenerateDeviceName(device, def, storage->serial) != 0)
987
        goto cleanup;
988

989
 cleanup:
990
    VIR_DEBUG("Storage ret=%d", ret);
991 992 993
    return ret;
}

994

995
static int
996
udevProcessSCSIGeneric(struct udev_device *dev,
997 998
                       virNodeDeviceDefPtr def)
{
999 1000
    if (udevGetStringProperty(dev, "DEVNAME", &def->caps->data.sg.path) < 0 ||
        !def->caps->data.sg.path)
1001 1002 1003 1004 1005 1006 1007 1008
        return -1;

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

    return 0;
}

1009

1010 1011 1012 1013 1014 1015 1016 1017
static int
udevProcessMediatedDevice(struct udev_device *dev,
                          virNodeDeviceDefPtr def)
{
    int ret = -1;
    const char *uuidstr = NULL;
    int iommugrp = -1;
    char *linkpath = NULL;
1018
    char *canonicalpath = NULL;
1019 1020
    virNodeDevCapMdevPtr data = &def->caps->data.mdev;

1021 1022 1023 1024 1025 1026
    /* 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.
     */

1027
    linkpath = g_strdup_printf("%s/mdev_type", udev_device_get_syspath(dev));
1028

1029 1030 1031 1032 1033 1034 1035
    if (virFileWaitForExists(linkpath, 1, 100) < 0) {
        virReportSystemError(errno,
                             _("failed to wait for file '%s' to appear"),
                             linkpath);
        goto cleanup;
    }

1036 1037
    if (virFileResolveLink(linkpath, &canonicalpath) < 0) {
        virReportSystemError(errno, _("failed to resolve '%s'"), linkpath);
1038
        goto cleanup;
1039
    }
1040

1041
    data->type = g_path_get_basename(canonicalpath);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

    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);
1055
    VIR_FREE(canonicalpath);
1056 1057 1058
    return ret;
}

B
Bjoern Walk 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

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


1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
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);

1099
    def->devnode = g_strdup(devnode);
1100 1101 1102 1103 1104 1105 1106 1107 1108

    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)) {
1109
        def->devlinks[n++] = g_strdup(udev_list_entry_get_name(list_entry));
1110 1111 1112 1113 1114
    }

    return 0;
}

1115

1116 1117
static int
udevGetDeviceType(struct udev_device *device,
1118
                  virNodeDevCapType *type)
1119 1120
{
    const char *devtype = NULL;
1121
    char *subsystem = NULL;
1122
    int ret = -1;
D
David Allan 已提交
1123

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    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 已提交
1142 1143
        else if (STREQ(devtype, "drm_minor"))
            *type = VIR_NODE_DEV_CAP_DRM;
1144 1145
    } else {
        /* PCI devices don't set the DEVTYPE property. */
1146
        if (udevHasDeviceProperty(device, "PCI_CLASS"))
1147
            *type = VIR_NODE_DEV_CAP_PCI_DEV;
1148

1149 1150 1151 1152
        /* 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. */
1153
        if (udevHasDeviceProperty(device, "INTERFACE"))
1154
            *type = VIR_NODE_DEV_CAP_NET;
1155

B
Bjoern Walk 已提交
1156 1157
        /* The following devices do not set the DEVTYPE property, therefore
         * we need to rely on the SUBSYSTEM property */
1158 1159 1160 1161
        if (udevGetStringProperty(device, "SUBSYSTEM", &subsystem) < 0)
            return -1;

        if (STREQ_NULLABLE(subsystem, "scsi_generic"))
1162
            *type = VIR_NODE_DEV_CAP_SCSI_GENERIC;
1163 1164
        else if (STREQ_NULLABLE(subsystem, "mdev"))
            *type = VIR_NODE_DEV_CAP_MDEV;
B
Bjoern Walk 已提交
1165 1166
        else if (STREQ_NULLABLE(subsystem, "ccw"))
            *type = VIR_NODE_DEV_CAP_CCW_DEV;
1167

1168
        VIR_FREE(subsystem);
1169 1170
    }

1171 1172 1173 1174 1175 1176
    if (!*type)
        VIR_DEBUG("Could not determine device type for device "
                  "with sysfs name '%s'",
                  udev_device_get_sysname(device));
    else
        ret = 0;
1177 1178 1179 1180 1181

    return ret;
}


1182 1183 1184
static int
udevGetDeviceDetails(struct udev_device *device,
                     virNodeDeviceDefPtr def)
1185
{
1186
    switch (def->caps->data.type) {
1187
    case VIR_NODE_DEV_CAP_PCI_DEV:
1188
        return udevProcessPCI(device, def);
1189
    case VIR_NODE_DEV_CAP_USB_DEV:
1190
        return udevProcessUSBDevice(device, def);
1191
    case VIR_NODE_DEV_CAP_USB_INTERFACE:
1192
        return udevProcessUSBInterface(device, def);
1193
    case VIR_NODE_DEV_CAP_NET:
1194
        return udevProcessNetworkInterface(device, def);
1195
    case VIR_NODE_DEV_CAP_SCSI_HOST:
1196
        return udevProcessSCSIHost(device, def);
D
David Allan 已提交
1197
    case VIR_NODE_DEV_CAP_SCSI_TARGET:
1198
        return udevProcessSCSITarget(device, def);
1199
    case VIR_NODE_DEV_CAP_SCSI:
1200
        return udevProcessSCSIDevice(device, def);
1201
    case VIR_NODE_DEV_CAP_STORAGE:
1202
        return udevProcessStorage(device, def);
1203
    case VIR_NODE_DEV_CAP_SCSI_GENERIC:
1204
        return udevProcessSCSIGeneric(device, def);
M
Marc-André Lureau 已提交
1205
    case VIR_NODE_DEV_CAP_DRM:
1206
        return udevProcessDRMDevice(device, def);
1207
    case VIR_NODE_DEV_CAP_MDEV:
1208
        return udevProcessMediatedDevice(device, def);
B
Bjoern Walk 已提交
1209 1210
    case VIR_NODE_DEV_CAP_CCW_DEV:
        return udevProcessCCW(device, def);
1211
    case VIR_NODE_DEV_CAP_MDEV_TYPES:
1212 1213 1214 1215
    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:
1216 1217 1218
        break;
    }

1219
    return 0;
1220 1221 1222
}


1223 1224
static int
udevRemoveOneDevice(struct udev_device *device)
1225
{
1226
    virNodeDeviceObjPtr obj = NULL;
1227
    virNodeDeviceDefPtr def;
1228
    virObjectEventPtr event = NULL;
1229 1230 1231
    const char *name = NULL;

    name = udev_device_get_syspath(device);
1232
    if (!(obj = virNodeDeviceObjListFindBySysfsPath(driver->devs, name))) {
1233 1234
        VIR_DEBUG("Failed to find device to remove that has udev name '%s'",
                  name);
1235
        return -1;
1236
    }
1237
    def = virNodeDeviceObjGetDef(obj);
1238

1239
    event = virNodeDeviceEventLifecycleNew(def->name,
1240 1241 1242 1243
                                           VIR_NODE_DEVICE_EVENT_DELETED,
                                           0);

    VIR_DEBUG("Removing device '%s' with sysfs path '%s'",
1244
              def->name, name);
1245
    virNodeDeviceObjListRemove(driver->devs, obj);
1246
    virObjectUnref(obj);
1247

1248
    virObjectEventStateQueue(driver->nodeDeviceEventState, event);
1249
    return 0;
1250 1251 1252
}


1253 1254 1255
static int
udevSetParent(struct udev_device *device,
              virNodeDeviceDefPtr def)
1256 1257 1258
{
    struct udev_device *parent_device = NULL;
    const char *parent_sysfs_path = NULL;
1259
    virNodeDeviceObjPtr obj = NULL;
1260
    virNodeDeviceDefPtr objdef;
1261

1262 1263
    parent_device = device;
    do {
1264

1265
        parent_device = udev_device_get_parent(parent_device);
1266
        if (parent_device == NULL)
1267
            break;
1268

1269 1270
        parent_sysfs_path = udev_device_get_syspath(parent_device);
        if (parent_sysfs_path == NULL) {
1271 1272 1273
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get syspath for parent of '%s'"),
                           udev_device_get_syspath(parent_device));
1274
            return -1;
1275 1276
        }

1277 1278
        if ((obj = virNodeDeviceObjListFindBySysfsPath(driver->devs,
                                                       parent_sysfs_path))) {
1279
            objdef = virNodeDeviceObjGetDef(obj);
1280
            def->parent = g_strdup(objdef->name);
1281
            virNodeDeviceObjEndAPI(&obj);
1282

1283
            def->parent_sysfs_path = g_strdup(parent_sysfs_path);
1284 1285 1286 1287
        }

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

1288 1289
    if (!def->parent)
        def->parent = g_strdup("computer");
1290

1291
    return 0;
1292 1293 1294
}


1295 1296
static int
udevAddOneDevice(struct udev_device *device)
1297 1298
{
    virNodeDeviceDefPtr def = NULL;
1299
    virNodeDeviceObjPtr obj = NULL;
1300
    virNodeDeviceDefPtr objdef;
1301 1302
    virObjectEventPtr event = NULL;
    bool new_device = true;
1303 1304
    int ret = -1;

1305
    if (VIR_ALLOC(def) != 0)
1306
        goto cleanup;
1307

1308
    def->sysfs_path = g_strdup(udev_device_get_syspath(device));
1309

1310
    if (udevGetStringProperty(device, "DRIVER", &def->driver) < 0)
1311
        goto cleanup;
1312

1313
    if (VIR_ALLOC(def->caps) != 0)
1314
        goto cleanup;
1315

1316
    if (udevGetDeviceType(device, &def->caps->data.type) != 0)
1317
        goto cleanup;
1318

1319 1320 1321
    if (udevGetDeviceNodes(device, def) != 0)
        goto cleanup;

1322
    if (udevGetDeviceDetails(device, def) != 0)
1323
        goto cleanup;
1324

1325
    if (udevSetParent(device, def) != 0)
1326
        goto cleanup;
1327

1328
    if ((obj = virNodeDeviceObjListFindByName(driver->devs, def->name))) {
1329
        virNodeDeviceObjEndAPI(&obj);
1330 1331 1332
        new_device = false;
    }

1333 1334
    /* If this is a device change, the old definition will be freed
     * and the current definition will take its place. */
1335
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1336
        goto cleanup;
1337
    objdef = virNodeDeviceObjGetDef(obj);
1338

1339
    if (new_device)
1340
        event = virNodeDeviceEventLifecycleNew(objdef->name,
1341 1342
                                               VIR_NODE_DEVICE_EVENT_CREATED,
                                               0);
1343
    else
1344
        event = virNodeDeviceEventUpdateNew(objdef->name);
1345

1346
    virNodeDeviceObjEndAPI(&obj);
1347 1348 1349

    ret = 0;

1350
 cleanup:
1351
    virObjectEventStateQueue(driver->nodeDeviceEventState, event);
1352

1353
    if (ret != 0) {
1354
        VIR_DEBUG("Discarding device %d %p %s", ret, def,
1355
                  def ? NULLSTR(def->sysfs_path) : "");
1356 1357 1358
        virNodeDeviceDefFree(def);
    }

1359 1360 1361 1362
    return ret;
}


1363 1364 1365
static int
udevProcessDeviceListEntry(struct udev *udev,
                           struct udev_list_entry *list_entry)
1366 1367 1368 1369 1370 1371 1372 1373
{
    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);
1374

1375 1376
    if (device != NULL) {
        if (udevAddOneDevice(device) != 0) {
1377 1378
            VIR_DEBUG("Failed to create node device for udev device '%s'",
                      name);
1379 1380 1381 1382
        }
        ret = 0;
    }

1383 1384
    udev_device_unref(device);

1385 1386 1387 1388
    return ret;
}


1389 1390 1391 1392 1393 1394 1395 1396
/* 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",
};

1397 1398
static int
udevEnumerateAddMatches(struct udev_enumerate *udev_enumerate)
1399 1400 1401
{
    size_t i;

1402
    for (i = 0; i < G_N_ELEMENTS(subsystem_blacklist); i++) {
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
        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;
}


1413 1414
static int
udevEnumerateDevices(struct udev *udev)
1415 1416 1417
{
    struct udev_enumerate *udev_enumerate = NULL;
    struct udev_list_entry *list_entry = NULL;
1418
    int ret = -1;
1419 1420

    udev_enumerate = udev_enumerate_new(udev);
1421 1422
    if (udevEnumerateAddMatches(udev_enumerate) < 0)
        goto cleanup;
1423

1424 1425
    if (udev_enumerate_scan_devices(udev_enumerate) < 0)
        VIR_WARN("udev scan devices failed");
1426 1427 1428 1429 1430 1431 1432

    udev_list_entry_foreach(list_entry,
                            udev_enumerate_get_list_entry(udev_enumerate)) {

        udevProcessDeviceListEntry(udev, list_entry);
    }

1433
    ret = 0;
1434
 cleanup:
1435 1436 1437 1438 1439
    udev_enumerate_unref(udev_enumerate);
    return ret;
}


1440 1441
static void
udevPCITranslateDeinit(void)
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
{
#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;
}


1453 1454
static int
nodeStateCleanup(void)
1455
{
1456 1457
    udevEventDataPtr priv = NULL;

J
Ján Tomko 已提交
1458 1459
    if (!driver)
        return -1;
1460

1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
    priv = driver->privateData;
    if (priv) {
        virObjectLock(priv);
        priv->threadQuit = true;
        virCondSignal(&priv->threadCond);
        virObjectUnlock(priv);
        virThreadJoin(&priv->th);
    }

    virObjectUnref(priv);
1471
    virObjectUnref(driver->nodeDeviceEventState);
1472

1473
    virNodeDeviceObjListFree(driver->devs);
1474 1475 1476 1477 1478

    if (driver->lockFD != -1)
        virPidFileRelease(driver->stateDir, "driver", driver->lockFD);

    VIR_FREE(driver->stateDir);
J
Ján Tomko 已提交
1479 1480
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
1481

J
Ján Tomko 已提交
1482 1483
    udevPCITranslateDeinit();
    return 0;
1484 1485 1486
}


1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
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;
}


1504 1505 1506
/* the caller must be holding the udevEventData object lock prior to calling
 * this function
 */
1507
static bool
1508
udevEventMonitorSanityCheck(udevEventDataPtr priv,
1509
                            int fd)
1510
{
1511
    int rc = -1;
1512

1513
    rc = udev_monitor_get_fd(priv->udev_monitor);
1514
    if (fd != rc) {
1515 1516 1517
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("File descriptor returned by udev %d does not "
                         "match node device file descriptor %d"),
1518
                       fd, rc);
1519 1520 1521 1522 1523 1524 1525 1526

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

1527
        return false;
1528 1529
    }

1530 1531 1532 1533
    return true;
}


1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
/**
 * 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.
 */
1554
static void
J
Ján Tomko 已提交
1555
udevEventHandleThread(void *opaque G_GNUC_UNUSED)
1556
{
1557
    udevEventDataPtr priv = driver->privateData;
1558 1559
    struct udev_device *device = NULL;

1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
    /* 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;
        }
1576

1577 1578
        errno = 0;
        device = udev_monitor_receive_device(priv->udev_monitor);
1579 1580
        virObjectUnlock(priv);

1581 1582 1583 1584 1585 1586
        if (!device) {
            if (errno == 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to receive device from udev monitor"));
                return;
            }
1587

1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
            /* 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;
            }
1599

1600 1601 1602
            /* 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. */
1603 1604 1605 1606 1607 1608 1609 1610 1611
            virObjectLock(priv);
            priv->dataReady = false;
            virObjectUnlock(priv);

            continue;
        }

        udevHandleOneDevice(device);
        udev_device_unref(device);
1612 1613 1614 1615 1616

        /* 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. */
1617
    }
1618 1619 1620
}


1621
static void
J
Ján Tomko 已提交
1622
udevEventHandleCallback(int watch G_GNUC_UNUSED,
1623
                        int fd,
J
Ján Tomko 已提交
1624 1625
                        int events G_GNUC_UNUSED,
                        void *data G_GNUC_UNUSED)
1626 1627 1628 1629 1630
{
    udevEventDataPtr priv = driver->privateData;

    virObjectLock(priv);

1631 1632 1633 1634 1635 1636 1637
    if (!udevEventMonitorSanityCheck(priv, fd))
        priv->threadQuit = true;
    else
        priv->dataReady = true;

    virCondSignal(&priv->threadCond);
    virObjectUnlock(priv);
1638 1639 1640
}


1641 1642
/* DMI is intel-compatible specific */
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1643
static void
1644
udevGetDMIData(virNodeDevCapSystemPtr syscap)
1645
{
1646
    udevEventDataPtr priv = driver->privateData;
1647 1648
    struct udev *udev = NULL;
    struct udev_device *device = NULL;
1649 1650
    virNodeDevCapSystemHardwarePtr hardware = &syscap->hardware;
    virNodeDevCapSystemFirmwarePtr firmware = &syscap->firmware;
1651

1652
    virObjectLock(priv);
1653
    udev = udev_monitor_get_udev(priv->udev_monitor);
1654

1655 1656
    device = udev_device_new_from_syspath(udev, DMI_DEVPATH);
    if (device == NULL) {
1657 1658
        device = udev_device_new_from_syspath(udev, DMI_DEVPATH_FALLBACK);
        if (device == NULL) {
1659 1660 1661
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to get udev device for syspath '%s' or '%s'"),
                           DMI_DEVPATH, DMI_DEVPATH_FALLBACK);
1662
            virObjectUnlock(priv);
1663
            return;
1664
        }
1665
    }
1666
    virObjectUnlock(priv);
1667

1668
    if (udevGetStringSysfsAttr(device, "product_name",
1669
                               &syscap->product_name) < 0)
1670
        goto cleanup;
1671
    if (udevGetStringSysfsAttr(device, "sys_vendor",
1672
                               &hardware->vendor_name) < 0)
1673
        goto cleanup;
1674
    if (udevGetStringSysfsAttr(device, "product_version",
1675
                               &hardware->version) < 0)
1676
        goto cleanup;
1677
    if (udevGetStringSysfsAttr(device, "product_serial",
1678
                               &hardware->serial) < 0)
1679
        goto cleanup;
1680

1681
    if (virGetHostUUID(hardware->uuid))
1682
        goto cleanup;
1683

1684
    if (udevGetStringSysfsAttr(device, "bios_vendor",
1685
                               &firmware->vendor_name) < 0)
1686
        goto cleanup;
1687
    if (udevGetStringSysfsAttr(device, "bios_version",
1688
                               &firmware->version) < 0)
1689
        goto cleanup;
1690
    if (udevGetStringSysfsAttr(device, "bios_date",
1691
                               &firmware->release_date) < 0)
1692
        goto cleanup;
1693

1694
 cleanup:
1695
    if (device != NULL)
1696 1697 1698
        udev_device_unref(device);
    return;
}
1699
#endif
1700 1701


1702 1703
static int
udevSetupSystemDev(void)
1704 1705
{
    virNodeDeviceDefPtr def = NULL;
1706
    virNodeDeviceObjPtr obj = NULL;
1707 1708
    int ret = -1;

1709 1710
    if (VIR_ALLOC(def) < 0)
        return -1;
1711

1712
    def->name = g_strdup("computer");
1713

1714
    if (VIR_ALLOC(def->caps) != 0)
1715
        goto cleanup;
1716

1717
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1718
    udevGetDMIData(&def->caps->data.system);
1719
#endif
1720

1721
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1722
        goto cleanup;
1723

1724
    virNodeDeviceObjEndAPI(&obj);
1725 1726 1727

    ret = 0;

1728
 cleanup:
1729
    if (ret == -1)
1730 1731
        virNodeDeviceDefFree(def);

1732 1733 1734
    return ret;
}

1735

1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
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);
1750 1751
    ignore_value(virEventRemoveHandle(priv->watch));
    priv->watch = -1;
1752
    priv->threadQuit = true;
1753
    virCondSignal(&priv->threadCond);
1754 1755 1756 1757
    virObjectUnlock(priv);
}


1758
static int
J
Ján Tomko 已提交
1759
udevPCITranslateInit(bool privileged G_GNUC_UNUSED)
1760
{
1761 1762 1763 1764
#if defined __s390__ || defined __s390x_
    /* On s390(x) system there is no PCI bus.
     * Therefore there is nothing to initialize here. */
#else
1765
    int rc;
1766

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

1781 1782 1783

static int
nodeStateInitialize(bool privileged,
1784
                    const char *root,
J
Ján Tomko 已提交
1785 1786
                    virStateInhibitCallback callback G_GNUC_UNUSED,
                    void *opaque G_GNUC_UNUSED)
1787
{
1788
    udevEventDataPtr priv = NULL;
1789
    struct udev *udev = NULL;
1790
    virThread enumThread;
1791

1792 1793 1794 1795 1796 1797
    if (root != NULL) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Driver does not support embedded mode"));
        return -1;
    }

1798
    if (VIR_ALLOC(driver) < 0)
1799
        return VIR_DRV_STATE_INIT_ERROR;
1800

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

1809 1810
    driver->privileged = privileged;

1811
    if (privileged) {
1812
        driver->stateDir = g_strdup_printf("%s/libvirt/nodedev", RUNSTATEDIR);
1813
    } else {
1814
        g_autofree char *rundir = NULL;
1815

1816
        rundir = virGetUserRuntimeDirectory();
1817
        driver->stateDir = g_strdup_printf("%s/nodedev/run", rundir);
1818 1819 1820 1821 1822 1823 1824 1825 1826
    }

    if (virFileMakePathWithMode(driver->stateDir, S_IRWXU) < 0) {
        virReportSystemError(errno, _("cannot create state directory '%s'"),
                             driver->stateDir);
        goto cleanup;
    }

    if ((driver->lockFD =
1827
         virPidFileAcquire(driver->stateDir, "driver", false, getpid())) < 0)
1828 1829
        goto cleanup;

1830 1831
    if (!(driver->devs = virNodeDeviceObjListNew()) ||
        !(priv = udevEventDataNew()))
1832
        goto cleanup;
1833

1834
    driver->privateData = priv;
1835
    driver->nodeDeviceEventState = virObjectEventStateNew();
1836

1837
    if (udevPCITranslateInit(privileged) < 0)
1838
        goto cleanup;
1839

1840
    udev = udev_new();
1841 1842 1843
    if (!udev) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create udev context"));
1844
        goto cleanup;
1845
    }
1846

1847 1848
    virObjectLock(priv);

1849
    priv->udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
1850
    if (!priv->udev_monitor) {
1851 1852
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("udev_monitor_new_from_netlink returned NULL"));
1853
        goto unlock;
1854 1855
    }

1856
    udev_monitor_enable_receiving(priv->udev_monitor);
1857

1858 1859 1860 1861 1862 1863 1864
    /* 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);

1865 1866 1867 1868 1869 1870
    if (virThreadCreate(&priv->th, true, udevEventHandleThread, NULL) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to create udev handler thread"));
        goto unlock;
    }

1871 1872 1873 1874 1875 1876 1877 1878
    /* 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.  */
1879 1880 1881
    priv->watch = virEventAddHandle(udev_monitor_get_fd(priv->udev_monitor),
                                    VIR_EVENT_HANDLE_READABLE,
                                    udevEventHandleCallback, NULL, NULL);
1882
    if (priv->watch == -1)
1883
        goto unlock;
1884

1885 1886
    virObjectUnlock(priv);

1887
    /* Create a fictional 'computer' device to root the device tree. */
1888
    if (udevSetupSystemDev() != 0)
1889
        goto cleanup;
1890

1891 1892 1893 1894
    if (virThreadCreate(&enumThread, false, nodeStateInitializeEnumerate,
                        udev) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to create udev enumerate thread"));
1895
        goto cleanup;
1896
    }
1897

1898
    return VIR_DRV_STATE_INIT_COMPLETE;
1899

1900
 cleanup:
1901
    nodeStateCleanup();
1902
    return VIR_DRV_STATE_INIT_ERROR;
1903 1904

 unlock:
1905
    virObjectUnlock(priv);
1906
    goto cleanup;
1907 1908 1909
}


1910 1911
static int
nodeStateReload(void)
1912 1913 1914 1915 1916
{
    return 0;
}


1917
static virNodeDeviceDriver udevNodeDeviceDriver = {
1918
    .name = "udev",
1919 1920
    .nodeNumOfDevices = nodeNumOfDevices, /* 0.7.3 */
    .nodeListDevices = nodeListDevices, /* 0.7.3 */
1921
    .connectListAllNodeDevices = nodeConnectListAllNodeDevices, /* 0.10.2 */
1922 1923
    .connectNodeDeviceEventRegisterAny = nodeConnectNodeDeviceEventRegisterAny, /* 2.2.0 */
    .connectNodeDeviceEventDeregisterAny = nodeConnectNodeDeviceEventDeregisterAny, /* 2.2.0 */
1924 1925 1926 1927 1928 1929 1930 1931
    .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 */
1932 1933
};

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945

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 = {
1946
    .localOnly = true,
1947
    .uriSchemes = (const char *[]){ "nodedev", NULL },
1948 1949 1950 1951 1952
    .hypervisorDriver = &udevHypervisorDriver,
    .nodeDeviceDriver = &udevNodeDeviceDriver,
};


1953
static virStateDriver udevStateDriver = {
M
Matthias Bolte 已提交
1954
    .name = "udev",
1955 1956 1957
    .stateInitialize = nodeStateInitialize, /* 0.7.3 */
    .stateCleanup = nodeStateCleanup, /* 0.7.3 */
    .stateReload = nodeStateReload, /* 0.7.3 */
1958 1959
};

1960 1961 1962

int
udevNodeRegister(void)
1963
{
1964
    VIR_DEBUG("Registering udev node device backend");
1965

1966 1967
    if (virRegisterConnectDriver(&udevConnectDriver, false) < 0)
        return -1;
1968
    if (virSetSharedNodeDeviceDriver(&udevNodeDeviceDriver) < 0)
1969 1970 1971 1972
        return -1;

    return virRegisterStateDriver(&udevStateDriver);
}