rsCpuCore.cpp revision 21dbc8ba61dd6a5852b1346c14bd29373326c240
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
21#include <malloc.h>
22#include "rsContext.h"
23
24#include <sys/types.h>
25#include <sys/resource.h>
26#include <sched.h>
27#include <sys/syscall.h>
28#include <string.h>
29#include <unistd.h>
30
31#include <stdio.h>
32#include <stdlib.h>
33#include <fcntl.h>
34
35#if !defined(RS_SERVER) && !defined(RS_COMPATIBILITY_LIB)
36#include <cutils/properties.h>
37#include "utils/StopWatch.h"
38#endif
39
40#ifdef RS_SERVER
41// Android exposes gettid(), standard Linux does not
42static pid_t gettid() {
43    return syscall(SYS_gettid);
44}
45#endif
46
47using namespace android;
48using namespace android::renderscript;
49
50typedef void (*outer_foreach_t)(
51    const android::renderscript::RsForEachStubParamStruct *,
52    uint32_t x1, uint32_t x2,
53    uint32_t instep, uint32_t outstep);
54
55
56static pthread_key_t gThreadTLSKey = 0;
57static uint32_t gThreadTLSKeyCount = 0;
58static pthread_mutex_t gInitMutex = PTHREAD_MUTEX_INITIALIZER;
59
60bool android::renderscript::gArchUseSIMD = false;
61
62RsdCpuReference::~RsdCpuReference() {
63}
64
65RsdCpuReference * RsdCpuReference::create(Context *rsc, uint32_t version_major,
66        uint32_t version_minor, sym_lookup_t lfn, script_lookup_t slfn
67#ifndef RS_COMPATIBILITY_LIB
68        , bcc::RSLinkRuntimeCallback pLinkRuntimeCallback,
69        RSSelectRTCallback pSelectRTCallback
70#endif
71        ) {
72
73    RsdCpuReferenceImpl *cpu = new RsdCpuReferenceImpl(rsc);
74    if (!cpu) {
75        return NULL;
76    }
77    if (!cpu->init(version_major, version_minor, lfn, slfn)) {
78        delete cpu;
79        return NULL;
80    }
81
82#ifndef RS_COMPATIBILITY_LIB
83    cpu->setLinkRuntimeCallback(pLinkRuntimeCallback);
84    cpu->setSelectRTCallback(pSelectRTCallback);
85#endif
86
87    return cpu;
88}
89
90
91Context * RsdCpuReference::getTlsContext() {
92    ScriptTLSStruct * tls = (ScriptTLSStruct *)pthread_getspecific(gThreadTLSKey);
93    return tls->mContext;
94}
95
96const Script * RsdCpuReference::getTlsScript() {
97    ScriptTLSStruct * tls = (ScriptTLSStruct *)pthread_getspecific(gThreadTLSKey);
98    return tls->mScript;
99}
100
101pthread_key_t RsdCpuReference::getThreadTLSKey(){ return gThreadTLSKey; }
102
103////////////////////////////////////////////////////////////
104///
105
106RsdCpuReferenceImpl::RsdCpuReferenceImpl(Context *rsc) {
107    mRSC = rsc;
108
109    version_major = 0;
110    version_minor = 0;
111    mInForEach = false;
112    memset(&mWorkers, 0, sizeof(mWorkers));
113    memset(&mTlsStruct, 0, sizeof(mTlsStruct));
114    mExit = false;
115#ifndef RS_COMPATIBILITY_LIB
116    mLinkRuntimeCallback = NULL;
117    mSelectRTCallback = NULL;
118    mSetupCompilerCallback = NULL;
119#endif
120}
121
122
123void * RsdCpuReferenceImpl::helperThreadProc(void *vrsc) {
124    RsdCpuReferenceImpl *dc = (RsdCpuReferenceImpl *)vrsc;
125
126    uint32_t idx = __sync_fetch_and_add(&dc->mWorkers.mLaunchCount, 1);
127
128    //ALOGV("RS helperThread starting %p idx=%i", dc, idx);
129
130    dc->mWorkers.mLaunchSignals[idx].init();
131    dc->mWorkers.mNativeThreadId[idx] = gettid();
132
133    memset(&dc->mTlsStruct, 0, sizeof(dc->mTlsStruct));
134    int status = pthread_setspecific(gThreadTLSKey, &dc->mTlsStruct);
135    if (status) {
136        ALOGE("pthread_setspecific %i", status);
137    }
138
139#if 0
140    typedef struct {uint64_t bits[1024 / 64]; } cpu_set_t;
141    cpu_set_t cpuset;
142    memset(&cpuset, 0, sizeof(cpuset));
143    cpuset.bits[idx / 64] |= 1ULL << (idx % 64);
144    int ret = syscall(241, rsc->mWorkers.mNativeThreadId[idx],
145              sizeof(cpuset), &cpuset);
146    ALOGE("SETAFFINITY ret = %i %s", ret, EGLUtils::strerror(ret));
147#endif
148
149    while (!dc->mExit) {
150        dc->mWorkers.mLaunchSignals[idx].wait();
151        if (dc->mWorkers.mLaunchCallback) {
152           // idx +1 is used because the calling thread is always worker 0.
153           dc->mWorkers.mLaunchCallback(dc->mWorkers.mLaunchData, idx+1);
154        }
155        __sync_fetch_and_sub(&dc->mWorkers.mRunningCount, 1);
156        dc->mWorkers.mCompleteSignal.set();
157    }
158
159    //ALOGV("RS helperThread exited %p idx=%i", dc, idx);
160    return NULL;
161}
162
163void RsdCpuReferenceImpl::launchThreads(WorkerCallback_t cbk, void *data) {
164    mWorkers.mLaunchData = data;
165    mWorkers.mLaunchCallback = cbk;
166
167    // fast path for very small launches
168    MTLaunchStruct *mtls = (MTLaunchStruct *)data;
169    if (mtls && mtls->fep.dimY <= 1 && mtls->xEnd <= mtls->xStart + mtls->mSliceSize) {
170        if (mWorkers.mLaunchCallback) {
171            mWorkers.mLaunchCallback(mWorkers.mLaunchData, 0);
172        }
173        return;
174    }
175
176    mWorkers.mRunningCount = mWorkers.mCount;
177    __sync_synchronize();
178
179    for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) {
180        mWorkers.mLaunchSignals[ct].set();
181    }
182
183    // We use the calling thread as one of the workers so we can start without
184    // the delay of the thread wakeup.
185    if (mWorkers.mLaunchCallback) {
186        mWorkers.mLaunchCallback(mWorkers.mLaunchData, 0);
187    }
188
189    while (__sync_fetch_and_or(&mWorkers.mRunningCount, 0) != 0) {
190        mWorkers.mCompleteSignal.wait();
191    }
192}
193
194
195void RsdCpuReferenceImpl::lockMutex() {
196    pthread_mutex_lock(&gInitMutex);
197}
198
199void RsdCpuReferenceImpl::unlockMutex() {
200    pthread_mutex_unlock(&gInitMutex);
201}
202
203#if defined(ARCH_ARM_HAVE_VFP)
204static int
205read_file(const char*  pathname, char*  buffer, size_t  buffsize)
206{
207    int  fd, len;
208
209    fd = open(pathname, O_RDONLY);
210    if (fd < 0)
211        return -1;
212
213    do {
214        len = read(fd, buffer, buffsize);
215    } while (len < 0 && errno == EINTR);
216
217    close(fd);
218
219    return len;
220}
221
222static void GetCpuInfo() {
223    char cpuinfo[4096];
224    int  cpuinfo_len;
225
226    cpuinfo_len = read_file("/proc/cpuinfo", cpuinfo, sizeof cpuinfo);
227    if (cpuinfo_len < 0)  /* should not happen */ {
228        return;
229    }
230
231    gArchUseSIMD = !!strstr(cpuinfo, " neon");
232}
233#endif // ARCH_ARM_HAVE_VFP
234
235bool RsdCpuReferenceImpl::init(uint32_t version_major, uint32_t version_minor,
236                               sym_lookup_t lfn, script_lookup_t slfn) {
237
238    mSymLookupFn = lfn;
239    mScriptLookupFn = slfn;
240
241    lockMutex();
242    if (!gThreadTLSKeyCount) {
243        int status = pthread_key_create(&gThreadTLSKey, NULL);
244        if (status) {
245            ALOGE("Failed to init thread tls key.");
246            unlockMutex();
247            return false;
248        }
249    }
250    gThreadTLSKeyCount++;
251    unlockMutex();
252
253    mTlsStruct.mContext = mRSC;
254    mTlsStruct.mScript = NULL;
255    int status = pthread_setspecific(gThreadTLSKey, &mTlsStruct);
256    if (status) {
257        ALOGE("pthread_setspecific %i", status);
258    }
259
260#if defined(ARCH_ARM_HAVE_VFP)
261    GetCpuInfo();
262#endif
263
264    int cpu = sysconf(_SC_NPROCESSORS_ONLN);
265    if(mRSC->props.mDebugMaxThreads) {
266        cpu = mRSC->props.mDebugMaxThreads;
267    }
268    if (cpu < 2) {
269        mWorkers.mCount = 0;
270        return true;
271    }
272
273    // Subtract one from the cpu count because we also use the command thread as a worker.
274    mWorkers.mCount = (uint32_t)(cpu - 1);
275
276    ALOGV("%p Launching thread(s), CPUs %i", mRSC, mWorkers.mCount + 1);
277
278    mWorkers.mThreadId = (pthread_t *) calloc(mWorkers.mCount, sizeof(pthread_t));
279    mWorkers.mNativeThreadId = (pid_t *) calloc(mWorkers.mCount, sizeof(pid_t));
280    mWorkers.mLaunchSignals = new Signal[mWorkers.mCount];
281    mWorkers.mLaunchCallback = NULL;
282
283    mWorkers.mCompleteSignal.init();
284
285    mWorkers.mRunningCount = mWorkers.mCount;
286    mWorkers.mLaunchCount = 0;
287    __sync_synchronize();
288
289    pthread_attr_t threadAttr;
290    status = pthread_attr_init(&threadAttr);
291    if (status) {
292        ALOGE("Failed to init thread attribute.");
293        return false;
294    }
295
296    for (uint32_t ct=0; ct < mWorkers.mCount; ct++) {
297        status = pthread_create(&mWorkers.mThreadId[ct], &threadAttr, helperThreadProc, this);
298        if (status) {
299            mWorkers.mCount = ct;
300            ALOGE("Created fewer than expected number of RS threads.");
301            break;
302        }
303    }
304    while (__sync_fetch_and_or(&mWorkers.mRunningCount, 0) != 0) {
305        usleep(100);
306    }
307
308    pthread_attr_destroy(&threadAttr);
309    return true;
310}
311
312
313void RsdCpuReferenceImpl::setPriority(int32_t priority) {
314    for (uint32_t ct=0; ct < mWorkers.mCount; ct++) {
315        setpriority(PRIO_PROCESS, mWorkers.mNativeThreadId[ct], priority);
316    }
317}
318
319RsdCpuReferenceImpl::~RsdCpuReferenceImpl() {
320    mExit = true;
321    mWorkers.mLaunchData = NULL;
322    mWorkers.mLaunchCallback = NULL;
323    mWorkers.mRunningCount = mWorkers.mCount;
324    __sync_synchronize();
325    for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) {
326        mWorkers.mLaunchSignals[ct].set();
327    }
328    void *res;
329    for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) {
330        pthread_join(mWorkers.mThreadId[ct], &res);
331    }
332    rsAssert(__sync_fetch_and_or(&mWorkers.mRunningCount, 0) == 0);
333    free(mWorkers.mThreadId);
334    free(mWorkers.mNativeThreadId);
335    delete[] mWorkers.mLaunchSignals;
336
337    // Global structure cleanup.
338    lockMutex();
339    --gThreadTLSKeyCount;
340    if (!gThreadTLSKeyCount) {
341        pthread_key_delete(gThreadTLSKey);
342    }
343    unlockMutex();
344
345}
346
347typedef void (*rs_t)(const void *, void *, const void *, uint32_t, uint32_t, uint32_t, uint32_t);
348
349static void wc_xy(void *usr, uint32_t idx) {
350    MTLaunchStruct *mtls = (MTLaunchStruct *)usr;
351    RsForEachStubParamStruct p;
352    memcpy(&p, &mtls->fep, sizeof(p));
353    p.lid = idx;
354    uint32_t sig = mtls->sig;
355
356    outer_foreach_t fn = (outer_foreach_t) mtls->kernel;
357    while (1) {
358        uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1);
359        uint32_t yStart = mtls->yStart + slice * mtls->mSliceSize;
360        uint32_t yEnd = yStart + mtls->mSliceSize;
361        yEnd = rsMin(yEnd, mtls->yEnd);
362        if (yEnd <= yStart) {
363            return;
364        }
365
366        //ALOGE("usr idx %i, x %i,%i  y %i,%i", idx, mtls->xStart, mtls->xEnd, yStart, yEnd);
367        //ALOGE("usr ptr in %p,  out %p", mtls->fep.ptrIn, mtls->fep.ptrOut);
368
369        for (p.y = yStart; p.y < yEnd; p.y++) {
370            p.out = mtls->fep.ptrOut + (mtls->fep.yStrideOut * p.y) +
371                    (mtls->fep.eStrideOut * mtls->xStart);
372            p.in = mtls->fep.ptrIn + (mtls->fep.yStrideIn * p.y) +
373                   (mtls->fep.eStrideIn * mtls->xStart);
374            fn(&p, mtls->xStart, mtls->xEnd, mtls->fep.eStrideIn, mtls->fep.eStrideOut);
375        }
376    }
377}
378
379static void wc_x(void *usr, uint32_t idx) {
380    MTLaunchStruct *mtls = (MTLaunchStruct *)usr;
381    RsForEachStubParamStruct p;
382    memcpy(&p, &mtls->fep, sizeof(p));
383    p.lid = idx;
384    uint32_t sig = mtls->sig;
385
386    outer_foreach_t fn = (outer_foreach_t) mtls->kernel;
387    while (1) {
388        uint32_t slice = (uint32_t)__sync_fetch_and_add(&mtls->mSliceNum, 1);
389        uint32_t xStart = mtls->xStart + slice * mtls->mSliceSize;
390        uint32_t xEnd = xStart + mtls->mSliceSize;
391        xEnd = rsMin(xEnd, mtls->xEnd);
392        if (xEnd <= xStart) {
393            return;
394        }
395
396        //ALOGE("usr slice %i idx %i, x %i,%i", slice, idx, xStart, xEnd);
397        //ALOGE("usr ptr in %p,  out %p", mtls->fep.ptrIn, mtls->fep.ptrOut);
398
399        p.out = mtls->fep.ptrOut + (mtls->fep.eStrideOut * xStart);
400        p.in = mtls->fep.ptrIn + (mtls->fep.eStrideIn * xStart);
401        fn(&p, xStart, xEnd, mtls->fep.eStrideIn, mtls->fep.eStrideOut);
402    }
403}
404
405void RsdCpuReferenceImpl::launchThreads(const Allocation * ain, Allocation * aout,
406                                     const RsScriptCall *sc, MTLaunchStruct *mtls) {
407
408    //android::StopWatch kernel_time("kernel time");
409
410    if ((mWorkers.mCount >= 1) && mtls->isThreadable && !mInForEach) {
411        const size_t targetByteChunk = 16 * 1024;
412        mInForEach = true;
413        if (mtls->fep.dimY > 1) {
414            uint32_t s1 = mtls->fep.dimY / ((mWorkers.mCount + 1) * 4);
415            uint32_t s2 = 0;
416
417            // This chooses our slice size to rate limit atomic ops to
418            // one per 16k bytes of reads/writes.
419            if (mtls->fep.yStrideOut) {
420                s2 = targetByteChunk / mtls->fep.yStrideOut;
421            } else {
422                s2 = targetByteChunk / mtls->fep.yStrideIn;
423            }
424            mtls->mSliceSize = rsMin(s1, s2);
425
426            if(mtls->mSliceSize < 1) {
427                mtls->mSliceSize = 1;
428            }
429
430         //   mtls->mSliceSize = 2;
431            launchThreads(wc_xy, mtls);
432        } else {
433            uint32_t s1 = mtls->fep.dimX / ((mWorkers.mCount + 1) * 4);
434            uint32_t s2 = 0;
435
436            // This chooses our slice size to rate limit atomic ops to
437            // one per 16k bytes of reads/writes.
438            if (mtls->fep.eStrideOut) {
439                s2 = targetByteChunk / mtls->fep.eStrideOut;
440            } else {
441                s2 = targetByteChunk / mtls->fep.eStrideIn;
442            }
443            mtls->mSliceSize = rsMin(s1, s2);
444
445            if(mtls->mSliceSize < 1) {
446                mtls->mSliceSize = 1;
447            }
448
449            launchThreads(wc_x, mtls);
450        }
451        mInForEach = false;
452
453        //ALOGE("launch 1");
454    } else {
455        RsForEachStubParamStruct p;
456        memcpy(&p, &mtls->fep, sizeof(p));
457        uint32_t sig = mtls->sig;
458
459        //ALOGE("launch 3");
460        outer_foreach_t fn = (outer_foreach_t) mtls->kernel;
461        for (p.ar[0] = mtls->arrayStart; p.ar[0] < mtls->arrayEnd; p.ar[0]++) {
462            for (p.z = mtls->zStart; p.z < mtls->zEnd; p.z++) {
463                for (p.y = mtls->yStart; p.y < mtls->yEnd; p.y++) {
464                    uint32_t offset = mtls->fep.dimY * mtls->fep.dimZ * p.ar[0] +
465                                      mtls->fep.dimY * p.z + p.y;
466                    p.out = mtls->fep.ptrOut + (mtls->fep.yStrideOut * offset) +
467                            (mtls->fep.eStrideOut * mtls->xStart);
468                    p.in = mtls->fep.ptrIn + (mtls->fep.yStrideIn * offset) +
469                           (mtls->fep.eStrideIn * mtls->xStart);
470                    fn(&p, mtls->xStart, mtls->xEnd, mtls->fep.eStrideIn, mtls->fep.eStrideOut);
471                }
472            }
473        }
474    }
475}
476
477RsdCpuScriptImpl * RsdCpuReferenceImpl::setTLS(RsdCpuScriptImpl *sc) {
478    //ALOGE("setTls %p", sc);
479    ScriptTLSStruct * tls = (ScriptTLSStruct *)pthread_getspecific(gThreadTLSKey);
480    rsAssert(tls);
481    RsdCpuScriptImpl *old = tls->mImpl;
482    tls->mImpl = sc;
483    tls->mContext = mRSC;
484    if (sc) {
485        tls->mScript = sc->getScript();
486    } else {
487        tls->mScript = NULL;
488    }
489    return old;
490}
491
492const RsdCpuReference::CpuSymbol * RsdCpuReferenceImpl::symLookup(const char *name) {
493    return mSymLookupFn(mRSC, name);
494}
495
496
497RsdCpuReference::CpuScript * RsdCpuReferenceImpl::createScript(const ScriptC *s,
498                                    char const *resName, char const *cacheDir,
499                                    uint8_t const *bitcode, size_t bitcodeSize,
500                                    uint32_t flags) {
501
502    RsdCpuScriptImpl *i = new RsdCpuScriptImpl(this, s);
503    if (!i->init(resName, cacheDir, bitcode, bitcodeSize, flags)) {
504        delete i;
505        return NULL;
506    }
507    return i;
508}
509
510extern RsdCpuScriptImpl * rsdIntrinsic_3DLUT(RsdCpuReferenceImpl *ctx,
511                                             const Script *s, const Element *e);
512extern RsdCpuScriptImpl * rsdIntrinsic_InterPred(RsdCpuReferenceImpl *ctx,
513                                                 const Script *s, const Element *e);
514extern RsdCpuScriptImpl * rsdIntrinsic_Convolve3x3(RsdCpuReferenceImpl *ctx,
515                                                   const Script *s, const Element *e);
516extern RsdCpuScriptImpl * rsdIntrinsic_ColorMatrix(RsdCpuReferenceImpl *ctx,
517                                                   const Script *s, const Element *e);
518extern RsdCpuScriptImpl * rsdIntrinsic_LUT(RsdCpuReferenceImpl *ctx,
519                                           const Script *s, const Element *e);
520extern RsdCpuScriptImpl * rsdIntrinsic_Convolve5x5(RsdCpuReferenceImpl *ctx,
521                                                   const Script *s, const Element *e);
522extern RsdCpuScriptImpl * rsdIntrinsic_Blur(RsdCpuReferenceImpl *ctx,
523                                            const Script *s, const Element *e);
524extern RsdCpuScriptImpl * rsdIntrinsic_YuvToRGB(RsdCpuReferenceImpl *ctx,
525                                                const Script *s, const Element *e);
526extern RsdCpuScriptImpl * rsdIntrinsic_Blend(RsdCpuReferenceImpl *ctx,
527                                             const Script *s, const Element *e);
528extern RsdCpuScriptImpl * rsdIntrinsic_Histogram(RsdCpuReferenceImpl *ctx,
529                                                 const Script *s, const Element *e);
530extern RsdCpuScriptImpl * rsdIntrinsic_LoopFilter(RsdCpuReferenceImpl *ctx,
531                                                  const Script *s, const Element *e);
532
533RsdCpuReference::CpuScript * RsdCpuReferenceImpl::createIntrinsic(const Script *s,
534                                    RsScriptIntrinsicID iid, Element *e) {
535
536    RsdCpuScriptImpl *i = NULL;
537    switch (iid) {
538    case RS_SCRIPT_INTRINSIC_ID_3DLUT:
539        i = rsdIntrinsic_3DLUT(this, s, e);
540        break;
541#ifndef RS_COMPATIBILITY_LIB
542    case RS_SCRIPT_INTRINSIC_ID_INTER_PRED:
543        i = rsdIntrinsic_InterPred(this, s, e);
544        break;
545#endif
546    case RS_SCRIPT_INTRINSIC_ID_CONVOLVE_3x3:
547        i = rsdIntrinsic_Convolve3x3(this, s, e);
548        break;
549    case RS_SCRIPT_INTRINSIC_ID_COLOR_MATRIX:
550        i = rsdIntrinsic_ColorMatrix(this, s, e);
551        break;
552    case RS_SCRIPT_INTRINSIC_ID_LUT:
553        i = rsdIntrinsic_LUT(this, s, e);
554        break;
555    case RS_SCRIPT_INTRINSIC_ID_CONVOLVE_5x5:
556        i = rsdIntrinsic_Convolve5x5(this, s, e);
557        break;
558    case RS_SCRIPT_INTRINSIC_ID_BLUR:
559        i = rsdIntrinsic_Blur(this, s, e);
560        break;
561    case RS_SCRIPT_INTRINSIC_ID_YUV_TO_RGB:
562        i = rsdIntrinsic_YuvToRGB(this, s, e);
563        break;
564    case RS_SCRIPT_INTRINSIC_ID_BLEND:
565        i = rsdIntrinsic_Blend(this, s, e);
566        break;
567    case RS_SCRIPT_INTRINSIC_ID_HISTOGRAM:
568        i = rsdIntrinsic_Histogram(this, s, e);
569        break;
570#ifndef RS_COMPATIBILITY_LIB
571    case RS_SCRIPT_INTRINSIC_ID_LOOP_FILTER:
572        i = rsdIntrinsic_LoopFilter(this, s, e);
573        break;
574#endif
575
576    default:
577        rsAssert(0);
578    }
579
580    return i;
581}
582
583RsdCpuReference::CpuScriptGroup * RsdCpuReferenceImpl::createScriptGroup(const ScriptGroup *sg) {
584    CpuScriptGroupImpl *sgi = new CpuScriptGroupImpl(this, sg);
585    if (!sgi->init()) {
586        delete sgi;
587        return NULL;
588    }
589    return sgi;
590}
591
592
593