Пример #1
0
void NetworkManager::Run()
{
	int threadId;
	struct epoll_event events[100];
	int numOfEvent, n;

	g_networkThreadCountLock.Lock();
	threadId = g_networkThreadCount++;
	g_networkThreadCountLock.Unlock();

	for(;;)
	{
		numOfEvent = epoll_wait(m_epollFdList[threadId], m_epollEvent2DList[threadId], 100, 2000);

		//printf("NW thread %d\n", threadId);
		if(numOfEvent < 0){	
			// critical error
			fprintf(stderr, "[ERROR] epoll_wait() ERROR : %s\n", strerror(errno));
			exit(1);
		}

		if(numOfEvent == 0)
		{
			continue;
		}

		//printf("NT %d activated\n", TC);
		OnEvent(numOfEvent, threadId);
	}
	close(m_serverFd);
	for(int i=0; i<NETWORK_THREAD_NUM; i++)
		close(m_epollFdList[i]);
}
Пример #2
0
void func(int i)
{
	g_lock.lock();
	std::this_thread::sleep_for(std::chrono::milliseconds(10));
	std::cout << std::this_thread::get_id() << "add : " << i << std::endl;
	sum++;
	g_lock.unlock();
}
Пример #3
0
void SingletonReleaseHashTable()
{
	g_SpinLockHashTable.Lock();
	if (g_pObjHash)
	{
		delete g_pObjHash;
		g_pObjHash = 0;
	}
	g_SpinLockHashTable.Unlock();
}
Пример #4
0
void SingletonReleaseTextVector()
{
	g_SpinLockTextVec.Lock();
	if (g_pTextVec)
	{
		delete g_pTextVec;
		g_pTextVec = 0;
	}
	g_SpinLockTextVec.Unlock();
}
Пример #5
0
TextBufVecType * SingletonGetTextVector()
{
	if (!g_pTextVec)
	{
		g_SpinLockTextVec.Lock();
		if (!g_pTextVec)
			g_pTextVec = new TextBufVecType;
		g_SpinLockTextVec.Unlock();
	}
	return g_pTextVec;
}
Пример #6
0
HashType * SingletonGetHashTable()
{
	if (!g_pObjHash)
	{
		g_SpinLockHashTable.Lock();
		if (!g_pObjHash)
			g_pObjHash = new HashType;
		g_SpinLockHashTable.Unlock();
	}
	return g_pObjHash;
}
 /**
  * Return the number of bytes consumed by all free list blocks.
  *
  * This does not define the number of bytes available for actual usable allocation, and should not be used
  * by non-implementation code outside of unit tests or debugging.
  */
 vm_size_t debug_bytes_free () {
     vm_size_t bytes_free = 0;
     
     _lock.lock();
     control_block *first = _free_list;
     for (control_block *b = _free_list; b != NULL; b = b->_next) {
         bytes_free += b->_size;
         
         if (b->_next == first)
             break;
     }
     _lock.unlock();
     
     return bytes_free;
 }
Пример #8
0
    ThreadingManagerOMP(int req = -1)
    : start_counter(1),
      barrier_protocol(*static_cast<ThreadingManager*>(this))
    {
        assert(req == -1);

        // In the OpenMP backend, the ThreadManager is instantiated
        // in a serial section, so in contrast to the threaded backend
        // we do not know the number of threads here.
        // Instead we find out when we are called again in thread_main()
        startup_lock.lock();
        lock_workers_initialized.lock();

        Options::ThreadAffinity::init();
    }
Пример #9
0
	void ParsingProcInternal()
	{
		while(true)
		{
			WString currentParsingText;
			{
				SpinLock::Scope scope(parsingTextLock);
				currentParsingText=parsingText;
				parsingText=L"";
			}
			if(currentParsingText==L"")
			{
				isParsingRunning=false;
				break;
			}

			List<Ptr<ParsingError>> errors;
			Ptr<ParsingTreeObject> node=grammarParser->Parse(currentParsingText, L"ParserDecl", errors).Cast<ParsingTreeObject>();
			Ptr<ParserDecl> decl;
			if(node)
			{
				node->InitializeQueryCache();
				decl=new ParserDecl(node);
			}
			{
				SpinLock::Scope scope(parsingTreeLock);
				parsingTreeNode=node;
				parsingTreeDecl=decl;
				node=0;
			}
			RestartColorizer();
		}
		parsingRunningEvent.Leave();
	}
Пример #10
0
// See that timer_trylock_or_cancel acquires the lock when the holder releases it.
static bool trylock_or_cancel_get_lock() {
    BEGIN_TEST;

    // We need 2 or more CPUs for this test.
    if (get_num_cpus_online() < 2) {
        printf("skipping test trylock_or_cancel_get_lock, not enough online cpus\n");
        return true;
    }

    timer_args arg{};
    timer_t t = TIMER_INITIAL_VALUE(t);

    SpinLock lock;
    arg.lock = lock.GetInternal();
    arg.wait = 1;

    arch_disable_ints();

    uint timer_cpu = arch_curr_cpu_num();
    const Deadline deadline = Deadline::no_slack(current_time() + ZX_USEC(100));
    timer_set(&t, deadline, timer_trylock_cb, &arg);

    // The timer is set to run on timer_cpu, switch to a different CPU, acquire the spinlock then
    // signal the callback to proceed.
    thread_set_cpu_affinity(get_current_thread(), ~cpu_num_to_mask(timer_cpu));
    DEBUG_ASSERT(arch_curr_cpu_num() != timer_cpu);

    arch_enable_ints();

    {
        AutoSpinLock guard(&lock);

        while (!atomic_load(&arg.timer_fired)) {
        }

        // Callback should now be running. Tell it to stop waiting and start trylocking.
        atomic_store(&arg.wait, 0);
    }

    // See that timer_cancel returns false indicating that the timer ran.
    ASSERT_FALSE(timer_cancel(&t), "");

    // Note, we cannot assert the value of arg.result. We have both released the lock and canceled
    // the timer, but we don't know which of these events the timer observed first.

    END_TEST;
}
Пример #11
0
    void init_master() {
        Options::ThreadAffinity::pin_main_thread();
        num_cpus = decide_num_cpus();
        threads = new TaskExecutor<Options> *[num_cpus];
        task_queues = new TaskQueue*[num_cpus];

        threads[0] = new TaskExecutor<Options>(0, *this);
        task_queues[0] = &threads[0]->get_task_queue();

        startup_lock.unlock();

        while (start_counter != num_cpus)
            Atomic::rep_nop();

        if (!workers_start_paused())
            lock_workers_initialized.unlock();
    }
Пример #12
0
void Scheduler::sleepAndRelease ( SpinLock &lock )
{
  lockScheduling();
  currentThread->state_=Sleeping;
  lock.release();
  unlockScheduling();
  yield();
}
Пример #13
0
    TEST(ParallelUtils,SpinLock) {

        const int N = 1000000;

        SpinLock lock;

        volatile int c =0;

        #pragma omp parallel for num_threads(4)
        for(int i=0; i<N; i++) {
            lock.lock();
            c++;
            lock.unlock();
        }

        EXPECT_EQ(N, c);

    }
Пример #14
0
void duplicate_node::match(vector<duplicate_node*>& entrances,
                           search_duplicate_files_status* status,
                           SpinLock& lock)
{
    duplicate_node* iter = this;
    while (iter) {
        bool first_matched = true;
        duplicate_node* current_node = iter;
        duplicate_node* last_node = iter;
        euint current_symbol = iter->m_symbol;
        while (current_node) {
            {
                SpinLock::Instance inst = lock.Lock();
                if (status) {
                    status->m_current_status = search_duplicate_files_status::Matching;
                    status->m_processing_file = current_node->m_path.c_str();
                }
            }
            if (current_node->m_symbol == current_symbol && current_node != last_node) {
                last_node->m_next1 = current_node;
                if (first_matched) {
                    entrances.push_back(last_node);
                    first_matched = false;
                }
                last_node->m_is_matched = true;
                current_node->m_is_matched = true;
                last_node = current_node;
            }
            current_node = current_node->m_next0;
        }
        iter = iter->m_next0;
        while (iter && iter->m_is_matched) {
            iter = iter->m_next0;
        }
    }
    {
        SpinLock::Instance inst = lock.Lock();
        if (status) {
            status->m_current_status = search_duplicate_files_status::Idling;
            status->m_processing_file = nullptr;
        }
    }
}
Пример #15
0
    void init_worker(int id) {
        Options::ThreadAffinity::pin_workerthread(id);
        // allocate Worker on thread
        TaskExecutor<Options> *te = new TaskExecutor<Options>(id, *this);

        // wait until main thread has initialized the threadmanager
        startup_lock.lock();
        startup_lock.unlock();

        threads[id] = te;
        task_queues[id] = &te->get_task_queue();

        Atomic::increase(&start_counter);

        lock_workers_initialized.lock();
        lock_workers_initialized.unlock();

        te->work_loop();
    }
Пример #16
0
euint64 duplicate_node::prepare(duplicate_node_cache* cache,
                                search_duplicate_files_status* status,
                                SpinLock& lock)
{
    euint64 proced_size = 0;
    duplicate_node* iter = this;
    while (iter) {
        iter->m_next1 = nullptr;
        iter->m_symbol = 0;
        iter->m_is_matched = false;
        cache->open(iter);

        {
            SpinLock::Instance inst = lock.Lock();
            if (status) {
                status->m_current_status = search_duplicate_files_status::Reading;
                status->m_processing_file = iter->m_path.c_str();
            }
        }

        ///fseek(iter->m_file.get(), iter->m_offset, SEEK_SET);
        iter->m_file.Seek(iter->m_offset);
        ///fread(&iter->m_symbol, 1, sizeof(SYMBOL), iter->m_file.get());
        iter->m_file.Read(&iter->m_symbol, sizeof(SYMBOL));

        proced_size += sizeof(SYMBOL);
        m_remainder -= sizeof(SYMBOL);
        iter->m_offset += sizeof(SYMBOL);
        iter = iter->m_next0;
    }
    {
        {
            SpinLock::Instance inst = lock.Lock();
            if (status) {
                status->m_current_status = search_duplicate_files_status::Idling;
                status->m_processing_file = nullptr;
            }
        }
    }
    return proced_size;
}
Пример #17
0
void xhn::thread::assign_to_local_thread(thread_ptr& local_thread, thread_ptr& global_thread, SpinLock& lock)
{
    {
        xhn::SpinLock::Instance inst = lock.Lock();
        local_thread = global_thread;
    }
    if (!local_thread) {

        local_thread = VNEW xhn::thread;
        while (!local_thread->is_running()) {}

        {
            xhn::SpinLock::Instance inst = lock.Lock();
            if (!global_thread) {
                global_thread = local_thread;
            }
            else {
                local_thread = global_thread;
            }
        }
    }
}
Пример #18
0
		Font Font::getDefault()
		{
			static Font font;
			static SpinLock lock;

			lock.lock();

			if (font.getHandle() == nullptr)
			{
				jni::Class Button("libnative/ui/TextComponent");
				jni::method_t viewConstructor = Button.getConstructor("(Landroid/content/Context;)V");
				jni::Object button = Button.newInstance(viewConstructor, (jni::Object*) App::getAppHandle());

				// Android already scales its default fonts.
				font._size = button.call<float>("getScaledTextSize");
				font._shared->handle = new jni::Object(button.call<jni::Object>("getTypeface()Landroid/graphics/Typeface;"));
			}

			lock.release();

			return font;
		}
Пример #19
0
    void stop() {
        if (get_thread_num() != 0) {
            
            // workers don't come here until terminate() has been called

            int nv = Atomic::decrease_nv(&start_counter);

            // wait until all workers reached this step
            // all threads must agree that we are shutting
            // down before we can continue and invoke the
            // destructor
            startup_lock.lock();
            startup_lock.unlock();
            return;
        }

        start_executing(); // make sure threads have been started, or we will wait forever in barrier
        barrier_protocol.barrier(*threads[0]);

        startup_lock.lock();

        for (int i = 1; i < get_num_cpus(); ++i)
            threads[i]->terminate();


        // wait for all threads to join
        while (start_counter != 1)
            Atomic::rep_nop();

        // signal that threads can destruct
        startup_lock.unlock();

        for (int i = 1; i < get_num_cpus(); ++i)
            delete threads[i];

        delete [] threads;
        delete [] task_queues;
    }
Пример #20
0
	void SubmitCurrentText(const wchar_t* text)
	{
		{
			// copy the text because this is a cross thread accessible data
			SpinLock::Scope scope(parsingTextLock);
			parsingText=text;
		}
		if(!isParsingRunning)
		{
			isParsingRunning=true;
			parsingRunningEvent.Enter();
			ThreadPoolLite::Queue(&ParsingProc, this);
		}
	}
Пример #21
0
	SpinGuard(SpinLock& mutex) : _mutex(&mutex){
		_mutex->lock();
	}
Пример #22
0
	~SpinGuard(){
		_mutex->unlock();
	}
Пример #23
0
void func(int n)
{
    g_Lock.lock();
    std::cout << "Output from thread: " << n << std::endl;
    g_Lock.unlock();
}
Пример #24
0
	~GrammarColorizer()
	{
		finalizing=true;
		parsingRunningEvent.Enter();
		parsingRunningEvent.Leave();
	}
Пример #25
0
 void start_executing() {
     if (workers_start_paused()) {
         if (lock_workers_initialized.is_locked())
             lock_workers_initialized.unlock();
     }
 }
 void addToCommittedByteCount(long byteCount)
 {
     ASSERT(spinlock.IsHeld());
     ASSERT(static_cast<long>(committedBytesCount) + byteCount > -1);
     committedBytesCount += byteCount;
 }
namespace JSC {
    
static size_t committedBytesCount = 0;  
static SpinLock spinlock = SPINLOCK_INITIALIZER;

// FreeListEntry describes a free chunk of memory, stored in the freeList.
struct FreeListEntry {
    FreeListEntry(void* pointer, size_t size)
        : pointer(pointer)
        , size(size)
        , nextEntry(0)
        , less(0)
        , greater(0)
        , balanceFactor(0)
    {
    }

    // All entries of the same size share a single entry
    // in the AVLTree, and are linked together in a linked
    // list, using nextEntry.
    void* pointer;
    size_t size;
    FreeListEntry* nextEntry;

    // These fields are used by AVLTree.
    FreeListEntry* less;
    FreeListEntry* greater;
    int balanceFactor;
};

// Abstractor class for use in AVLTree.
// Nodes in the AVLTree are of type FreeListEntry, keyed on
// (and thus sorted by) their size.
struct AVLTreeAbstractorForFreeList {
    typedef FreeListEntry* handle;
    typedef int32_t size;
    typedef size_t key;

    handle get_less(handle h) { return h->less; }
    void set_less(handle h, handle lh) { h->less = lh; }
    handle get_greater(handle h) { return h->greater; }
    void set_greater(handle h, handle gh) { h->greater = gh; }
    int get_balance_factor(handle h) { return h->balanceFactor; }
    void set_balance_factor(handle h, int bf) { h->balanceFactor = bf; }

    static handle null() { return 0; }

    int compare_key_key(key va, key vb) { return va - vb; }
    int compare_key_node(key k, handle h) { return compare_key_key(k, h->size); }
    int compare_node_node(handle h1, handle h2) { return compare_key_key(h1->size, h2->size); }
};

// Used to reverse sort an array of FreeListEntry pointers.
static int reverseSortFreeListEntriesByPointer(const void* leftPtr, const void* rightPtr)
{
    FreeListEntry* left = *(FreeListEntry**)leftPtr;
    FreeListEntry* right = *(FreeListEntry**)rightPtr;

    return (intptr_t)(right->pointer) - (intptr_t)(left->pointer);
}

// Used to reverse sort an array of pointers.
static int reverseSortCommonSizedAllocations(const void* leftPtr, const void* rightPtr)
{
    void* left = *(void**)leftPtr;
    void* right = *(void**)rightPtr;

    return (intptr_t)right - (intptr_t)left;
}

class FixedVMPoolAllocator
{
    // The free list is stored in a sorted tree.
    typedef AVLTree<AVLTreeAbstractorForFreeList, 40> SizeSortedFreeTree;

    void release(void* position, size_t size)
    {
        m_allocation.decommit(position, size);
        addToCommittedByteCount(-static_cast<long>(size));
    }

    void reuse(void* position, size_t size)
    {
        bool okay = m_allocation.commit(position, size);
        ASSERT_UNUSED(okay, okay);
        addToCommittedByteCount(static_cast<long>(size));
    }

    // All addition to the free list should go through this method, rather than
    // calling insert directly, to avoid multiple entries being added with the
    // same key.  All nodes being added should be singletons, they should not
    // already be a part of a chain.
    void addToFreeList(FreeListEntry* entry)
    {
        ASSERT(!entry->nextEntry);

        if (entry->size == m_commonSize) {
            m_commonSizedAllocations.append(entry->pointer);
            delete entry;
        } else if (FreeListEntry* entryInFreeList = m_freeList.search(entry->size, m_freeList.EQUAL)) {
            // m_freeList already contain an entry for this size - insert this node into the chain.
            entry->nextEntry = entryInFreeList->nextEntry;
            entryInFreeList->nextEntry = entry;
        } else
            m_freeList.insert(entry);
    }

    // We do not attempt to coalesce addition, which may lead to fragmentation;
    // instead we periodically perform a sweep to try to coalesce neighboring
    // entries in m_freeList.  Presently this is triggered at the point 16MB
    // of memory has been released.
    void coalesceFreeSpace()
    {
        Vector<FreeListEntry*> freeListEntries;
        SizeSortedFreeTree::Iterator iter;
        iter.start_iter_least(m_freeList);

        // Empty m_freeList into a Vector.
        for (FreeListEntry* entry; (entry = *iter); ++iter) {
            // Each entry in m_freeList might correspond to multiple
            // free chunks of memory (of the same size).  Walk the chain
            // (this is likely of course only be one entry long!) adding
            // each entry to the Vector (at reseting the next in chain
            // pointer to separate each node out).
            FreeListEntry* next;
            do {
                next = entry->nextEntry;
                entry->nextEntry = 0;
                freeListEntries.append(entry);
            } while ((entry = next));
        }
        // All entries are now in the Vector; purge the tree.
        m_freeList.purge();

        // Reverse-sort the freeListEntries and m_commonSizedAllocations Vectors.
        // We reverse-sort so that we can logically work forwards through memory,
        // whilst popping items off the end of the Vectors using last() and removeLast().
        qsort(freeListEntries.begin(), freeListEntries.size(), sizeof(FreeListEntry*), reverseSortFreeListEntriesByPointer);
        qsort(m_commonSizedAllocations.begin(), m_commonSizedAllocations.size(), sizeof(void*), reverseSortCommonSizedAllocations);

        // The entries from m_commonSizedAllocations that cannot be
        // coalesced into larger chunks will be temporarily stored here.
        Vector<void*> newCommonSizedAllocations;

        // Keep processing so long as entries remain in either of the vectors.
        while (freeListEntries.size() || m_commonSizedAllocations.size()) {
            // We're going to try to find a FreeListEntry node that we can coalesce onto.
            FreeListEntry* coalescionEntry = 0;

            // Is the lowest addressed chunk of free memory of common-size, or is it in the free list?
            if (m_commonSizedAllocations.size() && (!freeListEntries.size() || (m_commonSizedAllocations.last() < freeListEntries.last()->pointer))) {
                // Pop an item from the m_commonSizedAllocations vector - this is the lowest
                // addressed free chunk.  Find out the begin and end addresses of the memory chunk.
                void* begin = m_commonSizedAllocations.last();
                void* end = (void*)((intptr_t)begin + m_commonSize);
                m_commonSizedAllocations.removeLast();

                // Try to find another free chunk abutting onto the end of the one we have already found.
                if (freeListEntries.size() && (freeListEntries.last()->pointer == end)) {
                    // There is an existing FreeListEntry for the next chunk of memory!
                    // we can reuse this.  Pop it off the end of m_freeList.
                    coalescionEntry = freeListEntries.last();
                    freeListEntries.removeLast();
                    // Update the existing node to include the common-sized chunk that we also found. 
                    coalescionEntry->pointer = (void*)((intptr_t)coalescionEntry->pointer - m_commonSize);
                    coalescionEntry->size += m_commonSize;
                } else if (m_commonSizedAllocations.size() && (m_commonSizedAllocations.last() == end)) {
                    // There is a second common-sized chunk that can be coalesced.
                    // Allocate a new node.
                    m_commonSizedAllocations.removeLast();
                    coalescionEntry = new FreeListEntry(begin, 2 * m_commonSize);
                } else {
                    // Nope - this poor little guy is all on his own. :-(
                    // Add him into the newCommonSizedAllocations vector for now, we're
                    // going to end up adding him back into the m_commonSizedAllocations
                    // list when we're done.
                    newCommonSizedAllocations.append(begin);
                    continue;
                }
            } else {
                ASSERT(freeListEntries.size());
                ASSERT(!m_commonSizedAllocations.size() || (freeListEntries.last()->pointer < m_commonSizedAllocations.last()));
                // The lowest addressed item is from m_freeList; pop it from the Vector.
                coalescionEntry = freeListEntries.last();
                freeListEntries.removeLast();
            }
            
            // Right, we have a FreeListEntry, we just need check if there is anything else
            // to coalesce onto the end.
            ASSERT(coalescionEntry);
            while (true) {
                // Calculate the end address of the chunk we have found so far.
                void* end = (void*)((intptr_t)coalescionEntry->pointer - coalescionEntry->size);

                // Is there another chunk adjacent to the one we already have?
                if (freeListEntries.size() && (freeListEntries.last()->pointer == end)) {
                    // Yes - another FreeListEntry -pop it from the list.
                    FreeListEntry* coalescee = freeListEntries.last();
                    freeListEntries.removeLast();
                    // Add it's size onto our existing node.
                    coalescionEntry->size += coalescee->size;
                    delete coalescee;
                } else if (m_commonSizedAllocations.size() && (m_commonSizedAllocations.last() == end)) {
                    // We can coalesce the next common-sized chunk.
                    m_commonSizedAllocations.removeLast();
                    coalescionEntry->size += m_commonSize;
                } else
                    break; // Nope, nothing to be added - stop here.
            }

            // We've coalesced everything we can onto the current chunk.
            // Add it back into m_freeList.
            addToFreeList(coalescionEntry);
        }

        // All chunks of free memory larger than m_commonSize should be
        // back in m_freeList by now.  All that remains to be done is to
        // copy the contents on the newCommonSizedAllocations back into
        // the m_commonSizedAllocations Vector.
        ASSERT(m_commonSizedAllocations.size() == 0);
        m_commonSizedAllocations.append(newCommonSizedAllocations);
    }

public:

    FixedVMPoolAllocator(size_t commonSize, size_t totalHeapSize)
        : m_commonSize(commonSize)
        , m_countFreedSinceLastCoalesce(0)
    {
        // Cook up an address to allocate at, using the following recipe:
        //   17 bits of zero, stay in userspace kids.
        //   26 bits of randomness for ASLR.
        //   21 bits of zero, at least stay aligned within one level of the pagetables.
        //
        // But! - as a temporary workaround for some plugin problems (rdar://problem/6812854),
        // for now instead of 2^26 bits of ASLR lets stick with 25 bits of randomization plus
        // 2^24, which should put up somewhere in the middle of userspace (in the address range
        // 0x200000000000 .. 0x5fffffffffff).
#if VM_POOL_ASLR
        intptr_t randomLocation = 0;
        randomLocation = arc4random() & ((1 << 25) - 1);
        randomLocation += (1 << 24);
        randomLocation <<= 21;
        m_allocation = PageReservation::reserveAt(reinterpret_cast<void*>(randomLocation), false, totalHeapSize, PageAllocation::JSJITCodePages, EXECUTABLE_POOL_WRITABLE, true);
#else
        m_allocation = PageReservation::reserve(totalHeapSize, PageAllocation::JSJITCodePages, EXECUTABLE_POOL_WRITABLE, true);
#endif

        if (!!m_allocation)
            m_freeList.insert(new FreeListEntry(m_allocation.base(), m_allocation.size()));
#if !ENABLE(INTERPRETER)
        else
            CRASH();
#endif
    }

    ExecutablePool::Allocation alloc(size_t size)
    {
        return ExecutablePool::Allocation(allocInternal(size), size);
    }

    void free(ExecutablePool::Allocation allocation)
    {
        void* pointer = allocation.base();
        size_t size = allocation.size();

        ASSERT(!!m_allocation);
        // Call release to report to the operating system that this
        // memory is no longer in use, and need not be paged out.
        ASSERT(isWithinVMPool(pointer, size));
        release(pointer, size);

        // Common-sized allocations are stored in the m_commonSizedAllocations
        // vector; all other freed chunks are added to m_freeList.
        if (size == m_commonSize)
            m_commonSizedAllocations.append(pointer);
        else
            addToFreeList(new FreeListEntry(pointer, size));

        // Do some housekeeping.  Every time we reach a point that
        // 16MB of allocations have been freed, sweep m_freeList
        // coalescing any neighboring fragments.
        m_countFreedSinceLastCoalesce += size;
        if (m_countFreedSinceLastCoalesce >= COALESCE_LIMIT) {
            m_countFreedSinceLastCoalesce = 0;
            coalesceFreeSpace();
        }
    }

    bool isValid() const { return !!m_allocation; }

private:
    void* allocInternal(size_t size)
    {
#if ENABLE(INTERPRETER)
        if (!m_allocation)
            return 0;
#else
        ASSERT(!!m_allocation);
#endif
        void* result;

        // Freed allocations of the common size are not stored back into the main
        // m_freeList, but are instead stored in a separate vector.  If the request
        // is for a common sized allocation, check this list.
        if ((size == m_commonSize) && m_commonSizedAllocations.size()) {
            result = m_commonSizedAllocations.last();
            m_commonSizedAllocations.removeLast();
        } else {
            // Search m_freeList for a suitable sized chunk to allocate memory from.
            FreeListEntry* entry = m_freeList.search(size, m_freeList.GREATER_EQUAL);

            // This would be bad news.
            if (!entry) {
                // Errk!  Lets take a last-ditch desperation attempt at defragmentation...
                coalesceFreeSpace();
                // Did that free up a large enough chunk?
                entry = m_freeList.search(size, m_freeList.GREATER_EQUAL);
                // No?...  *BOOM!*
                if (!entry)
                    CRASH();
            }
            ASSERT(entry->size != m_commonSize);

            // Remove the entry from m_freeList.  But! -
            // Each entry in the tree may represent a chain of multiple chunks of the
            // same size, and we only want to remove one on them.  So, if this entry
            // does have a chain, just remove the first-but-one item from the chain.
            if (FreeListEntry* next = entry->nextEntry) {
                // We're going to leave 'entry' in the tree; remove 'next' from its chain.
                entry->nextEntry = next->nextEntry;
                next->nextEntry = 0;
                entry = next;
            } else
                m_freeList.remove(entry->size);

            // Whoo!, we have a result!
            ASSERT(entry->size >= size);
            result = entry->pointer;

            // If the allocation exactly fits the chunk we found in the,
            // m_freeList then the FreeListEntry node is no longer needed.
            if (entry->size == size)
                delete entry;
            else {
                // There is memory left over, and it is not of the common size.
                // We can reuse the existing FreeListEntry node to add this back
                // into m_freeList.
                entry->pointer = (void*)((intptr_t)entry->pointer + size);
                entry->size -= size;
                addToFreeList(entry);
            }
        }

        // Call reuse to report to the operating system that this memory is in use.
        ASSERT(isWithinVMPool(result, size));
        reuse(result, size);
        return result;
    }

#ifndef NDEBUG
    bool isWithinVMPool(void* pointer, size_t size)
    {
        return pointer >= m_allocation.base() && (reinterpret_cast<char*>(pointer) + size <= reinterpret_cast<char*>(m_allocation.base()) + m_allocation.size());
    }
#endif

    void addToCommittedByteCount(long byteCount)
    {
        ASSERT(spinlock.IsHeld());
        ASSERT(static_cast<long>(committedBytesCount) + byteCount > -1);
        committedBytesCount += byteCount;
    }

    // Freed space from the most common sized allocations will be held in this list, ...
    const size_t m_commonSize;
    Vector<void*> m_commonSizedAllocations;

    // ... and all other freed allocations are held in m_freeList.
    SizeSortedFreeTree m_freeList;

    // This is used for housekeeping, to trigger defragmentation of the freed lists.
    size_t m_countFreedSinceLastCoalesce;

    PageReservation m_allocation;
};

size_t ExecutableAllocator::committedByteCount()
{
    SpinLockHolder lockHolder(&spinlock);
    return committedBytesCount;
}   

void ExecutableAllocator::intializePageSize()
{
    ExecutableAllocator::pageSize = getpagesize();
}

static FixedVMPoolAllocator* allocator = 0;
    
bool ExecutableAllocator::isValid() const
{
    SpinLockHolder lock_holder(&spinlock);
    if (!allocator)
        allocator = new FixedVMPoolAllocator(JIT_ALLOCATOR_LARGE_ALLOC_SIZE, VM_POOL_SIZE);
    return allocator->isValid();
}

ExecutablePool::Allocation ExecutablePool::systemAlloc(size_t size)
{
    SpinLockHolder lock_holder(&spinlock);
    ASSERT(allocator);
    return allocator->alloc(size);
}

void ExecutablePool::systemRelease(ExecutablePool::Allocation& allocation) 
{
    SpinLockHolder lock_holder(&spinlock);
    ASSERT(allocator);
    allocator->free(allocation);
}

}