storage_backend_disk.c 26.1 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 "virutil.h"
34
#include "viralloc.h"
35
#include "vircommand.h"
36
#include "configmake.h"
37

38 39
#define VIR_FROM_THIS VIR_FROM_STORAGE

40
#define PARTHELPER LIBEXECDIR "/libvirt_parthelper"
41

42 43
#define SECTOR_SIZE 512

44
static int
45
virStorageBackendDiskMakeDataVol(virStoragePoolObjPtr pool,
46 47 48 49 50 51
                                 char **const groups,
                                 virStorageVolDefPtr vol)
{
    char *tmp, *devpath;

    if (vol == NULL) {
52
        if (VIR_ALLOC(vol) < 0) {
53
            virReportOOMError();
54 55 56
            return -1;
        }

57 58
        if (VIR_REALLOC_N(pool->volumes.objs,
                          pool->volumes.count+1) < 0) {
59
            virReportOOMError();
60 61 62 63
            virStorageVolDefFree(vol);
            return -1;
        }
        pool->volumes.objs[pool->volumes.count++] = vol;
64 65 66 67 68 69

        /* 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], '/');
        if ((vol->name = strdup(tmp ? tmp + 1 : groups[0])) == NULL) {
70
            virReportOOMError();
71 72 73 74 75 76
            return -1;
        }
    }

    if (vol->target.path == NULL) {
        if ((devpath = strdup(groups[0])) == NULL) {
77
            virReportOOMError();
78 79 80 81 82 83 84 85 86
            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...
         */
87
        vol->target.path = virStorageBackendStablePath(pool, devpath, true);
88
        VIR_FREE(devpath);
89 90
        if (vol->target.path == NULL)
            return -1;
91 92 93 94 95
    }

    if (vol->key == NULL) {
        /* XXX base off a unique key of the underlying disk */
        if ((vol->key = strdup(vol->target.path)) == NULL) {
96
            virReportOOMError();
97 98 99 100 101
            return -1;
        }
    }

    if (vol->source.extents == NULL) {
102
        if (VIR_ALLOC(vol->source.extents) < 0) {
103
            virReportOOMError();
104 105 106 107 108 109
            return -1;
        }
        vol->source.nextent = 1;

        if (virStrToLong_ull(groups[3], NULL, 10,
                             &vol->source.extents[0].start) < 0) {
110 111
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("cannot parse device start location"));
112 113 114 115 116
            return -1;
        }

        if (virStrToLong_ull(groups[4], NULL, 10,
                             &vol->source.extents[0].end) < 0) {
117 118
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("cannot parse device end location"));
119 120 121 122 123
            return -1;
        }

        if ((vol->source.extents[0].path =
             strdup(pool->def->source.devices[0].path)) == NULL) {
124
            virReportOOMError();
125 126 127 128 129
            return -1;
        }
    }

    /* Refresh allocation/capacity/perms */
130
    if (virStorageBackendUpdateVolInfo(vol, 1) < 0)
131 132
        return -1;

133
    /* set partition type */
E
Eric Blake 已提交
134
    if (STREQ(groups[1], "normal"))
135
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_PRIMARY;
E
Eric Blake 已提交
136
    else if (STREQ(groups[1], "logical"))
137
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_LOGICAL;
E
Eric Blake 已提交
138
    else if (STREQ(groups[1], "extended"))
139 140 141 142
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_EXTENDED;
    else
       vol->target.type = VIR_STORAGE_VOL_DISK_TYPE_NONE;

143 144
    vol->type = VIR_STORAGE_VOL_BLOCK;

145 146 147 148 149 150 151 152 153 154 155 156 157 158
    /* 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
159
virStorageBackendDiskMakeFreeExtent(virStoragePoolObjPtr pool,
160 161 162 163
                                    char **const groups)
{
    virStoragePoolSourceDevicePtr dev = &pool->def->source.devices[0];

164 165
    if (VIR_REALLOC_N(dev->freeExtents,
                      dev->nfreeExtent + 1) < 0)
166 167 168
        return -1;

    memset(dev->freeExtents +
169 170
           dev->nfreeExtent, 0,
           sizeof(dev->freeExtents[0]));
171

172
    /* set type of free area */
E
Eric Blake 已提交
173
    if (STREQ(groups[1], "logical")) {
174 175 176 177 178 179
        dev->freeExtents[dev->nfreeExtent].type = VIR_STORAGE_FREE_LOGICAL;
    } else {
        dev->freeExtents[dev->nfreeExtent].type = VIR_STORAGE_FREE_NORMAL;
    }


180 181 182 183 184 185 186 187
    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 */

188 189 190 191 192
    /* first block reported as free, even if it is not */
    if (dev->freeExtents[dev->nfreeExtent].start == 0) {
        dev->freeExtents[dev->nfreeExtent].start = SECTOR_SIZE;
    }

193 194 195 196 197 198 199 200 201 202 203 204 205
    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;
}


static int
206
virStorageBackendDiskMakeVol(virStoragePoolObjPtr pool,
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
                             size_t ntok ATTRIBUTE_UNUSED,
                             char **const groups,
                             void *data)
{
    /*
     * 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 已提交
223
    /* Remaining data / metadata parts get turn into volumes... */
224 225 226
    if (STREQ(groups[2], "metadata") ||
        STREQ(groups[2], "data")) {
        virStorageVolDefPtr vol = data;
227 228 229 230 231 232 233 234 235 236 237 238

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

240
        return virStorageBackendDiskMakeDataVol(pool, groups, vol);
241 242
    } else if (STREQ(groups[2], "free")) {
        /* ....or free space extents */
243
        return virStorageBackendDiskMakeFreeExtent(pool, groups);
244
    } else {
R
Richard W.M. Jones 已提交
245
        /* This code path should never happen unless someone changed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
         * 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
263
virStorageBackendDiskReadPartitions(virStoragePoolObjPtr pool,
264 265 266 267 268 269 270 271 272
                                    virStorageVolDefPtr vol)
{
    /*
     *  # libvirt_parthelper DEVICE
     * /dev/sda1      normal       data        32256    106928128    106896384
     * /dev/sda2      normal       data    106928640 100027629568  99920701440
     * -              normal   metadata 100027630080 100030242304      2612736
     *
     */
273 274 275 276
    virCommandPtr cmd = virCommandNewArgList(PARTHELPER,
                                             pool->def->source.devices[0].path,
                                             NULL);
    int ret;
277 278 279

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

280 281 282 283 284 285 286
    ret = virStorageBackendRunProgNul(pool,
                                      cmd,
                                      6,
                                      virStorageBackendDiskMakeVol,
                                      vol);
    virCommandFree(cmd);
    return ret;
287 288
}

289
static int
290 291 292 293
virStorageBackendDiskMakePoolGeometry(virStoragePoolObjPtr pool,
                                      size_t ntok ATTRIBUTE_UNUSED,
                                      char **const groups,
                                      void *data ATTRIBUTE_UNUSED)
294 295 296 297 298 299 300 301 302 303
{

       pool->def->source.devices[0].geometry.cyliders = atoi(groups[0]);
       pool->def->source.devices[0].geometry.heads = atoi(groups[1]);
       pool->def->source.devices[0].geometry.sectors = atoi(groups[2]);

       return 0;
}

static int
304
virStorageBackendDiskReadGeometry(virStoragePoolObjPtr pool)
305
{
306 307 308 309 310 311 312 313 314 315 316 317 318
    virCommandPtr cmd = virCommandNewArgList(PARTHELPER,
                                             pool->def->source.devices[0].path,
                                             "-g",
                                             NULL);
    int ret;

    ret = virStorageBackendRunProgNul(pool,
                                      cmd,
                                      3,
                                      virStorageBackendDiskMakePoolGeometry,
                                      NULL);
    virCommandFree(cmd);
    return ret;
319
}
320 321

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

328
    virFileWaitForDevices();
329

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

337
    if (virStorageBackendDiskReadGeometry(pool) != 0) {
338 339 340
        return -1;
    }

341
    return virStorageBackendDiskReadPartitions(pool, NULL);
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
/**
 * 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) {
369
        if (strstr(output, "unrecognised disk label"))
370 371 372 373 374 375 376 377 378
            ret = 1;
    }

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


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

391 392
    virCheckFlags(VIR_STORAGE_POOL_BUILD_OVERWRITE |
                  VIR_STORAGE_POOL_BUILD_NO_OVERWRITE, ret);
E
Eric Blake 已提交
393

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

402 403 404 405 406
    if (flags & VIR_STORAGE_POOL_BUILD_OVERWRITE)
        ok_to_mklabel = true;
    else {
        int check;

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

420 421 422 423 424 425 426 427 428
    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);
429
        ret = virCommandRun(cmd, NULL);
430
    }
431 432

error:
433
    virCommandFree(cmd);
434
    return ret;
435 436
}

437 438 439 440
/**
 * Decides what kind of partition type that should be created.
 * Important when the partition table is of msdos type
 */
441
static int
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
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 */
        int i;
        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
465
virStorageBackendDiskPartFormat(virStoragePoolObjPtr pool,
466
                                virStorageVolDefPtr vol,
E
Eric Blake 已提交
467
                                char** partFormat)
468 469 470
{
    int i;
    if (pool->def->source.format == VIR_STORAGE_POOL_DISK_DOS) {
E
Eric Blake 已提交
471 472 473
        const char *partedFormat;
        partedFormat = virStoragePartedFsTypeTypeToString(vol->target.format);
        if (partedFormat == NULL) {
474 475
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Invalid partition type"));
E
Eric Blake 已提交
476
            return -1;
477 478 479 480
        }
        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 已提交
481 482
                if (pool->volumes.objs[i]->target.format ==
                    VIR_STORAGE_VOL_DISK_EXTENDED) {
483 484
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("extended partition already exists"));
E
Eric Blake 已提交
485 486
                    return -1;
                }
487
            }
E
Eric Blake 已提交
488 489 490 491
            if ((*partFormat = strdup(partedFormat)) == NULL) {
                virReportOOMError();
                return -1;
            }
492 493 494 495 496 497
        } 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 已提交
498
            case VIR_STORAGE_VOL_DISK_TYPE_PRIMARY:
E
Eric Blake 已提交
499 500 501 502
                if (virAsprintf(partFormat, "primary %s", partedFormat) < 0) {
                    virReportOOMError();
                    return -1;
                }
E
Eric Blake 已提交
503 504 505 506 507 508
                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 已提交
509 510 511 512 513
                        if (virAsprintf(partFormat, "logical %s",
                                        partedFormat) < 0) {
                            virReportOOMError();
                            return -1;
                        }
E
Eric Blake 已提交
514 515 516 517
                        break;
                    }
                }
                if (i == pool->volumes.count) {
518 519
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("no extended partition found and no primary partition available"));
E
Eric Blake 已提交
520 521 522 523
                    return -1;
                }
                break;
            default:
524 525
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("unknown partition type"));
E
Eric Blake 已提交
526
                return -1;
527 528 529
            }
        }
    } else {
E
Eric Blake 已提交
530 531 532 533
        if ((*partFormat = strdup("primary")) == NULL) {
            virReportOOMError();
            return -1;
        }
534 535 536 537 538
    }
    return 0;
}

/**
J
Ján Tomko 已提交
539
 * Aligns a new partition to nearest cylinder boundary
E
Eric Blake 已提交
540
 * when having a msdos partition table type
J
Ján Tomko 已提交
541
 * to avoid any problem with already existing
542 543 544
 * partitions
 */
static int
545
virStorageBackendDiskPartBoundries(virStoragePoolObjPtr pool,
546 547 548
                                   unsigned long long *start,
                                   unsigned long long *end,
                                   unsigned long long allocation)
549 550 551
{
    int i;
    int smallestExtent = -1;
552 553 554
    unsigned long long smallestSize = 0;
    unsigned long long extraBytes = 0;
    unsigned long long alignedAllocation = allocation;
555
    virStoragePoolSourceDevicePtr dev = &pool->def->source.devices[0];
556 557 558
    unsigned long long cylinderSize = dev->geometry.heads *
                                      dev->geometry.sectors * SECTOR_SIZE;

559
    VIR_DEBUG("find free area: allocation %llu, cyl size %llu", allocation,
E
Eric Blake 已提交
560
          cylinderSize);
561 562 563
    int partType = virStorageBackendDiskPartTypeToCreate(pool);

    /* how many extra bytes we have since we allocate
J
Ján Tomko 已提交
564
       aligned to the cylinder boundary */
565 566 567 568 569 570 571 572 573
    extraBytes = cylinderSize - (allocation % cylinderSize);

    for (i = 0 ; i < dev->nfreeExtent ; i++) {
         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 已提交
574
             /* align to cylinder boundary */
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
             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 已提交
597 598 599
             } else if (partType == VIR_STORAGE_VOL_DISK_TYPE_PRIMARY &&
                        dev->freeExtents[i].type != VIR_STORAGE_FREE_NORMAL) {
                 continue;
600 601 602 603 604 605 606 607
             }
             smallestSize = size;
             smallestExtent = i;
             alignedAllocation = neededSize;
         }
    }

    if (smallestExtent == -1) {
608 609
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("no large enough free extent"));
610 611 612
        return -1;
    }

613
    VIR_DEBUG("aligned alloc %llu", alignedAllocation);
614 615 616 617 618 619 620 621 622
    *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 已提交
623
        /* adjust our allocation if start is not at a cylinder boundary */
624 625 626 627 628
        *end -= (*start % cylinderSize);
    }

    /* counting in byte, we want the last byte of the current sector */
    *end -= 1;
629
    VIR_DEBUG("final aligned start %llu, end %llu", *start, *end);
630 631 632 633 634
    return 0;
}


static int
635
virStorageBackendDiskCreateVol(virConnectPtr conn ATTRIBUTE_UNUSED,
636 637 638
                               virStoragePoolObjPtr pool,
                               virStorageVolDefPtr vol)
{
E
Eric Blake 已提交
639
    int res = -1;
640
    char *partFormat = NULL;
641
    unsigned long long startOffset = 0, endOffset = 0;
642 643 644 645 646
    virCommandPtr cmd = virCommandNewArgList(PARTED,
                                             pool->def->source.devices[0].path,
                                             "mkpart",
                                             "--script",
                                             NULL);
647

648
    if (vol->target.encryption != NULL) {
649 650 651
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("storage pool does not support encrypted "
                               "volumes"));
652
        goto cleanup;
653 654
    }

E
Eric Blake 已提交
655
    if (virStorageBackendDiskPartFormat(pool, vol, &partFormat) != 0) {
656
        goto cleanup;
657
    }
658
    virCommandAddArg(cmd, partFormat);
659

660
    if (virStorageBackendDiskPartBoundries(pool, &startOffset,
661
                                           &endOffset,
662
                                           vol->capacity) != 0) {
E
Eric Blake 已提交
663
        goto cleanup;
664 665
    }

666 667
    virCommandAddArgFormat(cmd, "%lluB", startOffset);
    virCommandAddArgFormat(cmd, "%lluB", endOffset);
668

669
    if (virCommandRun(cmd, NULL) < 0)
E
Eric Blake 已提交
670
        goto cleanup;
671

672
    /* wait for device node to show up */
673
    virFileWaitForDevices();
674

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

679 680 681 682
    /* Specifying a target path is meaningless */
    VIR_FREE(vol->target.path);

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

E
Eric Blake 已提交
686 687 688 689
    res = 0;

cleanup:
    VIR_FREE(partFormat);
690
    virCommandFree(cmd);
E
Eric Blake 已提交
691
    return res;
692 693
}

694 695
static int
virStorageBackendDiskBuildVolFrom(virConnectPtr conn,
696
                                  virStoragePoolObjPtr pool,
697 698 699 700 701 702
                                  virStorageVolDefPtr vol,
                                  virStorageVolDefPtr inputvol,
                                  unsigned int flags)
{
    virStorageBackendBuildVolFrom build_func;

703
    build_func = virStorageBackendGetBuildVolFromFunction(vol, inputvol);
704 705 706
    if (!build_func)
        return -1;

707
    return build_func(conn, pool, vol, inputvol, flags);
708
}
709 710

static int
711
virStorageBackendDiskDeleteVol(virConnectPtr conn ATTRIBUTE_UNUSED,
C
Cole Robinson 已提交
712 713
                               virStoragePoolObjPtr pool,
                               virStorageVolDefPtr vol,
E
Eric Blake 已提交
714
                               unsigned int flags)
715
{
C
Cole Robinson 已提交
716
    char *part_num = NULL;
D
Daniel P. Berrange 已提交
717
    char *devpath = NULL;
718
    char *dev_name, *srcname;
719 720
    virCommandPtr cmd = NULL;
    bool isDevMapperDevice;
D
Daniel P. Berrange 已提交
721
    int rc = -1;
C
Cole Robinson 已提交
722

E
Eric Blake 已提交
723 724
    virCheckFlags(0, -1);

725 726
    if (virFileResolveLink(vol->target.path, &devpath) < 0) {
        virReportSystemError(errno,
727 728
                             _("Couldn't read volume target path '%s'"),
                             vol->target.path);
D
Daniel P. Berrange 已提交
729
        goto cleanup;
C
Cole Robinson 已提交
730 731
    }

732 733
    dev_name = last_component(devpath);
    srcname = last_component(pool->def->source.devices[0].path);
734
    VIR_DEBUG("dev_name=%s, srcname=%s", dev_name, srcname);
C
Cole Robinson 已提交
735

736 737
    isDevMapperDevice = virIsDevMapperDevice(devpath);

738
    if (!isDevMapperDevice && !STRPREFIX(dev_name, srcname)) {
739 740 741
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Volume path '%s' did not start with parent "
                         "pool source device name."), dev_name);
D
Daniel P. Berrange 已提交
742
        goto cleanup;
C
Cole Robinson 已提交
743 744
    }

745
    if (!isDevMapperDevice) {
746
        part_num = dev_name + strlen(srcname);
C
Cole Robinson 已提交
747

748
        if (*part_num == 0) {
749 750 751
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse partition number from target "
                             "'%s'"), dev_name);
752 753
            goto cleanup;
        }
C
Cole Robinson 已提交
754

755 756 757 758 759 760 761 762 763 764 765
        /* 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 已提交
766

767 768 769
        if (virCommandRun(cmd, NULL) < 0)
            goto cleanup;
    }
C
Cole Robinson 已提交
770

D
Daniel P. Berrange 已提交
771 772 773
    rc = 0;
cleanup:
    VIR_FREE(devpath);
774
    virCommandFree(cmd);
D
Daniel P. Berrange 已提交
775
    return rc;
776 777 778 779 780 781 782 783 784 785 786
}


virStorageBackend virStorageBackendDisk = {
    .type = VIR_STORAGE_POOL_DISK,

    .buildPool = virStorageBackendDiskBuildPool,
    .refreshPool = virStorageBackendDiskRefreshPool,

    .createVol = virStorageBackendDiskCreateVol,
    .deleteVol = virStorageBackendDiskDeleteVol,
787
    .buildVolFrom = virStorageBackendDiskBuildVolFrom,
788
};