Blame autohbw/autohbw.c

Packit 345191
/*
Packit 345191
 * Copyright (C) 2015 - 2019 Intel Corporation.
Packit 345191
 * All rights reserved.
Packit 345191
 *
Packit 345191
 * Redistribution and use in source and binary forms, with or without
Packit 345191
 * modification, are permitted provided that the following conditions are met:
Packit 345191
 * 1. Redistributions of source code must retain the above copyright notice(s),
Packit 345191
 *    this list of conditions and the following disclaimer.
Packit 345191
 * 2. Redistributions in binary form must reproduce the above copyright notice(s),
Packit 345191
 *    this list of conditions and the following disclaimer in the documentation
Packit 345191
 *    and/or other materials provided with the distribution.
Packit 345191
 *
Packit 345191
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
Packit 345191
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
Packit 345191
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
Packit 345191
 * EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
Packit 345191
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
Packit 345191
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
Packit 345191
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
Packit 345191
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
Packit 345191
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
Packit 345191
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Packit 345191
 */
Packit 345191
Packit 345191
///////////////////////////////////////////////////////////////////////////
Packit 345191
// File   : autohbw.c
Packit 345191
// Purpose: Library to automatically allocate HBW (MCDRAM)
Packit 345191
// Author : Ruchira Sasanka (ruchira DOT sasanka AT intel DOT com)
Packit 345191
// Date   : Jan 30, 2015
Packit 345191
///////////////////////////////////////////////////////////////////////////
Packit 345191
Packit 345191
#include <memkind.h>
Packit 345191
Packit 345191
#include <assert.h>
Packit 345191
#include <ctype.h>
Packit 345191
#include <errno.h>
Packit 345191
#include <stdbool.h>
Packit 345191
#include <stddef.h>
Packit 345191
#include <stdio.h>
Packit 345191
#include <stdlib.h>
Packit 345191
#include <string.h>
Packit 345191
#include <unistd.h>
Packit 345191
Packit 345191
#define AUTOHBW_EXPORT __attribute__((visibility("default")))
Packit 345191
#define AUTOHBW_INIT __attribute__((constructor))
Packit 345191
Packit 345191
//-2 = nothing is printed
Packit 345191
//-1 = critical messages are printed
Packit 345191
// 0 = no log messages for allocations are printed but INFO messages are printed
Packit 345191
// 1 = a log message is printed for each allocation (Default)
Packit 345191
// 2 = a log message is printed for each allocation with a backtrace
Packit 345191
enum {
Packit 345191
    ALWAYS = -1,
Packit 345191
    INFO,
Packit 345191
    ALLOC,
Packit 345191
    VERBOSE
Packit 345191
};
Packit 345191
Packit 345191
// Default is to print allocations
Packit 345191
static int LogLevel = ALLOC;
Packit 345191
Packit 345191
// Allocations of size greater than low limit promoted to HBW memory.
Packit 345191
// If there is a high limit specified, allocations larger than this limit
Packit 345191
// will not be allocated in HBW.
Packit 345191
static size_t HBWLowLimit = 1 * 1024 * 1024;
Packit 345191
static size_t HBWHighLimit = -1ull;
Packit 345191
Packit 345191
// Whether we have initialized HBW arena of memkind library -- by making
Packit 345191
// a dummy call to it. HBW arena (and hence any memkind_* call with kind
Packit 345191
// HBW) must NOT be used until this flag is set true.
Packit 345191
static bool MemkindInitDone = false;
Packit 345191
Packit 345191
// Following is the type of HBW memory that is allocated using memkind.
Packit 345191
// By changing this type, this library can be used to allocate other
Packit 345191
// types of memory types (e.g., MEMKIND_HUGETLB, MEMKIND_GBTLB,
Packit 345191
// MEMKIND_HBW_HUGETLB etc.)
Packit 345191
static memkind_t hbw_kind;
Packit 345191
Packit 345191
// API control for HBW allocations.
Packit 345191
static bool isAutoHBWEnabled = true;
Packit 345191
Packit 345191
#define LOG(level, ...)                                                                            \
Packit 345191
    do {                                                                                           \
Packit 345191
        if (LogLevel >= level) {                                                                   \
Packit 345191
            fprintf(stderr, __VA_ARGS__);                                                          \
Packit 345191
        }                                                                                          \
Packit 345191
    } while (0)
Packit 345191
Packit 345191
static bool isAllocInHBW(size_t size)
Packit 345191
{
Packit 345191
    if (!MemkindInitDone)
Packit 345191
        return false;
Packit 345191
Packit 345191
    if (!isAutoHBWEnabled)
Packit 345191
        return false;
Packit 345191
Packit 345191
    if (size < HBWLowLimit)
Packit 345191
        return false;
Packit 345191
Packit 345191
    if (size > HBWHighLimit)
Packit 345191
        return false;
Packit 345191
Packit 345191
    return true;
Packit 345191
}
Packit 345191
Packit 345191
// Returns the limit in bytes using a limit value and a multiplier
Packit 345191
// character like K, M, G
Packit 345191
static size_t getLimit(size_t limit, char lchar)
Packit 345191
{
Packit 345191
    // Now read the trailing character (e.g., K, M, G)
Packit 345191
    // Based on the character, determine the multiplier
Packit 345191
    if ((limit > 0) && isalpha(lchar)) {
Packit 345191
        long mult = 1;
Packit 345191
Packit 345191
        switch (toupper(lchar)) {
Packit 345191
            case 'G':
Packit 345191
                mult *= 1024;
Packit 345191
            case 'M':
Packit 345191
                mult *= 1024;
Packit 345191
            case 'K':
Packit 345191
                mult *= 1024;
Packit 345191
        }
Packit 345191
Packit 345191
        // check for overflow, saturate at max
Packit 345191
        if (limit >= -1ull / mult)
Packit 345191
            return -1ull;
Packit 345191
Packit 345191
        return limit * mult;
Packit 345191
    }
Packit 345191
Packit 345191
    return limit;
Packit 345191
}
Packit 345191
Packit 345191
// Once HBWLowLimit (and HBWHighLimit) are set, call this method to
Packit 345191
// inform the user about the size range of arrays that will be allocated
Packit 345191
// in HBW
Packit 345191
static void printLimits()
Packit 345191
{
Packit 345191
    // Inform according to the limits set
Packit 345191
    if ((HBWLowLimit > 0) && (HBWHighLimit < -1ull)) {
Packit 345191
        // if both high and low limits are specified, we use a range
Packit 345191
        LOG(INFO, "INFO: Allocations between %ldK - %ldK will be allocated in "
Packit 345191
            "HBW. Set AUTO_HBW_SIZE=X:Y to change this limit.\n",
Packit 345191
            HBWLowLimit / 1024, HBWHighLimit / 1024);
Packit 345191
    } else if (HBWLowLimit > 0) {
Packit 345191
        // if only a low limit is provided, use that
Packit 345191
        LOG(INFO, "INFO: Allocations greater than %ldK will be allocated in HBW."
Packit 345191
            " Set AUTO_HBW_SIZE=X:Y to change this limit.\n",
Packit 345191
            HBWLowLimit / 1024);
Packit 345191
    } else if (HBWHighLimit < -1ull) {
Packit 345191
        // if only a high limit is provided, use that
Packit 345191
        LOG(INFO, "INFO: Allocations smaller than %ldK will be allocated in HBW. "
Packit 345191
            "Set AUTO_HBW_SIZE=X:Y to change this limit.\n",
Packit 345191
            HBWHighLimit / 1024);
Packit 345191
    } else {
Packit 345191
        // none of limits is set to non-edge value, everything goes to HBW
Packit 345191
        LOG(INFO, "INFO: All allocation will be done in HBW.");
Packit 345191
    }
Packit 345191
}
Packit 345191
Packit 345191
struct kind_name_t {
Packit 345191
    memkind_t *kind;
Packit 345191
    const char *name;
Packit 345191
};
Packit 345191
Packit 345191
static struct kind_name_t named_kinds[] = {
Packit 345191
    { &MEMKIND_DEFAULT, "memkind_default" },
Packit 345191
    { &MEMKIND_HUGETLB, "memkind_hugetlb" },
Packit 345191
    { &MEMKIND_INTERLEAVE, "memkind_interleave" },
Packit 345191
    { &MEMKIND_HBW, "memkind_hbw" },
Packit 345191
    { &MEMKIND_HBW_PREFERRED, "memkind_hbw_preferred" },
Packit 345191
    { &MEMKIND_HBW_HUGETLB, "memkind_hbw_hugetlb" },
Packit 345191
    { &MEMKIND_HBW_PREFERRED_HUGETLB, "memkind_hbw_preferred_hugetlb" },
Packit 345191
    { &MEMKIND_HBW_GBTLB, "memkind_hbw_gbtlb" },
Packit 345191
    { &MEMKIND_HBW_PREFERRED_GBTLB, "memkind_hbw_preferred_gbtlb" },
Packit 345191
    { &MEMKIND_GBTLB, "memkind_gbtlb" },
Packit 345191
    { &MEMKIND_HBW_INTERLEAVE, "memkind_hbw_interleave" },
Packit 345191
};
Packit 345191
Packit 345191
static memkind_t get_kind_by_name(const char *name)
Packit 345191
{
Packit 345191
    int i;
Packit 345191
    for (i = 0; i < sizeof(named_kinds) / sizeof(named_kinds[0]); ++i)
Packit 345191
        if (strcasecmp(named_kinds[i].name, name) == 0)
Packit 345191
            return *named_kinds[i].kind;
Packit 345191
Packit 345191
    return 0;
Packit 345191
}
Packit 345191
Packit 345191
// Read from the environment and sets global variables
Packit 345191
// Env variables are:
Packit 345191
//   AUTO_HBW_SIZE = gives the size for auto HBW allocation
Packit 345191
//   AUTO_HBW_LOG = gives logging level
Packit 345191
static void setEnvValues()
Packit 345191
{
Packit 345191
    // STEP: Read the log level from the env variable. Do this early because
Packit 345191
    //       printing depends on this
Packit 345191
    char *log_str = secure_getenv("AUTO_HBW_LOG");
Packit 345191
    if (log_str && strlen(log_str)) {
Packit 345191
        int level = atoi(log_str);
Packit 345191
        LogLevel = level;
Packit 345191
        LOG(ALWAYS, "INFO: Setting log level to %d\n", LogLevel);
Packit 345191
    }
Packit 345191
Packit 345191
    if (LogLevel == INFO) {
Packit 345191
        LOG(INFO, "INFO: HBW allocation stats will not be printed. "
Packit 345191
            "Set AUTO_HBW_LOG to enable.\n");
Packit 345191
    } else if (LogLevel == ALLOC) {
Packit 345191
        LOG(INFO, "INFO: Only HBW allocations will be printed. "
Packit 345191
            "Set AUTO_HBW_LOG to disable/enable.\n");
Packit 345191
    } else if (LogLevel == VERBOSE) {
Packit 345191
        LOG(INFO, "INFO: HBW allocation with backtrace info will be printed. "
Packit 345191
            "Set AUTO_HBW_LOG to disable.\n");
Packit 345191
    }
Packit 345191
Packit 345191
    // Set the memory type allocated by this library. By default, it is
Packit 345191
    // MEMKIND_HBW, but we can use this library to allocate other memory
Packit 345191
    // types
Packit 345191
    const char *memtype_str = secure_getenv("AUTO_HBW_MEM_TYPE");
Packit 345191
    if (memtype_str && strlen(memtype_str)) {
Packit 345191
        // Find the memkind_t using the name the user has provided in the env variable
Packit 345191
        memkind_t mty = get_kind_by_name(memtype_str);
Packit 345191
        if (mty != 0) {
Packit 345191
            hbw_kind = mty;
Packit 345191
            LOG(INFO, "INFO: Setting HBW memory type to %s\n", memtype_str);
Packit 345191
        } else {
Packit 345191
            LOG(ALWAYS, "WARN: Memory type %s not recognized. Using default type\n",
Packit 345191
                memtype_str);
Packit 345191
        }
Packit 345191
    }
Packit 345191
Packit 345191
    // STEP: Set the size limits (thresholds) for HBW allocation
Packit 345191
    //
Packit 345191
    // Reads the environment variable
Packit 345191
    const char *size_str = secure_getenv("AUTO_HBW_SIZE");
Packit 345191
    if (size_str) {
Packit 345191
        size_t lowlim = HBWLowLimit / 1024;
Packit 345191
        size_t highlim = HBWHighLimit / 1024;
Packit 345191
        char lowC = 'K', highC = 'K';
Packit 345191
Packit 345191
        if (size_str) {
Packit 345191
            char *ptr = (char *)size_str;
Packit 345191
            lowlim = strtoll(ptr, &ptr, 10);
Packit 345191
            if (*ptr != 0 && *ptr != ':')
Packit 345191
                lowC = *ptr++;
Packit 345191
            else
Packit 345191
                lowC = ' ';
Packit 345191
Packit 345191
            if (*ptr++ == ':') {
Packit 345191
                highlim = strtoll(ptr, &ptr, 10);
Packit 345191
                if (*ptr)
Packit 345191
                    highC = *ptr;
Packit 345191
                else
Packit 345191
                    highC = ' ';
Packit 345191
            }
Packit 345191
Packit 345191
            LOG(INFO, "INFO: lowlim=%zu(%c), highlim=%zu(%c)\n", lowlim, lowC, highlim,
Packit 345191
                highC);
Packit 345191
        }
Packit 345191
Packit 345191
        HBWLowLimit = getLimit(lowlim, lowC);
Packit 345191
        HBWHighLimit = getLimit(highlim, highC);
Packit 345191
Packit 345191
        if (HBWLowLimit >= HBWHighLimit) {
Packit 345191
            LOG(ALWAYS, "WARN: In AUTO_HBW_SIZE=X:Y, X cannot be greater or equal to Y. "
Packit 345191
                "None of allocations will use HBW memory.\n");
Packit 345191
        }
Packit 345191
    } else {
Packit 345191
        // if the user did not specify any limits, inform that we are using
Packit 345191
        // default limits
Packit 345191
        LOG(INFO, "INFO: Using default values for array size thresholds. "
Packit 345191
            "Set AUTO_HBW_SIZE=X:Y to change.\n");
Packit 345191
    }
Packit 345191
Packit 345191
    // inform the user about limits
Packit 345191
    printLimits();
Packit 345191
}
Packit 345191
Packit 345191
// This function is executed at library load time.
Packit 345191
// Initialize HBW arena by making a dummy allocation/free at library load
Packit 345191
// time. Until HBW initialization is complete, we must not call any
Packit 345191
// allocation routines with HBW as kind.
Packit 345191
static void AUTOHBW_INIT autohbw_load(void)
Packit 345191
{
Packit 345191
    // First set the default memory type this library allocates. This can
Packit 345191
    // be overridden by env variable
Packit 345191
    // Note: 'memkind_hbw_preferred' will allow falling back to DDR but
Packit 345191
    //       'memkind_hbw will not'
Packit 345191
    // Note: If HBM is not installed on a system, memkind_hbw_preferred call
Packit 345191
    //       would fail. Therefore, we need to check for availability first.
Packit 345191
    if (memkind_check_available(MEMKIND_HBW) != 0) {
Packit 345191
        LOG(ALWAYS, "WARN: *** No HBM found in system. Will use default (DDR) "
Packit 345191
            "OR user specified type ***\n");
Packit 345191
        hbw_kind = MEMKIND_DEFAULT;
Packit 345191
    } else {
Packit 345191
        hbw_kind = MEMKIND_HBW_PREFERRED;
Packit 345191
    }
Packit 345191
Packit 345191
    // Read any env variables. This has to be done first because DbgLevel
Packit 345191
    // is set using env variables and debug printing is used below
Packit 345191
    setEnvValues(); // read any env variables
Packit 345191
Packit 345191
    LOG(INFO, "INFO: autohbw.so loaded!\n");
Packit 345191
Packit 345191
    // dummy HBW call to initialize HBW arena
Packit 345191
    void *pp = memkind_malloc(hbw_kind, 16);
Packit 345191
    if (pp == 0) {
Packit 345191
        LOG(ALWAYS, "\t-HBW init call FAILED. "
Packit 345191
            "Is required memory type present on your system?\n");
Packit 345191
        abort();
Packit 345191
    }
Packit 345191
Packit 345191
    LOG(ALWAYS, "\t-HBW int call succeeded\n");
Packit 345191
    memkind_free(hbw_kind, pp);
Packit 345191
Packit 345191
    MemkindInitDone = true; // enable HBW allocation
Packit 345191
}
Packit 345191
Packit 345191
static void *MemkindMalloc(size_t size)
Packit 345191
{
Packit 345191
    LOG(VERBOSE, "In my memkind malloc sz:%ld ... ", size);
Packit 345191
Packit 345191
    bool useHbw = isAllocInHBW(size);
Packit 345191
    memkind_t kind = useHbw ? hbw_kind : MEMKIND_DEFAULT;
Packit 345191
Packit 345191
    if (useHbw)
Packit 345191
        LOG(VERBOSE, "\tHBW");
Packit 345191
Packit 345191
    void *ptr = memkind_malloc(kind, size);
Packit 345191
Packit 345191
    LOG(VERBOSE, "\tptr:%p\n", ptr);
Packit 345191
    return ptr;
Packit 345191
}
Packit 345191
Packit 345191
static void *MemkindCalloc(size_t nmemb, size_t size)
Packit 345191
{
Packit 345191
    LOG(VERBOSE, "In my memkind calloc sz:%ld ..", size * nmemb);
Packit 345191
Packit 345191
    bool useHbw = isAllocInHBW(size);
Packit 345191
    memkind_t kind = useHbw ? hbw_kind : MEMKIND_DEFAULT;
Packit 345191
Packit 345191
    if (useHbw)
Packit 345191
        LOG(VERBOSE, "\tHBW");
Packit 345191
Packit 345191
    void *ptr = memkind_calloc(kind, nmemb, size);
Packit 345191
Packit 345191
    LOG(VERBOSE, "\tptr:%p\n", ptr);
Packit 345191
    return ptr;
Packit 345191
}
Packit 345191
Packit 345191
static void *MemkindRealloc(void *ptr, size_t size)
Packit 345191
{
Packit 345191
    LOG(VERBOSE, "In my memkind realloc sz:%ld, p1:%p ..", size, ptr);
Packit 345191
Packit 345191
    bool useHbw = isAllocInHBW(size);
Packit 345191
    memkind_t kind = useHbw ? hbw_kind : MEMKIND_DEFAULT;
Packit 345191
Packit 345191
    if (useHbw)
Packit 345191
        LOG(VERBOSE, "\tHBW");
Packit 345191
Packit 345191
    void *nptr = memkind_realloc(kind, ptr, size);
Packit 345191
Packit 345191
    LOG(VERBOSE, "\tptr=%p\n", nptr);
Packit 345191
    return nptr;
Packit 345191
}
Packit 345191
Packit 345191
static int MemkindAlign(void **memptr, size_t alignment, size_t size)
Packit 345191
{
Packit 345191
    LOG(VERBOSE, "In my memkind align sz:%ld .. ", size);
Packit 345191
Packit 345191
    bool useHbw = isAllocInHBW(size);
Packit 345191
    memkind_t kind = useHbw ? hbw_kind : MEMKIND_DEFAULT;
Packit 345191
Packit 345191
    if (useHbw)
Packit 345191
        LOG(VERBOSE, "\tHBW");
Packit 345191
Packit 345191
    int ret = memkind_posix_memalign(kind, memptr, alignment, size);
Packit 345191
Packit 345191
    LOG(VERBOSE, "\tptr:%p\n", *memptr);
Packit 345191
    return ret;
Packit 345191
}
Packit 345191
Packit 345191
// memkind_free does not need the exact kind, if kind is 0. Then
Packit 345191
// the library can figure out the proper kind itself.
Packit 345191
static void MemkindFree(void *ptr)
Packit 345191
{
Packit 345191
    // avoid to many useless logs
Packit 345191
    if (ptr)
Packit 345191
        LOG(VERBOSE, "In my memkind free, ptr:%p\n", ptr);
Packit 345191
    memkind_free(0, ptr);
Packit 345191
}
Packit 345191
Packit 345191
//--------------------------------------------------------------------------
Packit 345191
// ------------------ Public API of autohbw           ----------------------
Packit 345191
//--------------------------------------------------------------------------
Packit 345191
Packit 345191
AUTOHBW_EXPORT void enableAutoHBW()
Packit 345191
{
Packit 345191
    isAutoHBWEnabled = true;
Packit 345191
    LOG(INFO, "INFO: HBW allocations enabled by application (for this rank)\n");
Packit 345191
}
Packit 345191
Packit 345191
AUTOHBW_EXPORT void disableAutoHBW()
Packit 345191
{
Packit 345191
    isAutoHBWEnabled = false;
Packit 345191
    LOG(INFO, "INFO: HBW allocations disabled by application (for this rank)\n");
Packit 345191
}
Packit 345191
Packit 345191
AUTOHBW_EXPORT void *malloc(size_t size)
Packit 345191
{
Packit 345191
    return MemkindMalloc(size);
Packit 345191
}
Packit 345191
Packit 345191
AUTOHBW_EXPORT void *calloc(size_t nmemb, size_t size)
Packit 345191
{
Packit 345191
    return MemkindCalloc(nmemb, size);
Packit 345191
}
Packit 345191
Packit 345191
AUTOHBW_EXPORT void *realloc(void *ptr, size_t size)
Packit 345191
{
Packit 345191
    return MemkindRealloc(ptr, size);
Packit 345191
}
Packit 345191
Packit 345191
AUTOHBW_EXPORT int posix_memalign(void **memptr, size_t alignment, size_t size)
Packit 345191
{
Packit 345191
    return MemkindAlign(memptr, alignment, size);
Packit 345191
}
Packit 345191
Packit 345191
// Warn about deprecated function usage.
Packit 345191
AUTOHBW_EXPORT void *valloc(size_t size)
Packit 345191
{
Packit 345191
    LOG(ALWAYS, "use of deprecated valloc. Use posix_memalign instead\n");
Packit 345191
    void *memptr = 0;
Packit 345191
    size_t boundary = sysconf(_SC_PAGESIZE);
Packit 345191
    int status = MemkindAlign(&memptr, boundary, size);
Packit 345191
    if (status == 0 && memptr != 0)
Packit 345191
        return memptr;
Packit 345191
Packit 345191
    return 0;
Packit 345191
}
Packit 345191
Packit 345191
// Warn about deprecated function usage.
Packit 345191
AUTOHBW_EXPORT void *memalign(size_t boundary, size_t size)
Packit 345191
{
Packit 345191
    LOG(ALWAYS, "use of deprecated memalign. Use posix_memalign instead\n");
Packit 345191
    void *memptr = 0;
Packit 345191
    int status = MemkindAlign(&memptr, boundary, size);
Packit 345191
    if (status == 0 && memptr != 0)
Packit 345191
        return memptr;
Packit 345191
Packit 345191
    return 0;
Packit 345191
}
Packit 345191
Packit 345191
AUTOHBW_EXPORT void free(void *ptr)
Packit 345191
{
Packit 345191
    return MemkindFree(ptr);
Packit 345191
}