virmdev.c 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * virmdev.c: helper APIs for managing host mediated devices
 *
 * 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, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include "dirname.h"
#include "virmdev.h"
#include "virlog.h"
#include "virerror.h"
#include "virfile.h"
#include "virstring.h"
27
#include "viralloc.h"
28 29 30

#define VIR_FROM_THIS VIR_FROM_NONE

31 32
#define MDEV_SYSFS_DEVICES "/sys/bus/mdev/devices/"

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
VIR_LOG_INIT("util.mdev");

struct _virMediatedDevice {
    char *path;                             /* sysfs path */
    virMediatedDeviceModelType model;

    char *used_by_drvname;
    char *used_by_domname;
};

struct _virMediatedDeviceList {
    virObjectLockable parent;

    size_t count;
    virMediatedDevicePtr *devs;
};

50 51
VIR_ENUM_IMPL(virMediatedDeviceModel,
              VIR_MDEV_MODEL_TYPE_LAST,
52
              "vfio-pci",
B
Boris Fiuczynski 已提交
53
              "vfio-ccw",
54 55
              "vfio-ap",
);
56 57 58 59 60 61 62 63 64

static virClassPtr virMediatedDeviceListClass;

static void
virMediatedDeviceListDispose(void *obj);

static int
virMediatedOnceInit(void)
{
65
    if (!VIR_CLASS_NEW(virMediatedDeviceList, virClassForObjectLockable()))
66 67 68 69 70
        return -1;

    return 0;
}

71
VIR_ONCE_GLOBAL_INIT(virMediated);
72 73 74 75 76 77 78

#ifdef __linux__

static int
virMediatedDeviceGetSysfsDeviceAPI(virMediatedDevicePtr dev,
                                   char **device_api)
{
79 80
    g_autofree char *buf = NULL;
    g_autofree char *file = NULL;
81 82 83
    char *tmp = NULL;

    if (virAsprintf(&file, "%s/mdev_type/device_api", dev->path) < 0)
84
        return -1;
85 86 87 88 89 90

    /* TODO - make this a generic method to access sysfs files for various
     * kinds of devices
     */
    if (!virFileExists(file)) {
        virReportSystemError(errno, _("failed to read '%s'"), file);
91
        return -1;
92 93 94
    }

    if (virFileReadAll(file, 1024, &buf) < 0)
95
        return -1;
96 97 98 99 100 101 102

    if ((tmp = strchr(buf, '\n')))
        *tmp = '\0';

    *device_api = buf;
    buf = NULL;

103
    return 0;
104 105 106 107 108 109 110
}


static int
virMediatedDeviceCheckModel(virMediatedDevicePtr dev,
                            virMediatedDeviceModelType model)
{
111
    g_autofree char *dev_api = NULL;
112 113 114 115 116 117 118 119 120 121 122 123
    int actual_model;

    if (virMediatedDeviceGetSysfsDeviceAPI(dev, &dev_api) < 0)
        return -1;

    /* safeguard in case we've got an older libvirt which doesn't know newer
     * device_api models yet
     */
    if ((actual_model = virMediatedDeviceModelTypeFromString(dev_api)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("device API '%s' not supported yet"),
                       dev_api);
124
        return -1;
125 126 127 128 129 130 131 132
    }

    if (actual_model != model) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid device API '%s' for device %s: "
                         "device only supports '%s'"),
                       virMediatedDeviceModelTypeToString(model),
                       dev->path, dev_api);
133
        return -1;
134 135
    }

136
    return 0;
137 138 139 140 141 142 143
}


virMediatedDevicePtr
virMediatedDeviceNew(const char *uuidstr, virMediatedDeviceModelType model)
{
    virMediatedDevicePtr ret = NULL;
J
Ján Tomko 已提交
144
    g_autoptr(virMediatedDevice) dev = NULL;
145
    g_autofree char *sysfspath = NULL;
146

147
    if (!(sysfspath = virMediatedDeviceGetSysfsPath(uuidstr)))
148
        return NULL;
149

150 151 152
    if (!virFileExists(sysfspath)) {
        virReportError(VIR_ERR_DEVICE_MISSING,
                       _("mediated device '%s' not found"), uuidstr);
153
        return NULL;
154 155 156
    }

    if (VIR_ALLOC(dev) < 0)
157
        return NULL;
158

159
    dev->path = g_steal_pointer(&sysfspath);
160 161 162 163 164

    /* Check whether the user-provided model corresponds with the actually
     * supported mediated device's API.
     */
    if (virMediatedDeviceCheckModel(dev, model))
165
        return NULL;
166 167

    dev->model = model;
168
    ret = g_steal_pointer(&dev);
169 170 171 172 173 174 175

    return ret;
}

#else

virMediatedDevicePtr
J
Ján Tomko 已提交
176 177
virMediatedDeviceNew(const char *uuidstr G_GNUC_UNUSED,
                     virMediatedDeviceModelType model G_GNUC_UNUSED)
178
{
179 180 181
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("mediated devices are not supported on non-linux "
                     "platforms"));
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
    return NULL;
}

#endif /* __linux__ */

void
virMediatedDeviceFree(virMediatedDevicePtr dev)
{
    if (!dev)
        return;
    VIR_FREE(dev->path);
    VIR_FREE(dev->used_by_drvname);
    VIR_FREE(dev->used_by_domname);
    VIR_FREE(dev);
}


const char *
virMediatedDeviceGetPath(virMediatedDevicePtr dev)
{
    return dev->path;
}


/* Returns an absolute canonicalized path to the device used to control the
 * mediated device's IOMMU group (e.g. "/dev/vfio/15"). Caller is responsible
 * for freeing the result.
 */
char *
211
virMediatedDeviceGetIOMMUGroupDev(const char *uuidstr)
212
{
213 214 215
    g_autofree char *result_path = NULL;
    g_autofree char *iommu_path = NULL;
    g_autofree char *dev_path = virMediatedDeviceGetSysfsPath(uuidstr);
216 217
    char *vfio_path = NULL;

218
    if (!dev_path)
219 220
        return NULL;

221
    if (virAsprintf(&iommu_path, "%s/iommu_group", dev_path) < 0)
222
        return NULL;
223

224 225
    if (!virFileExists(iommu_path)) {
        virReportSystemError(errno, _("failed to access '%s'"), iommu_path);
226
        return NULL;
227 228
    }

229
    if (virFileResolveLink(iommu_path, &result_path) < 0) {
230
        virReportSystemError(errno, _("failed to resolve '%s'"), iommu_path);
231
        return NULL;
232 233
    }

234
    if (virAsprintf(&vfio_path, "/dev/vfio/%s", last_component(result_path)) < 0)
235
        return NULL;
236 237 238 239 240 241

    return vfio_path;
}


int
242
virMediatedDeviceGetIOMMUGroupNum(const char *uuidstr)
243
{
244
    g_autofree char *vfio_path = NULL;
245 246 247
    char *group_num_str = NULL;
    unsigned int group_num = -1;

248
    if (!(vfio_path = virMediatedDeviceGetIOMMUGroupDev(uuidstr)))
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 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
        return -1;

    group_num_str = last_component(vfio_path);
    ignore_value(virStrToLong_ui(group_num_str, NULL, 10, &group_num));

    return group_num;
}


void
virMediatedDeviceGetUsedBy(virMediatedDevicePtr dev,
                           const char **drvname, const char **domname)
{
    *drvname = dev->used_by_drvname;
    *domname = dev->used_by_domname;
}


int
virMediatedDeviceSetUsedBy(virMediatedDevicePtr dev,
                           const char *drvname,
                           const char *domname)
{
    VIR_FREE(dev->used_by_drvname);
    VIR_FREE(dev->used_by_domname);
    if (VIR_STRDUP(dev->used_by_drvname, drvname) < 0)
        return -1;
    if (VIR_STRDUP(dev->used_by_domname, domname) < 0)
        return -1;

    return 0;
}


virMediatedDeviceListPtr
virMediatedDeviceListNew(void)
{
    virMediatedDeviceListPtr list;

    if (virMediatedInitialize() < 0)
        return NULL;

    if (!(list = virObjectLockableNew(virMediatedDeviceListClass)))
        return NULL;

    return list;
}


static void
virMediatedDeviceListDispose(void *obj)
{
    virMediatedDeviceListPtr list = obj;
    size_t i;

    for (i = 0; i < list->count; i++) {
        virMediatedDeviceFree(list->devs[i]);
        list->devs[i] = NULL;
    }

    list->count = 0;
    VIR_FREE(list->devs);
}


314 315 316
/* The reason for @dev to be double pointer is that VIR_APPEND_ELEMENT clears
 * the pointer and we need to clear the original not a copy on the stack
 */
317 318
int
virMediatedDeviceListAdd(virMediatedDeviceListPtr list,
319
                         virMediatedDevicePtr *dev)
320
{
321
    if (virMediatedDeviceListFind(list, *dev)) {
322
        virReportError(VIR_ERR_INTERNAL_ERROR,
323
                       _("device %s is already in use"), (*dev)->path);
324 325
        return -1;
    }
326
    return VIR_APPEND_ELEMENT(list->devs, list->count, *dev);
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
}


virMediatedDevicePtr
virMediatedDeviceListGet(virMediatedDeviceListPtr list,
                         ssize_t idx)
{
    if (idx < 0 || idx >= list->count)
        return NULL;

    return list->devs[idx];
}


size_t
virMediatedDeviceListCount(virMediatedDeviceListPtr list)
{
    return list->count;
}


virMediatedDevicePtr
virMediatedDeviceListStealIndex(virMediatedDeviceListPtr list,
                                ssize_t idx)
{
    virMediatedDevicePtr ret;

    if (idx < 0 || idx >= list->count)
        return NULL;

    ret = list->devs[idx];
    VIR_DELETE_ELEMENT(list->devs, idx, list->count);
    return ret;
}


virMediatedDevicePtr
virMediatedDeviceListSteal(virMediatedDeviceListPtr list,
                           virMediatedDevicePtr dev)
{
    int idx = virMediatedDeviceListFindIndex(list, dev);

    return virMediatedDeviceListStealIndex(list, idx);
}


void
virMediatedDeviceListDel(virMediatedDeviceListPtr list,
                         virMediatedDevicePtr dev)
{
377
    virMediatedDeviceFree(virMediatedDeviceListSteal(list, dev));
378 379 380 381 382 383 384 385 386 387 388 389 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
}


int
virMediatedDeviceListFindIndex(virMediatedDeviceListPtr list,
                               virMediatedDevicePtr dev)
{
    size_t i;

    for (i = 0; i < list->count; i++) {
        virMediatedDevicePtr other = list->devs[i];
        if (STREQ(other->path, dev->path))
            return i;
    }
    return -1;
}


virMediatedDevicePtr
virMediatedDeviceListFind(virMediatedDeviceListPtr list,
                          virMediatedDevicePtr dev)
{
    int idx;

    if ((idx = virMediatedDeviceListFindIndex(list, dev)) >= 0)
        return list->devs[idx];
    else
        return NULL;
}


bool
virMediatedDeviceIsUsed(virMediatedDevicePtr dev,
                        virMediatedDeviceListPtr list)
{
    const char *drvname, *domname;
    virMediatedDevicePtr tmp = NULL;

    if ((tmp = virMediatedDeviceListFind(list, dev))) {
        virMediatedDeviceGetUsedBy(tmp, &drvname, &domname);
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("mediated device %s is in use by "
                         "driver %s, domain %s"),
                       tmp->path, drvname, domname);
    }

    return !!tmp;
}


char *
virMediatedDeviceGetSysfsPath(const char *uuidstr)
{
    char *ret = NULL;

    ignore_value(virAsprintf(&ret, MDEV_SYSFS_DEVICES "%s", uuidstr));
    return ret;
}


int
virMediatedDeviceListMarkDevices(virMediatedDeviceListPtr dst,
                                 virMediatedDeviceListPtr src,
                                 const char *drvname,
                                 const char *domname)
{
    int ret = -1;
    size_t count = virMediatedDeviceListCount(src);
    size_t i, j;

    virObjectLock(dst);
    for (i = 0; i < count; i++) {
        virMediatedDevicePtr mdev = virMediatedDeviceListGet(src, i);

        if (virMediatedDeviceIsUsed(mdev, dst) ||
            virMediatedDeviceSetUsedBy(mdev, drvname, domname) < 0)
            goto cleanup;

        /* Copy mdev references to the driver list:
457
         * - caller is responsible for NOT freeing devices in @src on success
458 459
         * - we're responsible for performing a rollback on failure
         */
460 461
        VIR_DEBUG("Add '%s' to list of active mediated devices used by '%s'",
                  mdev->path, domname);
462
        if (virMediatedDeviceListAdd(dst, &mdev) < 0)
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
            goto rollback;

    }

    ret = 0;
 cleanup:
    virObjectUnlock(dst);
    return ret;

 rollback:
    for (j = 0; j < i; j++) {
        virMediatedDevicePtr tmp = virMediatedDeviceListGet(src, j);
        virMediatedDeviceListSteal(dst, tmp);
    }
    goto cleanup;
}
479 480 481 482 483 484 485 486 487 488 489 490 491


void
virMediatedDeviceTypeFree(virMediatedDeviceTypePtr type)
{
    if (!type)
        return;

    VIR_FREE(type->id);
    VIR_FREE(type->name);
    VIR_FREE(type->device_api);
    VIR_FREE(type);
}
492 493 494 495 496 497


int
virMediatedDeviceTypeReadAttrs(const char *sysfspath,
                               virMediatedDeviceTypePtr *type)
{
J
Ján Tomko 已提交
498
    g_autoptr(virMediatedDeviceType) tmp = NULL;
499

500
#define MDEV_GET_SYSFS_ATTR(attr, dst, cb, optional) \
501
    do { \
502 503 504
        int rc; \
        if ((rc = cb(dst, "%s/%s", sysfspath, attr)) < 0) { \
            if (rc != -2 || !optional) \
505
                return -1; \
506
        } \
507 508 509
    } while (0)

    if (VIR_ALLOC(tmp) < 0)
510
        return -1;
511 512

    if (VIR_STRDUP(tmp->id, last_component(sysfspath)) < 0)
513
        return -1;
514

515 516 517 518
    /* @name sysfs attribute is optional, so getting ENOENT is fine */
    MDEV_GET_SYSFS_ATTR("name", &tmp->name, virFileReadValueString, true);
    MDEV_GET_SYSFS_ATTR("device_api", &tmp->device_api,
                        virFileReadValueString, false);
519
    MDEV_GET_SYSFS_ATTR("available_instances", &tmp->available_instances,
520
                        virFileReadValueUint, false);
521 522 523

#undef MDEV_GET_SYSFS_ATTR

524
    *type = g_steal_pointer(&tmp);
525 526

    return 0;
527
}