storage_backend_scsi.c 18.0 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
/*
 * storage_backend_scsi.c: storage backend for SCSI handling
 *
 * Copyright (C) 2007-2008 Red Hat, Inc.
 * Copyright (C) 2007-2008 Daniel P. Berrange
 *
 * 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: Daniel P. Berrange <berrange redhat com>
 */

#include <config.h>

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <fcntl.h>

#include "virterror_internal.h"
#include "storage_backend_scsi.h"
#include "memory.h"
#include "logging.h"

#define VIR_FROM_THIS VIR_FROM_STORAGE

/* Function to check if the type file in the given sysfs_path is a
 * Direct-Access device (i.e. type 0).  Return -1 on failure, type of
 * the device otherwise.
 */
static int
getDeviceType(virConnectPtr conn,
              uint32_t host,
              uint32_t bus,
              uint32_t target,
              uint32_t lun,
              int *type)
{
    char *type_path = NULL;
    char typestr[3];
    char *gottype, *p;
    FILE *typefile;
    int retval = 0;

    if (virAsprintf(&type_path, "/sys/bus/scsi/devices/%u:%u:%u:%u/type",
                    host, bus, target, lun) < 0) {
58
        virReportOOMError();
59 60 61 62 63
        goto out;
    }

    typefile = fopen(type_path, "r");
    if (typefile == NULL) {
64
        virReportSystemError(errno,
65 66 67 68 69 70 71 72 73 74 75
                             _("Could not find typefile '%s'"),
                             type_path);
        /* there was no type file; that doesn't seem right */
        retval = -1;
        goto out;
    }

    gottype = fgets(typestr, 3, typefile);
    fclose(typefile);

    if (gottype == NULL) {
76
        virReportSystemError(errno,
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
                             _("Could not read typefile '%s'"),
                             type_path);
        /* we couldn't read the type file; have to give up */
        retval = -1;
        goto out;
    }

    /* we don't actually care about p, but if you pass NULL and the last
     * character is not \0, virStrToLong_i complains
     */
    if (virStrToLong_i(typestr, &p, 10, type) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Device type '%s' is not an integer"),
                              typestr);
        /* Hm, type wasn't an integer; seems strange */
        retval = -1;
        goto out;
    }

    VIR_DEBUG(_("Device type is %d"), *type);

out:
    VIR_FREE(type_path);
    return retval;
}

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
struct diskType {
    int part_table_type;
    unsigned short offset;
    unsigned short length;
    unsigned long long magic;
};

static struct diskType const disk_types[] = {
    { VIR_STORAGE_POOL_DISK_LVM2, 0x218, 8, 0x31303020324D564CULL },
    { VIR_STORAGE_POOL_DISK_GPT,  0x200, 8, 0x5452415020494645ULL },
    { VIR_STORAGE_POOL_DISK_DVH,  0x0,   4, 0x41A9E50BULL },
    { VIR_STORAGE_POOL_DISK_MAC,  0x0,   2, 0x5245ULL },
    { VIR_STORAGE_POOL_DISK_BSD,  0x40,  4, 0x82564557ULL },
    { VIR_STORAGE_POOL_DISK_SUN,  0x1fc, 2, 0xBEDAULL },
    /*
     * NOTE: pc98 is funky; the actual signature is 0x55AA (just like dos), so
     * we can't use that.  At the moment I'm relying on the "dummy" IPL
     * bootloader data that comes from parted.  Luckily, the chances of running
     * into a pc98 machine running libvirt are approximately nil.
     */
    /*{ 0x1fe, 2, 0xAA55UL },*/
    { VIR_STORAGE_POOL_DISK_PC98, 0x0,   8, 0x314C5049000000CBULL },
    /*
     * NOTE: the order is important here; some other disk types (like GPT and
     * and PC98) also have 0x55AA at this offset.  For that reason, the DOS
     * one must be the last one.
     */
    { VIR_STORAGE_POOL_DISK_DOS,  0x1fe, 2, 0xAA55ULL },
    { -1,                         0x0,   0, 0x0ULL },
};

static int
135
virStorageBackendSCSIUpdateVolTargetInfo(virStorageVolTargetPtr target,
136 137 138
                                         unsigned long long *allocation,
                                         unsigned long long *capacity)
{
139
    int fd, i, ret = -1;
140 141 142 143 144
    off_t start;
    unsigned char buffer[1024];
    ssize_t bytes;

    if ((fd = open(target->path, O_RDONLY)) < 0) {
145
        virReportSystemError(errno,
146 147 148 149 150
                             _("cannot open volume '%s'"),
                             target->path);
        return -1;
    }

151
    if (virStorageBackendUpdateVolTargetInfoFD(target,
152 153 154
                                               fd,
                                               allocation,
                                               capacity) < 0)
155
        goto cleanup;
156 157 158 159 160 161

    /* make sure to set the target format "unknown" to begin with */
    target->format = VIR_STORAGE_POOL_DISK_UNKNOWN;

    start = lseek(fd, 0, SEEK_SET);
    if (start < 0) {
162
        virReportSystemError(errno,
163 164
                             _("cannot seek to beginning of file '%s'"),
                             target->path);
165
        goto cleanup;
166 167 168
    }
    bytes = saferead(fd, buffer, sizeof(buffer));
    if (bytes < 0) {
169
        virReportSystemError(errno,
170 171
                             _("cannot read beginning of file '%s'"),
                             target->path);
172
        goto cleanup;
173 174 175 176 177 178 179 180 181 182 183 184
    }

    for (i = 0; disk_types[i].part_table_type != -1; i++) {
        if (disk_types[i].offset + disk_types[i].length > bytes)
            continue;
        if (memcmp(buffer+disk_types[i].offset, &disk_types[i].magic,
            disk_types[i].length) == 0) {
            target->format = disk_types[i].part_table_type;
            break;
        }
    }

185 186 187 188 189 190
    ret = 0;

  cleanup:
    close(fd);

    return ret;
191
}
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

static int
virStorageBackendSCSINewLun(virConnectPtr conn,
                            virStoragePoolObjPtr pool,
                            uint32_t host,
                            uint32_t bus,
                            uint32_t target,
                            uint32_t lun,
                            const char *dev)
{
    virStorageVolDefPtr vol;
    char *devpath = NULL;
    int retval = 0;

    if (VIR_ALLOC(vol) < 0) {
207
        virReportOOMError();
208 209 210 211 212 213 214
        retval = -1;
        goto out;
    }

    vol->type = VIR_STORAGE_VOL_BLOCK;

    if (virAsprintf(&(vol->name), "%u.%u.%u.%u", host, bus, target, lun) < 0) {
215
        virReportOOMError();
216 217 218 219 220
        retval = -1;
        goto free_vol;
    }

    if (virAsprintf(&devpath, "/dev/%s", dev) < 0) {
221
        virReportOOMError();
222 223 224 225 226 227 228 229 230 231 232 233
        retval = -1;
        goto free_vol;
    }

    VIR_DEBUG(_("Trying to create volume for '%s'"), devpath);

    /* Now figure out the stable path
     *
     * XXX this method is O(N) because it scans the pool target
     * dir every time its run. Should figure out a more efficient
     * way of doing this...
     */
234
    if ((vol->target.path = virStorageBackendStablePath(pool,
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                                                        devpath)) == NULL) {
        retval = -1;
        goto free_vol;
    }

    if (STREQLEN(devpath, vol->target.path, PATH_MAX) &&
        !(STREQ(pool->def->target.path, "/dev") ||
          STREQ(pool->def->target.path, "/dev/"))) {

        VIR_DEBUG(_("No stable path found for '%s' in '%s'"),
                  devpath, pool->def->target.path);

        retval = -1;
        goto free_vol;
    }

251
    if (virStorageBackendSCSIUpdateVolTargetInfo(&vol->target,
252 253
                                                 &vol->allocation,
                                                 &vol->capacity) < 0) {
254 255 256 257 258 259 260 261 262 263 264

        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to update volume for '%s'"),
                              devpath);
        retval = -1;
        goto free_vol;
    }

    /* XXX should use logical unit's UUID instead */
    vol->key = strdup(vol->target.path);
    if (vol->key == NULL) {
265
        virReportOOMError();
266 267 268 269 270 271 272 273 274
        retval = -1;
        goto free_vol;
    }

    pool->def->capacity += vol->capacity;
    pool->def->allocation += vol->allocation;

    if (VIR_REALLOC_N(pool->volumes.objs,
                      pool->volumes.count + 1) < 0) {
275
        virReportOOMError();
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        retval = -1;
        goto free_vol;
    }
    pool->volumes.objs[pool->volumes.count++] = vol;

    goto out;

free_vol:
    virStorageVolDefFree(vol);
out:
    VIR_FREE(devpath);
    return retval;
}


static int
292
getNewStyleBlockDevice(virConnectPtr conn ATTRIBUTE_UNUSED /*TEMPORARY*/,
293 294 295 296 297 298 299 300 301 302
                       const char *lun_path,
                       const char *block_name ATTRIBUTE_UNUSED,
                       char **block_device)
{
    char *block_path = NULL;
    DIR *block_dir = NULL;
    struct dirent *block_dirent = NULL;
    int retval = 0;

    if (virAsprintf(&block_path, "%s/block", lun_path) < 0) {
303
        virReportOOMError();
304 305 306 307 308 309 310
        goto out;
    }

    VIR_DEBUG(_("Looking for block device in '%s'"), block_path);

    block_dir = opendir(block_path);
    if (block_dir == NULL) {
311
        virReportSystemError(errno,
312 313 314 315 316 317 318 319 320 321 322 323 324
                             _("Failed to opendir sysfs path '%s'"),
                             block_path);
        retval = -1;
        goto out;
    }

    while ((block_dirent = readdir(block_dir))) {

        if (STREQLEN(block_dirent->d_name, ".", 1)) {
            continue;
        }

        *block_device = strdup(block_dirent->d_name);
325 326

        if (*block_device == NULL) {
327
            virReportOOMError();
328 329 330 331 332
            closedir(block_dir);
            retval = -1;
            goto out;
        }

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
        VIR_DEBUG(_("Block device is '%s'"), *block_device);

        break;
    }

    closedir(block_dir);

out:
    VIR_FREE(block_path);
    return retval;
}


static int
getOldStyleBlockDevice(virConnectPtr conn,
                       const char *lun_path ATTRIBUTE_UNUSED,
                       const char *block_name,
                       char **block_device)
{
    char *blockp = NULL;
    int retval = 0;

    /* old-style; just parse out the sd */
    blockp = strrchr(block_name, ':');
    if (blockp == NULL) {
        /* Hm, wasn't what we were expecting; have to give up */
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to parse block name %s"),
                              block_name);
        retval = -1;
    } else {
        blockp++;
        *block_device = strdup(blockp);

367
        if (*block_device == NULL) {
368
            virReportOOMError();
369 370 371 372
            retval = -1;
            goto out;
        }

373 374 375
        VIR_DEBUG(_("Block device is '%s'"), *block_device);
    }

376
out:
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    return retval;
}


static int
getBlockDevice(virConnectPtr conn,
               uint32_t host,
               uint32_t bus,
               uint32_t target,
               uint32_t lun,
               char **block_device)
{
    char *lun_path = NULL;
    DIR *lun_dir = NULL;
    struct dirent *lun_dirent = NULL;
    int retval = 0;

    if (virAsprintf(&lun_path, "/sys/bus/scsi/devices/%u:%u:%u:%u",
                    host, bus, target, lun) < 0) {
396
        virReportOOMError();
397 398 399 400 401
        goto out;
    }

    lun_dir = opendir(lun_path);
    if (lun_dir == NULL) {
402
        virReportSystemError(errno,
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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
                             _("Failed to opendir sysfs path '%s'"),
                             lun_path);
        retval = -1;
        goto out;
    }

    while ((lun_dirent = readdir(lun_dir))) {
        if (STREQLEN(lun_dirent->d_name, "block", 5)) {
            if (strlen(lun_dirent->d_name) == 5) {
                retval = getNewStyleBlockDevice(conn,
                                                lun_path,
                                                lun_dirent->d_name,
                                                block_device);
            } else {
                retval = getOldStyleBlockDevice(conn,
                                                lun_path,
                                                lun_dirent->d_name,
                                                block_device);
            }
            break;
        }
    }

    closedir(lun_dir);

out:
    VIR_FREE(lun_path);
    return retval;
}


static int
processLU(virConnectPtr conn,
          virStoragePoolObjPtr pool,
          uint32_t host,
          uint32_t bus,
          uint32_t target,
          uint32_t lun)
{
    char *type_path = NULL;
    int retval = 0;
    int device_type;
    char *block_device = NULL;

    VIR_DEBUG(_("Processing LU %u:%u:%u:%u"),
              host, bus, target, lun);

    if (getDeviceType(conn, host, bus, target, lun, &device_type) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("Failed to determine if %u:%u:%u:%u is a Direct-Access LUN"),
                              host, bus, target, lun);
        retval = -1;
        goto out;
    }

    /* We don't create volumes for devices other than disk and cdrom
     * devices, but finding a device that isn't one of those types
     * isn't an error, either. */
    if (!(device_type == VIR_STORAGE_DEVICE_TYPE_DISK ||
          device_type == VIR_STORAGE_DEVICE_TYPE_ROM))
    {
        retval = 0;
        goto out;
    }

    VIR_DEBUG(_("%u:%u:%u:%u is a Direct-Access LUN"),
              host, bus, target, lun);

    if (getBlockDevice(conn, host, bus, target, lun, &block_device) < 0) {
        goto out;
    }

    if (virStorageBackendSCSINewLun(conn, pool,
                                    host, bus, target, lun,
                                    block_device) < 0) {
        VIR_DEBUG(_("Failed to create new storage volume for %u:%u:%u:%u"),
                  host, bus, target, lun);
        retval = -1;
        goto out;
    }

    VIR_DEBUG(_("Created new storage volume for %u:%u:%u:%u successfully"),
              host, bus, target, lun);

    VIR_FREE(type_path);

out:
    return retval;
}


int
virStorageBackendSCSIFindLUs(virConnectPtr conn,
                             virStoragePoolObjPtr pool,
                             uint32_t scanhost)
{
    int retval = 0;
    uint32_t bus, target, lun;
    char *device_path = NULL;
    DIR *devicedir = NULL;
    struct dirent *lun_dirent = NULL;
    char devicepattern[64];

    VIR_DEBUG(_("Discovering LUs on host %u"), scanhost);

508
    virFileWaitForDevices();
509 510

    if (virAsprintf(&device_path, "/sys/bus/scsi/devices") < 0) {
511
        virReportOOMError();
512 513 514 515 516 517
        goto out;
    }

    devicedir = opendir(device_path);

    if (devicedir == NULL) {
518
        virReportSystemError(errno,
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
                             _("Failed to opendir path '%s'"), device_path);
        retval = -1;
        goto out;
    }

    snprintf(devicepattern, sizeof(devicepattern), "%u:%%u:%%u:%%u\n", scanhost);

    while ((lun_dirent = readdir(devicedir))) {
        if (sscanf(lun_dirent->d_name, devicepattern,
                   &bus, &target, &lun) != 3) {
            continue;
        }

        VIR_DEBUG(_("Found LU '%s'"), lun_dirent->d_name);

        processLU(conn, pool, scanhost, bus, target, lun);
    }

    closedir(devicedir);

out:
    VIR_FREE(device_path);
    return retval;
}


int
546
virStorageBackendSCSIGetHostNumber(const char *sysfs_path,
547 548 549 550 551 552 553 554
                                   uint32_t *host)
{
    int retval = 0;
    DIR *sysdir = NULL;
    struct dirent *dirent = NULL;

    VIR_DEBUG(_("Finding host number from '%s'"), sysfs_path);

555
    virFileWaitForDevices();
556 557 558 559

    sysdir = opendir(sysfs_path);

    if (sysdir == NULL) {
560
        virReportSystemError(errno,
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
                             _("Failed to opendir path '%s'"), sysfs_path);
        retval = -1;
        goto out;
    }

    while ((dirent = readdir(sysdir))) {
        if (STREQLEN(dirent->d_name, "target", strlen("target"))) {
            if (sscanf(dirent->d_name,
                       "target%u:", host) != 1) {
                VIR_DEBUG(_("Failed to parse target '%s'"), dirent->d_name);
                retval = -1;
                break;
            }
        }
    }

    closedir(sysdir);
out:
    return retval;
}


583
static int
584
virStorageBackendSCSITriggerRescan(uint32_t host)
585 586 587 588 589 590 591 592
{
    int fd = -1;
    int retval = 0;
    char *path;

    VIR_DEBUG(_("Triggering rescan of host %d"), host);

    if (virAsprintf(&path, "/sys/class/scsi_host/host%u/scan", host) < 0) {
593
        virReportOOMError();
594 595 596 597 598 599 600 601 602
        retval = -1;
        goto out;
    }

    VIR_DEBUG(_("Scan trigger path is '%s'"), path);

    fd = open(path, O_WRONLY);

    if (fd < 0) {
603
        virReportSystemError(errno,
604 605 606 607 608 609 610 611 612 613
                             _("Could not open '%s' to trigger host scan"),
                             path);
        retval = -1;
        goto free_path;
    }

    if (safewrite(fd,
                  LINUX_SYSFS_SCSI_HOST_SCAN_STRING,
                  sizeof(LINUX_SYSFS_SCSI_HOST_SCAN_STRING)) < 0) {

614
        virReportSystemError(errno,
615 616 617 618 619 620 621 622 623 624 625 626 627 628
                             _("Write to '%s' to trigger host scan failed"),
                             path);
        retval = -1;
    }

    close(fd);
free_path:
    VIR_FREE(path);
out:
    VIR_DEBUG(_("Rescan of host %d complete"), host);
    return retval;
}


629 630 631 632 633 634 635 636 637 638
static int
virStorageBackendSCSIRefreshPool(virConnectPtr conn,
                                 virStoragePoolObjPtr pool)
{
    int retval = 0;
    uint32_t host;

    pool->def->allocation = pool->def->capacity = pool->def->available = 0;

    if (sscanf(pool->def->source.adapter, "host%u", &host) != 1) {
639 640
        VIR_DEBUG(_("Failed to get host number from '%s'"),
                    pool->def->source.adapter);
641 642 643 644 645 646
        retval = -1;
        goto out;
    }

    VIR_DEBUG(_("Scanning host%u"), host);

647
    if (virStorageBackendSCSITriggerRescan(host) < 0) {
648 649 650 651
        retval = -1;
        goto out;
    }

652 653 654 655 656 657 658 659 660 661 662 663
    virStorageBackendSCSIFindLUs(conn, pool, host);

out:
    return retval;
}


virStorageBackend virStorageBackendSCSI = {
    .type = VIR_STORAGE_POOL_SCSI,

    .refreshPool = virStorageBackendSCSIRefreshPool,
};