node_device_hal.c 27.1 KB
Newer Older
1 2 3
/*
 * node_device_hal.c: node device enumeration - HAL-based implementation
 *
4
 * Copyright (C) 2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Copyright (C) 2008 Virtual Iron Software, Inc.
 * Copyright (C) 2008 David F. Lively
 *
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: David F. Lively <dlively@virtualiron.com>
 */

25 26
#include <config.h>

27 28 29 30 31
#include <stdio.h>
#include <stdlib.h>
#include <libhal.h>

#include "node_device_conf.h"
32
#include "node_device_hal.h"
33 34 35 36 37
#include "virterror_internal.h"
#include "driver.h"
#include "datatypes.h"
#include "memory.h"
#include "uuid.h"
38
#include "pci.h"
39
#include "logging.h"
40
#include "node_device_driver.h"
41

42 43
#define VIR_FROM_THIS VIR_FROM_NODEDEV

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
/*
 * Host device enumeration (HAL implementation)
 */

static virDeviceMonitorStatePtr driverState;

#define CONN_DRV_STATE(conn) \
        ((virDeviceMonitorStatePtr)((conn)->devMonPrivateData))
#define DRV_STATE_HAL_CTX(ds) ((LibHalContext *)((ds)->privateData))
#define CONN_HAL_CTX(conn) DRV_STATE_HAL_CTX(CONN_DRV_STATE(conn))

#define NODE_DEV_UDI(obj) ((const char *)((obj)->privateData)


static const char *hal_name(const char *udi)
{
    const char *name = strrchr(udi, '/');
    if (name)
        return name+1;
    return udi;
}


static int get_str_prop(LibHalContext *ctxt, const char *udi,
                        const char *prop, char **val_p)
{
    char *val = libhal_device_get_property_string(ctxt, udi, prop, NULL);

    if (val) {
        if (*val) {
            *val_p = val;
            return 0;
        } else {
            /* Treat empty strings as NULL values */
            VIR_FREE(val);
        }
    }

    return -1;
}

static int get_int_prop(LibHalContext *ctxt, const char *udi,
                        const char *prop, int *val_p)
{
    DBusError err;
    int val;
    int rv;

    dbus_error_init(&err);
    val = libhal_device_get_property_int(ctxt, udi, prop, &err);
    rv = dbus_error_is_set(&err);
    dbus_error_free(&err);
    if (rv == 0)
        *val_p = val;

    return rv;
}

static int get_bool_prop(LibHalContext *ctxt, const char *udi,
                         const char *prop, int *val_p)
{
    DBusError err;
    int val;
    int rv;

    dbus_error_init(&err);
    val = libhal_device_get_property_bool(ctxt, udi, prop, &err);
    rv = dbus_error_is_set(&err);
    dbus_error_free(&err);
    if (rv == 0)
        *val_p = val;

    return rv;
}

static int get_uint64_prop(LibHalContext *ctxt, const char *udi,
                           const char *prop, unsigned long long *val_p)
{
    DBusError err;
    unsigned long long val;
    int rv;

    dbus_error_init(&err);
    val = libhal_device_get_property_uint64(ctxt, udi, prop, &err);
    rv = dbus_error_is_set(&err);
    dbus_error_free(&err);
    if (rv == 0)
        *val_p = val;

    return rv;
}

static int gather_pci_cap(LibHalContext *ctx, const char *udi,
                          union _virNodeDevCapData *d)
{
    char *sysfs_path;

    if (get_str_prop(ctx, udi, "pci.linux.sysfs_path", &sysfs_path) == 0) {
        char *p = strrchr(sysfs_path, '/');
        if (p) {
            (void)virStrToLong_ui(p+1, &p, 16, &d->pci_dev.domain);
            (void)virStrToLong_ui(p+1, &p, 16, &d->pci_dev.bus);
            (void)virStrToLong_ui(p+1, &p, 16, &d->pci_dev.slot);
            (void)virStrToLong_ui(p+1, &p, 16, &d->pci_dev.function);
        }
149

150 151 152 153 154 155 156
        if (!pciGetPhysicalFunction(sysfs_path, &d->pci_dev.physical_function))
            d->pci_dev.flags |= VIR_NODE_DEV_CAP_FLAG_PCI_PHYSICAL_FUNCTION;

        if (!pciGetVirtualFunctions(sysfs_path, &d->pci_dev.virtual_functions,
            &d->pci_dev.num_virtual_functions) ||
            d->pci_dev.num_virtual_functions > 0)
            d->pci_dev.flags |= VIR_NODE_DEV_CAP_FLAG_PCI_VIRTUAL_FUNCTION;
157

158 159
        VIR_FREE(sysfs_path);
    }
160

161 162 163 164 165 166
    (void)get_int_prop(ctx, udi, "pci.vendor_id", (int *)&d->pci_dev.vendor);
    if (get_str_prop(ctx, udi, "pci.vendor", &d->pci_dev.vendor_name) != 0)
        (void)get_str_prop(ctx, udi, "info.vendor", &d->pci_dev.vendor_name);
    (void)get_int_prop(ctx, udi, "pci.product_id", (int *)&d->pci_dev.product);
    if (get_str_prop(ctx, udi, "pci.product", &d->pci_dev.product_name) != 0)
        (void)get_str_prop(ctx, udi, "info.product", &d->pci_dev.product_name);
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    return 0;
}


static int gather_usb_cap(LibHalContext *ctx, const char *udi,
                          union _virNodeDevCapData *d)
{
    (void)get_int_prop(ctx, udi, "usb.interface.number",
                       (int *)&d->usb_if.number);
    (void)get_int_prop(ctx, udi, "usb.interface.class",
                       (int *)&d->usb_if._class);
    (void)get_int_prop(ctx, udi, "usb.interface.subclass",
                       (int *)&d->usb_if.subclass);
    (void)get_int_prop(ctx, udi, "usb.interface.protocol",
                       (int *)&d->usb_if.protocol);
    (void)get_str_prop(ctx, udi, "usb.interface.description",
                       &d->usb_if.description);
    return 0;
}


static int gather_usb_device_cap(LibHalContext *ctx, const char *udi,
                          union _virNodeDevCapData *d)
{
    (void)get_int_prop(ctx, udi, "usb_device.bus_number",
                       (int *)&d->usb_dev.bus);
    (void)get_int_prop(ctx, udi, "usb_device.linux.device_number",
                       (int *)&d->usb_dev.device);
    (void)get_int_prop(ctx, udi, "usb_device.vendor_id",
                       (int *)&d->usb_dev.vendor);
    if (get_str_prop(ctx, udi, "usb_device.vendor",
                     &d->usb_dev.vendor_name) != 0)
        (void)get_str_prop(ctx, udi, "info.vendor", &d->usb_dev.vendor_name);
    (void)get_int_prop(ctx, udi, "usb_device.product_id",
                       (int *)&d->usb_dev.product);
    if (get_str_prop(ctx, udi, "usb_device.product",
                     &d->usb_dev.product_name) != 0)
        (void)get_str_prop(ctx, udi, "info.product", &d->usb_dev.product_name);
    return 0;
}


static int gather_net_cap(LibHalContext *ctx, const char *udi,
                          union _virNodeDevCapData *d)
{
    unsigned long long dummy;
214
    (void)get_str_prop(ctx, udi, "net.interface", &d->net.ifname);
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    (void)get_str_prop(ctx, udi, "net.address", &d->net.address);
    if (get_uint64_prop(ctx, udi, "net.80203.mac_address",
                        &dummy) == 0)
        d->net.subtype = VIR_NODE_DEV_CAP_NET_80203;
    else if (get_uint64_prop(ctx, udi, "net.80211.mac_address",
                             &dummy) == 0)
        d->net.subtype = VIR_NODE_DEV_CAP_NET_80211;
    else
        d->net.subtype = VIR_NODE_DEV_CAP_NET_LAST;

    return 0;
}


static int gather_scsi_host_cap(LibHalContext *ctx, const char *udi,
                                union _virNodeDevCapData *d)
{
232 233
    int retval = 0;

234
    (void)get_int_prop(ctx, udi, "scsi_host.host", (int *)&d->scsi_host.host);
235 236 237 238 239 240 241 242 243 244 245

    retval = check_fc_host(d);

    if (retval == -1) {
        goto out;
    }

    retval = check_vport_capable(d);

out:
    return retval;
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
}


static int gather_scsi_cap(LibHalContext *ctx, const char *udi,
                           union _virNodeDevCapData *d)
{
    (void)get_int_prop(ctx, udi, "scsi.host", (int *)&d->scsi.host);
    (void)get_int_prop(ctx, udi, "scsi.bus", (int *)&d->scsi.bus);
    (void)get_int_prop(ctx, udi, "scsi.target", (int *)&d->scsi.target);
    (void)get_int_prop(ctx, udi, "scsi.lun", (int *)&d->scsi.lun);
    (void)get_str_prop(ctx, udi, "scsi.type", &d->scsi.type);
    return 0;
}


static int gather_storage_cap(LibHalContext *ctx, const char *udi,
                              union _virNodeDevCapData *d)
{
    int val;
265
    (void)get_str_prop(ctx, udi, "block.device", &d->storage.block);
266 267 268 269
    (void)get_str_prop(ctx, udi, "storage.bus", &d->storage.bus);
    (void)get_str_prop(ctx, udi, "storage.drive_type", &d->storage.drive_type);
    (void)get_str_prop(ctx, udi, "storage.model", &d->storage.model);
    (void)get_str_prop(ctx, udi, "storage.vendor", &d->storage.vendor);
270
    (void)get_str_prop(ctx, udi, "storage.serial", &d->storage.serial);
271 272
    if (get_bool_prop(ctx, udi, "storage.removable", &val) == 0 && val) {
        d->storage.flags |= VIR_NODE_DEV_CAP_STORAGE_REMOVABLE;
273 274
        if (get_bool_prop(ctx, udi, "storage.removable.media_available",
                          &val) == 0 && val) {
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
            d->storage.flags |=
                VIR_NODE_DEV_CAP_STORAGE_REMOVABLE_MEDIA_AVAILABLE;
            (void)get_uint64_prop(ctx, udi, "storage.removable.media_size",
                                  &d->storage.removable_media_size);
        }
    } else {
        (void)get_uint64_prop(ctx, udi, "storage.size", &d->storage.size);
    }
    if (get_bool_prop(ctx, udi, "storage.hotpluggable", &val) == 0 && val)
        d->storage.flags |= VIR_NODE_DEV_CAP_STORAGE_HOTPLUGGABLE;
    return 0;
}


static int gather_system_cap(LibHalContext *ctx, const char *udi,
                             union _virNodeDevCapData *d)
{
    char *uuidstr;

    (void)get_str_prop(ctx, udi, "system.product", &d->system.product_name);
    (void)get_str_prop(ctx, udi, "system.hardware.vendor",
                       &d->system.hardware.vendor_name);
    (void)get_str_prop(ctx, udi, "system.hardware.version",
                       &d->system.hardware.version);
    (void)get_str_prop(ctx, udi, "system.hardware.serial",
                       &d->system.hardware.serial);
    if (get_str_prop(ctx, udi, "system.hardware.uuid", &uuidstr) == 0) {
        (void)virUUIDParse(uuidstr, d->system.hardware.uuid);
        VIR_FREE(uuidstr);
    }
    (void)get_str_prop(ctx, udi, "system.firmware.vendor",
                       &d->system.firmware.vendor_name);
    (void)get_str_prop(ctx, udi, "system.firmware.version",
                       &d->system.firmware.version);
    (void)get_str_prop(ctx, udi, "system.firmware.release_date",
                       &d->system.firmware.release_date);
    return 0;
}


struct _caps_tbl_entry {
    const char *cap_name;
    enum virNodeDevCapType type;
    int (*gather_fn)(LibHalContext *ctx,
                     const char *udi,
                     union _virNodeDevCapData *data);
};

typedef struct _caps_tbl_entry caps_tbl_entry;

static caps_tbl_entry caps_tbl[] = {
    { "system",     VIR_NODE_DEV_CAP_SYSTEM,        gather_system_cap },
    { "pci",        VIR_NODE_DEV_CAP_PCI_DEV,       gather_pci_cap },
    { "usb",        VIR_NODE_DEV_CAP_USB_INTERFACE, gather_usb_cap },
    { "usb_device", VIR_NODE_DEV_CAP_USB_DEV,       gather_usb_device_cap },
    { "net",        VIR_NODE_DEV_CAP_NET,           gather_net_cap },
    { "scsi_host",  VIR_NODE_DEV_CAP_SCSI_HOST,     gather_scsi_host_cap },
    { "scsi",       VIR_NODE_DEV_CAP_SCSI,          gather_scsi_cap },
    { "storage",    VIR_NODE_DEV_CAP_STORAGE,       gather_storage_cap },
};


/* qsort/bsearch string comparator */
static int cmpstringp(const void *p1, const void *p2)
{
    /* from man 3 qsort */
    return strcmp(* (char * const *) p1, * (char * const *) p2);
}


static int gather_capability(LibHalContext *ctx, const char *udi,
                             const char *cap_name,
                             virNodeDevCapsDefPtr *caps_p)
{
    caps_tbl_entry *entry;

    entry = bsearch(&cap_name, caps_tbl, ARRAY_CARDINALITY(caps_tbl),
                    sizeof(caps_tbl[0]), cmpstringp);

    if (entry) {
        virNodeDevCapsDefPtr caps;
        if (VIR_ALLOC(caps) < 0)
            return ENOMEM;
        caps->type = entry->type;
        if (entry->gather_fn) {
            int rv = (*entry->gather_fn)(ctx, udi, &caps->data);
            if (rv != 0) {
                virNodeDevCapsDefFree(caps);
                return rv;
            }
        }
        caps->next = *caps_p;
        *caps_p = caps;
    }

    return 0;
}


static int gather_capabilities(LibHalContext *ctx, const char *udi,
                               virNodeDevCapsDefPtr *caps_p)
{
    char *bus_name = NULL;
    virNodeDevCapsDefPtr caps = NULL;
379
    char **hal_cap_names = NULL;
380 381 382 383 384 385 386 387
    int rv, i;

    if (STREQ(udi, "/org/freedesktop/Hal/devices/computer")) {
        rv = gather_capability(ctx, udi, "system", &caps);
        if (rv != 0)
            goto failure;
    }

388 389
    if (get_str_prop(ctx, udi, "info.subsystem", &bus_name) == 0 ||
        get_str_prop(ctx, udi, "linux.subsystem", &bus_name) == 0) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        rv = gather_capability(ctx, udi, bus_name, &caps);
        if (rv != 0)
            goto failure;
    }

    hal_cap_names = libhal_device_get_property_strlist(ctx, udi,
                                                       "info.capabilities",
                                                       NULL);
    if (hal_cap_names) {
        for (i = 0; hal_cap_names[i]; i++) {
            if (! (bus_name && STREQ(hal_cap_names[i], bus_name))) {
                rv = gather_capability(ctx, udi, hal_cap_names[i], &caps);
                if (rv != 0)
                    goto failure;
            }
        }
        for (i = 0; hal_cap_names[i]; i++)
            VIR_FREE(hal_cap_names[i]);
        VIR_FREE(hal_cap_names);
    }
    VIR_FREE(bus_name);

    *caps_p = caps;
    return 0;

 failure:
    VIR_FREE(bus_name);
    if (hal_cap_names) {
        for (i = 0; hal_cap_names[i]; i++)
            VIR_FREE(hal_cap_names[i]);
        VIR_FREE(hal_cap_names);
    }
    while (caps) {
        virNodeDevCapsDefPtr next = caps->next;
        virNodeDevCapsDefFree(caps);
        caps = next;
    }
    return rv;
}

static void free_udi(void *udi)
{
    VIR_FREE(udi);
}

435
static void dev_create(const char *udi)
436
{
437
    LibHalContext *ctx;
438
    char *parent_key = NULL;
439 440
    virNodeDeviceObjPtr dev = NULL;
    virNodeDeviceDefPtr def = NULL;
441 442
    const char *name = hal_name(udi);
    int rv;
443
    char *privData = strdup(udi);
444
    char *devicePath = NULL;
445

446 447
    if (!privData)
        return;
448

449 450 451 452 453
    nodeDeviceLock(driverState);
    ctx = DRV_STATE_HAL_CTX(driverState);

    if (VIR_ALLOC(def) < 0)
        goto failure;
454

455
    if ((def->name = strdup(name)) == NULL)
456 457 458
        goto failure;

    if (get_str_prop(ctx, udi, "info.parent", &parent_key) == 0) {
459
        def->parent = strdup(hal_name(parent_key));
460
        VIR_FREE(parent_key);
461
        if (def->parent == NULL)
462 463 464
            goto failure;
    }

465
    rv = gather_capabilities(ctx, udi, &def->caps);
466 467
    if (rv != 0) goto failure;

468 469
    if (def->caps == NULL)
        goto cleanup;
470

471
    /* Some devices don't have a path in sysfs, so ignore failure */
472
    (void)get_str_prop(ctx, udi, "linux.sysfs_path", &devicePath);
473

474
    dev = virNodeDeviceAssignDef(&driverState->devs,
475 476
                                 def);

477 478
    if (!dev) {
        VIR_FREE(devicePath);
479
        goto failure;
480
    }
481

482 483
    dev->privateData = privData;
    dev->privateFree = free_udi;
484
    dev->def->sysfs_path = devicePath;
485

486
    virNodeDeviceObjUnlock(dev);
487

488
    nodeDeviceUnlock(driverState);
489 490 491
    return;

 failure:
492
    VIR_DEBUG("FAILED TO ADD dev %s", name);
493 494
cleanup:
    VIR_FREE(privData);
495
    virNodeDeviceDefFree(def);
496
    nodeDeviceUnlock(driverState);
497 498
}

499 500 501 502 503 504 505 506 507 508 509 510 511
static void dev_refresh(const char *udi)
{
    const char *name = hal_name(udi);
    virNodeDeviceObjPtr dev;

    nodeDeviceLock(driverState);
    dev = virNodeDeviceFindByName(&driverState->devs, name);
    if (dev) {
        /* Simply "rediscover" device -- incrementally handling changes
         * to sub-capabilities (like net.80203) is nasty ... so avoid it.
         */
        virNodeDeviceObjRemove(&driverState->devs, dev);
    } else
512
        VIR_DEBUG("no device named %s", name);
513 514 515 516 517 518
    nodeDeviceUnlock(driverState);

    if (dev) {
        dev_create(udi);
    }
}
519 520 521 522

static void device_added(LibHalContext *ctx ATTRIBUTE_UNUSED,
                         const char *udi)
{
523
    VIR_DEBUG("%s", hal_name(udi));
524
    dev_create(udi);
525 526 527 528 529 530 531
}


static void device_removed(LibHalContext *ctx ATTRIBUTE_UNUSED,
                           const char *udi)
{
    const char *name = hal_name(udi);
532 533 534 535
    virNodeDeviceObjPtr dev;

    nodeDeviceLock(driverState);
    dev = virNodeDeviceFindByName(&driverState->devs,name);
536
    VIR_DEBUG("%s", name);
537 538 539
    if (dev)
        virNodeDeviceObjRemove(&driverState->devs, dev);
    else
540
        VIR_DEBUG("no device named %s", name);
541
    nodeDeviceUnlock(driverState);
542 543 544 545 546 547 548
}


static void device_cap_added(LibHalContext *ctx,
                             const char *udi, const char *cap)
{
    const char *name = hal_name(udi);
549 550 551 552 553
    virNodeDeviceObjPtr dev;

    nodeDeviceLock(driverState);
    dev = virNodeDeviceFindByName(&driverState->devs,name);
    nodeDeviceUnlock(driverState);
554
    VIR_DEBUG("%s %s", cap, name);
555
    if (dev) {
556
        (void)gather_capability(ctx, udi, cap, &dev->def->caps);
557 558
        virNodeDeviceObjUnlock(dev);
    } else {
559
        VIR_DEBUG("no device named %s", name);
560
    }
561 562 563 564 565 566 567 568
}


static void device_cap_lost(LibHalContext *ctx ATTRIBUTE_UNUSED,
                            const char *udi,
                            const char *cap)
{
    const char *name = hal_name(udi);
569
    VIR_DEBUG("%s %s", cap, name);
570 571

    dev_refresh(udi);
572 573 574 575 576 577 578 579 580 581
}


static void device_prop_modified(LibHalContext *ctx ATTRIBUTE_UNUSED,
                                 const char *udi,
                                 const char *key,
                                 dbus_bool_t is_removed ATTRIBUTE_UNUSED,
                                 dbus_bool_t is_added ATTRIBUTE_UNUSED)
{
    const char *name = hal_name(udi);
582
    VIR_DEBUG("%s %s", name, key);
583

584
    dev_refresh(udi);
585 586 587 588 589 590 591 592
}


static void dbus_watch_callback(int fdatch ATTRIBUTE_UNUSED,
                                int fd ATTRIBUTE_UNUSED,
                                int events, void *opaque)
{
    DBusWatch *watch = opaque;
593 594
    LibHalContext *hal_ctx;
    DBusConnection *dbus_conn;
595 596 597 598 599 600 601 602 603 604 605 606 607
    int dbus_flags = 0;

    if (events & VIR_EVENT_HANDLE_READABLE)
        dbus_flags |= DBUS_WATCH_READABLE;
    if (events & VIR_EVENT_HANDLE_WRITABLE)
        dbus_flags |= DBUS_WATCH_WRITABLE;
    if (events & VIR_EVENT_HANDLE_ERROR)
        dbus_flags |= DBUS_WATCH_ERROR;
    if (events & VIR_EVENT_HANDLE_HANGUP)
        dbus_flags |= DBUS_WATCH_HANGUP;

    (void)dbus_watch_handle(watch, dbus_flags);

608 609 610 611
    nodeDeviceLock(driverState);
    hal_ctx = DRV_STATE_HAL_CTX(driverState);
    dbus_conn = libhal_ctx_get_dbus_connection(hal_ctx);
    nodeDeviceUnlock(driverState);
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    while (dbus_connection_dispatch(dbus_conn) == DBUS_DISPATCH_DATA_REMAINS)
        /* keep dispatching while data remains */;
}


static int xlate_dbus_watch_flags(int dbus_flags)
{
    unsigned int flags = 0;
    if (dbus_flags & DBUS_WATCH_READABLE)
        flags |= VIR_EVENT_HANDLE_READABLE;
    if (dbus_flags & DBUS_WATCH_WRITABLE)
        flags |= VIR_EVENT_HANDLE_WRITABLE;
    if (dbus_flags & DBUS_WATCH_ERROR)
        flags |= VIR_EVENT_HANDLE_ERROR;
    if (dbus_flags & DBUS_WATCH_HANGUP)
        flags |= VIR_EVENT_HANDLE_HANGUP;
    return flags;
}


632 633 634 635 636 637 638 639 640 641
struct nodeDeviceWatchInfo
{
    int watch;
};

static void nodeDeviceWatchFree(void *data) {
    struct nodeDeviceWatchInfo *info = data;
    VIR_FREE(info);
}

642
static dbus_bool_t add_dbus_watch(DBusWatch *watch,
643
                                  void *data ATTRIBUTE_UNUSED)
644 645
{
    int flags = 0;
646
    int fd;
647 648 649 650
    struct nodeDeviceWatchInfo *info;

    if (VIR_ALLOC(info) < 0)
        return 0;
651 652 653 654

    if (dbus_watch_get_enabled(watch))
        flags = xlate_dbus_watch_flags(dbus_watch_get_flags(watch));

655 656 657 658 659 660 661
#if HAVE_DBUS_WATCH_GET_UNIX_FD
    fd = dbus_watch_get_unix_fd(watch);
#else
    fd = dbus_watch_get_fd(watch);
#endif
    info->watch = virEventAddHandle(fd, flags, dbus_watch_callback,
                                    watch, NULL);
662 663
    if (info->watch < 0) {
        VIR_FREE(info);
664
        return 0;
665 666 667
    }
    dbus_watch_set_data(watch, info, nodeDeviceWatchFree);

668 669 670 671
    return 1;
}


672 673
static void remove_dbus_watch(DBusWatch *watch,
                              void *data ATTRIBUTE_UNUSED)
674
{
675
    struct nodeDeviceWatchInfo *info;
676

677 678 679
    info = dbus_watch_get_data(watch);

    (void)virEventRemoveHandle(info->watch);
680 681 682 683
}


static void toggle_dbus_watch(DBusWatch *watch,
684
                              void *data ATTRIBUTE_UNUSED)
685 686
{
    int flags = 0;
687
    struct nodeDeviceWatchInfo *info;
688 689 690 691

    if (dbus_watch_get_enabled(watch))
        flags = xlate_dbus_watch_flags(dbus_watch_get_flags(watch));

692 693 694
    info = dbus_watch_get_data(watch);

    (void)virEventUpdateHandle(info->watch, flags);
695 696 697
}


698
static int halDeviceMonitorStartup(int privileged ATTRIBUTE_UNUSED)
699 700 701 702 703 704
{
    LibHalContext *hal_ctx = NULL;
    DBusConnection *dbus_conn = NULL;
    DBusError err;
    char **udi = NULL;
    int num_devs, i;
705
    int ret = -1;
706 707 708 709 710 711 712 713

    /* Ensure caps_tbl is sorted by capability name */
    qsort(caps_tbl, ARRAY_CARDINALITY(caps_tbl), sizeof(caps_tbl[0]),
          cmpstringp);

    if (VIR_ALLOC(driverState) < 0)
        return -1;

714 715 716 717
    if (virMutexInit(&driverState->lock) < 0) {
        VIR_FREE(driverState);
        return -1;
    }
718 719
    nodeDeviceLock(driverState);

720
    /* Allocate and initialize a new HAL context */
721 722 723
    dbus_connection_set_change_sigpipe(FALSE);
    dbus_threads_init_default();

724 725 726
    dbus_error_init(&err);
    hal_ctx = libhal_ctx_new();
    if (hal_ctx == NULL) {
727
        VIR_ERROR(_("libhal_ctx_new returned NULL"));
728 729 730 731
        goto failure;
    }
    dbus_conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
    if (dbus_conn == NULL) {
732
        VIR_ERROR(_("dbus_bus_get failed"));
G
Guido Günther 已提交
733 734 735 736
        /* We don't want to show a fatal error here,
           otherwise entire libvirtd shuts down when
           D-Bus isn't running */
        ret = 0;
737 738
        goto failure;
    }
739 740
    dbus_connection_set_exit_on_disconnect(dbus_conn, FALSE);

741
    if (!libhal_ctx_set_dbus_connection(hal_ctx, dbus_conn)) {
742
        VIR_ERROR(_("libhal_ctx_set_dbus_connection failed"));
743 744 745
        goto failure;
    }
    if (!libhal_ctx_init(hal_ctx, &err)) {
746
        VIR_ERROR(_("libhal_ctx_init failed, haldaemon is probably not running"));
747 748 749 750
        /* We don't want to show a fatal error here,
           otherwise entire libvirtd shuts down when
           hald isn't running */
        ret = 0;
751 752 753 754 755 756 757 758
        goto failure;
    }

    /* Register dbus watch callbacks */
    if (!dbus_connection_set_watch_functions(dbus_conn,
                                             add_dbus_watch,
                                             remove_dbus_watch,
                                             toggle_dbus_watch,
759
                                             NULL, NULL)) {
760
        VIR_ERROR(_("dbus_connection_set_watch_functions failed"));
761 762 763
        goto failure;
    }

764 765 766 767 768 769 770 771 772 773
    /* Populate with known devices */
    driverState->privateData = hal_ctx;

    /* We need to unlock state now, since setting these callbacks cause
     * a dbus RPC call, and while this call is waiting for the reply,
     * a signal may already arrive, triggering the callback and thus
     * requiring the lock !
     */
    nodeDeviceUnlock(driverState);

774 775 776 777 778
    /* Register HAL event callbacks */
    if (!libhal_ctx_set_device_added(hal_ctx, device_added) ||
        !libhal_ctx_set_device_removed(hal_ctx, device_removed) ||
        !libhal_ctx_set_device_new_capability(hal_ctx, device_cap_added) ||
        !libhal_ctx_set_device_lost_capability(hal_ctx, device_cap_lost) ||
779
        !libhal_ctx_set_device_property_modified(hal_ctx, device_prop_modified) ||
780
        !libhal_device_property_watch_all(hal_ctx, &err)) {
781
        VIR_ERROR(_("setting up HAL callbacks failed"));
782 783 784 785 786
        goto failure;
    }

    udi = libhal_get_all_devices(hal_ctx, &num_devs, &err);
    if (udi == NULL) {
787
        VIR_ERROR(_("libhal_get_all_devices failed"));
788 789
        goto failure;
    }
790
    for (i = 0; i < num_devs; i++) {
791
        dev_create(udi[i]);
792 793 794
        VIR_FREE(udi[i]);
    }
    VIR_FREE(udi);
795 796 797 798 799

    return 0;

 failure:
    if (dbus_error_is_set(&err)) {
800
        VIR_ERROR(_("%s: %s"), err.name, err.message);
801 802 803 804 805
        dbus_error_free(&err);
    }
    virNodeDeviceObjListFree(&driverState->devs);
    if (hal_ctx)
        (void)libhal_ctx_free(hal_ctx);
806
    nodeDeviceUnlock(driverState);
807 808
    VIR_FREE(driverState);

809
    return ret;
810 811 812 813 814 815
}


static int halDeviceMonitorShutdown(void)
{
    if (driverState) {
816
        nodeDeviceLock(driverState);
817 818 819 820
        LibHalContext *hal_ctx = DRV_STATE_HAL_CTX(driverState);
        virNodeDeviceObjListFree(&driverState->devs);
        (void)libhal_ctx_shutdown(hal_ctx, NULL);
        (void)libhal_ctx_free(hal_ctx);
821
        nodeDeviceUnlock(driverState);
822
        virMutexDestroy(&driverState->lock);
823 824 825 826 827 828 829 830 831
        VIR_FREE(driverState);
        return 0;
    }
    return -1;
}


static int halDeviceMonitorReload(void)
{
832 833 834 835 836
    DBusError err;
    char **udi = NULL;
    int num_devs, i;
    LibHalContext *hal_ctx;

837
    VIR_INFO("Reloading HAL device state");
838
    nodeDeviceLock(driverState);
839
    VIR_INFO("Removing existing objects");
840 841 842 843
    virNodeDeviceObjListFree(&driverState->devs);
    nodeDeviceUnlock(driverState);

    hal_ctx = DRV_STATE_HAL_CTX(driverState);
844
    VIR_INFO("Creating new objects");
845 846 847
    dbus_error_init(&err);
    udi = libhal_get_all_devices(hal_ctx, &num_devs, &err);
    if (udi == NULL) {
848
        VIR_ERROR(_("libhal_get_all_devices failed"));
849 850 851 852 853 854 855
        return -1;
    }
    for (i = 0; i < num_devs; i++) {
        dev_create(udi[i]);
        VIR_FREE(udi[i]);
    }
    VIR_FREE(udi);
856
    VIR_INFO("HAL device reload complete");
857 858

    return 0;
859 860 861 862 863 864 865 866 867 868 869 870
}


static int halDeviceMonitorActive(void)
{
    /* Always ready to deal with a shutdown */
    return 0;
}


static virDrvOpenStatus halNodeDrvOpen(virConnectPtr conn,
                                       virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
871
                                       unsigned int flags)
872
{
E
Eric Blake 已提交
873 874
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
    if (driverState == NULL)
        return VIR_DRV_OPEN_DECLINED;

    conn->devMonPrivateData = driverState;

    return VIR_DRV_OPEN_SUCCESS;
}

static int halNodeDrvClose(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    conn->devMonPrivateData = NULL;
    return 0;
}


static virDeviceMonitor halDeviceMonitor = {
    .name = "halDeviceMonitor",
892 893 894 895 896 897 898 899 900 901 902
    .open = halNodeDrvOpen, /* 0.5.0 */
    .close = halNodeDrvClose, /* 0.5.0 */
    .numOfDevices = nodeNumOfDevices, /* 0.5.0 */
    .listDevices = nodeListDevices, /* 0.5.0 */
    .deviceLookupByName = nodeDeviceLookupByName, /* 0.5.0 */
    .deviceGetXMLDesc = nodeDeviceGetXMLDesc, /* 0.5.0 */
    .deviceGetParent = nodeDeviceGetParent, /* 0.5.0 */
    .deviceNumOfCaps = nodeDeviceNumOfCaps, /* 0.5.0 */
    .deviceListCaps = nodeDeviceListCaps, /* 0.5.0 */
    .deviceCreateXML = nodeDeviceCreateXML, /* 0.6.5 */
    .deviceDestroy = nodeDeviceDestroy, /* 0.6.5 */
903 904 905 906
};


static virStateDriver halStateDriver = {
907
    .name = "HAL",
908 909 910 911
    .initialize = halDeviceMonitorStartup, /* 0.5.0 */
    .cleanup = halDeviceMonitorShutdown, /* 0.5.0 */
    .reload = halDeviceMonitorReload, /* 0.5.0 */
    .active = halDeviceMonitorActive, /* 0.5.0 */
912 913 914 915 916 917 918 919
};

int halNodeRegister(void)
{
    if (virRegisterDeviceMonitor(&halDeviceMonitor) < 0)
        return -1;
    return virRegisterStateDriver(&halStateDriver);
}