XMem.cpp 45.3 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
/* NiuTrans.Tensor - an open-source tensor library
 * Copyright (C) 2017, Natural Language Processing Lab, Northestern University. 
 * All rights reserved.
 *
 * Licensed 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.
 */

/*
 * 
 * $Created by: XIAO Tong (xiaotong@mail.neu.edu.cn) 2016-5-25
 *
 */

#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "XGlobal.h"
#include "XUtility.h"
#include "XMem.h"

/* the nts (NiuTrans.Tensor) namespace */
namespace nts{
33
    
34 35
//int testxmemid = 0;
//void * recordp = NULL;
36

37 38 39 40 41
/*
for managing the memories
*/
XMemManager GMems;

42 43 44 45 46 47 48 49 50 51 52 53
XMem * GMem;

/* constructor */
XMem::XMem()
{
    memset(this, 0, sizeof(XMem));
    devID = -1;
    mode = UNI_FREE;
    curBlockPin = -1;
    indexOffset = -1;
    name = new char[64];
    strcpy(name, "xmem");
54
    signature = 0;
xiaotong committed
55
    mergeFreeOTF = true;
56
    isInitialized = false;
57 58 59 60 61 62 63 64 65 66
}

/* 
constructor 
>> myDevID - device id 
             -1:  CPU memory
             >=0: GPU device ID
>> myMode - mode of running the memory pool
            UNI_FREE: free all the space at the end of using the memory pool
            FREE_ON_THE_FLY: normal "malloc" and "free" mode
67
>> myBlockSize - size of a memory block
68 69 70 71 72 73 74 75 76 77
>> myBlockNum  - number of memory blocks
>> myBufSize - size of buffer
*/
XMem::XMem(int myDevID, MEMPOOL_MODE myMode, MTYPE myBlockSize, int myBlockNum, MTYPE myBufSize)
{
    memset(this, 0, sizeof(XMem));
    curBlockPin = -1;
    indexOffset = -1;
    name = new char[64];
    strcpy(name, "xmem");
78
    signature = 0;
xiaotong committed
79
    mergeFreeOTF = true;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    Initialize(myDevID, myMode, myBlockSize, myBlockNum, myBufSize);
}

/* deconstructor */
XMem::~XMem()
{
#ifdef USE_CUDA
    int devIDBackup = -1;
    cudaGetDevice(&devIDBackup);
    SetDevice(devID);

    if(devID >= 0 && cublasHandle != NULL)
        cublasDestroy(cublasHandle);
    curandDestroyGenerator(randGen);

    SetDevice(devIDBackup);
#endif
    Free();
    delete[] name;
99 100 101
    delete[] memIndex;
    delete[] memIndex2;
    delete[] minSizeIndex;
102 103 104 105 106 107 108 109 110 111
}

/* 
initialize it 
>> myDevID - device id 
             -1:  CPU memory
             >=0: GPU device ID
>> myMode - mode of running the memory pool
            UNI_FREE: free all the space at the end of using the memory pool
            FREE_ON_THE_FLY: normal "malloc" and "free" mode
112
>> myBlockSize - size of a memory block
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
>> myBlockNum  - number of memory blocks
>> myBufSize - size of buffer
*/
void XMem::Initialize(int myDevID, MEMPOOL_MODE myMode, MTYPE myBlockSize, int myBlockNum, MTYPE myBufSize)
{
    Free();

    CheckNTErrors((myBlockSize > 0 && myBlockNum > 0), "Illegal member block settings!");

    devID = myDevID;
    mode = myMode;
    maxBlockSize = myBlockSize;
    blockNum = myBlockNum;

    blocks = new XMemBlock[blockNum];
    for(int i = 0; i < blockNum; i++){
        blocks[i].mem = NULL;
        blocks[i].size = maxBlockSize;
        blocks[i].sizeDesired = maxBlockSize;
        blocks[i].used = 0;
    }

    curBlock = blocks;
    curBlockID = 0;
    finalBlockID = 0;

    if(myDevID < 0){
        buf = new char[(unsigned int)myBufSize];
    }
    else{
#ifdef USE_CUDA
        int devIDBackup = -1;
        cudaGetDevice(&devIDBackup);
        SetDevice(myDevID);

        CheckNTErrors(cudaMalloc((void **)&buf, myBufSize) == cudaSuccess, "Cannot allocate the memory.");
        CheckNTErrors(cudaMemset(buf, 0, myBufSize) == cudaSuccess, "Cannot update the memory.");
150 151
        CheckNTErrors(curandCreateGenerator(&randGen, CURAND_RNG_PSEUDO_DEFAULT) == CURAND_STATUS_SUCCESS, "Cannot make the cuda random number generator!");
        CheckNTErrors(curandSetPseudoRandomGeneratorSeed(randGen, (unsigned)time(NULL)) == CURAND_STATUS_SUCCESS, "Cannot generate the seed!");
152 153 154 155 156 157 158 159 160 161 162

        SetDevice(devIDBackup);

        /* create the cublas handle */
        SetComputationMode(true);
#else
        ShowNTErrors("Please specify USE_CUDA for compiling this program.");
#endif
    }

    bufSize = myBufSize;
163

164 165 166 167
#ifdef SMALL_DEVICE
    if (myMode == FREE_ON_THE_FLY)
        SetIndex(50000);
#else
168 169
    if (myMode == FREE_ON_THE_FLY)
        SetIndex(MILLION);
170
#endif
171 172

    signature++;
173
    isInitialized = true;
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
}

/* free memory */
void XMem::Free()
{
    for(int i = 0; i < blockNum; i++){
        Free(devID, blocks[i].mem);
    }
    delete[] blocks;
    blocks = NULL;

    Free(devID, buf);
    buf = NULL;
    bufSize = 0;
    bufUsed = 0;

    devID = -1;
}

/* 
free a piece of memory 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mem - address of the memory block to release
*/
void XMem::Free(int myDevID, void * mem)
{
    if(mem == NULL)
        return;

    /* on CPUs */
    if(myDevID < 0){
        delete[] (char*)mem;
    }
    /* on GPUs */
    else{
#ifdef USE_CUDA
210 211
        int devIDBackup = -1;
        cudaGetDevice(&devIDBackup);
212
        SetDevice(myDevID);
213

214 215 216 217
        cudaError_t error = cudaFree((char*)mem);
        if(error != cudaSuccess){
            ShowNTErrors("Cannot free the memory.");
        }
218 219

        SetDevice(devIDBackup);
220 221 222 223 224 225
#else
        ShowNTErrors("Please specify USE_CUDA for compiling this program.");
#endif
    }
}

226 227 228
/*
get the signature
<< return - the signature
229 230 231 232 233 234 235
*/
MTYPE XMem::GetSignature()
{
    return signature;
}

/* 
236
set the name of the memory pool 
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
>> myName - name of the memory pool
*/
void XMem::SetName(const char * myName)
{
    delete[] name;
    name = new char[(int)strlen(myName) + 1];
    strcpy(name, myName);
}

/* 
switch to the device where we intend to work 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
*/
void XMem::SetDevice(int myDevID)
{
    if(myDevID < 0)
        return;

#ifdef USE_CUDA
    cudaError_t error = cudaSetDevice(myDevID);

    if (error != cudaSuccess){
        fprintf(stderr, "Error! Calling cudaSetDevice(%d) fails(%d:%s)\n", myDevID, error, cudaGetErrorString(error));
        exit(1);
    }

#else
    ShowNTErrors("Please specify USE_CUDA for compiling this program.");
#endif
}

/* 
269
switch to the device (with fast cuda execution mode) we intend to work on
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
*/
void XMem::SetDeviceFast(int myDevID)
{
    SetDevice(myDevID);
#ifdef USE_CUDA
    cudaError_t error = cudaSetDeviceFlags(cudaDeviceScheduleSpin|cudaDeviceLmemResizeToMax);
    if (error != cudaSuccess){
        fprintf(stderr, "Error! Calling cudaSetDeviceFlags(%d) fails(%d:%s)\n", myDevID, error, cudaGetErrorString(error));
        exit(1);
    }
#endif
}

/* 
285
run in the static mode
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
>> myIsStatic - specify if the memory allocation is static
*/
void XMem::SetStaticMode(bool myIsStatic)
{
    isStatic = myIsStatic;
}

/* 
specify if the memory pool is used for tensor computation (rather
than storage 
>> myIsForComputation - specify if the memory pool is used in computation (if
                        so we need to create some handles for calling the BLAS interfaces)
*/
void XMem::SetComputationMode(bool myIsForComputation)
{
#ifdef USE_CUDA
    int devIDBackup = -1;
    cudaGetDevice(&devIDBackup);
    SetDevice(devID);

    if(!myIsForComputation && devID >= 0 && cublasHandle != NULL)
        cublasDestroy(cublasHandle);
    if(myIsForComputation)
309
        CheckNTErrors((enum curandStatus)cublasCreate(&cublasHandle) == CURAND_STATUS_SUCCESS, 
310
                      "Cannot create the cublas handle.");
311 312 313 314 315 316 317 318 319 320 321 322 323

    SetDevice(devIDBackup);
#endif
}

/*
initialize the index
>> indexSize - size of the index
>> minSizeFirst - minimal size allocation for the first entry
>> minSizeNum - number of minimal-size index nodes
*/
void XMem::SetIndex(INT_64 indexSize, MTYPE minSizeFirst, int minSizeNum)
{
324 325
    delete[] memIndex;
    delete[] memIndex2;
326
    delete[] minSizeIndex;
327

328 329 330
    nodeNum = indexSize;
    nodeNumUsed = minSizeNum * 2;
    indexEntryNum = minSizeNum;
331 332 333 334 335 336
    
    memIndex = new MPieceNode[nodeNum];
    memset(memIndex, 0, sizeof(MPieceNode) * nodeNum);
    
    memIndex2 = new MPieceNode[nodeNum];
    memset(memIndex2, 0, sizeof(MPieceNode) * nodeNum);
337

338 339
    minSizeIndex = new MTYPE[indexEntryNum];
    memset(minSizeIndex, 0, sizeof(MTYPE) * indexEntryNum);
340

341 342 343
    minSizeIndex[0] = minSizeFirst;
    for(int i = 1; i < indexEntryNum; i++)
        minSizeIndex[i] = minSizeIndex[i - 1] * 2;
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 394 395 396 397 398 399 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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

    indexOffset = GetMSB(minSizeFirst);
}

/* get device id */
int XMem::GetDevID()
{
    return devID;
}

/* set desired memory block size */
void XMem::SetDesiredSize(int myDevID, int blockID, MTYPE mySize)
{
    CheckNTErrors((blockID >= 0 && blockID < blockNum), "Illegal block id!");
    CheckNTErrors((mySize > 0), "Illegal block size!");
    CheckNTErrors((blocks[blockID].mem == NULL), "Cannot reset a memory block that is being used!");

    blocks[blockID].sizeDesired = mySize;
    blocks[blockID].size = mySize;
}

/* 
require a piece of memory 
>> mySize - size of the require memory
*/
void * XMem::Alloc(MTYPE mySize)
{
    return Alloc(devID, mySize);
}

/* 
require a piece of memory 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mySize - size of the require memory
*/
void * XMem::Alloc(int myDevID, MTYPE mySize)
{
    if(mode == FREE_ON_THE_FLY)
        return AllocStandard(myDevID, mySize);
    else if(isStatic)
        return AllocStatic(myDevID, mySize);
    else
        return AllocDynamic(myDevID, mySize);
}

/* 
require a piece of memory in a dynamic manner 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mySize - size of the require memory
*/
void * XMem::AllocDynamic(int myDevID, MTYPE mySize)
{
    int ID;
    XMemBlock * b = NULL;
    bool firstHit = false;

    for (ID = curBlockID; ID < blockNum; ID++) {
        b = blocks + ID;
        if (!firstHit && b->size > b->used) {
            firstHit = true;
            curBlockID = ID;
            curBlock = blocks + curBlockID;
        }
        if (b->size >= b->used + mySize)
            break;
    }

    CheckNTErrors((curBlockID < blockNum), "No enough memory blocks.");
    CheckNTErrors((ID < blockNum), "Cannot find a available memory block. Please use a larger memory pool.");
    CheckNTErrors((b->size - b->used >= mySize), "Cannot allocate the memory. Please use a larger memory block!");

    if (ID > finalBlockID)
        finalBlockID = ID;

    char * mem = NULL;
    char * required = NULL;
    int backOffset = 0;

    /* allocate the memory */
    if (b->mem == NULL && b->used == 0) {
        /* on CPUs */
        if (myDevID < 0) {
            mem = new char[(unsigned int)b->size + 2 * CUDA_PITCH];
            memset(mem, 0, (unsigned int)b->size + 2 * CUDA_PITCH);
        }
        /* on GPUs */
        else {
#ifdef USE_CUDA
            int devIDBackup = -1;
            cudaGetDevice(&devIDBackup);
            SetDevice(myDevID);
            cudaError_t e = cudaMalloc((void **)&mem, b->size + 2 * CUDA_PITCH);
            if (e != cudaSuccess) {
                ShowNTErrors("Cannot allocate the memory.");
            }
            CheckNTErrors(cudaMemset(mem, 0, b->size + 2 * CUDA_PITCH) == cudaSuccess, "Cannot update the memory.");
            SetDevice(devIDBackup);
#else
            ShowNTErrors("Please specify USE_CUDA for compiling this program.");
443

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 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
#endif
        }

        b->mem = mem;
    }

#ifdef USE_CUDA
    if (myDevID >= 0) {
        long long address = (long long)((char*)b->mem + b->used);
        int offset = address % CUDA_PITCH;
        backOffset = offset > 0 ? CUDA_PITCH - offset : 0;
    }
#endif

    required = (char*)b->mem + b->used + backOffset;
    b->used += mySize + backOffset;

#ifdef USE_CUDA
    if (myDevID >= 0) {
        CheckNTErrors(((long long)required % CUDA_PITCH == 0), "The GPU memory is not aligned.");
    }
#endif

    CheckNTErrors((b->size + 2 * CUDA_PITCH >= b->used), "Something is wrong with the memory block.");

    return required;
}

/* 
required a piece of memory with fixed size (if possible) 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mySize - size of the require memory
*/
void * XMem::AllocStatic(int myDevID, MTYPE mySize)
{
    for(int ID = curBlockID; ID < blockNum; ID++){
        XMemBlock * b = blocks + ID;
        if(b->mem == NULL){
            CheckNTErrors((mySize > 0), "Illegal required memory block size!");
            CheckNTErrors((b->mem == NULL), "Incorrect memory allocation!");
            b->size = mySize;
            return AllocDynamic(myDevID, mySize);
        }
        else if(b->mem != NULL && b->size > b->used + mySize)
            return AllocDynamic(myDevID, mySize);
    }

    ShowNTErrors("Cannot find a valid memory block!");

    return NULL;
}

/* 
require a piece of memory that is not in the memory pool 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mySize - size of the require memory
*/
void * XMem::AllocGlobal(int myDevID, MTYPE mySize)
{
    return XMemAllocOnDev(myDevID, (unsigned int)mySize);
}

/* get the available size of the memory that can be used */
MTYPE XMem::GetAvailableSize(int myDevID)
{
    return curBlock->size - curBlock->used;
}

/* 
require a piece of memory in the buffer
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mySize - size of the require memory
>> pitch - pitch for aligned memory 
<< return - the head pointer of the required memory
*/
void * XMem::AllocBuf(int myDevID, MTYPE mySize, int pitch)
{
    MTYPE backOffset = 0;

    if(pitch > 1){
        MTYPE address = (MTYPE)((char*)buf + bufUsed);
        int offset  = address % pitch;
        backOffset = offset > 0 ? pitch - offset : 0;
    }

    if((bufSize - bufUsed < mySize)){
        XPRINT1(0, stderr, "Cannot allocate the memory (%s). Please specify a larger buffer in XMem!", name);
        exit(1);
    }

    char * required = (char*)buf + bufUsed + backOffset;
    bufUsed += mySize + backOffset;

    CheckNTErrors((bufSize >= bufUsed), "Something is wrong with the memory block.");

    return required;
}

/* 
release a piece of memory 
>> p - pointer to the memory piece we intend to release
545 546
>> size - size of the memory piece to release
>> code - code the memory 
547
*/
548
void XMem::Release(void * p, MTYPE size, MTYPE code)
549
{
550 551
    if(code == signature)
        Release(devID, p, size);
552 553 554 555 556 557
}

/* 
release a piece of memory 
>> myDevID - device id
>> p - pointer to the memory piece we intend to release
558
>> size - size of the memory piece to release
559
*/
560
void XMem::Release(int myDevID, void * p, MTYPE size)
561 562
{
    if(mode == FREE_ON_THE_FLY)
563
        ReleaseStandard(myDevID, p, size);
564 565 566 567 568 569 570 571 572 573 574
}

/* 
release a piece of memory in the buffer
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mySize - size of the require memory
>> pitch - pitch for aligned memory 
*/
void XMem::ReleaseBuf(int myDevID, MTYPE mySize, int pitch)
{
    CheckNTErrors((bufUsed >= mySize), 
575
                  "Cannot allocate the memory. Please specify a larger buffer in XMem!");
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

    MTYPE backOffset = 0;

    if(pitch > 1){
        MTYPE address = (MTYPE)((char*)buf + (bufUsed - mySize));
        backOffset  = address % pitch;
    }

    bufUsed -= (mySize + backOffset);
}

/* 
free a piece of memory that is not in the memory pool 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> p - the pointer to the address of the memory we intend to free
*/
void XMem::ReleaseGlobal(int myDevID, void * p)
{
    XMemFreeOnDev(myDevID, p);
}

/* 
allocate a piece of memory as "malloc" 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> mySize - size of the require memory
>> myIsRebuiltIndex - indicates whether the index has been just rebuilt
<< return - index
*/
void * XMem::AllocStandard(int myDevID, MTYPE mySize, bool myIsRebuiltIndex)
{
606
    CheckNTErrors(memIndex != NULL, "The index of the memory pool is not initialized!");
607 608 609 610 611 612 613 614 615 616 617

    if(mySize <= minSizeIndex[0])
        mySize = minSizeIndex[0];

    int index = FindIndexEntry(mySize);
    MPieceNode * entry = NULL;
    MPieceNode * node = NULL;
    MPieceNode * hit = NULL;
    void * result = NULL;

    /* search for the memory piece avialable for the allocation */
618
    for(int i = index; i <= indexEntryNum; i++){
619
        if(i == indexEntryNum){
620
            entry = memIndex + index;
621 622 623
            CheckNTErrors(mySize >= minSizeIndex[index], "Wrong index!");
        }
        else
624
            entry = memIndex + i;
625
        
626
        node = entry->next;
627 628 629
        while(node != NULL){
            if(node->size == 0){
                MPieceNode * next = node->next;
xiaotong committed
630
                RemoveIndexNode(node, entry);
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
                node = next;
            }
            else{
                if(node->size >= mySize){
                    hit = node;
                    break;
                }
                node = node->next;
            }
        }

        if(hit != NULL)
            break;
    }
    
    /* if a free memory piece is found, we allocate the memory on it. */
    if(hit != NULL){
648 649
        MHeader * head = &hit->head;
        char * beg = (char*)GetPitchedAddress((char*)hit->p, MY_PITCH);
650
        char * end = (char*)beg + mySize;
651
        MTYPE needed = end - (char*)hit->p;
652
        MTYPE remaining = head->size - needed;
653 654
        
        if(remaining >= minSizeIndex[0]){
655 656

            /* make a new index node */
657 658
            MPieceNode * newNode = memIndex + nodeNumUsed++;
            newNode->head.indexNode = newNode;
659
            newNode->p = end;
660 661 662 663 664 665 666 667 668 669 670 671 672 673
            newNode->pReal = NULL;
            newNode->size = (char*)end + remaining -
                            (char*)GetPitchedAddress((char*)end, MY_PITCH);
            
            AddFreeIndexNode(newNode);
            
            /* connections for headers */
            MHeader &cur = hit->head;
            MHeader &next = newNode->head;
            next.pre = &cur;
            next.next = cur.next;
            cur.next = &next;
            cur.size = needed;
            
674 675 676
            if(next.next != NULL)
                next.next->pre = &next;
            
677 678 679
            next.state = 1;
            next.size = remaining;
            next.blockID = cur.blockID;
680 681
        }
        
682 683 684
        hit->size = mySize;
        hit->head.state = 2;
        hit->pReal = beg;
685
        blocks[hit->head.blockID].used += head->size;
686
        
xiaotong committed
687
        RemoveIndexNode(hit);
688 689
        AddAllocIndexNode(hit);
        
690 691 692 693 694 695 696 697 698 699 700 701 702 703
        result = beg;
    }
    else{
        /* if no free memory piece is available, we rebuild the index and merge small fragments
           to make bigger free memory pieces. */
        if(!myIsRebuiltIndex){
            RebuildIndex();
            result = AllocStandard(myDevID, mySize, true);
        }
        /* if there is still no available memory piece, we have to obtain a new block of memory. */
        else{
            int bi;
            for(bi = 0; bi < blockNum; bi++){
                XMemBlock * block = blocks + bi;
704 705 706 707
                if (block->mem != NULL && (block->head != NULL || block->size < mySize + 2 * MY_PITCH))
                    continue;
                
                if (block->mem == NULL) {
708
                    block->size = MAX(block->sizeDesired, mySize + 2 * MY_PITCH);
709 710 711 712
                    if (myDevID < 0) {
                        block->mem = new char[block->size];
                        memset(block->mem, 0, block->size);
                    }
713
                    else {
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
#ifdef USE_CUDA
                        int devIDBackup = -1;
                        cudaGetDevice(&devIDBackup);
                        SetDevice(myDevID);
                        cudaError_t e = cudaMalloc((void **)&block->mem, block->size);
                        if (e != cudaSuccess) {
                            ShowNTErrors("Cannot allocate the memory.");
                        }
                        CheckNTErrors(cudaMemset(block->mem, 0, block->size) == cudaSuccess, "Cannot update the memory.");
                        SetDevice(devIDBackup);
#else
                        ShowNTErrors("Please specify USE_CUDA for compiling this program.");
#endif
                    }
                }
729 730 731 732 733 734 735 736

                curBlockID = MAX(curBlockID, bi);
                    
                /* make a new index node */
                MPieceNode * newNode = memIndex + nodeNumUsed++;
                newNode->head.indexNode = newNode;
                newNode->p = block->mem;
                newNode->pReal = NULL;
737 738 739
                //newNode->size = (char*)block->mem + block->size -
                //                (char*)GetPitchedAddress(block->mem, MY_PITCH);
                newNode->size = mySize;
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                    
                AddFreeIndexNode(newNode);
                    
                MHeader &header = newNode->head;
                header.state = 1;
                header.size = block->size;
                header.pre = NULL;
                header.next = NULL;
                header.blockID = bi;
                    
                block->head = &header;
                block->used = 0;
                    
                result = AllocStandard(myDevID, mySize, myIsRebuiltIndex);
                break;
755 756 757 758 759 760
            }
            CheckNTErrors(bi < blockNum, "No enough memory is available!");
        }
    }

    /* if all index nodes are used, we rebuild the index to release the nodes that are free */
761
    if(nodeNumUsed == nodeNum){
762 763
        RebuildIndex();
        CheckNTErrors(nodeNumUsed < nodeNum, "No enough index nodes for the memory pool!");
764 765
    }

766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 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
    /*if(testxmemid == 30){
        recordp = result;
    }

    if(curBlockID >= 25){
        MHeader * head = blocks[25].head;
        while(head != NULL){
            fprintf(stderr, "head: %ld %ld\n", head->indexNode->pReal, head->indexNode->size);
            head = head->next;
        }
    }

    if(testxmemid == 32){
        int nnn = 0;
    }

    if(recordp != NULL){
        MTYPE size = mySize;
        if(size <= minSizeIndex[0])
            size = minSizeIndex[0];
    
        MPieceNode * entry = NULL;
        MPieceNode * node = NULL;
        MPieceNode * hit = NULL;
        MPieceNode * last = NULL;
    
        entry = memIndex + indexEntryNum + FindIndexEntry(size);
    
        last = entry;
        node = entry->next;
    
        while(node != NULL){
            CheckNTErrors(node->pre == last, "Something is wrong!");
            CheckNTErrors(last->next == node, "Something is wrong!");
            CheckNTErrors(node->head.state == 2, "Something is wrong!");
            last = node;
        
            if(node->size == 0){
                MPieceNode * next = node->next;
                RemoveFreeIndexNode(node, entry);
                node = next;
                ShowNTErrors("Something is wrong!");
            }
            else{
                CheckNTErrors(node->pReal != NULL, "Illegal pointer!");
                if(node->pReal == recordp){
                    hit = node;
                    break;
                }
                node = node->next;
            }
        }

        if(hit == NULL){
            int nnn = 0;
        }
    }*/

824 825 826 827 828 829 830 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
    return result;
}

/* 
find the highest set bit (or most significant set bit) in an integer-64 
>> mySize - required size
<< return - the position of MSB
*/
int XMem::GetMSB(MTYPE mySize)
{
    MTYPE value = mySize;

    int result = 0;
    if(value){
        if(0xFFFFFFFF00000000&value){value>>=(1<<5); result|=(1<<5);}
        if(0x00000000FFFF0000&value){value>>=(1<<4); result|=(1<<4);}
        if(0x000000000000FF00&value){value>>=(1<<3); result|=(1<<3);}
        if(0x00000000000000F0&value){value>>=(1<<2); result|=(1<<2);}
        if(0x000000000000000C&value){value>>=(1<<1); result|=(1<<1);}
        if(0x0000000000000002&value){result|=(1<<0);}
    }
    else
        result = -1;

    return result;
}

/* 
find the index entry for allocation query 
>> mySize - required size
<< return - index
*/
int XMem::FindIndexEntry(MTYPE mySize)
{
    CheckNTErrors(minSizeIndex != NULL && indexOffset >= 0, 
                 "The index of the memory pool is not initialized!");

    if(mySize <= minSizeIndex[0])
        mySize = minSizeIndex[0];

    int index = GetMSB(mySize) - indexOffset;

    if(index >= indexEntryNum)
        index = indexEntryNum - 1;

    return index;
}

/* 
xiaotong committed
873
remove an index node
874 875 876
>> node - node to remove
>> - the entry of the list that keeps the node
*/
xiaotong committed
877
void XMem::RemoveIndexNode(MPieceNode * node, MPieceNode * entry)
878 879 880
{
    MPieceNode * pre = node->pre;
    MPieceNode * next = node->next;
881
    
xiaotong committed
882

883
    CheckNTErrors(pre != NULL, "cannot free the entry node!");
884

885 886 887 888 889 890
    pre->next = next;
    if(next != NULL)
        next->pre = pre;
    
    node->pre = NULL;
    node->next = NULL;
891 892 893
}

/* 
894
add an index node for available memory pieces
895 896 897
>> node - node to add
>> entry - the entry of the list to append the node
*/
898
void XMem::AddFreeIndexNode(MPieceNode * node, MPieceNode * entry)
899 900
{
    MPieceNode * entryForMe = entry != NULL ? entry :
901
                              memIndex + FindIndexEntry(node->size);
xiaotong committed
902 903 904 905 906 907 908 909 910 911 912 913 914

    /*MPieceNode * backup = entryForMe->next;

    while(backup != NULL && backup->head.size < node->head.size){
        backup = backup->next;
        entryForMe = entryForMe->next;
    }

    entryForMe->next = node;
    node->pre = entryForMe;
    node->next = backup;
    if(backup != NULL)
        backup->pre = node;*/
915 916 917 918 919 920 921
    
    MPieceNode * backup = entryForMe->next;
    entryForMe->next = node;
    node->pre = entryForMe;
    node->next = backup;
    if(backup != NULL)
        backup->pre = node;
922

923 924 925 926 927 928 929 930 931 932 933
    CheckNTErrors(node != node->next, "Something wrong with the index node!");
    CheckNTErrors(node != node->pre,  "Something wrong with the index node!");
}
    
/*
remove an index node for memory pieces in use
>> node - node to remove
>> - the entry of the list that keeps the node
*/
void XMem::RemoveAllocIndexNode(MPieceNode * node, MPieceNode * entry)
{
xiaotong committed
934
    RemoveIndexNode(node, entry);
935
}
936

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
/*
add an index node for memory pieces in use
>> node - node to add
>> entry - the entry of the list to append the node
*/
void XMem::AddAllocIndexNode(MPieceNode * node, MPieceNode * entry)
{
    MPieceNode * entryForMe = entry != NULL ? entry :
                              memIndex + indexEntryNum + FindIndexEntry(node->size);
    
    MPieceNode * backup = entryForMe->next;
    entryForMe->next = node;
    node->pre = entryForMe;
    node->next = backup;
    if(backup != NULL)
        backup->pre = node;
    
954 955 956 957 958 959 960 961
    CheckNTErrors(node != node->next, "Something wrong with the index node!");
    CheckNTErrors(node != node->pre,  "Something wrong with the index node!");
}

/* 
release a piece of memory as "free" 
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
>> p - the pointer to the address of the memory we intend to free
962
>> size - size of the memory piece to release
963
*/
964
void XMem::ReleaseStandard(int myDevID, void * p, MTYPE size)
965
{
966 967
    if(p == NULL)
        return;
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
    
    if(size <= minSizeIndex[0])
        size = minSizeIndex[0];
    
    MPieceNode * entry = NULL;
    MPieceNode * node = NULL;
    MPieceNode * hit = NULL;
    MPieceNode * last = NULL;
    
    entry = memIndex + indexEntryNum + FindIndexEntry(size);
    
    last = entry;
    node = entry->next;
    
    while(node != NULL){
        CheckNTErrors(node->pre == last, "Something is wrong!");
        CheckNTErrors(last->next == node, "Something is wrong!");
        CheckNTErrors(node->head.state == 2, "Something is wrong!");
        last = node;
        
        if(node->size == 0){
            MPieceNode * next = node->next;
xiaotong committed
990
            RemoveIndexNode(node, entry);
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
            node = next;
            ShowNTErrors("Something is wrong!");
        }
        else{
            CheckNTErrors(node->pReal != NULL, "Illegal pointer!");
            if(node->pReal == p){
                hit = node;
                break;
            }
            node = node->next;
        }
    }
    
    CheckNTErrors(hit != NULL, "No header is found!");
    
    hit->head.state = 1;
    
    RemoveAllocIndexNode(hit);
1009

xiaotong committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    MTYPE usedSize = (char*)hit->p + hit->head.size - (char*)GetPitchedAddress((char*)hit->p, MY_PITCH);
    blocks[hit->head.blockID].used -= usedSize;

    if(mergeFreeOTF){
        MHeader * head = &hit->head;
        MHeader * pre = head->pre;
        MHeader * next = head->next;
        bool mergeLeft = false;
        bool mergeRight = false;

        CheckNTErrors(head != pre, "wrong list of memory headers");
        CheckNTErrors(head != next, "wrong list of memory headers");

        if(pre != NULL && pre->state == 1 && pre->blockID == head->blockID){
            mergeLeft = true;
            head->pre = pre->pre;
            if(head->pre != NULL)
                head->pre->next = head;
            hit->p = pre->indexNode->p;
            hit->head.size += pre->size;
            RemoveAllocIndexNode(pre->indexNode);

            if(pre == blocks[head->blockID].head)
                blocks[head->blockID].head = head;
        }
1035

xiaotong committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
        if(next != NULL && next->state == 1 && next->blockID == head->blockID){
            mergeRight = true;
            head->next = next->next;
            if(head->next != NULL)
                head->next->pre = head;
            hit->head.size += next->size;
            RemoveAllocIndexNode(next->indexNode);
        }

        if(!mergeLeft && !mergeRight){
            hit->size = usedSize;
        }
        else{
            hit->size = (char*)hit->p + hit->head.size - (char*)GetPitchedAddress((char*)hit->p, MY_PITCH);
        }
    }
    else{
        hit->size = usedSize;
    }

    AddFreeIndexNode(hit);
1057 1058 1059 1060 1061
}

/* rebuild index to merge small fragments of memory and free the block with no use */
void XMem::RebuildIndex()
{
1062 1063
    int nodeNumUsed2 = indexEntryNum * 2;
    memset(memIndex2, 0, sizeof(MPieceNode) * indexEntryNum * 2);
1064 1065 1066

    for(int bi = 0; bi <= curBlockID; bi++){
        XMemBlock * block = blocks + bi;
1067
        if(block->mem == NULL || block->head == NULL)
1068 1069
            continue;

1070
        MHeader * head = block->head;
1071
        CheckNTErrors(head->size <= block->size, "Illegal memory block!");
1072 1073 1074
        
        block->head = NULL;
        block->used = 0;
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096

        /* if the block is not used, we delete it */
        if(head->state == 1 && head->size == block->size){
            if(devID < 0){
                delete[] (char*)block->mem;
            }
            else{
#ifdef USE_CUDA
                int devIDBackup = -1;
                cudaGetDevice(&devIDBackup);
                SetDevice(devID);
                CheckNTErrors(cudaFree((char*)block->mem) == cudaSuccess, "Cannot free the memory.");
                SetDevice(devIDBackup);
#else
                ShowNTErrors("Please specify USE_CUDA for compiling this program.");
#endif 
            }

            block->size = 0;
            block->mem = NULL;
        }
        else{
1097
            /* if the block is in use, we build the index */
1098 1099
            int pieceCount = 0;
            MTYPE size = 0;
1100
            MHeader * newLast = NULL;
1101 1102 1103 1104 1105 1106 1107 1108 1109
            while(head != NULL){
                MHeader * next = head->next;
                if(head->state == 1){
                    while(next != NULL && next->state == 1){
                        head->size += next->size;
                        next = next->next;
                    }
                    head->next = next;
                }
1110 1111 1112 1113 1114 1115 1116
                
                MPieceNode * node = head->indexNode;
                void * p = node->p;
                
                /* make a new index node */
                MPieceNode * newNode = memIndex2 + nodeNumUsed2++;
                newNode->p = p;
1117 1118 1119
                
                if(head->state == 1){
                    newNode->size = (char*)p + head->size -
1120
                                    (head->state == 1 ? (char*)GetPitchedAddress((char*)p, MY_PITCH) : (char*)head->indexNode->pReal);
1121 1122 1123 1124
                }
                else
                    newNode->size = node->size;
                
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
                newNode->pre = NULL;
                newNode->next = NULL;
                
                CheckNTErrors(newNode->size > 0, "Illegal index node!");
                
                MHeader * newHeader = &newNode->head;
                
                newHeader->indexNode = newNode;
                newHeader->pre = newLast;
                newHeader->next = NULL;
                newHeader->blockID = bi;
                newHeader->size = head->size;
                newHeader->state = head->state;
                
                if(newLast != NULL)
                    newLast->next = newHeader;
                
                if(head->state == 1){
                    newNode->pReal = NULL;
                    MPieceNode * entry = memIndex2 + FindIndexEntry(newNode->size);
                    AddFreeIndexNode(newNode, entry);
                }
                else{
                    newNode->pReal = head->indexNode->pReal;
                    MPieceNode * entry = memIndex2 + indexEntryNum + FindIndexEntry(newNode->size);
                    AddAllocIndexNode(newNode, entry);
                    block->used += head->size;
                }
                
                if(newLast == NULL)
                    block->head = newHeader;
                
1157
                pieceCount++;
1158
                size += head->size;
1159
                CheckNTErrors(size <= block->size, "Illegal block size!");
1160 1161 1162
                
                newLast = newHeader;
                head = next;
1163 1164 1165
            }
        }
    }
1166 1167 1168 1169 1170
    
    MPieceNode * backup = memIndex2;
    memIndex2 = memIndex;
    memIndex = backup;    
    nodeNumUsed = nodeNumUsed2;
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
}

/* 
reset the memory pool  
>> myDevID - device id(-1: CPU memory, >=0: GPU device ID)
*/
void XMem::Reset(int myDevID)
{
    for(int i = 0; i <= curBlockID; i++){
        if(devID >= 0){
#ifdef USE_CUDA
            CheckNTErrors(cudaFree(blocks[i].mem) == cudaSuccess, "Cannot free the memory.");
#else
            ShowNTErrors("We need cuda code here!");
#endif
        }
        else
            delete[] (char*)blocks[i].mem;

        blocks[i].mem = NULL;
        blocks[i].used = 0;
        blocks[i].size = blocks[i].sizeDesired;
    }

    curBlockID = 0;
    curBlock = blocks;
    curBlock->used = 0;
    finalBlockID = 0;
    bufUsed = 0;
}

/* 
get pitch for aligned memory
>> baseAddress - where the allocated memory starts
>> mySize - size of the require memory
<< return - the actual size required for aligned memory
*/
MTYPE XMem::GetPitch(int myDevID, MTYPE baseAddress, MTYPE mySize)
{
    long long address = baseAddress + mySize;
    int offset  = address % CUDA_PITCH;
    int backOffset = offset > 0 ? CUDA_PITCH - offset : 0;
    return mySize + backOffset;
}

/* 
get pitched address for aligned memory 
>> address - the starting address
>> pitch - as it is
<< return - pitched address
*/
void * XMem::GetPitchedAddress(void * address, MTYPE pitch)
{
    MTYPE p = (MTYPE)address;
    MTYPE offset  = p % pitch;
    MTYPE backOffset = offset > 0 ? pitch - offset : 0;
    return (char*)address + backOffset;
}

/* get current address (for use) */
void * XMem::GetAddress()
{
    if(curBlock->mem == NULL)
        Alloc(devID, 0);

    return curBlock->mem;
}

/* clear it */
void XMem::Clear()
{
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    if (mode == UNI_FREE) {
        for (int i = 0; i < blockNum; i++)
            blocks[i].used = 0;
        curBlock = blocks;
        curBlockID = 0;
    }
    else if (mode == FREE_ON_THE_FLY) {
        nodeNumUsed = indexEntryNum * 2;
        memset(memIndex, 0, sizeof(MPieceNode) * indexEntryNum * 2);
        for (int i = 0; i <= curBlockID; i++) {
            blocks[i].head = NULL;
            blocks[i].used = 0;
            if (i > 0) {
                blocks[i].size = blocks[i].sizeDesired;
                Free(devID, blocks[i].mem);
                blocks[i].mem = NULL;
            }
        }
        curBlock = blocks;
        curBlockID = 0;
    }
    else {
        ShowNTErrors("Something is wrong!");
    }

    signature++;
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
}

/* clear the buffer */
void XMem::ClearBuf()
{
    bufUsed = 0;
}

/* clear the memory pool and the buffer */
void XMem::ClearAll()
{
    Clear();
    ClearBuf();
}

/* 
set a variable to the input value
>> tgt - where we put the value
>> src - where the value is from
>> size - data size, e.g., for a float, it is sizeof(float)
>> tgtMem - the memory pool used by the target variable
>> srcMem - the memory pool used by the source variable
>>
*/
void XMem::Copy(void * tgt, void * src, int size, XMem * tgtMem, XMem * srcMem)
{
    if(srcMem == NULL || srcMem->devID < 0){
        if(tgtMem == NULL || tgtMem->devID < 0)  // host (CPU memory)  -> host (CPU memory)
            memcpy(tgt, src, size);
#ifdef USE_CUDA
        else                                     // device (GPU memory) -> host (CPU memory)
            cudaMemcpyFromSymbol(tgt, src, size);
#endif
    }
#ifdef USE_CUDA
    else{
        if(tgtMem == NULL || tgtMem->devID < 0)  // host (CPU memory)  -> device (GPU memory)
            cudaMemcpyToSymbol(tgt, src, size);
        else                                     // device (GPU memory) -> device (GPU memory)
            cudaMemcpy(tgt, src, size, cudaMemcpyDeviceToDevice);
    }
#endif
}

/* 
set a float-typed variable to the input value 
>> tgt - where we put the value
>> src - where the value is from
>> tgtMem - the memory pool used by the target variable
>> srcMem - the memory pool used by the source variable
*/
void XMem::CopyFloat(float * tgt, float * src, XMem * tgtMem, XMem * srcMem)
{
    XMem::Copy(tgt, src, sizeof(float), tgtMem, srcMem);
}

/* 
set a variable to 0 
>> tgt - where the variable is placed
>> size - data size
>> tgtMem - the memory pool used by the variable
*/
void XMem::SetZero(void * tgt, MTYPE size, XMem * tgtMem)
{
    if(tgtMem == 0 || tgtMem->devID < 0)
        memset(tgt, 0, (unsigned int)size);
#ifdef USE_CUDA
    else
        cudaMemset(tgt, 0, size);
#endif
}

/* record the pin point */
void XMem::SetPin()
{
    CheckNTErrors((finalBlockID == curBlockID), "Cannot set pin for the memory pool. Please used a larger size of the first block!");

    curBlockPin = curBlockID;
    curUsedPin = curBlock->used;
}

/* go back to the pin point */
void XMem::BackToPin()
{
    if(curBlockPin < 0)
        return;

    for(int i = curBlockPin + 1; i <= finalBlockID; i++){

        if(devID >= 0){
#ifdef USE_CUDA
            CheckNTErrors(cudaFree(blocks[i].mem) == cudaSuccess, "Cannot free the memory.");
#else
            ShowNTErrors("We need cuda code here!");
#endif
        }
        else
            delete[] (char*)blocks[i].mem;

        blocks[i].mem = NULL;
        blocks[i].used = 0;
        blocks[i].size = blocks[i].sizeDesired;
    }

    curBlockID = curBlockPin;
    curBlock = blocks + curBlockID;
    curBlock->used = curUsedPin;
    finalBlockID = curBlockID;
}

/* record the pin point for buffer */
void XMem::SetPinBuf()
{
    bufUsedPin = bufUsed;
}

/* go back to the pin point */
void XMem::BackToPinBuf()
{
    bufUsed = bufUsedPin;
}

/* transform a size into a number (in million) */
MTYPE XMem::GetMemSize(const char * size)
{
    char * s = new char[strlen(size) + 1];
    strcpy(s, size);

    ToLowercase(s);

    int len = (int)strlen(s);

    bool ok = false;
    float num = 0;

    if(s[len-2] == 'm' && s[len-1] == 'b'){
        s[len-2] = 0;
        num = (float)atof(s);
        ok = true;
    }
    if(s[len-2] == 'g' && s[len-1] == 'b'){
        s[len-2] = 0;
        num = (float)atof(s);
        num *= 1000.0F;
        ok = true;
    }

    delete[] s;

    if(ok)
        return (MTYPE)num;
    else
        return 0;
}

/* transform a size into a number (in Bytes) */
MTYPE XMem::GetMemSizeInBytes(const char * size)
{
    char * s = new char[strlen(size) + 1];
    strcpy(s, size);

    ToLowercase(s);

    int len = (int)strlen(s);

    bool ok = false;
    float num = 0;

    if(s[len-2] == 'm' && s[len-1] == 'b'){
        num = (float)GetMemSize(size) * 1000000;
        ok = true;
    }
    else if(s[len-2] == 'g' && s[len-1] == 'b'){
        num = (float)GetMemSize(size) * 1000000;
        ok = true;
    }
    else{
        num = (float)atof(s);
        ok = true;
    }

    delete[] s;

    if(ok)
        return (MTYPE)num;
    else
        return 0;
}

/* create a new cublas handle */
void XMem::CreateBLASHandle()
{
#ifdef USE_CUDA
    if(cublasHandle != NULL){
1462 1463
        CheckNTErrors(cublasDestroy(cublasHandle) == CUBLAS_STATUS_SUCCESS, 
                      "Cannot destroy the cublas handle.");
1464 1465
    }

1466 1467
    CheckNTErrors((enum curandStatus)cublasCreate(&cublasHandle) == CURAND_STATUS_SUCCESS, 
                  "Cannot create the cublas handle.");
1468 1469 1470
#endif
}

xiaotong committed
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
/* show profile of the memory pool */
void XMem::ShowMemUsage(FILE * file)
{
    MTYPE used = 0;
    MTYPE total = 0;

    for(int i = 0; i < blockNum; i++){
        if(blocks[i].mem != NULL){
            used  += blocks[i].used;
            total += blocks[i].size;
        }
    }

    fprintf(file, "mem:%.1fMB used:%.1fMB usage:%.3f\n", 
1485
           (DTYPE)total/MILLION, (DTYPE)used/MILLION, (DTYPE)used/total);
xiaotong committed
1486 1487
}

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
#ifdef USE_CUDA

/* get the handle of cublas */
cublasHandle_t * XMem::GetCublasHandle()
{
    return &cublasHandle;
}

#endif

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
/* constructor */
XMemManager::XMemManager()
{
    Initialize();
}

/* de-constructor */
XMemManager::~XMemManager()
{
}

/* get memory size */
MTYPE XMemManager::GetAvailableMemory()
{
    unsigned long freeMem = 0;
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
#if __APPLE__
    int mib[2] = {CTL_HW, HW_MEMSIZE};
    unsigned int namelen = sizeof(mib) / sizeof(mib[0]);
    unsigned long long size;
    size_t len = sizeof(size);
    if (sysctl(mib, namelen, &size, &len, NULL, 0) < 0){
        ShowNTErrors("Cannot get memory size on Mac!");
    }
    else{
        return size;
    }
#elif _WIN32
1525 1526 1527 1528 1529
    MEMORYSTATUSEX memoryStatus;
    memoryStatus.dwLength = sizeof(memoryStatus);
    if (GlobalMemoryStatusEx(&memoryStatus)){
        freeMem = memoryStatus.ullAvailPhys;
    }
1530 1531 1532 1533
#else
    long pages = sysconf(_SC_AVPHYS_PAGES);
    long page_size = sysconf(_SC_PAGE_SIZE);
    freeMem = pages * page_size;
1534 1535 1536 1537 1538 1539 1540 1541
#endif
    return (MTYPE)freeMem;
}

/* get GPU memory size */
MTYPE XMemManager::GetAvailableGPUMemory(int devID)
{
    size_t freeMem = 0;
1542
    
1543
#ifdef USE_CUDA
1544
    size_t totalMem = 0;
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
    cudaSetDevice(devID);
    if (cudaMemGetInfo(&freeMem, &totalMem) != cudaSuccess){
        XPRINT(0, stderr, "cannot get GPU memory information.");
        exit(1);
    }
#endif
    return (MTYPE)freeMem;
}

/* get buffer size */
void XMemManager::GetBufferSize(MTYPE freeMem, MTYPE * myBufSize)
{
    *myBufSize = 0;
    if (freeMem >= MILLION * 128){
        *myBufSize = MILLION * 32;
        if (freeMem >= MILLION * 256){
            *myBufSize = MILLION * 64;
            if (freeMem >= MILLION * 512){
                *myBufSize = MILLION * 128;
                if (freeMem >= MILLION * 1024) {
1565
                    *myBufSize = MILLION * 128;
1566
                    if (freeMem >= MILLION * 2048)
1567
                        *myBufSize = MILLION * 128;
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
                }
            }
        }
    }
} 

/* initialize it and set the global memory information */
void XMemManager::Initialize()
{
    srand((unsigned int)time(NULL));

    Free();
    
    /* CPUs (we actually do not care about how many CPUs are using) */
    nCPUMem = 1;

    /* GPUs */
    nGPUMem = 0;

#ifdef USE_CUDA
    if (cudaGetDeviceCount(&nGPUMem) != cudaSuccess) {
        XPRINT(0, stderr, "cannot get GPU information.");
        exit(1);
    }
#endif
1593

1594 1595 1596 1597 1598
}

/* free it */
void XMemManager::Free()
{
1599
    for (int i = 0; i < MAX_CPU_MEM_NUM; i++)
1600
        CPUMems[i].Free();
1601
    for (int i = 0; i < MAX_GPU_MEM_NUM; i++)
1602 1603 1604 1605 1606 1607 1608
        GPUMems[i].Free();
}

/* get global memory pool */
XMem * XMemManager::GetMem(const int devID)
{
    XMem * mem = NULL;
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
    if (devID < 0){
        if(!CPUMems[0].isInitialized){
            MTYPE freeMem = GetAvailableMemory();
            MTYPE myBufSize = 0;
            GetBufferSize(freeMem, &myBufSize);
            CPUMems[0].Initialize(-1, FREE_ON_THE_FLY, 
                                  MIN_BLOCK_SIZE_FOR_MEMPOOL, 
                                  MIN_BLOCK_NUM_FOR_MEMPOOL, 
                                  myBufSize);
        }
1619
        mem = CPUMems;
1620
    }
1621
    else{
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
        if (devID < nGPUMem){
            if(!GPUMems[devID].isInitialized){
                MTYPE freeMem = GetAvailableGPUMemory(devID);
                MTYPE myBufSize = 0;
                GetBufferSize(freeMem, &myBufSize);
                GPUMems[devID].Initialize(devID, FREE_ON_THE_FLY, 
                                          MIN_BLOCK_SIZE_FOR_MEMPOOL, 
                                          MIN_BLOCK_NUM_FOR_MEMPOOL, 
                                          myBufSize);
            }
1632
            mem = GPUMems + devID;
1633 1634
        }
        else{
1635
            XPRINT1(0, stderr, "Cannot get the memory (%d). Please check your device id!", devID);
1636
        }
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
    }
    
    return mem;
}

/* get global memory size */
int XMemManager::GetMemSize(const int devID, MTYPE * myBlockSize, int * myBlockNum, MTYPE * myBufSize)
{
    XMem * mem = GetMem(devID);
    int result = 0;
    if (mem != NULL){
        *myBlockSize = mem->maxBlockSize;
        *myBlockNum = mem->blockNum;
        *myBufSize = mem->bufSize;
        result = 1;
    }
    return result;
}

/* show memory information */
void XMemManager::ShowMemInfo()
{
    XPRINT(1, stderr, "Memory Information:\n");
    MTYPE myBlockSize, myBufSize;
    int myBlockNum;
    for(int i = 0; i < nCPUMem; i++){
        GetMemSize(-1, &myBlockSize, &myBlockNum, &myBufSize);
1664
        XPRINT3(1, stderr, " - id:-1 CPU, blockSize:%lld, blockNum:%d, bufSize:%lld\n", myBlockSize, myBlockNum, myBufSize);
1665 1666 1667 1668
    }

    for(int i = 0; i < nGPUMem; i++){
        GetMemSize(i, &myBlockSize, &myBlockNum, &myBufSize);
1669
        XPRINT4(1, stderr, " - id:%2d GPU, blockSize:%lld, blockNum:%d, bufSize:%lld\n", i, myBlockSize, myBlockNum, myBufSize);
1670 1671 1672
    }
}

1673
} /* end of the nts (NiuTrans.Tensor) namespace */