bool ICACHE_FLASH_ATTR config_load(config_t* config) { DEBUG_FUNCTION_START(); // read head SpiFlashOpResult result = spi_flash_read(config->address, (uint32*) &config->head, sizeof(config->head)); if (result != SPI_FLASH_RESULT_OK) return false; // check head if (config->head.magic != CONFIG_MAGIC) return false; if (config->head.version != CONFIG_VERSION) return false; if (config->head.name.length > stack_buffer_left(&config->server->name)) return false; if (config->head.wifi.ssid.length > sizeof(config->network->station_config.ssid)) return false; if (config->head.wifi.password.length > sizeof(config->network->station_config.password)) return false; // read data data_read(config, config->head.name.buffer, config->server->name.start, config->head.name.length); stack_buffer_skip(&config->server->name, config->head.name.length); data_read(config, config->head.wifi.ssid.buffer, config->network->station_config.ssid, config->head.wifi.ssid.length); m_memset(config->network->station_config.ssid + config->head.wifi.ssid.length, 0, sizeof(config->network->station_config.ssid) - config->head.wifi.ssid.length); data_read(config, config->head.wifi.password.buffer, config->network->station_config.password, config->head.wifi.password.length); m_memset(config->network->station_config.password + config->head.wifi.password.length, 0, sizeof(config->network->station_config.password) - config->head.wifi.password.length); return true; }
/** * Funcion que añade un nodo a la lista que ya esta creada * * * */ void add_node(struct publicacion **primero){ struct publicacion *node = (struct publicacion *) malloc (sizeof (struct publicacion)); char *tipo_contribucion; printf ("Conferencia o Articulo(c/a): "); tipo_contribucion = string_read(); if ( strcmp (tipo_contribucion,"c") ){ node->tipo_contribucion = 0; } else if ( strcmp (tipo_contribucion,"a") ){ node->tipo_contribucion = 1; } free (tipo_contribucion); printf ("\nID: "); node->id = data_read(); printf("\nTitulo de publicacion: "); node->titulo_publicacion = string_read(); printf("\nNombre de la fuente: "); node->nombre_fuente = string_read(); printf("\nAutores: "); node->autores = string_read(); printf("\nAño de publicacion: "); node->ano_publicacion = data_read(); printf("\nISBN/ISSN: "); node->isbn_issn = (long) data_read(); if (node->tipo_contribucion == 0){ printf ("\nLugar de la conferencia: "); node->lugar_conferencia = string_read(); } else if (node->tipo_contribucion == 1){ printf ("\nVolumen de la revista: "); node->vol_revista = data_read(); printf ("\nNumero de la revista: "); node->num_revista = data_read(); } node->next = *primero; *primero = node; printf ("\n"); return; }
int main(int argc, char *argv[]){ options opts; opts.n_arrows = 100; opts.kmeans_attempts = 1; opts.use_all_vectors = 0; int c, i; opterr = 0; while((c = getopt(argc, argv, "ak:n:")) != -1){ switch(c){ case 'a': opts.use_all_vectors = 1; break; case 'k': opts.kmeans_attempts = atoi(optarg); if(opts.kmeans_attempts < 1){ opts.kmeans_attempts = 1; } break; case 'n': opts.n_arrows = atoi(optarg); if(opts.n_arrows < 1){ opts.n_arrows = 1; } break; case '?': if('k' == optopt || 'n' == optopt){ fprintf(stderr, "Option -%c requires an argument.\n", optopt); }else if(isprint(optopt)){ fprintf(stderr, "Unknown option `-%c'.\n", optopt); }else{ fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); } default: usage(); return EXIT_FAILURE; } } if(optind >= argc){ usage(); return EXIT_FAILURE; } for(i = optind; i < argc; i++){ data d; data_init(&d); data_read(&d, argv[i]); if(opts.use_all_vectors || d.n <= opts.n_arrows || data_cull_zeros(&d, opts.n_arrows)){ output_plot(&d); }else{ data plot_data; data_init(&plot_data); gen_plot_kmeans(&d, opts.n_arrows, &plot_data, opts.kmeans_attempts); output_plot(&plot_data); data_destroy(&plot_data); } data_destroy(&d); } return EXIT_SUCCESS; }
static int _fuzz_rep_read(struct x86_emulate_ctxt *ctxt, const char *why, unsigned long *reps) { int rc; unsigned long bytes_read = 0; rc = data_read(ctxt, x86_seg_none, why, &bytes_read, sizeof(bytes_read)); if ( bytes_read <= *reps ) *reps = bytes_read; switch ( rc ) { case X86EMUL_UNHANDLEABLE: /* No work is done in this case */ *reps = 0; break; case X86EMUL_EXCEPTION: case X86EMUL_RETRY: /* Halve the amount in this case */ *reps /= 2; break; } return rc; }
static int fuzz_read_io( unsigned int port, unsigned int bytes, unsigned long *val, struct x86_emulate_ctxt *ctxt) { return data_read(ctxt, x86_seg_none, "read_io", val, bytes); }
static int fuzz_fetch( unsigned int seg, unsigned long offset, void *p_data, unsigned int bytes, struct x86_emulate_ctxt *ctxt) { return data_read("fetch", p_data, bytes); }
void DataLink::acceptConnection() { connection = tcpServer.nextPendingConnection(); connect(connection, SIGNAL(readyRead()), this, SLOT(data_read())); connect(connection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); qDebug() << "Connection accepted"; //tcpServer.close(); }
int main(int argc,char **argv) { init(); if(open_accesory_com_dev()){ return -1; } printf("open\n"); data_read(); return 0; }
void app_apdu(nfc_tech_iso7816_app_t *pIso7816App, void *pUserData) { nfc_tech_type4_target_t *pType4Target = (nfc_tech_type4_target_t *) pUserData; //Reset buffers ac_buffer_builder_set_full(&pType4Target->ccFileBldr); ac_buffer_builder_set_full(&pType4Target->ndefFileBldr); ac_buffer_builder_set_full(ndef_msg_buffer_builder(pType4Target->pNdef)); //Set offset to 0, size to max ac_buffer_set_next(ac_buffer_builder_buffer(&pType4Target->ndefFileBldr), ac_buffer_builder_buffer(ndef_msg_buffer_builder(pType4Target->pNdef))); //Recover PDU nfc_tech_iso7816_c_apdu_t *pCApdu = nfc_tech_iso7816_app_c_apdu(pIso7816App); nfc_tech_iso7816_r_apdu_t *pRApdu = nfc_tech_iso7816_app_r_apdu(pIso7816App); nfc_err_t ret; switch (pCApdu->ins) { case ISO7816_INS_SELECT: switch (pCApdu->p1) { case 0x00: //Selection by ID case 0x02: //Selection by child ID if (ac_buffer_reader_readable(&pCApdu->dataIn) != 2) { pRApdu->sw = ISO7816_SW_NOT_FOUND; break; } uint16_t file = ac_buffer_read_nu16(&pCApdu->dataIn); if (file == NDEF_FILE) { pType4Target->selFile = NDEF_FILE; NFC_DBG("NDEF File selected"); pRApdu->sw = ISO7816_SW_OK; } else if (file == CC_FILE) { pType4Target->selFile = CC_FILE; NFC_DBG("CC File selected"); pRApdu->sw = ISO7816_SW_OK; } else { //file = DEFAULT_FILE; NFC_DBG("Could not select file %04X", file); pRApdu->sw = ISO7816_SW_NOT_FOUND; } break; default: pRApdu->sw = ISO7816_SW_NOT_FOUND; break; } break; case 0xB0: //Read binary NFC_DBG("Trying to read %d bytes at offset %d from file %04x", pCApdu->maxRespLength, (pCApdu->p1 << 8) | pCApdu->p2, pType4Target->selFile); ret = data_read(pType4Target, &pRApdu->dataOut, pType4Target->selFile, (pCApdu->p1 << 8) | pCApdu->p2, pCApdu->maxRespLength); if (ret == NFC_OK) { NFC_DBG("Read %d bytes", ac_buffer_reader_readable(&pRApdu->dataOut)); NFC_DBG_BLOCK(ac_buffer_dump(&pRApdu->dataOut);) pRApdu->sw = ISO7816_SW_OK; } else {
int main(int argc, char const* argv[]) { struct addrinfo hints, *ai, *ai0; int sock, error; int turn = 0; uint32_t budget = 200; char host[16]; char port[16]; strcpy(host, argv[1]); strcpy(port, argv[2]); //char host[] = *argv[1]; //char port = *argv[2]; printf("%s\n", host); do_connect(host, port, hints, ai, ai0, error, sock); //unsigned int buf; uint32_t buf[128]; int buf_len; //uint32_t get_data[ELEM]; /* bool connect = true; while(1) { if(buf_len = read(sock, &buf, BUFSIZE) <= 0) { connect = false; break; } data_read(); buf = ntohl(buf); printf("read : &u\n", buf); } */ /* while(buf_len = read(sock, &buf, BUFSIZE) > 0) { data_read(*buf, buf_len, get_data); printf("read : &u\n", buf); } */ int i; for(i = 0; i < ELEM; i++) { if(buf_len = read(sock, &buf, BUFSIZE) > 0) { data_read(*buf, buf_len, i); } else { printf("cannot read.\n"); } } return 0; }
static int fuzz_read( enum x86_segment seg, unsigned long offset, void *p_data, unsigned int bytes, struct x86_emulate_ctxt *ctxt) { /* Reads expected for all user and system segments. */ assert(is_x86_user_segment(seg) || is_x86_system_segment(seg)); return data_read(ctxt, seg, "read", p_data, bytes); }
uint32_t io_read() { io_stb_assert(); dir_read(); addr_0(); __asm__("nop"); __asm__("nop"); __asm__("nop"); const auto switches_raw = data_read(); io_stb_deassert(); return switches_raw; }
static int __init read_suspend_image(void) { int error = 0; if ((error = check_sig())) return error; if ((error = check_header())) return error; if ((error = read_pagedir())) return error; if ((error = data_read())) free_pages((unsigned long)pagedir_nosave, pagedir_order); return error; }
int td0dsk_t::next_word() { if(tdctl.ibufndx >= tdctl.ibufcnt) { tdctl.ibufndx = 0; tdctl.ibufcnt = data_read(tdctl.inbuf,BUFSZ); if(tdctl.ibufcnt <= 0) return(-1); } while (getlen <= 8) { // typically reads a word at a time getbuf |= tdctl.inbuf[tdctl.ibufndx++] << (8 - getlen); getlen += 8; } return(0); }
void run(void) { uint8_t c; int q=0; int st=0; int it=0; cmd_t *cptr; while(1) { it++; c = data_read(); if(p_cache[q]==NULL) { st=1; break; } cptr=p_cache[q]; while(cmd_qF(*cptr)==q && cmd_cF(*cptr)!=c)cptr++; if(cmd_qF(*cptr)==q) { q=cmd_qT(*cptr); data_write(cmd_cT(*cptr)); if(debug) printf("Q%02i -> Q%02i; %c -> %c\n", cmd_qF(*cptr),cmd_qT(*cptr), cmd_cF(*cptr), cmd_cT(*cptr)); if(cmd_act(*cptr)==CMD_ACT_S) break; else if(cmd_act(*cptr)==CMD_ACT_L) data.pos--; else if(cmd_act(*cptr)==CMD_ACT_R) data.pos++; } else { st=1; break; } } if(st==1) printf("ERROR: No command. Q = %i, C = `%c`, pos = %i\n", q, c, data.pos); else printf("Done.\n"); printf("Count of iterations:%i\n", it); }
/* * Incremental receive byte without stop (?). It is unclear why the slave * address is specified if this presumably is used in combination with * ig4iic_smb_quick(). */ int ig4iic_smb_recvb(device_t dev, u_char slave, char *byte) { ig4iic_softc_t *sc = device_get_softc(dev); int error; mtx_lock(&sc->mtx); set_slave_addr(sc, slave, 0); reg_write(sc, IG4_REG_DATA_CMD, IG4_DATA_COMMAND_RD); if (wait_status(sc, IG4_STATUS_RX_NOTEMPTY) == 0) { *byte = data_read(sc); error = 0; } else { *byte = 0; error = SMB_ETIMEOUT; } mtx_unlock(&sc->mtx); return error; }
static int fuzz_insn_fetch( enum x86_segment seg, unsigned long offset, void *p_data, unsigned int bytes, struct x86_emulate_ctxt *ctxt) { assert(seg == x86_seg_cs); /* * Zero-length instruction fetches are made at the destination of jumps, * to perform segmentation checks. No data needs returning. */ if ( bytes == 0 ) { assert(p_data == NULL); return maybe_fail(ctxt, "insn_fetch", true); } return data_read(ctxt, seg, "insn_fetch", p_data, bytes); }
/*========================================== * main *========================================== */ int main(int argc, char* argv[]) { int c, iter, ITER=0, seed=0; enum dataType data = LdaC; enum dataType testdata = LdaC; int dots = 0; enum GibbsType fix_hold = GibbsNone; char *stem; char *resstem; int topwords = 20; int noerrorlog = 0; int displayed = 0; int load_vocab = 0; int checkpoint = 0; int restart = 0; int dopmi = 0; int restart_hca = 0; int load_phi = 0; int load_mu = 0; int procs = 1; int maxW = 0; enum ScoreType score=ST_idf; double BM0val=0, BM1val =0, BP0val=0, BP1val=0; clock_t t1=0, t2=0, t3=0; double tot_time = 0; double psample_time = 0; enum ParType par; /* * default values */ ddN.T = 10; ITER = 100; ddN.TEST = 0; pctl_init(); while ( (c=getopt(argc, argv,"b:c:C:d:ef:F:g:G:h:K:l:L:N:o:pq:vr:s:S:t:T:vVW:"))>=0 ) { switch ( c ) { case 'b': if ( !optarg || sscanf(optarg,"%d",&ddP.back)!=1 ) yap_quit("Need a valid 'b' argument\n"); break; case 'c': if ( !optarg || sscanf(optarg,"%d",&checkpoint)!=1 ) yap_quit("Need a valid 'c' argument\n"); break; case 'C': if ( !optarg || sscanf(optarg,"%d",&ITER)!=1 ) yap_quit("Need a valid 'C' argument\n"); break; case 'd': if ( !optarg || sscanf(optarg,"%d",&dots)!=1 ) yap_quit("Need a valid 'd' argument\n"); break; case 'e': noerrorlog++; break; case 'f': if ( strcmp(optarg,"witdit")==0 ) data = WitDit; else if ( strcmp(optarg,"docword")==0 ) data = Docword; else if ( strcmp(optarg,"ldac")==0 ) data = LdaC; else if ( strcmp(optarg,"bag")==0 ) data = TxtBag; else if ( strcmp(optarg,"lst")==0 ) data = SeqTxtBag; else yap_quit("Illegal data type for -f\n"); break; case 'F': if ( strcmp(optarg,"all")==0 ) { for (par=ParAM; par<=ParBB; par++) ddT[par].fix = 1; } else { par = findpar(optarg); if ( par==ParNone ) yap_quit("Illegal arg for -F\n"); ddT[par].fix = 1; } break; case 'g': { char var[100]; int st=0; if ( !optarg || sscanf(optarg,"%[^, ],%d", &var[0], &st)<1 ) yap_quit("Need a valid 'g' argument\n"); par = findpar(var); if ( par==ParBP1 ) ddP.kbatch = st; else yap_quit("Illegal var for -g\n"); } break; case 'G': { char var[100]; int st=0, cy=0; if ( !optarg || sscanf(optarg,"%[^, ],%d,%d", &var[0], &cy, &st)<2 || st<0 || cy<0 ) yap_quit("Need a valid 'G' argument\n"); par = findpar(var); if ( par==ParNone || par==ParB0P || par==ParB0M ) yap_quit("Illegal var for -G\n"); ddT[par].fix = 0; ddT[par].start = st; ddT[par].cycles = cy; } break; case 'h': { fix_hold = GibbsHold; if ( !optarg ) yap_quit("Need a valid 'h' argument\n"); if ( strncmp(optarg,"dict,",5)==0 ) { if ( sscanf(&optarg[5],"%d",&ddP.hold_dict)<1 || ddP.hold_dict<2 ) yap_quit("Need a valid 'hdict' argument\n"); } else if ( strncmp(optarg,"fract,",6)==0 ) { if ( sscanf(&optarg[6],"%lf",&ddP.hold_fraction)<1 || ddP.hold_fraction<=0 || ddP.hold_fraction>=1 ) yap_quit("Need a valid 'hfract' argument\n"); } else if ( strncmp(optarg,"doc,",4)==0 ) { if ( sscanf(&optarg[4],"%d",&ddP.hold_every)<1 || ddP.hold_every<2 ) yap_quit("Need a valid 'hdoc' argument\n"); } else yap_quit("Need a valid 'h' argument\n"); } break; case 'K': if ( !optarg || sscanf(optarg,"%d",&ddN.T)!=1 ) yap_quit("Need a valid 'K' argument\n"); break; case 'l': if ( !optarg ) yap_quit("Need a valid 'l ' argument\n"); if ( strncmp(optarg,"phi,",4)==0 ) { if ( sscanf(&optarg[4],"%d,%d",&ddP.phiiter, &ddP.phiburn)<2 ) yap_quit("Need a valid 'l word,' argument\n"); } else if ( strncmp(optarg,"theta,",6)==0 ) { if ( sscanf(&optarg[6],"%d,%d",&ddP.thetaiter, &ddP.thetaburn)<2 ) yap_quit("Need a valid 'l word,' argument\n"); } else if ( strncmp(optarg,"mu,",3)==0 ) { if ( sscanf(&optarg[3],"%d,%d",&ddP.muiter, &ddP.muburn)<2 ) yap_quit("Need a valid 'l word,' argument\n"); } else if ( strncmp(optarg,"prog,",5)==0 ) { if ( sscanf(&optarg[5],"%d,%d",&ddP.progiter, &ddP.progburn)<2 ) yap_quit("Need a valid 'l prog,' argument\n"); } else yap_quit("Need a valid DIAG code in 'l' argument\n"); break; case 'L': if ( !optarg ) yap_quit("Need a valid 'L ' argument\n"); if ( strncmp(optarg,"like,",5)==0 ) { if ( sscanf(&optarg[5],"%d,%d",&ddP.mltiter, &ddP.mltburn)<1 ) yap_quit("Need a valid 'L like' argument\n"); } else yap_quit("Need a valid DIAG code in 'L' argument\n"); break; case 'N': if ( !optarg || sscanf(optarg,"%d,%d", &ddP.maxN, &ddP.maxM)<1 ) yap_quit("Need a valid 'N' argument\n"); break; case 'o': { char *ptr = strchr(optarg, ','); int len = strlen(optarg); if ( ptr ) len = ptr - optarg; if ( strncmp(optarg,"idf",len)==0 ) score = ST_idf; else if ( strncmp(optarg,"count",len)==0 ) score = ST_count; else if ( strncmp(optarg,"Q",len)==0 ) score = ST_Q; else if ( strncmp(optarg,"cost",len)==0 ) score = ST_cost; else yap_quit("Need a valid parameter for 'o' argument\n"); if ( ptr ) { /* there was a second arg */ if ( sscanf(ptr+1, "%d", &topwords) != 1) yap_quit("Need a valid second 'o' argument\n"); } break; } break; case 'p': dopmi++; break; case 'q': if(!optarg || sscanf(optarg, "%d", &procs) != 1) yap_quit("Need a valid 'q' argument\n"); break; case 'r': if(!optarg ) yap_quit("Need a valid 'r' argument\n"); if ( strcmp(optarg,"tca")==0 ) restart++; else if ( strcmp(optarg,"hca")==0 ) restart_hca++; else if ( strcmp(optarg,"phi")==0 ) load_phi++; else if ( strcmp(optarg,"mu")==0 ) load_mu++; else yap_quit("Need a valid 'r' argument\n"); break; case 's': if ( !optarg || sscanf(optarg,"%d",&seed)!=1 ) yap_quit("Need a valid 's' argument\n"); break; case 'S': { char var[100]; double vin=0; if ( !optarg || sscanf(optarg,"%[^=, ]=%lf", &var[0], &vin)<2 ) yap_quit("Need a valid 'S' argument\n"); par = findpar(var); if ( par==ParNone ) yap_quit("Illegal var for -S\n"); else if ( par==ParBM0 ) BM0val = vin; else if ( par==ParBM1 ) BM1val = vin; else if ( par==ParBP0 ) BP0val = vin; else if ( par==ParBP1 ) BP1val = vin; else *(ddT[par].ptr) = vin; } break; case 't': if ( !optarg || sscanf(optarg,"%d",&ddP.training)!=1 ) yap_quit("Need a valid 't' argument\n"); break; case 'T': if ( !optarg ) yap_quit("Need a valid 'T' argument\n"); { char *tname = data_name(optarg,data); FILE *fp = fopen(tname,"r"); if ( fp==NULL ) { free(tname); tname = data_name(optarg,testdata); fp = fopen(tname,"r"); } else { testdata = data; } free(tname); if ( fp!=NULL ) { /* its a valid test filename */ ddP.teststem = optarg; fclose(fp); } else if ( sscanf(optarg,"%d",&ddN.TEST)!=1 ) yap_quit("Need a valid 'T' argument\n"); } break; case 'v': verbose++; break; case 'V': load_vocab = 1; break; case 'W': if ( !optarg || sscanf(optarg,"%d",&maxW)<1 ) yap_quit("Need a valid 'W' argument\n"); break; default: yap_quit("Unknown option '%c'\n", c); } } if (argc-optind != 2) { usage(); exit(-1); } if ( optind>=argc ) { yap_quit("No arguments given\n"); } stem = strdup(argv[optind++]); resstem = strdup(argv[optind++]); if ( dopmi ) load_vocab = 1; if ( dopmi && verbose !=2 ) { /* * due to the use of the ".top" file * its really multi-purpose */ yap_quit("When computing PMI verbose must be exactly 2\n"); } if ( noerrorlog==0 ) { char *wname = yap_makename(resstem, ".log"); yap_file(wname); free(wname); } yap_commandline(argc, argv); #ifdef H_THREADS yap_message(" Threads,"); #endif if ( restart || restart_hca ) { char *fname = yap_makename(resstem,".par"); FILE *fp = fopen(fname,"r"); char *buf; if ( !fp ) yap_quit("Parameter file '%s' doesn't exist\n", fname); fclose(fp); free(fname); buf = readpar(resstem,"T",50); if ( !buf ) yap_quit("Parameter file '%s' has no T\n", fname); ddN.T = atoi(buf); free(buf); if ( restart ) { buf = readpar(resstem,"E",50); if ( !buf ) yap_quit("Parameter file '%s' has no E\n", fname); ddN.E = atoi(buf); free(buf); pctl_read(resstem); } if ( maxW==0 ) { buf = readpar(resstem,"W",50); if ( buf ) { maxW = atoi(buf); free(buf); } } if ( ddP.training==0 ) { buf = readpar(resstem,"TRAIN",50); if ( buf ) { ddP.training = atoi(buf); free(buf); } } if ( ddN.TEST==0 ) { buf = readpar(resstem,"TEST",50); if ( buf ) { ddN.TEST = atoi(buf); free(buf); } } } assert(ddN.T>0); assert(ddN.TEST>=0); assert(restart || restart_hca || ITER>0); if ( load_phi && ddP.phiiter>0 ) yap_quit("Options '-l phi,...' and '-r phi' incompatible\n"); if ( load_mu && ddP.muiter>0 ) yap_quit("Options '-l mu,...' and '-r mu' incompatible\n"); /* * set random number generator */ if ( seed ) { rng_seed(rngp,seed); } else { rng_time(rngp,&seed); } yap_message("Setting seed = %lu\n", seed); /* * read data and get dimensions */ { D_bag_t *dbp = data_read(stem, data); int training = pctl_training(dbp->D); if ( ddP.teststem ) { D_bag_t *dbpt = data_read(ddP.teststem, testdata); /* need to load a separate test set, strip to bare training */ data_shrink(dbp, training); ddN.TEST = dbpt->D; data_append(dbp, dbpt); free(dbpt->w); free(dbpt->d); free(dbpt); } if ( maxW>0 ) { if ( dbp->W <= maxW ) dbp->W = maxW; if ( dbp->W > maxW ) data_vocabshrink(dbp, maxW); } /* * transfer into system */ ddN.D = dbp->D; ddN.W = dbp->W; ddN.N = dbp->N; ddN.NT = dbp->N; ddN.DT = training; ddD.w = dbp->w; ddD.d = dbp->d; free(dbp); if ( ddN.DT<ddN.D ) { /* recompute NT */ int i; for (i=0; i<ddN.N; i++) if ( ddD.d[i]>=ddN.DT ) break; ddN.NT = i; } } data_read_epoch(stem); /* * at this point, dimensions are fixed, so load phi and mu if needed */ if ( load_phi ) pctl_loadphi(resstem); if ( load_mu ) pctl_loadmu(resstem); /* * correct parameters after command line */ pctl_fix(ITER); if ( BM0val>0 ) { ddP.b_mu[0] = BM0val; } if ( BM1val>0 ) { int i; for (i=1; i<ddN.E; i++) ddP.b_mu[i] = BM1val; } if ( BP0val>0 ) { int i; for (i=0; i<ddN.T; i++) ddP.b_phi[0][i] = BP0val; } if ( BP1val>0 ) { int i; if ( ddN.E==1 ) yap_quit("b_phi[1] invalid when epochs==1\n"); for (i=0; i<ddN.T; i++) ddP.b_phi[1][i] = BP1val; } pctl_samplereport(); /* * all data structures */ data_alloc(); if ( ddP.phiiter>0 ) phi_init(resstem); else ddS.phi = NULL; if ( ddP.muiter>0 ) mu_init(resstem); else ddS.mu = NULL; if ( ddP.thetaiter>0 ) theta_init(resstem); else ddS.theta = NULL; tca_alloc(); if ( PCTL_BURSTY() ) dmi_init(&ddM, ddS.z, ddD.w, ddD.N_dTcum, ddN.T, ddN.N, ddN.W, ddN.D, ddN.DT, (fix_hold==GibbsHold)?pctl_hold:NULL); if ( load_vocab ) { data_vocab(stem); } cache_init(); /* * yap some details */ data_report(ITER, seed); pctl_report(); /* * load/init topic assignments and prepare statistics */ if ( restart || restart_hca) { tca_read_z(resstem, 0, ddN.DT); tca_rand_z(ddN.T, ddN.DT, ddN.D); } else { tca_rand_z(ddN.T, 0, ddN.D); } tca_reset_stats(resstem, restart, 0); if ( (restart || restart_hca ) && ITER ) yap_message("Initial log_2(perp)=%lf\n", -M_LOG2E * likelihood()/ddN.NT); if ( ITER ) yap_report("cycles: "); for (iter=0; iter<ITER; iter++) { int pro; double thislp = 0; int thisNd = 0; int doc; #ifdef H_THREADS pthread_t thread[procs]; #endif D_pargs_p parg[procs]; #ifdef MU_CACHE mu_side_fact_reinit(); #endif #ifdef PHI_CACHE phi_cache_reinit(); #endif t1 = clock(); /* * sampling */ #ifdef IND_STATS ddP.doc_ind_stats = u32tri(ddN.T,ddN.E,ddN.E); ddP.word_ind_stats = u32tri(ddN.T,ddN.E,ddN.E); #endif /* a bit complex if no threads! */ doc = 0; for (pro = 0 ; pro < procs ; pro++){ parg[pro].dots=dots; parg[pro].procs=procs; parg[pro].doc = &doc; #ifndef H_THREADS sampling_p(&parg[pro]); #else if ( procs==1 ) sampling_p(&parg[pro]); else if( pthread_create(&thread[pro],NULL,sampling_p,(void*) &parg[pro]) != 0){ yap_message("thread failed %d\n",pro+1 ); } #endif } #ifdef H_THREADS if ( procs>1 ) { //waiting for threads to finish for (pro = 0; pro < procs; pro++){ pthread_join(thread[pro], NULL); } } #endif // getting lp, Nd and clock for(pro = 0; pro < procs; pro++){ thislp += parg[pro].thislp; thisNd += parg[pro].thisNd; tot_time += parg[pro].tot_time; } #ifdef H_THREADS if ( procs>1 ) tca_reset_stats(NULL,1,1); #endif /* * full check */ #ifndef NDEBUG { int e, d; check_cp_et(); for (e=0; e<ddN.E; e++) check_m_vte(e); for (d=0; d<ddN.DT; d++) check_n_dt(d); } #endif #ifdef IND_STATS { char *fname = yap_makename(resstem,".istats"); FILE *ifp = fopen(fname,"a"); int e1, e2, kk; fprintf(ifp,"Iteration %d\n", iter); for (kk=0; kk<ddN.T; kk++) { fprintf(ifp," Topic %d\n", kk); for (e1=0; e1<ddN.E; e1++) { fprintf(ifp," Epoch %d\n ", e1); for (e2=0; e2<ddN.E; e2++) fprintf(ifp," %u", (unsigned)ddP.doc_ind_stats[kk][e1][e2]); fprintf(ifp,"\n "); for (e2=0; e2<ddN.E; e2++) fprintf(ifp," %u", (unsigned)ddP.word_ind_stats[kk][e1][e2]); fprintf(ifp,"\n"); } } fclose(ifp); free(ddP.doc_ind_stats[0][0]); free(ddP.doc_ind_stats[0]); free(ddP.doc_ind_stats); free(ddP.word_ind_stats[0][0]); free(ddP.word_ind_stats[0]); free(ddP.word_ind_stats); free(fname); } #endif /* * sample hyperparameters */ t3 = clock(); pctl_sample(iter, procs); /* * do time calcs here to remove diagnostics+reporting */ t2 = clock(); tot_time += (double)(t2 - t1) / CLOCKS_PER_SEC; psample_time += (double)(t2 - t3) / CLOCKS_PER_SEC; /* * progress reports */ if ( ( iter>ddP.progburn && (iter%ddP.progiter)==0 ) || iter+1>=ITER ) { yap_message(" %d\nlog_2(perp)=%lf,%lf", iter, -M_LOG2E * likelihood()/ddN.NT, -M_LOG2E * thislp/thisNd); pctl_update(iter); if ( verbose && iter%10==0 ) yap_probs(); if ( iter>0 && verbose>1 ) { if ( ddN.tokens ) { tca_displaytopics(resstem,topwords,score); displayed++; } } if ( iter+1<ITER ) { // yap_message("\n"); yap_report("cycles: "); } } else { yap_message(" %d", iter); if ( verbose>1) yap_message("\n"); } if ( checkpoint>0 && iter>0 && iter%checkpoint==0 ) { data_checkpoint(resstem, stem, iter+1); yap_message(" checkpointed\n"); tca_report(resstem, stem, ITER, procs, fix_hold, (dopmi&&displayed>0)?1:0); } if ( ddP.phiiter>0 && iter>ddP.phiburn && (iter%ddP.phiiter)==0 ) phi_update(); if ( ddP.thetaiter>0 && iter>ddP.thetaburn && (iter%ddP.thetaiter)==0 ) theta_update(); if ( ddP.muiter>0 && iter>ddP.muburn && (iter%ddP.muiter)==0 ) mu_update(); } // over iter if ( ITER ) yap_report("Finished after %d cycles on average of %lf+%lf(s) per cycle\n", iter, (tot_time-psample_time)/iter, psample_time/iter); if ( ( verbose==1 || ((iter+1)%5!=0 && verbose>1) ) ) { if ( ddN.tokens ) { tca_displaytopics(resstem,topwords,score); displayed++; } } yap_probs(); if ( ITER>0 ) data_checkpoint(resstem, stem, ITER); tca_report(resstem, stem, ITER, procs, fix_hold, (dopmi&&displayed>0)?1:0); if ( ddP.phiiter>0 ) phi_save(resstem); if ( ddP.thetaiter>0 ) theta_save(resstem); if ( ddP.muiter>0 ) mu_save(resstem); /* * free */ phi_free(); theta_free(); mu_free(); cache_free(); pctl_free(); data_free(); dmi_free(&ddM); tca_free(); free(stem); free(resstem); rng_free(rngp); return 0; }
int main(int argc, char *argv[]) { char *dev_name; char *file_name; int dev_fd = 0; FILE *file_fd = NULL; int cnt = 0; struct tsu_stat tsu_stat; /* Eecutable name. */ util_name = argv[cnt++]; if(argc < 4) { if(argc > 1) fprintf(stderr,"Missing parameters.\n"); usage(); } /* Device name */ dev_name = argv[cnt++]; /* Read / Write operation. */ if(!strcmp(argv[cnt],"r")) { g_is_read = 1; } else if(!strcmp(argv[cnt],"w")) { g_is_read = 0; } else { fprintf(stderr,"Bad read / write option.\n"); usage(); } cnt++; /* Open the device. */ if(g_is_read) dev_fd = open(dev_name, O_RDONLY); else dev_fd = open(dev_name, O_WRONLY); if(dev_fd <= 0) { fprintf(stderr,"%s - Cannot open device %s.\n",util_name,dev_name); exit(2); } /* Input / Output file name. */ file_name = argv[cnt++]; if(g_is_read) { if(!strncmp(file_name,"stdout",strlen("stdout"))) file_fd = stdout; else file_fd = fopen(file_name, "w+"); }else{ file_fd = fopen(file_name, "r"); } if(file_fd == NULL) { fprintf(stderr,"%s - Cannot open file %s.\n",util_name,file_name); goto error; } if(get_buff_info(dev_fd) < 0){ fprintf(stderr,"%s - Failed to retrieve device buffer configuration.\n"); goto error; } /* Allocate buffer. */ data_buff = malloc(g_buf_size); if(data_buff == NULL) { fprintf(stderr,"%s - Failed to allocate memory (%d Bytes).\n",util_name, BUFSIZE); goto error; } if(process_options(argc,argv,cnt,dev_fd) < 0) { fprintf(stderr,"Bad options.\n"); goto error; } /* Clear statistics. */ if(ioctl(dev_fd,MVTSU_IOCCLEARSTAT,0) < 0) { fprintf(stderr,"Error Clearing statistics.\n"); goto error; } if(g_is_read) data_read(dev_fd,file_fd); else data_write(dev_fd,file_fd); /* Print statistics. */ if(ioctl(dev_fd,MVTSU_IOCGETSTAT,&tsu_stat) < 0) { fprintf(stderr,"Error Printing statistics.\n"); goto error; } tsu_print_stat(&tsu_stat); error: if(dev_fd != 0) close(dev_fd); if(file_fd != NULL) fclose(file_fd); if(data_buff != NULL) free(data_buff); if(g_stat_fd != NULL) fclose(g_stat_fd); return 0; }
void dsp16_device::execute_one(const UINT16& op, UINT8& cycles, UINT8& pcAdvance) { cycles = 1; pcAdvance = 0; const UINT8 opcode = (op >> 11) & 0x1f; switch(opcode) { // Format 1: Multiply/ALU Read/Write Group case 0x06: { // F1, Y : (page 3-38) const UINT8 Y = (op & 0x000f); const UINT8 S = (op & 0x0200) >> 9; const UINT8 D = (op & 0x0400) >> 10; const UINT8 F1 = (op & 0x01e0) >> 5; executeF1Field(F1, D, S); executeYFieldPost(Y); cycles = 1; pcAdvance = 1; break; } case 0x04: case 0x1c: { // F1 Y=a0[1] | F1 Y=a1[1] //const UINT8 Y = (op & 0x000f); //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 D = (op & 0x0400) >> 10; //const UINT8 F1 = (op & 0x01e0) >> 5; break; } case 0x16: { // F1, x = Y //const UINT8 Y = (op & 0x000f); //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 D = (op & 0x0400) >> 10; //const UINT8 F1 = (op & 0x01e0) >> 5; break; } case 0x17: { // F1, y[l] = Y : (page 3-44) const UINT8 Y = (op & 0x000f); const UINT8 X = (op & 0x0010) >> 4; const UINT8 S = (op & 0x0200) >> 9; const UINT8 D = (op & 0x0400) >> 10; const UINT8 F1 = (op & 0x01e0) >> 5; executeF1Field(F1, D, S); UINT16* sourceReg = (UINT16*)registerFromYFieldUpper(Y); UINT16 sourceValue = data_read(*sourceReg); switch (X) { case 0x00: writeRegister(addressYL(), sourceValue); break; case 0x01: writeRegister(&m_y, sourceValue); break; default: break; } executeYFieldPost(Y); cycles = 1; pcAdvance = 1; break; } case 0x1f: { // F1, y = Y, x = *pt++[i] //const UINT8 Y = (op & 0x000f); //const UINT8 X = (op & 0x0010) >> 4; //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 D = (op & 0x0400) >> 10; //const UINT8 F1 = (op & 0x01e0) >> 5; break; } case 0x19: case 0x1b: { // F1, y = a0|1, x = *pt++[i] //const UINT8 Y = (op & 0x000f); //const UINT8 X = (op & 0x0010) >> 4; //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 D = (op & 0x0400) >> 10; //const UINT8 F1 = (op & 0x01e0) >> 5; break; } case 0x14: { // F1, Y = y[1] : (page 3-53) const UINT8 Y = (op & 0x000f); const UINT8 X = (op & 0x0010) >> 4; const UINT8 S = (op & 0x0200) >> 9; const UINT8 D = (op & 0x0400) >> 10; const UINT8 F1 = (op & 0x01e0) >> 5; executeF1Field(F1, D, S); UINT16* destinationReg = (UINT16*)registerFromYFieldUpper(Y); UINT16 yRegValue = 0x0000; switch (X) { case 0x00: yRegValue = (m_y & 0x0000ffff); break; case 0x01: yRegValue = (m_y & 0xffff0000) >> 16; break; default: break; } data_write(*destinationReg, yRegValue); executeYFieldPost(Y); cycles = 2; pcAdvance = 1; break; } // Format 1a: Multiply/ALU Read/Write Group (TODO: Figure out major typo in docs on p3-51) case 0x07: { // F1, At[1] = Y : (page 3-50) const UINT8 Y = (op & 0x000f); const UINT8 S = (op & 0x0200) >> 9; const UINT8 aT = (op & 0x0400) >> 10; const UINT8 F1 = (op & 0x01e0) >> 5; executeF1Field(F1, !aT, S); UINT64* destinationReg = NULL; switch(aT) { case 0: destinationReg = &m_a1; break; case 1: destinationReg = &m_a0; break; default: break; } UINT16 sourceAddress = *((UINT16*)registerFromYFieldUpper(Y)); INT64 sourceValueSigned = (INT16)data_read(sourceAddress); *destinationReg = sourceValueSigned & U64(0xffffffffff); executeYFieldPost(Y); cycles = 1; pcAdvance = 1; break; } // Format 2: Multiply/ALU Read/Write Group case 0x15: { // F1, Z : y[1] //const UINT8 Z = (op & 0x000f); //const UINT8 X = (op & 0x0010) >> 4; //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 D = (op & 0x0400) >> 10; //const UINT8 F1 = (op & 0x01e0) >> 5; break; } case 0x1d: { // F1, Z : y, x=*pt++[i] //const UINT8 Z = (op & 0x000f); //const UINT8 X = (op & 0x0010) >> 4; //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 D = (op & 0x0400) >> 10; //const UINT8 F1 = (op & 0x01e0) >> 5; break; } // Format 2a: Multiply/ALU Read/Write Group case 0x05: { // F1, Z : aT[1] //const UINT8 Z = (op & 0x000f); //const UINT8 X = (op & 0x0010) >> 4; //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 aT = (op & 0x0400) >> 10; //const UINT8 F1 = (op & 0x01e0) >> 5; break; } // Format 3: Special Functions case 0x12: case 0x13: { // if|ifc CON F2 //const UINT8 CON = (op & 0x001f); //const UINT8 S = (op & 0x0200) >> 9; //const UINT8 D = (op & 0x0400) >> 10; //const UINT8 F2 = (op & 0x01e0) >> 5; break; } // Format 4: Branch Direct Group case 0x00: case 0x01: { // goto JA : (page 3-20) const UINT16 JA = (op & 0x0fff) | (m_pc & 0xf000); m_pc = JA; cycles = 2; pcAdvance = 0; break; } case 0x10: case 0x11: { // call JA : (page 3-23) const UINT16 JA = (op & 0x0fff) | (m_pc & 0xf000); m_pr = m_pc + 1; m_pc = JA; cycles = 2; pcAdvance = 0; break; } // Format 5: Branch Indirect Group case 0x18: { // goto B //const UINT8 B = (op & 0x0700) >> 8; break; } // Format 6: Contitional Branch Qualifier/Software Interrupt (icall) case 0x1a: { // if CON [goto/call/return] //const UINT8 CON = (op & 0x001f); break; } // Format 7: Data Move Group case 0x09: case 0x0b: { // R = aS //const UINT8 R = (op & 0x03f0) >> 4; //const UINT8 S = (op & 0x1000) >> 12; break; } case 0x08: { // aT = R //const UINT8 R = (op & 0x03f0) >> 4; //const UINT8 aT = (op & 0x0400) >> 10; break; } case 0x0f: { // R = Y //const UINT8 Y = (op & 0x000f); //const UINT8 R = (op & 0x03f0) >> 4; break; } case 0x0c: { // Y = R : (page 3-33) const UINT8 Y = (op & 0x000f); const UINT8 R = (op & 0x03f0) >> 4; UINT16* destinationReg = (UINT16*)registerFromYFieldUpper(Y); UINT16* sourceReg = (UINT16*)registerFromRTable(R); data_write(*destinationReg, *sourceReg); executeYFieldPost(Y); cycles = 2; pcAdvance = 1; break; } case 0x0d: { // Z : R //const UINT8 Z = (op & 0x000f); //const UINT8 R = (op & 0x03f0) >> 4; break; } // Format 8: Data Move (immediate operand - 2 words) case 0x0a: { // R = N : (page 3-28) const UINT8 R = (op & 0x03f0) >> 4; const UINT16 iVal = opcode_read(1); void* reg = registerFromRTable(R); writeRegister(reg, iVal); cycles = 2; pcAdvance = 2; break; } // Format 9: Short Immediate Group case 0x02: case 0x03: { // R = M : (page 3-27) const INT8 M = (op & 0x00ff); const UINT8 R = (op & 0x0e00) >> 9; void* reg = registerFromRImmediateField(R); writeRegister(reg, (INT16)M); // Sign extend 8 bit int cycles = 1; pcAdvance = 1; break; } // Format 10: do - redo case 0x0e: { // do|redo K : (pages 3-25 & 3-26) const UINT8 K = (op & 0x007f); const UINT8 NI = (op & 0x0780) >> 7; if (NI != 0) { // Do m_cacheStart = m_pc + 1; m_cacheEnd = m_pc + NI + 1; m_cacheIterations = K-1; // -1 because we check the counter below cycles = 1; pcAdvance = 1; } else { // Redo m_cacheIterations = K-1; // -1 because we check the counter below m_cacheRedoNextPC = m_pc + 1; m_pc = m_cacheStart; pcAdvance = 0; cycles = 2; pcAdvance = 1; } break; } // RESERVED case 0x1e: { break; } // UNKNOWN default: { break; } } // Handle end-of-cache conditions for do|redos if (m_cacheIterations == 0 && m_cacheRedoNextPC != CACHE_INVALID) { // You've reached the end of a cache loop after a redo opcode. m_pc = m_cacheRedoNextPC; m_cacheRedoNextPC = CACHE_INVALID; pcAdvance = 0; } if (m_cacheIterations > 0 && (m_pc+pcAdvance == m_cacheEnd)) { // A regular iteration on a cached loop. m_cacheIterations--; m_pc = m_cacheStart; pcAdvance = 0; } }
int main(int argc, char **argv) { if (argc < 3) err_quit("wrong number of parameters"); GraphData *data; Pipe *red_pipe, **blue_pipe; int st, fail, i, j, r, b, **vmatrix, mark, red_balance, msg_balance; int sem[2], monster_pipe[2]; pid_t *blue_pids; pid_t *red_pids; pid_t monster_pid, pid, rpid; const int mark_new_msg = 1; const int mark_dead_msg = -1; const int mark_dead_red = 0; data = data_read(); b = data->b; r = data->r; vmatrix = data->vmatrix; red_pipe = pipes_create(r); blue_pipe = blue_pipe_create(data); blue_pids = (pid_t*) malloc(sizeof(pid_t) * b); //sync pipes if (pipe(sem)) err_sys("sync pipe failed"); //blue processes for (i = 0; i < b; i++) { if ((pid = fork()) == 0) { Message *msg; Message **r_msg, **w_msg; Pipe *read_pipe; int *redp, redp_num, *isdead; int lock, l, k, s; int r_num; lock = 0; redp = (int*) malloc(sizeof(int) * r); isdead = (int*) malloc(sizeof(int) * r); //closing red pipes for (k = 0, j = 0; j < r; j++) { if (data->red[j].node == i) { isdead[k] = 0; redp[k++] = red_pipe[j].fd[0]; close(red_pipe[j].fd[1]); continue; } close(red_pipe[j].fd[0]); close(red_pipe[j].fd[1]); } redp_num = k; //copy pipes from which we read for faster access //and close them for writing, also close other pipes which we don't use in this process read_pipe = (Pipe*) malloc(sizeof(Pipe) * data->read_num[i]); for (k = 0, j = 0; j < b; j++) { if (j == i) continue; if (vmatrix[j][i] == 1) { for (lock = -1, l = 0; l < data->write_num[j]; l++) if (blue_pipe[j][l].to == i) { read_pipe[k++] = blue_pipe[j][l]; lock = l; break; } } for (l = 0; l < data->write_num[j]; l++) { if (l == lock) { close(blue_pipe[j][l].fd[1]); continue; } close(blue_pipe[j][l].fd[0]); close(blue_pipe[j][l].fd[1]); } } r_msg = (Message**) calloc(data->read_num[i], sizeof(Message*)); w_msg = (Message**) calloc(data->write_num[i], sizeof(Message*)); //don't read from pipes in which we write for (j = 0; j < data->write_num[i]; j++) close(blue_pipe[i][j].fd[0]); //main loop while (1) { r_num = -1; msg = NULL; //try to read from red pipes for (s = 0, j = 0; j < redp_num; j++) if (!isdead[j] && (msg = message_read(redp[j], &s, NULL)) != NULL) { //if we've received something from red pipe //we have a new packet in network st = write(sem[1], &mark_new_msg, sizeof(int)); break; } else if (s == -1) { //eof in pipe, so red is dead, and we will not receive smth from this one st = write(sem[1], &mark_dead_red, sizeof(int)); isdead[j] = 1; s = 0; } //try to read from blue pipes if nothing was read from red ones if (msg == NULL) { for (j = 0; j < data->read_num[i]; j++) if ((msg = message_read(read_pipe[j].fd[0], NULL, r_msg[j])) != NULL) { if (msg->len > msg->sv_r) { r_msg[j] = msg; r_num = j; msg = NULL; } else { r_msg[j] = NULL; debug("full - %d | id: %d", msg->len, msg->id); } break; } } //try again if (msg == NULL) { for (j = 0; msg == NULL && j < data->write_num[i]; j++) if (w_msg[j] != NULL) msg = w_msg[j]; if (msg == NULL) { usleep(100); continue; } } //check the message if (!msg->ch) { st = message_check(data, i, msg); fflush(stdout); if (st == MSG_ERROR || st == MSG_END) { //message is dead now st = write(sem[1], &mark_dead_msg, sizeof(int)); message_destroy(msg); continue; } //st == MSG_OK //send message for (j = 0; j < data->write_num[i]; j++) { if (blue_pipe[i][j].to == msg->node[0] - 1) { msg->num_w = j; msg->fd[1] = blue_pipe[i][j].fd[1]; break; } } j = msg->num_w; if (w_msg[j] != NULL) { Message *cur = w_msg[j]; while(cur->next != NULL) cur = cur->next; cur->next = msg; msg = w_msg[j]; } else { w_msg[j] = msg; } } st = message_send(msg->fd[1], msg); if (st == 0) { w_msg[msg->num_w] = w_msg[msg->num_w]->next; message_destroy(msg); } } exit(EXIT_SUCCESS); } else if (pid == -1) { err_sys("failed on %d's blue fork", i); } blue_pids[i] = pid; } //close all blue pipes for (i = 0; i < b; i++) pipes_close(blue_pipe[i], data->write_num[i]); //create red processes red_pids = (pid_t*) malloc(sizeof(pid_t) * r); for (i = 0; i < r; i++) { if ((pid = fork()) == 0) { char *filename = data->red[i].filename; char *name = argv[1]; char num_buf[10]; int pfd = red_pipe[i].fd[1]; dup2(pfd, 1); pipes_close(red_pipe, r); close_pipe(sem); sprintf(num_buf, "%d", i + 1); for (j = strlen(name); j > 0 && name[j] != '/'; j--) ; execlp(name, name + j + 1, num_buf, filename, NULL); err_sys("%d red process exec failed", i); } else if (pid == -1) { err_sys("%d red process fork failed", i); } red_pids[i] = pid; } //close all red pipes pipes_close(red_pipe, r); //create monster pipe and monster process if (pipe(monster_pipe) < 0) err_sys("monster pipe failed"); if ((monster_pid = fork()) == 0) { int *pfd = monster_pipe; char *name = argv[2]; dup2(pfd[0], 0); close_pipe(sem); close_pipe(pfd); for (i = strlen(name); i > 0 && name[i] != '/'; i--) ; execlp(name, name + i + 1, NULL); err_sys("monster process exec failed"); } else if (monster_pid == -1) { err_sys("monster process forking failed"); } close(monster_pipe[0]); //wait red processes for (i = 0; i < r; i++) { rpid = wait(&st); //check if dead process was red //do we need this check or not? for (fail = 1, j = 0; j < r; j++) if (rpid == red_pids[j]) fail = 0; if (fail) { err_quit("an error in blue process has occured, terminating..."); } } //wait all packets to reach their destination //and all red pipes to be read red_balance = r; msg_balance = 0; while (red_balance || msg_balance) { st = read(sem[0], &mark, sizeof(int)); if (st == 0) break; if (st == sizeof(int)) { if (mark == 0) red_balance--; else if (mark == 1) msg_balance++; else if (mark == -1) msg_balance--; continue; } err_sys("error in sync pipe"); } //tell monster to kill our children st = write(monster_pipe[1], &b, sizeof(int)); for (i = 0; i < b; i++) { st = write(monster_pipe[1], &blue_pids[i], sizeof(int)); } close(monster_pipe[1]); //wait him to do his dirty work, ignoring our children deaths while (wait(&st) != monster_pid); //will close everything that was opened and free everything that was allocated return 0; }
/* * Issue START with byte command, possible count, and a variable length * read or write buffer, then possible turn-around read. The read also * has a possible count received. * * For SMBUS - * * Quick: START+ADDR+RD/WR STOP * * Normal: START+ADDR+WR CMD DATA..DATA STOP * * START+ADDR+RD CMD * RESTART+ADDR RDATA..RDATA STOP * (can also be used for I2C transactions) * * Process Call: START+ADDR+WR CMD DATAL DATAH * RESTART+ADDR+RD RDATAL RDATAH STOP * * Block: START+ADDR+RD CMD * RESTART+ADDR+RD RCOUNT DATA... STOP * * START+ADDR+WR CMD * RESTART+ADDR+WR WCOUNT DATA... STOP * * For I2C - basically, no *COUNT fields, possibly no *CMD field. If the * sender needs to issue a 2-byte command it will incorporate it * into the write buffer and also set NOCMD. * * Generally speaking, the START+ADDR / RESTART+ADDR is handled automatically * by the controller at the beginning of a command sequence or on a data * direction turn-around, and we only need to tell it when to issue the STOP. */ static int smb_transaction(ig4iic_softc_t *sc, char cmd, int op, char *wbuf, int wcount, char *rbuf, int rcount, int *actualp) { int error; int unit; uint32_t last; /* * Debugging - dump registers */ if (ig4_dump) { unit = device_get_unit(sc->dev); if (ig4_dump & (1 << unit)) { ig4_dump &= ~(1 << unit); ig4iic_dump(sc); } } /* * Issue START or RESTART with next data byte, clear any previous * abort condition that may have been holding the txfifo in reset. */ last = IG4_DATA_RESTART; reg_read(sc, IG4_REG_CLR_TX_ABORT); if (actualp) *actualp = 0; /* * Issue command if not told otherwise (smbus). */ if ((op & SMB_TRANS_NOCMD) == 0) { error = wait_status(sc, IG4_STATUS_TX_NOTFULL); if (error) goto done; last |= (u_char)cmd; if (wcount == 0 && rcount == 0 && (op & SMB_TRANS_NOSTOP) == 0) last |= IG4_DATA_STOP; reg_write(sc, IG4_REG_DATA_CMD, last); last = 0; } /* * Clean out any previously received data. */ if (sc->rpos != sc->rnext && (op & SMB_TRANS_NOREPORT) == 0) { device_printf(sc->dev, "discarding %d bytes of spurious data\n", sc->rnext - sc->rpos); } sc->rpos = 0; sc->rnext = 0; /* * If writing and not told otherwise, issue the write count (smbus). */ if (wcount && (op & SMB_TRANS_NOCNT) == 0) { error = wait_status(sc, IG4_STATUS_TX_NOTFULL); if (error) goto done; last |= (u_char)cmd; reg_write(sc, IG4_REG_DATA_CMD, last); last = 0; } /* * Bulk write (i2c) */ while (wcount) { error = wait_status(sc, IG4_STATUS_TX_NOTFULL); if (error) goto done; last |= (u_char)*wbuf; if (wcount == 1 && rcount == 0 && (op & SMB_TRANS_NOSTOP) == 0) last |= IG4_DATA_STOP; reg_write(sc, IG4_REG_DATA_CMD, last); --wcount; ++wbuf; last = 0; } /* * Issue reads to xmit FIFO (strange, I know) to tell the controller * to clock in data. At the moment just issue one read ahead to * pipeline the incoming data. * * NOTE: In the case of NOCMD and wcount == 0 we still issue a * RESTART here, even if the data direction has not changed * from the previous CHAINing call. This we force the RESTART. * (A new START is issued automatically by the controller in * the other nominal cases such as a data direction change or * a previous STOP was issued). * * If this will be the last byte read we must also issue the STOP * at the end of the read. */ if (rcount) { last = IG4_DATA_RESTART | IG4_DATA_COMMAND_RD; if (rcount == 1 && (op & (SMB_TRANS_NOSTOP | SMB_TRANS_NOCNT)) == SMB_TRANS_NOCNT) { last |= IG4_DATA_STOP; } reg_write(sc, IG4_REG_DATA_CMD, last); last = IG4_DATA_COMMAND_RD; } /* * Bulk read (i2c) and count field handling (smbus) */ while (rcount) { /* * Maintain a pipeline by queueing the allowance for the next * read before waiting for the current read. */ if (rcount > 1) { if (op & SMB_TRANS_NOCNT) last = (rcount == 2) ? IG4_DATA_STOP : 0; else last = 0; reg_write(sc, IG4_REG_DATA_CMD, IG4_DATA_COMMAND_RD | last); } error = wait_status(sc, IG4_STATUS_RX_NOTEMPTY); if (error) { if ((op & SMB_TRANS_NOREPORT) == 0) { device_printf(sc->dev, "rx timeout addr 0x%02x\n", sc->last_slave); } goto done; } last = data_read(sc); if (op & SMB_TRANS_NOCNT) { *rbuf = (u_char)last; ++rbuf; --rcount; if (actualp) ++*actualp; } else { /* * Handle count field (smbus), which is not part of * the rcount'ed buffer. The first read data in a * bulk transfer is the count. * * XXX if rcount is loaded as 0 how do I generate a * STOP now without issuing another RD or WR? */ if (rcount > (u_char)last) rcount = (u_char)last; op |= SMB_TRANS_NOCNT; } } error = 0; done: /* XXX wait for xmit buffer to become empty */ last = reg_read(sc, IG4_REG_TX_ABRT_SOURCE); return (error); }
int main() { SetConsoleCP(1251);// установка кодовой страницы win-cp 1251 в поток ввода SetConsoleOutputCP(1251); // установка кодовой страницы win-cp 1251 в поток вывода struct HEADER header; char *in_filename = (char*)malloc(sizeof(char) * 1024); char *out_filename = (char*)malloc(sizeof(char) * 1024); /* ввод имени WAV файла для обработки и имени файла для записи результата */ printf("Enter input filename:\n"); fflush(stdin); gets(in_filename); //scanf("%s", in_filename); printf("Enter output filename:\n"); fflush(stdin); gets(out_filename); //scanf("%s", out_filename); /* открытие файлов для чтения или для записи */ printf("Opening files..\n"); FILE *fin = fopen(in_filename, "rb"); FILE *fout = fopen(out_filename, "wb+"); if (!fin || !fout) { printf("Error!\n"); _getch(); exit(1); } /* чтение заголовка WAV файла */ unsigned int num_samples = wave_header(&header, fin); unsigned int size_of_each_sample = header.block_align; unsigned int sample_rate = header.sample_rate; /* чтение сэмплов из WAV файла, если он имеет ИК кодирование */ if (header.format_type == 1) { // ИК printf("Dump sample data...\n"); int *dump = (int*)calloc(num_samples, sizeof(int)); data_read(size_of_each_sample, dump, num_samples, fin, header); /* ввод частоты "0" и "1" */ unsigned int f0; unsigned int f1; /* printf("Enter f0: \n"); fflush(stdin); scanf("%d", &f0); printf("Enter f1: \n"); fflush(stdin); scanf("%d", &f1); */ f0 = 1300; f1 = 2100; /* демодуляция данных WAV файла */ printf("Sync and Demode sample data...\n"); double time = clock(); int packet_count = receiver(num_samples, dump, sample_rate, f0, f1, fout); printf("Time: %f second\n", (clock() - time) / CLOCKS_PER_SEC); free(dump); /* проверка результата путем сравнения с эталонным выходным файлом */ printf("Check file? Y/N\n"); char c = 'n'; c = _getch(); if (c == 'Y' || c == 'y') { printf("Enter reference filename:\n"); char *check_filename = (char*)malloc(sizeof(char) * 1024); fflush(stdin); gets(check_filename); FILE *fcheck = fopen(check_filename, "rb"); if (!fcheck) { printf("Error!\n"); exit(1); } comparison_files(fout, packet_count, fcheck); fclose(fcheck); free(check_filename); } } printf("Closing files..\n"); fclose(fin); fclose(fout); free(in_filename); free(out_filename); _getch(); return 0; }