/*---------------------------------------------------------------------------* Project: Horizon File: os_ThreadLocalStorage.cpp Copyright (C)2009 Nintendo Co., Ltd. All rights reserved. These coded instructions, statements, and computer programs contain proprietary information of Nintendo of America Inc. and/or Nintendo Company Ltd., and are protected by Federal copyright law. They may not be disclosed to third parties or copied or duplicated in any form, in whole or in part, without the prior written consent of Nintendo. $Rev: 38846 $ *---------------------------------------------------------------------------*/ #include #include #include #include #include #include //--------------------------------------------------------------------------- using namespace nn; using nn::Result; namespace nn{ namespace os{ #if defined(NN_PROCESSOR_ARM_V6) NN_STATIC_ASSERT(TLS_NUM == 16); typedef ThreadLocalRegion ThreadLocalBuffer; inline ThreadLocalBuffer* GetThreadLocalBuffer() { return GetThreadLocalRegion(); } #elif defined(NN_PROCESSOR_ARM_V5) struct ThreadLocalBuffer { uptr tls[TLS_NUM]; }; ThreadLocalBuffer s_ThreadLocalBuffers[nn::os::CTR::ARM946ES::NUM_THREAD_INDEX]; inline ThreadLocalBuffer* GetThreadLocalBuffer() { return s_ThreadLocalBuffers + nn::os::CTR::ARM946ES::GetThreadIndex(); } #endif namespace { u16 sTLSMap = 0; // Manage TLS allocation state with bits 0 - 15 /* Please see man pages for details */ inline bool IsMappedIndex(s32 index) { return ((sTLSMap >> index) & 1) == 1; } /* Please see man pages for details */ s32 SearchFreeTLSIndex() { for(int i = 0; i < TLS_NUM; ++i) { if(!IsMappedIndex(i)) { return i; } } return -1; } /* Please see man pages for details */ s32 AllocateTLSIndex() { s32 index = SearchFreeTLSIndex(); if(index >= 0 && index < TLS_NUM) { sTLSMap |= (1 << index); } return index; } /* Please see man pages for details */ s32 FreeTLSIndex(int index) { if(!IsMappedIndex(index)) { return -1; } return sTLSMap &= ~(1 << index); } } // Namespace ThreadLocalStorage::ThreadLocalStorage() { this->m_Index = AllocateTLSIndex(); NN_TASSERTMSG_(m_Index >= 0, "Out of Thread Local Storage Slot."); if ( m_Index < 0 ) { NN_OS_ERROR_IF_FAILED(ResultExceedTlsLimit()); } } ThreadLocalStorage::~ThreadLocalStorage() { NN_TASSERT_(m_Index >= 0 && m_Index < TLS_NUM); NN_TASSERT_(IsMappedIndex(m_Index)); FreeTLSIndex(m_Index); } uptr ThreadLocalStorage::GetValue() const { NN_TASSERT_(m_Index >= 0 && m_Index < TLS_NUM); NN_TASSERT_(IsMappedIndex(m_Index)); if ( IsMappedIndex(m_Index) ) { return GetThreadLocalBuffer()->tls[m_Index]; } else { return 0; } } void ThreadLocalStorage::SetValue(uptr value) { NN_TASSERT_(m_Index >= 0 && m_Index < TLS_NUM); NN_TASSERT_(IsMappedIndex(m_Index)); if ( IsMappedIndex(m_Index) ) { GetThreadLocalBuffer()->tls[m_Index] = value; } } void ThreadLocalStorage::ClearAllSlots() { ThreadLocalBuffer& tlr = *GetThreadLocalBuffer(); for( int i = 0; i < TLS_NUM; ++i ) { tlr.tls[i] = 0; } } }} // namespace nn::os