virnuma.c 26.2 KB
Newer Older
1 2 3
/*
 * virnuma.c: helper APIs for managing numa
 *
4
 * Copyright (C) 2011-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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>

24 25
#define NUMA_MAX_N_CPUS 4096

G
Gao feng 已提交
26 27 28
#if WITH_NUMACTL
# define NUMA_VERSION1_COMPATIBILITY 1
# include <numa.h>
29 30 31 32 33 34 35

# if LIBNUMA_API_VERSION > 1
#  undef NUMA_MAX_N_CPUS
#  define NUMA_MAX_N_CPUS (numa_all_cpus_ptr->size)
# endif

#endif /* WITH_NUMACTL */
G
Gao feng 已提交
36

37 38 39
#include <sys/types.h>
#include <dirent.h>

40 41 42
#include "virnuma.h"
#include "vircommand.h"
#include "virerror.h"
G
Gao feng 已提交
43
#include "virlog.h"
44 45
#include "viralloc.h"
#include "virbitmap.h"
46 47 48
#include "virstring.h"
#include "virfile.h"
#include "nodeinfo.h"
49 50 51

#define VIR_FROM_THIS VIR_FROM_NONE

52 53
VIR_LOG_INIT("util.numa");

G
Gao feng 已提交
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#if HAVE_NUMAD
char *
virNumaGetAutoPlacementAdvice(unsigned short vcpus,
                              unsigned long long balloon)
{
    virCommandPtr cmd = NULL;
    char *output = NULL;

    cmd = virCommandNewArgList(NUMAD, "-w", NULL);
    virCommandAddArgFormat(cmd, "%d:%llu", vcpus,
                           VIR_DIV_UP(balloon, 1024));

    virCommandSetOutputBuffer(cmd, &output);

    if (virCommandRun(cmd, NULL) < 0)
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to query numad for the "
                         "advisory nodeset"));

    virCommandFree(cmd);
    return output;
}
M
Michal Privoznik 已提交
77
#else /* !HAVE_NUMAD */
78 79 80 81 82 83 84 85
char *
virNumaGetAutoPlacementAdvice(unsigned short vcpus ATTRIBUTE_UNUSED,
                              unsigned long long balloon ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                   _("numad is not available on this host"));
    return NULL;
}
M
Michal Privoznik 已提交
86
#endif /* !HAVE_NUMAD */
G
Gao feng 已提交
87 88 89

#if WITH_NUMACTL
int
90 91
virNumaSetupMemoryPolicy(virDomainNumatuneMemMode mode,
                         virBitmapPtr nodeset)
G
Gao feng 已提交
92 93 94 95
{
    nodemask_t mask;
    int node = -1;
    int ret = -1;
96 97
    int bit = 0;
    size_t i;
G
Gao feng 已提交
98 99
    int maxnode = 0;

100 101 102
    if (!nodeset)
        return 0;

103
    if (!virNumaNodesetIsAvailable(nodeset))
104 105
        return -1;

106 107
    maxnode = numa_max_node();
    maxnode = maxnode < NUMA_NUM_NODES ? maxnode : NUMA_NUM_NODES;
108

G
Gao feng 已提交
109 110
    /* Convert nodemask to NUMA bitmask. */
    nodemask_zero(&mask);
111
    bit = -1;
112
    while ((bit = virBitmapNextSetBit(nodeset, bit)) >= 0) {
113
        if (bit > maxnode) {
G
Gao feng 已提交
114
            virReportError(VIR_ERR_INTERNAL_ERROR,
115
                           _("NUMA node %d is out of range"), bit);
G
Gao feng 已提交
116 117
            return -1;
        }
118
        nodemask_set(&mask, bit);
G
Gao feng 已提交
119 120
    }

121
    switch (mode) {
122
    case VIR_DOMAIN_NUMATUNE_MEM_STRICT:
G
Gao feng 已提交
123 124 125
        numa_set_bind_policy(1);
        numa_set_membind(&mask);
        numa_set_bind_policy(0);
126 127 128 129
        break;

    case VIR_DOMAIN_NUMATUNE_MEM_PREFERRED:
    {
G
Gao feng 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        int nnodes = 0;
        for (i = 0; i < NUMA_NUM_NODES; i++) {
            if (nodemask_isset(&mask, i)) {
                node = i;
                nnodes++;
            }
        }

        if (nnodes != 1) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("NUMA memory tuning in 'preferred' mode "
                                   "only supports single node"));
            goto cleanup;
        }

        numa_set_bind_policy(0);
        numa_set_preferred(node);
    }
148 149 150 151 152
    break;

    case VIR_DOMAIN_NUMATUNE_MEM_INTERLEAVE:
        numa_set_interleave_mask(&mask);
        break;
G
Gao feng 已提交
153

154 155 156
    case VIR_DOMAIN_NUMATUNE_MEM_LAST:
        break;
    }
G
Gao feng 已提交
157 158
    ret = 0;

159
 cleanup:
G
Gao feng 已提交
160 161
    return ret;
}
162 163 164 165 166 167

bool
virNumaIsAvailable(void)
{
    return numa_available() != -1;
}
168 169 170 171 172 173 174


/**
 * virNumaGetMaxNode:
 * Get the highest node number available on the current system.
 * (See the node numbers in /sys/devices/system/node/ ).
 *
M
Michal Privoznik 已提交
175
 * Returns the highest NUMA node id on success, -1 on error.
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
 */
int
virNumaGetMaxNode(void)
{
    int ret;

    if (!virNumaIsAvailable()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("NUMA isn't available on this host"));
        return -1;
    }

    if ((ret = numa_max_node()) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to request maximum NUMA node id"));
        return -1;
    }

    return ret;
}
196 197 198


/**
M
Michal Privoznik 已提交
199
 * virNumaGetNodeMemory:
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
 * @node: identifier of the requested NUMA node
 * @memsize: returns the total size of memory in the NUMA node
 * @memfree: returns the total free memory in a NUMA node
 *
 * Returns the size of the memory in one NUMA node in bytes via the @size
 * argument and free memory of a node in the @free argument.  The caller has to
 * guarantee that @node is in range (see virNumaGetMaxNode).
 *
 * Returns 0 on success, -1 on error. Does not report errors.
 */
int
virNumaGetNodeMemory(int node,
                     unsigned long long *memsize,
                     unsigned long long *memfree)
{
    long long node_size;
    long long node_free;

    if (memsize)
        *memsize = 0;

    if (memfree)
        *memfree = 0;

    if ((node_size = numa_node_size64(node, &node_free)) < 0)
        return -1;

    if (memsize)
        *memsize = node_size;

    if (memfree)
        *memfree = node_free;

    return 0;
}
235 236 237 238 239 240 241 242 243 244 245 246 247 248 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


/**
 * virNumaGetNodeCPUs:
 * @node: identifier of the requested NUMA node
 * @cpus: returns a bitmap of CPUs in @node
 *
 * Returns count of CPUs in the selected node and sets the map of the cpus to
 * @cpus. On error if the @node doesn't exist in the system this function
 * returns -2 and sets @cpus to NULL. On other errors -1 is returned, @cpus
 * is set to NULL and an error is reported.
 */

# define n_bits(var) (8 * sizeof(var))
# define MASK_CPU_ISSET(mask, cpu) \
  (((mask)[((cpu) / n_bits(*(mask)))] >> ((cpu) % n_bits(*(mask)))) & 1)
int
virNumaGetNodeCPUs(int node,
                   virBitmapPtr *cpus)
{
    unsigned long *mask = NULL;
    unsigned long *allonesmask = NULL;
    virBitmapPtr cpumap = NULL;
    int ncpus = 0;
    int max_n_cpus = virNumaGetMaxCPUs();
    int mask_n_bytes = max_n_cpus / 8;
    size_t i;
    int ret = -1;

    *cpus = NULL;

    if (VIR_ALLOC_N(mask, mask_n_bytes / sizeof(*mask)) < 0)
        goto cleanup;

    if (VIR_ALLOC_N(allonesmask, mask_n_bytes / sizeof(*mask)) < 0)
        goto cleanup;

    memset(allonesmask, 0xff, mask_n_bytes);

    /* The first time this returns -1, ENOENT if node doesn't exist... */
    if (numa_node_to_cpus(node, mask, mask_n_bytes) < 0) {
        VIR_WARN("NUMA topology for cell %d is not available, ignoring", node);
        ret = -2;
        goto cleanup;
    }

    /* second, third... times it returns an all-1's mask */
    if (memcmp(mask, allonesmask, mask_n_bytes) == 0) {
        VIR_DEBUG("NUMA topology for cell %d is invalid, ignoring", node);
        ret = -2;
        goto cleanup;
    }

    if (!(cpumap = virBitmapNew(max_n_cpus)))
        goto cleanup;

    for (i = 0; i < max_n_cpus; i++) {
        if (MASK_CPU_ISSET(mask, i)) {
            ignore_value(virBitmapSetBit(cpumap, i));
            ncpus++;
        }
    }

    *cpus = cpumap;
    cpumap = NULL;
    ret = ncpus;

302
 cleanup:
303 304
    VIR_FREE(mask);
    VIR_FREE(allonesmask);
305
    virBitmapFree(cpumap);
306 307 308 309 310 311

    return ret;
}
# undef MASK_CPU_ISSET
# undef n_bits

M
Michal Privoznik 已提交
312 313
#else /* !WITH_NUMACTL */

G
Gao feng 已提交
314
int
315 316
virNumaSetupMemoryPolicy(virDomainNumatuneMemMode mode ATTRIBUTE_UNUSED,
                         virBitmapPtr nodeset)
G
Gao feng 已提交
317
{
318
    if (!virNumaNodesetIsAvailable(nodeset))
G
Gao feng 已提交
319 320 321 322
        return -1;

    return 0;
}
323 324 325 326 327 328

bool
virNumaIsAvailable(void)
{
    return false;
}
329 330 331 332 333 334 335 336 337


int
virNumaGetMaxNode(void)
{
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("NUMA isn't available on this host"));
    return -1;
}
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353


int
virNumaGetNodeMemory(int node ATTRIBUTE_UNUSED,
                     unsigned long long *memsize,
                     unsigned long long *memfree)
{
    if (memsize)
        *memsize = 0;

    if (memfree)
        *memfree = 0;

    VIR_DEBUG("NUMA isn't available on this host");
    return -1;
}
354 355 356 357 358 359 360 361 362 363 364 365


int
virNumaGetNodeCPUs(int node ATTRIBUTE_UNUSED,
                   virBitmapPtr *cpus)
{
    *cpus = NULL;

    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("NUMA isn't available on this host"));
    return -1;
}
M
Michal Privoznik 已提交
366
#endif /* !WITH_NUMACTL */
367 368 369 370 371 372 373 374 375 376 377 378 379

/**
 * virNumaGetMaxCPUs:
 *
 * Get the maximum count of CPUs supportable in the host.
 *
 * Returns the count of CPUs supported.
 */
unsigned int
virNumaGetMaxCPUs(void)
{
    return NUMA_MAX_N_CPUS;
}
380 381


E
Eric Blake 已提交
382
#if WITH_NUMACTL && HAVE_NUMA_BITMASK_ISBITSET
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
/**
 * virNumaNodeIsAvailable:
 * @node: node to check
 *
 * On some hosts the set of NUMA nodes isn't continuous.
 * Use this function to test if the @node is available.
 *
 * Returns: true if @node is available,
 *          false if @node doesn't exist
 */
bool
virNumaNodeIsAvailable(int node)
{
    return numa_bitmask_isbitset(numa_nodes_ptr, node);
}


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
/**
 * virNumaGetDistances:
 * @node: identifier of the requested NUMA node
 * @distances: array of distances to sibling nodes
 * @ndistances: size of @distances
 *
 * Get array of distances to sibling nodes from @node. If a
 * distances[x] equals to zero, the node x is not enabled or
 * doesn't exist. As a special case, if @node itself refers to
 * disabled or nonexistent NUMA node, then @distances and
 * @ndistances are set to NULL and zero respectively.
 *
 * The distances are a bit of magic. For a local node the value
 * is 10, for remote it's typically 20 meaning that time penalty
 * for accessing a remote node is two time bigger than when
 * accessing a local node.
 *
 * Returns 0 on success, -1 otherwise.
 */
int
virNumaGetDistances(int node,
                    int **distances,
                    int *ndistances)
{
    int ret = -1;
    int max_node;
    size_t i;

428
    if (!virNumaNodeIsAvailable(node)) {
429 430 431 432 433 434 435 436 437
        VIR_DEBUG("Node %d does not exist", node);
        *distances = NULL;
        *ndistances = 0;
        return 0;
    }

    if ((max_node = virNumaGetMaxNode()) < 0)
        goto cleanup;

438
    if (VIR_ALLOC_N(*distances, max_node + 1) < 0)
439 440 441 442
        goto cleanup;

    *ndistances = max_node + 1;

443
    for (i = 0; i <= max_node; i++) {
444
        if (!virNumaNodeIsAvailable(node))
445 446 447 448 449 450 451 452 453
            continue;

        (*distances)[i] = numa_distance(node, i);
    }

    ret = 0;
 cleanup:
    return ret;
}
454

M
Michal Privoznik 已提交
455
#else /* !(WITH_NUMACTL && HAVE_NUMA_BITMASK_ISBITSET) */
456 457 458 459 460 461 462 463 464 465

bool
virNumaNodeIsAvailable(int node)
{
    int max_node = virNumaGetMaxNode();

    if (max_node < 0)
        return false;

    /* Do we have anything better? */
466
    return (node >= 0) && (node <= max_node);
467 468 469
}


470 471 472 473 474 475 476
int
virNumaGetDistances(int node ATTRIBUTE_UNUSED,
                    int **distances,
                    int *ndistances)
{
    *distances = NULL;
    *ndistances = 0;
E
Eric Blake 已提交
477
    VIR_DEBUG("NUMA distance information isn't available on this host");
478 479
    return 0;
}
M
Michal Privoznik 已提交
480
#endif /* !(WITH_NUMACTL && HAVE_NUMA_BITMASK_ISBITSET) */
481 482


483 484
/* currently all the huge page stuff below is linux only */
#ifdef __linux__
485 486 487 488

# define HUGEPAGES_NUMA_PREFIX "/sys/devices/system/node/"
# define HUGEPAGES_SYSTEM_PREFIX "/sys/kernel/mm/hugepages/"
# define HUGEPAGES_PREFIX "hugepages-"
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 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 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

static int
virNumaGetHugePageInfoPath(char **path,
                           int node,
                           unsigned int page_size,
                           const char *suffix)
{

    int ret = -1;

    if (node == -1) {
        /* We are aiming at overall system info */
        if (page_size) {
            /* And even on specific huge page size */
            if (virAsprintf(path,
                            HUGEPAGES_SYSTEM_PREFIX HUGEPAGES_PREFIX "%ukB/%s",
                            page_size, suffix ? suffix : "") < 0)
                goto cleanup;
        } else {
            if (VIR_STRDUP(*path, HUGEPAGES_SYSTEM_PREFIX) < 0)
                goto cleanup;
        }

    } else {
        /* We are aiming on specific NUMA node */
        if (page_size) {
            /* And even on specific huge page size */
            if (virAsprintf(path,
                            HUGEPAGES_NUMA_PREFIX "node%d/hugepages/"
                            HUGEPAGES_PREFIX "%ukB/%s",
                            node, page_size, suffix ? suffix : "") < 0)
                goto cleanup;
        } else {
            if (virAsprintf(path,
                            HUGEPAGES_NUMA_PREFIX "node%d/hugepages/",
                            node) < 0)
                goto cleanup;
        }
    }

    ret = 0;
 cleanup:
    return ret;
}


/**
 * virNumaGetHugePageInfo:
 * @node: NUMA node id
 * @page_size: which huge page are we interested in
 * @page_avail: total number of huge pages in the pool
 * @page_free: the number of free huge pages in the pool
 *
 * For given NUMA node and huge page size fetch information on
 * total number of huge pages in the pool (both free and taken)
 * and count for free huge pages in the pool.
 *
 * If you're interested in just one bit, pass NULL to the other one.
 *
 * As a special case, if @node == -1, overall info is fetched
 * from the system.
 *
 * Returns 0 on success, -1 otherwise (with error reported).
 */
static int
virNumaGetHugePageInfo(int node,
                       unsigned int page_size,
                       unsigned int *page_avail,
                       unsigned int *page_free)
{
    int ret = -1;
    char *path = NULL;
    char *buf = NULL;
    char *end;

    if (page_avail) {
        if (virNumaGetHugePageInfoPath(&path, node,
                                       page_size, "nr_hugepages") < 0)
            goto cleanup;

        if (virFileReadAll(path, 1024, &buf) < 0)
            goto cleanup;

        if (virStrToLong_ui(buf, &end, 10, page_avail) < 0 ||
            *end != '\n') {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unable to parse: %s"),
                           buf);
            goto cleanup;
        }
        VIR_FREE(buf);
        VIR_FREE(path);
    }

    if (page_free) {
        if (virNumaGetHugePageInfoPath(&path, node,
                                       page_size, "free_hugepages") < 0)
            goto cleanup;

        if (virFileReadAll(path, 1024, &buf) < 0)
            goto cleanup;

        if (virStrToLong_ui(buf, &end, 10, page_free) < 0 ||
            *end != '\n') {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unable to parse: %s"),
                           buf);
            goto cleanup;
        }
    }

    ret = 0;
 cleanup:
    VIR_FREE(buf);
    VIR_FREE(path);
    return ret;
}

/**
 * virNumaGetPageInfo:
 * @node: NUMA node id
 * @page_size: which huge page are we interested in (in KiB)
611 612
 * @huge_page_sum: the sum of memory taken by huge pages (in
 * bytes)
613 614 615 616 617 618 619
 * @page_avail: total number of huge pages in the pool
 * @page_free: the number of free huge pages in the pool
 *
 * For given NUMA node and page size fetch information on
 * total number of pages in the pool (both free and taken)
 * and count for free pages in the pool.
 *
620 621 622 623 624 625 626
 * The @huge_page_sum parameter exists due to the Linux kernel
 * limitation. The problem is, if there are some huge pages
 * allocated, they are accounted under the 'MemUsed' field in the
 * meminfo file instead of being subtracted from the 'MemTotal'.
 * We must do the subtraction ourselves.
 * If unsure, pass 0.
 *
627 628 629 630 631 632 633 634 635 636
 * If you're interested in just one bit, pass NULL to the other one.
 *
 * As a special case, if @node == -1, overall info is fetched
 * from the system.
 *
 * Returns 0 on success, -1 otherwise (with error reported).
 */
int
virNumaGetPageInfo(int node,
                   unsigned int page_size,
637
                   unsigned long long huge_page_sum,
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
                   unsigned int *page_avail,
                   unsigned int *page_free)
{
    int ret = -1;
    long system_page_size = sysconf(_SC_PAGESIZE);

    /* sysconf() returns page size in bytes,
     * the @page_size is however in kibibytes */
    if (page_size == system_page_size / 1024) {
        unsigned long long memsize, memfree;

        /* TODO: come up with better algorithm that takes huge pages into
         * account. The problem is huge pages cut off regular memory. */
        if (node == -1) {
            if (nodeGetMemory(&memsize, &memfree) < 0)
                goto cleanup;
        } else {
            if (virNumaGetNodeMemory(node, &memsize, &memfree) < 0)
                goto cleanup;
        }

659 660 661
        /* see description above */
        memsize -= huge_page_sum;

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
        if (page_avail)
            *page_avail = memsize / system_page_size;

        if (page_free)
            *page_free = memfree / system_page_size;
    } else {
        if (virNumaGetHugePageInfo(node, page_size, page_avail, page_free) < 0)
            goto cleanup;
    }

    ret = 0;
 cleanup:
    return ret;
}


/**
 * virNumaGetPages:
 * @node: NUMA node id
 * @pages_size: list of pages supported on @node
 * @pages_avail: list of the pool sizes on @node
 * @pages_free: list of free pages on @node
 * @npages: the lists size
 *
 * For given NUMA node fetch info on pages. The size of pages
 * (e.g.  4K, 2M, 1G) is stored into @pages_size, the size of the
 * pool is then stored into @pages_avail and the number of free
 * pages in the pool is stored into @pages_free.
 *
 * If you're interested only in some lists, pass NULL to the
 * other ones.
 *
 * As a special case, if @node == -1, overall info is fetched
 * from the system.
 *
 * Returns 0 on success, -1 otherwise.
 */
int
virNumaGetPages(int node,
                unsigned int **pages_size,
                unsigned int **pages_avail,
                unsigned int **pages_free,
                size_t *npages)
{
    int ret = -1;
    char *path = NULL;
    DIR *dir = NULL;
709
    int direrr = 0;
710 711 712 713 714 715
    struct dirent *entry;
    unsigned int *tmp_size = NULL, *tmp_avail = NULL, *tmp_free = NULL;
    unsigned int ntmp = 0;
    size_t i;
    bool exchange;
    long system_page_size;
716
    unsigned long long huge_page_sum = 0;
717 718 719 720 721

    /* sysconf() returns page size in bytes,
     * but we are storing the page size in kibibytes. */
    system_page_size = sysconf(_SC_PAGESIZE) / 1024;

722 723 724 725 726
    /* Query huge pages at first.
     * On Linux systems, the huge pages pool cuts off the available memory and
     * is always shown as used memory. Here, however, we want to report
     * slightly different information. So we take the total memory on a node
     * and subtract memory taken by the huge pages. */
727 728 729 730
    if (virNumaGetHugePageInfoPath(&path, node, 0, NULL) < 0)
        goto cleanup;

    if (!(dir = opendir(path))) {
731 732 733 734 735 736 737 738
        /* It's okay if the @path doesn't exist. Maybe we are running on
         * system without huge pages support where the path may not exist. */
        if (errno != ENOENT) {
            virReportSystemError(errno,
                                 _("unable to open path: %s"),
                                 path);
            goto cleanup;
        }
739 740
    }

741
    while (dir && (direrr = virDirRead(dir, &entry, path)) > 0) {
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
        const char *page_name = entry->d_name;
        unsigned int page_size, page_avail = 0, page_free = 0;
        char *end;

        /* Just to give you a hint, we're dealing with this:
         * hugepages-2048kB/  or   hugepages-1048576kB/ */
        if (!STRPREFIX(entry->d_name, HUGEPAGES_PREFIX))
            continue;

        page_name += strlen(HUGEPAGES_PREFIX);

        if (virStrToLong_ui(page_name, &end, 10, &page_size) < 0 ||
            STRCASENEQ(end, "kB")) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unable to parse %s"),
                           entry->d_name);
            goto cleanup;
        }

761
        if (virNumaGetHugePageInfo(node, page_size,
762 763 764 765 766 767 768 769 770 771 772 773
                                   &page_avail, &page_free) < 0)
            goto cleanup;

        if (VIR_REALLOC_N(tmp_size, ntmp + 1) < 0 ||
            VIR_REALLOC_N(tmp_avail, ntmp + 1) < 0 ||
            VIR_REALLOC_N(tmp_free, ntmp + 1) < 0)
            goto cleanup;

        tmp_size[ntmp] = page_size;
        tmp_avail[ntmp] = page_avail;
        tmp_free[ntmp] = page_free;
        ntmp++;
774 775 776 777

        /* page_size is in kibibytes while we want huge_page_sum
         * in just bytes. */
        huge_page_sum += 1024 * page_size * page_avail;
778 779
    }

780 781 782
    if (direrr < 0)
        goto cleanup;

783 784 785 786 787 788 789 790 791 792 793 794
    /* Now append the ordinary system pages */
    if (VIR_REALLOC_N(tmp_size, ntmp + 1) < 0 ||
        VIR_REALLOC_N(tmp_avail, ntmp + 1) < 0 ||
        VIR_REALLOC_N(tmp_free, ntmp + 1) < 0)
        goto cleanup;

    if (virNumaGetPageInfo(node, system_page_size, huge_page_sum,
                           &tmp_avail[ntmp], &tmp_free[ntmp]) < 0)
        goto cleanup;
    tmp_size[ntmp] = system_page_size;
    ntmp++;

795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
    /* Just to produce nice output, sort the arrays by increasing page size */
    do {
        exchange = false;
        for (i = 0; i < ntmp -1; i++) {
            if (tmp_size[i] > tmp_size[i + 1]) {
                exchange = true;
                SWAP(tmp_size[i], tmp_size[i + 1]);
                SWAP(tmp_avail[i], tmp_avail[i + 1]);
                SWAP(tmp_free[i], tmp_free[i + 1]);
            }
        }
    } while (exchange);

    if (pages_size) {
        *pages_size = tmp_size;
        tmp_size = NULL;
    }
    if (pages_avail) {
        *pages_avail = tmp_avail;
        tmp_avail = NULL;
    }
    if (pages_free) {
        *pages_free = tmp_free;
        tmp_free = NULL;
    }
    *npages = ntmp;
    ret = 0;
 cleanup:
    VIR_FREE(tmp_free);
    VIR_FREE(tmp_avail);
    VIR_FREE(tmp_size);
826 827
    if (dir)
        closedir(dir);
828 829 830
    VIR_FREE(path);
    return ret;
}
831 832


833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
int
virNumaSetPagePoolSize(int node,
                       unsigned int page_size,
                       unsigned long long page_count,
                       bool add)
{
    int ret = -1;
    char *nr_path = NULL, *nr_buf =  NULL;
    char *end;
    unsigned long long nr_count;

    if (page_size == sysconf(_SC_PAGESIZE) / 1024) {
        /* Special case as kernel handles system pages
         * differently to huge pages. */
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("system pages pool can't be modified"));
        goto cleanup;
    }

    if (virNumaGetHugePageInfoPath(&nr_path, node, page_size, "nr_hugepages") < 0)
        goto cleanup;

    /* Firstly check, if there's anything for us to do */
    if (virFileReadAll(nr_path, 1024, &nr_buf) < 0)
        goto cleanup;

    if (virStrToLong_ull(nr_buf, &end, 10, &nr_count) < 0 ||
        *end != '\n') {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid number '%s' in '%s'"),
                       nr_buf, nr_path);
        goto cleanup;
    }

    if (add) {
        if (!page_count) {
            VIR_DEBUG("Nothing left to do: add = true page_count = 0");
            ret = 0;
            goto cleanup;
        }
        page_count += nr_count;
    } else {
        if (nr_count == page_count) {
            VIR_DEBUG("Nothing left to do: nr_count = page_count = %llu",
                      page_count);
            ret = 0;
            goto cleanup;
        }
    }

    /* Okay, page pool adjustment must be done in two steps. In
     * first we write the desired number into nr_hugepages file.
     * Kernel then starts to allocate the pages (return from
     * write should be postponed until the kernel is finished).
     * However, kernel may have not been successful and reserved
     * all the pages we wanted. So do the second read to check.
     */
    VIR_FREE(nr_buf);
    if (virAsprintf(&nr_buf, "%llu", page_count) < 0)
        goto cleanup;

    if (virFileWriteStr(nr_path, nr_buf, 0) < 0) {
        virReportSystemError(errno,
                             _("Unable to write to: %s"), nr_path);
        goto cleanup;
    }

    /* And now do the check. */

    VIR_FREE(nr_buf);
    if (virFileReadAll(nr_path, 1024, &nr_buf) < 0)
        goto cleanup;

    if (virStrToLong_ull(nr_buf, &end, 10, &nr_count) < 0 ||
        *end != '\n') {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid number '%s' in '%s'"),
                       nr_buf, nr_path);
        goto cleanup;
    }

    if (nr_count != page_count) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Unable to allocate %llu pages. Allocated only %llu"),
                       page_count, nr_count);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(nr_buf);
    VIR_FREE(nr_path);
    return ret;
}


929
#else /* #ifdef __linux__ */
930 931 932
int
virNumaGetPageInfo(int node ATTRIBUTE_UNUSED,
                   unsigned int page_size ATTRIBUTE_UNUSED,
933
                   unsigned long long huge_page_sum ATTRIBUTE_UNUSED,
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
                   unsigned int *page_avail ATTRIBUTE_UNUSED,
                   unsigned int *page_free ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                   _("page info is not supported on this platform"));
    return -1;
}


int
virNumaGetPages(int node ATTRIBUTE_UNUSED,
                unsigned int **pages_size ATTRIBUTE_UNUSED,
                unsigned int **pages_avail ATTRIBUTE_UNUSED,
                unsigned int **pages_free ATTRIBUTE_UNUSED,
                size_t *npages ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                   _("page info is not supported on this platform"));
    return -1;
}
954 955 956 957 958 959 960 961 962 963 964 965


int
virNumaSetPagePoolSize(int node ATTRIBUTE_UNUSED,
                       unsigned int page_size ATTRIBUTE_UNUSED,
                       unsigned long long page_count ATTRIBUTE_UNUSED,
                       bool add ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                   _("page pool allocation is not supported on this platform"));
    return -1;
}
966
#endif /* #ifdef __linux__ */
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985

bool
virNumaNodesetIsAvailable(virBitmapPtr nodeset)
{
    ssize_t bit = -1;

    if (!nodeset)
        return true;

    while ((bit = virBitmapNextSetBit(nodeset, bit)) >= 0) {
        if (virNumaNodeIsAvailable(bit))
            continue;

        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("NUMA node %zd is unavailable"), bit);
        return false;
    }
    return true;
}