rsCpuScript.cpp revision 87643a32d4eaefe349d3a81513fffe0c4e3e8a80
1/* 2 * Copyright (C) 2011-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 "rsCpuExecutable.h" 20 21#ifdef RS_COMPATIBILITY_LIB 22 #include <stdio.h> 23 #include <sys/stat.h> 24 #include <unistd.h> 25#else 26 #include "rsCppUtils.h" 27 28 #include <bcc/Config/Config.h> 29 #include <bcinfo/MetadataExtractor.h> 30 #include <cutils/properties.h> 31 32 #include <zlib.h> 33 #include <sys/file.h> 34 #include <sys/types.h> 35 #include <unistd.h> 36 37 #include <string> 38 #include <vector> 39#endif 40 41#include <set> 42#include <string> 43#include <dlfcn.h> 44#include <stdlib.h> 45#include <string.h> 46#include <iostream> 47#include <sstream> 48 49namespace { 50 51static const bool kDebugGlobalVariables = false; 52 53static bool allocationLODIsNull(const android::renderscript::Allocation *alloc) { 54 // Even if alloc != nullptr, mallocPtr could be null if 55 // IO_OUTPUT/IO_INPUT with no bound surface. 56 return alloc && alloc->mHal.drvState.lod[0].mallocPtr == nullptr; 57} 58 59#ifndef RS_COMPATIBILITY_LIB 60 61static bool is_force_recompile() { 62#ifdef RS_SERVER 63 return false; 64#else 65 char buf[PROPERTY_VALUE_MAX]; 66 67 // Re-compile if floating point precision has been overridden. 68 property_get("debug.rs.precision", buf, ""); 69 if (buf[0] != '\0') { 70 return true; 71 } 72 73 // Re-compile if debug.rs.forcerecompile is set. 74 property_get("debug.rs.forcerecompile", buf, "0"); 75 if ((::strcmp(buf, "1") == 0) || (::strcmp(buf, "true") == 0)) { 76 return true; 77 } else { 78 return false; 79 } 80#endif // RS_SERVER 81} 82 83static void setCompileArguments(std::vector<const char*>* args, 84 const std::string& bcFileName, 85 const char* cacheDir, const char* resName, 86 const char* core_lib, bool useRSDebugContext, 87 const char* bccPluginName, bool emitGlobalInfo, 88 int optLevel, bool emitGlobalInfoSkipConstant) { 89 rsAssert(cacheDir && resName && core_lib); 90 args->push_back(android::renderscript::RsdCpuScriptImpl::BCC_EXE_PATH); 91 args->push_back("-unroll-runtime"); 92 args->push_back("-scalarize-load-store"); 93 if (emitGlobalInfo) { 94 args->push_back("-rs-global-info"); 95 if (emitGlobalInfoSkipConstant) { 96 args->push_back("-rs-global-info-skip-constant"); 97 } 98 } 99 args->push_back("-o"); 100 args->push_back(resName); 101 args->push_back("-output_path"); 102 args->push_back(cacheDir); 103 args->push_back("-bclib"); 104 args->push_back(core_lib); 105 args->push_back("-mtriple"); 106 args->push_back(DEFAULT_TARGET_TRIPLE_STRING); 107 args->push_back("-O"); 108 109 switch (optLevel) { 110 case 0: 111 args->push_back("0"); 112 break; 113 case 3: 114 args->push_back("3"); 115 break; 116 default: 117 ALOGW("Expected optimization level of 0 or 3. Received %d", optLevel); 118 args->push_back("3"); 119 break; 120 } 121 122 // Enable workaround for A53 codegen by default. 123#if defined(__aarch64__) && !defined(DISABLE_A53_WORKAROUND) 124 args->push_back("-aarch64-fix-cortex-a53-835769"); 125#endif 126 127 // Execute the bcc compiler. 128 if (useRSDebugContext) { 129 args->push_back("-rs-debug-ctx"); 130 } else { 131 // Only load additional libraries for compiles that don't use 132 // the debug context. 133 if (bccPluginName && strlen(bccPluginName) > 0) { 134 args->push_back("-load"); 135 args->push_back(bccPluginName); 136 } 137 } 138 139 args->push_back("-fPIC"); 140 args->push_back("-embedRSInfo"); 141 142 args->push_back(bcFileName.c_str()); 143 args->push_back(nullptr); 144} 145 146static bool compileBitcode(const std::string &bcFileName, 147 const char *bitcode, 148 size_t bitcodeSize, 149 std::vector<const char *> &compileArguments) { 150 rsAssert(bitcode && bitcodeSize); 151 152 FILE *bcfile = fopen(bcFileName.c_str(), "w"); 153 if (!bcfile) { 154 ALOGE("Could not write to %s", bcFileName.c_str()); 155 return false; 156 } 157 size_t nwritten = fwrite(bitcode, 1, bitcodeSize, bcfile); 158 fclose(bcfile); 159 if (nwritten != bitcodeSize) { 160 ALOGE("Could not write %zu bytes to %s", bitcodeSize, 161 bcFileName.c_str()); 162 return false; 163 } 164 165 return android::renderscript::rsuExecuteCommand( 166 android::renderscript::RsdCpuScriptImpl::BCC_EXE_PATH, 167 compileArguments.size()-1, compileArguments.data()); 168} 169 170// The checksum is unnecessary under a few conditions, since the primary 171// use-case for it is debugging. If we are loading something from the 172// system partition (read-only), we know that it was precompiled as part of 173// application ahead of time (and thus the checksum is completely 174// unnecessary). The checksum is also unnecessary on release (non-debug) 175// builds, as the only way to get a shared object is to have compiled the 176// script once already. On a release build, there is no way to adjust the 177// other libraries/dependencies, and so the only reason to recompile would 178// be for a source APK change or an OTA. In either case, the APK would be 179// reinstalled, which would already clear the code_cache/ directory. 180bool isChecksumNeeded(const char *cacheDir) { 181 if ((::strcmp(SYSLIBPATH, cacheDir) == 0) || 182 (::strcmp(SYSLIBPATH_VENDOR, cacheDir) == 0)) 183 return false; 184 char buf[PROPERTY_VALUE_MAX]; 185 property_get("ro.debuggable", buf, ""); 186 return (buf[0] == '1'); 187} 188 189bool addFileToChecksum(const char *fileName, uint32_t &checksum) { 190 int FD = open(fileName, O_RDONLY); 191 if (FD == -1) { 192 ALOGE("Cannot open file \'%s\' to compute checksum", fileName); 193 return false; 194 } 195 196 char buf[256]; 197 while (true) { 198 ssize_t nread = read(FD, buf, sizeof(buf)); 199 if (nread < 0) { // bail out on failed read 200 ALOGE("Error while computing checksum for file \'%s\'", fileName); 201 return false; 202 } 203 204 checksum = adler32(checksum, (const unsigned char *) buf, nread); 205 if (static_cast<size_t>(nread) < sizeof(buf)) // EOF 206 break; 207 } 208 209 if (close(FD) != 0) { 210 ALOGE("Cannot close file \'%s\' after computing checksum", fileName); 211 return false; 212 } 213 return true; 214} 215 216#endif // !defined(RS_COMPATIBILITY_LIB) 217} // namespace 218 219namespace android { 220namespace renderscript { 221 222#ifndef RS_COMPATIBILITY_LIB 223 224uint32_t constructBuildChecksum(uint8_t const *bitcode, size_t bitcodeSize, 225 const char *commandLine, 226 const char** bccFiles, size_t numFiles) { 227 uint32_t checksum = adler32(0L, Z_NULL, 0); 228 229 // include checksum of bitcode 230 if (bitcode != nullptr && bitcodeSize > 0) { 231 checksum = adler32(checksum, bitcode, bitcodeSize); 232 } 233 234 // include checksum of command line arguments 235 checksum = adler32(checksum, (const unsigned char *) commandLine, 236 strlen(commandLine)); 237 238 // include checksum of bccFiles 239 for (size_t i = 0; i < numFiles; i++) { 240 const char* bccFile = bccFiles[i]; 241 if (bccFile[0] != 0 && !addFileToChecksum(bccFile, checksum)) { 242 // return empty checksum instead of something partial/corrupt 243 return 0; 244 } 245 } 246 247 return checksum; 248} 249 250#endif // !RS_COMPATIBILITY_LIB 251 252RsdCpuScriptImpl::RsdCpuScriptImpl(RsdCpuReferenceImpl *ctx, const Script *s) { 253 mCtx = ctx; 254 mScript = s; 255 256 mScriptSO = nullptr; 257 258 mRoot = nullptr; 259 mRootExpand = nullptr; 260 mInit = nullptr; 261 mFreeChildren = nullptr; 262 mScriptExec = nullptr; 263 264 mBoundAllocs = nullptr; 265 mIntrinsicData = nullptr; 266 mIsThreadable = true; 267 268 mBuildChecksum = 0; 269 mChecksumNeeded = false; 270} 271 272bool RsdCpuScriptImpl::storeRSInfoFromSO() { 273 // The shared object may have an invalid build checksum. 274 // Validate and fail early. 275 mScriptExec = ScriptExecutable::createFromSharedObject( 276 mScriptSO, mChecksumNeeded ? mBuildChecksum : 0); 277 278 if (mScriptExec == nullptr) { 279 return false; 280 } 281 282 mRoot = (RootFunc_t) dlsym(mScriptSO, "root"); 283 if (mRoot) { 284 //ALOGE("Found root(): %p", mRoot); 285 } 286 mRootExpand = (RootFunc_t) dlsym(mScriptSO, "root.expand"); 287 if (mRootExpand) { 288 //ALOGE("Found root.expand(): %p", mRootExpand); 289 } 290 mInit = (InitOrDtorFunc_t) dlsym(mScriptSO, "init"); 291 if (mInit) { 292 //ALOGE("Found init(): %p", mInit); 293 } 294 mFreeChildren = (InitOrDtorFunc_t) dlsym(mScriptSO, ".rs.dtor"); 295 if (mFreeChildren) { 296 //ALOGE("Found .rs.dtor(): %p", mFreeChildren); 297 } 298 299 size_t varCount = mScriptExec->getExportedVariableCount(); 300 if (varCount > 0) { 301 mBoundAllocs = new Allocation *[varCount]; 302 memset(mBoundAllocs, 0, varCount * sizeof(*mBoundAllocs)); 303 } 304 305 mIsThreadable = mScriptExec->getThreadable(); 306 //ALOGE("Script isThreadable? %d", mIsThreadable); 307 308 if (kDebugGlobalVariables) { 309 mScriptExec->dumpGlobalInfo(); 310 } 311 312 return true; 313} 314 315bool RsdCpuScriptImpl::init(char const *resName, char const *cacheDir, 316 uint8_t const *bitcode, size_t bitcodeSize, 317 uint32_t flags, char const *bccPluginName) { 318 //ALOGE("rsdScriptCreate %p %p %p %p %i %i %p", rsc, resName, cacheDir, 319 // bitcode, bitcodeSize, flags, lookupFunc); 320 //ALOGE("rsdScriptInit %p %p", rsc, script); 321 322 mCtx->lockMutex(); 323#ifndef RS_COMPATIBILITY_LIB 324 bool useRSDebugContext = false; 325 326 bcinfo::MetadataExtractor bitcodeMetadata((const char *) bitcode, bitcodeSize); 327 if (!bitcodeMetadata.extract()) { 328 ALOGE("Could not extract metadata from bitcode"); 329 mCtx->unlockMutex(); 330 return false; 331 } 332 333 const char* core_lib = findCoreLib(bitcodeMetadata, (const char*)bitcode, bitcodeSize); 334 335 if (mCtx->getContext()->getContextType() == RS_CONTEXT_TYPE_DEBUG) { 336 useRSDebugContext = true; 337 } 338 339 int optLevel = mCtx->getContext()->getOptLevel(); 340 341 std::string bcFileName(cacheDir); 342 bcFileName.append("/"); 343 bcFileName.append(resName); 344 bcFileName.append(".bc"); 345 346 std::vector<const char*> compileArguments; 347 bool emitGlobalInfo = mCtx->getEmbedGlobalInfo(); 348 bool emitGlobalInfoSkipConstant = mCtx->getEmbedGlobalInfoSkipConstant(); 349 setCompileArguments(&compileArguments, bcFileName, cacheDir, resName, core_lib, 350 useRSDebugContext, bccPluginName, emitGlobalInfo, 351 optLevel, emitGlobalInfoSkipConstant); 352 353 mChecksumNeeded = isChecksumNeeded(cacheDir); 354 if (mChecksumNeeded) { 355 std::vector<const char *> bccFiles = { BCC_EXE_PATH, 356 core_lib, 357 }; 358 359 // The last argument of compileArguments is a nullptr, so remove 1 from 360 // the size. 361 std::unique_ptr<const char> compileCommandLine( 362 rsuJoinStrings(compileArguments.size()-1, compileArguments.data())); 363 364 mBuildChecksum = constructBuildChecksum(bitcode, bitcodeSize, 365 compileCommandLine.get(), 366 bccFiles.data(), bccFiles.size()); 367 368 if (mBuildChecksum == 0) { 369 // cannot compute checksum but verification is enabled 370 mCtx->unlockMutex(); 371 return false; 372 } 373 } 374 else { 375 // add a dummy/constant as a checksum if verification is disabled 376 mBuildChecksum = 0xabadcafe; 377 } 378 379 // Append build checksum to commandline 380 // Handle the terminal nullptr in compileArguments 381 compileArguments.pop_back(); 382 compileArguments.push_back("-build-checksum"); 383 std::stringstream ss; 384 ss << std::hex << mBuildChecksum; 385 compileArguments.push_back(ss.str().c_str()); 386 compileArguments.push_back(nullptr); 387 388 if (!is_force_recompile() && !useRSDebugContext) { 389 mScriptSO = SharedLibraryUtils::loadSharedLibrary(cacheDir, resName); 390 391 // Read RS info from the shared object to detect checksum mismatch 392 if (mScriptSO != nullptr && !storeRSInfoFromSO()) { 393 dlclose(mScriptSO); 394 mScriptSO = nullptr; 395 } 396 } 397 398 // If we can't, it's either not there or out of date. We compile the bit code and try loading 399 // again. 400 if (mScriptSO == nullptr) { 401 if (!compileBitcode(bcFileName, (const char*)bitcode, bitcodeSize, 402 compileArguments)) 403 { 404 ALOGE("bcc: FAILS to compile '%s'", resName); 405 mCtx->unlockMutex(); 406 return false; 407 } 408 409 if (!SharedLibraryUtils::createSharedLibrary(mCtx->getContext()->getDriverName(), 410 cacheDir, resName)) { 411 ALOGE("Linker: Failed to link object file '%s'", resName); 412 mCtx->unlockMutex(); 413 return false; 414 } 415 416 mScriptSO = SharedLibraryUtils::loadSharedLibrary(cacheDir, resName); 417 if (mScriptSO == nullptr) { 418 ALOGE("Unable to load '%s'", resName); 419 mCtx->unlockMutex(); 420 return false; 421 } 422 423 // Read RS symbol information from the .so. 424 if (!storeRSInfoFromSO()) { 425 goto error; 426 } 427 } 428 429 mBitcodeFilePath.setTo(bcFileName.c_str()); 430 431#else // RS_COMPATIBILITY_LIB is defined 432 const char *nativeLibDir = mCtx->getContext()->getNativeLibDir(); 433 mScriptSO = SharedLibraryUtils::loadSharedLibrary(cacheDir, resName, nativeLibDir); 434 435 if (!mScriptSO) { 436 goto error; 437 } 438 439 if (!storeRSInfoFromSO()) { 440 goto error; 441 } 442#endif 443 mCtx->unlockMutex(); 444 return true; 445 446error: 447 448 mCtx->unlockMutex(); 449 if (mScriptSO) { 450 dlclose(mScriptSO); 451 mScriptSO = nullptr; 452 } 453 return false; 454} 455 456#ifndef RS_COMPATIBILITY_LIB 457 458const char* RsdCpuScriptImpl::findCoreLib(const bcinfo::MetadataExtractor& ME, const char* bitcode, 459 size_t bitcodeSize) { 460 const char* defaultLib = SYSLIBPATH"/libclcore.bc"; 461 462 // If we're debugging, use the debug library. 463 if (mCtx->getContext()->getContextType() == RS_CONTEXT_TYPE_DEBUG) { 464 return SYSLIBPATH"/libclcore_debug.bc"; 465 } 466 467 if (ME.hasDebugInfo()) { 468 return SYSLIBPATH"/libclcore_g.bc"; 469 } 470 471 // If a callback has been registered to specify a library, use that. 472 RSSelectRTCallback selectRTCallback = mCtx->getSelectRTCallback(); 473 if (selectRTCallback != nullptr) { 474 return selectRTCallback((const char*)bitcode, bitcodeSize); 475 } 476 477 // Check for a platform specific library 478#if defined(ARCH_ARM_HAVE_NEON) && !defined(DISABLE_CLCORE_NEON) 479 enum bcinfo::RSFloatPrecision prec = ME.getRSFloatPrecision(); 480 if (prec == bcinfo::RS_FP_Relaxed) { 481 // NEON-capable ARMv7a devices can use an accelerated math library 482 // for all reduced precision scripts. 483 // ARMv8 does not use NEON, as ASIMD can be used with all precision 484 // levels. 485 return SYSLIBPATH"/libclcore_neon.bc"; 486 } else { 487 return defaultLib; 488 } 489#elif defined(__i386__) || defined(__x86_64__) 490 // x86 devices will use an optimized library. 491 return SYSLIBPATH"/libclcore_x86.bc"; 492#else 493 return defaultLib; 494#endif 495} 496 497#endif 498 499void RsdCpuScriptImpl::populateScript(Script *script) { 500 // Copy info over to runtime 501 script->mHal.info.exportedFunctionCount = mScriptExec->getExportedFunctionCount(); 502 script->mHal.info.exportedReduceCount = mScriptExec->getExportedReduceCount(); 503 script->mHal.info.exportedReduceNewCount = mScriptExec->getExportedReduceNewCount(); 504 script->mHal.info.exportedForEachCount = mScriptExec->getExportedForEachCount(); 505 script->mHal.info.exportedVariableCount = mScriptExec->getExportedVariableCount(); 506 script->mHal.info.exportedPragmaCount = mScriptExec->getPragmaCount();; 507 script->mHal.info.exportedPragmaKeyList = mScriptExec->getPragmaKeys(); 508 script->mHal.info.exportedPragmaValueList = mScriptExec->getPragmaValues(); 509 510 // Bug, need to stash in metadata 511 if (mRootExpand) { 512 script->mHal.info.root = mRootExpand; 513 } else { 514 script->mHal.info.root = mRoot; 515 } 516} 517 518// Set up the launch dimensions, and write the values of the launch 519// dimensions into the mtls start/end fields. 520// 521// Inputs: 522// baseDim - base shape of the input 523// sc - used to constrain the launch dimensions 524// 525// Returns: 526// True on success, false on failure to set up 527bool RsdCpuScriptImpl::setUpMtlsDimensions(MTLaunchStructCommon *mtls, 528 const RsLaunchDimensions &baseDim, 529 const RsScriptCall *sc) { 530 rsAssert(mtls); 531 532#define SET_UP_DIMENSION(DIM_FIELD, SC_FIELD) do { \ 533 if (!sc || (sc->SC_FIELD##End == 0)) { \ 534 mtls->end.DIM_FIELD = baseDim.DIM_FIELD; \ 535 } else { \ 536 mtls->start.DIM_FIELD = \ 537 rsMin(baseDim.DIM_FIELD, sc->SC_FIELD##Start); \ 538 mtls->end.DIM_FIELD = \ 539 rsMin(baseDim.DIM_FIELD, sc->SC_FIELD##End); \ 540 if (mtls->start.DIM_FIELD >= mtls->end.DIM_FIELD) { \ 541 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, \ 542 "Failed to launch kernel; Invalid " \ 543 #SC_FIELD "Start or " #SC_FIELD "End."); \ 544 return false; \ 545 } \ 546 }} while(0) 547 548 SET_UP_DIMENSION(x, x); 549 SET_UP_DIMENSION(y, y); 550 SET_UP_DIMENSION(z, z); 551 // Checks and setup of fields other than x, y, z are ignored, since those 552 // fields are not used in the runtime and are not visible in the Java API. 553#undef SET_UP_DIMENSION 554 555 return true; 556} 557 558// Preliminary work to prepare a simple reduce-style kernel for launch. 559bool RsdCpuScriptImpl::reduceMtlsSetup(const Allocation *ain, 560 const Allocation *aout, 561 const RsScriptCall *sc, 562 MTLaunchStructReduce *mtls) { 563 rsAssert(ain && aout); 564 memset(mtls, 0, sizeof(MTLaunchStructReduce)); 565 mtls->dimPtr = &mtls->inputDim; 566 567 if (allocationLODIsNull(ain) || allocationLODIsNull(aout)) { 568 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 569 "reduce called with a null allocation"); 570 return false; 571 } 572 573 // Set up the dimensions of the input. 574 const Type *inType = ain->getType(); 575 mtls->inputDim.x = inType->getDimX(); 576 rsAssert(inType->getDimY() == 0); 577 578 if (!setUpMtlsDimensions(mtls, mtls->inputDim, sc)) { 579 return false; 580 } 581 582 mtls->rs = mCtx; 583 // Currently not threaded. 584 mtls->isThreadable = false; 585 mtls->mSliceNum = -1; 586 587 // Set up input and output. 588 mtls->inBuf = static_cast<uint8_t *>(ain->getPointerUnchecked(0, 0)); 589 mtls->outBuf = static_cast<uint8_t *>(aout->getPointerUnchecked(0, 0)); 590 591 rsAssert(mtls->inBuf && mtls->outBuf); 592 593 return true; 594} 595 596// Preliminary work to prepare a general reduce-style kernel for launch. 597bool RsdCpuScriptImpl::reduceNewMtlsSetup(const Allocation ** ains, 598 uint32_t inLen, 599 const Allocation * aout, 600 const RsScriptCall *sc, 601 MTLaunchStructReduceNew *mtls) { 602 rsAssert(ains && (inLen >= 1) && aout); 603 memset(mtls, 0, sizeof(MTLaunchStructReduceNew)); 604 mtls->dimPtr = &mtls->redp.dim; 605 606 for (int index = inLen; --index >= 0;) { 607 if (allocationLODIsNull(ains[index])) { 608 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 609 "reduce called with null in allocations"); 610 return false; 611 } 612 } 613 614 if (allocationLODIsNull(aout)) { 615 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 616 "reduce called with null out allocation"); 617 return false; 618 } 619 620 const Allocation *ain0 = ains[0]; 621 const Type *inType = ain0->getType(); 622 623 mtls->redp.dim.x = inType->getDimX(); 624 mtls->redp.dim.y = inType->getDimY(); 625 mtls->redp.dim.z = inType->getDimZ(); 626 627 for (int Index = inLen; --Index >= 1;) { 628 if (!ain0->hasSameDims(ains[Index])) { 629 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 630 "Failed to launch reduction kernel;" 631 "dimensions of input allocations do not match."); 632 return false; 633 } 634 } 635 636 if (!setUpMtlsDimensions(mtls, mtls->redp.dim, sc)) { 637 return false; 638 } 639 640 // The X & Y walkers always want 0-1 min even if dim is not present 641 mtls->end.x = rsMax((uint32_t)1, mtls->end.x); 642 mtls->end.y = rsMax((uint32_t)1, mtls->end.y); 643 644 mtls->rs = mCtx; 645 646 mtls->mSliceNum = 0; 647 mtls->mSliceSize = 1; 648 mtls->isThreadable = mIsThreadable; 649 650 // Set up output, 651 mtls->redp.outLen = 1; 652 mtls->redp.outPtr[0] = (uint8_t *)aout->mHal.drvState.lod[0].mallocPtr; 653 mtls->redp.outStride[0] = aout->getType()->getElementSizeBytes(); 654 655 // Set up input. 656 memcpy(mtls->ains, ains, inLen * sizeof(ains[0])); 657 mtls->redp.inLen = inLen; 658 for (int index = inLen; --index >= 0;) { 659 mtls->redp.inPtr[index] = (const uint8_t*)ains[index]->mHal.drvState.lod[0].mallocPtr; 660 mtls->redp.inStride[index] = ains[index]->getType()->getElementSizeBytes(); 661 } 662 663 // All validation passed, ok to launch threads 664 return true; 665} 666 667// Preliminary work to prepare a forEach-style kernel for launch. 668bool RsdCpuScriptImpl::forEachMtlsSetup(const Allocation ** ains, 669 uint32_t inLen, 670 Allocation * aout, 671 const void * usr, uint32_t usrLen, 672 const RsScriptCall *sc, 673 MTLaunchStructForEach *mtls) { 674 if (ains == nullptr && inLen != 0) { 675 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 676 "rsForEach called with none-zero inLen with null in allocations"); 677 return false; 678 } 679 680 memset(mtls, 0, sizeof(MTLaunchStructForEach)); 681 mtls->dimPtr = &mtls->fep.dim; 682 683 for (int index = inLen; --index >= 0;) { 684 if (allocationLODIsNull(ains[index])) { 685 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 686 "rsForEach called with null in allocations"); 687 return false; 688 } 689 } 690 691 if (allocationLODIsNull(aout)) { 692 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 693 "rsForEach called with null out allocations"); 694 return false; 695 } 696 697 if (inLen > 0) { 698 const Allocation *ain0 = ains[0]; 699 const Type *inType = ain0->getType(); 700 701 mtls->fep.dim.x = inType->getDimX(); 702 mtls->fep.dim.y = inType->getDimY(); 703 mtls->fep.dim.z = inType->getDimZ(); 704 705 for (int Index = inLen; --Index >= 1;) { 706 if (!ain0->hasSameDims(ains[Index])) { 707 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 708 "Failed to launch kernel; dimensions of input" 709 "allocations do not match."); 710 return false; 711 } 712 } 713 } else if (aout != nullptr) { 714 const Type *outType = aout->getType(); 715 716 mtls->fep.dim.x = outType->getDimX(); 717 mtls->fep.dim.y = outType->getDimY(); 718 mtls->fep.dim.z = outType->getDimZ(); 719 720 } else if (sc != nullptr) { 721 mtls->fep.dim.x = sc->xEnd; 722 mtls->fep.dim.y = sc->yEnd; 723 mtls->fep.dim.z = 0; 724 } else { 725 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 726 "rsForEach called with null allocations"); 727 return false; 728 } 729 730 if (inLen > 0 && aout != nullptr) { 731 if (!ains[0]->hasSameDims(aout)) { 732 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, 733 "Failed to launch kernel; dimensions of input and output allocations do not match."); 734 735 return false; 736 } 737 } 738 739 if (!setUpMtlsDimensions(mtls, mtls->fep.dim, sc)) { 740 return false; 741 } 742 743 // The X & Y walkers always want 0-1 min even if dim is not present 744 mtls->end.x = rsMax((uint32_t)1, mtls->end.x); 745 mtls->end.y = rsMax((uint32_t)1, mtls->end.y); 746 mtls->rs = mCtx; 747 if (ains) { 748 memcpy(mtls->ains, ains, inLen * sizeof(ains[0])); 749 } 750 mtls->aout[0] = aout; 751 mtls->fep.usr = usr; 752 mtls->fep.usrLen = usrLen; 753 mtls->mSliceSize = 1; 754 mtls->mSliceNum = 0; 755 756 mtls->isThreadable = mIsThreadable; 757 758 if (inLen > 0) { 759 mtls->fep.inLen = inLen; 760 for (int index = inLen; --index >= 0;) { 761 mtls->fep.inPtr[index] = (const uint8_t*)ains[index]->mHal.drvState.lod[0].mallocPtr; 762 mtls->fep.inStride[index] = ains[index]->getType()->getElementSizeBytes(); 763 } 764 } 765 766 if (aout != nullptr) { 767 mtls->fep.outPtr[0] = (uint8_t *)aout->mHal.drvState.lod[0].mallocPtr; 768 mtls->fep.outStride[0] = aout->getType()->getElementSizeBytes(); 769 } 770 771 // All validation passed, ok to launch threads 772 return true; 773} 774 775 776void RsdCpuScriptImpl::invokeForEach(uint32_t slot, 777 const Allocation ** ains, 778 uint32_t inLen, 779 Allocation * aout, 780 const void * usr, 781 uint32_t usrLen, 782 const RsScriptCall *sc) { 783 784 MTLaunchStructForEach mtls; 785 786 if (forEachMtlsSetup(ains, inLen, aout, usr, usrLen, sc, &mtls)) { 787 forEachKernelSetup(slot, &mtls); 788 789 RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this); 790 mCtx->launchForEach(ains, inLen, aout, sc, &mtls); 791 mCtx->setTLS(oldTLS); 792 } 793} 794 795void RsdCpuScriptImpl::invokeReduce(uint32_t slot, 796 const Allocation *ain, 797 Allocation *aout, 798 const RsScriptCall *sc) { 799 MTLaunchStructReduce mtls; 800 801 if (reduceMtlsSetup(ain, aout, sc, &mtls)) { 802 reduceKernelSetup(slot, &mtls); 803 RsdCpuScriptImpl *oldTLS = mCtx->setTLS(this); 804 mCtx->launchReduce(ain, aout, &mtls); 805 mCtx->setTLS(oldTLS); 806 } 807} 808 809void RsdCpuScriptImpl::invokeReduceNew(uint32_t slot, 810 const Allocation ** ains, uint32_t inLen, 811 Allocation *aout, 812 const RsScriptCall *sc) { 813 MTLaunchStructReduceNew mtls; 814 815 if (reduceNewMtlsSetup(ains, inLen, aout, sc, &mtls)) { 816 reduceNewKernelSetup(slot, &mtls); 817 RsdCpuScriptImpl *oldTLS = mCtx->setTLS(this); 818 mCtx->launchReduceNew(ains, inLen, aout, &mtls); 819 mCtx->setTLS(oldTLS); 820 } 821} 822 823void RsdCpuScriptImpl::forEachKernelSetup(uint32_t slot, MTLaunchStructForEach *mtls) { 824 mtls->script = this; 825 mtls->fep.slot = slot; 826 mtls->kernel = mScriptExec->getForEachFunction(slot); 827 rsAssert(mtls->kernel != nullptr); 828} 829 830void RsdCpuScriptImpl::reduceKernelSetup(uint32_t slot, MTLaunchStructReduce *mtls) { 831 mtls->script = this; 832 mtls->kernel = mScriptExec->getReduceFunction(slot); 833 rsAssert(mtls->kernel != nullptr); 834} 835 836void RsdCpuScriptImpl::reduceNewKernelSetup(uint32_t slot, MTLaunchStructReduceNew *mtls) { 837 mtls->script = this; 838 mtls->redp.slot = slot; 839 840 const ReduceNewDescription *desc = mScriptExec->getReduceNewDescription(slot); 841 mtls->accumFunc = desc->accumFunc; 842 mtls->initFunc = desc->initFunc; // might legally be nullptr 843 mtls->combFunc = desc->combFunc; // might legally be nullptr 844 mtls->outFunc = desc->outFunc; // might legally be nullptr 845 mtls->accumSize = desc->accumSize; 846 847 rsAssert(mtls->accumFunc != nullptr); 848} 849 850int RsdCpuScriptImpl::invokeRoot() { 851 RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this); 852 int ret = mRoot(); 853 mCtx->setTLS(oldTLS); 854 return ret; 855} 856 857void RsdCpuScriptImpl::invokeInit() { 858 if (mInit) { 859 mInit(); 860 } 861} 862 863void RsdCpuScriptImpl::invokeFreeChildren() { 864 if (mFreeChildren) { 865 mFreeChildren(); 866 } 867} 868 869void RsdCpuScriptImpl::invokeFunction(uint32_t slot, const void *params, 870 size_t paramLength) { 871 //ALOGE("invoke %i %p %zu", slot, params, paramLength); 872 void * ap = nullptr; 873 874#if defined(__x86_64__) 875 // The invoked function could have input parameter of vector type for example float4 which 876 // requires void* params to be 16 bytes aligned when using SSE instructions for x86_64 platform. 877 // So try to align void* params before passing them into RS exported function. 878 879 if ((uint8_t)(uint64_t)params & 0x0F) { 880 if ((ap = (void*)memalign(16, paramLength)) != nullptr) { 881 memcpy(ap, params, paramLength); 882 } else { 883 ALOGE("x86_64: invokeFunction memalign error, still use params which" 884 " is not 16 bytes aligned."); 885 } 886 } 887#endif 888 889 RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this); 890 reinterpret_cast<void (*)(const void *, uint32_t)>( 891 mScriptExec->getInvokeFunction(slot))(ap? (const void *) ap: params, paramLength); 892 893#if defined(__x86_64__) 894 free(ap); 895#endif 896 897 mCtx->setTLS(oldTLS); 898} 899 900void RsdCpuScriptImpl::setGlobalVar(uint32_t slot, const void *data, size_t dataLength) { 901 //rsAssert(!script->mFieldIsObject[slot]); 902 //ALOGE("setGlobalVar %i %p %zu", slot, data, dataLength); 903 904 //if (mIntrinsicID) { 905 //mIntrinsicFuncs.setVar(dc, script, drv->mIntrinsicData, slot, data, dataLength); 906 //return; 907 //} 908 909 int32_t *destPtr = reinterpret_cast<int32_t *>(mScriptExec->getFieldAddress(slot)); 910 if (!destPtr) { 911 //ALOGV("Calling setVar on slot = %i which is null", slot); 912 return; 913 } 914 915 memcpy(destPtr, data, dataLength); 916} 917 918void RsdCpuScriptImpl::getGlobalVar(uint32_t slot, void *data, size_t dataLength) { 919 //rsAssert(!script->mFieldIsObject[slot]); 920 //ALOGE("getGlobalVar %i %p %zu", slot, data, dataLength); 921 922 int32_t *srcPtr = reinterpret_cast<int32_t *>(mScriptExec->getFieldAddress(slot)); 923 if (!srcPtr) { 924 //ALOGV("Calling setVar on slot = %i which is null", slot); 925 return; 926 } 927 memcpy(data, srcPtr, dataLength); 928} 929 930 931void RsdCpuScriptImpl::setGlobalVarWithElemDims(uint32_t slot, const void *data, size_t dataLength, 932 const Element *elem, 933 const uint32_t *dims, size_t dimLength) { 934 int32_t *destPtr = reinterpret_cast<int32_t *>(mScriptExec->getFieldAddress(slot)); 935 if (!destPtr) { 936 //ALOGV("Calling setVar on slot = %i which is null", slot); 937 return; 938 } 939 940 // We want to look at dimension in terms of integer components, 941 // but dimLength is given in terms of bytes. 942 dimLength /= sizeof(int); 943 944 // Only a single dimension is currently supported. 945 rsAssert(dimLength == 1); 946 if (dimLength == 1) { 947 // First do the increment loop. 948 size_t stride = elem->getSizeBytes(); 949 const char *cVal = reinterpret_cast<const char *>(data); 950 for (uint32_t i = 0; i < dims[0]; i++) { 951 elem->incRefs(cVal); 952 cVal += stride; 953 } 954 955 // Decrement loop comes after (to prevent race conditions). 956 char *oldVal = reinterpret_cast<char *>(destPtr); 957 for (uint32_t i = 0; i < dims[0]; i++) { 958 elem->decRefs(oldVal); 959 oldVal += stride; 960 } 961 } 962 963 memcpy(destPtr, data, dataLength); 964} 965 966void RsdCpuScriptImpl::setGlobalBind(uint32_t slot, Allocation *data) { 967 968 //rsAssert(!script->mFieldIsObject[slot]); 969 //ALOGE("setGlobalBind %i %p", slot, data); 970 971 int32_t *destPtr = reinterpret_cast<int32_t *>(mScriptExec->getFieldAddress(slot)); 972 if (!destPtr) { 973 //ALOGV("Calling setVar on slot = %i which is null", slot); 974 return; 975 } 976 977 void *ptr = nullptr; 978 mBoundAllocs[slot] = data; 979 if (data) { 980 ptr = data->mHal.drvState.lod[0].mallocPtr; 981 } 982 memcpy(destPtr, &ptr, sizeof(void *)); 983} 984 985void RsdCpuScriptImpl::setGlobalObj(uint32_t slot, ObjectBase *data) { 986 987 //rsAssert(script->mFieldIsObject[slot]); 988 //ALOGE("setGlobalObj %i %p", slot, data); 989 990 int32_t *destPtr = reinterpret_cast<int32_t *>(mScriptExec->getFieldAddress(slot)); 991 if (!destPtr) { 992 //ALOGV("Calling setVar on slot = %i which is null", slot); 993 return; 994 } 995 996 rsrSetObject(mCtx->getContext(), (rs_object_base *)destPtr, data); 997} 998 999const char* RsdCpuScriptImpl::getFieldName(uint32_t slot) const { 1000 return mScriptExec->getFieldName(slot); 1001} 1002 1003RsdCpuScriptImpl::~RsdCpuScriptImpl() { 1004 delete mScriptExec; 1005 delete[] mBoundAllocs; 1006 if (mScriptSO) { 1007 dlclose(mScriptSO); 1008 } 1009} 1010 1011Allocation * RsdCpuScriptImpl::getAllocationForPointer(const void *ptr) const { 1012 if (!ptr) { 1013 return nullptr; 1014 } 1015 1016 for (uint32_t ct=0; ct < mScript->mHal.info.exportedVariableCount; ct++) { 1017 Allocation *a = mBoundAllocs[ct]; 1018 if (!a) continue; 1019 if (a->mHal.drvState.lod[0].mallocPtr == ptr) { 1020 return a; 1021 } 1022 } 1023 ALOGE("rsGetAllocation, failed to find %p", ptr); 1024 return nullptr; 1025} 1026 1027int RsdCpuScriptImpl::getGlobalEntries() const { 1028 return mScriptExec->getGlobalEntries(); 1029} 1030 1031const char * RsdCpuScriptImpl::getGlobalName(int i) const { 1032 return mScriptExec->getGlobalName(i); 1033} 1034 1035const void * RsdCpuScriptImpl::getGlobalAddress(int i) const { 1036 return mScriptExec->getGlobalAddress(i); 1037} 1038 1039size_t RsdCpuScriptImpl::getGlobalSize(int i) const { 1040 return mScriptExec->getGlobalSize(i); 1041} 1042 1043uint32_t RsdCpuScriptImpl::getGlobalProperties(int i) const { 1044 return mScriptExec->getGlobalProperties(i); 1045} 1046 1047void RsdCpuScriptImpl::preLaunch(uint32_t slot, const Allocation ** ains, 1048 uint32_t inLen, Allocation * aout, 1049 const void * usr, uint32_t usrLen, 1050 const RsScriptCall *sc) {} 1051 1052void RsdCpuScriptImpl::postLaunch(uint32_t slot, const Allocation ** ains, 1053 uint32_t inLen, Allocation * aout, 1054 const void * usr, uint32_t usrLen, 1055 const RsScriptCall *sc) {} 1056 1057 1058} 1059} 1060