node_device_udev.c 54.4 KB
Newer Older
1 2 3
/*
 * node_device_udev.c: node device enumeration - libudev implementation
 *
4
 * Copyright (C) 2009-2015 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23 24
 *
 * Author: Dave Allan <dallan@redhat.com>
 */

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

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

#define VIR_FROM_THIS VIR_FROM_NODEDEV

49 50
VIR_LOG_INIT("node_device.node_device_udev");

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

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

struct _udevEventData {
    virObjectLockable parent;

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

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

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

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


static int
udevEventDataOnceInit(void)
{
96
    if (!VIR_CLASS_NEW(udevEventData, virClassForObjectLockable()))
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(udevEventData)

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

    if (udevEventDataInitialize() < 0)
        return NULL;

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

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

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

124

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

    return false;
}


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

142
    ret = udev_device_get_property_value(udev_device, property_key);
143

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

    return ret;
}


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

160
    return 0;
161 162 163
}


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

172
    str = udevGetDeviceProperty(udev_device, property_key);
173

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


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

191
    str = udevGetDeviceProperty(udev_device, property_key);
192

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


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

208
    ret = udev_device_get_sysattr_value(udev_device, attr_name);
209 210

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


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

226
    virStringStripControlChars(*value);
227

228 229
    if (*value != NULL && (STREQ(*value, "")))
        VIR_FREE(*value);
230

231
    return 0;
232 233 234
}


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

243
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
244

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

251
    return 0;
252 253 254
}


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

263
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
264

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

271
    return 0;
272 273 274
}


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

282
    str = udevGetDeviceSysfsAttr(udev_device, attr_name);
283

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

J
Ján Tomko 已提交
290
    return 0;
291 292 293
}


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

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

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

309 310
    if (virBufferCheckError(&buf) < 0)
        return -1;
311 312 313

    def->name = virBufferContentAndReset(&buf);

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

319
    return 0;
320 321
}

322

323
#if HAVE_UDEV_LOGGING
324 325 326 327 328 329 330 331
typedef void
(*udevLogFunctionPtr)(struct udev *udev,
                      int priority,
                      const char *file,
                      int line,
                      const char *fn,
                      const char *format,
                      va_list args);
J
Ján Tomko 已提交
332 333

static void
334
ATTRIBUTE_FMT_PRINTF(6, 0)
J
Ján Tomko 已提交
335 336 337 338 339 340 341
udevLogFunction(struct udev *udev ATTRIBUTE_UNUSED,
                int priority,
                const char *file,
                int line,
                const char *fn,
                const char *fmt,
                va_list args)
342
{
J
Ján Tomko 已提交
343
    virBuffer buf = VIR_BUFFER_INITIALIZER;
344
    char *format = NULL;
J
Ján Tomko 已提交
345 346 347 348 349 350

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

    format = virBufferContentAndReset(&buf);

351
    virLogVMessage(&virLogSelf,
J
Ján Tomko 已提交
352 353 354 355
                   virLogPriorityFromSyslog(priority),
                   file, line, fn, NULL, format ? format : fmt, args);

    VIR_FREE(format);
356
}
357
#endif
358 359


360 361 362 363 364
static int
udevTranslatePCIIds(unsigned int vendor,
                    unsigned int product,
                    char **vendor_string,
                    char **product_string)
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
{
    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,
380
                    &vendor_name,
381 382 383
                    NULL,
                    NULL);

384
    if (VIR_STRDUP(*vendor_string, vendor_name) < 0 ||
385
        VIR_STRDUP(*product_string, device_name) < 0)
386
        return -1;
387

388
    return 0;
389 390 391
}


392 393 394
static int
udevProcessPCI(struct udev_device *device,
               virNodeDeviceDefPtr def)
395
{
396
    virNodeDevCapPCIDevPtr pci_dev = &def->caps->data.pci_dev;
397 398
    virPCIEDeviceInfoPtr pci_express = NULL;
    virPCIDevicePtr pciDev = NULL;
399
    int ret = -1;
400
    char *p;
401 402 403 404 405
    bool privileged;

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

407
    if (udevGetUintProperty(device, "PCI_CLASS", &pci_dev->class, 16) < 0)
408
        goto cleanup;
409

410
    if ((p = strrchr(def->sysfs_path, '/')) == NULL ||
411 412 413 414
        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) {
415 416
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the PCI address from sysfs path: '%s'"),
417
                       def->sysfs_path);
418
        goto cleanup;
419 420
    }

421
    if (udevGetUintSysfsAttr(device, "vendor", &pci_dev->vendor, 16) < 0)
422
        goto cleanup;
423

424
    if (udevGetUintSysfsAttr(device, "device", &pci_dev->product, 16) < 0)
425
        goto cleanup;
426

427 428 429 430
    if (udevTranslatePCIIds(pci_dev->vendor,
                            pci_dev->product,
                            &pci_dev->vendor_name,
                            &pci_dev->product_name) != 0) {
431
        goto cleanup;
432
    }
433

434
    if (udevGenerateDeviceName(device, def, NULL) != 0)
435
        goto cleanup;
436

437 438
    /* The default value is -1, because it can't be 0
     * as zero is valid node number. */
439
    pci_dev->numa_node = -1;
440
    if (udevGetIntSysfsAttr(device, "numa_node",
441
                            &pci_dev->numa_node, 10) < 0)
442
        goto cleanup;
443

444
    if (virNodeDeviceGetPCIDynamicCaps(def->sysfs_path, pci_dev) < 0)
445
        goto cleanup;
446

447 448 449 450
    if (!(pciDev = virPCIDeviceNew(pci_dev->domain,
                                   pci_dev->bus,
                                   pci_dev->slot,
                                   pci_dev->function)))
451
        goto cleanup;
452

453
    /* We need to be root to read PCI device configs */
454
    if (privileged) {
455
        if (virPCIGetHeaderType(pciDev, &pci_dev->hdrType) < 0)
456
            goto cleanup;
457

458 459
        if (virPCIDeviceIsPCIExpress(pciDev) > 0) {
            if (VIR_ALLOC(pci_express) < 0)
460
                goto cleanup;
461

462 463 464
            if (virPCIDeviceHasPCIExpressLink(pciDev) > 0) {
                if (VIR_ALLOC(pci_express->link_cap) < 0 ||
                    VIR_ALLOC(pci_express->link_sta) < 0)
465
                    goto cleanup;
466 467 468 469 470 471 472

                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)
473
                    goto cleanup;
474 475 476

                pci_express->link_sta->port = -1; /* PCIe can't negotiate port. Yet :) */
            }
477 478
            pci_dev->flags |= VIR_NODE_DEV_CAP_FLAG_PCIE;
            pci_dev->pci_express = pci_express;
479
            pci_express = NULL;
480 481 482
        }
    }

483 484
    ret = 0;

485
 cleanup:
486
    virPCIDeviceFree(pciDev);
487
    virPCIEDeviceInfoFree(pci_express);
488 489 490
    return ret;
}

491 492 493

static int
drmGetMinorType(int minor)
M
Marc-André Lureau 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
{
    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;
    }
}

510 511 512 513

static int
udevProcessDRMDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
M
Marc-André Lureau 已提交
514
{
515
    virNodeDevCapDRMPtr drm = &def->caps->data.drm;
M
Marc-André Lureau 已提交
516 517 518 519 520 521 522 523 524 525 526
    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;

527
    drm->type = minor;
M
Marc-André Lureau 已提交
528 529 530

    return 0;
}
531

532 533 534 535

static int
udevProcessUSBDevice(struct udev_device *device,
                     virNodeDeviceDefPtr def)
536
{
537
    virNodeDevCapUSBDevPtr usb_dev = &def->caps->data.usb_dev;
538

539
    if (udevGetUintProperty(device, "BUSNUM", &usb_dev->bus, 10) < 0)
540
        return -1;
541
    if (udevGetUintProperty(device, "DEVNUM", &usb_dev->device, 10) < 0)
542
        return -1;
543
    if (udevGetUintProperty(device, "ID_VENDOR_ID", &usb_dev->vendor, 16) < 0)
544
        return -1;
545

546 547
    if (udevGetStringProperty(device,
                              "ID_VENDOR_FROM_DATABASE",
548
                              &usb_dev->vendor_name) < 0)
549
        return -1;
550

551
    if (!usb_dev->vendor_name &&
552
        udevGetStringSysfsAttr(device, "manufacturer",
553
                               &usb_dev->vendor_name) < 0)
554
        return -1;
555

556
    if (udevGetUintProperty(device, "ID_MODEL_ID", &usb_dev->product, 16) < 0)
557
        return -1;
558

559 560
    if (udevGetStringProperty(device,
                              "ID_MODEL_FROM_DATABASE",
561
                              &usb_dev->product_name) < 0)
562
        return -1;
563

564
    if (!usb_dev->product_name &&
565
        udevGetStringSysfsAttr(device, "product",
566
                               &usb_dev->product_name) < 0)
567
        return -1;
568

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

572
    return 0;
573 574 575
}


576 577 578
static int
udevProcessUSBInterface(struct udev_device *device,
                        virNodeDeviceDefPtr def)
579
{
580
    virNodeDevCapUSBIfPtr usb_if = &def->caps->data.usb_if;
581

582
    if (udevGetUintSysfsAttr(device, "bInterfaceNumber",
583
                             &usb_if->number, 16) < 0)
584
        return -1;
585

586
    if (udevGetUintSysfsAttr(device, "bInterfaceClass",
587
                             &usb_if->_class, 16) < 0)
588
        return -1;
589

590
    if (udevGetUintSysfsAttr(device, "bInterfaceSubClass",
591
                             &usb_if->subclass, 16) < 0)
592
        return -1;
593

594
    if (udevGetUintSysfsAttr(device, "bInterfaceProtocol",
595
                             &usb_if->protocol, 16) < 0)
596
        return -1;
597

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

601
    return 0;
602 603 604
}


605 606 607
static int
udevProcessNetworkInterface(struct udev_device *device,
                            virNodeDeviceDefPtr def)
608
{
D
David Allan 已提交
609
    const char *devtype = udev_device_get_devtype(device);
610
    virNodeDevCapNetPtr net = &def->caps->data.net;
611

D
David Allan 已提交
612
    if (devtype && STREQ(devtype, "wlan")) {
613
        net->subtype = VIR_NODE_DEV_CAP_NET_80211;
D
David Allan 已提交
614
    } else {
615
        net->subtype = VIR_NODE_DEV_CAP_NET_80203;
D
David Allan 已提交
616 617
    }

618 619
    if (udevGetStringProperty(device,
                              "INTERFACE",
620
                              &net->ifname) < 0)
621
        return -1;
622

623
    if (udevGetStringSysfsAttr(device, "address",
624
                               &net->address) < 0)
625
        return -1;
626

627
    if (udevGetUintSysfsAttr(device, "addr_len", &net->address_len, 0) < 0)
628
        return -1;
629

630
    if (udevGenerateDeviceName(device, def, net->address) != 0)
631
        return -1;
632

633
    if (virNetDevGetLinkInfo(net->ifname, &net->lnk) < 0)
634
        return -1;
635

636
    if (virNetDevGetFeatures(net->ifname, &net->features) < 0)
637
        return -1;
638

639
    return 0;
640 641 642
}


643 644 645
static int
udevProcessSCSIHost(struct udev_device *device ATTRIBUTE_UNUSED,
                    virNodeDeviceDefPtr def)
646
{
647
    virNodeDevCapSCSIHostPtr scsi_host = &def->caps->data.scsi_host;
648
    char *filename = NULL;
J
Ján Tomko 已提交
649
    char *str;
650

651
    filename = last_component(def->sysfs_path);
652

653
    if (!(str = STRSKIP(filename, "host")) ||
654
        virStrToLong_ui(str, NULL, 0, &scsi_host->host) < 0) {
655 656 657
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse SCSI host '%s'"),
                       filename);
658
        return -1;
659 660
    }

661
    virNodeDeviceGetSCSIHostCaps(&def->caps->data.scsi_host);
662

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

666
    return 0;
667 668 669
}


670 671 672
static int
udevProcessSCSITarget(struct udev_device *device,
                      virNodeDeviceDefPtr def)
D
David Allan 已提交
673 674
{
    const char *sysname = NULL;
675
    virNodeDevCapSCSITargetPtr scsi_target = &def->caps->data.scsi_target;
D
David Allan 已提交
676 677 678

    sysname = udev_device_get_sysname(device);

679
    if (VIR_STRDUP(scsi_target->name, sysname) < 0)
680
        return -1;
D
David Allan 已提交
681

682
    virNodeDeviceGetSCSITargetCaps(def->sysfs_path, &def->caps->data.scsi_target);
683

684
    if (udevGenerateDeviceName(device, def, NULL) != 0)
685
        return -1;
D
David Allan 已提交
686

687
    return 0;
D
David Allan 已提交
688 689 690
}


691 692 693 694
static int
udevGetSCSIType(virNodeDeviceDefPtr def ATTRIBUTE_UNUSED,
                unsigned int type,
                char **typestring)
695 696 697 698 699 700 701 702
{
    int ret = 0;
    int foundtype = 1;

    *typestring = NULL;

    switch (type) {
    case TYPE_DISK:
703
        ignore_value(VIR_STRDUP(*typestring, "disk"));
704 705
        break;
    case TYPE_TAPE:
706
        ignore_value(VIR_STRDUP(*typestring, "tape"));
707 708
        break;
    case TYPE_PROCESSOR:
709
        ignore_value(VIR_STRDUP(*typestring, "processor"));
710 711
        break;
    case TYPE_WORM:
712
        ignore_value(VIR_STRDUP(*typestring, "worm"));
713 714
        break;
    case TYPE_ROM:
715
        ignore_value(VIR_STRDUP(*typestring, "cdrom"));
716 717
        break;
    case TYPE_SCANNER:
718
        ignore_value(VIR_STRDUP(*typestring, "scanner"));
719 720
        break;
    case TYPE_MOD:
721
        ignore_value(VIR_STRDUP(*typestring, "mod"));
722 723
        break;
    case TYPE_MEDIUM_CHANGER:
724
        ignore_value(VIR_STRDUP(*typestring, "changer"));
725 726
        break;
    case TYPE_ENCLOSURE:
727
        ignore_value(VIR_STRDUP(*typestring, "enclosure"));
728
        break;
729
    case TYPE_RAID:
730
        ignore_value(VIR_STRDUP(*typestring, "raid"));
731
        break;
732 733 734 735 736 737 738 739 740 741
    case TYPE_NO_LUN:
    default:
        foundtype = 0;
        break;
    }

    if (*typestring == NULL) {
        if (foundtype == 1) {
            ret = -1;
        } else {
742 743
            VIR_DEBUG("Failed to find SCSI device type %d for %s",
                      type, def->sysfs_path);
744 745 746 747 748 749 750
        }
    }

    return ret;
}


751 752 753
static int
udevProcessSCSIDevice(struct udev_device *device ATTRIBUTE_UNUSED,
                      virNodeDeviceDefPtr def)
754 755 756
{
    int ret = -1;
    unsigned int tmp = 0;
757
    virNodeDevCapSCSIPtr scsi = &def->caps->data.scsi;
758 759
    char *filename = NULL, *p = NULL;

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

762 763 764 765
    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) {
766 767 768 769
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse the SCSI address from filename: '%s'"),
                       filename);
        return -1;
770 771
    }

772 773
    if (udev_device_get_sysattr_value(device, "type")) {
        if (udevGetUintSysfsAttr(device, "type", &tmp, 0) < 0)
774
            goto cleanup;
775

776
        if (udevGetSCSIType(def, tmp, &scsi->type) < 0)
777
            goto cleanup;
778 779
    }

780
    if (udevGenerateDeviceName(device, def, NULL) != 0)
781
        goto cleanup;
782 783 784

    ret = 0;

785
 cleanup:
786
    if (ret != 0) {
787 788 789
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to process SCSI device with sysfs path '%s'"),
                       def->sysfs_path);
790 791 792 793 794
    }
    return ret;
}


795 796 797
static int
udevProcessDisk(struct udev_device *device,
                virNodeDeviceDefPtr def)
798
{
799
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
800

801
    if (udevGetUint64SysfsAttr(device, "size", &storage->num_blocks) < 0)
802
        return -1;
803

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

808
    storage->size = storage->num_blocks * storage->logical_block_size;
809

810
    return 0;
811 812 813
}


814 815 816 817
static int
udevProcessRemoveableMedia(struct udev_device *device,
                           virNodeDeviceDefPtr def,
                           int has_media)
818
{
819
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
J
Ján Tomko 已提交
820
    int is_removable = 0;
821

822 823 824
    if (udevGetIntSysfsAttr(device, "removable", &is_removable, 0) < 0)
        return -1;
    if (is_removable == 1)
825 826
        def->caps->data.storage.flags |= VIR_NODE_DEV_CAP_STORAGE_REMOVABLE;

J
Ján Tomko 已提交
827 828
    if (!has_media)
        return 0;
829

J
Ján Tomko 已提交
830 831
    def->caps->data.storage.flags |=
        VIR_NODE_DEV_CAP_STORAGE_REMOVABLE_MEDIA_AVAILABLE;
832

J
Ján Tomko 已提交
833
    if (udevGetStringProperty(device, "ID_FS_LABEL",
834
                              &storage->media_label) < 0)
J
Ján Tomko 已提交
835
        return -1;
836

J
Ján Tomko 已提交
837
    if (udevGetUint64SysfsAttr(device, "size",
838
                               &storage->num_blocks) < 0)
J
Ján Tomko 已提交
839
        return -1;
840

J
Ján Tomko 已提交
841
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
842
                               &storage->logical_block_size) < 0)
J
Ján Tomko 已提交
843
        return -1;
844

J
Ján Tomko 已提交
845 846 847 848 849 850 851
    /* 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;
852

J
Ján Tomko 已提交
853
    return 0;
854 855
}

856 857 858 859

static int
udevProcessCDROM(struct udev_device *device,
                 virNodeDeviceDefPtr def)
860 861 862 863 864 865 866 867
{
    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);
868
    if (VIR_STRDUP(def->caps->data.storage.drive_type, "cdrom") < 0)
869
        return -1;
870

871 872
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA") &&
        udevGetIntProperty(device, "ID_CDROM_MEDIA", &has_media, 0) < 0)
873
        return -1;
874

875
    return udevProcessRemoveableMedia(device, def, has_media);
876 877
}

878 879 880 881

static int
udevProcessFloppy(struct udev_device *device,
                  virNodeDeviceDefPtr def)
882 883 884
{
    int has_media = 0;

885
    if (udevHasDeviceProperty(device, "ID_CDROM_MEDIA")) {
886
        /* USB floppy */
887 888
        if (udevGetIntProperty(device, "DKD_MEDIA_AVAILABLE", &has_media, 0) < 0)
            return -1;
889
    } else if (udevHasDeviceProperty(device, "ID_FS_LABEL")) {
890 891 892 893 894 895
        /* Legacy floppy */
        has_media = 1;
    }

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

897

898 899 900
static int
udevProcessSD(struct udev_device *device,
              virNodeDeviceDefPtr def)
901
{
902
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
903

J
Ján Tomko 已提交
904
    if (udevGetUint64SysfsAttr(device, "size",
905
                               &storage->num_blocks) < 0)
906
        return -1;
907

J
Ján Tomko 已提交
908
    if (udevGetUint64SysfsAttr(device, "queue/logical_block_size",
909
                               &storage->logical_block_size) < 0)
910
        return -1;
911

912
    storage->size = storage->num_blocks * storage->logical_block_size;
913

914
    return 0;
915 916 917
}


918 919 920 921
/* 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. */
922 923
static int
udevKludgeStorageType(virNodeDeviceDefPtr def)
924
{
925 926 927
    VIR_DEBUG("Could not find definitive storage type for device "
              "with sysfs path '%s', trying to guess it",
              def->sysfs_path);
928

929 930 931
    /* virtio disk */
    if (STRPREFIX(def->caps->data.storage.block, "/dev/vd") &&
        VIR_STRDUP(def->caps->data.storage.drive_type, "disk") > 0) {
932
        VIR_DEBUG("Found storage type '%s' for device "
933
                  "with sysfs path '%s'",
934 935
                  def->caps->data.storage.drive_type,
                  def->sysfs_path);
936
        return 0;
937
    }
938 939 940
    VIR_DEBUG("Could not determine storage type "
              "for device with sysfs path '%s'", def->sysfs_path);
    return -1;
941 942 943
}


944 945 946
static int
udevProcessStorage(struct udev_device *device,
                   virNodeDeviceDefPtr def)
947
{
948
    virNodeDevCapStoragePtr storage = &def->caps->data.storage;
949
    int ret = -1;
950
    const char* devnode;
951

952
    devnode = udev_device_get_devnode(device);
953
    if (!devnode) {
954
        VIR_DEBUG("No devnode for '%s'", udev_device_get_devpath(device));
955
        goto cleanup;
956
    }
957

958
    if (VIR_STRDUP(storage->block, devnode) < 0)
959
        goto cleanup;
960

961
    if (udevGetStringProperty(device, "ID_BUS", &storage->bus) < 0)
962
        goto cleanup;
963
    if (udevGetStringProperty(device, "ID_SERIAL", &storage->serial) < 0)
964
        goto cleanup;
965

966
    if (udevGetStringSysfsAttr(device, "device/vendor", &storage->vendor) < 0)
967
        goto cleanup;
968 969 970
    if (def->caps->data.storage.vendor)
        virTrimSpaces(def->caps->data.storage.vendor, NULL);

971
    if (udevGetStringSysfsAttr(device, "device/model", &storage->model) < 0)
972
        goto cleanup;
973 974
    if (def->caps->data.storage.model)
        virTrimSpaces(def->caps->data.storage.model, NULL);
975 976 977 978 979
    /* 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. */

980
    if (udevGetStringProperty(device, "ID_TYPE", &storage->drive_type) < 0)
981
        goto cleanup;
982

983
    if (!storage->drive_type ||
984
        STREQ(def->caps->data.storage.drive_type, "generic")) {
985 986
        int val = 0;
        const char *str = NULL;
987 988 989

        /* All floppy drives have the ID_DRIVE_FLOPPY prop. This is
         * needed since legacy floppies don't have a drive_type */
990
        if (udevGetIntProperty(device, "ID_DRIVE_FLOPPY", &val, 0) < 0)
991
            goto cleanup;
992 993
        else if (val == 1)
            str = "floppy";
994

995
        if (!str) {
996
            if (udevGetIntProperty(device, "ID_CDROM", &val, 0) < 0)
997
                goto cleanup;
998 999 1000
            else if (val == 1)
                str = "cd";
        }
1001

1002
        if (!str) {
1003
            if (udevGetIntProperty(device, "ID_DRIVE_FLASH_SD", &val, 0) < 0)
1004
                goto cleanup;
1005 1006 1007
            if (val == 1)
                str = "sd";
        }
1008

1009
        if (str) {
1010
            if (VIR_STRDUP(storage->drive_type, str) < 0)
1011
                goto cleanup;
1012 1013
        } else {
            /* If udev doesn't have it, perhaps we can guess it. */
1014
            if (udevKludgeStorageType(def) != 0)
1015
                goto cleanup;
1016 1017 1018 1019 1020 1021 1022
        }
    }

    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);
1023 1024
    } else if (STREQ(def->caps->data.storage.drive_type, "floppy")) {
        ret = udevProcessFloppy(device, def);
1025 1026
    } else if (STREQ(def->caps->data.storage.drive_type, "sd")) {
        ret = udevProcessSD(device, def);
1027
    } else {
1028 1029
        VIR_DEBUG("Unsupported storage type '%s'",
                  def->caps->data.storage.drive_type);
1030
        goto cleanup;
1031 1032
    }

1033
    if (udevGenerateDeviceName(device, def, storage->serial) != 0)
1034
        goto cleanup;
1035

1036
 cleanup:
1037
    VIR_DEBUG("Storage ret=%d", ret);
1038 1039 1040
    return ret;
}

1041

1042
static int
1043
udevProcessSCSIGeneric(struct udev_device *dev,
1044 1045
                       virNodeDeviceDefPtr def)
{
1046 1047
    if (udevGetStringProperty(dev, "DEVNAME", &def->caps->data.sg.path) < 0 ||
        !def->caps->data.sg.path)
1048 1049 1050 1051 1052 1053 1054 1055
        return -1;

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

    return 0;
}

1056

1057 1058 1059 1060 1061 1062 1063 1064
static int
udevProcessMediatedDevice(struct udev_device *dev,
                          virNodeDeviceDefPtr def)
{
    int ret = -1;
    const char *uuidstr = NULL;
    int iommugrp = -1;
    char *linkpath = NULL;
1065
    char *canonicalpath = NULL;
1066 1067
    virNodeDevCapMdevPtr data = &def->caps->data.mdev;

1068 1069 1070 1071 1072 1073 1074 1075
    /* 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)
1076 1077
        goto cleanup;

1078 1079 1080 1081 1082 1083 1084
    if (virFileWaitForExists(linkpath, 1, 100) < 0) {
        virReportSystemError(errno,
                             _("failed to wait for file '%s' to appear"),
                             linkpath);
        goto cleanup;
    }

1085 1086
    if (virFileResolveLink(linkpath, &canonicalpath) < 0) {
        virReportSystemError(errno, _("failed to resolve '%s'"), linkpath);
1087
        goto cleanup;
1088
    }
1089

1090
    if (VIR_STRDUP(data->type, last_component(canonicalpath)) < 0)
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        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);
1105
    VIR_FREE(canonicalpath);
1106 1107 1108
    return ret;
}

B
Bjoern Walk 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

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


1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
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;
}

1167

1168 1169
static int
udevGetDeviceType(struct udev_device *device,
1170
                  virNodeDevCapType *type)
1171 1172
{
    const char *devtype = NULL;
1173
    char *subsystem = NULL;
1174
    int ret = -1;
D
David Allan 已提交
1175

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    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 已提交
1194 1195
        else if (STREQ(devtype, "drm_minor"))
            *type = VIR_NODE_DEV_CAP_DRM;
1196 1197
    } else {
        /* PCI devices don't set the DEVTYPE property. */
1198
        if (udevHasDeviceProperty(device, "PCI_CLASS"))
1199
            *type = VIR_NODE_DEV_CAP_PCI_DEV;
1200

1201 1202 1203 1204
        /* 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. */
1205
        if (udevHasDeviceProperty(device, "INTERFACE"))
1206
            *type = VIR_NODE_DEV_CAP_NET;
1207

B
Bjoern Walk 已提交
1208 1209
        /* The following devices do not set the DEVTYPE property, therefore
         * we need to rely on the SUBSYSTEM property */
1210 1211 1212 1213
        if (udevGetStringProperty(device, "SUBSYSTEM", &subsystem) < 0)
            return -1;

        if (STREQ_NULLABLE(subsystem, "scsi_generic"))
1214
            *type = VIR_NODE_DEV_CAP_SCSI_GENERIC;
1215 1216
        else if (STREQ_NULLABLE(subsystem, "mdev"))
            *type = VIR_NODE_DEV_CAP_MDEV;
B
Bjoern Walk 已提交
1217 1218
        else if (STREQ_NULLABLE(subsystem, "ccw"))
            *type = VIR_NODE_DEV_CAP_CCW_DEV;
1219

1220
        VIR_FREE(subsystem);
1221 1222
    }

1223 1224 1225 1226 1227 1228
    if (!*type)
        VIR_DEBUG("Could not determine device type for device "
                  "with sysfs name '%s'",
                  udev_device_get_sysname(device));
    else
        ret = 0;
1229 1230 1231 1232 1233

    return ret;
}


1234 1235 1236
static int
udevGetDeviceDetails(struct udev_device *device,
                     virNodeDeviceDefPtr def)
1237
{
1238
    switch (def->caps->data.type) {
1239
    case VIR_NODE_DEV_CAP_PCI_DEV:
1240
        return udevProcessPCI(device, def);
1241
    case VIR_NODE_DEV_CAP_USB_DEV:
1242
        return udevProcessUSBDevice(device, def);
1243
    case VIR_NODE_DEV_CAP_USB_INTERFACE:
1244
        return udevProcessUSBInterface(device, def);
1245
    case VIR_NODE_DEV_CAP_NET:
1246
        return udevProcessNetworkInterface(device, def);
1247
    case VIR_NODE_DEV_CAP_SCSI_HOST:
1248
        return udevProcessSCSIHost(device, def);
D
David Allan 已提交
1249
    case VIR_NODE_DEV_CAP_SCSI_TARGET:
1250
        return udevProcessSCSITarget(device, def);
1251
    case VIR_NODE_DEV_CAP_SCSI:
1252
        return udevProcessSCSIDevice(device, def);
1253
    case VIR_NODE_DEV_CAP_STORAGE:
1254
        return udevProcessStorage(device, def);
1255
    case VIR_NODE_DEV_CAP_SCSI_GENERIC:
1256
        return udevProcessSCSIGeneric(device, def);
M
Marc-André Lureau 已提交
1257
    case VIR_NODE_DEV_CAP_DRM:
1258
        return udevProcessDRMDevice(device, def);
1259
    case VIR_NODE_DEV_CAP_MDEV:
1260
        return udevProcessMediatedDevice(device, def);
B
Bjoern Walk 已提交
1261 1262
    case VIR_NODE_DEV_CAP_CCW_DEV:
        return udevProcessCCW(device, def);
1263
    case VIR_NODE_DEV_CAP_MDEV_TYPES:
1264 1265 1266 1267
    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:
1268 1269 1270
        break;
    }

1271
    return 0;
1272 1273 1274
}


1275 1276
static int
udevRemoveOneDevice(struct udev_device *device)
1277
{
1278
    virNodeDeviceObjPtr obj = NULL;
1279
    virNodeDeviceDefPtr def;
1280
    virObjectEventPtr event = NULL;
1281 1282 1283
    const char *name = NULL;

    name = udev_device_get_syspath(device);
1284
    if (!(obj = virNodeDeviceObjListFindBySysfsPath(driver->devs, name))) {
1285 1286
        VIR_DEBUG("Failed to find device to remove that has udev name '%s'",
                  name);
1287
        return -1;
1288
    }
1289
    def = virNodeDeviceObjGetDef(obj);
1290

1291
    event = virNodeDeviceEventLifecycleNew(def->name,
1292 1293 1294 1295
                                           VIR_NODE_DEVICE_EVENT_DELETED,
                                           0);

    VIR_DEBUG("Removing device '%s' with sysfs path '%s'",
1296
              def->name, name);
1297
    virNodeDeviceObjListRemove(driver->devs, obj);
1298
    virObjectUnref(obj);
1299 1300 1301

    if (event)
        virObjectEventStateQueue(driver->nodeDeviceEventState, event);
1302
    return 0;
1303 1304 1305
}


1306 1307 1308
static int
udevSetParent(struct udev_device *device,
              virNodeDeviceDefPtr def)
1309 1310 1311
{
    struct udev_device *parent_device = NULL;
    const char *parent_sysfs_path = NULL;
1312
    virNodeDeviceObjPtr obj = NULL;
1313
    virNodeDeviceDefPtr objdef;
1314 1315
    int ret = -1;

1316 1317
    parent_device = device;
    do {
1318

1319
        parent_device = udev_device_get_parent(parent_device);
1320
        if (parent_device == NULL)
1321
            break;
1322

1323 1324
        parent_sysfs_path = udev_device_get_syspath(parent_device);
        if (parent_sysfs_path == NULL) {
1325 1326 1327
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get syspath for parent of '%s'"),
                           udev_device_get_syspath(parent_device));
1328
            goto cleanup;
1329 1330
        }

1331 1332
        if ((obj = virNodeDeviceObjListFindBySysfsPath(driver->devs,
                                                       parent_sysfs_path))) {
1333
            objdef = virNodeDeviceObjGetDef(obj);
1334
            if (VIR_STRDUP(def->parent, objdef->name) < 0) {
1335
                virNodeDeviceObjEndAPI(&obj);
1336
                goto cleanup;
1337
            }
1338
            virNodeDeviceObjEndAPI(&obj);
1339

1340
            if (VIR_STRDUP(def->parent_sysfs_path, parent_sysfs_path) < 0)
1341
                goto cleanup;
1342 1343 1344 1345
        }

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

1346
    if (!def->parent && VIR_STRDUP(def->parent, "computer") < 0)
1347
        goto cleanup;
1348 1349 1350

    ret = 0;

1351
 cleanup:
1352 1353 1354 1355
    return ret;
}


1356 1357
static int
udevAddOneDevice(struct udev_device *device)
1358 1359
{
    virNodeDeviceDefPtr def = NULL;
1360
    virNodeDeviceObjPtr obj = NULL;
1361
    virNodeDeviceDefPtr objdef;
1362 1363
    virObjectEventPtr event = NULL;
    bool new_device = true;
1364 1365
    int ret = -1;

1366
    if (VIR_ALLOC(def) != 0)
1367
        goto cleanup;
1368

1369
    if (VIR_STRDUP(def->sysfs_path, udev_device_get_syspath(device)) < 0)
1370
        goto cleanup;
1371

1372
    if (udevGetStringProperty(device, "DRIVER", &def->driver) < 0)
1373
        goto cleanup;
1374

1375
    if (VIR_ALLOC(def->caps) != 0)
1376
        goto cleanup;
1377

1378
    if (udevGetDeviceType(device, &def->caps->data.type) != 0)
1379
        goto cleanup;
1380

1381 1382 1383
    if (udevGetDeviceNodes(device, def) != 0)
        goto cleanup;

1384
    if (udevGetDeviceDetails(device, def) != 0)
1385
        goto cleanup;
1386

1387
    if (udevSetParent(device, def) != 0)
1388
        goto cleanup;
1389

1390
    if ((obj = virNodeDeviceObjListFindByName(driver->devs, def->name))) {
1391
        virNodeDeviceObjEndAPI(&obj);
1392 1393 1394
        new_device = false;
    }

1395 1396
    /* If this is a device change, the old definition will be freed
     * and the current definition will take its place. */
1397
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1398
        goto cleanup;
1399
    objdef = virNodeDeviceObjGetDef(obj);
1400

1401
    if (new_device)
1402
        event = virNodeDeviceEventLifecycleNew(objdef->name,
1403 1404
                                               VIR_NODE_DEVICE_EVENT_CREATED,
                                               0);
1405
    else
1406
        event = virNodeDeviceEventUpdateNew(objdef->name);
1407

1408
    virNodeDeviceObjEndAPI(&obj);
1409 1410 1411

    ret = 0;

1412
 cleanup:
1413 1414 1415
    if (event)
        virObjectEventStateQueue(driver->nodeDeviceEventState, event);

1416
    if (ret != 0) {
1417
        VIR_DEBUG("Discarding device %d %p %s", ret, def,
1418
                  def ? NULLSTR(def->sysfs_path) : "");
1419 1420 1421
        virNodeDeviceDefFree(def);
    }

1422 1423 1424 1425
    return ret;
}


1426 1427 1428
static int
udevProcessDeviceListEntry(struct udev *udev,
                           struct udev_list_entry *list_entry)
1429 1430 1431 1432 1433 1434 1435 1436
{
    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);
1437

1438 1439
    if (device != NULL) {
        if (udevAddOneDevice(device) != 0) {
1440 1441
            VIR_DEBUG("Failed to create node device for udev device '%s'",
                      name);
1442 1443 1444 1445
        }
        ret = 0;
    }

1446 1447
    udev_device_unref(device);

1448 1449 1450 1451
    return ret;
}


1452 1453 1454 1455 1456 1457 1458 1459
/* 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",
};

1460 1461
static int
udevEnumerateAddMatches(struct udev_enumerate *udev_enumerate)
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
{
    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;
}


1476 1477
static int
udevEnumerateDevices(struct udev *udev)
1478 1479 1480
{
    struct udev_enumerate *udev_enumerate = NULL;
    struct udev_list_entry *list_entry = NULL;
1481
    int ret = -1;
1482 1483

    udev_enumerate = udev_enumerate_new(udev);
1484 1485
    if (udevEnumerateAddMatches(udev_enumerate) < 0)
        goto cleanup;
1486 1487

    ret = udev_enumerate_scan_devices(udev_enumerate);
1488
    if (ret != 0) {
1489 1490 1491
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("udev scan devices returned %d"),
                       ret);
1492
        goto cleanup;
1493 1494 1495 1496 1497 1498 1499 1500
    }

    udev_list_entry_foreach(list_entry,
                            udev_enumerate_get_list_entry(udev_enumerate)) {

        udevProcessDeviceListEntry(udev, list_entry);
    }

1501
 cleanup:
1502 1503 1504 1505 1506
    udev_enumerate_unref(udev_enumerate);
    return ret;
}


1507 1508
static void
udevPCITranslateDeinit(void)
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
{
#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;
}


1520 1521
static int
nodeStateCleanup(void)
1522
{
1523 1524
    udevEventDataPtr priv = NULL;

J
Ján Tomko 已提交
1525 1526
    if (!driver)
        return -1;
1527

1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    priv = driver->privateData;
    if (priv) {
        virObjectLock(priv);
        priv->threadQuit = true;
        virCondSignal(&priv->threadCond);
        virObjectUnlock(priv);
        virThreadJoin(&priv->th);
    }

    virObjectUnref(priv);
1538
    virObjectUnref(driver->nodeDeviceEventState);
1539

1540
    virNodeDeviceObjListFree(driver->devs);
J
Ján Tomko 已提交
1541 1542
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
1543

J
Ján Tomko 已提交
1544 1545
    udevPCITranslateDeinit();
    return 0;
1546 1547 1548
}


1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
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;
}


1566 1567 1568
/* the caller must be holding the udevEventData object lock prior to calling
 * this function
 */
1569
static bool
1570
udevEventMonitorSanityCheck(udevEventDataPtr priv,
1571
                            int fd)
1572
{
1573
    int rc = -1;
1574

1575
    rc = udev_monitor_get_fd(priv->udev_monitor);
1576
    if (fd != rc) {
1577 1578 1579
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("File descriptor returned by udev %d does not "
                         "match node device file descriptor %d"),
1580
                       fd, rc);
1581 1582 1583 1584 1585 1586 1587 1588

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

1589
        return false;
1590 1591
    }

1592 1593 1594 1595 1596
    return true;
}


static void
1597
udevEventHandleThread(void *opaque ATTRIBUTE_UNUSED)
1598
{
1599
    udevEventDataPtr priv = driver->privateData;
1600 1601
    struct udev_device *device = NULL;

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

1619 1620
        errno = 0;
        device = udev_monitor_receive_device(priv->udev_monitor);
1621 1622
        virObjectUnlock(priv);

1623 1624 1625 1626 1627 1628
        if (!device) {
            if (errno == 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to receive device from udev monitor"));
                return;
            }
1629

1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
            /* 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;
            }
1641

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
            virObjectLock(priv);
            priv->dataReady = false;
            virObjectUnlock(priv);

            continue;
        }

        udevHandleOneDevice(device);
        udev_device_unref(device);
    }
1652 1653 1654
}


1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
static void
udevEventHandleCallback(int watch ATTRIBUTE_UNUSED,
                        int fd,
                        int events ATTRIBUTE_UNUSED,
                        void *data ATTRIBUTE_UNUSED)
{
    udevEventDataPtr priv = driver->privateData;

    virObjectLock(priv);

1665 1666 1667 1668 1669 1670 1671
    if (!udevEventMonitorSanityCheck(priv, fd))
        priv->threadQuit = true;
    else
        priv->dataReady = true;

    virCondSignal(&priv->threadCond);
    virObjectUnlock(priv);
1672 1673 1674
}


1675 1676
/* DMI is intel-compatible specific */
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1677
static void
1678
udevGetDMIData(virNodeDevCapSystemPtr syscap)
1679
{
1680
    udevEventDataPtr priv = driver->privateData;
1681 1682
    struct udev *udev = NULL;
    struct udev_device *device = NULL;
1683 1684
    virNodeDevCapSystemHardwarePtr hardware = &syscap->hardware;
    virNodeDevCapSystemFirmwarePtr firmware = &syscap->firmware;
1685

1686
    virObjectLock(priv);
1687
    udev = udev_monitor_get_udev(priv->udev_monitor);
1688

1689 1690
    device = udev_device_new_from_syspath(udev, DMI_DEVPATH);
    if (device == NULL) {
1691 1692
        device = udev_device_new_from_syspath(udev, DMI_DEVPATH_FALLBACK);
        if (device == NULL) {
1693 1694 1695
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to get udev device for syspath '%s' or '%s'"),
                           DMI_DEVPATH, DMI_DEVPATH_FALLBACK);
1696
            virObjectUnlock(priv);
1697
            return;
1698
        }
1699
    }
1700
    virObjectUnlock(priv);
1701

1702
    if (udevGetStringSysfsAttr(device, "product_name",
1703
                               &syscap->product_name) < 0)
1704
        goto cleanup;
1705
    if (udevGetStringSysfsAttr(device, "sys_vendor",
1706
                               &hardware->vendor_name) < 0)
1707
        goto cleanup;
1708
    if (udevGetStringSysfsAttr(device, "product_version",
1709
                               &hardware->version) < 0)
1710
        goto cleanup;
1711
    if (udevGetStringSysfsAttr(device, "product_serial",
1712
                               &hardware->serial) < 0)
1713
        goto cleanup;
1714

1715
    if (virGetHostUUID(hardware->uuid))
1716
        goto cleanup;
1717

1718
    if (udevGetStringSysfsAttr(device, "bios_vendor",
1719
                               &firmware->vendor_name) < 0)
1720
        goto cleanup;
1721
    if (udevGetStringSysfsAttr(device, "bios_version",
1722
                               &firmware->version) < 0)
1723
        goto cleanup;
1724
    if (udevGetStringSysfsAttr(device, "bios_date",
1725
                               &firmware->release_date) < 0)
1726
        goto cleanup;
1727

1728
 cleanup:
1729
    if (device != NULL)
1730 1731 1732
        udev_device_unref(device);
    return;
}
1733
#endif
1734 1735


1736 1737
static int
udevSetupSystemDev(void)
1738 1739
{
    virNodeDeviceDefPtr def = NULL;
1740
    virNodeDeviceObjPtr obj = NULL;
1741 1742
    int ret = -1;

1743 1744
    if (VIR_ALLOC(def) < 0)
        return -1;
1745

1746
    if (VIR_STRDUP(def->name, "computer") < 0)
1747
        goto cleanup;
1748

1749
    if (VIR_ALLOC(def->caps) != 0)
1750
        goto cleanup;
1751

1752
#if defined(__x86_64__) || defined(__i386__) || defined(__amd64__)
1753
    udevGetDMIData(&def->caps->data.system);
1754
#endif
1755

1756
    if (!(obj = virNodeDeviceObjListAssignDef(driver->devs, def)))
1757
        goto cleanup;
1758

1759
    virNodeDeviceObjEndAPI(&obj);
1760 1761 1762

    ret = 0;

1763
 cleanup:
1764
    if (ret == -1)
1765 1766
        virNodeDeviceDefFree(def);

1767 1768 1769
    return ret;
}

1770

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
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);
    priv->threadQuit = true;
    virObjectUnlock(priv);
}


1790 1791
static int
udevPCITranslateInit(bool privileged ATTRIBUTE_UNUSED)
1792
{
1793 1794 1795 1796
#if defined __s390__ || defined __s390x_
    /* On s390(x) system there is no PCI bus.
     * Therefore there is nothing to initialize here. */
#else
1797
    int rc;
1798

1799
    if ((rc = pci_system_init()) != 0) {
1800 1801 1802
        /* 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.  */
1803
        if (errno != ENOENT && (privileged  || errno != EACCES)) {
1804 1805
            virReportSystemError(rc, "%s",
                                 _("Failed to initialize libpciaccess"));
1806
            return -1;
1807
        }
1808
    }
1809
#endif
1810 1811 1812
    return 0;
}

1813 1814 1815 1816 1817

static int
nodeStateInitialize(bool privileged,
                    virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                    void *opaque ATTRIBUTE_UNUSED)
1818
{
1819
    udevEventDataPtr priv = NULL;
1820
    struct udev *udev = NULL;
1821
    virThread enumThread;
1822

1823
    if (VIR_ALLOC(driver) < 0)
1824
        return -1;
1825

1826
    if (virMutexInit(&driver->lock) < 0) {
1827 1828
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to initialize mutex"));
1829
        VIR_FREE(driver);
1830
        return -1;
1831 1832
    }

1833 1834
    driver->privileged = privileged;

1835 1836
    if (!(driver->devs = virNodeDeviceObjListNew()) ||
        !(priv = udevEventDataNew()))
1837
        goto cleanup;
1838

1839
    driver->privateData = priv;
1840
    driver->nodeDeviceEventState = virObjectEventStateNew();
1841

1842
    if (udevPCITranslateInit(privileged) < 0)
1843
        goto cleanup;
1844

1845
    udev = udev_new();
1846 1847 1848
    if (!udev) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create udev context"));
1849
        goto cleanup;
1850
    }
1851
#if HAVE_UDEV_LOGGING
J
Ján Tomko 已提交
1852 1853
    /* cast to get rid of missing-format-attribute warning */
    udev_set_log_fn(udev, (udevLogFunctionPtr) udevLogFunction);
1854
#endif
1855

1856 1857
    virObjectLock(priv);

1858
    priv->udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
1859
    if (!priv->udev_monitor) {
1860 1861
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("udev_monitor_new_from_netlink returned NULL"));
1862
        goto unlock;
1863 1864
    }

1865
    udev_monitor_enable_receiving(priv->udev_monitor);
1866

1867
#if HAVE_UDEV_MONITOR_SET_RECEIVE_BUFFER_SIZE
1868 1869 1870 1871 1872 1873
    /* 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);
1874
#endif
1875

1876 1877 1878 1879 1880 1881
    if (virThreadCreate(&priv->th, true, udevEventHandleThread, NULL) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to create udev handler thread"));
        goto unlock;
    }

1882 1883 1884 1885 1886 1887 1888 1889
    /* 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.  */
1890 1891 1892
    priv->watch = virEventAddHandle(udev_monitor_get_fd(priv->udev_monitor),
                                    VIR_EVENT_HANDLE_READABLE,
                                    udevEventHandleCallback, NULL, NULL);
1893
    if (priv->watch == -1)
1894
        goto unlock;
1895

1896 1897
    virObjectUnlock(priv);

1898
    /* Create a fictional 'computer' device to root the device tree. */
1899
    if (udevSetupSystemDev() != 0)
1900
        goto cleanup;
1901

1902 1903 1904 1905
    if (virThreadCreate(&enumThread, false, nodeStateInitializeEnumerate,
                        udev) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to create udev enumerate thread"));
1906
        goto cleanup;
1907
    }
1908

1909
    return 0;
1910

1911
 cleanup:
1912 1913
    nodeStateCleanup();
    return -1;
1914 1915

 unlock:
1916
    virObjectUnlock(priv);
1917
    goto cleanup;
1918 1919 1920
}


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


1928
static virNodeDeviceDriver udevNodeDeviceDriver = {
1929
    .name = "udev",
1930 1931
    .nodeNumOfDevices = nodeNumOfDevices, /* 0.7.3 */
    .nodeListDevices = nodeListDevices, /* 0.7.3 */
1932
    .connectListAllNodeDevices = nodeConnectListAllNodeDevices, /* 0.10.2 */
1933 1934
    .connectNodeDeviceEventRegisterAny = nodeConnectNodeDeviceEventRegisterAny, /* 2.2.0 */
    .connectNodeDeviceEventDeregisterAny = nodeConnectNodeDeviceEventDeregisterAny, /* 2.2.0 */
1935 1936 1937 1938 1939 1940 1941 1942
    .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 */
1943 1944
};

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956

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 = {
1957
    .localOnly = true,
1958
    .uriSchemes = (const char *[]){ "nodedev", NULL },
1959 1960 1961 1962 1963
    .hypervisorDriver = &udevHypervisorDriver,
    .nodeDeviceDriver = &udevNodeDeviceDriver,
};


1964
static virStateDriver udevStateDriver = {
M
Matthias Bolte 已提交
1965
    .name = "udev",
1966 1967 1968
    .stateInitialize = nodeStateInitialize, /* 0.7.3 */
    .stateCleanup = nodeStateCleanup, /* 0.7.3 */
    .stateReload = nodeStateReload, /* 0.7.3 */
1969 1970
};

1971 1972 1973

int
udevNodeRegister(void)
1974
{
1975
    VIR_DEBUG("Registering udev node device backend");
1976

1977 1978
    if (virRegisterConnectDriver(&udevConnectDriver, false) < 0)
        return -1;
1979
    if (virSetSharedNodeDeviceDriver(&udevNodeDeviceDriver) < 0)
1980 1981 1982 1983
        return -1;

    return virRegisterStateDriver(&udevStateDriver);
}