memory.c 12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 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 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*!
 * \file memory.c
 * \brief Virtal memory manager
 *
 * To maximize portability, thread-safe feature has been dropped for now.
 */

#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/crt/memory.h>

#include <inttypes.h>

#include "logging.h"

/*! Number of bits in a page */
#define TVM_CRT_PAGE_BITS (TVM_CRT_PAGE_BYTES << 3)

/*! \brief Translate log memory size into bytes */
#define TVM_CRT_VIRT_MEM_SIZE (1 << TVM_CRT_LOG_VIRT_MEM_SIZE)

/*! \brief Number of possible page entries in total */
#define TVM_CRT_MAX_PAGES (TVM_CRT_VIRT_MEM_SIZE / TVM_CRT_PAGE_BYTES)

/*! \brief Physical address type */
typedef uint32_t tvm_phy_addr_t;

/*! \brief The bits in page table */
static const tvm_phy_addr_t kPageBits = TVM_CRT_PAGE_BITS;

/*! \brief Page size, also the maximum allocable size */
static const tvm_phy_addr_t kPageSize = TVM_CRT_PAGE_BYTES;

/**
 * \brief Memory pool for virtual dynamic memory allocation
 */
static char g_memory_pool[TVM_CRT_VIRT_MEM_SIZE];

/*! \brief A page in the DRAM */
typedef struct Page {
  /*! \brief Start location in page table */
  tvm_index_t ptable_begin;
  /*! \brief The total number of pages */
  tvm_index_t num_pages;
  /*! \brief Data */
  char * data;
} Page;

// construct a new page
Page PageCreate(tvm_index_t ptable_begin, tvm_index_t num_pages) {
  Page page;
  page.ptable_begin = ptable_begin;
  page.num_pages = num_pages;
  page.data = g_memory_pool + ptable_begin * kPageSize;
  return page;
}

typedef struct PageTable {
  Page page[TVM_CRT_MAX_PAGES];
  uint32_t count;
  void (*resize)(struct PageTable * ptable, uint32_t size, Page * page);
} PageTable;

void PageTable_Resize(struct PageTable * ptable, uint32_t new_size, Page * page) {
  CHECK_LE(ptable->count, new_size,
           "size value (%d) is smaller than expected (%d).", new_size, ptable->count);
  for (uint32_t idx = ptable->count; idx < new_size; idx++) {
    ptable->page[idx] = *page;
  }
  ptable->count = new_size;
}

typedef struct PageEntry {
  char * addr;
  Page page;
} PageEntry;

typedef struct TLB {
  PageEntry entries[TVM_CRT_MAX_PAGES];
  uint32_t count;
  void (*set)(struct TLB * tlb, char * data, Page * page);
  PageEntry * (*find)(struct TLB * tlb, char * data);
} TLB;

void TLB_Set(TLB * tlb, char * data, Page * page) {
  PageEntry * entry = tlb->find(tlb, data);
  if (entry == 0) {
    tlb->entries[tlb->count].addr = data;
    tlb->entries[tlb->count].page = *page;
    tlb->count++;
  } else {
    entry->addr = data;
    entry->page = *page;
  }
}

PageEntry * TLB_Find(TLB * tlb, char * data) {
  PageEntry * entry = 0;
  for (uint32_t idx = 0; idx < tlb->count; idx++) {
    if (tlb->entries[idx].addr == data) {
      entry = tlb->entries + idx;
      break;
    }
  }
  return entry;
}

typedef struct IndexedEntry {
  tvm_index_t index;
  Page page;
} IndexedEntry;

typedef struct MultiMap {
  IndexedEntry entries[TVM_CRT_MAX_PAGES];
  uint32_t count;
  IndexedEntry * (*lower_bound)(struct MultiMap * map, uint32_t npage);
  IndexedEntry * (*end)(struct MultiMap * map);
  void (*erase)(struct MultiMap * map, IndexedEntry * entry);
  void (*insert)(struct MultiMap * map, uint32_t npage, Page * p);
} MultiMap;

IndexedEntry * MultiMap_LowerBound(struct MultiMap * map, uint32_t npage) {
  IndexedEntry * entry = 0;
  for (uint32_t idx = 0; idx < map->count; idx++) {
    if (map->entries[idx].index >= npage) {
      entry = map->entries + idx;
      break;
    }
  }
  return entry;
}

IndexedEntry * MultiMap_End(struct MultiMap * map) {
  IndexedEntry * entry = 0;
  return entry;
}

void MultiMap_Erase(struct MultiMap * map, IndexedEntry * entry) {
  for (uint32_t idx = 0; idx < map->count; idx++) {
    if ((map->entries + idx) == entry) {
      memcpy(map->entries + idx, map->entries + (idx + 1),
             sizeof(IndexedEntry) * (map->count - idx));
      map->count--;
      break;
    }
  }
}

void MultiMap_Insert(struct MultiMap * map, uint32_t npage, Page * p) {
  CHECK_LE(map->count + 1, TVM_CRT_MAX_PAGES, "invalid number of free pages.");
  for (uint32_t idx = map->count; idx < (map->count + npage); idx++) {
    map->entries[map->count].index = npage;
    map->entries[map->count].page = *p;
  }
  map->count++;
}

/*!
 * \brief DRAM memory manager
 *  Implements simple paging to allow physical address translation.
 */
typedef struct MemoryManager {
  /*!
   * \brief Allocate memory from manager
   * \param size The size of memory
   * \return The virtual address
   */
  void* (*Alloc)(struct MemoryManager * mgr, tvm_index_t size);
  /*!
   * \brief Allocate memory from manager
   * \param ptr The pointer to the memory area to be reallocated
   * \param size The size of memory
   * \return The virtual address
   */
  void* (*Realloc)(struct MemoryManager * mgr, void * ptr, tvm_index_t size);
  /*!
   * \brief Free the memory.
   * \param ptr The pointer to the memory to deallocate
   * \return The virtual address
   */
  void (*Free)(struct MemoryManager * mgr, void* data);

  // Physical address -> page
  PageTable ptable;
  // Virtual address -> page
  TLB pmap;
  // Free map
  MultiMap free_map;
} MemoryManager;

/*!
 * \brief Allocate memory from manager
 * \param size The size of memory
 * \return The virtual address
 */
void* MemoryManager_Alloc(MemoryManager * mgr, tvm_index_t size) {
  char * data = 0;
  tvm_index_t npage = (size + kPageSize - 1) / kPageSize;
  MultiMap * free_map = &(mgr->free_map);
  IndexedEntry * it = free_map->lower_bound(free_map, npage);
  tvm_index_t start = 0;
  if (it != free_map->end(free_map)) {
    Page p = it->page;
    free_map->erase(free_map, it);
    data = p.data;
    start = p.ptable_begin;
    npage = p.num_pages;
  } else {
    PageTable * ptable = &(mgr->ptable);
    start = ptable->count;
    CHECK_LE((unsigned)(start + npage), (sizeof(g_memory_pool) / kPageSize),
             "insufficient memory, start=%" PRId64 ", npage=%" PRId64 ", total=%" PRId64 "",
             start, npage, start + npage);
    /* insert page entry */
    Page p = PageCreate(start, npage);
    ptable->resize(ptable, start + npage, &p);
    data = p.data;
    TLB * pmap = &(mgr->pmap);
    pmap->set(pmap, data, &p);
  }
  vleak_size++;
#if TVM_CRT_DEBUG > 1
  printf("allocate: addr=%p, start=%d/%d, npage=%d, vleak=%d\n",
         data, start, TVM_CRT_MAX_PAGES, npage, vleak_size);
#endif  // TVM_CRT_DEBUG
  return data;
}

/*!
 * \brief Reallocate memory from manager
 * \param ptr The pointer to the memory area to be reallocated
 * \param size The size of memory
 * \return The virtual address
 */
void* MemoryManager_Realloc(MemoryManager * mgr, void * ptr, tvm_index_t size) {
  char * data = (char*)ptr;  // NOLINT(*)
  PageTable * ptable = &(mgr->ptable);
  TLB * pmap = &(mgr->pmap);
  MultiMap * free_map = &(mgr->free_map);
  tvm_index_t start = 0;
  tvm_index_t npage = (size + kPageSize - 1) / kPageSize;
  if (ptr) {
    // get page size for given pointer
    CHECK_NE(pmap->count, 0, "invalid translation look-aside buffer.");
    PageEntry * entry = pmap->find(pmap, (char*)ptr);  // NOLINT(*)
    CHECK_NE(entry, 0, "no valid page entry found.");
    Page * pptr = &(entry->page);
    // if the page size is smaller than target page size,
    // try allocate new space
    if (pptr->num_pages < npage) {
      // TODO(liangfu): found out whether we can extend current entry
      //
      // insert new page entry
      IndexedEntry * it = free_map->lower_bound(free_map, npage);
      if (it != free_map->end(free_map)) {
        data = it->page.data;
        start = it->page.ptable_begin;
        npage = it->page.num_pages;
        free_map->erase(free_map, it);
      } else {
        start = ptable->count;
        CHECK_LE((unsigned)(start + npage), (sizeof(g_memory_pool) / kPageSize),
                 "insufficient memory, start=%" PRId64 ", npage=%" PRId64 ", total=%" PRId64 "",
                 start, npage, start + npage);
        Page p = PageCreate(start, npage);
        ptable->resize(ptable, start + npage, &p);
        data = p.data;
        pmap->set(pmap, data, &p);
      }
      // copy previous data to the new entry
      memcpy(data, ptr, kPageSize * pptr->num_pages);
      // release memory
      free_map->insert(free_map, pptr->num_pages, pptr);
    } else {
      start = pptr->ptable_begin;
    }
  } else {
    IndexedEntry * it = free_map->lower_bound(free_map, npage);
    if (it != free_map->end(free_map)) {
      Page p = it->page;
      free_map->erase(free_map, it);
      data = p.data;
      start = p.ptable_begin;
      npage = p.num_pages;
    } else {
      PageTable * ptable = &(mgr->ptable);
      start = ptable->count;
      CHECK_LE((unsigned)(start + npage), (sizeof(g_memory_pool) / kPageSize),
               "insufficient memory, start=%" PRId64 ", npage=%" PRId64 ", total=%" PRId64 "",
               start, npage, start + npage);
      /* insert page entry */
      Page p = PageCreate(start, npage);
      ptable->resize(ptable, start + npage, &p);
      data = p.data;
      TLB * pmap = &(mgr->pmap);
      pmap->set(pmap, data, &p);
    }
    vleak_size++;
  }
#if TVM_CRT_DEBUG > 1
  printf("reallocate: addr=%p, start=%d/%d, npage=%d, vleak=%d, size=%d\n",
         data, start, TVM_CRT_MAX_PAGES, npage, vleak_size, size);
#endif  // TVM_CRT_DEBUG
  return data;
}

/*!
 * \brief Free the memory.
 * \param ptr The pointer to the memory to deallocate
 * \return The virtual address
 */
void MemoryManager_Free(MemoryManager * mgr, void* ptr) {
  TLB * pmap = &(mgr->pmap);
  CHECK_NE(pmap->count, 0, "invalid translation look-aside buffer.");
  PageEntry * entry = pmap->find(pmap, (char*)ptr);  // NOLINT(*)
  CHECK_NE(entry, 0, "no valid page entry found.");
  Page * p = &(entry->page);
  MultiMap * free_map = &(mgr->free_map);
  free_map->insert(free_map, p->num_pages, p);
  vleak_size--;
#if TVM_CRT_DEBUG > 1
  printf("release: addr=%p, start=%d/%d, npage=%d, vleak=%d\n",
         ptr, entry->page.ptable_begin, TVM_CRT_MAX_PAGES, entry->page.num_pages, vleak_size);
#endif  // TVM_CRT_DEBUG
}

MemoryManager * MemoryManagerCreate() {
  static MemoryManager mgr;
  memset(&mgr, 0, sizeof(MemoryManager));
  /* handle MemoryManager member functions */
  mgr.Alloc = MemoryManager_Alloc;
  mgr.Realloc = MemoryManager_Realloc;
  mgr.Free = MemoryManager_Free;
  /* handle PageTable member functions */
  mgr.ptable.resize = PageTable_Resize;
  /* handle TLB member functions */
  mgr.pmap.set = TLB_Set;
  mgr.pmap.find = TLB_Find;
  /* handle free_map member functions */
  mgr.free_map.lower_bound = MultiMap_LowerBound;
  mgr.free_map.end = MultiMap_End;
  mgr.free_map.erase = MultiMap_Erase;
  mgr.free_map.insert = MultiMap_Insert;
  return &mgr;
}

MemoryManager * TVMGetGlobalMemoryManager() {
  /* initialize once */
  static uint32_t initialized = 0;
  static MemoryManager * mgr;
  if (!initialized) {
    mgr = MemoryManagerCreate();
    memset(g_memory_pool, 0, sizeof(g_memory_pool));
    initialized = 1;
  }
  return mgr;
}

/** \brief Allocate memory from manager */
void * vmalloc(size_t size) {
  MemoryManager * mgr = TVMGetGlobalMemoryManager();
  return mgr->Alloc(mgr, size);
}

/** \brief Reallocate memory from manager */
void * vrealloc(void * ptr, size_t size) {
  MemoryManager * mgr = TVMGetGlobalMemoryManager();
  return mgr->Realloc(mgr, ptr, size);
}

/** \brief Release memory from manager */
void vfree(void * ptr) {
  MemoryManager * mgr = TVMGetGlobalMemoryManager();
  mgr->Free(mgr, ptr);
}