int interrogate_success(isdn_ctrl *ic, struct call_struc *cs) { char *src = ic->parm.dss1_io.data; int restlen = ic->parm.dss1_io.datalen; int cnt = 1; u_char n,n1; char st[90], *p, *stp; if (restlen < 2) return(-100); /* frame too short */ if (*src++ != 0x30) return(-101); if ((n = *src++) > 0x81) return(-102); /* invalid length field */ restlen -= 2; /* remaining bytes */ if (n == 0x80) { if (restlen < 2) return(-103); if ((*(src+restlen-1)) || (*(src+restlen-2))) return(-104); restlen -= 2; } else if ( n == 0x81) { n = *src++; restlen--; if (n > restlen) return(-105); restlen = n; } else if (n > restlen) return(-106); else restlen = n; /* standard format */ if (restlen < 3) return(-107); /* no procedure */ if ((*src++ != 2) || (*src++ != 1) || (*src++ != 0x0B)) return(-108); restlen -= 3; if (restlen < 2) return(-109); /* list missing */ if (*src == 0x31) { src++; if ((n = *src++) > 0x81) return(-110); /* invalid length field */ restlen -= 2; /* remaining bytes */ if (n == 0x80) { if (restlen < 2) return(-111); if ((*(src+restlen-1)) || (*(src+restlen-2))) return(-112); restlen -= 2; } else if ( n == 0x81) { n = *src++; restlen--; if (n > restlen) return(-113); restlen = n; } else if (n > restlen) return(-114); else restlen = n; /* standard format */ } /* result list header */ while (restlen >= 2) { stp = st; sprintf(stp,"%d 0x%lx %d %s ",DIVERT_REPORT, ic->parm.dss1_io.ll_id, cnt++,divert_if.drv_to_name(ic->driver)); stp += strlen(stp); if (*src++ != 0x30) return(-115); /* invalid enum */ n = *src++; restlen -= 2; if (n > restlen) return(-116); /* enum length wrong */ restlen -= n; p = src; /* one entry */ src += n; if (!(n1 = put_address(stp,p,n & 0xFF))) continue; stp += strlen(stp); p += n1; n -= n1; if (n < 6) continue; /* no service and proc */ if ((*p++ != 0x0A) || (*p++ != 1)) continue; sprintf(stp," 0x%02x ",(*p++) & 0xFF); stp += strlen(stp); if ((*p++ != 0x0A) || (*p++ != 1)) continue; sprintf(stp,"%d ",(*p++) & 0xFF); stp += strlen(stp); n -= 6; if (n > 2) { if (*p++ != 0x30) continue; if (*p > (n-2)) continue; n = *p++; if (!(n1 = put_address(stp,p,n & 0xFF))) continue; stp += strlen(stp); } sprintf(stp,"\n"); put_info_buffer(st); } /* while restlen */ if (restlen) return(-117); return(0); } /* interrogate_success */
int ts_test() { // struct tsdev *ts; calibration cal; int cal_fd; char cal_buffer[256]; char *tsdevice = NULL; char *calfile = NULL; unsigned int i; int xtemp,ytemp; int x,y; /* Clear the LCD */ LCD_Clear(LCD_COLOR_WHITE); get_sample (&cal, 0, 50, 50, "Top left"); // clearbuf(ts); /* Clear the LCD */ // LCD_Clear(LCD_COLOR_WHITE); get_sample (&cal, 1, XRES - 50, 50, "Top right"); // clearbuf(ts); /* Clear the LCD */ // LCD_Clear(LCD_COLOR_WHITE); get_sample (&cal, 2, XRES - 50, YRES - 50, "Bot right"); // clearbuf(ts); /* Clear the LCD */ // LCD_Clear(LCD_COLOR_WHITE); get_sample (&cal, 3, 50, YRES - 50, "Bot left"); // clearbuf(ts); /* Clear the LCD */ // LCD_Clear(LCD_COLOR_WHITE); get_sample (&cal, 4, XRES / 2, YRES / 2, "Center"); if (perform_calibration (&cal)) { printf ("Calibration constants: "); for (i = 0; i < 7; i++) printf("%d ", cal.a [i]); printf("\n\r"); // if ((calfile = getenv("TSLIB_CALIBFILE")) != NULL) { // cal_fd = open (calfile, O_CREAT | O_RDWR); // } else { // cal_fd = open ("/etc/pointercal", O_CREAT | O_RDWR); // } sprintf (cal_buffer,"%d %d %d %d %d %d %d", cal.a[0], cal.a[1], cal.a[2], cal.a[3], cal.a[4], cal.a[5], cal.a[6]); printf ("%d %d %d %d %d %d %d", cal.a[1], cal.a[2], cal.a[0], cal.a[4], cal.a[5], cal.a[3], cal.a[6]); // write (cal_fd, cal_buffer, strlen (cal_buffer) + 1); // close (cal_fd); i = 0; } else { printf("Calibration failed.\n\r"); i = -1; } while(1) { getxy (&cal.x[0], &cal.y[0]); printf("before Calibration x = %d y=%d\n\r",cal.x[0],cal.y[0]); xtemp = cal.x[0]; ytemp = cal.y[0]; x = (int)(( cal.a[0] + cal.a[1]*xtemp + cal.a[2]*ytemp ) / cal.a[6]); y = (int)(( cal.a[3] + cal.a[4]*xtemp + cal.a[5]*ytemp ) / cal.a[6]); printf("after Calibration x = %d y=%d\n\r",x,y); LCD_Clear(LCD_COLOR_WHITE); LCD_DispNum(0,0,x,5,0); LCD_DispNum(0,16,y,5,0); } // close_framebuffer(); return i; }
void DrawProjections2(const char * testchar="", const char * numer="zdcx", const char * denom="vpdx") { const Int_t NBINS = 90; char filename[256]; if(!strcmp(testchar,"")) sprintf(filename,"fit_result.%s.%s.root",numer,denom); else sprintf(filename,"tests/%s/fit_result.%s.%s.root", testchar,numer,denom); TFile * infile = new TFile(filename,"READ"); TH1D * hist_all = (TH1D*) infile->Get("/asymmetry/asym_a3_v_run"); TFile * patfile[8]; char patfile_n[8][256]; Int_t pat_arr[8] = {13,14,23,24,31,32,41,42}; //Color_t colours[8] = {kOrange,kRed,kMagenta,kBlue,kCyan+1,kGreen+1,kYellow+2,kViolet-6}; Color_t colours[8] = {kBlue,kRed,kGreen+1,kMagenta,kBlue,kGreen+1,kRed,kMagenta}; // pairs TH1D * hist_pat[8]; for(Int_t pp=0; pp<8; pp++) { if(!strcmp(testchar,"")) sprintf(patfile_n[pp],"pats/fit_result.%s.%s.pat%d.root",numer,denom,pat_arr[pp]); else sprintf(patfile_n[pp],"tests/%s/pats/fit_result.%s.%s.pat%d.root", testchar,numer,denom,pat_arr[pp]); patfile[pp] = new TFile(patfile_n[pp],"READ"); hist_pat[pp] = (TH1D*) patfile[pp]->Get("/asymmetry/asym_a3_v_run"); }; // bin boundaries Double_t LBOUND=10; Double_t UBOUND=-10; for(Int_t pp=0; pp<8; pp++) { LBOUND = (hist_pat[pp]->GetMinimum() < LBOUND) ? hist_pat[pp]->GetMinimum():LBOUND; UBOUND = (hist_pat[pp]->GetMaximum() > UBOUND) ? hist_pat[pp]->GetMaximum():UBOUND; }; //LBOUND -= (UBOUND-LBOUND)*0.05; //UBOUND += (UBOUND-LBOUND)*0.05; LBOUND = -0.6e-2; // override UBOUND = 0.6e-2; // override printf("LBOUND=%f UBOUND=%f\n",LBOUND,UBOUND); char omit_str[64]; if(!strcmp(testchar,"")) strcpy(omit_str,""); else sprintf(omit_str," :: test %s",testchar); char asym_dist_all_n[256]; char asym_dist_all_t[256]; sprintf(asym_dist_all_n,"asym_dist_all"); //sprintf(asym_dist_all_t,"Run 13 S_{LL} distribution for %s/%s%s",numer,denom,omit_str); sprintf(asym_dist_all_t,"Run 13 S_{LL} distribution for rate-safe %s/%s%s",numer,denom,omit_str); TH1D * asym_dist_all = new TH1D(asym_dist_all_n,asym_dist_all_t,NBINS,LBOUND,UBOUND); asym_dist_all->SetLineWidth(2); asym_dist_all->SetLineColor(kBlack); char asym_dist_pat_n[8][256]; char asym_dist_pat_t[8][256]; TH1D * asym_dist_pat[8]; for(Int_t pp=0; pp<8; pp++) { sprintf(asym_dist_pat_n[pp],"asym_dist_pat%d",pp); //sprintf(asym_dist_pat_t[pp],"Run 13 S_{LL} distribution for %s/%s%s",numer,denom,omit_str); sprintf(asym_dist_pat_t[pp],"Run 13 S_{LL} distribution for rate-safe %s/%s%s",numer,denom,omit_str); asym_dist_pat[pp] = new TH1D(asym_dist_pat_n[pp],asym_dist_pat_t[pp],NBINS,LBOUND,UBOUND); asym_dist_pat[pp]->SetLineColor(colours[pp]); }; Double_t bc; for(Int_t b=1; b<=hist_all->GetNbinsX(); b++) { bc = hist_all->GetBinContent(b); asym_dist_all->Fill(bc); }; for(Int_t pp=0; pp<8; pp++) { for(Int_t b=1; b<=hist_pat[pp]->GetNbinsX(); b++) { bc = hist_pat[pp]->GetBinContent(b); if(bc!=0) asym_dist_pat[pp]->Fill(bc); }; }; // run 13 fits (2 gaussians) //TF1 * gaus1 = new TF1("gaus1","gaus",-1*WIDTH,0); //TF1 * gaus2 = new TF1("gaus2","gaus",0,WIDTH); TF1 * twogaus = new TF1("twogaus","[0]*exp(-0.5*((x-[1])/[2])^2)+[3]*exp(-0.5*((x-[4])/[5])^2)"); twogaus->SetParameter(0,80); // normalisation twogaus->SetParameter(3,80); twogaus->SetParameter(1,0.002); // mean twogaus->SetParameter(4,-0.002); twogaus->SetParameter(2,0.0005); // sigma twogaus->SetParameter(5,0.0005); twogaus->SetParNames("N_{R}","#mu_{R}","#sigma_{R}","N_{L}","#mu_{L}","#sigma_{L}"); //asym_dist_all->Fit(gaus1,"","",-1*WIDTH,0); //asym_dist_all->Fit(gaus2,"","",0,WIDTH); asym_dist_all->Fit(twogaus,"","",-1*WIDTH,WIDTH); c1->Close(); TCanvas * cc = new TCanvas("cc","cc",800,500); cc->SetGrid(1,0); gStyle->SetOptStat(1100); gStyle->SetOptFit(1); gStyle->SetStatFormat(".3g"); gStyle->SetFitFormat(".3g"); //gStyle->SetStatFontSize(0.1); Float_t size = 0.05; asym_dist_all->GetXaxis()->SetLabelSize(size); asym_dist_all->GetYaxis()->SetLabelSize(size); asym_dist_all->Draw(); gaus1->Draw("same"); gaus2->Draw("same"); for(Int_t pp=0; pp<8; pp++) { asym_dist_pat[pp]->GetXaxis()->SetLabelSize(size); asym_dist_pat[pp]->GetYaxis()->SetLabelSize(size); asym_dist_pat[pp]->Draw("same"); }; asym_dist_all->Draw("same"); Double_t sigma1 = gaus1->GetParameter(2); Double_t sigma2 = gaus2->GetParameter(2); Double_t sigma = (sigma1>sigma2)?sigma1:sigma2; Double_t mean = asym_dist_all->GetMean(); Double_t sys = sigma + fabs(mean); printf("sigma1 = %f\nsigma2 = %f\n",sigma1,sigma2); printf("sigma = %f\nmean = %f\nsystematic = %f\n",sigma,mean,sys); char printname[64]; if(!strcmp(testchar,"")) strcpy(printname,"projection.pdf"); else sprintf(printname,"projection.test%s.pdf",testchar); cc->Print(printname,"pdf"); };
int main(int argc,char *argv[]){ vqgen v; int entries=-1,dim=-1; int start=0,num=-1; float desired=.05f,mindist=0.f; int iter=1000; int biasp=1; int centroid=0; FILE *out=NULL; char *line; long i,j,k; int init=0; q.quant=-1; argv++; if(!*argv){ usage(); exit(0); } /* get the book name, a preexisting book to continue training */ { FILE *in=NULL; char *filename=alloca(strlen(*argv)+30),*ptr; strcpy(filename,*argv); in=fopen(filename,"r"); ptr=strrchr(filename,'-'); if(ptr){ int num; ptr++; num=atoi(ptr); sprintf(ptr,"%d.vqi",num+1); }else strcat(filename,"-0.vqi"); out=fopen(filename,"w"); if(out==NULL){ fprintf(stderr,"Unable to open %s for writing\n",filename); exit(1); } if(in){ /* we wish to suck in a preexisting book and continue to train it */ float a; line=rline(in,out,1); if(strcmp(line,vqext_booktype)){ fprintf(stderr,"wrong book type; %s!=%s\n",line,vqext_booktype); exit(1); } line=rline(in,out,1); if(sscanf(line,"%d %d %d",&entries,&dim,&vqext_aux)!=3){ fprintf(stderr,"Syntax error reading book file\n"); exit(1); } vqgen_init(&v,dim,vqext_aux,entries,mindist, vqext_metric,vqext_weight,centroid); init=1; /* quant setup */ line=rline(in,out,1); if(sscanf(line,"%ld %ld %d %d",&q.min,&q.delta, &q.quant,&q.sequencep)!=4){ fprintf(stderr,"Syntax error reading book file\n"); exit(1); } /* quantized entries */ i=0; for(j=0;j<entries;j++){ for(k=0;k<dim;k++){ line=rline(in,out,0); sscanf(line,"%f",&a); v.entrylist[i++]=a; } } vqgen_unquantize(&v,&q); /* bias */ i=0; for(j=0;j<entries;j++){ line=rline(in,out,0); sscanf(line,"%f",&a); v.bias[i++]=a; } v.seeded=1; { float *b=alloca((dim+vqext_aux)*sizeof(float)); i=0; while(1){ for(k=0;k<dim+vqext_aux;k++){ line=rline(in,out,0); if(!line)break; sscanf(line,"%f",b+k); } if(feof(in))break; vqgen_addpoint(&v,b,b+dim); } } fclose(in); } } /* get the rest... */ argv=argv++; while(*argv){ if(argv[0][0]=='-'){ /* it's an option */ if(!argv[1]){ fprintf(stderr,"Option %s missing argument.\n",argv[0]); exit(1); } switch(argv[0][1]){ case 'p': if(sscanf(argv[1],"%d,%d,%d",&entries,&dim,&q.quant)!=3) goto syner; break; case 's': if(sscanf(argv[1],"%d,%d",&start,&num)!=2){ num= -1; if(sscanf(argv[1],"%d",&start)!=1) goto syner; } break; case 'e': if(sscanf(argv[1],"%f",&desired)!=1) goto syner; break; case 'd': if(sscanf(argv[1],"%f",&mindist)!=1) goto syner; if(init)v.mindist=mindist; break; case 'i': if(sscanf(argv[1],"%d",&iter)!=1) goto syner; break; case 'b': biasp=0; break; case 'c': centroid=1; break; default: fprintf(stderr,"Unknown option %s\n",argv[0]); exit(1); } argv+=2; }else{ /* it's an input file */ char *file=strdup(*argv++); FILE *in; int cols=-1; if(!init){ if(dim==-1 || entries==-1 || q.quant==-1){ fprintf(stderr,"-p required when training a new set\n"); exit(1); } vqgen_init(&v,dim,vqext_aux,entries,mindist, vqext_metric,vqext_weight,centroid); init=1; } in=fopen(file,"r"); if(in==NULL){ fprintf(stderr,"Could not open input file %s\n",file); exit(1); } fprintf(out,"# training file entry: %s\n",file); while((line=rline(in,out,0))){ if(cols==-1){ char *temp=line; while(*temp==' ')temp++; for(cols=0;*temp;cols++){ while(*temp>32)temp++; while(*temp==' ')temp++; } fprintf(stderr,"%d colums per line in file %s\n",cols,file); } { int i; float b[cols]; if(start+num*dim>cols){ fprintf(stderr,"ran out of columns reading %s\n",file); exit(1); } while(*line==' ')line++; for(i=0;i<cols;i++){ /* static length buffer bug workaround */ char *temp=line; char old; while(*temp>32)temp++; old=temp[0]; temp[0]='\0'; b[i]=atof(line); temp[0]=old; while(*line>32)line++; while(*line==' ')line++; } if(num<=0)num=(cols-start)/dim; for(i=0;i<num;i++) vqext_addpoint_adj(&v,b,start+i*dim,dim,cols,num); } } fclose(in); } } if(!init){ fprintf(stderr,"No input files!\n"); exit(1); } vqext_preprocess(&v); /* train the book */ signal(SIGTERM,setexit); signal(SIGINT,setexit); for(i=0;i<iter && !exiting;i++){ float result; if(i!=0){ vqgen_unquantize(&v,&q); vqgen_cellmetric(&v); } result=vqgen_iterate(&v,biasp); vqext_quantize(&v,&q); if(result<desired)break; } /* save the book */ fprintf(out,"# OggVorbis VQ codebook trainer, intermediate file\n"); fprintf(out,"%s\n",vqext_booktype); fprintf(out,"%d %d %d\n",entries,dim,vqext_aux); fprintf(out,"%ld %ld %d %d\n", q.min,q.delta,q.quant,q.sequencep); /* quantized entries */ fprintf(out,"# quantized entries---\n"); i=0; for(j=0;j<entries;j++) for(k=0;k<dim;k++) fprintf(out,"%d\n",(int)(rint(v.entrylist[i++]))); fprintf(out,"# biases---\n"); i=0; for(j=0;j<entries;j++) fprintf(out,"%f\n",v.bias[i++]); /* we may have done the density limiting mesh trick; refetch the training points from the temp file */ rewind(v.asciipoints); fprintf(out,"# points---\n"); { /* sloppy, no error handling */ long bytes; char buff[4096]; while((bytes=fread(buff,1,4096,v.asciipoints))) while(bytes)bytes-=fwrite(buff,1,bytes,out); } fclose(out); fclose(v.asciipoints); vqgen_unquantize(&v,&q); vqgen_cellmetric(&v); exit(0); syner: fprintf(stderr,"Syntax error in argument '%s'\n",*argv); exit(1); }
/* * 功能: 场景相机状态自动更新 * 摘要: 该函数功能主要实现,根据自身的当前状态自动更新相机内部数据,无须外部干预 * 参数: - * 返回值: - * 作者: lpf * 创建日期: 2008.02.02 * 修改日志: * 2008.03.08 - lpf * 修正了相机在执行水平旋转和垂直旋转,并到达目的位置时,会不停的震动问题 * 2008.10.17 - lpf * 暂时屏蔽了"处理垂直角度与距离的限制"; */ void CRegionCamera::Update(void) { CClientRegion * c = GetGame()->GetRegion(); if (c == NULL) /*&& GetGame()->GetSetup()->bSound*/ return; // 处理场景3D音效 D3DXVECTOR3 * pos; D3DXVECTOR3 face; D3DXVECTOR3 right; D3DXVECTOR3 up; pos = c->GetCamera()->GetPosition(); //pos->z = -pos->z; GetGame()->GetAudioList()->SetListenerPosition(*pos); //pos->z = -pos->z; face = (*c->GetCamera()->GetView()) - (*pos); Vector3 v = face; D3DXVec3Normalize(&face, &face); D3DXVec3Cross(&right, &Vector3(0, 1, 0), &face); D3DXVec3Normalize(&right, &right); D3DXVec3Cross(&up, &face, &right); //face.z = -face.z; //up.z = -up.z; GetGame()->GetAudioList()->SetListenerOritation(face, up); if (g_bDebug) { if (GetKeyboard()->IsKeyDown(DIK_TAB)) { char t[255]; sprintf(t, "距离平方:%f", (v.x) * (v.x) + v.y * v.y + (v.z) * (v.z)); GetGame()->OutPutText(140, 40, t, 255, D3DCOLOR_ARGB(255, 255, 255, 255)); } } // 回到默认摄像机镜头角度H if (m_dwState & SCS_REPOS_H) { if (abs(m_iHoriAngle - m_iSourceHoriAngle) <= 5) { m_dwState &= ~SCS_REPOS_H; m_iHoriAngle = m_iSourceHoriAngle; }else { if (m_iHoriAngle > 180) m_iHoriAngle -= 360; else if(m_iHoriAngle < -180) m_iHoriAngle += 360; if (m_iHoriAngle > -45 && m_iHoriAngle < 135) m_iHoriAngle += 4; else if (m_iHoriAngle <= -45 || m_iHoriAngle >= 135) m_iHoriAngle -= 4; } } // 回到默认摄像机镜头角度V if (m_dwState & SCS_REPOS_V) { if (abs(m_iVertAngle - m_iSourceVertAngle) <= 5) { m_dwState &= ~SCS_REPOS_V; m_iVertAngle = m_iSourceVertAngle; }else { m_iVertAngle += (m_iSourceVertAngle - m_iVertAngle)/abs(m_iSourceVertAngle - m_iVertAngle) * 4; } } // 回到默认摄像机镜头角度V if (m_dwState & SCS_REPOS_D) { if (abs(s_fDistance - 17.0f) <= 1.0f) { m_dwState &= ~SCS_REPOS_D; s_fDistance = 17.0f; }else { s_fDistance += (17.0f - s_fDistance)/abs(17.0f - s_fDistance) * 0.5f; } } // 处理相机移动 if (m_dwState & SCS_MOVE) { if (D3DXVec3Length(&m_vMoveDis) < m_fMoveDis) m_vMoveDis += m_vMoveSpeed; //else // m_dwState &= ~SCS_MOVE; } // 处理相机水平旋转 if (m_dwState & SCS_ROTATE_H) { if (m_iHoriAngle > m_iHDesAngle) { m_fHCurAngle -= m_fHRotateSpeed; m_iHoriAngle = (int)m_fHCurAngle; if (m_iHoriAngle < m_iHDesAngle) m_iHoriAngle = m_iHDesAngle; }else if (m_iHoriAngle < m_iHDesAngle) { m_fHCurAngle += m_fHRotateSpeed; m_iHoriAngle = (int)m_fHCurAngle; if (m_iHoriAngle > m_iHDesAngle) m_iHoriAngle = m_iHDesAngle; }else m_dwState &= ~SCS_ROTATE_H; } // 处理相机垂直旋转 if (m_dwState & SCS_ROTATE_V) { if (m_iVertAngle > m_iVDesAngle) { m_fVCurAngle -= m_fVRotateSpeed; m_iVertAngle = (int)m_fVCurAngle; if (m_iVertAngle < m_iVDesAngle) m_iVertAngle = m_iVDesAngle; }else if (m_iVertAngle < m_iVDesAngle) { m_fVCurAngle += m_fVRotateSpeed; m_iVertAngle = (int)m_fVCurAngle; if (m_iVertAngle > m_iVDesAngle) m_iVertAngle = m_iVDesAngle; }else m_dwState &= ~SCS_ROTATE_V; } // 处理相机缩放 if (m_dwState & SCS_ZOOM) { if (m_fZoomSpeed > 0.0f) { if (s_fDistance < m_fZoomDesDis) s_fDistance += m_fZoomSpeed; else m_dwState &= ~SCS_ZOOM; }else if (m_fZoomSpeed < 0.0f) { if (s_fDistance > m_fZoomDesDis) s_fDistance += m_fZoomSpeed; else m_dwState &= ~SCS_ZOOM; } if (s_fDistance > s_fMaxDistance) { s_fDistance = s_fMaxDistance; m_dwState &= ~SCS_ZOOM; }else if (s_fDistance < s_fMinDistance) { s_fDistance = s_fMinDistance; m_dwState &= ~SCS_ZOOM; } } // 处理相机震动 if (m_dwState & SCS_SHOCK) { static const float fOffsetArray[6] = { 1.0f, -0.6f, 0.8f, -0.2f, 0.4f, 0.0f }; static int iOffPos = 0; DWORD dwCurrentTime = timeGetTime(); DWORD dwTimeElapse = dwCurrentTime - m_dwShockStartTime; if (dwTimeElapse > m_dwShockDelayTime) { m_fShcokrOffset = fOffsetArray[iOffPos] * m_fShockMaxRatio; if (dwTimeElapse > m_dwShockTimeLength) { iOffPos = 0; m_dwState &= ~SCS_SHOCK; } if (iOffPos > 4) iOffPos = 0; else ++iOffPos; } } // 处理垂直角度与距离的限制 //float angle = s_fDistance/17.0f * 43.0f; //m_fMinVAngle = angle > 43.0f?43.0f:angle; //if (m_iVertAngle < m_fMinVAngle) //{ // m_iVertAngle = m_fMinVAngle; // m_fVCurAngle = m_iVertAngle; //} if (s_fDistance > 0.0f) m_fDistance = s_fDistance; }
int ex_put_node_set (int exoid, int node_set_id, const int *node_set_node_list) { int dimid, node_list_id, node_set_id_ndx, iresult; long num_nodes_in_set, start[1], count[1]; nclong *lptr; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* first check if any node sets are specified */ if ((dimid = ncdimid (exoid, DIM_NUM_NS)) < 0) { exerrval = ncerr; sprintf(errmsg, "Error: no node sets specified in file id %d", exoid); ex_err("ex_put_node_set",errmsg,exerrval); return (EX_FATAL); } /* Lookup index of node set id in VAR_NS_IDS array */ node_set_id_ndx = ex_id_lkup(exoid,VAR_NS_IDS,node_set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no data allowed for NULL node set %d in file id %d", node_set_id,exoid); ex_err("ex_put_node_set",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate node set id %d in VAR_NS_IDS array in file id %d", node_set_id,exoid); ex_err("ex_put_node_set",errmsg,exerrval); return (EX_FATAL); } } /* inquire id's of previously defined dimensions */ if ((dimid = ncdimid (exoid, DIM_NUM_NOD_NS(node_set_id_ndx))) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate number of nodes in set %d in file id %d", node_set_id,exoid); ex_err("ex_put_node_set",errmsg,exerrval); return (EX_FATAL); } if (ncdiminq (exoid, dimid, (char *) 0, &num_nodes_in_set) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get number of nodes in set %d in file id %d", node_set_id,exoid); ex_err("ex_put_node_set",errmsg,exerrval); return (EX_FATAL); } /* inquire if variable for node set node list has been defined */ if ((node_list_id = ncvarid (exoid, VAR_NODE_NS(node_set_id_ndx))) == -1) { /* variable doesn't exist */ exerrval = ncerr; sprintf(errmsg, "Error: failed to locate node set %d node list in file id %d", node_set_id,exoid); ex_err("ex_put_node_set",errmsg,exerrval); return (EX_FATAL); } /* write out the node list array */ /* this contortion is necessary because netCDF is expecting nclongs; fortunately it's necessary only when ints and nclongs aren't the same size */ start[0] = 0; count[0] = num_nodes_in_set; if (sizeof(int) == sizeof(nclong)) { iresult = ncvarput(exoid, node_list_id, start, count, node_set_node_list); } else { lptr = itol (node_set_node_list, (int)num_nodes_in_set); iresult = ncvarput (exoid, node_list_id, start, count, lptr); free(lptr); } if (iresult == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store node set %d node list in file id %d", node_set_id,exoid); ex_err("ex_put_node_set",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); }
static int cs_value(MY_XML_PARSER *st,const char *attr, size_t len) { struct my_cs_file_info *i= (struct my_cs_file_info *)st->user_data; const struct my_cs_file_section_st *s; int state= (int)((s= cs_file_sec(st->attr, strlen(st->attr))) ? s->state : 0); switch (state) { case _CS_ID: i->cs.number= strtol(attr,(char**)NULL,10); break; case _CS_BINARY_ID: i->cs.binary_number= strtol(attr,(char**)NULL,10); break; case _CS_PRIMARY_ID: i->cs.primary_number= strtol(attr,(char**)NULL,10); break; case _CS_COLNAME: i->cs.name=mstr(i->name,attr,len,MY_CS_NAME_SIZE-1); break; case _CS_CSNAME: i->cs.csname=mstr(i->csname,attr,len,MY_CS_NAME_SIZE-1); break; case _CS_CSDESCRIPT: i->cs.comment=mstr(i->comment,attr,len,MY_CS_CSDESCR_SIZE-1); break; case _CS_FLAG: if (!strncmp("primary",attr,len)) i->cs.state|= MY_CS_PRIMARY; else if (!strncmp("binary",attr,len)) i->cs.state|= MY_CS_BINSORT; else if (!strncmp("compiled",attr,len)) i->cs.state|= MY_CS_COMPILED; break; case _CS_UPPERMAP: fill_uchar(i->to_upper,MY_CS_TO_UPPER_TABLE_SIZE,attr,len); i->cs.to_upper=i->to_upper; break; case _CS_LOWERMAP: fill_uchar(i->to_lower,MY_CS_TO_LOWER_TABLE_SIZE,attr,len); i->cs.to_lower=i->to_lower; break; case _CS_UNIMAP: fill_uint16(i->tab_to_uni,MY_CS_TO_UNI_TABLE_SIZE,attr,len); i->cs.tab_to_uni=i->tab_to_uni; break; case _CS_COLLMAP: fill_uchar(i->sort_order,MY_CS_SORT_ORDER_TABLE_SIZE,attr,len); i->cs.sort_order=i->sort_order; break; case _CS_CTYPEMAP: fill_uchar(i->ctype,MY_CS_CTYPE_TABLE_SIZE,attr,len); i->cs.ctype=i->ctype; break; case _CS_RESET: case _CS_DIFF1: case _CS_DIFF2: case _CS_DIFF3: case _CS_IDENTICAL: { /* Convert collation description from Locale Data Markup Language (LDML) into ICU Collation Customization expression. */ char arg[16]; const char *cmd[]= {"&","<","<<","<<<","="}; i->cs.tailoring= i->tailoring; mstr(arg,attr,len,sizeof(arg)-1); if (i->tailoring_length + 20 < sizeof(i->tailoring)) { char *dst= i->tailoring_length + i->tailoring; i->tailoring_length+= sprintf(dst," %s %s",cmd[state-_CS_RESET],arg); } } } return MY_XML_OK; }
HRESULT __stdcall VF_ReadDataFunc_Blen( VF_FileHandle hFileHandle, DWORD dwStream,void *lpData ) { char req[256]; char buf[256]; SOCKET s_in; int width; int height; int y; int rval; unsigned char * framebuf; conndesc * c = (conndesc*) hFileHandle; LPVF_ReadData_Video v = (LPVF_ReadData_Video) lpData; if (c == 0 || dwStream != VF_STREAM_VIDEO || v == 0) { return VF_ERROR; } s_in = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s_in < 0) { return VF_ERROR; } if (connect(s_in, (struct sockaddr*) &c->addr, sizeof(c->addr)) < 0) { goto errout; } sprintf(req, "GET /images/ppm/%d.ppm HTTP/1.0\n\n", (int) (v->dwFrameNumberL) + c->start); my_send(s_in, req); do { if (my_gets(s_in, buf, 256) <= 0) { goto errout; } } while (strcmp(buf, "P6\n") != 0); do { rval = my_gets(s_in, buf, 256); } while ( (buf[0] == '#' || buf[0] == '\n') && rval >= 0); if (sscanf(buf, "%d %d\n", &width, &height) != 2) { goto errout; } if (width != c->width || height != c->height) { goto errout; } my_gets(s_in, buf, 256); /* 255 */ framebuf = (unsigned char*) v->lpData; for (y = 0; y < height; y++) { unsigned char * p = framebuf + v->lPitch * y; unsigned char * e = p + width * 3; my_recv(s_in, (char*) p, width * 3); while (p != e) { unsigned char tmp = p[2]; p[2] = p[0]; p[0] = tmp; p += 3; } } closesocket(s_in); return VF_OK; errout: closesocket(s_in); return VF_ERROR; }
static int miscd_dodaemon(char *argv1, char *daemon) { struct sigaction act; char *commandline; char commbuf[10]; char ch; if (!check_file_writable(PASSFILE)) { fprintf(stderr, "Error! File %s is not writable.\n", PASSFILE); exit(-1); } if (!check_file_writable(BOARDS)) { fprintf(stderr, "Error! File %s is not writable.\n", BOARDS); exit(-1); } truncate(BOARDS, MAXBOARD * sizeof(struct boardheader)); if (load_ucache() != 0) { printf("ft,load ucache error!"); exit(-1); } /* init tmpfs */ sprintf(genbuf1,"%s/home",TMPFSROOT); mkdir(genbuf1,0700); sprintf(genbuf1,"%s/boards",TMPFSROOT); mkdir(genbuf1,0700); for (ch='A';ch<='Z';ch++) { sprintf(genbuf1,"%s/home/%c",TMPFSROOT,ch); mkdir(genbuf1,0700); } resolve_boards(); resolve_utmp(); resolve_guest_table(); if (argv1 != NULL) { switch (fork()) { case -1: printf("faint, i can't fork.\n"); exit(0); break; case 0: break; default: exit(0); break; } commandline = argv1; } else { commandline = commbuf; } setsid(); #ifdef AIX setpgrp(); #elif defined FREEBSD setpgid(0, 0); #else // by zixia setpgrp(0, 0); setpgrp(); #endif #ifdef AIX act.sa_handler = NULL; act.sa_flags = SA_RESTART | SA_NOCLDWAIT; sigaction(SIGCHLD, &act, NULL); #else act.sa_handler = reaper; act.sa_flags = SA_RESTART; sigaction(SIGCHLD, &act, NULL); #endif if (((daemon == NULL) || (!strcmp(daemon, "timed"))) && ((argv1 == NULL) || fork())) { strcpy(commandline, "timed"); timed(); exit(0); } if (((daemon == NULL) || (!strcmp(daemon, "killd"))) && ((argv1 == NULL) || fork())) { strcpy(commandline, "killd"); while (1) { time_t ft; ft = getnextday4am(); do { sleep(ft - time(0)); } while (ft > time(0)); if (argv1 == NULL) { dokilluser(); //doupdategiveupuser(); } else { switch (fork()) { case -1: bbslog("3error", "fork failed\n"); break; case 0: dokilluser(); //doupdategiveupuser(); exit(0); break; default: break; } } switch (fork()) { case -1: bbslog("3error", "fork failed\n"); break; case 0: dokillalldir(); exit(0); break; default: break; } }; exit(0); } if (((daemon == NULL) || (!strcmp(daemon, "userd"))) && ((argv1 == NULL) || fork())) { strcpy(commandline, "userd"); userd(); exit(0); } if ((daemon == NULL) || (!strcmp(daemon, "flushd"))) { strcpy(commandline, "flushd"); flushd(); exit(0); } return 0; }
int main(int argc, char *argv[]) { netsnmp_session session, *ss; netsnmp_pdu *pdu, *response; netsnmp_variable_list *vars; int arg; char *gateway; int count; struct varInfo *vip; u_int value = 0; struct counter64 c64value; float printvalue; time_t last_time = 0; time_t this_time; time_t delta_time; int sum; /* what the heck is this for, its never used? */ char filename[128] = { 0 }; struct timeval tv; struct tm tm; char timestring[64] = { 0 }, valueStr[64] = { 0}, maxStr[64] = { 0}; char outstr[256] = { 0 }, peakStr[64] = { 0}; int status; int begin, end, last_end; int print = 1; int exit_code = 0; switch (arg = snmp_parse_args(argc, argv, &session, "C:", &optProc)) { case -2: exit(0); case -1: usage(); exit(1); default: break; } gateway = session.peername; for (; optind < argc; optind++) { if (current_name >= MAX_ARGS) { fprintf(stderr, "%s: Too many variables specified (max %d)\n", argv[optind], MAX_ARGS); exit(1); } varinfo[current_name++].name = argv[optind]; } if (current_name == 0) { usage(); exit(1); } if (dosum) { if (current_name >= MAX_ARGS) { fprintf(stderr, "Too many variables specified (max %d)\n", MAX_ARGS); exit(1); } varinfo[current_name++].name = 0; } SOCK_STARTUP; /* * open an SNMP session */ ss = snmp_open(&session); if (ss == NULL) { /* * diagnose snmp_open errors with the input netsnmp_session pointer */ snmp_sess_perror("snmpdelta", &session); SOCK_CLEANUP; exit(1); } if (tableForm && timestamp) { printf("%s", gateway); } for (count = 0; count < current_name; count++) { vip = varinfo + count; if (vip->name) { vip->oidlen = MAX_OID_LEN; vip->info_oid = (oid *) malloc(sizeof(oid) * vip->oidlen); if (snmp_parse_oid(vip->name, vip->info_oid, &vip->oidlen) == NULL) { snmp_perror(vip->name); SOCK_CLEANUP; exit(1); } sprint_descriptor(vip->descriptor, vip); if (tableForm) printf("\t%s", vip->descriptor); } else { vip->oidlen = 0; strcpy(vip->descriptor, SumFile); } vip->value = 0; zeroU64(&vip->c64value); vip->time = 0; vip->max = 0; if (peaks) { vip->peak_count = -1; vip->peak = 0; vip->peak_average = 0; } } wait_for_period(period); end = current_name; sum = 0; while (1) { pdu = snmp_pdu_create(SNMP_MSG_GET); if (deltat) snmp_add_null_var(pdu, sysUpTimeOid, sysUpTimeLen); if (end == current_name) count = 0; else count = end; begin = count; for (; count < current_name && count < begin + varbindsPerPacket - deltat; count++) { if (varinfo[count].oidlen) snmp_add_null_var(pdu, varinfo[count].info_oid, varinfo[count].oidlen); } last_end = end; end = count; retry: status = snmp_synch_response(ss, pdu, &response); if (status == STAT_SUCCESS) { if (response->errstat == SNMP_ERR_NOERROR) { if (timestamp) { gettimeofday(&tv, (struct timezone *) 0); memcpy(&tm, localtime((time_t *) & tv.tv_sec), sizeof(tm)); if (((period % 60) && (!peaks || ((period * peaks) % 60))) || keepSeconds) sprintf(timestring, " [%02d:%02d:%02d %d/%d]", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_mon + 1, tm.tm_mday); else sprintf(timestring, " [%02d:%02d %d/%d]", tm.tm_hour, tm.tm_min, tm.tm_mon + 1, tm.tm_mday); } vars = response->variables; if (deltat) { if (!vars || !vars->val.integer) { fprintf(stderr, "Missing variable in reply\n"); continue; } else { this_time = *(vars->val.integer); } vars = vars->next_variable; } else { this_time = 1; } for (count = begin; count < end; count++) { vip = varinfo + count; if (vip->oidlen) { if (!vars || !vars->val.integer) { fprintf(stderr, "Missing variable in reply\n"); break; } vip->type = vars->type; if (vars->type == ASN_COUNTER64) { u64Subtract(vars->val.counter64, &vip->c64value, &c64value); memcpy(&vip->c64value, vars->val.counter64, sizeof(struct counter64)); } else { value = *(vars->val.integer) - vip->value; vip->value = *(vars->val.integer); } vars = vars->next_variable; } else { value = sum; sum = 0; } delta_time = this_time - vip->time; if (delta_time <= 0) delta_time = 100; last_time = vip->time; vip->time = this_time; if (last_time == 0) continue; if (vip->oidlen && vip->type != ASN_COUNTER64) { sum += value; } if (tableForm) { if (count == begin) { sprintf(outstr, "%s", timestring + 1); } else { outstr[0] = '\0'; } } else { sprintf(outstr, "%s %s", timestring, vip->descriptor); } if (deltat || tableForm) { if (vip->type == ASN_COUNTER64) { fprintf(stderr, "time delta and table form not supported for counter64s\n"); exit(1); } else { printvalue = ((float) value * 100) / delta_time; if (tableForm) sprintf(valueStr, "\t%.2f", printvalue); else sprintf(valueStr, " /sec: %.2f", printvalue); } } else { printvalue = (float) value; sprintf(valueStr, " /%d sec: ", period); if (vip->type == ASN_COUNTER64) printU64(valueStr + strlen(valueStr), &c64value); else sprintf(valueStr + strlen(valueStr), "%u", value); } if (!peaks) { strcat(outstr, valueStr); } else { print = 0; if (vip->peak_count == -1) { if (wait_for_peak_start(period, peaks) == 0) vip->peak_count = 0; } else { vip->peak_average += printvalue; if (vip->peak < printvalue) vip->peak = printvalue; if (++vip->peak_count == peaks) { if (deltat) sprintf(peakStr, " /sec: %.2f (%d sec Peak: %.2f)", vip->peak_average / vip->peak_count, period, vip->peak); else sprintf(peakStr, " /%d sec: %.0f (%d sec Peak: %.0f)", period, vip->peak_average / vip->peak_count, period, vip->peak); vip->peak_average = 0; vip->peak = 0; vip->peak_count = 0; print = 1; strcat(outstr, peakStr); } } } if (printmax) { if (printvalue > vip->max) { vip->max = printvalue; } if (deltat) sprintf(maxStr, " (Max: %.2f)", vip->max); else sprintf(maxStr, " (Max: %.0f)", vip->max); strcat(outstr, maxStr); } if (print) { if (fileout) { sprintf(filename, "%s-%s", gateway, vip->descriptor); print_log(filename, outstr + 1); } else { if (tableForm) printf("%s", outstr); else printf("%s\n", outstr + 1); fflush(stdout); } } } if (end == last_end && tableForm) printf("\n"); } else { if (response->errstat == SNMP_ERR_TOOBIG) { if (response->errindex <= varbindsPerPacket && response->errindex > 0) { varbindsPerPacket = response->errindex - 1; } else { if (varbindsPerPacket > 30) varbindsPerPacket -= 5; else varbindsPerPacket--; } if (varbindsPerPacket <= 0) { exit_code = 5; break; } end = last_end; continue; } else if (response->errindex != 0) { fprintf(stderr, "Failed object: "); for (count = 1, vars = response->variables; vars && count != response->errindex; vars = vars->next_variable, count++); if (vars) fprint_objid(stderr, vars->name, vars->name_length); fprintf(stderr, "\n"); /* * Don't exit when OIDs from file are not found on agent * exit_code = 1; * break; */ } else { fprintf(stderr, "Error in packet: %s\n", snmp_errstring(response->errstat)); exit_code = 1; break; } /* * retry if the errored variable was successfully removed */ if (!netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_APP_DONT_FIX_PDUS)) { pdu = snmp_fix_pdu(response, SNMP_MSG_GET); snmp_free_pdu(response); response = NULL; if (pdu != NULL) goto retry; } } } else if (status == STAT_TIMEOUT) { fprintf(stderr, "Timeout: No Response from %s\n", gateway); response = 0; exit_code = 1; break; } else { /* status == STAT_ERROR */ snmp_sess_perror("snmpdelta", ss); response = 0; exit_code = 1; break; } if (response) snmp_free_pdu(response); if (end == current_name) { wait_for_period(period); } } snmp_close(ss); SOCK_CLEANUP; return (exit_code); }
//CBool CTexture::LoadTargaTexture( CImage * texObj, CChar* name, CChar* sceneFileName ) //{ // //attache the sceneFileName path( without the dea file ) to the texture name // CChar pathName[MAX_NAME_SIZE]; // // if( sceneFileName ) //To deal with COLLADA files. // { // CChar * texName = GetAfterPath( name ); //don't know if it's required? Maybe the name in collada file has no path // //strcpy( pathName , sceneFileName ); // //CChar *removeExtra = GetAfterPath( pathName ); // //removeExtra[0] = 0; // //strcat( pathName, texName ); // //save functions. it should be copies in WIN32 Project as well // CChar g_currentVSceneNameWithoutDot[MAX_NAME_SIZE]; // Cpy( g_currentVSceneNameWithoutDot, g_currentVSceneName ); // GetWithoutDot( g_currentVSceneNameWithoutDot ); // // sprintf( pathName, "%s%s%s%s", "assets/vscenes/", g_currentVSceneNameWithoutDot, "/Textures/", texName ); // // } // else //To load independent targa files(not specified in a collada file ) // strcpy( pathName, name ); // // ILuint imageId; // ilGenImages(1, &imageId); // ilBindImage(imageId); // // PrintInfo( _T( "\nReading Image : " ) ); // PrintInfo( _T( "'" ) + CString( pathName ) + _T("'"), COLOR_RED_GREEN ); // // // Read in the image file into DevIL. // if (!ilLoadImage(pathName)) { // // ERROR // ilDeleteImages(1, &imageId); // CChar temp[MAX_NAME_SIZE]; // sprintf( temp, "\nError! CTexture::LoadTargaTexture > Couldn't load the targa file: '%s'", pathName ); // PrintInfo( temp, COLOR_RED ); // numErrors += 1; // // return false; // } // else { // texObj->SetWidth( ilGetInteger(IL_IMAGE_WIDTH) ); // texObj->SetHeight( ilGetInteger(IL_IMAGE_HEIGHT) ); // // CUChar* imageData; // CInt imageSize; // // imageSize = ilGetInteger(IL_IMAGE_WIDTH) * ilGetInteger(IL_IMAGE_HEIGHT) * ilGetInteger(IL_IMAGE_CHANNELS); // imageData = (CUChar*)malloc( imageSize ); // // if( ilGetInteger(IL_IMAGE_CHANNELS) == 3 ) // texObj->SetFormat( TGA_TRUECOLOR_24 ); // else if ( ilGetInteger(IL_IMAGE_CHANNELS) == 4 ) // texObj->SetFormat( TGA_TRUECOLOR_32 ); // // memcpy( imageData , ilGetData() , imageSize ); // texObj->SetImageData( imageData ); // ilDeleteImages(1, &imageId); // } // PrintInfo( "\nCreating Texture '" ); // PrintInfo(pathName, COLOR_RED_GREEN); // PrintInfo( "' "); // // CreateTargaTexture( texObj ); // // return CTrue; //} // CBool CTexture::LoadDDSTexture( CImage * texObj, CChar* name, CChar* sceneFileName, CBool reportError ) { //attache the sceneFileName path( without the dea file ) to the texture name CChar pathName[MAX_NAME_SIZE]; if( sceneFileName ) //To deal with COLLADA files. { CChar * texName = NULL; if( g_useOriginalPathOfDAETextures || g_updateTextureViaEditor) { texName = CNewData(CChar,MAX_NAME_SIZE); Cpy( texName, name ); } else { texName = GetAfterPath( name ); } GetWithoutDot( texName); Append( texName, ".dds" ); //replace %20 with space using std::string std::string s(texName); size_t i = 0; for (;;) { i = s.find("%20", i); if (i == string::npos) { break; } s.replace(i, 3, " "); } if( g_useOriginalPathOfDAETextures || g_updateTextureViaEditor) { s.begin(); size_t i = 0; for (;;) { i = s.find("file:/", i); if (i == string::npos) { break; } s.replace(i, 6, ""); } } strcpy(texName, s.c_str()); if( g_useOriginalPathOfDAETextures || g_updateTextureViaEditor) { strcpy( pathName, texName ); CDelete(texName); } else { CChar g_currentVSceneNameWithoutDot[MAX_NAME_SIZE]; Cpy( g_currentVSceneNameWithoutDot, g_currentVSceneName ); GetWithoutDot( g_currentVSceneNameWithoutDot ); sprintf( pathName, "%s%s%s%s", g_VScenePath, g_currentVSceneNameWithoutDot, "/Textures/", texName ); } } else //To load independent dds files(not specified in a collada file ) strcpy( pathName, name ); ifstream file(pathName, ios::binary); if (! file ) { if( reportError ) { CChar temp[MAX_NAME_SIZE]; sprintf( temp, "\nError! CTexture::LoadDDSTexture > Couldn't load the dds file: '%s'", pathName ); PrintInfo( temp, COLOR_RED ); numErrors += 1; } return false; } CDDS *m_ddsImage = CNew( CDDS ); if (! m_ddsImage->LoadFile(file) ) { if( reportError ) { CChar temp[MAX_NAME_SIZE]; sprintf( temp, "\nError! CTexture::LoadDDSTexture > Couldn't load the dds file: '%s'", pathName ); PrintInfo( temp, COLOR_RED ); numErrors += 1; } return false; } texObj->SetWidth( (CInt32)m_ddsImage->GetWidth() ); texObj->SetHeight( (CInt32)m_ddsImage->GetHeight() ); if( m_ddsImage->m_alphaChannel) texObj->SetFormat(TGA_TRUECOLOR_32); else texObj->SetFormat(TGA_TRUECOLOR_24); PrintInfo( "\nCreating Texture ' " ); PrintInfo(pathName, COLOR_RED_GREEN); PrintInfo( " '"); CreateDDSTexture( texObj, m_ddsImage ); return CTrue; }
IGL_INLINE igl::opengl::gliGenericImage * igl::opengl::gliReadTGA(FILE *fp, char *name, int /*hflip*/, int vflip) { igl::opengl::TgaHeader tgaHeader; igl::opengl::TgaFooter tgaFooter; char horzrev, vertrev; int width, height, bpp; int start, end, dir; int i, j, k; int pelbytes, wbytes; GLenum format; int components; RLEstate rleRec; RLEstate *rleInfo; int rle; int index, colors, length; GLubyte *cmap, *pixels, *data; int (*myfread)(RLEstate *rleInfo, unsigned char*, size_t, size_t, FILE*); igl::opengl::gliGenericImage *genericImage; /* Check the footer. */ if (fseek(fp, 0L - sizeof(tgaFooter), SEEK_END) || fread(&tgaFooter, sizeof(tgaFooter), 1, fp) != 1) { sprintf(error, "TGA: Cannot read footer from \"%s\"", name); if (_verbose) printf("%s\n", error); return NULL; } /* Check the signature. */ if (memcmp(tgaFooter.signature, TGA_SIGNATURE, sizeof(tgaFooter.signature)) == 0) { if (_verbose) printf("TGA: found New TGA\n"); } else { if (_verbose) printf("TGA: found Original TGA\n"); } if (fseek(fp, 0, SEEK_SET) || fread(&tgaHeader, sizeof(tgaHeader), 1, fp) != 1) { sprintf(error, "TGA: Cannot read header from \"%s\"", name); if (_verbose) printf("%s\n", error); return NULL; } if (_verbose && tgaHeader.idLength) { char *idString = (char*) malloc(tgaHeader.idLength); if (fread(idString, tgaHeader.idLength, 1, fp) != 1) { sprintf(error, "TGA: Cannot read ID field in \"%s\"", name); printf("%s\n", error); } else { printf("TGA: ID field: \"%*s\"\n", tgaHeader.idLength, idString); } free(idString); } else { /* Skip the image ID field. */ if (tgaHeader.idLength && fseek(fp, tgaHeader.idLength, SEEK_CUR)) { sprintf(error, "TGA: Cannot skip ID field in \"%s\"", name); if (_verbose) printf("%s\n", error); return NULL; } } /* Reassemble the multi-byte values correctly, regardless of host endianness. */ width = (tgaHeader.widthHi << 8) | tgaHeader.widthLo; height = (tgaHeader.heightHi << 8) | tgaHeader.heightLo; bpp = tgaHeader.bpp; if (_verbose) { printf("TGA: width=%d, height=%d, bpp=%d\n", width, height, bpp); } horzrev = tgaHeader.descriptor & TGA_DESC_HORIZONTAL; vertrev = tgaHeader.descriptor & TGA_DESC_VERTICAL; //vertrev=0; // // JASON - we can force this stuff if we want // if( hflip ) // horzrev = 1; if( vflip ) vertrev = 1; if (_verbose && horzrev) printf("TGA: horizontal reversed\n"); if (_verbose && vertrev) printf("TGA: vertical reversed\n"); rle = 0; switch (tgaHeader.imageType) { case TGA_TYPE_MAPPED_RLE: rle = 1; if (_verbose) printf("TGA: run-length encoded\n"); case TGA_TYPE_MAPPED: /* Test for alpha channel. */ format = GL_COLOR_INDEX; components = 1; if (_verbose) { printf("TGA: %d bit indexed image (%d bit palette)\n", tgaHeader.colorMapSize, bpp); } break; case TGA_TYPE_GRAY_RLE: rle = 1; if (_verbose) printf("TGA: run-length encoded\n"); case TGA_TYPE_GRAY: format = GL_LUMINANCE; components = 1; if (_verbose) printf("TGA: %d bit grayscale image\n", bpp); break; case TGA_TYPE_COLOR_RLE: rle = 1; if (_verbose) printf("TGA: run-length encoded\n"); case TGA_TYPE_COLOR: /* Test for alpha channel. */ if (bpp == 32) { format = GL_BGRA_EXT; components = 4; if (_verbose) { printf("TGA: %d bit color image with alpha channel\n", bpp); } } else { format = GL_BGR_EXT; components = 3; if (_verbose) printf("TGA: %d bit color image\n", bpp); } break; default: sprintf(error, "TGA: unrecognized image type %d\n", tgaHeader.imageType); if (_verbose) printf("%s\n", error); return NULL; } if ((format == GL_BGRA_EXT && bpp != 32) || (format == GL_BGR_EXT && bpp != 24) || ((format == GL_LUMINANCE || format == GL_COLOR_INDEX) && bpp != 8)) { /* FIXME: We haven't implemented bit-packed fields yet. */ fprintf(stderr, "bpp %d, format %x\n", bpp, (unsigned int)format); sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented"); if (_verbose) printf("%s\n", error); return NULL; } /* Check that we have a color map only when we need it. */ if (format == GL_COLOR_INDEX) { if (tgaHeader.colorMapType != 1) { sprintf(error, "TGA: indexed image has invalid color map type %d\n", tgaHeader.colorMapType); if (_verbose) printf("%s\n", error); return NULL; } } else if (tgaHeader.colorMapType != 0) { sprintf(error, "TGA: non-indexed image has invalid color map type %d\n", tgaHeader.colorMapType); if (_verbose) printf("%s\n", error); return NULL; } if (tgaHeader.colorMapType == 1) { /* We need to read in the colormap. */ index = (tgaHeader.colorMapIndexHi << 8) | tgaHeader.colorMapIndexLo; length = (tgaHeader.colorMapLengthHi << 8) | tgaHeader.colorMapLengthLo; if (_verbose) { printf("TGA: reading color map (%d + %d) * (%d / 8)\n", index, length, tgaHeader.colorMapSize); } if (length == 0) { sprintf(error, "TGA: invalid color map length %d", length); if (_verbose) printf("%s\n", error); return NULL; } if (tgaHeader.colorMapSize != 24) { /* We haven't implemented bit-packed fields yet. */ sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented"); if (_verbose) printf("%s\n", error); return NULL; } pelbytes = tgaHeader.colorMapSize / 8; colors = length + index; cmap = (GLubyte*)malloc (colors * pelbytes); /* Zero the entries up to the beginning of the map. */ memset(cmap, 0, index * pelbytes); /* Read in the rest of the colormap. */ if (fread(cmap, pelbytes, length, fp) != (size_t) length) { sprintf(error, "TGA: error reading colormap (ftell == %ld)\n", ftell (fp)); if (_verbose) printf("%s\n", error); return NULL; } if (pelbytes >= 3) { /* Rearrange the colors from BGR to RGB. */ int tmp; for (j = index; j < length * pelbytes; j += pelbytes) { tmp = cmap[j]; cmap[j] = cmap[j + 2]; cmap[j + 2] = tmp; } } } else { colors = 0; cmap = NULL; } /* Allocate the data. */ pelbytes = bpp / 8; pixels = (unsigned char *) malloc (width * height * pelbytes); if (rle) { rleRec.statebuf = 0; rleRec.statelen = 0; rleRec.laststate = 0; rleInfo = &rleRec; myfread = rle_fread; } else { rleInfo = NULL; myfread = std_fread; } wbytes = width * pelbytes; if (vertrev) { start = 0; end = height; dir = 1; } else { /* We need to reverse loading order of rows. */ start = height-1; end = -1; dir = -1; } for (i = start; i != end; i += dir) { data = pixels + i*wbytes; /* Suck in the data one row at a time. */ if (myfread(rleInfo, data, pelbytes, width, fp) != width) { /* Probably premature end of file. */ if (_verbose) { printf ("TGA: error reading (ftell == %ld, width=%d)\n", ftell(fp), width); } return NULL; } if (horzrev) { /* We need to mirror row horizontally. */ for (j = 0; j < width/2; j++) { GLubyte tmp; for (k = 0; k < pelbytes; k++) { tmp = data[j*pelbytes+k]; data[j*pelbytes+k] = data[(width-j-1)*pelbytes+k]; data[(width-j-1)*pelbytes+k] = tmp; } } } } if (rle) { free(rleInfo->statebuf); } if (fgetc (fp) != EOF) { if (_verbose) printf ("TGA: too much input data, ignoring extra...\n"); } genericImage = (igl::opengl::gliGenericImage*) malloc(sizeof(igl::opengl::gliGenericImage)); genericImage->width = width; genericImage->height = height; genericImage->format = format; genericImage->components = components; genericImage->cmapEntries = colors; genericImage->cmapFormat = GL_BGR_EXT; // XXX fix me genericImage->cmap = cmap; genericImage->pixels = pixels; return genericImage; }
int getAllInterfacesAndAddresses (JNIEnv *env, netif **netifPP) { DWORD ret; IP_ADAPTER_ADDRESSES *ptr, *adapters=0; ULONG len=ipinflen, count=0; netif *nif=0, *dup_nif, *last=0, *loopif=0, *curr; int tun=0, net=0; *netifPP = 0; /* * Get the IPv4 interfaces. This information is the same * as what previous JDK versions would return. */ ret = enumInterfaces(env, netifPP); if (ret == -1) { return -1; } else { count = ret; } /* locate the loopback (and the last) interface */ for (nif=*netifPP, last=nif; nif!=0; nif=nif->next) { if (nif->ifType == MIB_IF_TYPE_LOOPBACK) { loopif = nif; } last = nif; } // Retrieve IPv4 addresses with the IP Helper API curr = *netifPP; while (curr != NULL) { netaddr *netaddrP; ret = enumAddresses_win(env, curr, &netaddrP); if (ret == -1) { return -1; } curr->addrs = netaddrP; curr->naddrs += ret; curr = curr->next; } ret = getAdapters (env, &adapters); if (ret != ERROR_SUCCESS) { goto err; } /* Now get the IPv6 information. This includes: * (a) IPv6 information associated with interfaces already found * (b) IPv6 information for IPv6 only interfaces (probably tunnels) * * For compatibility with previous releases we use the naming * information gotten from enumInterfaces() for (a) entries * However, the index numbers are taken from the new API. * * The procedure is to go through the list of adapters returned * by the new API looking for entries that correspond to IPv4 interfaces * already found. */ ptr = adapters; while (ptr != NULL) { int c; netif *nif0; if (ptr->IfType == IF_TYPE_SOFTWARE_LOOPBACK && (loopif != NULL)) { c = getAddrsFromAdapter(ptr, &loopif->addrs); if (c == -1) { goto err; } loopif->naddrs += c; } else { int index = ptr->IfIndex; if (index != 0) { /* This entry is associated with an IPv4 interface */ for (nif=*netifPP; nif!=0; nif=nif->next) { if (nif->index == index) { /* found the interface entry * set the index to the IPv6 index and add the * IPv6 addresses */ nif->ipv6Index = ptr->Ipv6IfIndex; c = getAddrsFromAdapter(ptr, &nif->addrs); nif->naddrs += c; break; } } } else { /* This entry is IPv6 only */ char newname [128]; int c; /* Windows allocates duplicate adapter entries * for tunnel interfaces when there are multiple * physical adapters. Need to check * if this is a duplicate (ipv6Index is the same) */ dup_nif = 0; for (nif0=*netifPP; nif0!=0; nif0=nif0->next) { if (nif0->hasIpv6Address && ptr->Ipv6IfIndex == nif0->ipv6Index) { dup_nif = nif0; break; } } if (dup_nif == 0) { /* new interface */ nif = (netif *) calloc (1, sizeof(netif)); if (nif == 0) { goto err; } if (ptr->IfType == IF_TYPE_TUNNEL) { sprintf (newname, "tun%d", tun); tun ++; } else { sprintf (newname, "net%d", net); net ++; } nif->name = malloc (strlen(newname)+1); nif->displayName = malloc (wcslen(ptr->FriendlyName)*2+2); if (nif->name == 0 || nif->displayName == 0) { goto err; } strcpy (nif->name, newname); wcscpy ((PWCHAR)nif->displayName, ptr->FriendlyName); nif->dNameIsUnicode = TRUE; // the java.net.NetworkInterface abstraction only has index // so the Ipv6IfIndex needs to map onto index nif->index = ptr->Ipv6IfIndex; nif->ipv6Index = ptr->Ipv6IfIndex; nif->hasIpv6Address = TRUE; last->next = nif; last = nif; count++; c = getAddrsFromAdapter(ptr, &nif->addrs); if (c == -1) { goto err; } nif->naddrs += c; } else { /* add the addresses from this adapter to the * original (dup_nif) */ c = getAddrsFromAdapter(ptr, &dup_nif->addrs); if (c == -1) { goto err; } dup_nif->naddrs += c; } } } ptr=ptr->Next; } free (adapters); return count; err: if (*netifPP) { free_netif (*netifPP); } if (adapters) { free (adapters); } return -1; }
int prot_stat_callback(isdn_ctrl *ic) { struct call_struc *cs, *cs1; int i; unsigned long flags; cs = divert_head; /* start of list */ cs1 = NULL; while (cs) { if (ic->driver == cs->ics.driver) { switch (cs->ics.arg) { case DSS1_CMD_INVOKE: if ((cs->ics.parm.dss1_io.ll_id == ic->parm.dss1_io.ll_id) && (cs->ics.parm.dss1_io.hl_id == ic->parm.dss1_io.hl_id)) { switch (ic->arg) { case DSS1_STAT_INVOKE_ERR: sprintf(cs->info,"128 0x%lx 0x%x\n", ic->parm.dss1_io.ll_id, ic->parm.dss1_io.timeout); put_info_buffer(cs->info); break; case DSS1_STAT_INVOKE_RES: switch (cs->ics.parm.dss1_io.proc) { case 7: case 8: put_info_buffer(cs->info); break; case 11: i = interrogate_success(ic,cs); if (i) sprintf(cs->info,"%d 0x%lx %d\n",DIVERT_REPORT, ic->parm.dss1_io.ll_id,i); put_info_buffer(cs->info); break; default: printk(KERN_WARNING "dss1_divert: unknown proc %d\n",cs->ics.parm.dss1_io.proc); break; } break; default: printk(KERN_WARNING "dss1_divert unknown invoke answer %lx\n",ic->arg); break; } cs1 = cs; /* remember structure */ cs = NULL; continue; /* abort search */ } /* id found */ break; case DSS1_CMD_INVOKE_ABORT: printk(KERN_WARNING "dss1_divert unhandled invoke abort\n"); break; default: printk(KERN_WARNING "dss1_divert unknown cmd 0x%lx\n",cs->ics.arg); break; } /* switch ics.arg */ cs = cs->next; } /* driver ok */ } if (!cs1) { printk(KERN_WARNING "dss1_divert unhandled process\n"); return(0); } if (cs1->ics.driver == -1) { save_flags(flags); cli(); del_timer(&cs1->timer); if (cs1->prev) cs1->prev->next = cs1->next; /* forward link */ else divert_head = cs1->next; if (cs1->next) cs1->next->prev = cs1->prev; /* back link */ restore_flags(flags); kfree(cs1); } return(0); } /* prot_stat_callback */
int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program binary */ unsigned char *bin; size_t bin_len; cl_int bin_ret; /* Read program binary */ if (argc == 2) bin = read_buffer((char *)argv[1], &bin_len); else { printf("error: No binary specified\n"); exit(1); } /* Create a program */ cl_program program; program = clCreateProgramWithBinary(context, 1, &device, &bin_len, (const unsigned char **)&bin, &bin_ret, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithBinary' failed\n"); exit(1); } if (bin_ret != CL_SUCCESS) { printf("error: Invalid binary for device\n"); exit(1); } printf("program=%p\n", program); /* Free binary */ free(bin); printf("program binary loaded\n"); printf("\n"); ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object*/ cl_kernel kernel; kernel = clCreateKernel(program, "pre_decrement_ushort4", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_ushort4 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_ushort4)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_ushort4){{2, 2, 2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_ushort4), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_ushort4), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_ushort4 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_ushort4)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_ushort4)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_ushort4), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_ushort4), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_ushort4)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
/********************************************************************** * For a given dr_path - return TRUE if the path should be dropped, * return FALSE otherwise. * The check uses random criteria in order to determine whether or not * the path should be dropped. * First - if not all paths are initialized, it randomally chooses if * to use this path as a fault path or not. * Second - if the path is in the fault paths (meaning - it is equal * to or includes one of the fault paths) - then it randomally chooses * if to drop it or not. **********************************************************************/ boolean_t __osm_pkt_randomizer_process_path(IN osm_log_t * p_log, IN osm_pkt_randomizer_t * p_pkt_rand, IN osm_dr_path_t * p_dr_path) { boolean_t res = FALSE; static boolean_t rand_value_init = FALSE; static int rand_value; boolean_t in_fault_paths; uint8_t i; char buf[BUF_SIZE]; char line[BUF_SIZE]; OSM_LOG_ENTER(p_log); if (rand_value_init == FALSE) { int seed; #ifdef __WIN__ SYSTEMTIME st; #else struct timeval tv; struct timezone tz; #endif /* __WIN__ */ /* initiate the rand_value according to timeofday */ rand_value_init = TRUE; #ifdef __WIN__ GetLocalTime(&st); seed = st.wMilliseconds; #else gettimeofday(&tv, &tz); seed = tv.tv_usec; #endif /* __WIN__ */ srand(seed); } /* If the hop_count is 1 - then this is a mad down to our local port - don't drop it */ if (p_dr_path->hop_count <= 1) goto Exit; rand_value = rand(); sprintf(buf, "Path: "); /* update the dr_path into the buf */ for (i = 0; i <= p_dr_path->hop_count; i++) { sprintf(line, "[%X]", p_dr_path->path[i]); strcat(buf, line); } /* Check if the path given is in one of the fault paths */ in_fault_paths = __osm_pkt_randomizer_is_path_in_fault_paths(p_log, p_dr_path, p_pkt_rand); /* Check if all paths are initialized */ if (p_pkt_rand->num_paths_initialized < p_pkt_rand->osm_pkt_num_unstable_links) { /* Not all packets are initialized. */ if (in_fault_paths == FALSE) { /* the path is not in the false paths. Check using the rand value if to update it there or not. */ if (rand_value % (p_pkt_rand->osm_pkt_unstable_link_rate) == 0) { OSM_LOG(p_log, OSM_LOG_VERBOSE, "%s added to the fault_dr_paths list\n" "\t\t\t rand_value:%u, unstable_link_rate:%u \n", buf, rand_value, p_pkt_rand->osm_pkt_unstable_link_rate); /* update the path in the fault paths */ memcpy(& (p_pkt_rand-> fault_dr_paths[p_pkt_rand-> num_paths_initialized]), p_dr_path, sizeof(osm_dr_path_t)); p_pkt_rand->num_paths_initialized++; in_fault_paths = TRUE; } } } if (in_fault_paths == FALSE) { /* If in_fault_paths is FALSE - just ignore the path */ OSM_LOG(p_log, OSM_LOG_VERBOSE, "%s not in fault paths\n", buf); goto Exit; } /* The path is in the fault paths. Need to choose (randomally if to drop it or not. */ rand_value = rand(); if (rand_value % (p_pkt_rand->osm_pkt_drop_rate) == 0) { /* drop the current packet */ res = TRUE; OSM_LOG(p_log, OSM_LOG_VERBOSE, "Dropping path:%s\n", buf); } Exit: OSM_LOG_EXIT(p_log); return res; }
int main( int argc, char *argv[ ], char *envp[ ] ) { char temp[5] ; char path_elements[200] = "data\\base\\elements" ; char path_map[200] = "data\\maps\\map" ; int path_map_def = 0; char path_los[200] = "data\\maps\\map" ; int path_los_def = 0; long i=0, mapnum=0 ; int j; CClos_TextOutput = 1 ; if ( argc > 1 ) { for ( j = 1 ; j < argc ; j++ ) { if (argv[j][0] == '+' || argv[j][0] == '-') { switch (argv[j][1]) { case 'T': CClos_TextOutput = 0 ; break; case 'M': strcpy ( path_map , argv[j+1] ) ; add_backslash ( path_map ) ; strcat ( path_map , "map" ) ; path_map_def = 1 ; if ( !path_los_def) strcpy ( path_los , path_map ) ; break ; case 'L': strcpy ( path_los , argv[j+1] ) ; add_backslash ( path_los ) ; strcat ( path_los , "map" ) ; path_los_def = 1 ; if ( !path_map_def) strcpy ( path_map , path_los ) ; break ; case 'E': strcpy ( path_elements , argv[j+1] ) ; break ; case 'N': i = sscanf ( argv[j+1] , "%d" , &mapnum ) ; break ; } } } } if (CClos_TextOutput) printf ("CC2 LOS calculation - v0.99b\n"); while ( i == 0 || mapnum > 999 ) { if (!CClos_TextOutput) return -8; printf ("enter map number : "); i = scanf ( "%d" , &mapnum ) ; if ( i == 0 ) printf ("only the number...\n"); if ( mapnum > 999 ) printf ("number too hight...\n"); if ( i != 0 && mapnum < 999 ) printf ("\n"); } sprintf ( temp , "%03d" , mapnum ) ; strcat ( path_map , temp ) ; strcat ( path_los , temp ) ; strcat ( path_los , ".los" ) ; fflush ( stdin ) ; i = LOScalculate ( path_map, path_los, path_elements ) ; if (CClos_TextOutput) switch (i) { case 0: printf ( "All OK!\n" ) ; getchar (); break ; case -1: printf ( "ERROR : bad map file\n" ) ; getchar (); break ; case -2: printf ( "ERROR : bad elements file\n" ) ; getchar (); break ; case -3: printf ( "ERROR : not enough memory\n" ) ; getchar (); break ; case -4: printf ( "ERROR : map file not found\n" ) ; getchar (); break ; case -5: printf ( "ERROR : element file not found\n" ) ; getchar (); break ; case -6: printf ( "ERROR : can't create LOS file\n" ) ; getchar (); break ; case -7: printf ( "ERROR : can't write in LOS file (disk full)\n" ) ; getchar (); break ; case -8: printf ( "ERROR : bad element in map\n" ) ; getchar (); break ; } if (CClos_TextOutput) return 0 ; else return i ; }
BOOL burnBootloader(const TCHAR *path) { unsigned char *buf = (unsigned char *)0x80000000; unsigned int rdlen; FIL file; FRESULT fret; int ret; if (!strendwith(path, ".MBT")) { return FALSE; } fret = f_open(&file, path, FA_READ); if (fret != FR_OK) { return FALSE; } if (file.fsize > 109 * 1024) { //109KB goto ERROR; } memset(buf, 0, 512); memcpy(buf, emmcheader, sizeof emmcheader); *(unsigned int *)(buf + 512) = file.fsize; *(unsigned int *)(buf + 512 + 4) = BOOTLOADER_ENTRY; fret = f_read(&file, buf + 512 + 8, file.fsize, &rdlen); if (fret != FR_OK) { goto ERROR; } if (rdlen != file.fsize) { goto ERROR; } //memset(buf,0,file.fsize+8+512); ret = MMCSDP_Write(mmcsdctr, buf, BOOTLOADER_BEGIN_SECTOR, DIVUP(file.fsize + 8 + 512,512)); if (FALSE == ret) { goto ERROR; } long long flashid; spiFlashReadId(&flashid); if ((flashid!=0)&&(flashid!=-1L)){ unsigned char flashstatus = spiFlashReadStatus(); if(!(flashstatus & 0x01)){ spiFlashSwitch256PageSize(); flashstatus = spiFlashReadStatus(); if(!(flashstatus & 0x01)){ goto ERROR; } } } unsigned int flashwcont = DIVUP(file.fsize+8,256); unsigned int byteswapcont = DIVUP(file.fsize+8,4); if ((flashid!=0)&&(flashid!=-1L)) { statBarPrint(0, "found dataflash chip ,burn to dataflash"); for(int i=0;i<byteswapcont;i++){ *(unsigned int *)(buf+512+4*i) = htonl(*(unsigned int *)(buf+512+4*i)); } delay(500); unsigned char percent1 = 0,percent2 = 0; char checkbuf[256]; for (int i=0;i<flashwcont;i++) { ret = spiFlashPageWrite(256*i,(void *)(buf + 512+256*i),256 ); percent1 = (i+1)*100/flashwcont; if(percent1/5 != percent2/5){ percent2 = percent1; char printbuf[200]; sprintf(printbuf,"dataflash write percent %d%%",percent2); statBarPrint(0, printbuf); } if (FALSE==ret) { statBarPrint(1, "data flash write error"); delay(1000); goto ERROR; } delay(45); spiFlashRead(256*i,checkbuf,256); if(memcmp(checkbuf,(void *)(buf + 512+256*i),256)!=0){ statBarPrint(1, "data flash write check error"); delay(500); goto ERROR; } } } f_close(&file); return TRUE; ERROR: f_close(&file); return FALSE; }
BOOLEAN class_cp_is_entry_resolved(Class_Handle clazz, U_16 cp_index) { ConstantPool& cp = clazz->get_constant_pool(); #ifdef ORDER bool res = cp.is_entry_resolved(cp_index, (Class *)clazz); #else bool res = cp.is_entry_resolved(cp_index); #endif if (!res) { unsigned char tag = cp.get_tag(cp_index); //during the loading of a class not all items in it's constant pool are updated if (tag == CONSTANT_Fieldref || tag == CONSTANT_Methodref || tag == CONSTANT_InterfaceMethodref || tag == CONSTANT_Class) { uint16 typeIndex = tag == CONSTANT_Class ? cp_index : cp.get_ref_class_index(cp_index); #ifdef ORDER res = cp.is_entry_resolved(typeIndex, (Class *)clazz); #else res = cp.is_entry_resolved(typeIndex); #endif if (!res) { // the type is not marked as loaded in local constant pool // ask classloader directly uint16 nameIdx = cp.get_class_name_index(typeIndex); String* typeName = cp.get_utf8_string(nameIdx); assert(typeName!=NULL); #ifdef ORDER Class* type = NULL; if(vm_order_record){ // record mode type = clazz->get_class_loader()->LookupClass(typeName); U_32 tid = hythread_self()->thread_id; if (order_system_call[tid] == NULL) { char name[40]; sprintf(name, "SYSTEM_CALL.%d.log", tid); order_system_call[tid] = fopen64(name, "a+"); #ifdef ORDER_DEBUG assert(order_system_call[tid]); #endif } #ifdef ORDER_DEBUG fprintf(order_system_call[tid], "[%d] ", 38); #endif fprintf(order_system_call[tid], "%d\n", type == NULL ? 0 : 1); } else{ // replay mode U_32 tid = hythread_self()->thread_id; if (order_system_call[tid] == NULL) { char name[40]; sprintf(name, "SYSTEM_CALL.%d.log", tid); order_system_call[tid] = fopen64(name, "r"); #ifdef ORDER_DEBUG assert(order_system_call[tid]); #endif } #ifdef ORDER_DEBUG int bit_num; fscanf(order_system_call[tid], "[%d] ", &bit_num); assert(bit_num == 38); #endif int type_state = 0; fscanf(order_system_call[tid], "%d\n", &type_state); if(type_state == 0){ type = NULL; } else{ while((type = clazz->get_class_loader()->LookupClass(typeName)) == NULL){ #ifdef ORDER_DEBUG printf("(type = clazz->get_class_loader()->LookupClass(typeName)) == NULL!!! \n"); #endif usleep(100); } #ifdef ORDER_DEBUG assert(type); #endif } } #else //NOT define ORDER Class* type = clazz->get_class_loader()->LookupClass(typeName); #endif //#ifdef ORDER if (type) { /*TODO: uncommenting this code lead to a crash in StressLoader test clazz->lock(); cp.resolve_entry(typeIndex, type); clazz->unlock();*/ res = true; } //if array of primitives -> return true; if (*typeName->bytes=='[' && !strchr(typeName->bytes, 'L')) { return true; } } } } return res; }
int burnAPP(TCHAR *path) { int errorcode = 0; unsigned char *buf = (unsigned char *)0x80000000; unsigned char *buftemp = buf; unsigned char headbuf[512]; unsigned int rdlen; APPHEADER *header = (APPHEADER * )headbuf; FIL file; FRESULT fret; int ret; char disbuf[32]; unsigned int percent = 0, percentold = 0; unsigned int filesize, count; APPPACKHEAD *apppackhead = (APPPACKHEAD * )(buf + 32); APPSETCTION *appsection1 = &(apppackhead->appsec1); APPSETCTION *appsection2 = &(apppackhead->appsec2); fret = f_open(&file, path, FA_READ); if (fret != FR_OK) { errorcode = BURNAPP_READERROR; return errorcode; } filesize = file.fsize; if ((filesize > APP_MAX_SIZE) || (filesize <= 1024)) { errorcode = BURNAPP_FILE_ERROR; goto ERROR; } count = DIVUP(filesize, 512); memset(headbuf, 0, sizeof headbuf); statBarPrint(0, "reading"); delay(300); for (int i = 0; i < count; i++, buftemp+=512) { fret = f_read(&file, buftemp, 512, &rdlen); if (fret != FR_OK) goto ERROR; for (int j = 0; j < 256; j++) { buftemp[j] ^= ProgramTable[j]; buftemp[j + 256] ^= ProgramTable[j]; } if (i == 0) { /* if ((buftemp[0] != 'T') || (buftemp[1] != 'H') || (buftemp[2] != 'J')) { errorcode = BURNAPP_FILE_ERROR; goto ERROR; } if ((buftemp[10] != 'A') || (buftemp[11] != 'R') || (buftemp[12] != 'A')) { errorcode = BURNAPP_FILE_ERROR; goto ERROR; } */ apppackhead = (APPPACKHEAD * )(buftemp + 32); appsection1 = &(apppackhead->appsec1); appsection2 = &(apppackhead->appsec2); if ((apppackhead->secflag & 0x01) && ((appsection1->imageaddr + appsection1->imageSize) > (filesize - 16))) { errorcode = BURNAPP_FILE_ERROR; goto ERROR; } if ((apppackhead->secflag & 0x02) && ((appsection2->imageaddr + appsection2->imageSize) > (filesize - 16))) { errorcode = BURNAPP_FILE_ERROR; goto ERROR; } } else { percent = i * 100 / count; if (percent / 5 != percentold / 5) { sprintf(disbuf, "%d%%", percent); statBarPrint(0, disbuf); percentold = percent; } } } MD5_CTX md5context; unsigned char decrypt[16]; statBarPrint(0, "processing please waite"); MD5Init(& md5context); MD5Update(& md5context, buf, filesize-16); MD5Final(& md5context, decrypt); if (memcmp(buf + filesize - 16, decrypt, 16)) { errorcode = BURNAPP_FILE_ERROR; goto ERROR; } statBarPrint(0, "write file please waite"); delay(300); header->magic = APP_MAGIC_NO; header->secflag = apppackhead->secflag; if (apppackhead->secflag & 0x01) { header->appsec1.imageaddr = APP_BEGIN_SECTOR; header->appsec1.imageSize = DIVUP(appsection1->imageSize, 512); header->appsec1.imageRevPrefix = appsection1->imageRevPrefix; header->appsec1.imageMainRev = appsection1->imageMainRev; header->appsec1.imageMidRev = appsection1->imageMidRev; header->appsec1.imageMinRev = appsection1->imageMinRev; } if (apppackhead->secflag & 0x02) { header->appsec2.imageaddr = BAG_BEGIN_SETCTOR; header->appsec2.imageSize = DIVUP(appsection2->imageSize, 512); header->appsec2.imageRevPrefix = appsection2->imageRevPrefix; header->appsec2.imageMainRev = appsection2->imageMainRev; header->appsec2.imageMidRev = appsection2->imageMidRev; header->appsec2.imageMinRev = appsection2->imageMinRev; } ret = MMCSDP_Write(mmcsdctr, headbuf, APP_HEAD_SECTOR, 1); if (FALSE == ret) { errorcode = BURNAPP_WRITEERROR; goto ERROR; } if (apppackhead->secflag & 0x01) { ret = MMCSDP_Write(mmcsdctr, (void *)(buf + appsection1->imageaddr), header->appsec1.imageaddr, header->appsec1.imageSize); if (FALSE == ret) { errorcode = BURNAPP_WRITEERROR; goto ERROR; } header->magic = APP_MAGIC_OK; } if (apppackhead->secflag & 0x02) { ret = MMCSDP_Write(mmcsdctr, (void *)(buf + appsection2->imageaddr), header->appsec2.imageaddr, header->appsec2.imageSize); if (FALSE == ret) { errorcode = BURNAPP_WRITEERROR; goto ERROR; } } MMCSDP_Write(mmcsdctr, headbuf, APP_HEAD_SECTOR, 1); return 0; ERROR: f_close(&file); return errorcode; }
int main(int argc, char **argv) { int rc, nrow, ncol; sqlite *dbname; char *errmsg = NULL, **result = NULL; struct in_addr in_ip; FILE *fp1, *fp2; char line[256]; /* get program name */ progname = cli_get_progname(argv[0]); /* print version information */ cli_print_version(); /* initialize */ cli_dns_init(); /* open configuration database */ if((dbname = sqlite_open(DB_CONF, 0, &errmsg)) == NULL) { cli_print_debug_msg("Error: %s\n", errmsg); exit(3); } /* parse command line */ if(argc < 2) { cli_dns_usage(); cli_dns_exit(1); } if(!strcmp(argv[1], "set") && (argc == 4 || argc == 5) && !strcmp(argv[2], "ip")) { if(cli_check_keyword("<single_ip>", argv[3])) { cli_get_user_msg("public", 1, cli_user_msg); printf(cli_user_msg, argv[3]); printf("\n"); cli_dns_exit(1); } inet_aton(argv[3], &in_ip); strcpy(dns.dnssrv, inet_ntoa(in_ip)); if(argc == 5) { if(cli_check_keyword("<single_ip>", argv[4])) { cli_get_user_msg("public", 1, cli_user_msg); printf(cli_user_msg, argv[4]); printf("\n"); cli_dns_exit(1); } inet_aton(argv[4], &in_ip); strcpy(dns.dnssrv2, inet_ntoa(in_ip)); } if((fp1 = fopen(FILE_RESOLV_CONF, "r")) == NULL) { cli_print_debug_msg("Error: open file \"%s\"\n", FILE_RESOLV_CONF); cli_dns_exit(3); } flock(fileno(fp1), LOCK_EX); if((fp2 = fopen(FILE_RESOLV_CONF_TEMP, "w+")) == NULL) { cli_print_debug_msg("Error: open file \"%s\"\n", FILE_RESOLV_CONF_TEMP); cli_dns_exit(3); } flock(fileno(fp2), LOCK_EX); while(fgets(line, 256, fp1) != NULL) { if(strstr(line, "domain") == line) { fputs(line, fp2); } } if(strlen(dns.dnssrv)) { sprintf(line, "nameserver\t%s\n", dns.dnssrv); fputs(line, fp2); } if(strlen(dns.dnssrv2)) { sprintf(line, "nameserver\t%s\n", dns.dnssrv2); fputs(line, fp2); } flock(fileno(fp1), LOCK_UN); fclose(fp1); flock(fileno(fp2), LOCK_UN); fclose(fp2); remove(FILE_RESOLV_CONF); rename(FILE_RESOLV_CONF_TEMP, FILE_RESOLV_CONF); rc = sqlite_exec_printf(dbname, "update %s set dnssrv = %Q, dnssrv2 = %Q", 0, 0, 0, TABLE_DNS, dns.dnssrv, dns.dnssrv2); if(rc != SQLITE_OK) { cli_dns_exit(3); } if(strlen(dns.dnssrv2)) { fw_log_write(FWLOG_DEV_MNG, LOG_NOTICE, "mod=%s act=set ip=\"%s %s\" result=0", progname, dns.dnssrv, dns.dnssrv2); } else { fw_log_write(FWLOG_DEV_MNG, LOG_NOTICE, "mod=%s act=set ip=%s result=0", progname, dns.dnssrv); } } else if(!strcmp(argv[1], "unset") && argc == 2) { if((fp1 = fopen(FILE_RESOLV_CONF, "w+")) == NULL) { cli_print_debug_msg("Error: open file \"%s\"\n", FILE_RESOLV_CONF); cli_dns_exit(3); } fclose(fp1); rc = sqlite_exec_printf(dbname, "update %s set dnssrv = '', dnssrv2 = ''", 0, 0, 0, TABLE_DNS); if(rc != SQLITE_OK) { cli_dns_exit(3); } fw_log_write(FWLOG_DEV_MNG, LOG_NOTICE, "mod=%s act=unset result=0", progname); } else if(!strcmp(argv[1], "show") && argc == 2) { rc = sqlite_get_table_printf(dbname, "select * from %s", &result, &nrow, &ncol, &errmsg, TABLE_DNS); if(rc != SQLITE_OK) { cli_dns_exit(3); } if(nrow > 0) { if(strlen(result[ncol]) || strlen(result[ncol + 1])) { printf("DNS 1: %s\n", result[ncol]); printf("DNS 2: %s\n", result[ncol + 1]); } else { printf("DNS are not set\n"); } } } else if(!strcmp(argv[1], "startup") && argc == 2) { rc = sqlite_get_table_printf(dbname, "select * from %s", &result, &nrow, &ncol, &errmsg, TABLE_DNS); if(rc != SQLITE_OK) { cli_dns_exit(3); } if(nrow > 0) { strcpy(dns.dnssrv, result[ncol]); strcpy(dns.dnssrv2, result[ncol + 1]); } if(strlen(dns.dnssrv)) { if((fp1 = fopen(FILE_RESOLV_CONF, "r")) == NULL) { cli_print_debug_msg("Error: open file \"%s\"\n", FILE_RESOLV_CONF); cli_dns_exit(3); } flock(fileno(fp1), LOCK_EX); if((fp2 = fopen(FILE_RESOLV_CONF_TEMP, "w+")) == NULL) { cli_print_debug_msg("Error: open file \"%s\"\n", FILE_RESOLV_CONF_TEMP); cli_dns_exit(3); } flock(fileno(fp2), LOCK_EX); while(fgets(line, 256, fp1) != NULL) { if(strstr(line, "domain") == line) { fputs(line, fp2); } } if(strlen(dns.dnssrv)) { sprintf(line, "nameserver\t%s\n", dns.dnssrv); fputs(line, fp2); } if(strlen(dns.dnssrv2)) { sprintf(line, "nameserver\t%s\n", dns.dnssrv2); fputs(line, fp2); } flock(fileno(fp1), LOCK_UN); fclose(fp1); flock(fileno(fp2), LOCK_UN); fclose(fp2); remove(FILE_RESOLV_CONF); rename(FILE_RESOLV_CONF_TEMP, FILE_RESOLV_CONF); } } else { cli_dns_usage(); cli_dns_exit(1); } sqlite_close(dbname); cli_dns_exit(0); exit(0); }
static int snd_atiixp_pcm_open(struct snd_pcm_substream *substream, struct atiixp_dma *dma, int pcm_type) { struct atiixp_modem *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; int err; static unsigned int rates[] = { 8000, 9600, 12000, 16000 }; static struct snd_pcm_hw_constraint_list hw_constraints_rates = { .count = ARRAY_SIZE(rates), .list = rates, .mask = 0, }; if (snd_BUG_ON(!dma->ops || !dma->ops->enable_dma)) return -EINVAL; if (dma->opened) return -EBUSY; dma->substream = substream; runtime->hw = snd_atiixp_pcm_hw; dma->ac97_pcm_type = pcm_type; if ((err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_rates)) < 0) return err; if ((err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS)) < 0) return err; runtime->private_data = dma; /* enable DMA bits */ spin_lock_irq(&chip->reg_lock); dma->ops->enable_dma(chip, 1); spin_unlock_irq(&chip->reg_lock); dma->opened = 1; return 0; } static int snd_atiixp_pcm_close(struct snd_pcm_substream *substream, struct atiixp_dma *dma) { struct atiixp_modem *chip = snd_pcm_substream_chip(substream); /* disable DMA bits */ if (snd_BUG_ON(!dma->ops || !dma->ops->enable_dma)) return -EINVAL; spin_lock_irq(&chip->reg_lock); dma->ops->enable_dma(chip, 0); spin_unlock_irq(&chip->reg_lock); dma->substream = NULL; dma->opened = 0; return 0; } /* */ static int snd_atiixp_playback_open(struct snd_pcm_substream *substream) { struct atiixp_modem *chip = snd_pcm_substream_chip(substream); int err; mutex_lock(&chip->open_mutex); err = snd_atiixp_pcm_open(substream, &chip->dmas[ATI_DMA_PLAYBACK], 0); mutex_unlock(&chip->open_mutex); if (err < 0) return err; return 0; } static int snd_atiixp_playback_close(struct snd_pcm_substream *substream) { struct atiixp_modem *chip = snd_pcm_substream_chip(substream); int err; mutex_lock(&chip->open_mutex); err = snd_atiixp_pcm_close(substream, &chip->dmas[ATI_DMA_PLAYBACK]); mutex_unlock(&chip->open_mutex); return err; } static int snd_atiixp_capture_open(struct snd_pcm_substream *substream) { struct atiixp_modem *chip = snd_pcm_substream_chip(substream); return snd_atiixp_pcm_open(substream, &chip->dmas[ATI_DMA_CAPTURE], 1); } static int snd_atiixp_capture_close(struct snd_pcm_substream *substream) { struct atiixp_modem *chip = snd_pcm_substream_chip(substream); return snd_atiixp_pcm_close(substream, &chip->dmas[ATI_DMA_CAPTURE]); } /* AC97 playback */ static struct snd_pcm_ops snd_atiixp_playback_ops = { .open = snd_atiixp_playback_open, .close = snd_atiixp_playback_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_atiixp_pcm_hw_params, .hw_free = snd_atiixp_pcm_hw_free, .prepare = snd_atiixp_playback_prepare, .trigger = snd_atiixp_pcm_trigger, .pointer = snd_atiixp_pcm_pointer, }; /* AC97 capture */ static struct snd_pcm_ops snd_atiixp_capture_ops = { .open = snd_atiixp_capture_open, .close = snd_atiixp_capture_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_atiixp_pcm_hw_params, .hw_free = snd_atiixp_pcm_hw_free, .prepare = snd_atiixp_capture_prepare, .trigger = snd_atiixp_pcm_trigger, .pointer = snd_atiixp_pcm_pointer, }; static struct atiixp_dma_ops snd_atiixp_playback_dma_ops = { .type = ATI_DMA_PLAYBACK, .llp_offset = ATI_REG_MODEM_OUT_DMA1_LINKPTR, .dt_cur = ATI_REG_MODEM_OUT_DMA1_DT_CUR, .enable_dma = atiixp_out_enable_dma, .enable_transfer = atiixp_out_enable_transfer, .flush_dma = atiixp_out_flush_dma, }; static struct atiixp_dma_ops snd_atiixp_capture_dma_ops = { .type = ATI_DMA_CAPTURE, .llp_offset = ATI_REG_MODEM_IN_DMA_LINKPTR, .dt_cur = ATI_REG_MODEM_IN_DMA_DT_CUR, .enable_dma = atiixp_in_enable_dma, .enable_transfer = atiixp_in_enable_transfer, .flush_dma = atiixp_in_flush_dma, }; static int __devinit snd_atiixp_pcm_new(struct atiixp_modem *chip) { struct snd_pcm *pcm; int err; /* initialize constants */ chip->dmas[ATI_DMA_PLAYBACK].ops = &snd_atiixp_playback_dma_ops; chip->dmas[ATI_DMA_CAPTURE].ops = &snd_atiixp_capture_dma_ops; /* PCM #0: analog I/O */ err = snd_pcm_new(chip->card, "ATI IXP MC97", ATI_PCMDEV_ANALOG, 1, 1, &pcm); if (err < 0) return err; snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_atiixp_playback_ops); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_atiixp_capture_ops); pcm->dev_class = SNDRV_PCM_CLASS_MODEM; pcm->private_data = chip; strcpy(pcm->name, "ATI IXP MC97"); chip->pcmdevs[ATI_PCMDEV_ANALOG] = pcm; snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci), 64*1024, 128*1024); return 0; } /* * interrupt handler */ static irqreturn_t snd_atiixp_interrupt(int irq, void *dev_id) { struct atiixp_modem *chip = dev_id; unsigned int status; status = atiixp_read(chip, ISR); if (! status) return IRQ_NONE; /* process audio DMA */ if (status & ATI_REG_ISR_MODEM_OUT1_XRUN) snd_atiixp_xrun_dma(chip, &chip->dmas[ATI_DMA_PLAYBACK]); else if (status & ATI_REG_ISR_MODEM_OUT1_STATUS) snd_atiixp_update_dma(chip, &chip->dmas[ATI_DMA_PLAYBACK]); if (status & ATI_REG_ISR_MODEM_IN_XRUN) snd_atiixp_xrun_dma(chip, &chip->dmas[ATI_DMA_CAPTURE]); else if (status & ATI_REG_ISR_MODEM_IN_STATUS) snd_atiixp_update_dma(chip, &chip->dmas[ATI_DMA_CAPTURE]); /* for codec detection */ if (status & CODEC_CHECK_BITS) { unsigned int detected; detected = status & CODEC_CHECK_BITS; spin_lock(&chip->reg_lock); chip->codec_not_ready_bits |= detected; atiixp_update(chip, IER, detected, 0); /* disable the detected irqs */ spin_unlock(&chip->reg_lock); } /* ack */ atiixp_write(chip, ISR, status); return IRQ_HANDLED; } /* * ac97 mixer section */ static int __devinit snd_atiixp_mixer_new(struct atiixp_modem *chip, int clock) { struct snd_ac97_bus *pbus; struct snd_ac97_template ac97; int i, err; int codec_count; static struct snd_ac97_bus_ops ops = { .write = snd_atiixp_ac97_write, .read = snd_atiixp_ac97_read, }; static unsigned int codec_skip[NUM_ATI_CODECS] = { ATI_REG_ISR_CODEC0_NOT_READY, ATI_REG_ISR_CODEC1_NOT_READY, ATI_REG_ISR_CODEC2_NOT_READY, }; if (snd_atiixp_codec_detect(chip) < 0) return -ENXIO; if ((err = snd_ac97_bus(chip->card, 0, &ops, chip, &pbus)) < 0) return err; pbus->clock = clock; chip->ac97_bus = pbus; codec_count = 0; for (i = 0; i < NUM_ATI_CODECS; i++) { if (chip->codec_not_ready_bits & codec_skip[i]) continue; memset(&ac97, 0, sizeof(ac97)); ac97.private_data = chip; ac97.pci = chip->pci; ac97.num = i; ac97.scaps = AC97_SCAP_SKIP_AUDIO | AC97_SCAP_POWER_SAVE; if ((err = snd_ac97_mixer(pbus, &ac97, &chip->ac97[i])) < 0) { chip->ac97[i] = NULL; /* to be sure */ snd_printdd("atiixp-modem: codec %d not available for modem\n", i); continue; } codec_count++; } if (! codec_count) { snd_printk(KERN_ERR "atiixp-modem: no codec available\n"); return -ENODEV; } /* snd_ac97_tune_hardware(chip->ac97, ac97_quirks); */ return 0; } #ifdef CONFIG_PM /* * power management */ static int snd_atiixp_suspend(struct pci_dev *pci, pm_message_t state) { struct snd_card *card = pci_get_drvdata(pci); struct atiixp_modem *chip = card->private_data; int i; snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); for (i = 0; i < NUM_ATI_PCMDEVS; i++) snd_pcm_suspend_all(chip->pcmdevs[i]); for (i = 0; i < NUM_ATI_CODECS; i++) snd_ac97_suspend(chip->ac97[i]); snd_atiixp_aclink_down(chip); snd_atiixp_chip_stop(chip); pci_disable_device(pci); pci_save_state(pci); pci_set_power_state(pci, pci_choose_state(pci, state)); return 0; } static int snd_atiixp_resume(struct pci_dev *pci) { struct snd_card *card = pci_get_drvdata(pci); struct atiixp_modem *chip = card->private_data; int i; pci_set_power_state(pci, PCI_D0); pci_restore_state(pci); if (pci_enable_device(pci) < 0) { printk(KERN_ERR "atiixp-modem: pci_enable_device failed, " "disabling device\n"); snd_card_disconnect(card); return -EIO; } pci_set_master(pci); snd_atiixp_aclink_reset(chip); snd_atiixp_chip_start(chip); for (i = 0; i < NUM_ATI_CODECS; i++) snd_ac97_resume(chip->ac97[i]); snd_power_change_state(card, SNDRV_CTL_POWER_D0); return 0; } #endif /* CONFIG_PM */ #ifdef CONFIG_PROC_FS /* * proc interface for register dump */ static void snd_atiixp_proc_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct atiixp_modem *chip = entry->private_data; int i; for (i = 0; i < 256; i += 4) snd_iprintf(buffer, "%02x: %08x\n", i, readl(chip->remap_addr + i)); } static void __devinit snd_atiixp_proc_init(struct atiixp_modem *chip) { struct snd_info_entry *entry; if (! snd_card_proc_new(chip->card, "atiixp-modem", &entry)) snd_info_set_text_ops(entry, chip, snd_atiixp_proc_read); } #else #define snd_atiixp_proc_init(chip) #endif /* * destructor */ static int snd_atiixp_free(struct atiixp_modem *chip) { if (chip->irq < 0) goto __hw_end; snd_atiixp_chip_stop(chip); __hw_end: if (chip->irq >= 0) free_irq(chip->irq, chip); if (chip->remap_addr) iounmap(chip->remap_addr); pci_release_regions(chip->pci); pci_disable_device(chip->pci); kfree(chip); return 0; } static int snd_atiixp_dev_free(struct snd_device *device) { struct atiixp_modem *chip = device->device_data; return snd_atiixp_free(chip); } /* * constructor for chip instance */ static int __devinit snd_atiixp_create(struct snd_card *card, struct pci_dev *pci, struct atiixp_modem **r_chip) { static struct snd_device_ops ops = { .dev_free = snd_atiixp_dev_free, }; struct atiixp_modem *chip; int err; if ((err = pci_enable_device(pci)) < 0) return err; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (chip == NULL) { pci_disable_device(pci); return -ENOMEM; } spin_lock_init(&chip->reg_lock); mutex_init(&chip->open_mutex); chip->card = card; chip->pci = pci; chip->irq = -1; if ((err = pci_request_regions(pci, "ATI IXP MC97")) < 0) { kfree(chip); pci_disable_device(pci); return err; } chip->addr = pci_resource_start(pci, 0); chip->remap_addr = pci_ioremap_bar(pci, 0); if (chip->remap_addr == NULL) { snd_printk(KERN_ERR "AC'97 space ioremap problem\n"); snd_atiixp_free(chip); return -EIO; } if (request_irq(pci->irq, snd_atiixp_interrupt, IRQF_SHARED, card->shortname, chip)) { snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq); snd_atiixp_free(chip); return -EBUSY; } chip->irq = pci->irq; pci_set_master(pci); synchronize_irq(chip->irq); if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) { snd_atiixp_free(chip); return err; } snd_card_set_dev(card, &pci->dev); *r_chip = chip; return 0; } static int __devinit snd_atiixp_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { struct snd_card *card; struct atiixp_modem *chip; int err; err = snd_card_create(index, id, THIS_MODULE, 0, &card); if (err < 0) return err; strcpy(card->driver, "ATIIXP-MODEM"); strcpy(card->shortname, "ATI IXP Modem"); if ((err = snd_atiixp_create(card, pci, &chip)) < 0) goto __error; card->private_data = chip; if ((err = snd_atiixp_aclink_reset(chip)) < 0) goto __error; if ((err = snd_atiixp_mixer_new(chip, ac97_clock)) < 0) goto __error; if ((err = snd_atiixp_pcm_new(chip)) < 0) goto __error; snd_atiixp_proc_init(chip); snd_atiixp_chip_start(chip); sprintf(card->longname, "%s rev %x at 0x%lx, irq %i", card->shortname, pci->revision, chip->addr, chip->irq); if ((err = snd_card_register(card)) < 0) goto __error; pci_set_drvdata(pci, card); return 0; __error: snd_card_free(card); return err; } static void __devexit snd_atiixp_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); pci_set_drvdata(pci, NULL); }
int main(int argc, char *argv[]) { /* select部份 */ int opt = TRUE; int master_socket, addrlen, new_socket, client_socket[MAXCLIENTS], max_clients = MAXCLIENTS, activity, i, valread, sd; user_content_t *my_contents[MAXCLIENTS + 1]; int max_sd; struct timeval tv; /* select超时 */ //set of socket descriptors fd_set readfds; /* IP部份 */ struct addrinfo hints, *res; /* 连接到target的用到的 */ struct sockaddr_in address; /* 每个客户端的缓冲区和索引 */ char buffer[MAXCLIENTS][MAXLEN]; char *buffer_p[MAXCLIENTS]; //data buffer of 1K int buffer_data_size[MAXCLIENTS]; char itoa_buffer[8]; /* ip地址从网络顺序转成char数组 */ char *header = NULL; /* 将转换好的ip地址:封包成header */ /* 串口部份 固定变量 */ static char com_devicename[] = "/dev/ttyUSB0"; /* 固定的linux串口设备文件 */ user_content_t *my_com_conf = my_malloc(sizeof(user_content_t));/* 串口配置 */ /* 串口部份 动态变量 */ #ifdef MODULE_SERIAL char buffer_com[MAXLEN]; /* 串口缓冲区 */ char *buffer_com_p=buffer_com; int buffer_com_data_size=0; #endif /* 蓝牙部份 */ #ifdef MODULE_BLUETOOTH struct sockaddr_rc blue_rem_addr = {0}; char blue_buffer[MAXLEN],blue_sender_MAC[18]; int blue_fd,blue_fd_client,blue_bytes_read; socklen_t blue_opt=sizeof(blue_rem_addr); user_content_t *blue_user_content; #endif /* args参数 */ char *PORT; if (argc != 2) { fprintf(stderr, "usage: %s listen-port\n", argv[0]); return 1; } PORT = argv[1]; #ifdef MODULE_SERIAL /* 打开串口,须root权限 */ if(NULL==(my_com_conf=open_com(com_devicename))) { printf("error open com!\n"); return 1; } #endif #ifdef MODULE_BLUETOOTH /* 打开蓝牙 */ blue_fd=create_bluetooth_socket(); if(blue_fd<0) { printf("error bluetooth fd is -1\n"); return -1; } listen(blue_fd, 1); #endif //initialise all client_socket[] to 0 so not checked for (i = 0; i < max_clients; i++) { client_socket[i] = 0; } if ((master_socket = create_server_socket("0.0.0.0", PORT)) < 0) { printf("error create socket fd\n"); return 1; } //set master socket to allow multiple connections , this is just a good habit, it will work without this if (setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof(opt)) < 0) { perror("setsockopt"); exit(EXIT_FAILURE); } //try to specify maximum of 3 pending connections for the master socket if (listen(master_socket, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } printf("Listening on port %s \n", PORT); //accept the incoming connection addrlen = sizeof(address); puts("Waiting for connections ..."); while (TRUE) { //clear the socket set FD_ZERO(&readfds); //add master socket to set FD_SET(master_socket, &readfds); max_sd = master_socket; #ifdef MODULE_SERIAL FD_SET(my_com_conf->fd,&readfds); max_sd = max_sd>my_com_conf->fd?max_sd:my_com_conf->fd; #endif #ifdef MODULE_BLUETOOTH FD_SET(blue_fd,&readfds); max_sd = max_sd>blue_fd?max_sd:blue_fd; #endif //add child sockets to set for (i = 0; i < max_clients; i++) { //socket descriptor sd = client_socket[i]; //if valid socket descriptor then add to read list if (sd > 0) FD_SET(sd, &readfds); //highest file descriptor number, need it for the select function if (sd > max_sd) max_sd = sd; } //wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely activity = select(max_sd + 1, &readfds, NULL, NULL, NULL); if ((activity < 0) && (errno != EINTR)) { printf("select error"); } //If something happened on the master socket , then its an incoming connection if (FD_ISSET(master_socket, &readfds)) { if ((new_socket = accept(master_socket, (struct sockaddr *) &address, (socklen_t*) &addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } //add new socket to array of sockets for (i = 0; i < max_clients; i++) { //if position is empty, create new one if (client_socket[i] == 0) { client_socket[i] = new_socket; // 初始化buffer buffer_p[i] = buffer[i]; memset(buffer_p[i], 0, MAXLEN); buffer_data_size[i] = 0; printf("accepted #%d client\n", i); break; } } } #ifdef MODULE_SERIAL // 串口读 if (FD_ISSET(my_com_conf->fd, &readfds)) { /* 非阻塞读取 */ valread=sp_nonblocking_read(my_com_conf->com_port,buffer_com_p+buffer_com_data_size,MAXLEN); if(valread<0) { printf("read data from com error: %d\n",valread); return 1; buffer_com_data_size=0; buffer_com_p=buffer_com; } else { buffer_com_data_size+=valread; /* 读完所有数据,串口数据包必须以\r\n结尾 */ if(buffer_com[buffer_com_data_size-2]==13 && buffer_com[buffer_com_data_size-1]==10) { printf("- - - - - - - - - -\nread from COM ok\n"); buffer_com_p[buffer_com_data_size]=0; my_contents[MAXCLIENTS]=new_user_content_from_str(buffer_com,com_devicename,get_direction(buffer_com)); if(!my_contents[MAXCLIENTS]) { printf("invalid packet!\n"); } else { printf(" %s",com_devicename); redirect_from_user_content(my_contents[MAXCLIENTS]); } my_free(my_contents[MAXCLIENTS]); /* reset buffer offset */ buffer_com_data_size=0; buffer_com_p=buffer_com; } } } #endif #ifdef MODULE_BLUETOOTH // 蓝牙读 if(FD_ISSET(blue_fd,&readfds)) { // accept one connection blue_fd_client = accept(blue_fd, (struct sockaddr *)&blue_rem_addr, &blue_opt); ba2str( &blue_rem_addr.rc_bdaddr, blue_sender_MAC ); // read data from the client blue_bytes_read = read(blue_fd_client, blue_buffer, sizeof(blue_buffer)); if( blue_bytes_read > 0 ) { printf("- - - - - - - - - -\nread from bluetooth ok\n"); blue_buffer[blue_bytes_read]=0; blue_user_content=new_user_content_from_str(blue_buffer,blue_sender_MAC,get_direction(blue_buffer)); if(!blue_user_content) { printf("invalid packet!\n"); } else { printf(" %s",blue_sender_MAC); redirect_from_user_content(blue_user_content); } my_free(blue_user_content); } else { printf("bluetooth recv data error!\n"); } // close connection close(blue_fd_client); } #endif // 局域网ip读 for (i = 0; i < max_clients; i++) { sd = client_socket[i]; if (FD_ISSET(sd, &readfds)) { //Check if it was for closing , and also read the incoming message if ((valread = read(sd, buffer_p[i] + buffer_data_size[i], MAXLEN)) == 0) { //Somebody disconnected , get his details and print buffer[i][buffer_data_size[i]] = 0; getpeername(sd, (struct sockaddr*) &address, (socklen_t*) &addrlen); printf( "- - - - - - - - - -\nread %d bytes from LAN client\n", buffer_data_size[i]); //Close the socket and mark as 0 in list for reuse close(sd); client_socket[i] = 0; /* convert port(interger) to char* */ sprintf(itoa_buffer, "%d", ntohs(address.sin_port)); header = get_header_ipv4(inet_ntoa(address.sin_addr), itoa_buffer); /* create relay struct: from LAN ip, to serial */ my_contents[i] = new_user_content_from_str(buffer[i], header, get_direction(buffer[i])); if (!my_contents[i]) { printf("invalid packet!\n"); } else { printf(" %s", header); redirect_from_user_content(my_contents[i]); } my_free(header); my_free(my_contents[i]); } else { /* 累加数据 */ buffer_data_size[i] += valread; } } } } #ifdef MODULE_SERIAL sp_close(my_com_conf->com_port); sp_free_port(my_com_conf->com_port); sp_free_config(my_com_conf->com_conf); my_free(my_com_conf); #endif #ifdef MODULE_BLUETOOTH close(blue_fd); #endif close(master_socket); printf("exit..\n"); return 0; }
void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) { int i=0; while( i<(int)str.length() ) { unsigned char c = (unsigned char) str[i]; if ( c == '&' && i < ( (int)str.length() - 2 ) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // © -- copyright symbol, for example. // // The -1 is a bug fix from Rob Laveaux. It keeps // an overflow from happening if there is no ';'. // There are actually 2 ways to exit this loop - // while fails (error case) and break (semicolon found). // However, there is no mechanism (currently) for // this function to return an error. while ( i<(int)str.length()-1 ) { outString->append( str.c_str() + i, 1 ); ++i; if ( str[i] == ';' ) break; } } else if ( c == '&' ) { outString->append( entity[0].str, entity[0].strLength ); ++i; } else if ( c == '<' ) { outString->append( entity[1].str, entity[1].strLength ); ++i; } else if ( c == '>' ) { outString->append( entity[2].str, entity[2].strLength ); ++i; } else if ( c == '\"' ) { outString->append( entity[3].str, entity[3].strLength ); ++i; } else if ( c == '\'' ) { outString->append( entity[4].str, entity[4].strLength ); ++i; } else if ( c < 32 ) { // Easy pass at non-alpha/numeric/symbol // Below 32 is symbolic. char buf[ 32 ]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); #else sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); #endif //*ME: warning C4267: convert 'size_t' to 'int' //*ME: Int-Cast to make compiler happy ... outString->append( buf, (int)strlen( buf ) ); ++i; } else { //char realc = (char) c; //outString->append( &realc, 1 ); *outString += (char) c; // somewhat more efficient function call. ++i; } } }
void ipv4_format(char* buf, ipv4_t ipv4) { sprintf(buf, "%d.%d.%d.%d", ipv4.byte[3], ipv4.byte[2], ipv4.byte[1], ipv4.byte[0]); }
int Zoltan_Drum_Create_Model(ZZ *zz) { char *yo = "Zoltan_Drum_Create_Model"; int ierr; FILE *fp; char buf[80]; /* check params */ Zoltan_Drum_Init(zz); if (zz->Drum.use_drum && !zz->Drum.dmm) { if (zz->Drum.build_tree) { zz->Drum.dmm = DRUM_createMachineModel(zz->Communicator, zz->Drum.debug_level); if (!zz->Drum.dmm) { ZOLTAN_PRINT_ERROR(zz->Proc, yo, "Unable to create DRUM machine model"); return ZOLTAN_FATAL; } /* some parameters should be set between machine model creation and machine model initialization */ sprintf(buf, "%d", zz->Drum.use_flat_model); DRUM_setParam(zz->Drum.dmm, "USE_FLAT_MODEL", buf); sprintf(buf, "%d", zz->Drum.ignore_rpp); DRUM_setParam(zz->Drum.dmm, "IGNORE_RPP", buf); ierr = DRUM_initMachineModel(zz->Drum.dmm); if (ierr == DRUM_FATAL || ierr == DRUM_MEMERR) { ZOLTAN_PRINT_ERROR(zz->Proc, yo, "Unable to initialize DRUM machine model"); return (ierr == DRUM_FATAL ? ZOLTAN_FATAL : ZOLTAN_MEMERR); } if( zz->Drum.drum_hier){ Zoltan_Set_Param(zz, "LB_METHOD", "HIER"); ierr = DRUM_hierCreateCallbacks(zz->Drum.dmm, zz); if(ierr != DRUM_OK){ ZOLTAN_PRINT_ERROR(zz->Proc, yo, "DRUM_hier_create_callbacks returned an error"); return (ierr == DRUM_FATAL ? ZOLTAN_FATAL : ZOLTAN_MEMERR); } DRUM_hierSetCallbacks(zz); } /* print the "power file" if it was requested */ if (zz->Proc == 0 && strcmp(zz->Drum.power_filename,"")) { fp = fopen(zz->Drum.power_filename, "w"); if (fp) { DRUM_printMachineModel(zz->Drum.dmm, fp); fclose(fp); } else { ZOLTAN_PRINT_WARN(zz->Proc, yo, "Could not open power file"); } } DRUM_setMonitoringFrequency(zz->Drum.dmm, zz->Drum.monitoring_frequency); sprintf(buf, "%d", zz->Drum.use_snmp); DRUM_setParam(zz->Drum.dmm, "USE_SNMP", buf); sprintf(buf, "%d", zz->Drum.use_kstat); DRUM_setParam(zz->Drum.dmm, "USE_KSTAT", buf); sprintf(buf, "%d", zz->Drum.use_nws); DRUM_setParam(zz->Drum.dmm, "USE_NWS", buf); sprintf(buf, "%d", zz->Drum.nws_method); DRUM_setParam(zz->Drum.dmm, "NWS_METHOD", buf); sprintf(buf, "%d", zz->Drum.monitor_memory); DRUM_setParam(zz->Drum.dmm, "MONITOR_MEMORY", buf); sprintf(buf, "%d", zz->Drum.use_network_powers); DRUM_setParam(zz->Drum.dmm, "USE_NETWORK_POWERS", buf); sprintf(buf, "%f", zz->Drum.fixed_network_weight); DRUM_setParam(zz->Drum.dmm, "FIXED_NETWORK_WEIGHT", buf); } if (zz->Drum.start_monitors) { ierr = DRUM_startMonitoring(zz->Drum.dmm); if (ierr == DRUM_FATAL || ierr == DRUM_MEMERR) { ZOLTAN_PRINT_ERROR(zz->Proc, yo, "Unable to start DRUM monitors"); return (ierr == DRUM_FATAL ? ZOLTAN_FATAL : ZOLTAN_MEMERR); } } } return ZOLTAN_OK; }
int main( int ac, char *av[] ) { const char* const pqfname = getQueuePath(); const char* const progname = ubasename(av[0]); int useProductID = FALSE; int signatureFromId = FALSE; char *productID = NULL; int multipleFiles = FALSE; char identifier[KEYSIZE]; int status; int seq_start = 0; enum ExitCode { exit_success = 0, /* all files inserted successfully */ exit_system = 1, /* operating-system failure */ exit_pq_open = 2, /* couldn't open product-queue */ exit_infile = 3, /* couldn't process input file */ exit_dup = 4, /* input-file already in product-queue */ exit_md5 = 6 /* couldn't initialize MD5 processing */ } exitCode = exit_success; #ifndef HAVE_MMAP pqeIndex = PQE_NONE; #endif { extern int optind; extern int opterr; extern char *optarg; int ch; (void) openulog(progname, LOG_NOTIME, LOG_LDM, "-"); (void) setulogmask(LOG_UPTO(LOG_NOTICE)); opterr = 0; /* Suppress getopt(3) error messages */ while ((ch = getopt(ac, av, ":ivxl:q:f:s:p:")) != EOF) switch (ch) { case 'i': signatureFromId = 1; break; case 'v': (void) setulogmask(getulogmask() | LOG_MASK(LOG_INFO)); break; case 'x': (void) setulogmask(getulogmask() | LOG_MASK(LOG_DEBUG)); break; case 'l': openulog(progname, ulog_get_options(), LOG_LDM, optarg); break; case 'q': setQueuePath(optarg); break; case 's': seq_start = atoi(optarg); break; case 'f': feedtype = atofeedtypet(optarg); if(feedtype == NONE) { fprintf(stderr, "Unknown feedtype \"%s\"\n", optarg); usage(progname); } break; case 'p': useProductID = TRUE; productID = optarg; break; case ':': { LOG_ADD1("Option \"-%c\" requires an operand", optopt); usage(progname); } /* no break */ default: LOG_ADD1("Unknown option: \"%c\"", optopt); usage(progname); /* no break */ } ac -= optind; av += optind ; if(ac < 1) usage(progname); } /* * register exit handler */ if(atexit(cleanup) != 0) { serror("atexit"); exit(exit_system); } /* * set up signal handlers */ set_sigactions(); /* * who am i, anyway */ (void) strncpy(myname, ghostname(), sizeof(myname)); myname[sizeof(myname)-1] = 0; /* * open the product queue */ if(status = pq_open(pqfname, PQ_DEFAULT, &pq)) { if (PQ_CORRUPT == status) { uerror("The product-queue \"%s\" is inconsistent\n", pqfname); } else { uerror("pq_open: \"%s\" failed: %s", pqfname, status > 0 ? strerror(status) : "Internal error"); } exit(exit_pq_open); } { char *filename; int fd; struct stat statb; product prod; MD5_CTX *md5ctxp = NULL; /* * Allocate an MD5 context */ md5ctxp = new_MD5_CTX(); if(md5ctxp == NULL) { serror("new_md5_CTX failed"); exit(exit_md5); } /* These members are constant over the loop. */ prod.info.origin = myname; prod.info.feedtype = feedtype; if (ac > 1) { multipleFiles = TRUE; } for(prod.info.seqno = seq_start ; ac > 0 ; av++, ac--, prod.info.seqno++) { filename = *av; fd = open(filename, O_RDONLY, 0); if(fd == -1) { serror("open: %s", filename); exitCode = exit_infile; continue; } if( fstat(fd, &statb) == -1) { serror("fstat: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } /* Determine what to use for product identifier */ if (useProductID) { if (multipleFiles) { sprintf(identifier,"%s.%d", productID, prod.info.seqno); prod.info.ident = identifier; } else prod.info.ident = productID; } else prod.info.ident = filename; prod.info.sz = statb.st_size; prod.data = NULL; /* These members, and seqno, vary over the loop. */ status = set_timestamp(&prod.info.arrival); if(status != ENOERR) { serror("set_timestamp: %s, filename"); exitCode = exit_infile; continue; } #ifdef HAVE_MMAP prod.data = mmap(0, prod.info.sz, PROT_READ, MAP_PRIVATE, fd, 0); if(prod.data == NULL) { serror("mmap: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } status = signatureFromId ? mm_md5(md5ctxp, prod.info.ident, strlen(prod.info.ident), prod.info.signature) : mm_md5(md5ctxp, prod.data, prod.info.sz, prod.info.signature); (void)exitIfDone(1); if (status != 0) { serror("mm_md5: %s", filename); (void) munmap(prod.data, prod.info.sz); (void) close(fd); exitCode = exit_infile; continue; } /* These members, and seqno, vary over the loop. */ status = set_timestamp(&prod.info.arrival); if(status != ENOERR) { serror("set_timestamp: %s, filename"); exitCode = exit_infile; continue; } /* * Do the deed */ status = pq_insert(pq, &prod); switch (status) { case ENOERR: /* no error */ if(ulogIsVerbose()) uinfo("%s", s_prod_info(NULL, 0, &prod.info, ulogIsDebug())) ; break; case PQUEUE_DUP: uerror("Product already in queue: %s", s_prod_info(NULL, 0, &prod.info, 1)); exitCode = exit_dup; break; case PQUEUE_BIG: uerror("Product too big for queue: %s", s_prod_info(NULL, 0, &prod.info, 1)); exitCode = exit_infile; break; case ENOMEM: uerror("queue full?"); exitCode = exit_system; break; case EINTR: #if defined(EDEADLOCK) && EDEADLOCK != EDEADLK case EDEADLOCK: /*FALLTHROUGH*/ #endif case EDEADLK: /* TODO: retry ? */ /*FALLTHROUGH*/ default: uerror("pq_insert: %s", status > 0 ? strerror(status) : "Internal error"); break; } (void) munmap(prod.data, prod.info.sz); #else /*HAVE_MMAP*/ status = signatureFromId ? mm_md5(md5ctxp, prod.info.ident, strlen(prod.info.ident), prod.info.signature) : fd_md5(md5ctxp, fd, statb.st_size, prod.info.signature); (void)exitIfDone(1); if (status != 0) { serror("fd_md5: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } if(lseek(fd, 0, SEEK_SET) == (off_t)-1) { serror("rewind: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } index = PQE_NONE; status = pqe_new(pq, &prod.info, &prod.data, &index); if(status != ENOERR) { serror("pqe_new: %s", filename); exitCode = exit_infile; } else { ssize_t nread = read(fd, prod.data, prod.info.sz); (void)exitIfDone(1); if (nread != prod.info.sz) { serror("read %s %u", filename, prod.info.sz); status = EIO; } else { status = pqe_insert(pq, index); index = PQE_NONE; switch (status) { case ENOERR: /* no error */ if(ulogIsVerbose()) uinfo("%s", s_prod_info(NULL, 0, &prod.info, ulogIsDebug())) ; break; case PQUEUE_DUP: uerror("Product already in queue: %s", s_prod_info(NULL, 0, &prod.info, 1)); exitCode = exit_dup; break; case ENOMEM: uerror("queue full?"); break; case EINTR: #if defined(EDEADLOCK) && EDEADLOCK != EDEADLK case EDEADLOCK: /*FALLTHROUGH*/ #endif case EDEADLK: /* TODO: retry ? */ /*FALLTHROUGH*/ default: uerror("pq_insert: %s", status > 0 ? strerror(status) : "Internal error"); } } /* data read into "index" region */ if (status != ENOERR) { (void)pqe_discard(pq, index); index = PQE_NONE; } } /* "index" region allocated */ #endif /*HAVE_MMAP*/ (void) close(fd); } /* input-file loop */ free_MD5_CTX(md5ctxp); } /* code block */ exit(exitCode); }
/* The following X functions affect are the only ones that affect the name cache (and the directory cache): nfs_open (in file nfs_lookup_cache.c), nfs_lookup (in file nfs_lookup_cache.c), nfs_link, nfs_symlink, nfs_mkdir, nfs_rmdir, nfs_rename */ int nfs_unlink(struct file *dirp, const char *name) { nfsc_p d,f; int dev; struct nfs_fh *fhandle; int status,lookup_status; DPRINTF(CLU_LEVEL,("** nfs_unlink %s\n",name)); demand(dirp, bogus filp); d = GETNFSCE(dirp); fhandle = GETFHANDLE(dirp); dev = FHGETDEV(fhandle); lookup_status = nfs_cache_lookup(dev,GETNFSCEINO(d),name,&f); switch(lookup_status) { case -1: /* negative cache hit, treat it as a miss to be sure is properly removed */ case 0: /* cache miss */ { struct nfs_fh fhandle2; struct nfs_fattr temp_fattr; k2printf("nfs_unlink: nfs_proc_lookup %s\n",name); status = nfs_proc_lookup(fhandle, name, &fhandle2, &temp_fattr); if (status != 0) { errno = status; return -1; } f = nfsc_get(dev,temp_fattr.fileid); nfs_fill_stat(&temp_fattr, f); } /* fall-through now that we have setup f */ case 1: /* cache hit */ if (nfsc_get_refcnt(f) == 1) { /* last copy */ if (S_ISDIR(nfsc_get_mode(f))) { status = nfs_proc_rmdir(fhandle, name); //fprintf(stderr,"rmdir status %d\n",status); } else { status = nfs_proc_remove(fhandle,name); //fprintf(stderr,"remove status %d\n",status); } if (status == 0) { nfs_cache_remove(dirp,NULL); nfs_flush_filp(dirp); } nfsc_put(f); if (status != 0) { errno = status; return -1; } return 0; } else { /* has other references */ static int i = 0; char difname[NAME_MAX]; //fprintf(stderr,"removing a file that is still referenced: %s\n",name); demand (!(S_ISDIR(f->sb.st_mode)), removing last ref directory); if (i == 0) atexit(nfs_process_unlinkatend); sprintf(difname,".nfs%d%d.%s",time(0),i++,name); status = nfs_proc_rename(fhandle,name,fhandle,difname); if (status != 0) fprintf(stderr,"could not rename %s\n",name); nfs_cache_remove(dirp,name); nfs_flush_filp(dirp); nfs_unlinkatend(difname, fhandle); nfsc_put(f); /* since it will be unlinked we can avoid flushing on close */ nfsc_or_flags(f,NFSCE_WILLBEGONE); return 0; } default: PR; assert(0); return 0; } }
static ssize_t resume_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf,"%d:%d\n", MAJOR(swsusp_resume_device), MINOR(swsusp_resume_device)); }
int isdn_divert_icall(isdn_ctrl *ic) { int retval = 0; unsigned long flags; struct call_struc *cs = NULL; struct deflect_struc *dv; char *p,*p1; u_char accept; /* first check the internal deflection table */ for (dv = table_head; dv ; dv = dv->next ) { /* scan table */ if (((dv->rule.callopt == 1) && (ic->command == ISDN_STAT_ICALLW)) || ((dv->rule.callopt == 2) && (ic->command == ISDN_STAT_ICALL))) continue; /* call option check */ if (!(dv->rule.drvid & (1L << ic->driver))) continue; /* driver not matching */ if ((dv->rule.si1) && (dv->rule.si1 != ic->parm.setup.si1)) continue; /* si1 not matching */ if ((dv->rule.si2) && (dv->rule.si2 != ic->parm.setup.si2)) continue; /* si2 not matching */ p = dv->rule.my_msn; p1 = ic->parm.setup.eazmsn; accept = 0; while (*p) { /* complete compare */ if (*p == '-') { accept = 1; /* call accepted */ break; } if (*p++ != *p1++) break; /* not accepted */ if ((!*p) && (!*p1)) accept = 1; } /* complete compare */ if (!accept) continue; /* not accepted */ if ((strcmp(dv->rule.caller,"0")) || (ic->parm.setup.phone[0])) { p = dv->rule.caller; p1 = ic->parm.setup.phone; accept = 0; while (*p) { /* complete compare */ if (*p == '-') { accept = 1; /* call accepted */ break; } if (*p++ != *p1++) break; /* not accepted */ if ((!*p) && (!*p1)) accept = 1; } /* complete compare */ if (!accept) continue; /* not accepted */ } switch (dv->rule.action) { case DEFLECT_IGNORE: return(0); break; case DEFLECT_ALERT: case DEFLECT_PROCEED: case DEFLECT_REPORT: case DEFLECT_REJECT: if (dv->rule.action == DEFLECT_PROCEED) if ((!if_used) || ((!extern_wait_max) && (!dv->rule.waittime))) return(0); /* no external deflection needed */ if (!(cs = (struct call_struc *) kmalloc(sizeof(struct call_struc), GFP_ATOMIC))) return(0); /* no memory */ init_timer(&cs->timer); cs->info[0] = '\0'; cs->timer.function = deflect_timer_expire; cs->timer.data = (ulong) cs; /* pointer to own structure */ cs->ics = *ic; /* copy incoming data */ if (!cs->ics.parm.setup.phone[0]) strcpy(cs->ics.parm.setup.phone,"0"); if (!cs->ics.parm.setup.eazmsn[0]) strcpy(cs->ics.parm.setup.eazmsn,"0"); cs->ics.parm.setup.screen = dv->rule.screen; if (dv->rule.waittime) cs->timer.expires = jiffies + (HZ * dv->rule.waittime); else if (dv->rule.action == DEFLECT_PROCEED) cs->timer.expires = jiffies + (HZ * extern_wait_max); else cs->timer.expires = 0; cs->akt_state = dv->rule.action; save_flags(flags); cli(); cs->divert_id = next_id++; /* new sequence number */ restore_flags(flags); cs->prev = NULL; if (cs->akt_state == DEFLECT_ALERT) { strcpy(cs->deflect_dest,dv->rule.to_nr); if (!cs->timer.expires) { strcpy(ic->parm.setup.eazmsn,"Testtext direct"); ic->parm.setup.screen = dv->rule.screen; strcpy(ic->parm.setup.phone,dv->rule.to_nr); cs->akt_state = DEFLECT_AUTODEL; /* delete after timeout */ cs->timer.expires = jiffies + (HZ * AUTODEL_TIME); retval = 5; } else retval = 1; /* alerting */ } else { cs->deflect_dest[0] = '\0'; retval = 4; /* only proceed */ } sprintf(cs->info,"%d 0x%lx %s %s %s %s 0x%x 0x%x %d %d %s\n", cs->akt_state, cs->divert_id, divert_if.drv_to_name(cs->ics.driver), (ic->command == ISDN_STAT_ICALLW) ? "1":"0", cs->ics.parm.setup.phone, cs->ics.parm.setup.eazmsn, cs->ics.parm.setup.si1, cs->ics.parm.setup.si2, cs->ics.parm.setup.screen, dv->rule.waittime, cs->deflect_dest); if ((dv->rule.action == DEFLECT_REPORT) || (dv->rule.action == DEFLECT_REJECT)) { put_info_buffer(cs->info); kfree(cs); /* remove */ return((dv->rule.action == DEFLECT_REPORT) ? 0:2); /* nothing to do */ } break; default: return(0); /* ignore call */ break; } /* switch action */ break; } /* scan_table */ if (cs) { cs->prev = NULL; save_flags(flags); cli(); cs->next = divert_head; divert_head = cs; if (cs->timer.expires) add_timer(&cs->timer); restore_flags(flags); put_info_buffer(cs->info); return(retval); } else return(0); } /* isdn_divert_icall */