rsContext.cpp revision c946b614ee6c983215cc3de7834a7a334f860d68
1/*
2 * Copyright (C) 2009 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 "rsDevice.h"
18#include "rsContext.h"
19#include "rsThreadIO.h"
20#include <ui/FramebufferNativeWindow.h>
21#include <ui/PixelFormat.h>
22#include <ui/EGLUtils.h>
23#include <ui/egl/android_natives.h>
24
25#include <sys/types.h>
26#include <sys/resource.h>
27#include <sched.h>
28
29#include <cutils/properties.h>
30
31#include <GLES/gl.h>
32#include <GLES/glext.h>
33#include <GLES2/gl2.h>
34#include <GLES2/gl2ext.h>
35
36#include <cutils/sched_policy.h>
37#include <sys/syscall.h>
38#include <string.h>
39
40using namespace android;
41using namespace android::renderscript;
42
43pthread_key_t Context::gThreadTLSKey = 0;
44uint32_t Context::gThreadTLSKeyCount = 0;
45uint32_t Context::gGLContextCount = 0;
46pthread_mutex_t Context::gInitMutex = PTHREAD_MUTEX_INITIALIZER;
47pthread_mutex_t Context::gLibMutex = PTHREAD_MUTEX_INITIALIZER;
48
49static void checkEglError(const char* op, EGLBoolean returnVal = EGL_TRUE) {
50    if (returnVal != EGL_TRUE) {
51        fprintf(stderr, "%s() returned %d\n", op, returnVal);
52    }
53
54    for (EGLint error = eglGetError(); error != EGL_SUCCESS; error
55            = eglGetError()) {
56        fprintf(stderr, "after %s() eglError %s (0x%x)\n", op, EGLUtils::strerror(error),
57                error);
58    }
59}
60
61void printEGLConfiguration(EGLDisplay dpy, EGLConfig config) {
62
63#define X(VAL) {VAL, #VAL}
64    struct {EGLint attribute; const char* name;} names[] = {
65    X(EGL_BUFFER_SIZE),
66    X(EGL_ALPHA_SIZE),
67    X(EGL_BLUE_SIZE),
68    X(EGL_GREEN_SIZE),
69    X(EGL_RED_SIZE),
70    X(EGL_DEPTH_SIZE),
71    X(EGL_STENCIL_SIZE),
72    X(EGL_CONFIG_CAVEAT),
73    X(EGL_CONFIG_ID),
74    X(EGL_LEVEL),
75    X(EGL_MAX_PBUFFER_HEIGHT),
76    X(EGL_MAX_PBUFFER_PIXELS),
77    X(EGL_MAX_PBUFFER_WIDTH),
78    X(EGL_NATIVE_RENDERABLE),
79    X(EGL_NATIVE_VISUAL_ID),
80    X(EGL_NATIVE_VISUAL_TYPE),
81    X(EGL_SAMPLES),
82    X(EGL_SAMPLE_BUFFERS),
83    X(EGL_SURFACE_TYPE),
84    X(EGL_TRANSPARENT_TYPE),
85    X(EGL_TRANSPARENT_RED_VALUE),
86    X(EGL_TRANSPARENT_GREEN_VALUE),
87    X(EGL_TRANSPARENT_BLUE_VALUE),
88    X(EGL_BIND_TO_TEXTURE_RGB),
89    X(EGL_BIND_TO_TEXTURE_RGBA),
90    X(EGL_MIN_SWAP_INTERVAL),
91    X(EGL_MAX_SWAP_INTERVAL),
92    X(EGL_LUMINANCE_SIZE),
93    X(EGL_ALPHA_MASK_SIZE),
94    X(EGL_COLOR_BUFFER_TYPE),
95    X(EGL_RENDERABLE_TYPE),
96    X(EGL_CONFORMANT),
97   };
98#undef X
99
100    for (size_t j = 0; j < sizeof(names) / sizeof(names[0]); j++) {
101        EGLint value = -1;
102        EGLint returnVal = eglGetConfigAttrib(dpy, config, names[j].attribute, &value);
103        EGLint error = eglGetError();
104        if (returnVal && error == EGL_SUCCESS) {
105            LOGV(" %s: %d (0x%x)", names[j].name, value, value);
106        }
107    }
108}
109
110
111bool Context::initGLThread() {
112    pthread_mutex_lock(&gInitMutex);
113    LOGV("initGLThread start %p", this);
114
115    mEGL.mNumConfigs = -1;
116    EGLint configAttribs[128];
117    EGLint *configAttribsPtr = configAttribs;
118    EGLint context_attribs2[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
119
120    memset(configAttribs, 0, sizeof(configAttribs));
121
122    configAttribsPtr[0] = EGL_SURFACE_TYPE;
123    configAttribsPtr[1] = EGL_WINDOW_BIT;
124    configAttribsPtr += 2;
125
126    configAttribsPtr[0] = EGL_RENDERABLE_TYPE;
127    configAttribsPtr[1] = EGL_OPENGL_ES2_BIT;
128    configAttribsPtr += 2;
129
130    if (mUserSurfaceConfig.depthMin > 0) {
131        configAttribsPtr[0] = EGL_DEPTH_SIZE;
132        configAttribsPtr[1] = mUserSurfaceConfig.depthMin;
133        configAttribsPtr += 2;
134    }
135
136    if (mDev->mForceSW) {
137        configAttribsPtr[0] = EGL_CONFIG_CAVEAT;
138        configAttribsPtr[1] = EGL_SLOW_CONFIG;
139        configAttribsPtr += 2;
140    }
141
142    configAttribsPtr[0] = EGL_NONE;
143    rsAssert(configAttribsPtr < (configAttribs + (sizeof(configAttribs) / sizeof(EGLint))));
144
145    LOGV("%p initEGL start", this);
146    mEGL.mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
147    checkEglError("eglGetDisplay");
148
149    eglInitialize(mEGL.mDisplay, &mEGL.mMajorVersion, &mEGL.mMinorVersion);
150    checkEglError("eglInitialize");
151
152#if 1
153    PixelFormat pf = PIXEL_FORMAT_RGBA_8888;
154    if (mUserSurfaceConfig.alphaMin == 0) {
155        pf = PIXEL_FORMAT_RGBX_8888;
156    }
157
158    status_t err = EGLUtils::selectConfigForPixelFormat(mEGL.mDisplay, configAttribs, pf, &mEGL.mConfig);
159    if (err) {
160       LOGE("%p, couldn't find an EGLConfig matching the screen format\n", this);
161    }
162    if (props.mLogVisual) {
163        printEGLConfiguration(mEGL.mDisplay, mEGL.mConfig);
164    }
165#else
166    eglChooseConfig(mEGL.mDisplay, configAttribs, &mEGL.mConfig, 1, &mEGL.mNumConfigs);
167#endif
168
169    mEGL.mContext = eglCreateContext(mEGL.mDisplay, mEGL.mConfig, EGL_NO_CONTEXT, context_attribs2);
170    checkEglError("eglCreateContext");
171    if (mEGL.mContext == EGL_NO_CONTEXT) {
172        pthread_mutex_unlock(&gInitMutex);
173        LOGE("%p, eglCreateContext returned EGL_NO_CONTEXT", this);
174        return false;
175    }
176    gGLContextCount++;
177
178
179    EGLint pbuffer_attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
180    mEGL.mSurfaceDefault = eglCreatePbufferSurface(mEGL.mDisplay, mEGL.mConfig, pbuffer_attribs);
181    checkEglError("eglCreatePbufferSurface");
182    if (mEGL.mSurfaceDefault == EGL_NO_SURFACE) {
183        LOGE("eglCreatePbufferSurface returned EGL_NO_SURFACE");
184        pthread_mutex_unlock(&gInitMutex);
185        deinitEGL();
186        return false;
187    }
188
189    EGLBoolean ret = eglMakeCurrent(mEGL.mDisplay, mEGL.mSurfaceDefault, mEGL.mSurfaceDefault, mEGL.mContext);
190    if (ret == EGL_FALSE) {
191        LOGE("eglMakeCurrent returned EGL_FALSE");
192        checkEglError("eglMakeCurrent", ret);
193        pthread_mutex_unlock(&gInitMutex);
194        deinitEGL();
195        return false;
196    }
197
198    mGL.mVersion = glGetString(GL_VERSION);
199    mGL.mVendor = glGetString(GL_VENDOR);
200    mGL.mRenderer = glGetString(GL_RENDERER);
201    mGL.mExtensions = glGetString(GL_EXTENSIONS);
202
203    //LOGV("EGL Version %i %i", mEGL.mMajorVersion, mEGL.mMinorVersion);
204    //LOGV("GL Version %s", mGL.mVersion);
205    //LOGV("GL Vendor %s", mGL.mVendor);
206    //LOGV("GL Renderer %s", mGL.mRenderer);
207    //LOGV("GL Extensions %s", mGL.mExtensions);
208
209    const char *verptr = NULL;
210    if (strlen((const char *)mGL.mVersion) > 9) {
211        if (!memcmp(mGL.mVersion, "OpenGL ES-CM", 12)) {
212            verptr = (const char *)mGL.mVersion + 12;
213        }
214        if (!memcmp(mGL.mVersion, "OpenGL ES ", 10)) {
215            verptr = (const char *)mGL.mVersion + 9;
216        }
217    }
218
219    if (!verptr) {
220        LOGE("Error, OpenGL ES Lite not supported");
221        pthread_mutex_unlock(&gInitMutex);
222        deinitEGL();
223        return false;
224    } else {
225        sscanf(verptr, " %i.%i", &mGL.mMajorVersion, &mGL.mMinorVersion);
226    }
227
228    glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &mGL.mMaxVertexAttribs);
229    glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &mGL.mMaxVertexUniformVectors);
230    glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &mGL.mMaxVertexTextureUnits);
231
232    glGetIntegerv(GL_MAX_VARYING_VECTORS, &mGL.mMaxVaryingVectors);
233    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mGL.mMaxTextureImageUnits);
234
235    glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &mGL.mMaxFragmentTextureImageUnits);
236    glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, &mGL.mMaxFragmentUniformVectors);
237
238    mGL.OES_texture_npot = NULL != strstr((const char *)mGL.mExtensions, "GL_OES_texture_npot");
239    mGL.GL_IMG_texture_npot = NULL != strstr((const char *)mGL.mExtensions, "GL_IMG_texture_npot");
240    mGL.GL_NV_texture_npot_2D_mipmap = NULL != strstr((const char *)mGL.mExtensions, "GL_NV_texture_npot_2D_mipmap");
241    mGL.EXT_texture_max_aniso = 1.0f;
242    bool hasAniso = NULL != strstr((const char *)mGL.mExtensions, "GL_EXT_texture_filter_anisotropic");
243    if (hasAniso) {
244        glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &mGL.EXT_texture_max_aniso);
245    }
246
247    LOGV("initGLThread end %p", this);
248    pthread_mutex_unlock(&gInitMutex);
249    return true;
250}
251
252void Context::deinitEGL() {
253    LOGV("%p, deinitEGL", this);
254
255    if (mEGL.mContext != EGL_NO_CONTEXT) {
256        eglMakeCurrent(mEGL.mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
257        eglDestroySurface(mEGL.mDisplay, mEGL.mSurfaceDefault);
258        if (mEGL.mSurface != EGL_NO_SURFACE) {
259            eglDestroySurface(mEGL.mDisplay, mEGL.mSurface);
260        }
261        eglDestroyContext(mEGL.mDisplay, mEGL.mContext);
262        checkEglError("eglDestroyContext");
263    }
264
265    gGLContextCount--;
266    if (!gGLContextCount) {
267        eglTerminate(mEGL.mDisplay);
268    }
269}
270
271Context::PushState::PushState(Context *con) {
272    mRsc = con;
273    if (con->mIsGraphicsContext) {
274        mFragment.set(con->getProgramFragment());
275        mVertex.set(con->getProgramVertex());
276        mStore.set(con->getProgramStore());
277        mRaster.set(con->getProgramRaster());
278        mFont.set(con->getFont());
279    }
280}
281
282Context::PushState::~PushState() {
283    if (mRsc->mIsGraphicsContext) {
284        mRsc->setProgramFragment(mFragment.get());
285        mRsc->setProgramVertex(mVertex.get());
286        mRsc->setProgramStore(mStore.get());
287        mRsc->setProgramRaster(mRaster.get());
288        mRsc->setFont(mFont.get());
289    }
290}
291
292
293uint32_t Context::runScript(Script *s) {
294    PushState(this);
295
296    uint32_t ret = s->run(this);
297    return ret;
298}
299
300void Context::checkError(const char *msg, bool isFatal) const {
301
302    GLenum err = glGetError();
303    if (err != GL_NO_ERROR) {
304        char buf[1024];
305        snprintf(buf, sizeof(buf), "GL Error = 0x%08x, from: %s", err, msg);
306
307        if (isFatal) {
308            setError(RS_ERROR_FATAL_DRIVER, buf);
309        } else {
310            switch (err) {
311            case GL_OUT_OF_MEMORY:
312                setError(RS_ERROR_OUT_OF_MEMORY, buf);
313                break;
314            default:
315                setError(RS_ERROR_DRIVER, buf);
316                break;
317            }
318        }
319
320        LOGE("%p, %s", this, buf);
321    }
322}
323
324uint32_t Context::runRootScript() {
325    glViewport(0, 0, mWidth, mHeight);
326
327    timerSet(RS_TIMER_SCRIPT);
328    mStateFragmentStore.mLast.clear();
329    uint32_t ret = runScript(mRootScript.get());
330
331    checkError("runRootScript");
332    return ret;
333}
334
335uint64_t Context::getTime() const {
336    struct timespec t;
337    clock_gettime(CLOCK_MONOTONIC, &t);
338    return t.tv_nsec + ((uint64_t)t.tv_sec * 1000 * 1000 * 1000);
339}
340
341void Context::timerReset() {
342    for (int ct=0; ct < _RS_TIMER_TOTAL; ct++) {
343        mTimers[ct] = 0;
344    }
345}
346
347void Context::timerInit() {
348    mTimeLast = getTime();
349    mTimeFrame = mTimeLast;
350    mTimeLastFrame = mTimeLast;
351    mTimerActive = RS_TIMER_INTERNAL;
352    mAverageFPSFrameCount = 0;
353    mAverageFPSStartTime = mTimeLast;
354    mAverageFPS = 0;
355    timerReset();
356}
357
358void Context::timerFrame() {
359    mTimeLastFrame = mTimeFrame;
360    mTimeFrame = getTime();
361    // Update average fps
362    const uint64_t averageFramerateInterval = 1000 * 1000000;
363    mAverageFPSFrameCount ++;
364    uint64_t inverval = mTimeFrame - mAverageFPSStartTime;
365    if (inverval >= averageFramerateInterval) {
366        inverval = inverval / 1000000;
367        mAverageFPS = (mAverageFPSFrameCount * 1000) / inverval;
368        mAverageFPSFrameCount = 0;
369        mAverageFPSStartTime = mTimeFrame;
370    }
371}
372
373void Context::timerSet(Timers tm) {
374    uint64_t last = mTimeLast;
375    mTimeLast = getTime();
376    mTimers[mTimerActive] += mTimeLast - last;
377    mTimerActive = tm;
378}
379
380void Context::timerPrint() {
381    double total = 0;
382    for (int ct = 0; ct < _RS_TIMER_TOTAL; ct++) {
383        total += mTimers[ct];
384    }
385    uint64_t frame = mTimeFrame - mTimeLastFrame;
386    mTimeMSLastFrame = frame / 1000000;
387    mTimeMSLastScript = mTimers[RS_TIMER_SCRIPT] / 1000000;
388    mTimeMSLastSwap = mTimers[RS_TIMER_CLEAR_SWAP] / 1000000;
389
390
391    if (props.mLogTimes) {
392        LOGV("RS: Frame (%i),   Script %2.1f%% (%i),  Swap %2.1f%% (%i),  Idle %2.1f%% (%lli),  Internal %2.1f%% (%lli), Avg fps: %u",
393             mTimeMSLastFrame,
394             100.0 * mTimers[RS_TIMER_SCRIPT] / total, mTimeMSLastScript,
395             100.0 * mTimers[RS_TIMER_CLEAR_SWAP] / total, mTimeMSLastSwap,
396             100.0 * mTimers[RS_TIMER_IDLE] / total, mTimers[RS_TIMER_IDLE] / 1000000,
397             100.0 * mTimers[RS_TIMER_INTERNAL] / total, mTimers[RS_TIMER_INTERNAL] / 1000000,
398             mAverageFPS);
399    }
400}
401
402bool Context::setupCheck() {
403    if (!mShaderCache.lookup(this, mVertex.get(), mFragment.get())) {
404        LOGE("Context::setupCheck() 1 fail");
405        return false;
406    }
407
408    mFragmentStore->setupGL2(this, &mStateFragmentStore);
409    mFragment->setupGL2(this, &mStateFragment, &mShaderCache);
410    mRaster->setupGL2(this, &mStateRaster);
411    mVertex->setupGL2(this, &mStateVertex, &mShaderCache);
412    return true;
413}
414
415void Context::setupProgramStore() {
416    mFragmentStore->setupGL2(this, &mStateFragmentStore);
417}
418
419static bool getProp(const char *str) {
420    char buf[PROPERTY_VALUE_MAX];
421    property_get(str, buf, "0");
422    return 0 != strcmp(buf, "0");
423}
424
425void Context::displayDebugStats() {
426    char buffer[128];
427    sprintf(buffer, "Avg fps %u, Frame %i ms, Script %i ms", mAverageFPS, mTimeMSLastFrame, mTimeMSLastScript);
428    float oldR, oldG, oldB, oldA;
429    mStateFont.getFontColor(&oldR, &oldG, &oldB, &oldA);
430    uint32_t bufferLen = strlen(buffer);
431
432    float shadowCol = 0.1f;
433    mStateFont.setFontColor(shadowCol, shadowCol, shadowCol, 1.0f);
434    mStateFont.renderText(buffer, bufferLen, 5, getHeight() - 6);
435
436    mStateFont.setFontColor(1.0f, 0.7f, 0.0f, 1.0f);
437    mStateFont.renderText(buffer, bufferLen, 4, getHeight() - 7);
438
439    mStateFont.setFontColor(oldR, oldG, oldB, oldA);
440}
441
442void * Context::threadProc(void *vrsc) {
443     Context *rsc = static_cast<Context *>(vrsc);
444     rsc->mNativeThreadId = gettid();
445
446     setpriority(PRIO_PROCESS, rsc->mNativeThreadId, ANDROID_PRIORITY_DISPLAY);
447     rsc->mThreadPriority = ANDROID_PRIORITY_DISPLAY;
448
449     rsc->props.mLogTimes = getProp("debug.rs.profile");
450     rsc->props.mLogScripts = getProp("debug.rs.script");
451     rsc->props.mLogObjects = getProp("debug.rs.object");
452     rsc->props.mLogShaders = getProp("debug.rs.shader");
453     rsc->props.mLogShadersAttr = getProp("debug.rs.shader.attributes");
454     rsc->props.mLogShadersUniforms = getProp("debug.rs.shader.uniforms");
455     rsc->props.mLogVisual = getProp("debug.rs.visual");
456
457     rsc->mTlsStruct = new ScriptTLSStruct;
458     if (!rsc->mTlsStruct) {
459         LOGE("Error allocating tls storage");
460         rsc->setError(RS_ERROR_OUT_OF_MEMORY, "Failed allocation for TLS");
461         return NULL;
462     }
463     rsc->mTlsStruct->mContext = rsc;
464     rsc->mTlsStruct->mScript = NULL;
465     int status = pthread_setspecific(rsc->gThreadTLSKey, rsc->mTlsStruct);
466     if (status) {
467         LOGE("pthread_setspecific %i", status);
468     }
469
470     if (!rsc->initGLThread()) {
471         rsc->setError(RS_ERROR_OUT_OF_MEMORY, "Failed initializing GL");
472         return NULL;
473     }
474
475     if (rsc->mIsGraphicsContext) {
476         rsc->mStateRaster.init(rsc);
477         rsc->setProgramRaster(NULL);
478         rsc->mStateVertex.init(rsc);
479         rsc->setProgramVertex(NULL);
480         rsc->mStateFragment.init(rsc);
481         rsc->setProgramFragment(NULL);
482         rsc->mStateFragmentStore.init(rsc);
483         rsc->setProgramStore(NULL);
484         rsc->mStateFont.init(rsc);
485         rsc->setFont(NULL);
486         rsc->mStateVertexArray.init(rsc);
487     }
488
489     rsc->mRunning = true;
490     bool mDraw = true;
491     while (!rsc->mExit) {
492         mDraw |= rsc->mIO.playCoreCommands(rsc, !mDraw);
493         mDraw &= (rsc->mRootScript.get() != NULL);
494         mDraw &= (rsc->mWndSurface != NULL);
495
496         uint32_t targetTime = 0;
497         if (mDraw && rsc->mIsGraphicsContext) {
498             targetTime = rsc->runRootScript();
499
500             if (rsc->props.mLogVisual) {
501                 rsc->displayDebugStats();
502             }
503
504             mDraw = targetTime && !rsc->mPaused;
505             rsc->timerSet(RS_TIMER_CLEAR_SWAP);
506             eglSwapBuffers(rsc->mEGL.mDisplay, rsc->mEGL.mSurface);
507             rsc->timerFrame();
508             rsc->timerSet(RS_TIMER_INTERNAL);
509             rsc->timerPrint();
510             rsc->timerReset();
511         }
512         if (targetTime > 1) {
513             int32_t t = (targetTime - (int32_t)(rsc->mTimeMSLastScript + rsc->mTimeMSLastSwap)) * 1000;
514             if (t > 0) {
515                 usleep(t);
516             }
517         }
518     }
519
520     LOGV("%p, RS Thread exiting", rsc);
521
522     if (rsc->mIsGraphicsContext) {
523         pthread_mutex_lock(&gInitMutex);
524         rsc->deinitEGL();
525         pthread_mutex_unlock(&gInitMutex);
526     }
527     delete rsc->mTlsStruct;
528
529     LOGV("%p, RS Thread exited", rsc);
530     return NULL;
531}
532
533void Context::destroyWorkerThreadResources() {
534    //LOGV("destroyWorkerThreadResources 1");
535    ObjectBase::zeroAllUserRef(this);
536    if (mIsGraphicsContext) {
537         mRaster.clear();
538         mFragment.clear();
539         mVertex.clear();
540         mFragmentStore.clear();
541         mFont.clear();
542         mRootScript.clear();
543         mStateRaster.deinit(this);
544         mStateVertex.deinit(this);
545         mStateFragment.deinit(this);
546         mStateFragmentStore.deinit(this);
547         mStateFont.deinit(this);
548         mShaderCache.cleanupAll();
549    }
550    //LOGV("destroyWorkerThreadResources 2");
551    mExit = true;
552}
553
554void * Context::helperThreadProc(void *vrsc) {
555     Context *rsc = static_cast<Context *>(vrsc);
556     uint32_t idx = (uint32_t)android_atomic_inc(&rsc->mWorkers.mLaunchCount);
557
558     //LOGV("RS helperThread starting %p idx=%i", rsc, idx);
559
560     rsc->mWorkers.mLaunchSignals[idx].init();
561     rsc->mWorkers.mNativeThreadId[idx] = gettid();
562
563#if 0
564     typedef struct {uint64_t bits[1024 / 64]; } cpu_set_t;
565     cpu_set_t cpuset;
566     memset(&cpuset, 0, sizeof(cpuset));
567     cpuset.bits[idx / 64] |= 1ULL << (idx % 64);
568     int ret = syscall(241, rsc->mWorkers.mNativeThreadId[idx],
569               sizeof(cpuset), &cpuset);
570     LOGE("SETAFFINITY ret = %i %s", ret, EGLUtils::strerror(ret));
571#endif
572
573     setpriority(PRIO_PROCESS, rsc->mWorkers.mNativeThreadId[idx], rsc->mThreadPriority);
574     int status = pthread_setspecific(rsc->gThreadTLSKey, rsc->mTlsStruct);
575     if (status) {
576         LOGE("pthread_setspecific %i", status);
577     }
578
579     while (!rsc->mExit) {
580         rsc->mWorkers.mLaunchSignals[idx].wait();
581         if (rsc->mWorkers.mLaunchCallback) {
582            rsc->mWorkers.mLaunchCallback(rsc->mWorkers.mLaunchData, idx);
583         }
584         android_atomic_dec(&rsc->mWorkers.mRunningCount);
585         rsc->mWorkers.mCompleteSignal.set();
586     }
587
588     //LOGV("RS helperThread exited %p idx=%i", rsc, idx);
589     return NULL;
590}
591
592void Context::launchThreads(WorkerCallback_t cbk, void *data) {
593    mWorkers.mLaunchData = data;
594    mWorkers.mLaunchCallback = cbk;
595    mWorkers.mRunningCount = (int)mWorkers.mCount;
596    for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) {
597        mWorkers.mLaunchSignals[ct].set();
598    }
599    while (mWorkers.mRunningCount) {
600        mWorkers.mCompleteSignal.wait();
601    }
602}
603
604void Context::setPriority(int32_t p) {
605    // Note: If we put this in the proper "background" policy
606    // the wallpapers can become completly unresponsive at times.
607    // This is probably not what we want for something the user is actively
608    // looking at.
609    mThreadPriority = p;
610#if 0
611    SchedPolicy pol = SP_FOREGROUND;
612    if (p > 0) {
613        pol = SP_BACKGROUND;
614    }
615    if (!set_sched_policy(mNativeThreadId, pol)) {
616        // success; reset the priority as well
617    }
618#else
619    setpriority(PRIO_PROCESS, mNativeThreadId, p);
620    for (uint32_t ct=0; ct < mWorkers.mCount; ct++) {
621        setpriority(PRIO_PROCESS, mWorkers.mNativeThreadId[ct], p);
622    }
623#endif
624}
625
626Context::Context() {
627    mDev = NULL;
628    mRunning = false;
629    mExit = false;
630    mPaused = false;
631    mObjHead = NULL;
632    mError = RS_ERROR_NONE;
633}
634
635Context * Context::createContext(Device *dev, const RsSurfaceConfig *sc) {
636    Context * rsc = new Context();
637    if (!rsc->initContext(dev, sc)) {
638        delete rsc;
639        return NULL;
640    }
641    return rsc;
642}
643
644bool Context::initContext(Device *dev, const RsSurfaceConfig *sc) {
645    pthread_mutex_lock(&gInitMutex);
646
647    dev->addContext(this);
648    mDev = dev;
649    if (sc) {
650        mUserSurfaceConfig = *sc;
651    } else {
652        memset(&mUserSurfaceConfig, 0, sizeof(mUserSurfaceConfig));
653    }
654
655    memset(&mEGL, 0, sizeof(mEGL));
656    memset(&mGL, 0, sizeof(mGL));
657    mIsGraphicsContext = sc != NULL;
658
659    int status;
660    pthread_attr_t threadAttr;
661
662    if (!gThreadTLSKeyCount) {
663        status = pthread_key_create(&gThreadTLSKey, NULL);
664        if (status) {
665            LOGE("Failed to init thread tls key.");
666            pthread_mutex_unlock(&gInitMutex);
667            return false;
668        }
669    }
670    gThreadTLSKeyCount++;
671
672    pthread_mutex_unlock(&gInitMutex);
673
674    // Global init done at this point.
675
676    status = pthread_attr_init(&threadAttr);
677    if (status) {
678        LOGE("Failed to init thread attribute.");
679        return false;
680    }
681
682    mWndSurface = NULL;
683
684    timerInit();
685    timerSet(RS_TIMER_INTERNAL);
686
687    int cpu = sysconf(_SC_NPROCESSORS_ONLN);
688    LOGV("RS Launching thread(s), reported CPU count %i", cpu);
689    if (cpu < 2) cpu = 0;
690
691    mWorkers.mCount = (uint32_t)cpu;
692    mWorkers.mThreadId = (pthread_t *) calloc(mWorkers.mCount, sizeof(pthread_t));
693    mWorkers.mNativeThreadId = (pid_t *) calloc(mWorkers.mCount, sizeof(pid_t));
694    mWorkers.mLaunchSignals = new Signal[mWorkers.mCount];
695    mWorkers.mLaunchCallback = NULL;
696    status = pthread_create(&mThreadId, &threadAttr, threadProc, this);
697    if (status) {
698        LOGE("Failed to start rs context thread.");
699        return false;
700    }
701    while (!mRunning && (mError == RS_ERROR_NONE)) {
702        usleep(100);
703    }
704
705    if (mError != RS_ERROR_NONE) {
706        return false;
707    }
708
709    mWorkers.mCompleteSignal.init();
710    mWorkers.mRunningCount = 0;
711    mWorkers.mLaunchCount = 0;
712    for (uint32_t ct=0; ct < mWorkers.mCount; ct++) {
713        status = pthread_create(&mWorkers.mThreadId[ct], &threadAttr, helperThreadProc, this);
714        if (status) {
715            mWorkers.mCount = ct;
716            LOGE("Created fewer than expected number of RS threads.");
717            break;
718        }
719    }
720    pthread_attr_destroy(&threadAttr);
721    return true;
722}
723
724Context::~Context() {
725    LOGV("Context::~Context");
726
727    mIO.mToCore.flush();
728    rsAssert(mExit);
729    mExit = true;
730    mPaused = false;
731    void *res;
732
733    mIO.shutdown();
734    int status = pthread_join(mThreadId, &res);
735
736    // Cleanup compute threads.
737    mWorkers.mLaunchData = NULL;
738    mWorkers.mLaunchCallback = NULL;
739    mWorkers.mRunningCount = (int)mWorkers.mCount;
740    for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) {
741        mWorkers.mLaunchSignals[ct].set();
742    }
743    for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) {
744        int status = pthread_join(mWorkers.mThreadId[ct], &res);
745    }
746    rsAssert(!mWorkers.mRunningCount);
747
748    // Global structure cleanup.
749    pthread_mutex_lock(&gInitMutex);
750    if (mDev) {
751        mDev->removeContext(this);
752        --gThreadTLSKeyCount;
753        if (!gThreadTLSKeyCount) {
754            pthread_key_delete(gThreadTLSKey);
755        }
756        mDev = NULL;
757    }
758    pthread_mutex_unlock(&gInitMutex);
759    LOGV("Context::~Context done");
760}
761
762void Context::setSurface(uint32_t w, uint32_t h, ANativeWindow *sur) {
763    rsAssert(mIsGraphicsContext);
764
765    EGLBoolean ret;
766    // WAR: Some drivers fail to handle 0 size surfaces correcntly.
767    // Use the pbuffer to avoid this pitfall.
768    if ((mEGL.mSurface != NULL) || (w == 0) || (h == 0)) {
769        ret = eglMakeCurrent(mEGL.mDisplay, mEGL.mSurfaceDefault, mEGL.mSurfaceDefault, mEGL.mContext);
770        checkEglError("eglMakeCurrent", ret);
771
772        ret = eglDestroySurface(mEGL.mDisplay, mEGL.mSurface);
773        checkEglError("eglDestroySurface", ret);
774
775        mEGL.mSurface = NULL;
776        mWidth = 1;
777        mHeight = 1;
778    }
779
780    mWndSurface = sur;
781    if (mWndSurface != NULL) {
782        mWidth = w;
783        mHeight = h;
784
785        mEGL.mSurface = eglCreateWindowSurface(mEGL.mDisplay, mEGL.mConfig, mWndSurface, NULL);
786        checkEglError("eglCreateWindowSurface");
787        if (mEGL.mSurface == EGL_NO_SURFACE) {
788            LOGE("eglCreateWindowSurface returned EGL_NO_SURFACE");
789        }
790
791        ret = eglMakeCurrent(mEGL.mDisplay, mEGL.mSurface, mEGL.mSurface, mEGL.mContext);
792        checkEglError("eglMakeCurrent", ret);
793
794        mStateVertex.updateSize(this);
795    }
796}
797
798void Context::pause() {
799    rsAssert(mIsGraphicsContext);
800    mPaused = true;
801}
802
803void Context::resume() {
804    rsAssert(mIsGraphicsContext);
805    mPaused = false;
806}
807
808void Context::setRootScript(Script *s) {
809    rsAssert(mIsGraphicsContext);
810    mRootScript.set(s);
811}
812
813void Context::setProgramStore(ProgramStore *pfs) {
814    rsAssert(mIsGraphicsContext);
815    if (pfs == NULL) {
816        mFragmentStore.set(mStateFragmentStore.mDefault);
817    } else {
818        mFragmentStore.set(pfs);
819    }
820}
821
822void Context::setProgramFragment(ProgramFragment *pf) {
823    rsAssert(mIsGraphicsContext);
824    if (pf == NULL) {
825        mFragment.set(mStateFragment.mDefault);
826    } else {
827        mFragment.set(pf);
828    }
829}
830
831void Context::setProgramRaster(ProgramRaster *pr) {
832    rsAssert(mIsGraphicsContext);
833    if (pr == NULL) {
834        mRaster.set(mStateRaster.mDefault);
835    } else {
836        mRaster.set(pr);
837    }
838}
839
840void Context::setProgramVertex(ProgramVertex *pv) {
841    rsAssert(mIsGraphicsContext);
842    if (pv == NULL) {
843        mVertex.set(mStateVertex.mDefault);
844    } else {
845        mVertex.set(pv);
846    }
847}
848
849void Context::setFont(Font *f) {
850    rsAssert(mIsGraphicsContext);
851    if (f == NULL) {
852        mFont.set(mStateFont.mDefault);
853    } else {
854        mFont.set(f);
855    }
856}
857
858void Context::assignName(ObjectBase *obj, const char *name, uint32_t len) {
859    rsAssert(!obj->getName());
860    obj->setName(name, len);
861    mNames.add(obj);
862}
863
864void Context::removeName(ObjectBase *obj) {
865    for (size_t ct=0; ct < mNames.size(); ct++) {
866        if (obj == mNames[ct]) {
867            mNames.removeAt(ct);
868            return;
869        }
870    }
871}
872
873RsMessageToClientType Context::peekMessageToClient(size_t *receiveLen, uint32_t *subID, bool wait) {
874    *receiveLen = 0;
875    if (!wait && mIO.mToClient.isEmpty()) {
876        return RS_MESSAGE_TO_CLIENT_NONE;
877    }
878
879    uint32_t bytesData = 0;
880    uint32_t commandID = 0;
881    const uint32_t *d = (const uint32_t *)mIO.mToClient.get(&commandID, &bytesData);
882    *receiveLen = bytesData - sizeof(uint32_t);
883    if (bytesData) {
884        *subID = d[0];
885    }
886    return (RsMessageToClientType)commandID;
887}
888
889RsMessageToClientType Context::getMessageToClient(void *data, size_t *receiveLen, uint32_t *subID, size_t bufferLen, bool wait) {
890    //LOGE("getMessageToClient %i %i", bufferLen, wait);
891    *receiveLen = 0;
892    if (!wait && mIO.mToClient.isEmpty()) {
893        return RS_MESSAGE_TO_CLIENT_NONE;
894    }
895
896    //LOGE("getMessageToClient 2 con=%p", this);
897    uint32_t bytesData = 0;
898    uint32_t commandID = 0;
899    const uint32_t *d = (const uint32_t *)mIO.mToClient.get(&commandID, &bytesData);
900    //LOGE("getMessageToClient 3    %i  %i", commandID, bytesData);
901
902    *receiveLen = bytesData - sizeof(uint32_t);
903    *subID = d[0];
904
905    //LOGE("getMessageToClient  %i %i", commandID, *subID);
906    if (bufferLen >= bytesData) {
907        memcpy(data, d+1, *receiveLen);
908        mIO.mToClient.next();
909        return (RsMessageToClientType)commandID;
910    }
911    return RS_MESSAGE_TO_CLIENT_RESIZE;
912}
913
914bool Context::sendMessageToClient(const void *data, RsMessageToClientType cmdID,
915                                  uint32_t subID, size_t len, bool waitForSpace) const {
916    //LOGE("sendMessageToClient %i %i %i %i", cmdID, subID, len, waitForSpace);
917    if (cmdID == 0) {
918        LOGE("Attempting to send invalid command 0 to client.");
919        return false;
920    }
921    if (!waitForSpace) {
922        if (!mIO.mToClient.makeSpaceNonBlocking(len + 12)) {
923            // Not enough room, and not waiting.
924            return false;
925        }
926    }
927    //LOGE("sendMessageToClient 2");
928    uint32_t *p = (uint32_t *)mIO.mToClient.reserve(len + sizeof(subID));
929    p[0] = subID;
930    if (len > 0) {
931        memcpy(p+1, data, len);
932    }
933    mIO.mToClient.commit(cmdID, len + sizeof(subID));
934    //LOGE("sendMessageToClient 3");
935    return true;
936}
937
938void Context::initToClient() {
939    while (!mRunning) {
940        usleep(100);
941    }
942}
943
944void Context::deinitToClient() {
945    mIO.mToClient.shutdown();
946}
947
948void Context::setError(RsError e, const char *msg) const {
949    mError = e;
950    sendMessageToClient(msg, RS_MESSAGE_TO_CLIENT_ERROR, e, strlen(msg) + 1, true);
951}
952
953
954void Context::dumpDebug() const {
955    LOGE("RS Context debug %p", this);
956    LOGE("RS Context debug");
957
958    LOGE(" EGL ver %i %i", mEGL.mMajorVersion, mEGL.mMinorVersion);
959    LOGE(" EGL context %p  surface %p,  Display=%p", mEGL.mContext, mEGL.mSurface, mEGL.mDisplay);
960    LOGE(" GL vendor: %s", mGL.mVendor);
961    LOGE(" GL renderer: %s", mGL.mRenderer);
962    LOGE(" GL Version: %s", mGL.mVersion);
963    LOGE(" GL Extensions: %s", mGL.mExtensions);
964    LOGE(" GL int Versions %i %i", mGL.mMajorVersion, mGL.mMinorVersion);
965    LOGE(" RS width %i, height %i", mWidth, mHeight);
966    LOGE(" RS running %i, exit %i, paused %i", mRunning, mExit, mPaused);
967    LOGE(" RS pThreadID %li, nativeThreadID %i", mThreadId, mNativeThreadId);
968
969    LOGV("MAX Textures %i, %i  %i", mGL.mMaxVertexTextureUnits, mGL.mMaxFragmentTextureImageUnits, mGL.mMaxTextureImageUnits);
970    LOGV("MAX Attribs %i", mGL.mMaxVertexAttribs);
971    LOGV("MAX Uniforms %i, %i", mGL.mMaxVertexUniformVectors, mGL.mMaxFragmentUniformVectors);
972    LOGV("MAX Varyings %i", mGL.mMaxVaryingVectors);
973}
974
975///////////////////////////////////////////////////////////////////////////////////////////
976//
977
978namespace android {
979namespace renderscript {
980
981void rsi_ContextFinish(Context *rsc) {
982}
983
984void rsi_ContextBindRootScript(Context *rsc, RsScript vs) {
985    Script *s = static_cast<Script *>(vs);
986    rsc->setRootScript(s);
987}
988
989void rsi_ContextBindSampler(Context *rsc, uint32_t slot, RsSampler vs) {
990    Sampler *s = static_cast<Sampler *>(vs);
991
992    if (slot > RS_MAX_SAMPLER_SLOT) {
993        LOGE("Invalid sampler slot");
994        return;
995    }
996
997    s->bindToContext(&rsc->mStateSampler, slot);
998}
999
1000void rsi_ContextBindProgramStore(Context *rsc, RsProgramStore vpfs) {
1001    ProgramStore *pfs = static_cast<ProgramStore *>(vpfs);
1002    rsc->setProgramStore(pfs);
1003}
1004
1005void rsi_ContextBindProgramFragment(Context *rsc, RsProgramFragment vpf) {
1006    ProgramFragment *pf = static_cast<ProgramFragment *>(vpf);
1007    rsc->setProgramFragment(pf);
1008}
1009
1010void rsi_ContextBindProgramRaster(Context *rsc, RsProgramRaster vpr) {
1011    ProgramRaster *pr = static_cast<ProgramRaster *>(vpr);
1012    rsc->setProgramRaster(pr);
1013}
1014
1015void rsi_ContextBindProgramVertex(Context *rsc, RsProgramVertex vpv) {
1016    ProgramVertex *pv = static_cast<ProgramVertex *>(vpv);
1017    rsc->setProgramVertex(pv);
1018}
1019
1020void rsi_ContextBindFont(Context *rsc, RsFont vfont) {
1021    Font *font = static_cast<Font *>(vfont);
1022    rsc->setFont(font);
1023}
1024
1025void rsi_AssignName(Context *rsc, void * obj, const char *name, uint32_t len) {
1026    ObjectBase *ob = static_cast<ObjectBase *>(obj);
1027    rsc->assignName(ob, name, len);
1028}
1029
1030void rsi_ObjDestroy(Context *rsc, void *optr) {
1031    ObjectBase *ob = static_cast<ObjectBase *>(optr);
1032    rsc->removeName(ob);
1033    ob->decUserRef();
1034}
1035
1036void rsi_ContextPause(Context *rsc) {
1037    rsc->pause();
1038}
1039
1040void rsi_ContextResume(Context *rsc) {
1041    rsc->resume();
1042}
1043
1044void rsi_ContextSetSurface(Context *rsc, uint32_t w, uint32_t h, ANativeWindow *sur) {
1045    rsc->setSurface(w, h, sur);
1046}
1047
1048void rsi_ContextSetPriority(Context *rsc, int32_t p) {
1049    rsc->setPriority(p);
1050}
1051
1052void rsi_ContextDump(Context *rsc, int32_t bits) {
1053    ObjectBase::dumpAll(rsc);
1054}
1055
1056void rsi_ContextDestroyWorker(Context *rsc) {
1057    rsc->destroyWorkerThreadResources();;
1058}
1059
1060}
1061}
1062
1063void rsContextDestroy(RsContext vcon) {
1064    LOGV("rsContextDestroy %p", vcon);
1065    Context *rsc = static_cast<Context *>(vcon);
1066    rsContextDestroyWorker(rsc);
1067    delete rsc;
1068    LOGV("rsContextDestroy 2 %p", vcon);
1069}
1070
1071RsContext rsContextCreate(RsDevice vdev, uint32_t version) {
1072    LOGV("rsContextCreate %p", vdev);
1073    Device * dev = static_cast<Device *>(vdev);
1074    Context *rsc = Context::createContext(dev, NULL);
1075    return rsc;
1076}
1077
1078RsContext rsContextCreateGL(RsDevice vdev, uint32_t version, RsSurfaceConfig sc) {
1079    LOGV("rsContextCreateGL %p", vdev);
1080    Device * dev = static_cast<Device *>(vdev);
1081    Context *rsc = Context::createContext(dev, &sc);
1082    LOGV("rsContextCreateGL ret %p ", rsc);
1083    return rsc;
1084}
1085
1086RsMessageToClientType rsContextPeekMessage(RsContext vrsc, size_t *receiveLen, uint32_t *subID, bool wait) {
1087    Context * rsc = static_cast<Context *>(vrsc);
1088    return rsc->peekMessageToClient(receiveLen, subID, wait);
1089}
1090
1091RsMessageToClientType rsContextGetMessage(RsContext vrsc, void *data, size_t *receiveLen, uint32_t *subID, size_t bufferLen, bool wait) {
1092    Context * rsc = static_cast<Context *>(vrsc);
1093    return rsc->getMessageToClient(data, receiveLen, subID, bufferLen, wait);
1094}
1095
1096void rsContextInitToClient(RsContext vrsc) {
1097    Context * rsc = static_cast<Context *>(vrsc);
1098    rsc->initToClient();
1099}
1100
1101void rsContextDeinitToClient(RsContext vrsc) {
1102    Context * rsc = static_cast<Context *>(vrsc);
1103    rsc->deinitToClient();
1104}
1105
1106// Only to be called at a3d load time, before object is visible to user
1107// not thread safe
1108void rsaGetName(RsContext con, void * obj, const char **name) {
1109    ObjectBase *ob = static_cast<ObjectBase *>(obj);
1110    (*name) = ob->getName();
1111}
1112