storage_backend_disk.c 25.9 KB
Newer Older
1 2 3
/*
 * storage_backend_disk.c: storage backend for disk handling
 *
4
 * Copyright (C) 2007-2008, 2010-2013 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>
C
Cole Robinson 已提交
25
#include <string.h>
26
#include <unistd.h>
27
#include <stdio.h>
28

29
#include "dirname.h"
30
#include "virerror.h"
31
#include "virlog.h"
32
#include "storage_backend_disk.h"
33
#include "viralloc.h"
34
#include "vircommand.h"
35
#include "virfile.h"
36
#include "configmake.h"
37
#include "virstring.h"
38

39 40
#define VIR_FROM_THIS VIR_FROM_STORAGE

41 42
VIR_LOG_INIT("storage.storage_backend_disk");

43
#define PARTHELPER LIBEXECDIR "/libvirt_parthelper"
44

45 46
#define SECTOR_SIZE 512

47
static int
48
virStorageBackendDiskMakeDataVol(virStoragePoolObjPtr pool,
49 50 51 52 53 54
                                 char **const groups,
                                 virStorageVolDefPtr vol)
{
    char *tmp, *devpath;

    if (vol == NULL) {
55
        if (VIR_ALLOC(vol) < 0)
56 57 58 59 60
            return -1;
        /* Prepended path will be same for all partitions, so we can
         * strip the path to form a reasonable pool-unique name
         */
        tmp = strrchr(groups[0], '/');
61
        if (VIR_STRDUP(vol->name, tmp ? tmp + 1 : groups[0]) < 0 ||
62 63
            VIR_APPEND_ELEMENT_COPY(pool->volumes.objs,
                                    pool->volumes.count, vol) < 0) {
64
            virStorageVolDefFree(vol);
65
            return -1;
66
        }
67 68 69
    }

    if (vol->target.path == NULL) {
70
        if (VIR_STRDUP(devpath, groups[0]) < 0)
71 72 73 74 75 76 77 78
            return -1;

        /* 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...
         */
79
        vol->target.path = virStorageBackendStablePath(pool, devpath, true);
80
        VIR_FREE(devpath);
81 82
        if (vol->target.path == NULL)
            return -1;
83 84 85 86
    }

    if (vol->key == NULL) {
        /* XXX base off a unique key of the underlying disk */
87
        if (VIR_STRDUP(vol->key, vol->target.path) < 0)
88 89 90 91
            return -1;
    }

    if (vol->source.extents == NULL) {
92
        if (VIR_ALLOC(vol->source.extents) < 0)
93 94 95 96 97
            return -1;
        vol->source.nextent = 1;

        if (virStrToLong_ull(groups[3], NULL, 10,
                             &vol->source.extents[0].start) < 0) {
98 99
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("cannot parse device start location"));
100 101 102 103 104
            return -1;
        }

        if (virStrToLong_ull(groups[4], NULL, 10,
                             &vol->source.extents[0].end) < 0) {
105 106
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("cannot parse device end location"));
107 108 109
            return -1;
        }

110 111
        if (VIR_STRDUP(vol->source.extents[0].path,
                       pool->def->source.devices[0].path) < 0)
112 113 114 115
            return -1;
    }

    /* Refresh allocation/capacity/perms */
116
    if (virStorageBackendUpdateVolInfo(vol, 1) < 0)
117 118
        return -1;

119
    /* set partition type */
E
Eric Blake 已提交
120
    if (STREQ(groups[1], "normal"))
121
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_PRIMARY;
E
Eric Blake 已提交
122
    else if (STREQ(groups[1], "logical"))
123
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_LOGICAL;
E
Eric Blake 已提交
124
    else if (STREQ(groups[1], "extended"))
125 126 127 128
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_EXTENDED;
    else
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_NONE;

129 130
    vol->type = VIR_STORAGE_VOL_BLOCK;

131 132 133 134 135 136 137 138 139 140 141 142 143 144
    /* The above gets allocation wrong for
     * extended partitions, so overwrite it */
    vol->allocation = vol->capacity =
        (vol->source.extents[0].end - vol->source.extents[0].start);

    if (STRNEQ(groups[2], "metadata"))
        pool->def->allocation += vol->allocation;
    if (vol->source.extents[0].end > pool->def->capacity)
        pool->def->capacity = vol->source.extents[0].end;

    return 0;
}

static int
145
virStorageBackendDiskMakeFreeExtent(virStoragePoolObjPtr pool,
146 147 148 149
                                    char **const groups)
{
    virStoragePoolSourceDevicePtr dev = &pool->def->source.devices[0];

150 151
    if (VIR_REALLOC_N(dev->freeExtents,
                      dev->nfreeExtent + 1) < 0)
152 153 154
        return -1;

    memset(dev->freeExtents +
155 156
           dev->nfreeExtent, 0,
           sizeof(dev->freeExtents[0]));
157

158
    /* set type of free area */
E
Eric Blake 已提交
159
    if (STREQ(groups[1], "logical")) {
160 161 162 163 164 165
        dev->freeExtents[dev->nfreeExtent].type = VIR_STORAGE_FREE_LOGICAL;
    } else {
        dev->freeExtents[dev->nfreeExtent].type = VIR_STORAGE_FREE_NORMAL;
    }


166 167 168 169 170 171 172 173
    if (virStrToLong_ull(groups[3], NULL, 10,
                         &dev->freeExtents[dev->nfreeExtent].start) < 0)
        return -1; /* Don't bother to re-alloc freeExtents - it'll be free'd shortly */

    if (virStrToLong_ull(groups[4], NULL, 10,
                         &dev->freeExtents[dev->nfreeExtent].end) < 0)
        return -1; /* Don't bother to re-alloc freeExtents - it'll be free'd shortly */

174 175 176 177 178
    /* first block reported as free, even if it is not */
    if (dev->freeExtents[dev->nfreeExtent].start == 0) {
        dev->freeExtents[dev->nfreeExtent].start = SECTOR_SIZE;
    }

179 180 181 182 183 184 185 186 187 188 189 190
    pool->def->available +=
        (dev->freeExtents[dev->nfreeExtent].end -
         dev->freeExtents[dev->nfreeExtent].start);
    if (dev->freeExtents[dev->nfreeExtent].end > pool->def->capacity)
        pool->def->capacity = dev->freeExtents[dev->nfreeExtent].end;

    dev->nfreeExtent++;

    return 0;
}


191 192 193 194 195
struct virStorageBackendDiskPoolVolData {
    virStoragePoolObjPtr pool;
    virStorageVolDefPtr vol;
};

196
static int
197
virStorageBackendDiskMakeVol(size_t ntok ATTRIBUTE_UNUSED,
198
                             char **const groups,
199
                             void *opaque)
200
{
201 202
    struct virStorageBackendDiskPoolVolData *data = opaque;
    virStoragePoolObjPtr pool = data->pool;
203 204 205 206 207 208 209 210 211 212 213 214
    /*
     * Ignore normal+metadata, and logical+metadata partitions
     * since they're basically internal book-keeping regions
     * we have no control over. Do keep extended+metadata though
     * because that's the MS-DOS extended partition region we
     * need to be able to view/create/delete
     */
    if ((STREQ(groups[1], "normal") ||
         STREQ(groups[1], "logical")) &&
        STREQ(groups[2], "metadata"))
        return 0;

R
Richard W.M. Jones 已提交
215
    /* Remaining data / metadata parts get turn into volumes... */
216 217
    if (STREQ(groups[2], "metadata") ||
        STREQ(groups[2], "data")) {
218
        virStorageVolDefPtr vol = data->vol;
219 220 221 222 223 224 225 226 227 228 229 230

        if (vol) {
            /* We're searching for a specific vol only */
            if (vol->key) {
                if (STRNEQ(vol->key, groups[0]))
                    return 0;
            } else if (virStorageVolDefFindByKey(pool, groups[0]) != NULL) {
                /* If no key, the volume must be newly created. If groups[0]
                 * isn't already a volume, assume it's the path we want */
                return 0;
            }
        }
231

232
        return virStorageBackendDiskMakeDataVol(pool, groups, vol);
233 234
    } else if (STREQ(groups[2], "free")) {
        /* ....or free space extents */
235
        return virStorageBackendDiskMakeFreeExtent(pool, groups);
236
    } else {
R
Richard W.M. Jones 已提交
237
        /* This code path should never happen unless someone changed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
         * libvirt_parthelper forgot to change this code */
        return -1;
    }
}

/* To get a list of partitions we run an external helper
 * tool which then uses parted APIs. This is because
 * parted's API is not compatible with libvirt's license
 * but we really really want to use parted because the
 * other options all suck :-)
 *
 * All the other storage backends run an external tool for
 * listing volumes so this really isn't too much of a pain,
 * and we can even ensure the output is friendly.
 */
static int
254
virStorageBackendDiskReadPartitions(virStoragePoolObjPtr pool,
255 256 257 258 259 260 261 262 263
                                    virStorageVolDefPtr vol)
{
    /*
     *  # libvirt_parthelper DEVICE
     * /dev/sda1      normal       data        32256    106928128    106896384
     * /dev/sda2      normal       data    106928640 100027629568  99920701440
     * -              normal   metadata 100027630080 100030242304      2612736
     *
     */
264 265 266
    virCommandPtr cmd = virCommandNewArgList(PARTHELPER,
                                             pool->def->source.devices[0].path,
                                             NULL);
267 268 269 270
    struct virStorageBackendDiskPoolVolData cbdata = {
        .pool = pool,
        .vol = vol,
    };
271
    int ret;
272 273 274

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

275 276 277 278
    ret = virCommandRunNul(cmd,
                           6,
                           virStorageBackendDiskMakeVol,
                           &cbdata);
279 280
    virCommandFree(cmd);
    return ret;
281 282
}

283
static int
284
virStorageBackendDiskMakePoolGeometry(size_t ntok ATTRIBUTE_UNUSED,
285
                                      char **const groups,
286
                                      void *data)
287
{
288
    virStoragePoolObjPtr pool = data;
P
Peter Krempa 已提交
289 290 291 292 293 294 295 296
    virStoragePoolSourceDevicePtr device = &(pool->def->source.devices[0]);
    if (virStrToLong_i(groups[0], NULL, 0, &device->geometry.cylinders) < 0 ||
        virStrToLong_i(groups[1], NULL, 0, &device->geometry.heads) < 0 ||
        virStrToLong_i(groups[2], NULL, 0, &device->geometry.sectors) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to create disk pool geometry"));
        return -1;
    }
297

P
Peter Krempa 已提交
298
    return 0;
299 300 301
}

static int
302
virStorageBackendDiskReadGeometry(virStoragePoolObjPtr pool)
303
{
304 305 306 307 308 309
    virCommandPtr cmd = virCommandNewArgList(PARTHELPER,
                                             pool->def->source.devices[0].path,
                                             "-g",
                                             NULL);
    int ret;

310 311 312 313
    ret = virCommandRunNul(cmd,
                           3,
                           virStorageBackendDiskMakePoolGeometry,
                           pool);
314 315
    virCommandFree(cmd);
    return ret;
316
}
317 318

static int
319
virStorageBackendDiskRefreshPool(virConnectPtr conn ATTRIBUTE_UNUSED,
320 321
                                 virStoragePoolObjPtr pool)
{
322
    VIR_FREE(pool->def->source.devices[0].freeExtents);
323 324
    pool->def->source.devices[0].nfreeExtent = 0;

325
    virFileWaitForDevices();
326

327
    if (!virFileExists(pool->def->source.devices[0].path)) {
328 329 330
        virReportError(VIR_ERR_INVALID_ARG,
                       _("device path '%s' doesn't exist"),
                       pool->def->source.devices[0].path);
331 332 333
        return -1;
    }

334
    if (virStorageBackendDiskReadGeometry(pool) != 0) {
335 336 337
        return -1;
    }

338
    return virStorageBackendDiskReadPartitions(pool, NULL);
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
/**
 * Check for a valid disk label (partition table) on device
 *
 * return: 0 - valid disk label found
 *        >0 - no or unrecognized disk label
 *        <0 - error finding the disk label
 */
static int
virStorageBackendDiskFindLabel(const char* device)
{
    const char *const args[] = {
        device, "print", "--script", NULL,
    };
    virCommandPtr cmd = virCommandNew(PARTED);
    char *output = NULL;
    int ret = -1;

    virCommandAddArgSet(cmd, args);
    virCommandAddEnvString(cmd, "LC_ALL=C");
    virCommandSetOutputBuffer(cmd, &output);

    /* if parted succeeds we have a valid partition table */
    ret = virCommandRun(cmd, NULL);
    if (ret < 0) {
366
        if (strstr(output, "unrecognised disk label"))
367 368 369 370 371 372 373 374 375
            ret = 1;
    }

    virCommandFree(cmd);
    VIR_FREE(output);
    return ret;
}


376 377 378 379
/**
 * Write a new partition table header
 */
static int
380
virStorageBackendDiskBuildPool(virConnectPtr conn ATTRIBUTE_UNUSED,
381
                               virStoragePoolObjPtr pool,
E
Eric Blake 已提交
382
                               unsigned int flags)
383
{
384 385
    bool ok_to_mklabel = false;
    int ret = -1;
386
    virCommandPtr cmd = NULL;
387

388 389
    virCheckFlags(VIR_STORAGE_POOL_BUILD_OVERWRITE |
                  VIR_STORAGE_POOL_BUILD_NO_OVERWRITE, ret);
E
Eric Blake 已提交
390

391 392
    if (flags == (VIR_STORAGE_POOL_BUILD_OVERWRITE |
                  VIR_STORAGE_POOL_BUILD_NO_OVERWRITE)) {
393
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
394 395
                       _("Overwrite and no overwrite flags"
                         " are mutually exclusive"));
396 397
        goto error;
    }
398

399 400 401 402 403
    if (flags & VIR_STORAGE_POOL_BUILD_OVERWRITE)
        ok_to_mklabel = true;
    else {
        int check;

404
        check = virStorageBackendDiskFindLabel(
405 406 407 408
                    pool->def->source.devices[0].path);
        if (check > 0) {
            ok_to_mklabel = true;
        } else if (check < 0) {
409
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
410
                           _("Error checking for disk label"));
411
        } else {
412
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
413
                           _("Disk label already present"));
414 415 416
        }
    }

417 418 419 420 421 422 423 424 425
    if (ok_to_mklabel) {
        /* eg parted /dev/sda mklabel msdos */
        cmd = virCommandNewArgList(PARTED,
                                   pool->def->source.devices[0].path,
                                   "mklabel",
                                   "--script",
                                   ((pool->def->source.format == VIR_STORAGE_POOL_DISK_DOS) ? "msdos" :
                                   virStoragePoolFormatDiskTypeToString(pool->def->source.format)),
                                   NULL);
426
        ret = virCommandRun(cmd, NULL);
427
    }
428

429
 error:
430
    virCommandFree(cmd);
431
    return ret;
432 433
}

434 435 436 437
/**
 * Decides what kind of partition type that should be created.
 * Important when the partition table is of msdos type
 */
438
static int
439 440 441 442 443
virStorageBackendDiskPartTypeToCreate(virStoragePoolObjPtr pool)
{
    if (pool->def->source.format == VIR_STORAGE_POOL_DISK_DOS) {
        /* count primary and extended paritions,
           can't be more than 3 to create a new primary partition */
444
        size_t i;
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        int count = 0;
        for (i = 0; i < pool->volumes.count; i++) {
             if (pool->volumes.objs[i]->target.type == VIR_STORAGE_VOL_DISK_TYPE_PRIMARY ||
                 pool->volumes.objs[i]->target.type == VIR_STORAGE_VOL_DISK_TYPE_EXTENDED) {
                     count++;
             }
        }
        if (count >= 4) {
            return VIR_STORAGE_VOL_DISK_TYPE_LOGICAL;
        }
    }

    /* for all other cases, all partitions are primary */
    return VIR_STORAGE_VOL_DISK_TYPE_PRIMARY;
}

static int
462
virStorageBackendDiskPartFormat(virStoragePoolObjPtr pool,
463
                                virStorageVolDefPtr vol,
E
Eric Blake 已提交
464
                                char** partFormat)
465
{
466
    size_t i;
467
    if (pool->def->source.format == VIR_STORAGE_POOL_DISK_DOS) {
E
Eric Blake 已提交
468 469 470
        const char *partedFormat;
        partedFormat = virStoragePartedFsTypeTypeToString(vol->target.format);
        if (partedFormat == NULL) {
471 472
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid partition type"));
E
Eric Blake 已提交
473
            return -1;
474 475 476 477
        }
        if (vol->target.format == VIR_STORAGE_VOL_DISK_EXTENDED) {
            /* make sure we don't have a extended partition already */
            for (i = 0; i < pool->volumes.count; i++) {
E
Eric Blake 已提交
478 479
                if (pool->volumes.objs[i]->target.format ==
                    VIR_STORAGE_VOL_DISK_EXTENDED) {
480 481
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("extended partition already exists"));
E
Eric Blake 已提交
482 483
                    return -1;
                }
484
            }
485
            if (VIR_STRDUP(*partFormat, partedFormat) < 0)
E
Eric Blake 已提交
486
                return -1;
487 488 489 490 491 492
        } else {
            /* create primary partition as long as it is possible
               and after that check if an extended partition exists
               to create logical partitions. */
            /* XXX Only support one extended partition */
            switch (virStorageBackendDiskPartTypeToCreate(pool)) {
E
Eric Blake 已提交
493
            case VIR_STORAGE_VOL_DISK_TYPE_PRIMARY:
494
                if (virAsprintf(partFormat, "primary %s", partedFormat) < 0)
E
Eric Blake 已提交
495
                    return -1;
E
Eric Blake 已提交
496 497 498 499 500 501
                break;
            case VIR_STORAGE_VOL_DISK_TYPE_LOGICAL:
                /* make sure we have a extended partition */
                for (i = 0; i < pool->volumes.count; i++) {
                    if (pool->volumes.objs[i]->target.format ==
                        VIR_STORAGE_VOL_DISK_EXTENDED) {
E
Eric Blake 已提交
502
                        if (virAsprintf(partFormat, "logical %s",
503
                                        partedFormat) < 0)
E
Eric Blake 已提交
504
                            return -1;
E
Eric Blake 已提交
505 506 507 508
                        break;
                    }
                }
                if (i == pool->volumes.count) {
509 510
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("no extended partition found and no primary partition available"));
E
Eric Blake 已提交
511 512 513 514
                    return -1;
                }
                break;
            default:
515 516
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("unknown partition type"));
E
Eric Blake 已提交
517
                return -1;
518 519 520
            }
        }
    } else {
521
        if (VIR_STRDUP(*partFormat, "primary") < 0)
E
Eric Blake 已提交
522
            return -1;
523 524 525 526 527
    }
    return 0;
}

/**
J
Ján Tomko 已提交
528
 * Aligns a new partition to nearest cylinder boundary
E
Eric Blake 已提交
529
 * when having a msdos partition table type
J
Ján Tomko 已提交
530
 * to avoid any problem with already existing
531 532 533
 * partitions
 */
static int
534
virStorageBackendDiskPartBoundries(virStoragePoolObjPtr pool,
535 536 537
                                   unsigned long long *start,
                                   unsigned long long *end,
                                   unsigned long long allocation)
538
{
539
    size_t i;
540
    int smallestExtent = -1;
541 542 543
    unsigned long long smallestSize = 0;
    unsigned long long extraBytes = 0;
    unsigned long long alignedAllocation = allocation;
544
    virStoragePoolSourceDevicePtr dev = &pool->def->source.devices[0];
545 546 547
    unsigned long long cylinderSize = dev->geometry.heads *
                                      dev->geometry.sectors * SECTOR_SIZE;

548
    VIR_DEBUG("find free area: allocation %llu, cyl size %llu", allocation,
E
Eric Blake 已提交
549
          cylinderSize);
550 551 552
    int partType = virStorageBackendDiskPartTypeToCreate(pool);

    /* how many extra bytes we have since we allocate
J
Ján Tomko 已提交
553
       aligned to the cylinder boundary */
554 555
    extraBytes = cylinderSize - (allocation % cylinderSize);

556
    for (i = 0; i < dev->nfreeExtent; i++) {
557 558 559 560 561 562
         unsigned long long size =
             dev->freeExtents[i].end -
             dev->freeExtents[i].start;
         unsigned long long neededSize = allocation;

         if (pool->def->source.format == VIR_STORAGE_POOL_DISK_DOS) {
J
Ján Tomko 已提交
563
             /* align to cylinder boundary */
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
             neededSize += extraBytes;
             if ((*start % cylinderSize) > extraBytes) {
                 /* add an extra cylinder if the offset can't fit within
                    the extra bytes we have */
                 neededSize += cylinderSize;
             }
             /* if we are creating a logical patition, we need one extra
                block between partitions (or actually move start one block) */
             if (partType == VIR_STORAGE_VOL_DISK_TYPE_LOGICAL) {
                 size -= SECTOR_SIZE;
             }
         }
         if (size > neededSize &&
             (smallestSize == 0 ||
             size < smallestSize)) {
             /* for logical partition, the free extent
                must be within a logical free area */
             if (partType == VIR_STORAGE_VOL_DISK_TYPE_LOGICAL &&
                 dev->freeExtents[i].type != VIR_STORAGE_FREE_LOGICAL) {
                 continue;
                 /* for primary partition, the free extent
                    must not be within a logical free area */
E
Eric Blake 已提交
586 587 588
             } else if (partType == VIR_STORAGE_VOL_DISK_TYPE_PRIMARY &&
                        dev->freeExtents[i].type != VIR_STORAGE_FREE_NORMAL) {
                 continue;
589 590 591 592 593 594 595 596
             }
             smallestSize = size;
             smallestExtent = i;
             alignedAllocation = neededSize;
         }
    }

    if (smallestExtent == -1) {
597 598
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no large enough free extent"));
599 600 601
        return -1;
    }

602
    VIR_DEBUG("aligned alloc %llu", alignedAllocation);
603 604 605 606 607 608 609 610 611
    *start = dev->freeExtents[smallestExtent].start;

    if (partType == VIR_STORAGE_VOL_DISK_TYPE_LOGICAL) {
        /* for logical partition, skip one block */
        *start += SECTOR_SIZE;
    }

    *end = *start + alignedAllocation;
    if (pool->def->source.format == VIR_STORAGE_POOL_DISK_DOS) {
J
Ján Tomko 已提交
612
        /* adjust our allocation if start is not at a cylinder boundary */
613 614 615 616 617
        *end -= (*start % cylinderSize);
    }

    /* counting in byte, we want the last byte of the current sector */
    *end -= 1;
618
    VIR_DEBUG("final aligned start %llu, end %llu", *start, *end);
619 620 621 622 623
    return 0;
}


static int
624
virStorageBackendDiskCreateVol(virConnectPtr conn ATTRIBUTE_UNUSED,
625
                               virStoragePoolObjPtr pool,
626 627
                               virStorageVolDefPtr vol)
{
E
Eric Blake 已提交
628
    int res = -1;
629
    char *partFormat = NULL;
630
    unsigned long long startOffset = 0, endOffset = 0;
631 632 633 634 635
    virCommandPtr cmd = virCommandNewArgList(PARTED,
                                             pool->def->source.devices[0].path,
                                             "mkpart",
                                             "--script",
                                             NULL);
636

637 638 639 640
    if (vol->target.encryption != NULL) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("storage pool does not support encrypted "
                               "volumes"));
641
        goto cleanup;
642
    }
643

644 645 646
    if (virStorageBackendDiskPartFormat(pool, vol, &partFormat) != 0) {
        goto cleanup;
    }
647
    virCommandAddArg(cmd, partFormat);
648

649
    if (virStorageBackendDiskPartBoundries(pool, &startOffset,
650
                                           &endOffset,
651
                                           vol->capacity) != 0) {
E
Eric Blake 已提交
652
        goto cleanup;
653 654
    }

655 656
    virCommandAddArgFormat(cmd, "%lluB", startOffset);
    virCommandAddArgFormat(cmd, "%lluB", endOffset);
657

658
    if (virCommandRun(cmd, NULL) < 0)
E
Eric Blake 已提交
659
        goto cleanup;
660

661
    /* wait for device node to show up */
662
    virFileWaitForDevices();
663

664
    /* Blow away free extent info, as we're about to re-populate it */
665
    VIR_FREE(pool->def->source.devices[0].freeExtents);
666 667
    pool->def->source.devices[0].nfreeExtent = 0;

668 669 670 671
    /* Specifying a target path is meaningless */
    VIR_FREE(vol->target.path);

    /* Fetch actual extent info, generate key */
672
    if (virStorageBackendDiskReadPartitions(pool, vol) < 0)
E
Eric Blake 已提交
673
        goto cleanup;
674

E
Eric Blake 已提交
675 676
    res = 0;

677
 cleanup:
E
Eric Blake 已提交
678
    VIR_FREE(partFormat);
679
    virCommandFree(cmd);
E
Eric Blake 已提交
680
    return res;
681 682
}

683 684
static int
virStorageBackendDiskBuildVolFrom(virConnectPtr conn,
685
                                  virStoragePoolObjPtr pool,
686 687 688 689 690 691
                                  virStorageVolDefPtr vol,
                                  virStorageVolDefPtr inputvol,
                                  unsigned int flags)
{
    virStorageBackendBuildVolFrom build_func;

692
    build_func = virStorageBackendGetBuildVolFromFunction(vol, inputvol);
693 694 695
    if (!build_func)
        return -1;

696
    return build_func(conn, pool, vol, inputvol, flags);
697
}
698 699

static int
700
virStorageBackendDiskDeleteVol(virConnectPtr conn ATTRIBUTE_UNUSED,
C
Cole Robinson 已提交
701 702
                               virStoragePoolObjPtr pool,
                               virStorageVolDefPtr vol,
E
Eric Blake 已提交
703
                               unsigned int flags)
704
{
C
Cole Robinson 已提交
705
    char *part_num = NULL;
D
Daniel P. Berrange 已提交
706
    char *devpath = NULL;
707
    char *dev_name, *srcname;
708 709
    virCommandPtr cmd = NULL;
    bool isDevMapperDevice;
D
Daniel P. Berrange 已提交
710
    int rc = -1;
C
Cole Robinson 已提交
711

E
Eric Blake 已提交
712 713
    virCheckFlags(0, -1);

714 715
    if (virFileResolveLink(vol->target.path, &devpath) < 0) {
        virReportSystemError(errno,
716 717
                             _("Couldn't read volume target path '%s'"),
                             vol->target.path);
D
Daniel P. Berrange 已提交
718
        goto cleanup;
C
Cole Robinson 已提交
719 720
    }

721 722
    dev_name = last_component(devpath);
    srcname = last_component(pool->def->source.devices[0].path);
723
    VIR_DEBUG("dev_name=%s, srcname=%s", dev_name, srcname);
C
Cole Robinson 已提交
724

725 726
    isDevMapperDevice = virIsDevMapperDevice(devpath);

727
    if (!isDevMapperDevice && !STRPREFIX(dev_name, srcname)) {
728 729 730
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Volume path '%s' did not start with parent "
                         "pool source device name."), dev_name);
D
Daniel P. Berrange 已提交
731
        goto cleanup;
C
Cole Robinson 已提交
732 733
    }

734
    if (!isDevMapperDevice) {
735
        part_num = dev_name + strlen(srcname);
C
Cole Robinson 已提交
736

737
        if (*part_num == 0) {
738 739 740
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse partition number from target "
                             "'%s'"), dev_name);
741 742
            goto cleanup;
        }
C
Cole Robinson 已提交
743

744 745 746 747 748 749 750 751 752 753 754
        /* eg parted /dev/sda rm 2 */
        cmd = virCommandNewArgList(PARTED,
                                   pool->def->source.devices[0].path,
                                   "rm",
                                   "--script",
                                   part_num,
                                   NULL);
        if (virCommandRun(cmd, NULL) < 0)
            goto cleanup;
    } else {
        cmd = virCommandNewArgList(DMSETUP, "remove", "--force", devpath, NULL);
C
Cole Robinson 已提交
755

756 757 758
        if (virCommandRun(cmd, NULL) < 0)
            goto cleanup;
    }
C
Cole Robinson 已提交
759

D
Daniel P. Berrange 已提交
760
    rc = 0;
761
 cleanup:
D
Daniel P. Berrange 已提交
762
    VIR_FREE(devpath);
763
    virCommandFree(cmd);
D
Daniel P. Berrange 已提交
764
    return rc;
765 766 767 768 769 770 771 772 773 774 775
}


virStorageBackend virStorageBackendDisk = {
    .type = VIR_STORAGE_POOL_DISK,

    .buildPool = virStorageBackendDiskBuildPool,
    .refreshPool = virStorageBackendDiskRefreshPool,

    .createVol = virStorageBackendDiskCreateVol,
    .deleteVol = virStorageBackendDiskDeleteVol,
776
    .buildVolFrom = virStorageBackendDiskBuildVolFrom,
777
};