eathread_kettle.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Copyright (c) Electronic Arts Inc. All rights reserved.
  3. ///////////////////////////////////////////////////////////////////////////////
  4. #include <EABase/eabase.h>
  5. #include <eathread/eathread.h>
  6. #include <eathread/eathread_thread.h>
  7. #include <eathread/eathread_atomic.h>
  8. #include <eathread/eathread_storage.h>
  9. #include <sched.h>
  10. #include <unistd.h>
  11. #if defined(EA_HAVE_DINKUMWARE_CPP_LIBRARY)
  12. #include <time.h>
  13. #else
  14. #include <sys/time.h>
  15. #endif
  16. #include <kernel.h>
  17. #include <sceerror.h>
  18. #include <sdk_version.h>
  19. #include <cpuid.h>
  20. #include <new>
  21. #include <string.h>
  22. namespace EA
  23. {
  24. namespace Thread
  25. {
  26. // Assertion variables.
  27. EA::Thread::AssertionFailureFunction gpAssertionFailureFunction = NULL;
  28. void* gpAssertionFailureContext = NULL;
  29. }
  30. }
  31. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  32. // Variables required for ThreadSleep
  33. //
  34. // TLS var for quicker lookups to our thread's data so we may grab the thread local EAThreadTimerQueue
  35. static EA_THREAD_LOCAL EAThreadDynamicData* tpThreadDynamicData = nullptr;
  36. // In the event a non-EAThread requires a timer queue we may supply the global instance
  37. static EAThreadTimerQueue gThreadTimerQueue;
  38. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  39. EA::Thread::ThreadId EA::Thread::GetThreadId()
  40. {
  41. // https://ps4.scedev.net/forums/thread/12697/
  42. // https://ps4.scedev.net/forums/thread/53323/
  43. //
  44. // ScePthread scePthreadSelf() does not return a integral thread id value. Instead it returns a ScePthread structure
  45. // with is actually a pointer to a pthread structure (eg. pthread*). On other Sony platforms, an API like
  46. // scePthreadGetthreadid was available for this use case but this isn't the case on the PS4. The above scedev.net
  47. // threads indicate that the request for an additiona API to retrieve the kernel threadid has been submitted to
  48. // Sony. Until this feature is shipped in a future SDK update we use the following technique to get a scalar thread
  49. // id value that matches the threadid presented in the PS4 debugger.
  50. const EA::Thread::ThreadId currentThreadId = *reinterpret_cast<EA::Thread::ThreadId*>(scePthreadSelf());
  51. return currentThreadId;
  52. }
  53. EA::Thread::ThreadId EA::Thread::GetThreadId(EA::Thread::SysThreadId id)
  54. {
  55. EAThreadDynamicData* const pTDD = EA::Thread::FindThreadDynamicData(id);
  56. if(pTDD)
  57. {
  58. return pTDD->mThreadId;
  59. }
  60. return EA::Thread::kThreadIdInvalid;
  61. }
  62. int EA::Thread::GetThreadPriority()
  63. {
  64. int policy;
  65. sched_param param;
  66. SysThreadId currentThreadId = scePthreadSelf();
  67. int result = scePthreadGetschedparam(currentThreadId, &policy, &param);
  68. if(result == SCE_OK)
  69. {
  70. // Kettle pthreads uses a reversed interpretation of sched_get_priority_min and sched_get_priority_max.
  71. return -1 * (param.sched_priority - SCE_KERNEL_PRIO_FIFO_DEFAULT);
  72. }
  73. return kThreadPriorityDefault;
  74. }
  75. bool EA::Thread::SetThreadPriority(int nPriority)
  76. {
  77. SysThreadId currentThreadId = scePthreadSelf();
  78. int policy;
  79. SceKernelSchedParam param;
  80. int result = -1;
  81. EAT_ASSERT(nPriority != kThreadPriorityUnknown);
  82. result = scePthreadGetschedparam(currentThreadId, &policy, &param);
  83. if(result == SCE_OK)
  84. {
  85. // Kettle pthreads uses a reversed interpretation of sched_get_priority_min and sched_get_priority_max.
  86. const int nMin = SCE_KERNEL_PRIO_FIFO_HIGHEST;
  87. const int nMax = SCE_KERNEL_PRIO_FIFO_LOWEST;
  88. param.sched_priority = (SCE_KERNEL_PRIO_FIFO_DEFAULT + (-1 * nPriority));
  89. // Clamp to min/max as appropriate for current scheduling policy
  90. if(param.sched_priority < nMin)
  91. param.sched_priority = nMin;
  92. else if(param.sched_priority > nMax)
  93. param.sched_priority = nMax;
  94. result = scePthreadSetprio(currentThreadId, param.sched_priority);
  95. }
  96. return (result == SCE_OK);
  97. }
  98. void* EA::Thread::GetThreadStackBase()
  99. {
  100. void* pStackAddr = NULL;
  101. int result;
  102. ScePthreadAttr attr;
  103. result = scePthreadAttrInit(&attr);
  104. EAT_ASSERT(SCE_OK == result);
  105. result = scePthreadAttrGet(scePthreadSelf(), &attr);
  106. EAT_ASSERT(SCE_OK == result);
  107. result = scePthreadAttrGetstackaddr(&attr, &pStackAddr);
  108. EAT_ASSERT(SCE_OK == result);
  109. result = scePthreadAttrDestroy(&attr);
  110. EAT_ASSERT(SCE_OK == result);
  111. EA_UNUSED(result);
  112. return pStackAddr;
  113. }
  114. namespace
  115. {
  116. SceKernelCpumask GetSceKernelAllCpuMask()
  117. {
  118. #if (SCE_ORBIS_SDK_VERSION >= 0x03000000u)
  119. return (EA::Thread::GetProcessorCount() == 6) ? SCE_KERNEL_CPUMASK_6CPU_ALL : SCE_KERNEL_CPUMASK_7CPU_ALL;
  120. #else
  121. nAffinityMask &= 0x3f;
  122. #endif
  123. }
  124. }
  125. void EA::Thread::SetThreadProcessor(int nProcessor)
  126. {
  127. SceKernelCpumask mask = GetSceKernelAllCpuMask();
  128. if (nProcessor >= 0)
  129. mask = (SceKernelCpumask)(1 << nProcessor);
  130. int result = scePthreadSetaffinity(scePthreadSelf(), mask);
  131. EA_UNUSED(result);
  132. EAT_ASSERT(SCE_OK == result);
  133. }
  134. int EA::Thread::GetThreadProcessor()
  135. {
  136. return sceKernelGetCurrentCpu();
  137. }
  138. EATHREADLIB_API void EA::Thread::SetThreadAffinityMask(const EA::Thread::ThreadId& id, ThreadAffinityMask nAffinityMask)
  139. {
  140. // Update the affinity mask in the thread dynamic data cache.
  141. EAThreadDynamicData* const pTDD = FindThreadDynamicData(id);
  142. if(pTDD)
  143. {
  144. pTDD->mnThreadAffinityMask = nAffinityMask;
  145. }
  146. #if EATHREAD_THREAD_AFFINITY_MASK_SUPPORTED
  147. nAffinityMask &= GetSceKernelAllCpuMask();
  148. int res = scePthreadSetaffinity(GetSysThreadId(id), static_cast<SceKernelCpumask>(nAffinityMask));
  149. EAT_ASSERT(SCE_OK == res);
  150. EA_UNUSED(res);
  151. #endif
  152. }
  153. EATHREADLIB_API EA::Thread::ThreadAffinityMask EA::Thread::GetThreadAffinityMask(const EA::Thread::ThreadId& id)
  154. {
  155. // Update the affinity mask in the thread dynamic data cache.
  156. EAThreadDynamicData* const pTDD = FindThreadDynamicData(id);
  157. if(pTDD)
  158. {
  159. return pTDD->mnThreadAffinityMask;
  160. }
  161. return kThreadAffinityMaskAny;
  162. }
  163. namespace Internal
  164. {
  165. void SetThreadName(EAThreadDynamicData* pTDD)
  166. {
  167. if(pTDD)
  168. {
  169. EAT_COMPILETIME_ASSERT(EATHREAD_NAME_SIZE == 32); // New name (up to 32 bytes including the NULL terminator), or NULL due to Sony OS constraint
  170. char buf[EATHREAD_NAME_SIZE];
  171. snprintf(buf, sizeof(buf), "%s", pTDD->mName);
  172. buf[EATHREAD_NAME_SIZE - 1] = 0;
  173. auto sceResult = scePthreadRename(pTDD->mSysThreadId, buf);
  174. EA_UNUSED(sceResult);
  175. EAT_ASSERT(SCE_OK == sceResult);
  176. }
  177. }
  178. };
  179. EATHREADLIB_API void EA::Thread::SetThreadName(const char* pName) { SetThreadName(GetThreadId(), pName); }
  180. EATHREADLIB_API const char* EA::Thread::GetThreadName() { return GetThreadName(GetThreadId()); }
  181. EATHREADLIB_API void EA::Thread::SetThreadName(const EA::Thread::ThreadId& id, const char* pName)
  182. {
  183. EAThreadDynamicData* const pTDD = FindThreadDynamicData(id);
  184. if (pTDD)
  185. {
  186. strncpy(pTDD->mName, pName, EATHREAD_NAME_SIZE);
  187. pTDD->mName[EATHREAD_NAME_SIZE - 1] = 0;
  188. Internal::SetThreadName(pTDD);
  189. }
  190. }
  191. EATHREADLIB_API const char* EA::Thread::GetThreadName(const EA::Thread::ThreadId& id)
  192. {
  193. EAThreadDynamicData* const pTDD = FindThreadDynamicData(id);
  194. return pTDD ? pTDD->mName : "";
  195. }
  196. int EA::Thread::GetProcessorCount()
  197. {
  198. #if (SCE_ORBIS_SDK_VERSION >= 0x03000000u)
  199. return sceKernelGetCpumode() == SCE_KERNEL_CPUMODE_6CPU ? 6 : 7;
  200. #else
  201. return 6;
  202. #endif
  203. }
  204. void EA::Thread::ThreadSleep(const ThreadTime& timeRelative)
  205. {
  206. if(timeRelative == kTimeoutImmediate)
  207. {
  208. scePthreadYield();
  209. }
  210. else
  211. {
  212. SceKernelTimespec ts;
  213. static const double MILLISECONDS_TO_NANOSECONDS = 1000000.0;
  214. static const uint64_t SECONDS_TO_NANOSECONDS = 1000000000;
  215. // make sure we compute this with doubles then uint64_t or we will run out of bits precision
  216. uint64_t timeNanoSeconds = (uint64_t)(MILLISECONDS_TO_NANOSECONDS * timeRelative);
  217. ts.tv_sec = timeNanoSeconds / SECONDS_TO_NANOSECONDS;
  218. ts.tv_nsec = static_cast<long>(timeNanoSeconds % SECONDS_TO_NANOSECONDS); // converting from milliseconds to nanoseconds.
  219. // Determine which TimerQueue to use. Timer Queues are used to allow for higher resolution sleeps
  220. EAThreadTimerQueue* pThreadTimerQueue = nullptr;
  221. if (EA_UNLIKELY(tpThreadDynamicData == nullptr))
  222. {
  223. // This is either the first time an EAThread thread has called ThreadSleep or we are calling ThreadSleep
  224. // from a non-eathread function. Find the ThreadDynamicData which houses the TimerQueue and if not present (we are
  225. // using a non-eathread) grab the global instance instead.
  226. tpThreadDynamicData = EA::Thread::FindThreadDynamicData(EA::Thread::GetThreadId());
  227. if (tpThreadDynamicData)
  228. {
  229. pThreadTimerQueue = &tpThreadDynamicData->mThreadTimerQueue;
  230. }
  231. else
  232. {
  233. pThreadTimerQueue = &gThreadTimerQueue;
  234. }
  235. }
  236. else
  237. {
  238. pThreadTimerQueue = &tpThreadDynamicData->mThreadTimerQueue;
  239. }
  240. // Timer queues may only accept sleep values between 100 microseconds and while we guarantee pThreadTimerQueue will
  241. // not be null, we must ensure it has been enabled since it may fail in two uncommon ways:
  242. // 1. The underlying Sony Queue failed to initialize (such as too many queues currently being created)
  243. // 2. This function (ThreadSleep) is called during static initialization and due to static initialization order
  244. // we haven't had a chance to initialize the global static EAThreadTimerQueue instance
  245. if (EA_LIKELY((timeNanoSeconds < (SECONDS_TO_NANOSECONDS * 100)) && pThreadTimerQueue->mbEnabled))
  246. {
  247. const long kMinTimeForTimerEventNanoSeconds = 100000; // 100 microseconds represented in nanoseconds
  248. ts.tv_nsec = EA_UNLIKELY((ts.tv_nsec < kMinTimeForTimerEventNanoSeconds) && (ts.tv_sec != 0)) ?
  249. kMinTimeForTimerEventNanoSeconds : ts.tv_nsec;
  250. // it's ok to submit negative ids to the queue in the event that mCurrentId wraps around
  251. int result = sceKernelAddHRTimerEvent(pThreadTimerQueue->mTimerEventQueue, (int)pThreadTimerQueue->mCurrentId++, &ts, nullptr);
  252. EA_UNUSED(result);
  253. EAT_ASSERT_FORMATTED(result == SCE_OK, "sceKernelAddHRTimerEvent returned an error (0x%08x)", result);
  254. int out;
  255. SceKernelEvent ev;
  256. result = sceKernelWaitEqueue(pThreadTimerQueue->mTimerEventQueue, &ev, 1, &out, nullptr);
  257. EAT_ASSERT_FORMATTED(result == SCE_OK, "sceKernelWaitEqueue returned an error (0x%08x)", result);
  258. }
  259. else
  260. {
  261. int result = sceKernelNanosleep(&ts, 0);
  262. EA_UNUSED(result);
  263. EAT_ASSERT_MSG(result == SCE_OK, "sceKernelNanosleep returned an error");
  264. }
  265. }
  266. }
  267. namespace EA
  268. {
  269. namespace Thread
  270. {
  271. EAThreadDynamicData* FindThreadDynamicData(ThreadId threadId);
  272. }
  273. }
  274. void EA::Thread::ThreadEnd(intptr_t threadReturnValue)
  275. {
  276. EAThreadDynamicData* const pTDD = FindThreadDynamicData(GetThreadId());
  277. if(pTDD)
  278. {
  279. pTDD->mnStatus = Thread::kStatusEnded;
  280. pTDD->mnReturnValue = threadReturnValue;
  281. pTDD->mRunMutex.Unlock();
  282. pTDD->Release();
  283. }
  284. scePthreadExit((void*)threadReturnValue);
  285. }
  286. EA::Thread::ThreadTime EA::Thread::GetThreadTime()
  287. {
  288. SceKernelTimespec ts;
  289. sceKernelClockGettime(SCE_KERNEL_CLOCK_MONOTONIC, &ts);
  290. ThreadTime ret = EA_TIMESPEC_AS_DOUBLE_IN_MS(ts);
  291. return ret;
  292. }
  293. void EA::Thread::SetAssertionFailureFunction(EA::Thread::AssertionFailureFunction pAssertionFailureFunction, void* pContext)
  294. {
  295. gpAssertionFailureFunction = pAssertionFailureFunction;
  296. gpAssertionFailureContext = pContext;
  297. }
  298. void EA::Thread::AssertionFailure(const char* pExpression)
  299. {
  300. if(gpAssertionFailureFunction)
  301. gpAssertionFailureFunction(pExpression, gpAssertionFailureContext);
  302. else
  303. {
  304. #if EAT_ASSERT_ENABLED
  305. // Todo.
  306. #endif
  307. }
  308. }
  309. EA::Thread::SysThreadId EA::Thread::GetSysThreadId(EA::Thread::ThreadId id)
  310. {
  311. EAThreadDynamicData* const pTDD = FindThreadDynamicData(id);
  312. if (pTDD)
  313. {
  314. return pTDD->mSysThreadId;
  315. }
  316. return kSysThreadIdInvalid;
  317. }
  318. EA::Thread::SysThreadId EA::Thread::GetSysThreadId()
  319. {
  320. return scePthreadSelf();
  321. }