static int stressone(unsigned long long ramsizeMB) { size_t pagesPerMB = 1024 * 1024 / PAGE_SIZE; char *ram = malloc(ramsizeMB * 1024 * 1024); char *ramptr; size_t i, j, k; char *data = malloc(PAGE_SIZE); char *dataptr; size_t nMB = 0; unsigned long long before, after; if (!ram) { fprintf(stderr, "%s (%05d): ERROR: cannot allocate %llu MB of RAM: %s\n", argv0, gettid(), ramsizeMB, strerror(errno)); return -1; } if (!data) { fprintf(stderr, "%s (%d): ERROR: cannot allocate %d bytes of RAM: %s\n", argv0, gettid(), PAGE_SIZE, strerror(errno)); free(ram); return -1; } /* We don't care about initial state, but we do want * to fault it all into RAM, otherwise the first iter * of the loop below will be quite slow. We cna't use * 0x0 as the byte as gcc optimizes that away into a * calloc instead :-) */ memset(ram, 0xfe, ramsizeMB * 1024 * 1024); if (random_bytes(data, PAGE_SIZE) < 0) { free(ram); free(data); return -1; } before = now(); while (1) { ramptr = ram; for (i = 0; i < ramsizeMB; i++, nMB++) { for (j = 0; j < pagesPerMB; j++) { dataptr = data; for (k = 0; k < PAGE_SIZE; k += sizeof(long long)) { ramptr += sizeof(long long); dataptr += sizeof(long long); *(unsigned long long *)ramptr ^= *(unsigned long long *)dataptr; } } if (nMB == 1024) { after = now(); fprintf(stderr, "%s (%05d): INFO: %06llums copied 1 GB in %05llums\n", argv0, gettid(), after, after - before); before = now(); nMB = 0; } } } free(data); free(ram); }
SB_Timer_Comp_Queue::SB_Timer_Comp_Queue(int pv_qid, const char *pp_name) : SB_Ts_D_Queue(pv_qid, pp_name) { iv_tid = gettid(); }
MBOOL CamIOPipe:: configPipe(vector<PortInfo const*>const& vInPorts, vector<PortInfo const*>const& vOutPorts) { FUNCTION_LOG_START; MY_LOGD("+ tid(%d), %d in / %d out", gettid(), vInPorts.size(), vOutPorts.size()); MBOOL ret = MTRUE; // if (0 == vInPorts.size() || 0 == vOutPorts.size() || vOutPorts.size() > 2) { MY_LOGE("Port config error"); return MFALSE; } // if (EPortType_Sensor != vInPorts.at(0)->type) { MY_LOGE("The IN port type should be sensor type"); return MFALSE; } // for (MUINT32 i = 0; i < vOutPorts.size(); i++) { if (EPortType_MemoryOut != vOutPorts.at(i)->type) { MY_LOGE("The OUT port type should be EPortType_MemoryOut"); return MFALSE; } } // (1). callbacks mpCamIOPipe->setCallbacks(NULL, NULL, NULL); // (2). command queue config ret = ret && mpCamIOPipe->sendCommand(NSImageio::NSIspio::EPIPECmd_SET_CQ_CHANNEL, (MINT32)NSImageio::NSIspio::EPIPE_PASS1_CQ0, 0, 0 ) && mpCamIOPipe->sendCommand(NSImageio::NSIspio::EPIPECmd_SET_CQ_TRIGGER_MODE, (MINT32)NSImageio::NSIspio::EPIPE_PASS1_CQ0, (MINT32)NSImageio::NSIspio::EPIPECQ_TRIGGER_SINGLE_IMMEDIATE, (MINT32)NSImageio::NSIspio::EPIPECQ_TRIG_BY_START ) && mpCamIOPipe->sendCommand(NSImageio::NSIspio::EPIPECmd_SET_CONFIG_STAGE, (MINT32)NSImageio::NSIspio::eConfigSettingStage_Init, 0, 0 ); if (!ret) { MY_LOGE("Cammand queue config fail:%d", mpCamIOPipe->getLastErrorCode()); return ret; } // // (3). In sensor port vector<NSImageio::NSIspio::PortInfo const*> vCamIOInPorts; SensorPortInfo const* const pSensorPort = reinterpret_cast<SensorPortInfo const*> (vInPorts.at(0)); ::memcpy(&mrSensorPortInfo, const_cast<SensorPortInfo*>(pSensorPort),sizeof(SensorPortInfo)); MUINT32 u4SensorWidth = 0, u4SensorHeight = 0; MUINT32 u4RawPixelID = 0; EImageFormat eSensorFmt = eImgFmt_UNKNOWN; // (3.1) Sensor instance if (NULL == mpSensorHal) { mpSensorHal = SensorHal::createInstance(); if (NULL == mpSensorHal) { MY_LOGE("Null sensorHal object"); return MFALSE; } } // mpSensorHal->sendCommand(static_cast<halSensorDev_e>(pSensorPort->u4DeviceID), SENSOR_CMD_SET_SENSOR_DEV, 0, 0, 0 ); // //mpSensorHal->init(); ret = querySensorInfo( pSensorPort->u4DeviceID, pSensorPort->u4Scenario, pSensorPort->u4Bitdepth, eSensorFmt, u4SensorWidth, u4SensorHeight, u4RawPixelID); MY_LOGD("SensorPortInfo: (u4DeviceID, u4Scenario, bitdepth, fgBypassDelay, fgBypassScenaio, u4RawType) = (%d, %d, %d, %d, %d, %d)", pSensorPort->u4DeviceID, pSensorPort->u4Scenario, pSensorPort->u4Bitdepth, pSensorPort->fgBypassDelay, pSensorPort->fgBypassScenaio, pSensorPort->u4RawType); // MUINT32 u4SensorStride = u4SensorWidth; if (eImgFmt_BAYER8 == eSensorFmt || eImgFmt_BAYER10 == eSensorFmt || eImgFmt_BAYER12 == eSensorFmt) { u4SensorStride = NSImageio::NSIspio::queryRawStride(eSensorFmt, u4SensorWidth); } MY_LOGD("SensorPortInfo: (width, height, format, stride) = (%d, %d, 0x%x, %d, %d, %d)", u4SensorWidth, u4SensorHeight, eSensorFmt, u4SensorStride); // NSImageio::NSIspio::PortInfo tgi; tgi.eImgFmt = eSensorFmt; tgi.eRawPxlID = mapRawPixelID(u4RawPixelID); tgi.u4ImgWidth = u4SensorWidth; tgi.u4ImgHeight = u4SensorHeight; tgi.u4Stride[0] = u4SensorStride; tgi.u4Stride[1] = 0; tgi.u4Stride[2] = 0; tgi.type = NSImageio::NSIspio::EPortType_Sensor; mu4DeviceID = pSensorPort->u4DeviceID; tgi.index = ((mu4DeviceID == SENSOR_DEV_MAIN)||(mu4DeviceID == SENSOR_DEV_ATV)) ? (NSImageio::NSIspio::EPortIndex_TG1I) : (NSImageio::NSIspio::EPortIndex_TG2I); tgi.inout = NSImageio::NSIspio::EPortDirection_In; tgi.u4BufSize = (MUINT32)0; vCamIOInPorts.push_back(&tgi); // The raw type, 0: pure raw, 1: pre-process raw if(pSensorPort->u4RawType == 1) { ret = mpCamIOPipe->sendCommand(NSImageio::NSIspio::EPIPECmd_SET_IMGO_RAW_TYPE, (MINT32)NSImageio::NSIspio::eRawImageType_PreProc, 0, 0 ); } // // (4). Out Port vector<NSImageio::NSIspio::PortInfo const*> vCamIOOutPorts; NSImageio::NSIspio::PortInfo imgo; NSImageio::NSIspio::PortInfo img2o; for (MUINT32 i = 0; i < vOutPorts.size(); i++) { MemoryOutPortInfo const* const memOutPort= reinterpret_cast<MemoryOutPortInfo const*> (vOutPorts.at(i)); // if (0 == memOutPort->index) { MY_LOGD("MemoryOutPortInfo1: (fmt, width, height) = (0x%x, %d, %d)", tgi.eImgFmt, tgi.u4ImgWidth, tgi.u4ImgHeight); MY_LOGD("MemoryOutPortInfo1: stride = (%d, %d, %d)", memOutPort->u4Stride[0], memOutPort->u4Stride[1], memOutPort->u4Stride[2]); imgo.eImgFmt = tgi.eImgFmt; imgo.u4ImgWidth = tgi.u4ImgWidth; imgo.u4ImgHeight = tgi.u4ImgHeight; // no crop imgo.crop.y = 0; imgo.crop.h = imgo.u4ImgHeight; imgo.type = NSImageio::NSIspio::EPortType_Memory; imgo.index = NSImageio::NSIspio::EPortIndex_IMGO; imgo.inout = NSImageio::NSIspio::EPortDirection_Out; imgo.u4Stride[0] = memOutPort->u4Stride[0]; imgo.u4Stride[1] = memOutPort->u4Stride[1]; imgo.u4Stride[2] = memOutPort->u4Stride[2]; imgo.u4Offset = 0; vCamIOOutPorts.push_back(&imgo); } #warning [TODO] Should check the port config by scenario else if (1 == memOutPort->index) { MY_LOGD("MemoryOutPortInfo2: (fmt, width, height) = (0x%x, %d, %d)", memOutPort->eImgFmt, memOutPort->u4ImgWidth, memOutPort->u4ImgHeight); MY_LOGD("MemoryOutPortInfo2: stride = (%d, %d, %d)", memOutPort->u4Stride[0], memOutPort->u4Stride[1], memOutPort->u4Stride[2]); img2o.eImgFmt = memOutPort->eImgFmt; img2o.u4ImgWidth = memOutPort->u4ImgWidth; img2o.u4ImgHeight = memOutPort->u4ImgHeight; img2o.crop.y = 0; img2o.crop.h = img2o.u4ImgHeight; img2o.type = NSImageio::NSIspio::EPortType_Memory; img2o.index = NSImageio::NSIspio::EPortIndex_IMG2O; img2o.inout = NSImageio::NSIspio::EPortDirection_Out; img2o.u4Stride[0] = memOutPort->u4Stride[0]; img2o.u4Stride[1] = memOutPort->u4Stride[1]; img2o.u4Stride[2] = memOutPort->u4Stride[2]; vCamIOOutPorts.push_back(&img2o); mfgIsYUVPortON = MTRUE; } } ret = mpCamIOPipe->configPipe(vCamIOInPorts, vCamIOOutPorts); // ret = configSensor(pSensorPort->u4DeviceID, pSensorPort->u4Scenario, u4SensorWidth, u4SensorHeight, pSensorPort->fgBypassDelay, pSensorPort->fgBypassScenaio, MTRUE); FUNCTION_LOG_END; return ret; }
char * embperl_GetApacheAppName (/*in*/ tApacheDirConfig * pDirCfg) { char *n = pDirCfg?pDirCfg -> AppConfig.sAppName:"Embperl" ; if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: get_appname %s[%d/%d]\n", n?n:"", getpid(), gettid()) ; return n ; }
/** * @ingroup shell * * Shell command (ping). * @param nargs number of arguments in args array * @param args array of arguments * @return OK for success, SYSERR for syntax error */ shellcmd xsh_ping(int nargs, char *args[]) { int i = 0; int interval = 1000, count = 10, recv = 0, echoq = 0; ulong rtt = 0, min = 0, max = 0, total = 0; ulong startsec = 0, startms = 0; struct netaddr target; struct packet *pkt = NULL; char str[50]; /* Output help, if '--help' argument was supplied */ if (nargs == 2 && strncmp(args[1], "--help", 7) == 0) { printf("Usage: ping <IP>\n\n"); printf("Description:\n"); printf("\tSend ICMP echo requests to network hosts\n"); printf("Options:\n"); printf("\t<IP>\t\tIP address\n"); printf("\t-c count\tstop after sending count packets\n"); printf ("\t-i interval\tsleep interval milliseconds between pings\n"); printf("\t--help\t\tdisplay this help and exit\n"); return OK; } /* Check for correct number of arguments */ if (nargs < 2) { fprintf(stderr, "ping: too few arguments\n"); fprintf(stderr, "Try 'ping --help' for more information\n"); return SHELL_ERROR; } i = 1; while (i < nargs) { if (0 == strncmp(args[i], "-c", 3)) { i++; if (i < nargs) { count = atoi(args[i]); } else { fprintf(stderr, "ping: -c requires integer argument\n"); return SHELL_ERROR; } } else if (0 == strncmp(args[i], "-i", 3)) { i++; if (i < nargs) { interval = atoi(args[i]); } else { fprintf(stderr, "ping: -i requires integer argument\n"); return SHELL_ERROR; } } else if (SYSERR == dot2ipv4(args[i], &target)) { fprintf(stderr, "ping: %s is not a valid IPv4 address.\n", args[i]); return SHELL_ERROR; } i++; } netaddrsprintf(str, &target); if (0 == strncmp(str, "ERROR", 6)) { fprintf(stderr, "ping: destination IP address required.\n"); return SHELL_ERROR; } printf("PING %s\n", str); echoq = echoQueueAlloc(); if (SYSERR == echoq) { printf("...No free echo queues!\n"); return SHELL_ERROR; } startsec = clktime; startms = clkticks; for (i = 0; i < count; i++) { // Send ping packet if (SYSERR == icmpEchoRequest(&target, gettid(), i)) { printf("...Failed to reach %s\n", str); return SHELL_ERROR; } sleep(interval); if (NOMSG != recvclr()) { // pick reply packets off of the queue pkt = echoQueueGet(echoq); while ((NULL != (ulong)pkt) && (SYSERR != (ulong)pkt)) { rtt = echoTripTime(pkt); total += rtt; if ((rtt < min) || (0 == min)) { min = rtt; } if (rtt > max) { max = rtt; } echoPrintPkt(pkt, rtt); netFreebuf(pkt); recv++; pkt = echoQueueGet(echoq); } } } echoQueueDealloc(echoq); netaddrsprintf(str, &target); printf("--- %s ping statistics ---\n", str); printf("%d packets transmitted, %d received,", count, recv); printf(" %d%% packet loss,", (count - recv) * 100 / count); printf(" time %dms\n", (clktime - startsec) * 1000 + ((clkticks - startms) * 1000) / CLKTICKS_PER_SEC); printf("rtt min/avg/max = %d.%03d/", min / 1000, min % 1000); if (0 != recv) { printf("%d.%03d/", (total / recv) / 1000, (total / recv) % 1000); } else { printf("-/"); } printf("%d.%03d ms\n", max / 1000, max % 1000); return SHELL_OK; }
static void embperl_ApacheInitCleanup (void * p) #endif { #ifdef APACHE2 if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: embperl_ApacheInitCleanup [%d/%d]\n", getpid(), gettid()) ; return OK ; #else module * m ; /* make sure embperl module is removed before mod_perl in case mod_perl is loaded dynamicly*/ if ((m = ap_find_linked_module("mod_perl.c"))) { if (m -> dynamic_load_handle) { if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: ApacheInitCleanup: mod_perl.c dynamicly loaded -> remove mod_embperl.c [%d/%d]\n", getpid(), gettid()) ; /*embperl_EndPass1 () ;*/ ap_remove_module (&embperl_module) ; } else { if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: ApacheInitCleanup: mod_perl.c not dynamic loaded [%d/%d]\n", getpid(), gettid()) ; embperl_EndPass1 () ; } } else { if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: ApacheInitCleanup: mod_perl.c not found [%d/%d]\n", getpid(), gettid()) ; embperl_EndPass1 () ; } #endif }
static void *embperl_create_dir_config(apr_pool_t * p, char *d) { /*char buf [20] ;*/ tApacheDirConfig *cfg ; apr_pool_t * subpool ; embperl_ApacheInitUnload (p) ; #ifdef APACHE2 apr_pool_create_ex(&subpool, p, NULL, NULL); #else subpool = ap_make_sub_pool(p); #endif cfg = (tApacheDirConfig *) apr_pcalloc(subpool, sizeof(tApacheDirConfig)); #if 0 #ifdef APACHE2 apr_pool_cleanup_register(subpool, cfg, embperl_ApacheConfigCleanup, embperl_ApacheConfigCleanup); #else ap_register_cleanup(subpool, cfg, embperl_ApacheConfigCleanup, embperl_ApacheConfigCleanup); #endif #endif embperl_DefaultReqConfig (&cfg -> ReqConfig) ; embperl_DefaultAppConfig (&cfg -> AppConfig) ; embperl_DefaultComponentConfig (&cfg -> ComponentConfig) ; cfg -> bUseEnv = -1 ; if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: create_dir_config %s (0x%p) [%d/%d]\n", cfg -> AppConfig.sAppName?cfg -> AppConfig.sAppName:"", cfg, getpid(), gettid()) ; return cfg; }
Tracer::Tracer(const char *env_var, const char *file, unsigned int line) : m_emit(false) { s_trace_mutex.Acquire(); #ifdef __APPLE__ m_emit = true; #endif if (getenv("LOG_ALL")) m_emit = true; else { if (env_var) { const char *value = getenv(env_var); if (value && *value) m_emit = true; } else m_emit = true; } if (m_emit) { if (getenv("LOG_TIME")) { struct timeval tv; gettimeofday(&tv, NULL); if (s_logfile) fprintf(s_logfile, "%09u.%06u:", (unsigned)tv.tv_sec, (unsigned)tv.tv_usec); else printf("%09u.%06u:", (unsigned)tv.tv_sec, (unsigned)tv.tv_usec); // struct timespec tp; // clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp); // printf("%02u.%09u:", (unsigned)tp.tv_sec, // (unsigned)tp.tv_nsec); } if (getenv("LOG_TID")) { /// @todo boost::thread_id #if HAVE_GETTID unsigned int raw_tid = gettid(); #elif HAVE_NR_GETTID unsigned int raw_tid = (unsigned int)syscall(__NR_gettid); #elif HAVE_GETCURRENTTHREADID unsigned int raw_tid = ::GetCurrentThreadId(); #else #warning "No thread id implementation on this platform" unsigned int raw_tid = 0; #endif static std::map<unsigned int, unsigned int> tidmap; if (tidmap.find(raw_tid) == tidmap.end()) { // We're still under the Tracer sm_mutex so this is safe unsigned int tid = (unsigned int)tidmap.size(); tidmap[raw_tid] = tid; } if (s_logfile) fprintf(s_logfile, "%03u:", tidmap[raw_tid]); else printf("%03u:", tidmap[raw_tid]); } if (!strncmp(file, "../", 3)) file += 3; if (s_logfile) fprintf(s_logfile, "%-25s:%4u: ", file, line); else printf("%-25s:%4u: ", file, line); } }
// *********************************************************************** // *********************************************************************** // lc3 simulator task // // argc = 2 // argv[0] = 0 - load from system // 1 - load from FAT // int lc3Task(int argc, char* argv[]) { int DR, oldpc, ir; // local variables int i; int LC3_REGS[8]; // General purpose registers int LC3_CC = 0x02; // NZP condition codes int LC3_PC = 0x3000; // program counter int ips = 0; // instructions per swapTask(); int curTask = gettid(); // Initialize LC3 Simulator // clear registers for (i=0; i<8; i++) LC3_REGS[i] = 0; // set condition codes to nZp LC3_CC = 0x02; // load program if ((LC3_PC = loadLC3Program(argv)) < 0) { return -1; } // Execute LC3 program while(1) { oldpc = LC3_PC; // save old pc for debug message ir = getMemoryData(LC3_PC); // load ir and increment pc LC3_PC = LC3_PC + 1; // increment program counter DR = GET_DR; // preload destination register # switch(GET_OPCODE) { case LC3_ADD: // ADD instruction if (!GET_IMMEDIATE_BIT) { if (LC3_DEBUG&0x01) printf(ADD_MSG, oldpc, DR, GET_SR1, GET_SR2); LC3_REGS[DR] = MASKTO16BITS(LC3_REGS[GET_SR1] + LC3_REGS[GET_SR2]); } else { if (LC3_DEBUG&0x01) printf(ADDI_MSG, oldpc, DR, GET_SR1, MASKTO16BITS(SEXT5(ir))); LC3_REGS[DR] = MASKTO16BITS(LC3_REGS[GET_SR1] + SEXT5(ir)); } SET_CC(LC3_REGS[DR]); break; case LC3_AND: // AND instruction if (!GET_IMMEDIATE_BIT) { if (LC3_DEBUG&0x01) printf(AND_MSG, oldpc, DR, GET_SR1, GET_SR2); LC3_REGS[DR] = MASKTO16BITS(LC3_REGS[GET_SR1] & LC3_REGS[GET_SR2]); } else { if (LC3_DEBUG&0x01) printf(ANDI_MSG, oldpc, DR, GET_SR1, MASKTO16BITS(SEXT5(ir))); LC3_REGS[DR] = MASKTO16BITS(LC3_REGS[GET_SR1] & SEXT5(ir)); } SET_CC(LC3_REGS[DR]); break; case LC3_BR: // BR instruction if (ir == 0) { printf("\n**(%d) Illegal instruction 0x%04x at 0x%04x (frame %d)", LC3_TID, ir, LC3_PC, LC3_PC>>6); return -1; // abort! } if ((LC3_CC&0x04 && GET_N) || (LC3_CC&0x02 && GET_Z) || (LC3_CC&0x01 && GET_P)) LC3_PC = LC3_PC + SEXT9(ir); if (LC3_DEBUG&0x01) { char cchr[4]; cchr[0] = 0; if (GET_N) strcat(cchr, "N"); if (GET_Z) strcat(cchr, "Z"); if (GET_P) strcat(cchr, "P"); printf(BR_MSG, oldpc, cchr, LC3_PC); } break; case LC3_JMP: // JMP instruction if (LC3_DEBUG&0x01) { if (GET_BASER == 7) printf(RET_MSG, oldpc); else printf(JMP_MSG, oldpc, GET_BASER); } LC3_PC = LC3_REGS[GET_BASER]; break; case LC3_JSR: // JSR instruction LC3_REGS[7] = MASKTO16BITS(LC3_PC); if (GET_ADDR_BIT == 0) { if (LC3_DEBUG&0x01) printf(JSRR_MSG, oldpc, GET_BASER); LC3_PC = LC3_REGS[GET_BASER]; } else { if (LC3_DEBUG&0x01) printf(JSR_MSG, oldpc, LC3_PC + SEXT11(ir)); LC3_PC = LC3_PC + SEXT11(ir); } break; case LC3_LD: // LD instruction if (LC3_DEBUG&0x01) printf(LD_MSG, oldpc, DR, SEXT9(ir)); LC3_REGS[DR] = MASKTO16BITS(getMemoryData(LC3_PC + SEXT9(ir))); SET_CC(LC3_REGS[DR]); break; case LC3_LDI: // LDI instruction if (LC3_DEBUG&0x01) printf(LDI_MSG, oldpc, DR, SEXT9(ir)); LC3_REGS[DR] = MASKTO16BITS(getMemoryData(getMemoryData(LC3_PC + SEXT9(ir)))); SET_CC(LC3_REGS[DR]); break; case LC3_LDR: // LDR instruction if (LC3_DEBUG&0x01) printf(LDR_MSG, oldpc, DR, GET_BASER, SEXT6(ir)); LC3_REGS[DR] = MASKTO16BITS(getMemoryData(LC3_REGS[GET_BASER] + SEXT6(ir))); SET_CC(LC3_REGS[DR]); break; case LC3_LEA: // LEA instruction if (LC3_DEBUG&0x01) printf(LEA_MSG, oldpc, DR, LC3_PC + SEXT9(ir)); LC3_REGS[DR] = MASKTO16BITS(LC3_PC + SEXT9(ir)); SET_CC(LC3_REGS[DR]); break; case LC3_NOT: // NOT instruction if (LC3_DEBUG&0x01) printf(NOT_MSG, oldpc, DR, GET_SR1); LC3_REGS[DR] = MASKTO16BITS(~LC3_REGS[GET_SR1]); SET_CC(LC3_REGS[DR]); break; case LC3_ST: // ST instruction if (LC3_DEBUG&0x01) printf(ST_MSG, oldpc, GET_SR, LC3_PC + SEXT9(ir)); setMemoryData(LC3_PC + SEXT9(ir), LC3_REGS[GET_SR]); break; case LC3_STI: // STI instruction if (LC3_DEBUG&0x01) printf(STI_MSG, oldpc, GET_SR, SEXT9(ir)); setMemoryData(getMemoryData(LC3_PC + SEXT9(ir)), LC3_REGS[GET_SR]); break; case LC3_STR: // STR instruction if (LC3_DEBUG&0x01) printf(STR_MSG, oldpc, GET_SR, GET_BASER, SEXT6(ir)); setMemoryData(LC3_REGS[GET_BASER] + SEXT6(ir), LC3_REGS[GET_SR]); break; case LC3_TRAP: // TRAP instruction { int trapv = getMemoryData(GET_TRAPVECT8); // access trap vector getMemoryData(trapv); // access system routine switch(GET_TRAPVECT8) { // @DISABLE_SWAPS int tmp, string_address; // @ENABLE_SWAPS case LC3_GETID: { // Note: This function not supported by simulator. if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "GETTID"); //printf("\nLC3_TID = %d (%d)", LC3_TID, curTask); LC3_REGS[0] = LC3_TID; LC3_REGS[7] = MASKTO16BITS(LC3_PC); break; } case LC3_GETC: { // Note: This does not function quite like GETC. if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "GETC"); LC3_REGS[0] = MASKTO8BITS(getCharacter()); LC3_REGS[7] = MASKTO16BITS(LC3_PC); break; } case LC3_OUT: { if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "OUT"); putchar(LC3_REGS[0]); LC3_REGS[7] = MASKTO16BITS(LC3_PC); break; } case LC3_PUTSP: { if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "PUTSP"); putchar(' '); LC3_REGS[7] = MASKTO16BITS(LC3_PC); break; } case LC3_PUTS: { if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "PUTS"); string_address = LC3_REGS[0]; while((tmp=getMemoryData(string_address++)) != 0) putchar(tmp); LC3_REGS[7] = MASKTO16BITS(LC3_PC); break; } case LC3_IN: { // Note: This does not function quite like IN. if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "IN"); putchar(':'); LC3_REGS[0] = MASKTO8BITS(getCharacter()); LC3_REGS[7] = MASKTO16BITS(LC3_PC); break; } case LC3_HALT: { LC3_REGS[7] = MASKTO16BITS(LC3_PC); if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "HALT"); printf("\nProcess #%d Halted at 0x%04x\n", LC3_TID, LC3_PC); charFlag = 0; // release input return 0; } case LC3_getNextDirEntry: { // Note: This function not supported by simulator. // IN: R0 = int *dirNum // R1 = char* mask // R2 = DirEntry* dirEntry // R3 = int cDir // OUT: R0 = 0-success, otherwise error if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsGetNextDirEntry"); LC3_REGS[0] = fmsGetNextDirEntry((int*)getMemAdr(LC3_REGS[0], 1), // int *dirNum (char*)getMemAdr(LC3_REGS[1], 0), // char* mask (DirEntry*)getMemAdr(LC3_REGS[2], 1), // DirEntry* dirEntry (short int)LC3_REGS[3]); // int cDir swapTask(); break; } case LC3_closeFile: { // Note: This function not supported by simulator. // IN: R0 = int fileDescriptor // OUT: R0 = 0-success, otherwise error if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsCloseFile"); LC3_REGS[0] = fmsCloseFile((short int)LC3_REGS[0]); // int fileDescriptor swapTask(); break; } case LC3_defineFile: { // Note: This function not supported by simulator. // IN: R0 = char* fileName // OUT: R0 = 0-success, otherwise error char fileName[32]; char* s = (char*)getMemAdr(LC3_REGS[0], 0); int j = i = 0; if(!s[j]) j++; while((fileName[i++] = s[j])) j+=2; if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsCreateFile"); LC3_REGS[0] = fmsDefineFile(fileName, 0); // char* fileName swapTask(); break; } case LC3_deleteFile: { // Note: This function not supported by simulator. // IN: R0 = char* fileName // OUT: R0 = 0-success, otherwise error char fileName[32]; char* s = (char*)getMemAdr(LC3_REGS[0], 0); int j = i = 0; if(!s[j]) j++; while((fileName[i++] = s[j])) j+=2; if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsDeleteFile"); LC3_REGS[0] = fmsDeleteFile(fileName); // char* fileName swapTask(); break; } case LC3_openFile: { // Note: This function not supported by simulator. // IN: R0 = char* fileName // R1 = int rwMode // OUT: R0 = 0-success, otherwise error char fileName[32]; char* s = (char*)getMemAdr(LC3_REGS[0], 0); int j = i = 0; if(!s[j]) j++; while((fileName[i++] = s[j])) j+=2; if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsOpenFile"); LC3_REGS[0] = fmsOpenFile(fileName, // char* fileName (short int)LC3_REGS[1]); // int rwMode swapTask(); break; } case LC3_readFile: { // Note: This function not supported by simulator. // IN: R0 = int fileDescriptor // R1 = char* buffer // R2 = int nBytes // OUT: R0 = 0-success, otherwise error if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsReadFile"); LC3_REGS[0] = fmsReadFile((short int)LC3_REGS[0], // int fileDescriptor (char*)getMemAdr(LC3_REGS[1], 0), // char* buffer (short int)LC3_REGS[2]); // int nBytes swapTask(); break; } case LC3_seekFile: { // Note: This function not supported by simulator. // IN: R0 = int fileDescriptor // R1 = int index // OUT: R0 = 0-success, otherwise error if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsSeekFile"); LC3_REGS[0] = fmsSeekFile((short int)LC3_REGS[0], // int fileDescriptor (short int)LC3_REGS[1]); // int index swapTask(); break; } case LC3_writeFile: { // Note: This function not supported by simulator. // IN: R0 = int fileDescriptor // R1 = char* buffer // R2 = int nBytes // OUT: R0 = 0-success, otherwise error if (LC3_DEBUG&0x01) printf(TRAP_MSG, oldpc, "fmsWriteFile"); LC3_REGS[0] = fmsWriteFile((short int)LC3_REGS[0], // int fileDescriptor (char*)getMemAdr(LC3_REGS[1], 0), // char* buffer (short int)LC3_REGS[2]); // int nBytes swapTask(); break; } default: printf(TRAP_ERROR_MSG, GET_TRAPVECT8); break; } break; } default: printf(UNDEFINED_OPCODE_MSG, GET_OPCODE); return -1; // abort! } if (LC3_DEBUG&0x02) // debug mode { char cchr[4]; // \n--PC:3000 IR:193b Nzp - 0000 0001 0002 0003 0004 0005 0006 0007 printf("\n--PC:%04x IR:%04x ",LC3_PC, ir); cchr[0] = (LC3_CC&0x04)?'N':'n'; cchr[1] = (LC3_CC&0x02)?'Z':'z'; cchr[2] = (LC3_CC&0x01)?'P':'p'; cchr[3] = 0; printf("%s -", &cchr[0]); for (i=0; i<8; i++) printf(" %04x", LC3_REGS[i]); //getchar(); // enable to single step } // swapTask(); tasks every INSTRUCTIONS_PER_swapTask(); instructions if (ips++ > INSTRUCTIONS_PER_SWAP) { ips = 0; swapTask(); } } // end while(1) execution loop
static int connect_master(const char *need_str) { int fd = socket(AF_UNIX, SOCK_STREAM, 0); ASSERT(-1 != fd); char *env_sockaddr = getenv(ENVVARS_PREFIX "MASTER_UNIX_SOCKADDR"); ASSERT(env_sockaddr); char *env_job_id = getenv(ENVVARS_PREFIX "JOB_ID"); ASSERT(env_job_id); struct sockaddr_un addr = { .sun_family = AF_UNIX, }; ASSERT(strlen(env_sockaddr) < sizeof addr.sun_path); strcpy(addr.sun_path, env_sockaddr); int connect_rc = connect(fd, (struct sockaddr*) &addr, sizeof addr); if(0 != connect_rc) { close(fd); return -1; } char hello[strlen(PROTOCOL_HELLO) + strlen(env_job_id) + 24]; /* TODO: Avoid magic constant */ hello[sizeof hello-1] = 0; int len = snprintf(hello, sizeof hello-1, PROTOCOL_HELLO "%d:%d:%s:%s", getpid(), gettid(), env_job_id, need_str); if(!send_size(fd, len)) return false; bool hello_success = send_all(fd, hello, len); if(!hello_success) { close(fd); return -1; } return fd; }
static int show_thread() { int ID = __cilkrts_get_worker_number(); printf("Thread %d TID %lu CPU %d\n", ID, gettid(), sched_getcpu()); return 0; }
/* A real-time thread is very similar to the main function of a single-threaded * real-time app. Notice, that init_rt_thread() is called to initialized per-thread * data structures of the LITMUS^RT user space libary. */ void* rt_thread(void *tcontext) { int do_exit; struct thread_context *ctx = (struct thread_context *) tcontext; struct rt_task param; /* Set up task parameters */ memset(¶m, 0, sizeof(param)); param.exec_cost = EXEC_COST * NS_PER_MS; param.period = PERIOD * NS_PER_MS; param.relative_deadline = RELATIVE_DEADLINE * NS_PER_MS; /* What to do in the case of budget overruns? */ param.budget_policy = NO_ENFORCEMENT; /* The task class parameter is ignored by most plugins. */ param.cls = RT_CLASS_SOFT; /* The priority parameter is only used by fixed-priority plugins. */ param.priority = LITMUS_LOWEST_PRIORITY; /* Make presence visible. */ printf("RT Thread %d active.\n", ctx->id); /***** * 1) Initialize real-time settings. */ CALL( init_rt_thread() ); /* To specify a partition, do * * param.cpu = CPU; * be_migrate_to(CPU); * * where CPU ranges from 0 to "Number of CPUs" - 1 before calling * set_rt_task_param(). */ CALL( set_rt_task_param(gettid(), ¶m) ); /***** * 2) Transition to real-time mode. */ CALL( task_mode(LITMUS_RT_TASK) ); /* The task is now executing as a real-time task if the call didn't fail. */ /***** * 3) Invoke real-time jobs. */ do { /* Wait until the next job is released. */ sleep_next_period(); /* Invoke job. */ do_exit = job(); } while (!do_exit); /***** * 4) Transition to background mode. */ CALL( task_mode(BACKGROUND_TASK) ); return NULL; }
void TLSInit(struct ThreadLocalArea *tlp) { memset(tlp, 0, sizeof(struct ThreadLocalArea)); tlp->tid = gettid(); sprintf(tlp->tbuf, "Hello Thread[%d]\n", tlp->tid); }
int main(int argc, char **argv) { unsigned long long ramsizeGB = 1; char *end; int ch; int opt_ind = 0; const char *sopt = "hr:c:"; struct option lopt[] = { { "help", no_argument, NULL, 'h' }, { "ramsize", required_argument, NULL, 'r' }, { "cpus", required_argument, NULL, 'c' }, { NULL, 0, NULL, 0 } }; int ret; int ncpus = 0; argv0 = argv[0]; while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) { switch (ch) { case 'r': errno = 0; ramsizeGB = strtoll(optarg, &end, 10); if (errno != 0 || *end) { fprintf(stderr, "%s (%05d): ERROR: Cannot parse RAM size %s\n", argv0, gettid(), optarg); exit_failure(); } break; case 'c': errno = 0; ncpus = strtoll(optarg, &end, 10); if (errno != 0 || *end) { fprintf(stderr, "%s (%05d): ERROR: Cannot parse CPU count %s\n", argv0, gettid(), optarg); exit_failure(); } break; case '?': case 'h': fprintf(stderr, "%s: [--help][--ramsize GB][--cpus N]\n", argv0); exit_failure(); } } if (getpid() == 1) { if (mount_all() < 0) exit_failure(); ret = get_command_arg_ull("ramsize", &ramsizeGB); if (ret < 0) exit_failure(); } if (ncpus == 0) ncpus = sysconf(_SC_NPROCESSORS_ONLN); fprintf(stdout, "%s (%05d): INFO: RAM %llu GiB across %d CPUs\n", argv0, gettid(), ramsizeGB, ncpus); if (stress(ramsizeGB, ncpus) < 0) exit_failure(); exit_success(); }
void embperl_ApacheAddModule (void) { bApDebug |= ap_exists_config_define("EMBPERL_APDEBUG") ; #ifdef APACHE2 if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: Perl part initialization start [%d/%d]\n", getpid(), gettid()) ; return ; #else if (!ap_find_linked_module("mod_embperl.c")) { apr_pool_t * pool ; if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: About to add mod_embperl.c as dynamic module [%d/%d]\n", getpid(), gettid()) ; ap_add_module (&embperl_module) ; pool = perl_get_startup_pool () ; embperl_ApacheInitUnload (pool) ; } else if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: mod_embperl.c already added as dynamic module [%d/%d]\n", getpid(), gettid()) ; #endif }
/** * @ingroup arp * * Obtains a hardware address from the ARP table given a protocol address. * @param netptr network interface * @param praddr protocol address * @param hwaddr buffer into which hardware address should be placed * @return OK if hardware address was obtained, otherwise TIMEOUT or SYSERR */ syscall arpLookup(struct netif *netptr, const struct netaddr *praddr, struct netaddr *hwaddr) { struct arpEntry *entry = NULL; /**< pointer to ARP table entry */ uint lookups = 0; /**< num of ARP lookups performed */ int ttl; /**< TTL for ARP table entry */ irqmask im; /**< interrupt state */ /* Error check pointers */ if ((NULL == netptr) || (NULL == praddr) || (NULL == hwaddr)) { ARP_TRACE("Invalid args"); return SYSERR; } ARP_TRACE("Looking up protocol address"); /* Attempt to obtain destination hardware address from ARP table until: * 1) lookup succeeds; 2) TIMEOUT occurs; 3) SYSERR occurs; or * 4) maximum number of lookup attempts occrus. */ while (lookups < ARP_MAX_LOOKUP) { lookups++; /* Obtain entry from ARP table */ im = disable(); entry = arpGetEntry(praddr); /* If ARP entry does not exist; create an unresolved entry */ if (NULL == entry) { ARP_TRACE("Entry does not exist"); entry = arpAlloc(); if (SYSERR == (int)entry) { restore(im); return SYSERR; } entry->state = ARP_UNRESOLVED; entry->nif = netptr; netaddrcpy(&entry->praddr, praddr); entry->expires = clktime + ARP_TTL_UNRESOLVED; entry->count = 0; } /* Place hardware address in buffer if entry is resolved */ if (ARP_RESOLVED == entry->state) { netaddrcpy(hwaddr, &entry->hwaddr); ARP_TRACE("Entry exists"); return OK; } /* Entry is unresolved; enqueue thread to wait for resolution */ if (entry->count >= ARP_NTHRWAIT) { restore(im); ARP_TRACE("Queue of waiting threads is full"); return SYSERR; } entry->waiting[entry->count] = gettid(); entry->count++; ttl = (entry->expires - clktime) * CLKTICKS_PER_SEC; restore(im); /* Send an ARP request and wait for response */ if (SYSERR == arpSendRqst(entry)) { ARP_TRACE("Failed to send request"); return SYSERR; } recvclr(); switch (recvtime(ttl)) { case TIMEOUT: case SYSERR: return SYSERR; case ARP_MSG_RESOLVED: default: /* Reply received, address resolved, re-attempt lookup */ continue; } } return SYSERR; }
static void embperl_ApacheInit (server_rec *s, apr_pool_t *p) #endif { #ifndef APACHE2 int rc; #endif dTHX ; #ifndef APACHE2 embperl_ApacheInitUnload (p) ; #endif bApDebug |= ap_exists_config_define("EMBPERL_APDEBUG") ; if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: ApacheInit [%d/%d]\n", getpid(), gettid()) ; #ifdef APACHE2 bApInit = 1 ; return APR_SUCCESS ; #else ap_add_version_component ("Embperl/"VERSION) ; if ((rc = embperl_Init (aTHX_ NULL, NULL, s)) != ok) { ap_log_error (APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "Initialization of Embperl failed (#%d)\n", rc) ; } bApInit = 1 ; #endif }
void *AudioALSACaptureDataProviderEchoRefExt::readThread(void *arg) { status_t retval = NO_ERROR; AudioALSACaptureDataProviderEchoRefExt *pDataProvider = static_cast<AudioALSACaptureDataProviderEchoRefExt *>(arg); uint32_t open_index = pDataProvider->mOpenIndex; char nameset[32]; sprintf(nameset, "%s%d", __FUNCTION__, pDataProvider->mCaptureDataProviderType); prctl(PR_SET_NAME, (unsigned long)nameset, 0, 0, 0); #ifdef MTK_AUDIO_ADJUST_PRIORITY // force to set priority struct sched_param sched_p; sched_getparam(0, &sched_p); sched_p.sched_priority = RTPM_PRIO_AUDIO_RECORD + 5; if (0 != sched_setscheduler(0, SCHED_RR, &sched_p)) { ALOGE("[%s] failed, errno: %d", __FUNCTION__, errno); } else { sched_p.sched_priority = RTPM_PRIO_AUDIO_RECORD + 5; sched_getparam(0, &sched_p); ALOGD("sched_setscheduler ok, priority: %d", sched_p.sched_priority); } #endif ALOGD("+%s(), pid: %d, tid: %d, kReadBufferSize=%x", __FUNCTION__, getpid(), gettid(), kReadBufferSize); // read raw data from alsa driver char linear_buffer[kReadBufferSize]; while (pDataProvider->mEnable == true) { if (open_index != pDataProvider->mOpenIndex) { ALOGD("%s(), open_index(%d) != mOpenIndex(%d), return", __FUNCTION__, open_index, pDataProvider->mOpenIndex); break; } retval = pDataProvider->mEnableLock.lock_timeout(300); ASSERT(retval == NO_ERROR); if (pDataProvider->mEnable == false) { pDataProvider->mEnableLock.unlock(); break; } ASSERT(pDataProvider->mPcm != NULL); clock_gettime(CLOCK_REALTIME, &pDataProvider->mNewtime); pDataProvider->timerec[0] = calc_time_diff(pDataProvider->mNewtime, pDataProvider->mOldtime); pDataProvider->mOldtime = pDataProvider->mNewtime; int retval = pcm_read(pDataProvider->mPcm, linear_buffer, kReadBufferSize); if (retval != 0) { ALOGE("%s(), pcm_read() error, retval = %d", __FUNCTION__, retval); } clock_gettime(CLOCK_REALTIME, &pDataProvider->mNewtime); pDataProvider->timerec[1] = calc_time_diff(pDataProvider->mNewtime, pDataProvider->mOldtime); pDataProvider->mOldtime = pDataProvider->mNewtime; pDataProvider->GetCaptureTimeStamp(&pDataProvider->mStreamAttributeSource.Time_Info, kReadBufferSize); // use ringbuf format to save buffer info pDataProvider->mPcmReadBuf.pBufBase = linear_buffer; pDataProvider->mPcmReadBuf.bufLen = kReadBufferSize + 1; // +1: avoid pRead == pWrite pDataProvider->mPcmReadBuf.pRead = linear_buffer; pDataProvider->mPcmReadBuf.pWrite = linear_buffer + kReadBufferSize; pDataProvider->mEnableLock.unlock(); //Provide EchoRef data #if 0 //for check the echoref data got pDataProvider->provideCaptureDataToAllClients(open_index); #else pDataProvider->provideEchoRefCaptureDataToAllClients(open_index); #endif clock_gettime(CLOCK_REALTIME, &pDataProvider->mNewtime); pDataProvider->timerec[2] = calc_time_diff(pDataProvider->mNewtime, pDataProvider->mOldtime); pDataProvider->mOldtime = pDataProvider->mNewtime; ALOGD("%s, latency_in_us,%1.6lf,%1.6lf,%1.6lf", __FUNCTION__, pDataProvider->timerec[0], pDataProvider->timerec[1], pDataProvider->timerec[2]); } ALOGD("-%s(), pid: %d, tid: %d", __FUNCTION__, getpid(), gettid()); pthread_exit(NULL); return NULL; }
static void embperl_ApacheConfigCleanup (void * p) #endif { tApacheDirConfig * cfg = (tApacheDirConfig *) p ; dTHX ; if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: ApacheConfigCleanup [%d/%d]\n", getpid(), gettid()) ; #include "epcfg.h" #ifdef APACHE2 return OK ; #endif }
int main(int argc, char **argv) { int i, j, k, l; printf("color = 3, prob = 5 between 3 and 0\n"); if(setcolor(gettid(), 3)) fprintf(stderr, "holy crap\n"); if(setprob(3,0,5)) fprintf(stderr, "more crap\n"); struct sched_param param; param.sched_priority = 0; if(sched_setscheduler(0,4, ¶m) < 0) fprintf(stderr, "even more crap\n"); /* fork(); */ sched_yield(); int b = 300; for(i = 0; i < b; i++) { if(i%49 == 0) { printf("i is divisible by 50\n"); } for(j = 0; j < b; j++) { for(k = 0; k < b; k++) { l = j + k; } } } /* pthread_t t1, t2, t3; */ /* printf("%s\n", "testing setprob"); */ /* if(setprob(-1,0,5)) { */ /* printf("%s %s\n", "invalid color1 lower bound: ", strerror(errno)); */ /* } */ /* if(setprob(5,0,5)) { */ /* printf("%s %s\n", "invalid color1 upper bound: ", strerror(errno)); */ /* } */ /* if(setprob(0,-1,5)) { */ /* printf("%s %s\n", "invalid color2 lower bound: ", strerror(errno)); */ /* } */ /* if(setprob(0,5,5)) { */ /* printf("%s %s\n", "invalid color2 upper bound: ", strerror(errno)); */ /* } */ /* if(setprob(0,0,11)) { */ /* printf("%s %s\n", "invalid prob upper bound: ", strerror(errno)); */ /* } */ /* if(setprob(0,0,-1)) { */ /* printf("%s %s\n", "invalid prob lower bound: ", strerror(errno)); */ /* } */ /* printf("\n"); */ /* printf("%s\n", "testing getprob after bad values"); */ /* printf("%s %ld\n", "getprob(0,0))", getprob(0,0)); */ /* printf("\n"); */ /* printf("%s\n", "setting the following color probabilities"); */ /* printf("%s\n", "setprob(0,1,1))"); */ /* if(setprob(0,1,1)) { */ /* printf("%s\n", strerror(errno)); */ /* } */ /* else { */ /* printf("success!\n"); */ /* } */ /* printf("%s\n", "setprob(0,0,3)"); */ /* if(setprob(0,0,3)) { */ /* printf("%s\n", strerror(errno)); */ /* } */ /* else { */ /* printf("success!\n"); */ /* } */ /* printf("\n"); */ /* printf("%s\n", "testing getprob. check the returns!"); */ /* printf("%s: %ld\n", "getprob(0,0)", getprob(0,0)); */ /* printf("%s: %ld\n", "getprob(0,1)", getprob(0,1)); */ /* printf("\n"); */ /* printf("%s\n", "testing setcolor with invalid pid"); */ /* if(setcolor(-1, 4)) { */ /* printf("%s %s\n", "invalid pid", strerror(errno)); */ /* } */ /* printf("%s\n", "testing setcolor(gettid(), 4) with current pid"); */ /* if(setcolor(gettid(), 4)) { */ /* printf("%s\n", "this should not have failed"); */ /* } */ /* else { */ /* printf("success!\n"); */ /* } */ /* printf("%s\n", "testing getcolor(gettid())"); */ /* if(getcolor(gettid()) != 4) { */ /* printf("%s: %s\n", "problem", strerror(errno)); */ /* } */ /* else { */ /* printf("success!\n"); */ /* } */ return 0; }
static void *embperl_create_server_config(apr_pool_t * p, server_rec *s) { tApacheDirConfig *cfg = (tApacheDirConfig *) apr_pcalloc(p, sizeof(tApacheDirConfig)); bApDebug |= ap_exists_config_define("EMBPERL_APDEBUG") ; embperl_ApacheInitUnload (p) ; embperl_DefaultReqConfig (&cfg -> ReqConfig) ; embperl_DefaultAppConfig (&cfg -> AppConfig) ; embperl_DefaultComponentConfig (&cfg -> ComponentConfig) ; cfg -> bUseEnv = -1 ; if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: create_server_config (0x%p) [%d/%d]\n", cfg, getpid(), gettid()) ; return cfg; }
///#define DISABLE_FAST_SNIFF bool DataSource::fastsniff( int fd, const char* urlStr, String8 *mimeType) { #ifdef DISABLE_FAST_SNIFF return false; #endif ALOGD("fastsniff: fd is %d, urlStr is %s, strlen(urlStr) is %d", fd, urlStr, strlen(urlStr)); *mimeType =""; float confidence = 0.0f; sp<AMessage> *meta; String8 newMimeType ; sp<AMessage> newMeta; int len = 0; char buffer[256]; char linkto[256]; memset(buffer, 0, 256); memset(linkto, 0, 256); if(strlen(urlStr) == 0 && fd >= 0) { sprintf(buffer, "/proc/%d/fd/%d", gettid(), fd); len = readlink(buffer, linkto, sizeof(linkto)); if(len <= 5) { return false; } ALOGV("fastsniff pid %d, fd %d, fd=%d", gettid(), fd, len); } else if(fd < 0) { if(strlen(urlStr) > 255) { strncpy(linkto, urlStr, 255); linkto[255] = '\0'; } else strcpy(linkto, urlStr); ALOGD("linkto is %s", linkto); len = strlen(urlStr); } struct { unsigned FileextSize; char *FileextName; bool (*Snifffun)(const sp<DataSource> &source, String8 *mimeType, float *confidence, sp<AMessage> *meta); } snifftable[] = { { 4, ".ogg", SniffOgg }, { 4, ".mp3", FastSniffMP3}, { 4, ".aac", FastSniffAAC}, #ifdef MTK_AUDIO_APE_SUPPORT { 4, ".ape", SniffAPE }, #endif { 5, ".flac",SniffFLAC }, { 4, ".amr", SniffAMR }, { 4, ".awb", SniffAMR }, #ifdef MTK_ASF_PLAYBACK_SUPPORT { 4, ".wma", SniffASF }, #endif { 4, ".wav", SniffWAV} }; for (unsigned i = 0; i < sizeof(snifftable)/sizeof(snifftable[0]); ++i) { if(strcasestr(linkto + (len - snifftable[i].FileextSize), snifftable[i].FileextName) != NULL) { if((*snifftable[i].Snifffun)(this, &newMimeType, &confidence, &newMeta)) ALOGD("fastsniff is %s", snifftable[i].FileextName); break; } } if(confidence > 0.0) *mimeType = newMimeType; return confidence > 0.0; }
status_t ExtendedWriter::threadFunc() { mEstimatedDurationUs = 0; mEstimatedSizeBytes = 0; bool stoppedPrematurely = true; int64_t previousPausedDurationUs = 0; int64_t maxTimestampUs = 0; status_t err = OK; pid_t tid = gettid(); androidSetThreadPriority(tid, ANDROID_PRIORITY_AUDIO); prctl(PR_SET_NAME, (unsigned long)"ExtendedWriter", 0, 0, 0); while (!mDone) { MediaBuffer *buffer; err = mSource->read(&buffer); if (err != OK) { break; } if (mPaused) { buffer->release(); buffer = NULL; continue; } mEstimatedSizeBytes += buffer->range_length(); if (exceedsFileSizeLimit()) { buffer->release(); buffer = NULL; notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED, 0); break; } int64_t timestampUs; CHECK(buffer->meta_data()->findInt64(kKeyTime, ×tampUs)); if (timestampUs > mEstimatedDurationUs) { mEstimatedDurationUs = timestampUs; } if (mResumed) { previousPausedDurationUs += (timestampUs - maxTimestampUs - 20000); mResumed = false; } timestampUs -= previousPausedDurationUs; ALOGV("time stamp: %lld, previous paused duration: %lld", timestampUs, previousPausedDurationUs); if (timestampUs > maxTimestampUs) { maxTimestampUs = timestampUs; } if (exceedsFileDurationLimit()) { buffer->release(); buffer = NULL; notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_INFO_MAX_DURATION_REACHED, 0); break; } ssize_t n = fwrite( (const uint8_t *)buffer->data() + buffer->range_offset(), 1, buffer->range_length(), mFile); mOffset += n; if (n < (ssize_t)buffer->range_length()) { buffer->release(); buffer = NULL; break; } // XXX: How to tell it is stopped prematurely? if (stoppedPrematurely) { stoppedPrematurely = false; } buffer->release(); buffer = NULL; } if (stoppedPrematurely) { notify(MEDIA_RECORDER_EVENT_INFO, MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS, UNKNOWN_ERROR); } if ( mFormat == AUDIO_FORMAT_QCELP ) { writeQCPHeader( ); } else if ( mFormat == AUDIO_FORMAT_EVRC ) { writeEVRCHeader( ); } fflush(mFile); fclose(mFile); mFile = NULL; mReachedEOS = true; if (err == ERROR_END_OF_STREAM || (err == -ETIMEDOUT)) { return OK; } return err; }
void vfileLogger(int priority, const char *format, va_list optional_arguments) { int n = 0; int error = EXIT_SUCCESS; const int saved_errno = errno; int internalError = EXIT_SUCCESS; const int LogMask = setlogmask(0); /* Check priority against setlogmask values. */ if ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) { //char logMsg[2048]; //char logFormat[1024]; //char *cursor = logFormat; char *buf = 0; size_t bufsize = 1024; FILE *f = open_memstream(&buf, &bufsize); if (f != NULL) { struct tm now_tm; time_t now; (void) time(&now); /*cursor += strftime(cursor,sizeof(logFormat),"%h %e %T ",localtime_r(&now, &now_tm));*/ n = strftime(f->_IO_write_ptr,f->_IO_write_end - f->_IO_write_ptr,"%h %e %T ",localtime_r(&now, &now_tm)); //f->_IO_write_ptr += strftime(f->_IO_write_ptr,f->_IO_write_end - f->_IO_write_ptr,"%h %e %T ",localtime_r(&now, &now_tm)); f->_IO_write_ptr += n; if (LogTag) { /*cursor += sprintf (cursor,"%s: ",LogTag);*/ n += fprintf(f,"%s: ",LogTag); } if (LogStat & LOG_PID) { if (LogStat & LOG_TID) { const pid_t tid = gettid(); /*cursor += sprintf (cursor, "[%d:%d]", (int) getpid (),(int) tid);*/ n += fprintf(f,"[%d:%d]", (int) getpid (),(int) tid); } else { /*cursor += sprintf (cursor, "[%d]", (int) getpid ());*/ n += fprintf(f,"[%d]", (int) getpid ()); } } if (LogStat & LOG_RDTSC) { const unsigned long long int t = rdtsc(); /*cursor += sprintf (cursor, "(%llu)",t);*/ n += fprintf(f,"(%llu)",t); } /* (LogStat & LOG_RDTSC) */ if (LogStat & LOG_CLOCK) { #if HAVE_CLOCK_GETTIME struct timespec timeStamp; if (clock_gettime(CLOCK_MONOTONIC,&timeStamp) == 0) { /*cursor += sprintf (cursor, "(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec);*/ n += fprintf(f,"(%lu.%.9d)",timeStamp.tv_sec,timeStamp.tv_nsec); } else { const int error = errno; ERROR_MSG("clock_gettime CLOCK_MONOTONIC error %d (%m)",error); } #else static unsigned int alreadyPrinted = 0; /* to avoid to print this error msg on each call */ if (unlikely(0 == alreadyPrinted)) { ERROR_MSG("clock_gettime not available on this system"); alreadyPrinted = 1; } #endif } /* (LogStat & LOG_CLOCK) */ if (LogStat & LOG_LEVEL) { switch(LOG_PRI(priority)) { case LOG_EMERG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Emergency * %s",format);*/ n += fprintf(f, "[EMERG]"); break; case LOG_ALERT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Alert * %s",format);*/ n += fprintf(f, "[ALERT]"); break; case LOG_CRIT: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Critical * %s",format);*/ n += fprintf(f, "[CRIT]"); break; case LOG_ERR: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Error * %s",format);*/ n += fprintf(f, "[ERROR]"); break; case LOG_WARNING: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Warning * %s",format);*/ n += fprintf(f, "[WARNING]"); break; case LOG_NOTICE: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Notice * %s",format); */ n += fprintf(f, "[NOTICE]"); break; case LOG_INFO: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Info * %s",format);*/ n += fprintf(f, "[INFO]"); break; case LOG_DEBUG: /*cursor += snprintf(cursor,sizeof(logFormat) - (cursor - logFormat),"* Debug * %s",format);*/ n += fprintf(f, "[DEBUG]"); break; default: /*cursor += sprintf(cursor,"* <%d> * %s",priority,format);*/ n += fprintf(f,"[<%d>]",priority); } /* switch(priority) */ } /* (LogStat & LOG_LEVEL) */ errno = saved_errno; /* restore errno for %m format */ n += vfprintf(f, format, optional_arguments); /* Close the memory stream; this will finalize the data into a malloc'd buffer in BUF. */ fclose(f); /* * begin of the critical section. * Some of the function used below are thread cancellation points * (according to Advanced Programming in the Unix Environment 2nd ed p411) * so set the handler to avoid deadlocks and memory leaks */ cleanup_args cancelArgs; cancelArgs.buffer = buf; pthread_cleanup_push(cancel_handler, &cancelArgs); error = pthread_mutex_lock(&fileLock); if (likely(EXIT_SUCCESS == error)) { if (unlikely(LogStat & LOG_PERROR)) { /* add the format argument to the header */ const size_t n = strlen(format); const size_t size = bufsize + n + 1; char *logFormatBuffer = (char *)malloc(size); if (logFormatBuffer) { pthread_cleanup_push(free,logFormatBuffer); strcpyNcat(logFormatBuffer,buf,format); vfprintf(stderr, logFormatBuffer, optional_arguments); pthread_cleanup_pop(1); /* pop the handler and free the allocated memory */ } else { ERROR_MSG("failed to allocate %u bytes to print the msg on stderr",size); } } /* (LogStat & LOG_PERROR) */ /* file management */ if (unlikely(LOG_FILE_DURATION & LogStat)) { const time_t currentTime = time(NULL); const time_t elapsedTime = currentTime - startTime; if (unlikely(elapsedTime >= maxDuration)) { close(logFile); logFile = -1; } } /* (LOG_FILE_DURATION & LogStat) */ if (unlikely(-1 == logFile)) { error = createFile(); /* error already logged */ } if (likely(EXIT_SUCCESS == error)) { const ssize_t written = write(logFile,buf,n); if (written > 0) { if (unlikely(written != n)) { ERROR_MSG("only %d byte(s) of %d has been written to %s",written,n,fullFileName); if (LogStat & LOG_CONS) { int fd = open("/dev/console", O_WRONLY | O_NOCTTY, 0); if (fd >= 0 ) { dprintf(fd,"logMsg"); close(fd); fd = -1; } } /* (LogStat & LOG_CONS) */ if (unlikely((LogStat & LOG_FILE_SYNC_ON_ERRORS_ONLY) && (LOG_PRI(priority) <= LOG_ERR))) { /* flush data if the log priority is "upper" or equal to error */ error = fdatasync(logFile); if (error != 0) { error = errno; ERROR_MSG("fdatasync to %s error %d (%m)",fullFileName,error); } error = posix_fadvise(logFile, 0,0,POSIX_FADV_DONTNEED); /* tell the OS that log message bytes could be released from the file system cache */ if (error != 0) { ERROR_MSG("posix_fadvise to %s error %d (%m)",fullFileName,error); } } /* (unlikely((LogStat & LOG_FILE_SYNC_ON_ERRORS_ONLY) && (LOG_PRI(priority) <= LOG_ERR))) */ } /* (unlikely(written != n)) */ fileSize += written; #ifdef FILESYSTEM_PAGE_CACHE_FLUSH_THRESHOLD static size_t currentPageCacheMaxSize = 0; currentPageCacheMaxSize += written; if (currentPageCacheMaxSize >= FILESYSTEM_PAGE_CACHE_FLUSH_THRESHOLD) { /* tell the OS that log message bytes could be released from the file system cache */ if (likely(posix_fadvise(logFile, 0,0,POSIX_FADV_DONTNEED) == 0)) { currentPageCacheMaxSize = 0; DEBUG_MSG("used file system cache allowed to be flushed (size was %u)",currentPageCacheMaxSize); } else { NOTICE_MSG("posix_fadvise to %s error %d (%m), current page cache max size is %u",fullFileName,error,currentPageCacheMaxSize); } } #endif /* FILESYSTEM_PAGE_CACHE_FLUSH_THRESHOLD */ if ((LOG_FILE_ROTATE & LogStat) || (LOG_FILE_HISTO & LogStat)) { if (fileSize >= maxSize) { close(logFile); logFile = -1; } } } else if (0 == written) { WARNING_MSG("nothing has been written in %s", fullFileName); } else { error = errno; ERROR_MSG("write to %s error %d (%m)", fullFileName, error); } } /*(likely(EXIT_SUCCESS == error)) */ /* End of critical section. */ /*pthread_cleanup_pop(0); implementation can't allow to set this instruction here */ /* free allocated ressources */ internalError = pthread_mutex_unlock(&fileLock); if (internalError != EXIT_SUCCESS) { ERROR_MSG("pthread_mutex_lock fileLock error %d (%s)", internalError, strerror(internalError)); if (EXIT_SUCCESS == error) { error = internalError; } } /* (internalError != EXIT_SUCCESS) */ } else { ERROR_MSG("pthread_mutex_lock fileLock error %d (%s)", error, strerror(error)); } pthread_cleanup_pop(0); /* moved to avoid a build error, use the preprocessor to understand why * or have a look on man 3 pthread_cleanup_push: * push & pop MUST BE in the SAME lexical nesting level !!! */ free(buf); cancelArgs.buffer = buf = NULL; } else { /* open_memstream(&buf, &bufsize) == NULL */ ERROR_MSG("failed to get stream buffer"); /* TMP! display the raw message to the console */ vfprintf(stderr,format,optional_arguments); /* TODO: write the raw message to the file */ } } /* ((LOG_MASK (LOG_PRI (priority)) & LogMask) != 0) */ /* message has not to be displayed because of the current LogMask and its priority */ /*return n;*/ }
static int task_api_test(void) { pthread_t pthread_id[CPU_SETSIZE]; cpu_set_t cpu_mask; int status, i; void *value_ptr; pthread_attr_t attr; printf("\n"); printf("TEST BEGIN: Task Management\n"); // Set stack size to something small to avoid running out of heap pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 1024 * 32); printf(" My Linux process id (PID) is: %d\n", getpid()); printf(" My Linux thread id (TID) is: %d\n", gettid()); status = pthread_getaffinity_np(pthread_self(), sizeof(cpu_mask), &cpu_mask); if (status) { printf(" ERROR: pthread_getaffinity_np() status=%d\n", status); return -1; } printf(" My CPU mask is: "); for (i = 0; i < CPU_SETSIZE; i++) { if (CPU_ISSET(i, &cpu_mask)) printf("%d ", i); } printf("\n"); printf(" Creating one thread for each CPU:\n"); pthread_mutex_lock(&num_threads_mutex); for (i = 0; i < CPU_SETSIZE; i++) { if (!CPU_ISSET(i, &cpu_mask)) continue; status = pthread_create( &pthread_id[num_threads], &attr, &hello_world_thread, (void *)(uintptr_t)num_threads+1 ); if (status) { printf(" ERROR: pthread_create() status=%d\n", status); continue; } else { printf(" created thread %d\n", num_threads+1); ++num_threads; } } pthread_mutex_unlock(&num_threads_mutex); printf(" Waiting for threads to exit:\n"); for (i = 0; i < num_threads; i++) { status = pthread_join(pthread_id[i], &value_ptr); if (status) { printf(" ERROR: pthread_join() status=%d\n", status); continue; } else { printf(" thread %d exited\n", (int)(uintptr_t)value_ptr); } } printf("TEST END: Task Management\n"); return 0; }
/* * Writes a summary of the signal to the log file. We do this so that, if * for some reason we're not able to contact debuggerd, there is still some * indication of the failure in the log. * * We could be here as a result of native heap corruption, or while a * mutex is being held, so we don't want to use any libc functions that * could allocate memory or hold a lock. */ static void log_signal_summary(int signum, const siginfo_t* info) { const char* signal_name = "???"; bool has_address = false; switch (signum) { case SIGABRT: signal_name = "SIGABRT"; break; case SIGBUS: signal_name = "SIGBUS"; has_address = true; break; case SIGFPE: signal_name = "SIGFPE"; has_address = true; break; case SIGILL: signal_name = "SIGILL"; has_address = true; break; case SIGPIPE: signal_name = "SIGPIPE"; break; case SIGSEGV: signal_name = "SIGSEGV"; has_address = true; break; #if defined(SIGSTKFLT) case SIGSTKFLT: signal_name = "SIGSTKFLT"; break; #endif case SIGTRAP: signal_name = "SIGTRAP"; break; } char thread_name[MAX_TASK_NAME_LEN + 1]; // one more for termination if (prctl(PR_GET_NAME, (unsigned long)thread_name, 0, 0, 0) != 0) { strcpy(thread_name, "<name unknown>"); } else { // short names are null terminated by prctl, but the man page // implies that 16 byte names are not. thread_name[MAX_TASK_NAME_LEN] = 0; } // "info" will be NULL if the siginfo_t information was not available. // Many signals don't have an address or a code. char code_desc[32]; // ", code -6" char addr_desc[32]; // ", fault addr 0x1234" addr_desc[0] = code_desc[0] = 0; if (info != NULL) { // For a rethrown signal, this si_code will be right and the one debuggerd shows will // always be SI_TKILL. snprintf(code_desc, sizeof(code_desc), ", code %d", info->si_code); if (has_address) { snprintf(addr_desc, sizeof(addr_desc), ", fault addr %p", info->si_addr); } } __libc_format_log(ANDROID_LOG_FATAL, "libc", "Fatal signal %d (%s)%s%s in tid %d (%s)", signum, signal_name, code_desc, addr_desc, gettid(), thread_name); }
// // timer-start (common) // static short sb_timer_start_com(const char *pp_where, bool pv_cc, Timer_TLE_Kind_Type pv_kind, int pv_toval, short pv_parm1, long pv_parm2, short *pp_tleid, pid_t pv_tid, SB_Ms_Event_Mgr *pp_mgr, Timer_Cb_Type pv_callback) { Timer_TLE_Type *lp_tle; short lv_fserr; int lv_status; short lv_tleid; SB_To lv_to; if (gv_timer_alloc) sb_timer_alloc(); lv_status = gv_timer_mutex.lock(); SB_util_assert_ieq(lv_status, 0); lp_tle = sb_timer_tle_alloc(pp_where, pv_kind); if (lp_tle == NULL) { if (pv_cc) lv_fserr = XZFIL_ERR_BADERR; // CCL else lv_fserr = XZFIL_ERR_NOTFOUND; lv_tleid = -1; } else { lv_fserr = XZFIL_ERR_OK; switch (pv_kind) { case TIMER_TLE_KIND_CB: lp_tle->ip_mgr = NULL; lp_tle->iv_stid = gettid(); lp_tle->iv_ttid = lp_tle->iv_stid; lp_tle->ip_comp_q = NULL; lp_tle->iv_cb = pv_callback; break; case TIMER_TLE_KIND_COMPQ: lp_tle->ip_mgr = pp_mgr; lp_tle->iv_stid = gettid(); lp_tle->iv_cb = NULL; if (pv_tid == 0) { lp_tle->iv_ttid = lp_tle->iv_stid; lp_tle->ip_comp_q = sb_timer_comp_q_get(); } else { lp_tle->iv_ttid = pv_tid; lp_tle->ip_comp_q = sb_timer_comp_q_get_tid(pv_tid); } break; default: break; } lv_to = sb_timer_to_calc(pv_toval); lp_tle->iv_to = lv_to; lp_tle->iv_toval = pv_toval; lp_tle->iv_parm1 = pv_parm1; lp_tle->iv_parm2 = pv_parm2; lv_tleid = lp_tle->iv_tleid; sb_timer_tle_insert(pp_where, lv_to, lp_tle); if (gv_ms_trace_timer) sb_timer_timer_list_print(); } lv_status = gv_timer_mutex.unlock(); SB_util_assert_ieq(lv_status, 0); *pp_tleid = lv_tleid; if (gv_ms_trace_params) trace_where_printf(pp_where, "EXIT tleid=%d, ret=%d\n", lv_tleid, lv_fserr); return lv_fserr; }
static int embperl_ApacheInitUnload (apr_pool_t *p) { #ifdef APACHE2 if (!unload_subpool && p) { apr_pool_create_ex(&unload_subpool, p, NULL, NULL); apr_pool_cleanup_register(unload_subpool, NULL, embperl_ApacheInitCleanup, embperl_ApacheInitCleanup); if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: ApacheInitUnload [%d/%d]\n", getpid(), gettid()) ; } #else if (!unload_subpool && p) { unload_subpool = ap_make_sub_pool(p); ap_register_cleanup(unload_subpool, NULL, embperl_ApacheInitCleanup, embperl_ApacheInitCleanup); if (bApDebug) ap_log_error (APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, APLOG_STATUSCODE NULL, "EmbperlDebug: ApacheInitUnload [%d/%d]\n", getpid(), gettid()) ; } #endif return ok ; }
void object_lock_exclusive_(IObject *thiz, const char *file, int line) { int ok; ok = pthread_mutex_trylock(&thiz->mMutex); if (0 != ok) { // not android_atomic_acquire_load because we don't care about relative load/load ordering int32_t oldGeneration = thiz->mGeneration; // wait up to a total of 250 ms static const long nanoBackoffs[] = { 10 * 1000000, 20 * 1000000, 30 * 1000000, 40 * 1000000, 50 * 1000000, 100 * 1000000}; unsigned i = 0; timespec ts; memset(&ts, 0, sizeof(timespec)); for (;;) { init_time_spec(&ts, nanoBackoffs[i]); ok = pthread_mutex_timedlock(&thiz->mMutex, &ts); if (0 == ok) { break; } if (EBUSY == ok) { // this is the expected return value for timeout, and will be handled below } else if (EDEADLK == ok) { // we don't use the kind of mutex that can return this error, but just in case SL_LOGE("%s:%d: recursive lock detected", file, line); } else { // some other return value SL_LOGE("%s:%d: pthread_mutex_lock_timeout_np returned %d", file, line, ok); } // is anyone else making forward progress? int32_t newGeneration = thiz->mGeneration; if (newGeneration != oldGeneration) { // if we ever see forward progress then lock without timeout (more efficient) goto forward_progress; } // no, then continue trying to lock but with increasing timeouts if (++i >= (sizeof(nanoBackoffs) / sizeof(nanoBackoffs[0]))) { // the extra block avoids a C++ compiler error about goto past initialization { pthread_t me = pthread_self(); pthread_t owner = thiz->mOwner; // unlikely, but this could result in a memory fault if owner is corrupt pid_t ownerTid = LIKELY_VALID(owner) ? __pthread_gettid(owner) : -1; SL_LOGW("%s:%d: pthread %p (tid %d) sees object %p was locked by pthread %p" " (tid %d) at %s:%d\n", file, line, *(void **)&me, gettid(), thiz, *(void **)&owner, ownerTid, thiz->mFile, thiz->mLine); } forward_progress: // attempt one more time without timeout; maybe this time we will be successful ok = pthread_mutex_lock(&thiz->mMutex); assert(0 == ok); break; } } } // here if mutex was successfully locked pthread_t zero; memset(&zero, 0, sizeof(pthread_t)); if (0 != memcmp(&zero, &thiz->mOwner, sizeof(pthread_t))) { pthread_t me = pthread_self(); pthread_t owner = thiz->mOwner; pid_t ownerTid = LIKELY_VALID(owner) ? __pthread_gettid(owner) : -1; if (pthread_equal(pthread_self(), owner)) { SL_LOGE("%s:%d: pthread %p (tid %d) sees object %p was recursively locked by pthread" " %p (tid %d) at %s:%d\n", file, line, *(void **)&me, gettid(), thiz, *(void **)&owner, ownerTid, thiz->mFile, thiz->mLine); } else { SL_LOGE("%s:%d: pthread %p (tid %d) sees object %p was left unlocked in unexpected" " state by pthread %p (tid %d) at %s:%d\n", file, line, *(void **)&me, gettid(), thiz, *(void **)&owner, ownerTid, thiz->mFile, thiz->mLine); } assert(false); } thiz->mOwner = pthread_self(); thiz->mFile = file; thiz->mLine = line; // not android_atomic_inc because we are already holding a mutex ++thiz->mGeneration; }
static void whoami(char *msg) { fprintf(stderr, "pid %ld Thread %ld %s\n", (long) getpid(), (long) gettid(), msg); fflush(stderr); }