rsCpuScript.cpp revision 3a25fdd3786c1a08b783d8a83ef94b756347ff5c
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
18
19#include "rsCpuCore.h"
20
21#include "rsCpuScript.h"
22//#include "rsdRuntime.h"
23//#include "rsdAllocation.h"
24//#include "rsCpuIntrinsics.h"
25
26
27#include "utils/Vector.h"
28#include "utils/Timers.h"
29#include "utils/StopWatch.h"
30
31
32#include <bcc/BCCContext.h>
33#include <bcc/Renderscript/RSCompilerDriver.h>
34#include <bcc/Renderscript/RSExecutable.h>
35#include <bcc/Renderscript/RSInfo.h>
36
37namespace android {
38namespace renderscript {
39
40
41
42RsdCpuScriptImpl::RsdCpuScriptImpl(RsdCpuReferenceImpl *ctx, const Script *s) {
43    mCtx = ctx;
44    mScript = s;
45
46    mRoot = NULL;
47    mRootExpand = NULL;
48    mInit = NULL;
49    mFreeChildren = NULL;
50
51    mCompilerContext = NULL;
52    mCompilerDriver = NULL;
53    mExecutable = NULL;
54
55    mBoundAllocs = NULL;
56    mIntrinsicData = NULL;
57    mIsThreadable = true;
58}
59
60
61bool RsdCpuScriptImpl::init(char const *resName, char const *cacheDir,
62                            uint8_t const *bitcode, size_t bitcodeSize,
63                            uint32_t flags) {
64    //ALOGE("rsdScriptCreate %p %p %p %p %i %i %p", rsc, resName, cacheDir, bitcode, bitcodeSize, flags, lookupFunc);
65    //ALOGE("rsdScriptInit %p %p", rsc, script);
66
67    mCtx->lockMutex();
68
69    bcc::RSExecutable *exec;
70    const bcc::RSInfo *info;
71
72    mCompilerContext = NULL;
73    mCompilerDriver = NULL;
74    mExecutable = NULL;
75
76    mCompilerContext = new bcc::BCCContext();
77    if (mCompilerContext == NULL) {
78        ALOGE("bcc: FAILS to create compiler context (out of memory)");
79        mCtx->unlockMutex();
80        return false;
81    }
82
83    mCompilerDriver = new bcc::RSCompilerDriver();
84    if (mCompilerDriver == NULL) {
85        ALOGE("bcc: FAILS to create compiler driver (out of memory)");
86        mCtx->unlockMutex();
87        return false;
88    }
89
90    mCompilerDriver->setRSRuntimeLookupFunction(lookupRuntimeStub);
91    mCompilerDriver->setRSRuntimeLookupContext(this);
92
93    exec = mCompilerDriver->build(*mCompilerContext, cacheDir, resName,
94                                  (const char *)bitcode, bitcodeSize, NULL,
95                                  mCtx->getLinkRuntimeCallback());
96
97    if (exec == NULL) {
98        ALOGE("bcc: FAILS to prepare executable for '%s'", resName);
99        mCtx->unlockMutex();
100        return false;
101    }
102
103    mExecutable = exec;
104
105    exec->setThreadable(mIsThreadable);
106    if (!exec->syncInfo()) {
107        ALOGW("bcc: FAILS to synchronize the RS info file to the disk");
108    }
109
110    mRoot = reinterpret_cast<int (*)()>(exec->getSymbolAddress("root"));
111    mRootExpand =
112        reinterpret_cast<int (*)()>(exec->getSymbolAddress("root.expand"));
113    mInit = reinterpret_cast<void (*)()>(exec->getSymbolAddress("init"));
114    mFreeChildren =
115        reinterpret_cast<void (*)()>(exec->getSymbolAddress(".rs.dtor"));
116
117
118    info = &mExecutable->getInfo();
119    if (info->getExportVarNames().size()) {
120        mBoundAllocs = new Allocation *[info->getExportVarNames().size()];
121        memset(mBoundAllocs, 0, sizeof(void *) * info->getExportVarNames().size());
122    }
123
124    mCtx->unlockMutex();
125    return true;
126}
127
128void RsdCpuScriptImpl::populateScript(Script *script) {
129    const bcc::RSInfo *info = &mExecutable->getInfo();
130
131    // Copy info over to runtime
132    script->mHal.info.exportedFunctionCount = info->getExportFuncNames().size();
133    script->mHal.info.exportedVariableCount = info->getExportVarNames().size();
134    script->mHal.info.exportedPragmaCount = info->getPragmas().size();
135    script->mHal.info.exportedPragmaKeyList =
136        const_cast<const char**>(mExecutable->getPragmaKeys().array());
137    script->mHal.info.exportedPragmaValueList =
138        const_cast<const char**>(mExecutable->getPragmaValues().array());
139
140    if (mRootExpand) {
141        script->mHal.info.root = mRootExpand;
142    } else {
143        script->mHal.info.root = mRoot;
144    }
145}
146
147/*
148bool rsdInitIntrinsic(const Context *rsc, Script *s, RsScriptIntrinsicID iid, Element *e) {
149    pthread_mutex_lock(&rsdgInitMutex);
150
151    DrvScript *drv = (DrvScript *)calloc(1, sizeof(DrvScript));
152    if (drv == NULL) {
153        goto error;
154    }
155    s->mHal.drv = drv;
156    drv->mIntrinsicID = iid;
157    drv->mIntrinsicData = rsdIntrinsic_Init(rsc, s, iid, &drv->mIntrinsicFuncs);
158    s->mHal.info.isThreadable = true;
159
160    pthread_mutex_unlock(&rsdgInitMutex);
161    return true;
162
163error:
164    pthread_mutex_unlock(&rsdgInitMutex);
165    return false;
166}
167*/
168
169typedef void (*rs_t)(const void *, void *, const void *, uint32_t, uint32_t, uint32_t, uint32_t);
170
171void RsdCpuScriptImpl::forEachMtlsSetup(const Allocation * ain, Allocation * aout,
172                                        const void * usr, uint32_t usrLen,
173                                        const RsScriptCall *sc,
174                                        MTLaunchStruct *mtls) {
175
176    memset(mtls, 0, sizeof(MTLaunchStruct));
177
178    // possible for this to occur if IO_OUTPUT/IO_INPUT with no bound surface
179    if (ain && (const uint8_t *)ain->mHal.drvState.lod[0].mallocPtr == NULL) {
180        mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, "rsForEach called with null allocations");
181        return;
182    }
183    if (aout && (const uint8_t *)aout->mHal.drvState.lod[0].mallocPtr == NULL) {
184        mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, "rsForEach called with null allocations");
185        return;
186    }
187
188    if (ain) {
189        mtls->fep.dimX = ain->getType()->getDimX();
190        mtls->fep.dimY = ain->getType()->getDimY();
191        mtls->fep.dimZ = ain->getType()->getDimZ();
192        //mtls->dimArray = ain->getType()->getDimArray();
193    } else if (aout) {
194        mtls->fep.dimX = aout->getType()->getDimX();
195        mtls->fep.dimY = aout->getType()->getDimY();
196        mtls->fep.dimZ = aout->getType()->getDimZ();
197        //mtls->dimArray = aout->getType()->getDimArray();
198    } else {
199        mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT, "rsForEach called with null allocations");
200        return;
201    }
202
203    if (!sc || (sc->xEnd == 0)) {
204        mtls->xEnd = mtls->fep.dimX;
205    } else {
206        rsAssert(sc->xStart < mtls->fep.dimX);
207        rsAssert(sc->xEnd <= mtls->fep.dimX);
208        rsAssert(sc->xStart < sc->xEnd);
209        mtls->xStart = rsMin(mtls->fep.dimX, sc->xStart);
210        mtls->xEnd = rsMin(mtls->fep.dimX, sc->xEnd);
211        if (mtls->xStart >= mtls->xEnd) return;
212    }
213
214    if (!sc || (sc->yEnd == 0)) {
215        mtls->yEnd = mtls->fep.dimY;
216    } else {
217        rsAssert(sc->yStart < mtls->fep.dimY);
218        rsAssert(sc->yEnd <= mtls->fep.dimY);
219        rsAssert(sc->yStart < sc->yEnd);
220        mtls->yStart = rsMin(mtls->fep.dimY, sc->yStart);
221        mtls->yEnd = rsMin(mtls->fep.dimY, sc->yEnd);
222        if (mtls->yStart >= mtls->yEnd) return;
223    }
224
225    if (!sc || (sc->zEnd == 0)) {
226        mtls->zEnd = mtls->fep.dimZ;
227    } else {
228        rsAssert(sc->zStart < mtls->fep.dimZ);
229        rsAssert(sc->zEnd <= mtls->fep.dimZ);
230        rsAssert(sc->zStart < sc->zEnd);
231        mtls->zStart = rsMin(mtls->fep.dimZ, sc->zStart);
232        mtls->zEnd = rsMin(mtls->fep.dimZ, sc->zEnd);
233        if (mtls->zStart >= mtls->zEnd) return;
234    }
235
236    mtls->xEnd = rsMax((uint32_t)1, mtls->xEnd);
237    mtls->yEnd = rsMax((uint32_t)1, mtls->yEnd);
238    mtls->zEnd = rsMax((uint32_t)1, mtls->zEnd);
239    mtls->arrayEnd = rsMax((uint32_t)1, mtls->arrayEnd);
240
241    rsAssert(!ain || (ain->getType()->getDimZ() == 0));
242
243    mtls->rsc = mCtx;
244    mtls->ain = ain;
245    mtls->aout = aout;
246    mtls->fep.usr = usr;
247    mtls->fep.usrLen = usrLen;
248    mtls->mSliceSize = 1;
249    mtls->mSliceNum = 0;
250
251    mtls->fep.ptrIn = NULL;
252    mtls->fep.eStrideIn = 0;
253    mtls->isThreadable = mIsThreadable;
254
255    if (ain) {
256        mtls->fep.ptrIn = (const uint8_t *)ain->mHal.drvState.lod[0].mallocPtr;
257        mtls->fep.eStrideIn = ain->getType()->getElementSizeBytes();
258        mtls->fep.yStrideIn = ain->mHal.drvState.lod[0].stride;
259    }
260
261    mtls->fep.ptrOut = NULL;
262    mtls->fep.eStrideOut = 0;
263    if (aout) {
264        mtls->fep.ptrOut = (uint8_t *)aout->mHal.drvState.lod[0].mallocPtr;
265        mtls->fep.eStrideOut = aout->getType()->getElementSizeBytes();
266        mtls->fep.yStrideOut = aout->mHal.drvState.lod[0].stride;
267    }
268}
269
270
271void RsdCpuScriptImpl::invokeForEach(uint32_t slot,
272                                     const Allocation * ain,
273                                     Allocation * aout,
274                                     const void * usr,
275                                     uint32_t usrLen,
276                                     const RsScriptCall *sc) {
277
278    MTLaunchStruct mtls;
279    forEachMtlsSetup(ain, aout, usr, usrLen, sc, &mtls);
280    forEachKernelSetup(slot, &mtls);
281
282    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
283    mCtx->launchThreads(ain, aout, sc, &mtls);
284    mCtx->setTLS(oldTLS);
285}
286
287void RsdCpuScriptImpl::forEachKernelSetup(uint32_t slot, MTLaunchStruct *mtls) {
288
289    mtls->script = this;
290    mtls->fep.slot = slot;
291
292    rsAssert(slot < mExecutable->getExportForeachFuncAddrs().size());
293    mtls->kernel = reinterpret_cast<ForEachFunc_t>(
294                      mExecutable->getExportForeachFuncAddrs()[slot]);
295    rsAssert(mtls->kernel != NULL);
296    mtls->sig = mExecutable->getInfo().getExportForeachFuncs()[slot].second;
297}
298
299int RsdCpuScriptImpl::invokeRoot() {
300    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
301    int ret = mRoot();
302    mCtx->setTLS(oldTLS);
303    return ret;
304}
305
306void RsdCpuScriptImpl::invokeInit() {
307    if (mInit) {
308        mInit();
309    }
310}
311
312void RsdCpuScriptImpl::invokeFreeChildren() {
313    if (mFreeChildren) {
314        mFreeChildren();
315    }
316}
317
318void RsdCpuScriptImpl::invokeFunction(uint32_t slot, const void *params,
319                                      size_t paramLength) {
320    //ALOGE("invoke %p %p %i %p %i", dc, script, slot, params, paramLength);
321
322    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
323    reinterpret_cast<void (*)(const void *, uint32_t)>(
324        mExecutable->getExportFuncAddrs()[slot])(params, paramLength);
325    mCtx->setTLS(oldTLS);
326}
327
328void RsdCpuScriptImpl::setGlobalVar(uint32_t slot, const void *data, size_t dataLength) {
329    //rsAssert(!script->mFieldIsObject[slot]);
330    //ALOGE("setGlobalVar %p %p %i %p %i", dc, script, slot, data, dataLength);
331
332    //if (mIntrinsicID) {
333        //mIntrinsicFuncs.setVar(dc, script, drv->mIntrinsicData, slot, data, dataLength);
334        //return;
335    //}
336
337    int32_t *destPtr = reinterpret_cast<int32_t *>(
338                          mExecutable->getExportVarAddrs()[slot]);
339    if (!destPtr) {
340        //ALOGV("Calling setVar on slot = %i which is null", slot);
341        return;
342    }
343
344    memcpy(destPtr, data, dataLength);
345}
346
347void RsdCpuScriptImpl::setGlobalVarWithElemDims(uint32_t slot, const void *data, size_t dataLength,
348                                                const Element *elem,
349                                                const size_t *dims, size_t dimLength) {
350
351    int32_t *destPtr = reinterpret_cast<int32_t *>(
352        mExecutable->getExportVarAddrs()[slot]);
353    if (!destPtr) {
354        //ALOGV("Calling setVar on slot = %i which is null", slot);
355        return;
356    }
357
358    // We want to look at dimension in terms of integer components,
359    // but dimLength is given in terms of bytes.
360    dimLength /= sizeof(int);
361
362    // Only a single dimension is currently supported.
363    rsAssert(dimLength == 1);
364    if (dimLength == 1) {
365        // First do the increment loop.
366        size_t stride = elem->getSizeBytes();
367        const char *cVal = reinterpret_cast<const char *>(data);
368        for (size_t i = 0; i < dims[0]; i++) {
369            elem->incRefs(cVal);
370            cVal += stride;
371        }
372
373        // Decrement loop comes after (to prevent race conditions).
374        char *oldVal = reinterpret_cast<char *>(destPtr);
375        for (size_t i = 0; i < dims[0]; i++) {
376            elem->decRefs(oldVal);
377            oldVal += stride;
378        }
379    }
380
381    memcpy(destPtr, data, dataLength);
382}
383
384void RsdCpuScriptImpl::setGlobalBind(uint32_t slot, Allocation *data) {
385
386    //rsAssert(!script->mFieldIsObject[slot]);
387    //ALOGE("setGlobalBind %p %p %i %p", dc, script, slot, data);
388
389    int32_t *destPtr = reinterpret_cast<int32_t *>(
390                          mExecutable->getExportVarAddrs()[slot]);
391    if (!destPtr) {
392        //ALOGV("Calling setVar on slot = %i which is null", slot);
393        return;
394    }
395
396    void *ptr = NULL;
397    mBoundAllocs[slot] = data;
398    if(data) {
399        ptr = data->mHal.drvState.lod[0].mallocPtr;
400    }
401    memcpy(destPtr, &ptr, sizeof(void *));
402}
403
404void RsdCpuScriptImpl::setGlobalObj(uint32_t slot, ObjectBase *data) {
405
406    //rsAssert(script->mFieldIsObject[slot]);
407    //ALOGE("setGlobalObj %p %p %i %p", dc, script, slot, data);
408
409    //if (mIntrinsicID) {
410        //mIntrinsicFuncs.setVarObj(dc, script, drv->mIntrinsicData, slot, alloc);
411        //return;
412    //}
413
414    int32_t *destPtr = reinterpret_cast<int32_t *>(
415                          mExecutable->getExportVarAddrs()[slot]);
416    if (!destPtr) {
417        //ALOGV("Calling setVar on slot = %i which is null", slot);
418        return;
419    }
420
421    rsrSetObject(mCtx->getContext(), (ObjectBase **)destPtr, data);
422}
423
424RsdCpuScriptImpl::~RsdCpuScriptImpl() {
425
426    if (mExecutable) {
427        Vector<void *>::const_iterator var_addr_iter =
428            mExecutable->getExportVarAddrs().begin();
429        Vector<void *>::const_iterator var_addr_end =
430            mExecutable->getExportVarAddrs().end();
431
432        bcc::RSInfo::ObjectSlotListTy::const_iterator is_object_iter =
433            mExecutable->getInfo().getObjectSlots().begin();
434        bcc::RSInfo::ObjectSlotListTy::const_iterator is_object_end =
435            mExecutable->getInfo().getObjectSlots().end();
436
437        while ((var_addr_iter != var_addr_end) &&
438               (is_object_iter != is_object_end)) {
439            // The field address can be NULL if the script-side has optimized
440            // the corresponding global variable away.
441            ObjectBase **obj_addr =
442                reinterpret_cast<ObjectBase **>(*var_addr_iter);
443            if (*is_object_iter) {
444                if (*var_addr_iter != NULL) {
445                    rsrClearObject(mCtx->getContext(), obj_addr);
446                }
447            }
448            var_addr_iter++;
449            is_object_iter++;
450        }
451    }
452
453    if (mCompilerContext) {
454        delete mCompilerContext;
455    }
456    if (mCompilerDriver) {
457        delete mCompilerDriver;
458    }
459    if (mExecutable) {
460        delete mExecutable;
461    }
462    if (mBoundAllocs) {
463        delete[] mBoundAllocs;
464    }
465}
466
467Allocation * RsdCpuScriptImpl::getAllocationForPointer(const void *ptr) const {
468    if (!ptr) {
469        return NULL;
470    }
471
472    for (uint32_t ct=0; ct < mScript->mHal.info.exportedVariableCount; ct++) {
473        Allocation *a = mBoundAllocs[ct];
474        if (!a) continue;
475        if (a->mHal.drvState.lod[0].mallocPtr == ptr) {
476            return a;
477        }
478    }
479    ALOGE("rsGetAllocation, failed to find %p", ptr);
480    return NULL;
481}
482
483
484}
485}
486