//
// Copyright (c) 2011 by István Váradi
//
// This file is part of liblwt, a Lightweight (Cooperative) Threading library

// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

//------------------------------------------------------------------------------

#include "StackManager.h"

#include <cstdlib>
#include <cstdio>

#include <sys/mman.h>

//------------------------------------------------------------------------------

using lwt::StackManager;

using std::set;

//------------------------------------------------------------------------------

StackManager* StackManager::instance = 0;

//------------------------------------------------------------------------------

StackManager::~StackManager()
{
    size_t stackPoolSize = (stackSize + PAGE_SIZE) * stacksPerPool;
    for(set<unsigned char*>::iterator i = pools.begin(); i!=pools.end(); ++i) {
        munmap(*i, stackPoolSize);
    }

    assert(instance==this);
    instance = 0;
}
    
//------------------------------------------------------------------------------

void StackManager::allocatePool()
{
    size_t stackPoolSize = (stackSize + PAGE_SIZE) * stacksPerPool;

    unsigned char* pool = 
        reinterpret_cast<unsigned char*>(mmap(0, stackPoolSize, 
                                              PROT_READ|PROT_WRITE,
                                              MAP_PRIVATE|MAP_ANONYMOUS, 
                                              -1, 0));
    if (pool==MAP_FAILED) {
        abort();
    }

    pools.insert(pool);

    for(size_t i = 0; i<stacksPerPool; ++i, pool += stackSize + PAGE_SIZE) {
        if (mprotect(pool, PAGE_SIZE, PROT_NONE)<0) {
            abort();
        }
        unsigned char* stackTop = pool + stackSize + PAGE_SIZE - sizeof(void*);
        *reinterpret_cast<unsigned char**>(stackTop) = firstFreeStack;
        firstFreeStack = stackTop;
    }
}

//------------------------------------------------------------------------------
