rsCpuCore.cpp revision 415a249300cb9ca3f560814bfde52c6796fed1f7
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include "rsCpuCore.h" 18#include "rsCpuScript.h" 19#include "rsCpuScriptGroup.h" 20#include "rsCpuScriptGroup2.h" 21 22#include <malloc.h> 23#include "rsContext.h" 24 25#include <sys/types.h> 26#include <sys/resource.h> 27#include <sched.h> 28#include <sys/syscall.h> 29#include <stdio.h> 30#include <string.h> 31#include <unistd.h> 32 33#if !defined(RS_SERVER) && !defined(RS_COMPATIBILITY_LIB) 34#include <cutils/properties.h> 35#include "utils/StopWatch.h" 36#endif 37 38#ifdef RS_SERVER 39// Android exposes gettid(), standard Linux does not 40static pid_t gettid() { 41 return syscall(SYS_gettid); 42} 43#endif 44 45using namespace android; 46using namespace android::renderscript; 47 48#define REDUCE_NEW_ALOGV(mtls, level, ...) do { if ((mtls)->logReduce >= (level)) ALOGV(__VA_ARGS__); } while(0) 49 50static pthread_key_t gThreadTLSKey = 0; 51static uint32_t gThreadTLSKeyCount = 0; 52static pthread_mutex_t gInitMutex = PTHREAD_MUTEX_INITIALIZER; 53 54bool android::renderscript::gArchUseSIMD = false; 55 56RsdCpuReference::~RsdCpuReference() { 57} 58 59RsdCpuReference * RsdCpuReference::create(Context *rsc, uint32_t version_major, 60 uint32_t version_minor, sym_lookup_t lfn, script_lookup_t slfn 61 , RSSelectRTCallback pSelectRTCallback, 62 const char *pBccPluginName 63 ) { 64 65 RsdCpuReferenceImpl *cpu = new RsdCpuReferenceImpl(rsc); 66 if (!cpu) { 67 return nullptr; 68 } 69 if (!cpu->init(version_major, version_minor, lfn, slfn)) { 70 delete cpu; 71 return nullptr; 72 } 73 74 cpu->setSelectRTCallback(pSelectRTCallback); 75 if (pBccPluginName) { 76 cpu->setBccPluginName(pBccPluginName); 77 } 78 79 return cpu; 80} 81 82 83Context * RsdCpuReference::getTlsContext() { 84 ScriptTLSStruct * tls = (ScriptTLSStruct *)pthread_getspecific(gThreadTLSKey); 85 return tls->mContext; 86} 87 88const Script * RsdCpuReference::getTlsScript() { 89 ScriptTLSStruct * tls = (ScriptTLSStruct *)pthread_getspecific(gThreadTLSKey); 90 return tls->mScript; 91} 92 93pthread_key_t RsdCpuReference::getThreadTLSKey(){ return gThreadTLSKey; } 94 95//////////////////////////////////////////////////////////// 96/// 97 98RsdCpuReferenceImpl::RsdCpuReferenceImpl(Context *rsc) { 99 mRSC = rsc; 100 101 version_major = 0; 102 version_minor = 0; 103 mInKernel = false; 104 memset(&mWorkers, 0, sizeof(mWorkers)); 105 memset(&mTlsStruct, 0, sizeof(mTlsStruct)); 106 mExit = false; 107 mSelectRTCallback = nullptr; 108 mEmbedGlobalInfo = true; 109 mEmbedGlobalInfoSkipConstant = true; 110} 111 112 113void * RsdCpuReferenceImpl::helperThreadProc(void *vrsc) { 114 RsdCpuReferenceImpl *dc = (RsdCpuReferenceImpl *)vrsc; 115 116 uint32_t idx = __sync_fetch_and_add(&dc->mWorkers.mLaunchCount, 1); 117 118 //ALOGV("RS helperThread starting %p idx=%i", dc, idx); 119 120 dc->mWorkers.mLaunchSignals[idx].init(); 121 dc->mWorkers.mNativeThreadId[idx] = gettid(); 122 123 memset(&dc->mTlsStruct, 0, sizeof(dc->mTlsStruct)); 124 int status = pthread_setspecific(gThreadTLSKey, &dc->mTlsStruct); 125 if (status) { 126 ALOGE("pthread_setspecific %i", status); 127 } 128 129#if 0 130 typedef struct {uint64_t bits[1024 / 64]; } cpu_set_t; 131 cpu_set_t cpuset; 132 memset(&cpuset, 0, sizeof(cpuset)); 133 cpuset.bits[idx / 64] |= 1ULL << (idx % 64); 134 int ret = syscall(241, rsc->mWorkers.mNativeThreadId[idx], 135 sizeof(cpuset), &cpuset); 136 ALOGE("SETAFFINITY ret = %i %s", ret, EGLUtils::strerror(ret)); 137#endif 138 139 while (!dc->mExit) { 140 dc->mWorkers.mLaunchSignals[idx].wait(); 141 if (dc->mWorkers.mLaunchCallback) { 142 // idx +1 is used because the calling thread is always worker 0. 143 dc->mWorkers.mLaunchCallback(dc->mWorkers.mLaunchData, idx+1); 144 } 145 __sync_fetch_and_sub(&dc->mWorkers.mRunningCount, 1); 146 dc->mWorkers.mCompleteSignal.set(); 147 } 148 149 //ALOGV("RS helperThread exited %p idx=%i", dc, idx); 150 return nullptr; 151} 152 153// Launch a kernel. 154// The callback function is called to execute the kernel. 155void RsdCpuReferenceImpl::launchThreads(WorkerCallback_t cbk, void *data) { 156 mWorkers.mLaunchData = data; 157 mWorkers.mLaunchCallback = cbk; 158 159 // fast path for very small launches 160 MTLaunchStructCommon *mtls = (MTLaunchStructCommon *)data; 161 if (mtls && mtls->dimPtr->y <= 1 && mtls->end.x <= mtls->start.x + mtls->mSliceSize) { 162 if (mWorkers.mLaunchCallback) { 163 mWorkers.mLaunchCallback(mWorkers.mLaunchData, 0); 164 } 165 return; 166 } 167 168 mWorkers.mRunningCount = mWorkers.mCount; 169 __sync_synchronize(); 170 171 for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) { 172 mWorkers.mLaunchSignals[ct].set(); 173 } 174 175 // We use the calling thread as one of the workers so we can start without 176 // the delay of the thread wakeup. 177 if (mWorkers.mLaunchCallback) { 178 mWorkers.mLaunchCallback(mWorkers.mLaunchData, 0); 179 } 180 181 while (__sync_fetch_and_or(&mWorkers.mRunningCount, 0) != 0) { 182 mWorkers.mCompleteSignal.wait(); 183 } 184} 185 186 187void RsdCpuReferenceImpl::lockMutex() { 188 pthread_mutex_lock(&gInitMutex); 189} 190 191void RsdCpuReferenceImpl::unlockMutex() { 192 pthread_mutex_unlock(&gInitMutex); 193} 194 195// Determine if the CPU we're running on supports SIMD instructions. 196static void GetCpuInfo() { 197 // Read the CPU flags from /proc/cpuinfo. 198 FILE *cpuinfo = fopen("/proc/cpuinfo", "r"); 199 200 if (!cpuinfo) { 201 return; 202 } 203 204 char cpuinfostr[4096]; 205 // fgets() ends with newline or EOF, need to check the whole 206 // "cpuinfo" file to make sure we can use SIMD or not. 207 while (fgets(cpuinfostr, sizeof(cpuinfostr), cpuinfo)) { 208#if defined(ARCH_ARM_HAVE_VFP) || defined(ARCH_ARM_USE_INTRINSICS) 209 gArchUseSIMD = strstr(cpuinfostr, " neon") || strstr(cpuinfostr, " asimd"); 210#elif defined(ARCH_X86_HAVE_SSSE3) 211 gArchUseSIMD = strstr(cpuinfostr, " ssse3"); 212#endif 213 if (gArchUseSIMD) { 214 break; 215 } 216 } 217 fclose(cpuinfo); 218} 219 220bool RsdCpuReferenceImpl::init(uint32_t version_major, uint32_t version_minor, 221 sym_lookup_t lfn, script_lookup_t slfn) { 222 mSymLookupFn = lfn; 223 mScriptLookupFn = slfn; 224 225 lockMutex(); 226 if (!gThreadTLSKeyCount) { 227 int status = pthread_key_create(&gThreadTLSKey, nullptr); 228 if (status) { 229 ALOGE("Failed to init thread tls key."); 230 unlockMutex(); 231 return false; 232 } 233 } 234 gThreadTLSKeyCount++; 235 unlockMutex(); 236 237 mTlsStruct.mContext = mRSC; 238 mTlsStruct.mScript = nullptr; 239 int status = pthread_setspecific(gThreadTLSKey, &mTlsStruct); 240 if (status) { 241 ALOGE("pthread_setspecific %i", status); 242 } 243 244 mPageSize = sysconf(_SC_PAGE_SIZE); 245 // ALOGV("page size = %ld", mPageSize); 246 247 GetCpuInfo(); 248 249 int cpu = sysconf(_SC_NPROCESSORS_CONF); 250 if(mRSC->props.mDebugMaxThreads) { 251 cpu = mRSC->props.mDebugMaxThreads; 252 } 253 if (cpu < 2) { 254 mWorkers.mCount = 0; 255 return true; 256 } 257 258 // Subtract one from the cpu count because we also use the command thread as a worker. 259 mWorkers.mCount = (uint32_t)(cpu - 1); 260 261 ALOGV("%p Launching thread(s), CPUs %i", mRSC, mWorkers.mCount + 1); 262 263 mWorkers.mThreadId = (pthread_t *) calloc(mWorkers.mCount, sizeof(pthread_t)); 264 mWorkers.mNativeThreadId = (pid_t *) calloc(mWorkers.mCount, sizeof(pid_t)); 265 mWorkers.mLaunchSignals = new Signal[mWorkers.mCount]; 266 mWorkers.mLaunchCallback = nullptr; 267 268 mWorkers.mCompleteSignal.init(); 269 270 mWorkers.mRunningCount = mWorkers.mCount; 271 mWorkers.mLaunchCount = 0; 272 __sync_synchronize(); 273 274 pthread_attr_t threadAttr; 275 status = pthread_attr_init(&threadAttr); 276 if (status) { 277 ALOGE("Failed to init thread attribute."); 278 return false; 279 } 280 281 for (uint32_t ct=0; ct < mWorkers.mCount; ct++) { 282 status = pthread_create(&mWorkers.mThreadId[ct], &threadAttr, helperThreadProc, this); 283 if (status) { 284 mWorkers.mCount = ct; 285 ALOGE("Created fewer than expected number of RS threads."); 286 break; 287 } 288 } 289 while (__sync_fetch_and_or(&mWorkers.mRunningCount, 0) != 0) { 290 usleep(100); 291 } 292 293 pthread_attr_destroy(&threadAttr); 294 return true; 295} 296 297 298void RsdCpuReferenceImpl::setPriority(int32_t priority) { 299 for (uint32_t ct=0; ct < mWorkers.mCount; ct++) { 300 setpriority(PRIO_PROCESS, mWorkers.mNativeThreadId[ct], priority); 301 } 302} 303 304RsdCpuReferenceImpl::~RsdCpuReferenceImpl() { 305 mExit = true; 306 mWorkers.mLaunchData = nullptr; 307 mWorkers.mLaunchCallback = nullptr; 308 mWorkers.mRunningCount = mWorkers.mCount; 309 __sync_synchronize(); 310 for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) { 311 mWorkers.mLaunchSignals[ct].set(); 312 } 313 void *res; 314 for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) { 315 pthread_join(mWorkers.mThreadId[ct], &res); 316 } 317 rsAssert(__sync_fetch_and_or(&mWorkers.mRunningCount, 0) == 0); 318 free(mWorkers.mThreadId); 319 free(mWorkers.mNativeThreadId); 320 delete[] mWorkers.mLaunchSignals; 321 322 // Global structure cleanup. 323 lockMutex(); 324 --gThreadTLSKeyCount; 325 if (!gThreadTLSKeyCount) { 326 pthread_key_delete(gThreadTLSKey); 327 } 328 unlockMutex(); 329 330} 331 332// Set up the appropriate input and output pointers to the kernel driver info structure. 333// Inputs: 334// mtls - The MTLaunchStruct holding information about the kernel launch 335// fep - The forEach parameters (driver info structure) 336// x, y, z, lod, face, a1, a2, a3, a4 - The start offsets into each dimension 337static inline void FepPtrSetup(const MTLaunchStructForEach *mtls, RsExpandKernelDriverInfo *fep, 338 uint32_t x, uint32_t y, 339 uint32_t z = 0, uint32_t lod = 0, 340 RsAllocationCubemapFace face = RS_ALLOCATION_CUBEMAP_FACE_POSITIVE_X, 341 uint32_t a1 = 0, uint32_t a2 = 0, uint32_t a3 = 0, uint32_t a4 = 0) { 342 for (uint32_t i = 0; i < fep->inLen; i++) { 343 fep->inPtr[i] = (const uint8_t *)mtls->ains[i]->getPointerUnchecked(x, y, z, lod, face, a1, a2, a3, a4); 344 } 345 if (mtls->aout[0] != nullptr) { 346 fep->outPtr[0] = (uint8_t *)mtls->aout[0]->getPointerUnchecked(x, y, z, lod, face, a1, a2, a3, a4); 347 } 348} 349 350// Set up the appropriate input and output pointers to the kernel driver info structure. 351// Inputs: 352// mtls - The MTLaunchStruct holding information about the kernel launch 353// redp - The reduce parameters (driver info structure) 354// x, y, z - The start offsets into each dimension 355static inline void RedpPtrSetup(const MTLaunchStructReduceNew *mtls, RsExpandKernelDriverInfo *redp, 356 uint32_t x, uint32_t y, uint32_t z) { 357 for (uint32_t i = 0; i < redp->inLen; i++) { 358 redp->inPtr[i] = (const uint8_t *)mtls->ains[i]->getPointerUnchecked(x, y, z); 359 } 360} 361 362static uint32_t sliceInt(uint32_t *p, uint32_t val, uint32_t start, uint32_t end) { 363 if (start >= end) { 364 *p = start; 365 return val; 366 } 367 368 uint32_t div = end - start; 369 370 uint32_t n = val / div; 371 *p = (val - (n * div)) + start; 372 return n; 373} 374 375static bool SelectOuterSlice(const MTLaunchStructCommon *mtls, RsExpandKernelDriverInfo* info, uint32_t sliceNum) { 376 uint32_t r = sliceNum; 377 r = sliceInt(&info->current.z, r, mtls->start.z, mtls->end.z); 378 r = sliceInt(&info->current.lod, r, mtls->start.lod, mtls->end.lod); 379 r = sliceInt(&info->current.face, r, mtls->start.face, mtls->end.face); 380 r = sliceInt(&info->current.array[0], r, mtls->start.array[0], mtls->end.array[0]); 381 r = sliceInt(&info->current.array[1], r, mtls->start.array[1], mtls->end.array[1]); 382 r = sliceInt(&info->current.array[2], r, mtls->start.array[2], mtls->end.array[2]); 383 r = sliceInt(&info->current.array[3], r, mtls->start.array[3], mtls->end.array[3]); 384 return r == 0; 385} 386 387static bool SelectZSlice(const MTLaunchStructCommon *mtls, RsExpandKernelDriverInfo* info, uint32_t sliceNum) { 388 return sliceInt(&info->current.z, sliceNum, mtls->start.z, mtls->end.z) == 0; 389} 390 391static void walk_general_foreach(void *usr, uint32_t idx) { 392 MTLaunchStructForEach *mtls = (MTLaunchStructForEach *)usr; 393 RsExpandKernelDriverInfo fep = mtls->fep; 394 fep.lid = idx; 395 ForEachFunc_t fn = mtls->kernel; 396 397 while(1) { 398 uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1); 399 400 if (!SelectOuterSlice(mtls, &fep, slice)) { 401 return; 402 } 403 404 for (fep.current.y = mtls->start.y; fep.current.y < mtls->end.y; 405 fep.current.y++) { 406 407 FepPtrSetup(mtls, &fep, mtls->start.x, 408 fep.current.y, fep.current.z, fep.current.lod, 409 (RsAllocationCubemapFace)fep.current.face, 410 fep.current.array[0], fep.current.array[1], 411 fep.current.array[2], fep.current.array[3]); 412 413 fn(&fep, mtls->start.x, mtls->end.x, mtls->fep.outStride[0]); 414 } 415 } 416} 417 418static void walk_2d_foreach(void *usr, uint32_t idx) { 419 MTLaunchStructForEach *mtls = (MTLaunchStructForEach *)usr; 420 RsExpandKernelDriverInfo fep = mtls->fep; 421 fep.lid = idx; 422 ForEachFunc_t fn = mtls->kernel; 423 424 while (1) { 425 uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1); 426 uint32_t yStart = mtls->start.y + slice * mtls->mSliceSize; 427 uint32_t yEnd = yStart + mtls->mSliceSize; 428 429 yEnd = rsMin(yEnd, mtls->end.y); 430 431 if (yEnd <= yStart) { 432 return; 433 } 434 435 for (fep.current.y = yStart; fep.current.y < yEnd; fep.current.y++) { 436 FepPtrSetup(mtls, &fep, mtls->start.x, fep.current.y); 437 438 fn(&fep, mtls->start.x, mtls->end.x, fep.outStride[0]); 439 } 440 } 441} 442 443static void walk_1d_foreach(void *usr, uint32_t idx) { 444 MTLaunchStructForEach *mtls = (MTLaunchStructForEach *)usr; 445 RsExpandKernelDriverInfo fep = mtls->fep; 446 fep.lid = idx; 447 ForEachFunc_t fn = mtls->kernel; 448 449 while (1) { 450 uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1); 451 uint32_t xStart = mtls->start.x + slice * mtls->mSliceSize; 452 uint32_t xEnd = xStart + mtls->mSliceSize; 453 454 xEnd = rsMin(xEnd, mtls->end.x); 455 456 if (xEnd <= xStart) { 457 return; 458 } 459 460 FepPtrSetup(mtls, &fep, xStart, 0); 461 462 fn(&fep, xStart, xEnd, fep.outStride[0]); 463 } 464} 465 466// The function format_bytes() is an auxiliary function to assist in logging. 467// 468// Bytes are read from an input (inBuf) and written (as pairs of hex digits) 469// to an output (outBuf). 470// 471// Output format: 472// - starts with ": " 473// - each input byte is translated to a pair of hex digits 474// - bytes are separated by "." except that every fourth separator is "|" 475// - if the input is sufficiently long, the output is truncated and terminated with "..." 476// 477// Arguments: 478// - outBuf -- Pointer to buffer of type "FormatBuf" into which output is written 479// - inBuf -- Pointer to bytes which are to be formatted into outBuf 480// - inBytes -- Number of bytes in inBuf 481// 482// Constant: 483// - kFormatInBytesMax -- Only min(kFormatInBytesMax, inBytes) bytes will be read 484// from inBuf 485// 486// Return value: 487// - pointer (const char *) to output (which is part of outBuf) 488// 489static const int kFormatInBytesMax = 16; 490// ": " + 2 digits per byte + 1 separator between bytes + "..." + null 491typedef char FormatBuf[2 + kFormatInBytesMax*2 + (kFormatInBytesMax - 1) + 3 + 1]; 492static const char *format_bytes(FormatBuf *outBuf, const uint8_t *inBuf, const int inBytes) { 493 strcpy(*outBuf, ": "); 494 int pos = 2; 495 const int lim = std::min(kFormatInBytesMax, inBytes); 496 for (int i = 0; i < lim; ++i) { 497 if (i) { 498 sprintf(*outBuf + pos, (i % 4 ? "." : "|")); 499 ++pos; 500 } 501 sprintf(*outBuf + pos, "%02x", inBuf[i]); 502 pos += 2; 503 } 504 if (kFormatInBytesMax < inBytes) 505 strcpy(*outBuf + pos, "..."); 506 return *outBuf; 507} 508 509static void reduce_new_get_accumulator(uint8_t *&accumPtr, const MTLaunchStructReduceNew *mtls, 510 const char *walkerName, uint32_t threadIdx) { 511 rsAssert(!accumPtr); 512 513 uint32_t accumIdx = (uint32_t)__sync_fetch_and_add(&mtls->accumCount, 1); 514 if (mtls->outFunc) { 515 accumPtr = mtls->accumAlloc + mtls->accumStride * accumIdx; 516 } else { 517 if (accumIdx == 0) { 518 accumPtr = mtls->redp.outPtr[0]; 519 } else { 520 accumPtr = mtls->accumAlloc + mtls->accumStride * (accumIdx - 1); 521 } 522 } 523 REDUCE_NEW_ALOGV(mtls, 2, "%s(%p): idx = %u got accumCount %u and accumPtr %p", 524 walkerName, mtls->accumFunc, threadIdx, accumIdx, accumPtr); 525 // initialize accumulator 526 if (mtls->initFunc) { 527 mtls->initFunc(accumPtr); 528 } else { 529 memset(accumPtr, 0, mtls->accumSize); 530 } 531} 532 533static void walk_1d_reduce_new(void *usr, uint32_t idx) { 534 const MTLaunchStructReduceNew *mtls = (const MTLaunchStructReduceNew *)usr; 535 RsExpandKernelDriverInfo redp = mtls->redp; 536 537 // find accumulator 538 uint8_t *&accumPtr = mtls->accumPtr[idx]; 539 if (!accumPtr) { 540 reduce_new_get_accumulator(accumPtr, mtls, __func__, idx); 541 } 542 543 // accumulate 544 const ReduceNewAccumulatorFunc_t fn = mtls->accumFunc; 545 while (1) { 546 uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1); 547 uint32_t xStart = mtls->start.x + slice * mtls->mSliceSize; 548 uint32_t xEnd = xStart + mtls->mSliceSize; 549 550 xEnd = rsMin(xEnd, mtls->end.x); 551 552 if (xEnd <= xStart) { 553 return; 554 } 555 556 RedpPtrSetup(mtls, &redp, xStart, 0, 0); 557 fn(&redp, xStart, xEnd, accumPtr); 558 559 // Emit log line after slice has been run, so that we can include 560 // the results of the run on that line. 561 FormatBuf fmt; 562 if (mtls->logReduce >= 3) { 563 format_bytes(&fmt, accumPtr, mtls->accumSize); 564 } else { 565 fmt[0] = 0; 566 } 567 REDUCE_NEW_ALOGV(mtls, 2, "walk_1d_reduce_new(%p): idx = %u, x in [%u, %u)%s", 568 mtls->accumFunc, idx, xStart, xEnd, fmt); 569 } 570} 571 572static void walk_2d_reduce_new(void *usr, uint32_t idx) { 573 const MTLaunchStructReduceNew *mtls = (const MTLaunchStructReduceNew *)usr; 574 RsExpandKernelDriverInfo redp = mtls->redp; 575 576 // find accumulator 577 uint8_t *&accumPtr = mtls->accumPtr[idx]; 578 if (!accumPtr) { 579 reduce_new_get_accumulator(accumPtr, mtls, __func__, idx); 580 } 581 582 // accumulate 583 const ReduceNewAccumulatorFunc_t fn = mtls->accumFunc; 584 while (1) { 585 uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1); 586 uint32_t yStart = mtls->start.y + slice * mtls->mSliceSize; 587 uint32_t yEnd = yStart + mtls->mSliceSize; 588 589 yEnd = rsMin(yEnd, mtls->end.y); 590 591 if (yEnd <= yStart) { 592 return; 593 } 594 595 for (redp.current.y = yStart; redp.current.y < yEnd; redp.current.y++) { 596 RedpPtrSetup(mtls, &redp, mtls->start.x, redp.current.y, 0); 597 fn(&redp, mtls->start.x, mtls->end.x, accumPtr); 598 } 599 600 FormatBuf fmt; 601 if (mtls->logReduce >= 3) { 602 format_bytes(&fmt, accumPtr, mtls->accumSize); 603 } else { 604 fmt[0] = 0; 605 } 606 REDUCE_NEW_ALOGV(mtls, 2, "walk_2d_reduce_new(%p): idx = %u, y in [%u, %u)%s", 607 mtls->accumFunc, idx, yStart, yEnd, fmt); 608 } 609} 610 611static void walk_3d_reduce_new(void *usr, uint32_t idx) { 612 const MTLaunchStructReduceNew *mtls = (const MTLaunchStructReduceNew *)usr; 613 RsExpandKernelDriverInfo redp = mtls->redp; 614 615 // find accumulator 616 uint8_t *&accumPtr = mtls->accumPtr[idx]; 617 if (!accumPtr) { 618 reduce_new_get_accumulator(accumPtr, mtls, __func__, idx); 619 } 620 621 // accumulate 622 const ReduceNewAccumulatorFunc_t fn = mtls->accumFunc; 623 while (1) { 624 uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1); 625 626 if (!SelectZSlice(mtls, &redp, slice)) { 627 return; 628 } 629 630 for (redp.current.y = mtls->start.y; redp.current.y < mtls->end.y; redp.current.y++) { 631 RedpPtrSetup(mtls, &redp, mtls->start.x, redp.current.y, redp.current.z); 632 fn(&redp, mtls->start.x, mtls->end.x, accumPtr); 633 } 634 635 FormatBuf fmt; 636 if (mtls->logReduce >= 3) { 637 format_bytes(&fmt, accumPtr, mtls->accumSize); 638 } else { 639 fmt[0] = 0; 640 } 641 REDUCE_NEW_ALOGV(mtls, 2, "walk_3d_reduce_new(%p): idx = %u, z = %u%s", 642 mtls->accumFunc, idx, redp.current.z, fmt); 643 } 644} 645 646// Launch a simple reduce-style kernel. 647// Inputs: 648// ain: The allocation that contains the input 649// aout: The allocation that will hold the output 650// mtls: Holds launch parameters 651void RsdCpuReferenceImpl::launchReduce(const Allocation *ain, 652 Allocation *aout, 653 MTLaunchStructReduce *mtls) { 654 const uint32_t xStart = mtls->start.x; 655 const uint32_t xEnd = mtls->end.x; 656 657 if (xStart >= xEnd) { 658 return; 659 } 660 661 const uint32_t startOffset = ain->getType()->getElementSizeBytes() * xStart; 662 mtls->kernel(&mtls->inBuf[startOffset], mtls->outBuf, xEnd - xStart); 663} 664 665// Launch a general reduce-style kernel. 666// Inputs: 667// ains[0..inLen-1]: Array of allocations that contain the inputs 668// aout: The allocation that will hold the output 669// mtls: Holds launch parameters 670void RsdCpuReferenceImpl::launchReduceNew(const Allocation ** ains, 671 uint32_t inLen, 672 Allocation * aout, 673 MTLaunchStructReduceNew *mtls) { 674 mtls->logReduce = mRSC->props.mLogReduce; 675 if ((mWorkers.mCount >= 1) && mtls->isThreadable && !mInKernel) { 676 launchReduceNewParallel(ains, inLen, aout, mtls); 677 } else { 678 launchReduceNewSerial(ains, inLen, aout, mtls); 679 } 680} 681 682// Launch a general reduce-style kernel, single-threaded. 683// Inputs: 684// ains[0..inLen-1]: Array of allocations that contain the inputs 685// aout: The allocation that will hold the output 686// mtls: Holds launch parameters 687void RsdCpuReferenceImpl::launchReduceNewSerial(const Allocation ** ains, 688 uint32_t inLen, 689 Allocation * aout, 690 MTLaunchStructReduceNew *mtls) { 691 REDUCE_NEW_ALOGV(mtls, 1, "launchReduceNewSerial(%p): %u x %u x %u", mtls->accumFunc, 692 mtls->redp.dim.x, mtls->redp.dim.y, mtls->redp.dim.z); 693 694 // In the presence of outconverter, we allocate temporary memory for 695 // the accumulator. 696 // 697 // In the absence of outconverter, we use the output allocation as the 698 // accumulator. 699 uint8_t *const accumPtr = (mtls->outFunc 700 ? static_cast<uint8_t *>(malloc(mtls->accumSize)) 701 : mtls->redp.outPtr[0]); 702 703 // initialize 704 if (mtls->initFunc) { 705 mtls->initFunc(accumPtr); 706 } else { 707 memset(accumPtr, 0, mtls->accumSize); 708 } 709 710 // accumulate 711 const ReduceNewAccumulatorFunc_t fn = mtls->accumFunc; 712 uint32_t slice = 0; 713 while (SelectOuterSlice(mtls, &mtls->redp, slice++)) { 714 for (mtls->redp.current.y = mtls->start.y; 715 mtls->redp.current.y < mtls->end.y; 716 mtls->redp.current.y++) { 717 RedpPtrSetup(mtls, &mtls->redp, mtls->start.x, mtls->redp.current.y, mtls->redp.current.z); 718 fn(&mtls->redp, mtls->start.x, mtls->end.x, accumPtr); 719 } 720 } 721 722 // outconvert 723 if (mtls->outFunc) { 724 mtls->outFunc(mtls->redp.outPtr[0], accumPtr); 725 free(accumPtr); 726 } 727} 728 729// Launch a general reduce-style kernel, multi-threaded. 730// Inputs: 731// ains[0..inLen-1]: Array of allocations that contain the inputs 732// aout: The allocation that will hold the output 733// mtls: Holds launch parameters 734void RsdCpuReferenceImpl::launchReduceNewParallel(const Allocation ** ains, 735 uint32_t inLen, 736 Allocation * aout, 737 MTLaunchStructReduceNew *mtls) { 738 // For now, we don't know how to go parallel in the absence of a combiner. 739 if (!mtls->combFunc) { 740 launchReduceNewSerial(ains, inLen, aout, mtls); 741 return; 742 } 743 744 // Number of threads = "main thread" + number of other (worker) threads 745 const uint32_t numThreads = mWorkers.mCount + 1; 746 747 // In the absence of outconverter, we use the output allocation as 748 // an accumulator, and therefore need to allocate one fewer accumulator. 749 const uint32_t numAllocAccum = numThreads - (mtls->outFunc == nullptr); 750 751 // If mDebugReduceSplitAccum, then we want each accumulator to start 752 // on a page boundary. (TODO: Would some unit smaller than a page 753 // be sufficient to avoid false sharing?) 754 if (mRSC->props.mDebugReduceSplitAccum) { 755 // Round up accumulator size to an integral number of pages 756 mtls->accumStride = 757 (unsigned(mtls->accumSize) + unsigned(mPageSize)-1) & 758 ~(unsigned(mPageSize)-1); 759 // Each accumulator gets its own page. Alternatively, if we just 760 // wanted to make sure no two accumulators are on the same page, 761 // we could instead do 762 // allocSize = mtls->accumStride * (numAllocation - 1) + mtls->accumSize 763 const size_t allocSize = mtls->accumStride * numAllocAccum; 764 mtls->accumAlloc = static_cast<uint8_t *>(memalign(mPageSize, allocSize)); 765 } else { 766 mtls->accumStride = mtls->accumSize; 767 mtls->accumAlloc = static_cast<uint8_t *>(malloc(mtls->accumStride * numAllocAccum)); 768 } 769 770 const size_t accumPtrArrayBytes = sizeof(uint8_t *) * numThreads; 771 mtls->accumPtr = static_cast<uint8_t **>(malloc(accumPtrArrayBytes)); 772 memset(mtls->accumPtr, 0, accumPtrArrayBytes); 773 774 mtls->accumCount = 0; 775 776 rsAssert(!mInKernel); 777 mInKernel = true; 778 REDUCE_NEW_ALOGV(mtls, 1, "launchReduceNewParallel(%p): %u x %u x %u, %u threads, accumAlloc = %p", 779 mtls->accumFunc, 780 mtls->redp.dim.x, mtls->redp.dim.y, mtls->redp.dim.z, 781 numThreads, mtls->accumAlloc); 782 if (mtls->redp.dim.z > 1) { 783 mtls->mSliceSize = 1; 784 launchThreads(walk_3d_reduce_new, mtls); 785 } else if (mtls->redp.dim.y > 1) { 786 mtls->mSliceSize = rsMax(1U, mtls->redp.dim.y / (numThreads * 4)); 787 launchThreads(walk_2d_reduce_new, mtls); 788 } else { 789 mtls->mSliceSize = rsMax(1U, mtls->redp.dim.x / (numThreads * 4)); 790 launchThreads(walk_1d_reduce_new, mtls); 791 } 792 mInKernel = false; 793 794 // Combine accumulators and identify final accumulator 795 uint8_t *finalAccumPtr = (mtls->outFunc ? nullptr : mtls->redp.outPtr[0]); 796 // Loop over accumulators, combining into finalAccumPtr. If finalAccumPtr 797 // is null, then the first accumulator I find becomes finalAccumPtr. 798 for (unsigned idx = 0; idx < mtls->accumCount; ++idx) { 799 uint8_t *const thisAccumPtr = mtls->accumPtr[idx]; 800 if (finalAccumPtr) { 801 if (finalAccumPtr != thisAccumPtr) { 802 if (mtls->combFunc) { 803 if (mtls->logReduce >= 3) { 804 FormatBuf fmt; 805 REDUCE_NEW_ALOGV(mtls, 3, "launchReduceNewParallel(%p): accumulating into%s", 806 mtls->accumFunc, 807 format_bytes(&fmt, finalAccumPtr, mtls->accumSize)); 808 REDUCE_NEW_ALOGV(mtls, 3, "launchReduceNewParallel(%p): accumulator[%d]%s", 809 mtls->accumFunc, idx, 810 format_bytes(&fmt, thisAccumPtr, mtls->accumSize)); 811 } 812 mtls->combFunc(finalAccumPtr, thisAccumPtr); 813 } else { 814 rsAssert(!"expected combiner"); 815 } 816 } 817 } else { 818 finalAccumPtr = thisAccumPtr; 819 } 820 } 821 rsAssert(finalAccumPtr != nullptr); 822 if (mtls->logReduce >= 3) { 823 FormatBuf fmt; 824 REDUCE_NEW_ALOGV(mtls, 3, "launchReduceNewParallel(%p): final accumulator%s", 825 mtls->accumFunc, format_bytes(&fmt, finalAccumPtr, mtls->accumSize)); 826 } 827 828 // Outconvert 829 if (mtls->outFunc) { 830 mtls->outFunc(mtls->redp.outPtr[0], finalAccumPtr); 831 if (mtls->logReduce >= 3) { 832 FormatBuf fmt; 833 REDUCE_NEW_ALOGV(mtls, 3, "launchReduceNewParallel(%p): final outconverted result%s", 834 mtls->accumFunc, 835 format_bytes(&fmt, mtls->redp.outPtr[0], mtls->redp.outStride[0])); 836 } 837 } 838 839 // Clean up 840 free(mtls->accumPtr); 841 free(mtls->accumAlloc); 842} 843 844 845void RsdCpuReferenceImpl::launchForEach(const Allocation ** ains, 846 uint32_t inLen, 847 Allocation* aout, 848 const RsScriptCall* sc, 849 MTLaunchStructForEach* mtls) { 850 851 //android::StopWatch kernel_time("kernel time"); 852 853 bool outerDims = (mtls->start.z != mtls->end.z) || 854 (mtls->start.face != mtls->end.face) || 855 (mtls->start.lod != mtls->end.lod) || 856 (mtls->start.array[0] != mtls->end.array[0]) || 857 (mtls->start.array[1] != mtls->end.array[1]) || 858 (mtls->start.array[2] != mtls->end.array[2]) || 859 (mtls->start.array[3] != mtls->end.array[3]); 860 861 if ((mWorkers.mCount >= 1) && mtls->isThreadable && !mInKernel) { 862 const size_t targetByteChunk = 16 * 1024; 863 mInKernel = true; // NOTE: The guard immediately above ensures this was !mInKernel 864 865 if (outerDims) { 866 // No fancy logic for chunk size 867 mtls->mSliceSize = 1; 868 launchThreads(walk_general_foreach, mtls); 869 } else if (mtls->fep.dim.y > 1) { 870 uint32_t s1 = mtls->fep.dim.y / ((mWorkers.mCount + 1) * 4); 871 uint32_t s2 = 0; 872 873 // This chooses our slice size to rate limit atomic ops to 874 // one per 16k bytes of reads/writes. 875 if ((mtls->aout[0] != nullptr) && mtls->aout[0]->mHal.drvState.lod[0].stride) { 876 s2 = targetByteChunk / mtls->aout[0]->mHal.drvState.lod[0].stride; 877 } else if (mtls->ains[0]) { 878 s2 = targetByteChunk / mtls->ains[0]->mHal.drvState.lod[0].stride; 879 } else { 880 // Launch option only case 881 // Use s1 based only on the dimensions 882 s2 = s1; 883 } 884 mtls->mSliceSize = rsMin(s1, s2); 885 886 if(mtls->mSliceSize < 1) { 887 mtls->mSliceSize = 1; 888 } 889 890 launchThreads(walk_2d_foreach, mtls); 891 } else { 892 uint32_t s1 = mtls->fep.dim.x / ((mWorkers.mCount + 1) * 4); 893 uint32_t s2 = 0; 894 895 // This chooses our slice size to rate limit atomic ops to 896 // one per 16k bytes of reads/writes. 897 if ((mtls->aout[0] != nullptr) && mtls->aout[0]->getType()->getElementSizeBytes()) { 898 s2 = targetByteChunk / mtls->aout[0]->getType()->getElementSizeBytes(); 899 } else if (mtls->ains[0]) { 900 s2 = targetByteChunk / mtls->ains[0]->getType()->getElementSizeBytes(); 901 } else { 902 // Launch option only case 903 // Use s1 based only on the dimensions 904 s2 = s1; 905 } 906 mtls->mSliceSize = rsMin(s1, s2); 907 908 if (mtls->mSliceSize < 1) { 909 mtls->mSliceSize = 1; 910 } 911 912 launchThreads(walk_1d_foreach, mtls); 913 } 914 mInKernel = false; 915 916 } else { 917 ForEachFunc_t fn = mtls->kernel; 918 uint32_t slice = 0; 919 920 921 while(SelectOuterSlice(mtls, &mtls->fep, slice++)) { 922 for (mtls->fep.current.y = mtls->start.y; 923 mtls->fep.current.y < mtls->end.y; 924 mtls->fep.current.y++) { 925 926 FepPtrSetup(mtls, &mtls->fep, mtls->start.x, 927 mtls->fep.current.y, mtls->fep.current.z, mtls->fep.current.lod, 928 (RsAllocationCubemapFace) mtls->fep.current.face, 929 mtls->fep.current.array[0], mtls->fep.current.array[1], 930 mtls->fep.current.array[2], mtls->fep.current.array[3]); 931 932 fn(&mtls->fep, mtls->start.x, mtls->end.x, mtls->fep.outStride[0]); 933 } 934 } 935 } 936} 937 938RsdCpuScriptImpl * RsdCpuReferenceImpl::setTLS(RsdCpuScriptImpl *sc) { 939 //ALOGE("setTls %p", sc); 940 ScriptTLSStruct * tls = (ScriptTLSStruct *)pthread_getspecific(gThreadTLSKey); 941 rsAssert(tls); 942 RsdCpuScriptImpl *old = tls->mImpl; 943 tls->mImpl = sc; 944 tls->mContext = mRSC; 945 if (sc) { 946 tls->mScript = sc->getScript(); 947 } else { 948 tls->mScript = nullptr; 949 } 950 return old; 951} 952 953const RsdCpuReference::CpuSymbol * RsdCpuReferenceImpl::symLookup(const char *name) { 954 return mSymLookupFn(mRSC, name); 955} 956 957 958RsdCpuReference::CpuScript * RsdCpuReferenceImpl::createScript(const ScriptC *s, 959 char const *resName, char const *cacheDir, 960 uint8_t const *bitcode, size_t bitcodeSize, 961 uint32_t flags) { 962 963 RsdCpuScriptImpl *i = new RsdCpuScriptImpl(this, s); 964 if (!i->init(resName, cacheDir, bitcode, bitcodeSize, flags 965 , getBccPluginName() 966 )) { 967 delete i; 968 return nullptr; 969 } 970 return i; 971} 972 973extern RsdCpuScriptImpl * rsdIntrinsic_3DLUT(RsdCpuReferenceImpl *ctx, 974 const Script *s, const Element *e); 975extern RsdCpuScriptImpl * rsdIntrinsic_Convolve3x3(RsdCpuReferenceImpl *ctx, 976 const Script *s, const Element *e); 977extern RsdCpuScriptImpl * rsdIntrinsic_ColorMatrix(RsdCpuReferenceImpl *ctx, 978 const Script *s, const Element *e); 979extern RsdCpuScriptImpl * rsdIntrinsic_LUT(RsdCpuReferenceImpl *ctx, 980 const Script *s, const Element *e); 981extern RsdCpuScriptImpl * rsdIntrinsic_Convolve5x5(RsdCpuReferenceImpl *ctx, 982 const Script *s, const Element *e); 983extern RsdCpuScriptImpl * rsdIntrinsic_Blur(RsdCpuReferenceImpl *ctx, 984 const Script *s, const Element *e); 985extern RsdCpuScriptImpl * rsdIntrinsic_YuvToRGB(RsdCpuReferenceImpl *ctx, 986 const Script *s, const Element *e); 987extern RsdCpuScriptImpl * rsdIntrinsic_Blend(RsdCpuReferenceImpl *ctx, 988 const Script *s, const Element *e); 989extern RsdCpuScriptImpl * rsdIntrinsic_Histogram(RsdCpuReferenceImpl *ctx, 990 const Script *s, const Element *e); 991extern RsdCpuScriptImpl * rsdIntrinsic_Resize(RsdCpuReferenceImpl *ctx, 992 const Script *s, const Element *e); 993extern RsdCpuScriptImpl * rsdIntrinsic_BLAS(RsdCpuReferenceImpl *ctx, 994 const Script *s, const Element *e); 995 996RsdCpuReference::CpuScript * RsdCpuReferenceImpl::createIntrinsic(const Script *s, 997 RsScriptIntrinsicID iid, Element *e) { 998 999 RsdCpuScriptImpl *i = nullptr; 1000 switch (iid) { 1001 case RS_SCRIPT_INTRINSIC_ID_3DLUT: 1002 i = rsdIntrinsic_3DLUT(this, s, e); 1003 break; 1004 case RS_SCRIPT_INTRINSIC_ID_CONVOLVE_3x3: 1005 i = rsdIntrinsic_Convolve3x3(this, s, e); 1006 break; 1007 case RS_SCRIPT_INTRINSIC_ID_COLOR_MATRIX: 1008 i = rsdIntrinsic_ColorMatrix(this, s, e); 1009 break; 1010 case RS_SCRIPT_INTRINSIC_ID_LUT: 1011 i = rsdIntrinsic_LUT(this, s, e); 1012 break; 1013 case RS_SCRIPT_INTRINSIC_ID_CONVOLVE_5x5: 1014 i = rsdIntrinsic_Convolve5x5(this, s, e); 1015 break; 1016 case RS_SCRIPT_INTRINSIC_ID_BLUR: 1017 i = rsdIntrinsic_Blur(this, s, e); 1018 break; 1019 case RS_SCRIPT_INTRINSIC_ID_YUV_TO_RGB: 1020 i = rsdIntrinsic_YuvToRGB(this, s, e); 1021 break; 1022 case RS_SCRIPT_INTRINSIC_ID_BLEND: 1023 i = rsdIntrinsic_Blend(this, s, e); 1024 break; 1025 case RS_SCRIPT_INTRINSIC_ID_HISTOGRAM: 1026 i = rsdIntrinsic_Histogram(this, s, e); 1027 break; 1028 case RS_SCRIPT_INTRINSIC_ID_RESIZE: 1029 i = rsdIntrinsic_Resize(this, s, e); 1030 break; 1031 case RS_SCRIPT_INTRINSIC_ID_BLAS: 1032 i = rsdIntrinsic_BLAS(this, s, e); 1033 break; 1034 1035 default: 1036 rsAssert(0); 1037 } 1038 1039 return i; 1040} 1041 1042void* RsdCpuReferenceImpl::createScriptGroup(const ScriptGroupBase *sg) { 1043 switch (sg->getApiVersion()) { 1044 case ScriptGroupBase::SG_V1: { 1045 CpuScriptGroupImpl *sgi = new CpuScriptGroupImpl(this, sg); 1046 if (!sgi->init()) { 1047 delete sgi; 1048 return nullptr; 1049 } 1050 return sgi; 1051 } 1052 case ScriptGroupBase::SG_V2: { 1053 return new CpuScriptGroup2Impl(this, sg); 1054 } 1055 } 1056 return nullptr; 1057} 1058