bool KPtyDevicePrivate::doWait(int msecs, bool reading) { Q_Q(KPtyDevice); #ifndef __linux__ struct timeval etv; #endif struct timeval tv, *tvp; if (msecs < 0) tvp = nullptr; else { tv.tv_sec = msecs / 1000; tv.tv_usec = (msecs % 1000) * 1000; #ifndef __linux__ gettimeofday(&etv, 0); timeradd(&tv, &etv, &etv); #endif tvp = &tv; } while (reading ? readNotifier->isEnabled() : !writeBuffer.isEmpty()) { fd_set rfds; fd_set wfds; FD_ZERO(&rfds); FD_ZERO(&wfds); if (readNotifier->isEnabled()) FD_SET(q->masterFd(), &rfds); if (!writeBuffer.isEmpty()) FD_SET(q->masterFd(), &wfds); #ifndef __linux__ if (tvp) { gettimeofday(&tv, 0); timersub(&etv, &tv, &tv); if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0; } #endif switch (select(q->masterFd() + 1, &rfds, &wfds, nullptr, tvp)) { case -1: if (errno == EINTR) break; return false; case 0: q->setErrorString(QLatin1String("PTY operation timed out")); return false; default: if (FD_ISSET(q->masterFd(), &rfds)) { bool canRead = _k_canRead(); if (reading && canRead) return true; } if (FD_ISSET(q->masterFd(), &wfds)) { bool canWrite = _k_canWrite(); if (!reading) return canWrite; } break; } } return false; }
int main(int argc, char *argv[]) { int fd; struct stat sb; struct aiocb *aio; char **abuf; const char *fn; int aio_len; int io_size, nrun; off_t file_size, offset; struct aiocb *a; int i, n; struct timeval st, et, rt; float f_rt; iot_t iowhat; if (argc < 6) { printf("Usage: %s <file> <io size> <number of runs> <concurrency> <ro|wo|rw>\n", argv[0]); exit(1); } fn = argv[1]; io_size = atoi(argv[2]); nrun = atoi(argv[3]); aio_len = atoi(argv[4]); if (strcmp(argv[5], "ro") == 0) { iowhat = IOT_READ; } else if (strcmp(argv[5], "rw") == 0) { iowhat = IOT_READ | IOT_WRITE; } else if (strcmp(argv[5], "wo") == 0) { iowhat = IOT_WRITE; } else { fprintf(stderr, "needs to be ro, rw, wo!\n"); exit(1); } /* * Random returns values between 0 and (2^32)-1; only good for 4 gig. * Lets instead treat random() as returning a block offset w/ block size * being "io_size", so we can handle > 4 gig files. */ if (iowhat == IOT_READ) fd = open(fn, O_RDONLY | O_DIRECT); else if (iowhat == IOT_WRITE) fd = open(fn, O_WRONLY | O_DIRECT); else fd = open(fn, O_RDWR | O_DIRECT); if (fd < 0) { perror("open"); exit(1); } if (fstat(fd, &sb) < 0) { perror("fstat"); exit(1); } if (S_ISREG(sb.st_mode)) { file_size = sb.st_size; } else if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) { file_size = disk_getsize(fd); } else { perror("unknown file type\n"); exit(1); } printf("File: %s; File size %jd bytes\n", fn, (intmax_t)file_size); aio = calloc(aio_len, sizeof(struct aiocb)); abuf = calloc(aio_len, sizeof(char *)); for (i = 0; i < aio_len; i++) { abuf[i] = calloc(1, io_size * sizeof(char)); } /* Fill with the initial contents */ gettimeofday(&st, NULL); for (i = 0; i < aio_len; i++) { offset = random() % (file_size / io_size); offset *= io_size; set_aio(aio + i, choose_aio(iowhat), fd, offset, io_size, abuf[i]); } for (i = 0; i < nrun; i++) { aio_waitcomplete(&a, NULL); n = a - aio; assert(n < aio_len); assert(n >= 0); offset = random() % (file_size / io_size); offset *= io_size; set_aio(aio + n, choose_aio(iowhat), fd, offset, io_size, abuf[n]); } gettimeofday(&et, NULL); timersub(&et, &st, &rt); f_rt = ((float) (rt.tv_usec)) / 1000000.0; f_rt += (float) (rt.tv_sec); printf("Runtime: %.2f seconds, ", f_rt); printf("Op rate: %.2f ops/sec, ", ((float) (nrun)) / f_rt); printf("Avg transfer rate: %.2f bytes/sec\n", ((float) (nrun)) * ((float)io_size) / f_rt); exit(0); }
static void *encode_thr_fn(void *data) { ENCODE_CALLBACK_PARAM_T *param = (ENCODE_CALLBACK_PARAM_T *) data; API_VENC_CHN_E eCh = param->eCh; char *str_profile = (tApiInitParam[eCh].eProfile == API_VENC_HEVC_MAIN_PROFILE) ? "Main" : "Main10"; LOG("%p Channel: %d\n", param, eCh); LOG("Profile: %s\n", str_profile); char *str_level; struct timeval tv1, tv2, res; switch (tApiInitParam[eCh].eLevel) { case API_VENC_HEVC_LEVEL_40: { str_level = "L4.0"; break; } case API_VENC_HEVC_LEVEL_41: { str_level = "L4.1"; break; } case API_VENC_HEVC_LEVEL_50: { str_level = "L5.0"; break; } case API_VENC_HEVC_LEVEL_51: { str_level = "L5.1"; break; } default: { break; } } LOG("Level: %s\n", str_level); char *str_tier = (tApiInitParam[eCh].eTier == API_VENC_HEVC_MAIN_TIER) ? "Main Tier" : "High Tier"; LOG("Tier: %s\n", str_tier); char *str_res = "Unknown"; switch (tApiInitParam[eCh].eResolution) { case API_VENC_RESOLUTION_4096x2160: { str_res = RESOLUTION_DCI_4K_TEXT; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropTop = 0; tApiInitParam[eCh].tCrop.u32CropBottom = 0; break; } case API_VENC_RESOLUTION_3840x2160: { str_res = RESOLUTION_4K_TEXT; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropTop = 0; tApiInitParam[eCh].tCrop.u32CropBottom = 0; break; } case API_VENC_RESOLUTION_1920x1080: { str_res = RESOLUTION_2K_TEXT; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropTop = 0; tApiInitParam[eCh].tCrop.u32CropBottom = 8; break; } case API_VENC_RESOLUTION_1280x720: { str_res = RESOLUTION_HD_TEXT; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropTop = 0; tApiInitParam[eCh].tCrop.u32CropBottom = 0; break; } case API_VENC_RESOLUTION_720x576: { str_res = RESOLUTION_SD_576_TEXT; tApiInitParam[eCh].eAspectRatioIdc = API_VENC_HEVC_ASPECT_RATIO_IDC_4; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropTop = 0; tApiInitParam[eCh].tCrop.u32CropBottom = 0; break; } case API_VENC_RESOLUTION_720x480: { str_res = RESOLUTION_SD_480_TEXT; tApiInitParam[eCh].eAspectRatioIdc = API_VENC_HEVC_ASPECT_RATIO_IDC_5; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropLeft = 0; tApiInitParam[eCh].tCrop.u32CropTop = 0; tApiInitParam[eCh].tCrop.u32CropBottom = 0; break; } default: { break; } } LOG("Resolution: %s\n", str_res); char *str_framerate = "Unknown"; switch (tApiInitParam[eCh].eTargetFrameRate) { case API_VENC_FPS_24: { str_framerate = "24p"; break; } case API_VENC_FPS_25: { str_framerate = "25p"; break; } case API_VENC_FPS_29_97: { str_framerate = "29.97p"; break; } case API_VENC_FPS_30: { str_framerate = "30p"; break; } case API_VENC_FPS_50: { str_framerate = "50p"; break; } case API_VENC_FPS_59_94: { str_framerate = "59.94p"; break; } case API_VENC_FPS_60: { str_framerate = "60p"; break; } default: { break; } } LOG("Framerate: %s\n", str_framerate); guint bitrate_val; bitrate_val = gtk_range_get_value(GTK_RANGE(Bitrate[eCh])); LOG("Bitrate %d kbps\n", bitrate_val); tApiInitParam[eCh].u32Bitrate = bitrate_val; char *str_bitdepth = "Unknown"; switch (tApiInitParam[eCh].eBitDepth) { case API_VENC_BIT_DEPTH_8: { str_bitdepth = "8"; break; } case API_VENC_BIT_DEPTH_10: { str_bitdepth = "10"; break; } default: { break; } } LOG("bit depth: %s\n", str_bitdepth); char *str_chroma = (tApiInitParam[eCh].eChromaFmt == API_VENC_CHROMA_FORMAT_420) ? "420" : "422"; LOG("Chroma: %s\n", str_chroma); { GSList *list; GtkToggleButton *button = NULL; API_VENC_IMG_T *pImg = &img[eCh]; list = gtk_radio_button_get_group(GTK_RADIO_BUTTON(PixFmtIntRadioButton[eCh])); while (list) // As long as we didn't reach the end of the group. { button = list->data; // Get one of the buttons in the group. list = list->next; // Next time we're going to check this one. if (gtk_toggle_button_get_active(button)) { break; } } const gchar *val = gtk_button_get_label(GTK_BUTTON(button)); if (strcmp(val, PIXEL_FMT_INTERLEAVE_TEXT) == 0) { switch (tApiInitParam[eCh].eChromaFmt) { case API_VENC_CHROMA_FORMAT_422: { pImg->eFormat = API_VENC_IMAGE_FORMAT_NV16; break; } case API_VENC_CHROMA_FORMAT_420: default: { pImg->eFormat = API_VENC_IMAGE_FORMAT_NV12; break; } } } else if (strcmp(val, PIXEL_FMT_PLANAR_TEXT) == 0) { pImg->eFormat = API_VENC_IMAGE_FORMAT_YUV420; } LOG("%s: %s selected\n", __FUNCTION__, val); } char *str_gop = "Unknown"; switch (tApiInitParam[eCh].eGopType) { case API_VENC_GOP_I: { str_gop = "I"; break; } case API_VENC_GOP_IP: { str_gop = "IP"; break; } case API_VENC_GOP_IB: { str_gop = "IB"; break; } case API_VENC_GOP_IPB: { str_gop = "IPB"; break; } default: { break; } } LOG("GOP: %s\n", str_gop); if (tApiInitParam[eCh].eGopType != API_VENC_GOP_I) { tApiInitParam[eCh].eGopSize = atoi(gtk_entry_get_text(GTK_ENTRY(GopSizeEntry[eCh]))); } LOG("GOP size=%d\n", tApiInitParam[eCh].eGopSize); if (tApiInitParam[eCh].eGopType != API_VENC_GOP_I) { tApiInitParam[eCh].eIDRFrameNum = atoi(gtk_entry_get_text(GTK_ENTRY(IdrIntervalEntry[eCh]))); } LOG("IDR interval=%d\n", tApiInitParam[eCh].eIDRFrameNum); if ((tApiInitParam[eCh].eGopType == API_VENC_GOP_IB) || (tApiInitParam[eCh].eGopType == API_VENC_GOP_IPB)) { guint refnum; refnum = gtk_range_get_value(GTK_RANGE(BNumScale[eCh])); tApiInitParam[eCh].eBFrameNum = (API_VENC_B_FRAME_NUM_E) refnum; LOG("B ref#=%u\n", refnum); } API_VENC_BOARD_E eBoard = API_VENC_BOARD_1; eCh = param->eCh; gettimeofday(&tv1, NULL); if (Api_VENC_Init(eBoard, eCh, &tApiInitParam[eCh])) { sprintf(err_msg, "%s line %d failed!", __FILE__, __LINE__); goto callback_encode_ret; } LOG("HVC_ENC_Init success!\n"); tPopEsArgs[eBoard][eCh].board_num = eBoard; tPopEsArgs[eBoard][eCh].channel = eCh; if (Api_VENC_RegisterCallback ( eBoard, eCh, ui_process_coded_frame, (void *) &tPopEsArgs[eBoard][eCh] )) { sprintf(err_msg, "%s line %d failed!", __FILE__, __LINE__); goto callback_encode_ret; } if (Api_VENC_Start(eBoard, eCh)) { sprintf(err_msg, "%s line %d failed!", __FILE__, __LINE__); goto callback_encode_ret; } LOG("HVC_ENC_Start success!\n"); char es_file_name[FILENAME_MAX]; char timestamp[15]; make_timestamp(timestamp, sizeof(timestamp)); make_output_file_name(timestamp, es_file_name, FILENAME_MAX, FilenameRawYUV[eCh]); fd_r[eCh] = open(FilenameRawYUV[eCh], O_RDONLY); fd_w[eCh] = open(es_file_name, O_WRONLY | O_CREAT, S_IRWXU); // update status bar char msg[256]; sprintf(msg, "Output: %s", es_file_name); context_id = gtk_statusbar_push(GTK_STATUSBAR(statusbar), context_id, msg); uint8_t *vraw_data_buf_p = NULL; uint32_t frame_sz = 0; struct stat file_stat; int remain_frame = 0; fstat(fd_r[eCh], &file_stat); frame_sz = calculate_vraw_enqueue_data_size(&tApiInitParam[eCh]); remain_frame = ((uint64_t) file_stat.st_size / frame_sz); tPopEsArgs[eBoard][eCh].total_frame = remain_frame; tPopEsArgs[eBoard][eCh].poped_frame = 0; vraw_data_buf_p = malloc(frame_sz); API_VENC_IMG_T *pImg = &img[eCh]; while (remain_frame > 0) { read(fd_r[eCh], vraw_data_buf_p, frame_sz); remain_frame--; pImg->pu8Addr = vraw_data_buf_p; pImg->u32Size = frame_sz; pImg->pts = GET_PTS_IN_MS(eCh, tPopEsArgs[eBoard][eCh].total_frame - remain_frame); pImg->bLastFrame = (remain_frame == 0) ? true : false; if (Api_VENC_PushImage(eBoard, eCh, pImg)) { sprintf(err_msg, "Error: %s PushImage failed!\n", __FILE__); goto callback_encode_ret; } } LOG("Encode done...\n"); // try stop while (Api_VENC_Stop(eBoard, eCh)) { usleep(1); } LOG("\n stop complete!\n"); if (Api_VENC_Exit(eBoard, eCh)) { LOG(err_msg, "%s line %d failed!", __FILE__, __LINE__); goto callback_encode_ret; } LOG("\n Encoder exit!\n"); gettimeofday(&tv2, NULL); timersub(&tv2, &tv1, &res); LOG("%lu sec %lu usec\n", res.tv_sec, res.tv_usec); gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progressbar[eCh]), 0.0); close(fd_w[eCh]); callback_encode_ret: LOG("%s\n", err_msg); }
int main( int argc, char ** argv ) { /* getopt_long stores the option index here. */ int option_index = 0; int port = 9999; const char * config_file = NULL; const char * startup_message = ""; int timeout = 60; unsigned width = 512; unsigned height = 64; int no_init = 0; while (1) { const int c = getopt_long( argc, argv, "vp:c:t:W:H:m:n", long_options, &option_index ); if (c == -1) break; switch (c) { case 'v': verbose++; break; case 'n': no_init++; break; case 'c': config_file = optarg; break; case 't': timeout = atoi(optarg); break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'm': startup_message = optarg; break; default: usage(); return -1; } } const int sock = udp_socket(port); if (sock < 0) die("socket port %d failed: %s\n", port, strerror(errno)); const size_t image_size = width * height * 3; const size_t buf_size = (width*height*4)/packets_per_frame + 1; // largest possible UDP packet uint8_t *buf = malloc(buf_size); #if 0 if (sizeof(buf) < image_size + 1) die("%u x %u too large for UDP\n", width, height); #endif fprintf(stderr, "%u x %u, UDP port %u\n", width, height, port); ledscape_config_t * config = &ledscape_matrix_default; if (config_file) { config = ledscape_config(config_file); if (!config) return EXIT_FAILURE; } if (config->type == LEDSCAPE_MATRIX) { config->matrix_config.width = width; config->matrix_config.height = height; } ledscape_t * const leds = ledscape_init(config, no_init); if (!leds) return EXIT_FAILURE; const unsigned report_interval = 10; unsigned last_report = 0; unsigned long delta_sum = 0; unsigned frames = 0; uint32_t * const fb = calloc(width*height,4); ledscape_printf(fb, width, 0xFF0000, "%s", startup_message); ledscape_printf(fb+16*width, width, 0x00FF00, "%dx%d UDP port %d", width, height, port); ledscape_draw(leds, fb); while (1) { int rc = wait_socket(sock, timeout*1000); if (rc < 0) { // something failed memset(fb, 0, width*height*4); ledscape_printf(fb, width, 0xFF0000, "read failed?"); ledscape_draw(leds, fb); exit(EXIT_FAILURE); } if (rc == 0) { // go into timeout mode memset(fb, 0, width*height*4); ledscape_printf(fb, width, 0xFF0000, "timeout"); ledscape_draw(leds, fb); continue; } const ssize_t rlen = recv(sock, buf, buf_size, 0); if (rlen < 0) die("recv failed: %s\n", strerror(errno)); warn_once("received %zu bytes\n", rlen); /* if (buf[0] == 2) { // image type printf("image type: %.*s\n", (int) rlen - 1, &buf[1] ); continue; } if (buf[0] != 1) { // What is it? warn_once("Unknown image type '%c' (%02x)\n", buf[0], buf[0] ); continue; } */ const unsigned frame_part = buf[0]; if (frame_part != 0 && frame_part != 1) { printf("bad type %d\n", frame_part); continue; } if ((size_t) rlen != image_size + 1) { warn_once("WARNING: Received packet %zu bytes, expected %zu\n", rlen, image_size + 1 ); } struct timeval start_tv, stop_tv, delta_tv; gettimeofday(&start_tv, NULL); const unsigned frame_num = 0; // copy the 3-byte values into the 4-byte framebuffer // and turn onto the side for (unsigned x = 0 ; x < width ; x++) // 256 { for (unsigned y = 0 ; y < 32 ; y++) // 64 { uint32_t * out = (void*) &fb[(y+32*frame_part)*width + x]; const uint8_t * const in = &buf[1 + 3*(y*width + x)]; uint32_t r = in[0]; uint32_t g = in[1]; uint32_t b = in[2]; *out = (r << 16) | (g << 8) | (b << 0); } } // only draw after the second frame if (frame_part == 1) ledscape_draw(leds, fb); gettimeofday(&stop_tv, NULL); timersub(&stop_tv, &start_tv, &delta_tv); frames++; delta_sum += delta_tv.tv_usec; if (stop_tv.tv_sec - last_report < report_interval) continue; last_report = stop_tv.tv_sec; const unsigned delta_avg = delta_sum / frames; printf("%6u usec avg, max %.2f fps, actual %.2f fps (over %u frames)\n", delta_avg, report_interval * 1.0e6 / delta_avg, frames * 1.0 / report_interval, frames ); frames = delta_sum = 0; } return 0; }
int main(int argc, char **argv) { #ifndef _WIN32 int c; #endif socklen_t addr_len; struct sockaddr_in local_addr; struct timeval start_time, now, diff_time; int client; uint16_t local_port, remote_port, port, local_udp_port, remote_udp_port; int rcvbufsize=0, sndbufsize=0, myrcvbufsize, mysndbufsize; socklen_t intlen; double seconds; double throughput; int nodelay = 0; struct sctp_assoc_value av; struct sctp_udpencaps encaps; struct sctp_sndinfo sndinfo; #ifdef _WIN32 unsigned long srcAddr; HANDLE tid; #else in_addr_t srcAddr; pthread_t tid; #endif int fragpoint = 0; struct sctp_setadaptation ind = {0}; #ifdef _WIN32 char *opt; int optind; #endif unordered = 0; length = DEFAULT_LENGTH; number_of_messages = DEFAULT_NUMBER_OF_MESSAGES; port = DEFAULT_PORT; remote_udp_port = 0; local_udp_port = 9899; verbose = 0; very_verbose = 0; srcAddr = htonl(INADDR_ANY); memset((void *) &remote_addr, 0, sizeof(struct sockaddr_in)); memset((void *) &local_addr, 0, sizeof(struct sockaddr_in)); #ifndef _WIN32 while ((c = getopt(argc, argv, "a:cp:l:E:f:L:n:R:S:T:uU:vVD")) != -1) switch(c) { case 'a': ind.ssb_adaptation_ind = atoi(optarg); break; case 'c': use_cb = 1; break; case 'l': length = atoi(optarg); break; case 'n': number_of_messages = atoi(optarg); break; case 'p': port = atoi(optarg); break; case 'E': local_udp_port = atoi(optarg); break; case 'f': fragpoint = atoi(optarg); break; case 'L': inet_pton(AF_INET, optarg, &srcAddr); break; case 'R': rcvbufsize = atoi(optarg); break; case 'S': sndbufsize = atoi(optarg); break; case 'T': runtime = atoi(optarg); number_of_messages = 0; break; case 'u': unordered = 1; break; case 'U': remote_udp_port = atoi(optarg); break; case 'v': verbose = 1; break; case 'V': verbose = 1; very_verbose = 1; break; case 'D': nodelay = 1; break; default: fprintf(stderr, "%s", Usage); exit(1); } #else for (optind = 1; optind < argc; optind++) { if (argv[optind][0] == '-') { switch (argv[optind][1]) { case 'a': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; ind.ssb_adaptation_ind = atoi(opt); break; case 'c': use_cb = 1; break; case 'l': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; length = atoi(opt); break; case 'p': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; port = atoi(opt); break; case 'n': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; number_of_messages = atoi(opt); break; case 'f': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; fragpoint = atoi(opt); break; case 'L': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; inet_pton(AF_INET, opt, &srcAddr); break; case 'U': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; remote_udp_port = atoi(opt); break; case 'E': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; local_udp_port = atoi(opt); break; case 'R': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; rcvbufsize = atoi(opt); break; case 'S': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; sndbufsize = atoi(opt); break; case 'T': if (++optind >= argc) { printf("%s", Usage); exit(1); } opt = argv[optind]; runtime = atoi(opt); number_of_messages = 0; break; case 'u': unordered = 1; break; case 'v': verbose = 1; break; case 'V': verbose = 1; very_verbose = 1; break; case 'D': nodelay = 1; break; default: printf("%s", Usage); exit(1); } } else { break; } } #endif if (optind == argc) { client = 0; local_port = port; remote_port = 0; } else { client = 1; local_port = 0; remote_port = port; } local_addr.sin_family = AF_INET; #ifdef HAVE_SIN_LEN local_addr.sin_len = sizeof(struct sockaddr_in); #endif local_addr.sin_port = htons(local_port); local_addr.sin_addr.s_addr = srcAddr; usrsctp_init(local_udp_port, NULL, debug_printf); #ifdef SCTP_DEBUG usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL); #endif usrsctp_sysctl_set_sctp_blackhole(2); usrsctp_sysctl_set_sctp_enable_sack_immediately(1); if (client) { if (use_cb) { if (!(psock = usrsctp_socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP, client_receive_cb, send_cb, length, NULL))) { perror("user_socket"); exit(1); } } else { if (!(psock = usrsctp_socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP, NULL, NULL, 0, NULL))) { perror("user_socket"); exit(1); } } } else { if (use_cb) { if (!(psock = usrsctp_socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP, server_receive_cb, NULL, 0, NULL))) { perror("user_socket"); exit(1); } } else { if (!(psock = usrsctp_socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP, NULL, NULL, 0, NULL))) { perror("user_socket"); exit(1); } } } if (usrsctp_bind(psock, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in)) == -1) { perror("usrsctp_bind"); exit(1); } if (usrsctp_setsockopt(psock, IPPROTO_SCTP, SCTP_ADAPTATION_LAYER, (const void*)&ind, (socklen_t)sizeof(struct sctp_setadaptation)) < 0) { perror("setsockopt"); } if (!client) { if (rcvbufsize) { if (usrsctp_setsockopt(psock, SOL_SOCKET, SO_RCVBUF, &rcvbufsize, sizeof(int)) < 0) { perror("setsockopt: rcvbuf"); } } if (verbose) { intlen = sizeof(int); if (usrsctp_getsockopt(psock, SOL_SOCKET, SO_RCVBUF, &myrcvbufsize, (socklen_t *)&intlen) < 0) { perror("getsockopt: rcvbuf"); } else { fprintf(stdout,"Receive buffer size: %d.\n", myrcvbufsize); } } if (usrsctp_listen(psock, 1) < 0) { perror("usrsctp_listen"); exit(1); } while (1) { memset(&remote_addr, 0, sizeof(struct sockaddr_in)); addr_len = sizeof(struct sockaddr_in); if (use_cb) { struct socket *conn_sock; if ((conn_sock = usrsctp_accept(psock, (struct sockaddr *) &remote_addr, &addr_len))== NULL) { perror("usrsctp_accept"); continue; } } else { struct socket **conn_sock; conn_sock = (struct socket **)malloc(sizeof(struct socket *)); if ((*conn_sock = usrsctp_accept(psock, (struct sockaddr *) &remote_addr, &addr_len))== NULL) { perror("usrsctp_accept"); continue; } #ifdef _WIN32 tid = CreateThread(NULL, 0, &handle_connection, (void *)conn_sock, 0, NULL); #else pthread_create(&tid, NULL, &handle_connection, (void *)conn_sock); #endif } if (verbose) { // const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) //inet_ntoa(remote_addr.sin_addr) char addrbuf[INET_ADDRSTRLEN]; printf("Connection accepted from %s:%d\n", inet_ntop(AF_INET, &(remote_addr.sin_addr), addrbuf, INET_ADDRSTRLEN), ntohs(remote_addr.sin_port)); } } usrsctp_close(psock); } else { memset(&encaps, 0, sizeof(struct sctp_udpencaps)); encaps.sue_address.ss_family = AF_INET; encaps.sue_port = htons(remote_udp_port); if (usrsctp_setsockopt(psock, IPPROTO_SCTP, SCTP_REMOTE_UDP_ENCAPS_PORT, (const void*)&encaps, (socklen_t)sizeof(struct sctp_udpencaps)) < 0) { perror("setsockopt"); } remote_addr.sin_family = AF_INET; #ifdef HAVE_SIN_LEN remote_addr.sin_len = sizeof(struct sockaddr_in); #endif if (!inet_pton(AF_INET, argv[optind], &remote_addr.sin_addr.s_addr)){ printf("error: invalid destination address\n"); exit(1); } remote_addr.sin_port = htons(remote_port); /* TODO fragpoint stuff */ if (nodelay == 1) { optval = 1; } else { optval = 0; } usrsctp_setsockopt(psock, IPPROTO_SCTP, SCTP_NODELAY, &optval, sizeof(int)); if (fragpoint) { av.assoc_id = 0; av.assoc_value = fragpoint; if (usrsctp_setsockopt(psock, IPPROTO_SCTP, SCTP_MAXSEG, &av, sizeof(struct sctp_assoc_value)) < 0) { perror("setsockopt: SCTP_MAXSEG"); } } if (sndbufsize) { if (usrsctp_setsockopt(psock, SOL_SOCKET, SO_SNDBUF, &sndbufsize, sizeof(int)) < 0) { perror("setsockopt: sndbuf"); } } if (verbose) { intlen = sizeof(int); if (usrsctp_getsockopt(psock, SOL_SOCKET, SO_SNDBUF, &mysndbufsize, (socklen_t *)&intlen) < 0) { perror("setsockopt: SO_SNDBUF"); } else { fprintf(stdout,"Send buffer size: %d.\n", mysndbufsize); } } buffer = malloc(length); memset(buffer, 'b', length); if (usrsctp_connect(psock, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr_in)) == -1 ) { perror("usrsctp_connect"); exit(1); } gettimeofday(&start_time, NULL); done = 0; if (runtime > 0) { #ifndef _WIN32 signal(SIGALRM, stop_sender); alarm(runtime); #else printf("You cannot set the runtime in Windows yet\n"); exit(-1); #endif } if (use_cb) { while (done < 2 && (messages < (number_of_messages - 1))) { #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } } else { sndinfo.snd_sid = 0; sndinfo.snd_flags = 0; if (unordered != 0) { sndinfo.snd_flags |= SCTP_UNORDERED; } sndinfo.snd_ppid = 0; sndinfo.snd_context = 0; sndinfo.snd_assoc_id = 0; if (verbose) { printf("Start sending "); if (number_of_messages > 0) { printf("%ld messages ", (long)number_of_messages); } if (runtime > 0) { printf("for %u seconds ...", runtime); } printf("\n"); fflush(stdout); } while (!done && ((number_of_messages == 0) || (messages < (number_of_messages - 1)))) { if (very_verbose) { printf("Sending message number %lu.\n", messages + 1); } if (usrsctp_sendv(psock, buffer, length, (struct sockaddr *) &remote_addr, 1, (void *)&sndinfo, (socklen_t)sizeof(struct sctp_sndinfo), SCTP_SENDV_SNDINFO, 0) < 0) { perror("usrsctp_sendv"); exit(1); } messages++; } if (very_verbose) { printf("Sending message number %lu.\n", messages + 1); } sndinfo.snd_flags |= SCTP_EOF; if (usrsctp_sendv(psock, buffer, length, (struct sockaddr *) &remote_addr, 1, (void *)&sndinfo, (socklen_t)sizeof(struct sctp_sndinfo), SCTP_SENDV_SNDINFO, 0) < 0) { perror("usrsctp_sendv"); exit(1); } messages++; } free (buffer); if (verbose) { printf("Closing socket.\n"); } usrsctp_close(psock); gettimeofday(&now, NULL); timersub(&now, &start_time, &diff_time); seconds = diff_time.tv_sec + (double)diff_time.tv_usec/1000000; printf("%s of %ld messages of length %u took %f seconds.\n", "Sending", messages, length, seconds); throughput = (double)messages * (double)length / seconds; printf("Throughput was %f Byte/sec.\n", throughput); } while (usrsctp_finish() != 0) { #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } return 0; }
void threat_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename) { #ifdef OPENCV float threat = 0; float roll = .2; printf("Classifier Demo\n"); network net = parse_network_cfg(cfgfile); if(weightfile){ load_weights(&net, weightfile); } set_batch_network(&net, 1); list *options = read_data_cfg(datacfg); srand(2222222); CvCapture * cap; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } int top = option_find_int(options, "top", 1); char *name_list = option_find_str(options, "names", 0); char **names = get_labels(name_list); int *indexes = calloc(top, sizeof(int)); if(!cap) error("Couldn't connect to webcam.\n"); //cvNamedWindow("Threat", CV_WINDOW_NORMAL); //cvResizeWindow("Threat", 512, 512); float fps = 0; int i; int count = 0; while(1){ ++count; struct timeval tval_before, tval_after, tval_result; gettimeofday(&tval_before, NULL); image in = get_image_from_stream(cap); if(!in.data) break; image in_s = resize_image(in, net.w, net.h); image out = in; int x1 = out.w / 20; int y1 = out.h / 20; int x2 = 2*x1; int y2 = out.h - out.h/20; int border = .01*out.h; int h = y2 - y1 - 2*border; int w = x2 - x1 - 2*border; float *predictions = network_predict(net, in_s.data); float curr_threat = 0; if(1){ curr_threat = predictions[0] * 0 + predictions[1] * .6 + predictions[2]; } else { curr_threat = predictions[218] + predictions[539] + predictions[540] + predictions[368] + predictions[369] + predictions[370]; } threat = roll * curr_threat + (1-roll) * threat; draw_box_width(out, x2 + border, y1 + .02*h, x2 + .5 * w, y1 + .02*h + border, border, 0,0,0); if(threat > .97) { draw_box_width(out, x2 + .5 * w + border, y1 + .02*h - 2*border, x2 + .5 * w + 6*border, y1 + .02*h + 3*border, 3*border, 1,0,0); } draw_box_width(out, x2 + .5 * w + border, y1 + .02*h - 2*border, x2 + .5 * w + 6*border, y1 + .02*h + 3*border, .5*border, 0,0,0); draw_box_width(out, x2 + border, y1 + .42*h, x2 + .5 * w, y1 + .42*h + border, border, 0,0,0); if(threat > .57) { draw_box_width(out, x2 + .5 * w + border, y1 + .42*h - 2*border, x2 + .5 * w + 6*border, y1 + .42*h + 3*border, 3*border, 1,1,0); } draw_box_width(out, x2 + .5 * w + border, y1 + .42*h - 2*border, x2 + .5 * w + 6*border, y1 + .42*h + 3*border, .5*border, 0,0,0); draw_box_width(out, x1, y1, x2, y2, border, 0,0,0); for(i = 0; i < threat * h ; ++i){ float ratio = (float) i / h; float r = (ratio < .5) ? (2*(ratio)) : 1; float g = (ratio < .5) ? 1 : 1 - 2*(ratio - .5); draw_box_width(out, x1 + border, y2 - border - i, x2 - border, y2 - border - i, 1, r, g, 0); } top_predictions(net, top, indexes); char buff[256]; sprintf(buff, "/home/pjreddie/tmp/threat_%06d", count); //save_image(out, buff); printf("\033[2J"); printf("\033[1;1H"); printf("\nFPS:%.0f\n",fps); for(i = 0; i < top; ++i){ int index = indexes[i]; printf("%.1f%%: %s\n", predictions[index]*100, names[index]); } if(1){ show_image(out, "Threat"); cvWaitKey(10); } free_image(in_s); free_image(in); gettimeofday(&tval_after, NULL); timersub(&tval_after, &tval_before, &tval_result); float curr = 1000000.f/((long int)tval_result.tv_usec); fps = .9*fps + .1*curr; } #endif }
int main(int argc, char *argv[]) { int c, error, s, verbose, s2, kfd; int xmitset, family; int bufsize; int ai_flag; char *host; const char *portstr; struct kttcp_io_args kio; struct addrinfo hints, *addr, *res; struct sockaddr_storage ss; struct rusage rustart, ruend; struct timeval tvtmp; unsigned long long ull, usecs, bytespersec, bitspersec, xmitsize; char connecthost[NI_MAXHOST]; socklen_t slen; const int one = 1; u_long cmd; cmd = 0; portstr = KTTCP_PORT; verbose = 1; xmitset = 0; bufsize = KTTCP_SOCKBUF_DEFAULT; xmitsize = KTTCP_XMITSIZE; family = PF_UNSPEC; while ((c = getopt(argc, argv, "46b:n:p:qrtvw:")) != -1) { switch (c) { case '4': if (family != PF_UNSPEC) usage(); family = PF_INET; break; case '6': if (family != PF_UNSPEC) usage(); family = PF_INET6; break; case 'b': ull = get_bytes(optarg); if (ull > INT_MAX) errx(1, "invalid socket buffer size: %s\n", optarg); bufsize = ull; break; case 'n': xmitsize = get_bytes(optarg); if (xmitsize > KTTCP_MAX_XMIT) xmitsize = KTTCP_MAX_XMIT; xmitset = 1; break; case 'p': portstr = optarg; break; case 'q': verbose = 0; break; case 'r': if (cmd != 0) usage(); cmd = KTTCP_IO_RECV; break; case 't': if (cmd != 0) usage(); cmd = KTTCP_IO_SEND; break; case 'v': verbose = 2; break; case '?': default: usage(); } } if (cmd == 0) usage(); argc -= optind; argv += optind; if (cmd == KTTCP_IO_SEND) { if (xmitsize <= 0 || argc < 1) usage(); host = argv[0]; ai_flag = 0; } else { if (xmitset == 0) xmitsize = KTTCP_MAX_XMIT; host = NULL; ai_flag = AI_PASSIVE; } if ((kfd = open(KTTCP_DEVICE, O_RDWR, 666)) == -1) err(2, "open %s", KTTCP_DEVICE); memset(&hints, 0, sizeof hints); hints.ai_flags = ai_flag; hints.ai_socktype = SOCK_STREAM; hints.ai_family = family; error = getaddrinfo(host, portstr, &hints, &addr); if (error != 0) errx(2, "%s", gai_strerror(error)); s = -1; for (res = addr; res != NULL; res = res->ai_next) { s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (s >= 0) break; } if (res == NULL) err(2, "can't create socket"); printf("kttcp: socket buffer size: %d\n", bufsize); if (cmd == KTTCP_IO_SEND) { if (connect(s, res->ai_addr, res->ai_addrlen) < 0) err(2, "connect"); if (verbose) { getnameinfo(res->ai_addr, res->ai_addrlen, connecthost, sizeof connecthost, NULL, 0, NI_NUMERICHOST); printf("kttcp: connected to %s\n", connecthost); } if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof (int)) < 0) err(2, "setsockopt sndbuf"); kio.kio_socket = s; } else { if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (int)) < 0) err(2, "setsockopt reuseaddr"); if (bind(s, res->ai_addr, res->ai_addrlen) < 0) err(2, "bind"); if (listen(s, 1) < 0) err(2, "listen"); if (verbose) printf("kttcp: listening on port %s\n", portstr); slen = sizeof ss; s2 = accept(s, (struct sockaddr *)&ss, &slen); if (s2 < 0) err(2, "accept"); if (verbose) { getnameinfo((struct sockaddr *)&ss, ss.ss_len, connecthost, sizeof connecthost, NULL, 0, NI_NUMERICHOST); printf("kttcp: connect from %s\n", connecthost); } if (setsockopt(s2, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof (int)) < 0) err(2, "setsockopt rcvbuf"); kio.kio_socket = s2; } kio.kio_totalsize = xmitsize; getrusage(RUSAGE_SELF, &rustart); if (ioctl(kfd, cmd, &kio) == -1) err(2, "kttcp i/o command"); getrusage(RUSAGE_SELF, &ruend); usecs = (unsigned long long)kio.kio_elapsed.tv_sec * 1000000; usecs += kio.kio_elapsed.tv_usec; bytespersec = kio.kio_bytesdone * 1000000LL / usecs; bitspersec = bytespersec * NBBY; printf("kttcp: %llu bytes in %jd.%03jd real seconds " "==> %llu bytes/sec\n", kio.kio_bytesdone, (intmax_t)kio.kio_elapsed.tv_sec, (intmax_t)kio.kio_elapsed.tv_usec / 1000, bytespersec); if (verbose > 1) { timersub(&ruend.ru_stime, &rustart.ru_stime, &tvtmp); bytespersec = kio.kio_bytesdone * 1000000LL / (tvtmp.tv_sec * 1000000ULL + tvtmp.tv_usec); printf("kttcp: %llu bytes in %jd.%03jd CPU seconds " "==> %llu bytes/CPU sec\n", kio.kio_bytesdone, (intmax_t)tvtmp.tv_sec, (intmax_t)tvtmp.tv_usec / 1000, bytespersec); } printf(" %g (%g) Megabits/sec\n", ((double) bitspersec / 1024.0) / 1024.0, ((double) bitspersec / 1000.0) / 1000.0); timersub(&ruend.ru_utime, &rustart.ru_utime, &tvtmp); /* XXX * sometimes, this ends up as -1 * hz!? */ if (tvtmp.tv_sec < 0) tvtmp.tv_sec = tvtmp.tv_usec = 0; printf(" %jd.%02jduser", (intmax_t)tvtmp.tv_sec, (intmax_t)tvtmp.tv_usec / 10000); ull = tvtmp.tv_sec * 1000000ULL + tvtmp.tv_usec; timersub(&ruend.ru_stime, &rustart.ru_stime, &tvtmp); printf(" %jd.%02jdsys", (intmax_t)tvtmp.tv_sec, (intmax_t)tvtmp.tv_usec / 10000); ull += tvtmp.tv_sec * 1000000ULL + tvtmp.tv_usec; printf(" %lld.%lldreal", usecs / 1000000, (usecs % 1000000) / 10000); printf(" %lld%%", ull * 100 / usecs); printf("\n"); close(kio.kio_socket); if (cmd == KTTCP_IO_RECV) close(s); close(kfd); freeaddrinfo(addr); return 0; }
/* * Send the current request, after encrypting it. Returns 0 on success, * or -1 on failure. */ static int send_msg(struct tac_handle *h) { struct timeval deadline; struct tac_msg *msg; char *ptr; int len; if (h->last_seq_no & 1) { generr(h, "Attempt to send message out of sequence"); return -1; } if (establish_connection(h) == -1) return -1; msg = &h->request; msg->seq_no = ++h->last_seq_no; if (msg->seq_no == 1) gen_session_id(msg); crypt_msg(h, msg); if (h->single_connect) msg->flags |= TAC_SINGLE_CONNECT; else msg->flags &= ~TAC_SINGLE_CONNECT; gettimeofday(&deadline, NULL); deadline.tv_sec += h->servers[h->cur_server].timeout; len = HDRSIZE + ntohl(msg->length); ptr = (char *)msg; while (len > 0) { int n; n = write(h->fd, ptr, len); if (n == -1) { struct timeval tv; int nfds; if (errno != EAGAIN) { generr(h, "Network write error: %s", strerror(errno)); return -1; } /* Wait until we can write more data. */ gettimeofday(&tv, NULL); timersub(&deadline, &tv, &tv); if (tv.tv_sec >= 0) { fd_set wfds; FD_ZERO(&wfds); FD_SET(h->fd, &wfds); nfds = select(h->fd + 1, NULL, &wfds, NULL, &tv); if (nfds == -1) { generr(h, "select: %s", strerror(errno)); return -1; } } else nfds = 0; if (nfds == 0) { generr(h, "Network write timed out"); return -1; } } else { ptr += n; len -= n; } } return 0; }
static PI_THREAD (softServoThread) { register int i, j, k, m, tmp ; int lastDelay, pin, servo ; int myDelays [MAX_SERVOS] ; int myPins [MAX_SERVOS] ; struct timeval tNow, tStart, tPeriod, tGap, tTotal ; struct timespec tNs ; tTotal.tv_sec = 0 ; tTotal.tv_usec = 8000 ; piHiPri (50) ; for (;;) { gettimeofday (&tStart, NULL) ; memcpy (myDelays, pulseWidth, sizeof (myDelays)) ; memcpy (myPins, pinMap, sizeof (myPins)) ; // Sort the delays (& pins), shortest first for (m = MAX_SERVOS / 2 ; m > 0 ; m /= 2 ) for (j = m ; j < MAX_SERVOS ; ++j) for (i = j - m ; i >= 0 ; i -= m) { k = i + m ; if (myDelays [k] >= myDelays [i]) break ; else // Swap { tmp = myDelays [i] ; myDelays [i] = myDelays [k] ; myDelays [k] = tmp ; tmp = myPins [i] ; myPins [i] = myPins [k] ; myPins [k] = tmp ; } } // All on lastDelay = 0 ; for (servo = 0 ; servo < MAX_SERVOS ; ++servo) { if ((pin = myPins [servo]) == -1) continue ; digitalWrite (pin, HIGH) ; myDelays [servo] = myDelays [servo] - lastDelay ; lastDelay += myDelays [servo] ; } // Now loop, turning them all off as required for (servo = 0 ; servo < MAX_SERVOS ; ++servo) { if ((pin = myPins [servo]) == -1) continue ; delayMicroseconds (myDelays [servo]) ; digitalWrite (pin, LOW) ; } // Wait until the end of an 8mS time-slot gettimeofday (&tNow, NULL) ; timersub (&tNow, &tStart, &tPeriod) ; timersub (&tTotal, &tPeriod, &tGap) ; tNs.tv_sec = tGap.tv_sec ; tNs.tv_nsec = tGap.tv_usec * 1000 ; nanosleep (&tNs, NULL) ; } return NULL ; }
int time_elapsed_with_signal(void) { struct timespec ts, rts; struct timeval stv, etv; pid_t pid; int status; signal(SIGUSR1, sighandler); pid = getpid(); switch(fork()) { case -1: err(1, "fork"); default: ts.tv_sec = 1; ts.tv_nsec = 0; nanosleep(&ts, NULL); kill(pid, SIGUSR1); exit(0); } ts.tv_sec = 10; ts.tv_nsec = 0; rts.tv_sec = 0; rts.tv_nsec = 0; if (gettimeofday(&stv, NULL) < 0) { warn("gettimeofday"); return 1; } if (nanosleep(&ts, &rts) == 0) { warnx("nanosleep"); return 1; } if (gettimeofday(&etv, NULL) < 0) { warn("gettimeofday"); return 1; } timersub(&etv, &stv, &stv); etv.tv_sec = rts.tv_sec; etv.tv_usec = rts.tv_nsec / 1000 + 1; /* the '+ 1' is a "roundup" */ timeradd(&etv, &stv, &stv); if (stv.tv_sec < 10) { warnx("slept time + leftover time < 10 sec"); return 1; } if (wait(&status) < 0) err(1, "wait"); return 0; }
void puffsdump_req(struct puffs_req *preq) { static struct timeval tv_prev; struct timeval tv_now, tv; const char **map; int isvn = 0; map = NULL; /* yes, we are all interested in your opinion, gcc */ switch (PUFFSOP_OPCLASS(preq->preq_opclass)) { case PUFFSOP_VFS: map = vfsop_revmap; break; case PUFFSOP_VN: map = vnop_revmap; isvn = 1; break; case PUFFSOP_CACHE: map = cacheop_revmap; break; case PUFFSOP_ERROR: map = errnot_revmap; break; case PUFFSOP_FLUSH: map = flush_revmap; break; } printf("\treqid: %" PRIu64 ", opclass %d%s, optype: %s, " "cookie: %p,\n\t\taux: %p, auxlen: %zu, pid: %d, lwpid: %d\n", preq->preq_id, PUFFSOP_OPCLASS(preq->preq_opclass), PUFFSOP_WANTREPLY(preq->preq_opclass) ? "" : " (FAF)", map[preq->preq_optype], preq->preq_cookie, preq->preq_buf, preq->preq_buflen, preq->preq_pid, preq->preq_lid); if (isvn) { switch (preq->preq_optype) { case PUFFS_VN_LOOKUP: puffsdump_lookup(preq); break; case PUFFS_VN_READ: case PUFFS_VN_WRITE: puffsdump_readwrite(preq); break; case PUFFS_VN_OPEN: puffsdump_open(preq); break; case PUFFS_VN_REMOVE: case PUFFS_VN_RMDIR: case PUFFS_VN_LINK: puffsdump_targ(preq); break; case PUFFS_VN_READDIR: puffsdump_readdir(preq); break; default: break; } } PU_LOCK(); gettimeofday(&tv_now, NULL); timersub(&tv_now, &tv_prev, &tv); printf("\t\tsince previous call: %lld.%06ld\n", (long long)tv.tv_sec, (long)tv.tv_usec); gettimeofday(&tv_prev, NULL); PU_UNLOCK(); }
/** * Monitor thread for each packet slinger. Takes data from the priority-ordered skip list and places it into a * packetized FIFO queue * @param m_arg Pointer to the link state structure */ void *slinger_monitor(void *m_arg) { int32_t increment; slinger_dl_node_t *dl_node = NULL; slinger_fifo_node_t *temp_packet = NULL; slinger_link_state_t *link = (slinger_link_state_t *)m_arg; struct timeval last_downlink; struct timeval delta_t; struct timeval current_time; size_t level; size_t loops_to_clear = SLINGER_LOOPS_TO_CLEAR; if (!(temp_packet = balloc(err, sizeof(slinger_fifo_node_t) + SLINGER_MAX_SMALL_PAYLOAD_SIZE + 2 * sizeof(uint32_t)))) { blast_tfatal("Could not create temporary packet"); return NULL; } e_memset(temp_packet, 0, sizeof(slinger_fifo_node_t) + SLINGER_MAX_SMALL_PAYLOAD_SIZE + sizeof(uint32_t)); gettimeofday(¤t_time, NULL); timersub(¤t_time, &slinger_sleep_us, &last_downlink); blast_startup("Started Packet Slinger monitor thread"); while(link->is_active) { gettimeofday(¤t_time, NULL); timersub(¤t_time, &last_downlink, &delta_t); last_downlink.tv_sec = current_time.tv_sec; last_downlink.tv_usec = current_time.tv_usec; if (link->bytes_to_write <= 0) { increment = (uint64_t)link->bps * delta_t.tv_usec / 8000000; ADD_TO(link->bytes_to_write, increment); link->bytes_to_write = min_safe(link->bytes_to_write, increment); } if ( (link->bytes_to_write > 0) && (dl_node = dequeue_pq(link->downlink_pq, &level)) ) { if ((float)level > link->max_priority) link->max_priority = (float)level; if (!dl_node->data) { if (!slinger_compress_node(dl_node)) { blast_warn("Could not compress node of length %zu", dl_node->size); slinger_free_dl_node(dl_node); continue; } } /** * Assign the packet data header type to be the dl_node type's * bottom three bits. This is hacky but used to quickly implement * a mandated LOS change */ dl_node->data->type = (dl_node->type & 0b111); /** * Process the highest-priority node in the skip list. Small packets get lumped together to * save overhead. Larger packets are sent individually. */ if (dl_node->size < SLINGER_MAX_SEGMENT_SIZE && dl_node->data->type == BLAST_PORT_DEF_DATA) { slinger_packetize_small(dl_node, temp_packet, link); } else if (dl_node->size < SLINGER_MAX_PAYLOAD_SIZE) { slinger_packetize_normal(dl_node, link); } else { blast_err("Packet size %zu larger than maximum downlink size %u", dl_node->size, SLINGER_MAX_PAYLOAD_SIZE); } slinger_free_dl_node(dl_node); } if (!dl_node || link->bytes_to_write <= 0) { if (!dl_node) { link->max_priority = min(link->max_priority + 1., (float)SLINGER_MAX_PRIORITY); } else if (link->max_priority > (float)level) { link->max_priority = link->max_priority - SLINGER_PRIORITY_ADJUST_RATE * (link->max_priority - (float)level); } if (!loops_to_clear--) { clear_levels_pq(link->downlink_pq, ceilf(link->max_priority), slinger_free_dl_node); loops_to_clear = SLINGER_LOOPS_TO_CLEAR; } usleep(slinger_sleep_us.tv_usec); } }; blast_info("Stopped Packet Slinger monitor thread"); BLAST_SAFE_FREE(temp_packet); clear_levels_pq(link->downlink_pq, 0, slinger_free_dl_node); return NULL; }
int vg_output_timing(vg_context_t *vcp, int cycle, struct timeval *last) { pthread_t me; struct timeval tvnow, tv; timing_info_t *tip, *mytip; unsigned long long rate, myrate = 0, mytime, total, sincelast; int p, i; /* Compute the rate */ gettimeofday(&tvnow, NULL); timersub(&tvnow, last, &tv); memcpy(last, &tvnow, sizeof(*last)); mytime = tv.tv_usec + (1000000ULL * tv.tv_sec); if (!mytime) mytime = 1; rate = 0; pthread_mutex_lock(&timing_mutex); me = pthread_self(); for (tip = vcp->vc_timing_head, mytip = NULL; tip != NULL; tip = tip->ti_next) { if (pthread_equal(tip->ti_thread, me)) { mytip = tip; p = ((tip->ti_hist_last + 1) % timing_hist_size); tip->ti_hist_time[p] = mytime; tip->ti_hist_work[p] = cycle; tip->ti_hist_last = p; mytime = 0; myrate = 0; for (i = 0; i < timing_hist_size; i++) { mytime += tip->ti_hist_time[i]; myrate += tip->ti_hist_work[i]; } myrate = (myrate * 1000000) / mytime; tip->ti_last_rate = myrate; rate += myrate; } else rate += tip->ti_last_rate; } if (!mytip) { mytip = (timing_info_t *) malloc(sizeof(*tip)); mytip->ti_next = vcp->vc_timing_head; mytip->ti_thread = me; vcp->vc_timing_head = mytip; mytip->ti_hist_last = 0; mytip->ti_hist_time[0] = mytime; mytip->ti_hist_work[0] = cycle; for (i = 1; i < timing_hist_size; i++) { mytip->ti_hist_time[i] = 1; mytip->ti_hist_work[i] = 0; } myrate = ((unsigned long long)cycle * 1000000) / mytime; mytip->ti_last_rate = myrate; rate += myrate; } vcp->vc_timing_total += cycle; if (vcp->vc_timing_prevfound != vcp->vc_found) { vcp->vc_timing_prevfound = vcp->vc_found; vcp->vc_timing_sincelast = 0; } vcp->vc_timing_sincelast += cycle; if (mytip != vcp->vc_timing_head) { pthread_mutex_unlock(&timing_mutex); return myrate; } total = vcp->vc_timing_total; sincelast = vcp->vc_timing_sincelast; pthread_mutex_unlock(&timing_mutex); vcp->vc_output_timing(vcp, sincelast, rate, total); return myrate; }
d_define_method(particle, update)(struct s_object *self, unsigned int max_particles) { d_using(particle); unsigned int index; struct timeval current, elapsed_begin, elapsed_update; struct s_drawable_attributes *drawable_attributes_self = d_cast(self, drawable); double local_position_x, local_position_y, real_elapsed_begin, real_elapsed_update, radians, speed_x, speed_y; unsigned int generated = 0; gettimeofday(¤t, NULL); d_call(&(drawable_attributes_self->point_destination), m_point_get, (double *)&local_position_x, (double *)&local_position_y); for (index = 0; index < particle_attributes->configuration.particles; ++index) { if (particle_attributes->particles[index].alive) { timersub(¤t, &(particle_attributes->particles[index].born), &elapsed_begin); real_elapsed_begin = elapsed_begin.tv_sec + ((double)(elapsed_begin.tv_usec) / 1000000.0); if (particle_attributes->particles[index].core.lifetime > real_elapsed_begin) { timersub(¤t, &(particle_attributes->particles[index].update), &elapsed_update); real_elapsed_update = elapsed_update.tv_sec + ((double)(elapsed_update.tv_usec) / 1000000.0); particle_attributes->particles[index].core.mask_R += (particle_attributes->particles[index].core.speed_R * real_elapsed_update); particle_attributes->particles[index].core.mask_G += (particle_attributes->particles[index].core.speed_G * real_elapsed_update); particle_attributes->particles[index].core.mask_B += (particle_attributes->particles[index].core.speed_B * real_elapsed_update); particle_attributes->particles[index].core.mask_A += (particle_attributes->particles[index].core.speed_A * real_elapsed_update); d_particle_apply_limits(particle_attributes->particles[index].core.mask_R, 0, 255); d_particle_apply_limits(particle_attributes->particles[index].core.mask_G, 0, 255); d_particle_apply_limits(particle_attributes->particles[index].core.mask_B, 0, 255); d_particle_apply_limits(particle_attributes->particles[index].core.mask_A, 0, 255); particle_attributes->particles[index].core.zoom += (particle_attributes->particles[index].core.speed_zoom * real_elapsed_update); particle_attributes->particles[index].core.angle += (particle_attributes->particles[index].core.speed_angle * real_elapsed_update); particle_attributes->particles[index].core.direction_angle += (particle_attributes->particles[index].core.speed_direction_angle * real_elapsed_update); radians = (particle_attributes->particles[index].core.direction_angle * d_math_pi) / 180.0; speed_x = particle_attributes->particles[index].core.speed_linear * cos(radians); speed_y = particle_attributes->particles[index].core.speed_linear * sin(radians); speed_x += (particle_attributes->particles[index].core.gravity_x * real_elapsed_begin); speed_y += (particle_attributes->particles[index].core.gravity_y * real_elapsed_begin); particle_attributes->particles[index].core.position_x += (speed_x * real_elapsed_update); particle_attributes->particles[index].core.position_y += (speed_y * real_elapsed_update); memcpy(&(particle_attributes->particles[index].update), ¤t, sizeof(struct timeval)); } else particle_attributes->particles[index].alive = d_false; } else if ((generated < max_particles) && ((particle_attributes->particles[index].was_alive == d_false) || (particle_attributes->single_shoot == d_false))) { particle_attributes->particles[index].was_alive = d_true; memcpy(&(particle_attributes->particles[index].born), ¤t, sizeof(struct timeval)); memcpy(&(particle_attributes->particles[index].update), ¤t, sizeof(struct timeval)); particle_attributes->particles[index].core.position_x = d_particle_randomizeF(particle_attributes, position_x) + local_position_x; particle_attributes->particles[index].core.position_y = d_particle_randomizeF(particle_attributes, position_y) + local_position_y; particle_attributes->particles[index].core.zoom = d_particle_randomizeF(particle_attributes, zoom); particle_attributes->particles[index].core.angle = d_particle_randomizeF(particle_attributes, angle); particle_attributes->particles[index].core.gravity_x = d_particle_randomizeF(particle_attributes, gravity_x); particle_attributes->particles[index].core.gravity_y = d_particle_randomizeF(particle_attributes, gravity_y); particle_attributes->particles[index].core.direction_angle = d_particle_randomizeF(particle_attributes, direction_angle); particle_attributes->particles[index].core.speed_linear = d_particle_randomizeF(particle_attributes, speed_linear); particle_attributes->particles[index].core.speed_direction_angle = d_particle_randomizeF(particle_attributes, speed_direction_angle); particle_attributes->particles[index].core.speed_zoom = d_particle_randomizeF(particle_attributes, speed_zoom); particle_attributes->particles[index].core.speed_angle = d_particle_randomizeF(particle_attributes, speed_angle); particle_attributes->particles[index].core.mask_R = d_particle_randomizeF(particle_attributes, mask_R); particle_attributes->particles[index].core.mask_G = d_particle_randomizeF(particle_attributes, mask_G); particle_attributes->particles[index].core.mask_B = d_particle_randomizeF(particle_attributes, mask_B); particle_attributes->particles[index].core.mask_A = d_particle_randomizeF(particle_attributes, mask_A); particle_attributes->particles[index].core.speed_R = d_particle_randomizeF(particle_attributes, speed_R); particle_attributes->particles[index].core.speed_G = d_particle_randomizeF(particle_attributes, speed_G); particle_attributes->particles[index].core.speed_B = d_particle_randomizeF(particle_attributes, speed_B); particle_attributes->particles[index].core.speed_A = d_particle_randomizeF(particle_attributes, speed_A); particle_attributes->particles[index].core.lifetime = d_particle_randomizeF(particle_attributes, lifetime); if (particle_attributes->configuration.initializer) particle_attributes->configuration.initializer(&(particle_attributes->particles[index].core)); particle_attributes->particles[index].alive = d_true; ++generated; } } return self; }
void test_netmap(usn_mbuf_t *m) { int tosend = 0; int n, i; int rate_limit = 0; int sent = 0; struct pollfd pfd = { .fd = g_nmd->fd, .events = POLLOUT }; struct netmap_if *nifp = g_nmd->nifp; struct timeval stime, etime; struct nm_desc nmd = *g_nmd; struct nm_desc *t_nmd; uint64_t nmd_flags = 0; // re-open netmap device. nmd.req.nr_flags = NR_REG_ONE_NIC; nmd.req.nr_ringid = 0; printf("interface name:%s,len=%d\n",g_interface, m->mlen); t_nmd = nm_open(g_interface, NULL, nmd_flags | NM_OPEN_IFNAME | NM_OPEN_NO_MMAP, &nmd); if (t_nmd == NULL) { printf("Unable to open %s: %s", g_interface, strerror(errno)); return; } nifp =t_nmd->nifp; pfd.fd =t_nmd->fd; pfd.events = POLLOUT; n = 10000; sent = 0; g_config.burst = 512; printf("g_config.burst=%d\n", g_config.burst); gettimeofday(&stime, 0); while ( sent < n ) { /* * wait for available room in the send queue(s) */ if (poll(&pfd, 1, 1000) <= 0) { D("poll error/timeout on queue: %s", strerror(errno)); // goto quit; } if (pfd.revents & POLLERR) { D("poll error"); goto quit; } for (i = g_nmd->first_tx_ring; i <= g_nmd->last_tx_ring; i++) { int limit = rate_limit ? tosend : g_config.burst; int cnt = 0; if (n > 0 && n - sent < limit) limit = n - sent; struct netmap_ring *txring = NETMAP_TXRING(nifp, i); if (nm_ring_empty(txring)) continue; cnt = test_send(txring, m, limit); DEBUG("limit %d tail %d cnt %d", limit, txring->tail, cnt); sent += cnt; } } // print info stats gettimeofday(&etime, 0); timersub(&etime,&stime,&etime); printf("num of sent pkts: %d\n", n); printf("total time: %lu (seconds) %lu (microseconds) \n", etime.tv_sec, etime.tv_usec); /* flush any remaining packets */ ioctl(pfd.fd, NIOCTXSYNC, NULL); /* final part: wait all the TX queues to be empty. */ for (i = g_nmd->first_tx_ring; i <= g_nmd->last_tx_ring; i++) { struct netmap_ring *txring = NETMAP_TXRING(nifp, i); while (nm_tx_pending(txring)) { ioctl(pfd.fd, NIOCTXSYNC, NULL); usleep(1); /* wait 1 tick */ } } quit: return; } /* set the thread affinity. */ int setaffinity( int i) { cpuset_t cpumask; if (i == -1) return 0; /* Set thread affinity affinity.*/ CPU_ZERO(&cpumask); CPU_SET(i, &cpumask); if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_CPUSET, -1, sizeof(cpuset_t), &cpumask) != 0) { DEBUG("Unable to set affinity: %s", strerror(errno)); return 1; } return 0; }
int tls_bio(int fd, int timeout, TLS_SESS_STATE *TLScontext, int (*hsfunc) (SSL *), int (*rfunc) (SSL *, void *, int), int (*wfunc) (SSL *, const void *, int), void *buf, int num) { const char *myname = "tls_bio"; int status; int err; int enable_deadline; struct timeval time_left; /* amount of time left */ struct timeval time_deadline; /* time of deadline */ struct timeval time_now; /* time after SSL_mumble() call */ /* * Compensation for interface mis-match: With VSTREAMs, timeout <= 0 * means wait forever; with the read/write_wait() calls below, we need to * specify timeout < 0 instead. * * Safety: no time limit means no deadline. */ if (timeout <= 0) { timeout = -1; enable_deadline = 0; } /* * Deadline management is simpler than with VSTREAMs, because we don't * need to decrement a per-stream time limit. We just work within the * budget that is available for this tls_bio() call. */ else { enable_deadline = vstream_fstat(TLScontext->stream, VSTREAM_FLAG_DEADLINE); if (enable_deadline) { GETTIMEOFDAY(&time_deadline); time_deadline.tv_sec += timeout; } } /* * If necessary, retry the SSL handshake or read/write operation after * handling any pending network I/O. */ for (;;) { if (hsfunc) status = hsfunc(TLScontext->con); else if (rfunc) status = rfunc(TLScontext->con, buf, num); else if (wfunc) status = wfunc(TLScontext->con, buf, num); else msg_panic("%s: nothing to do here", myname); err = SSL_get_error(TLScontext->con, status); #if (OPENSSL_VERSION_NUMBER <= 0x0090581fL) /* * There is a bug up to and including OpenSSL-0.9.5a: if an error * occurs while checking the peers certificate due to some * certificate error (e.g. as happend with a RSA-padding error), the * error is put onto the error stack. If verification is not * enforced, this error should be ignored, but the error-queue is not * cleared, so we can find this error here. The bug has been fixed on * May 28, 2000. * * This bug so far has only manifested as 4800:error:0407006A:rsa * routines:RSA_padding_check_PKCS1_type_1:block type is not * 01:rsa_pk1.c:100: 4800:error:04067072:rsa * routines:RSA_EAY_PUBLIC_DECRYPT:padding check * failed:rsa_eay.c:396: 4800:error:0D079006:asn1 encoding * routines:ASN1_verify:bad get asn1 object call:a_verify.c:109: so * that we specifically test for this error. We print the errors to * the logfile and automatically clear the error queue. Then we retry * to get another error code. We cannot do better, since we can only * retrieve the last entry of the error-queue without actually * cleaning it on the way. * * This workaround is secure, as verify_result is set to "failed" * anyway. */ if (err == SSL_ERROR_SSL) { if (ERR_peek_error() == 0x0407006AL) { tls_print_errors(); msg_info("OpenSSL <= 0.9.5a workaround called: certificate errors ignored"); err = SSL_get_error(TLScontext->con, status); } } #endif /* * Correspondence between SSL_ERROR_* error codes and tls_bio_(read, * write, accept, connect, shutdown) return values (for brevity: * retval). * * SSL_ERROR_NONE corresponds with retval > 0. With SSL_(read, write) * this is the number of plaintext bytes sent or received. With * SSL_(accept, connect, shutdown) this means that the operation was * completed successfully. * * SSL_ERROR_WANT_(WRITE, READ) start a new loop iteration, or force * (retval = -1, errno = ETIMEDOUT) when the time limit is exceeded. * * All other SSL_ERROR_* cases correspond with retval <= 0. With * SSL_(read, write, accept, connect) retval == 0 means that the * remote party either closed the network connection or that it * requested TLS shutdown; with SSL_shutdown() retval == 0 means that * our own shutdown request is in progress. With all operations * retval < 0 means that there was an error. In the latter case, * SSL_ERROR_SYSCALL means that error details are returned via the * errno value. * * Find out if we must retry the operation and/or if there is pending * network I/O. * * XXX If we're the first to invoke SSL_shutdown(), then the operation * isn't really complete when the call returns. We could hide that * anomaly here and repeat the call. */ switch (err) { case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: if (enable_deadline) { GETTIMEOFDAY(&time_now); timersub(&time_deadline, &time_now, &time_left); timeout = time_left.tv_sec + (time_left.tv_usec > 0); if (timeout <= 0) { errno = ETIMEDOUT; return (-1); } } if (err == SSL_ERROR_WANT_WRITE) { if (write_wait(fd, timeout) < 0) return (-1); /* timeout error */ } else { if (read_wait(fd, timeout) < 0) return (-1); /* timeout error */ } break; /* * Unhandled cases: SSL_ERROR_WANT_(ACCEPT, CONNECT, X509_LOOKUP) * etc. Historically, Postfix silently treated these as ordinary * I/O errors so we don't really know how common they are. For * now, we just log a warning. */ default: msg_warn("%s: unexpected SSL_ERROR code %d", myname, err); /* FALLTHROUGH */ /* * With tls_timed_read() and tls_timed_write() the caller is the * VSTREAM library module which is unaware of TLS, so we log the * TLS error stack here. In a better world, each VSTREAM I/O * object would provide an error reporting method in addition to * the timed_read and timed_write methods, so that we would not * need to have ad-hoc code like this. */ case SSL_ERROR_SSL: if (rfunc || wfunc) tls_print_errors(); /* FALLTHROUGH */ case SSL_ERROR_ZERO_RETURN: case SSL_ERROR_NONE: errno = 0; /* avoid bogus warnings */ /* FALLTHROUGH */ case SSL_ERROR_SYSCALL: return (status); } } }
void demo_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename) { #ifdef OPENCV printf("Classifier Demo\n"); network net = parse_network_cfg(cfgfile); if(weightfile){ load_weights(&net, weightfile); } set_batch_network(&net, 1); list *options = read_data_cfg(datacfg); srand(2222222); CvCapture * cap; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } int top = option_find_int(options, "top", 1); char *name_list = option_find_str(options, "names", 0); char **names = get_labels(name_list); int *indexes = calloc(top, sizeof(int)); if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow("Classifier", CV_WINDOW_NORMAL); cvResizeWindow("Classifier", 512, 512); float fps = 0; int i; while(1){ struct timeval tval_before, tval_after, tval_result; gettimeofday(&tval_before, NULL); image in = get_image_from_stream(cap); image in_s = resize_image(in, net.w, net.h); show_image(in, "Classifier"); float *predictions = network_predict(net, in_s.data); if(net.hierarchy) hierarchy_predictions(predictions, net.outputs, net.hierarchy, 1, 1); top_predictions(net, top, indexes); printf("\033[2J"); printf("\033[1;1H"); printf("\nFPS:%.0f\n",fps); for(i = 0; i < top; ++i){ int index = indexes[i]; printf("%.1f%%: %s\n", predictions[index]*100, names[index]); } free_image(in_s); free_image(in); cvWaitKey(10); gettimeofday(&tval_after, NULL); timersub(&tval_after, &tval_before, &tval_result); float curr = 1000000.f/((long int)tval_result.tv_usec); fps = .9*fps + .1*curr; } #endif }
static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num) { int ret, icmp_sock = -1; unsigned long num = 1, i = 0; struct timeval start, end, diff; unsigned long long tx_bytes = 0, tx_packets = 0; struct packet_dyn *pktd; struct sockaddr_ll saddr = { .sll_family = PF_PACKET, .sll_halen = ETH_ALEN, .sll_ifindex = device_ifindex(ctx->device), }; if (ctx->num > 0) num = ctx->num; if (ctx->num == 0 && orig_num > 0) num = 0; if (ctx->smoke_test) icmp_sock = xmit_smoke_setup(ctx); drop_privileges(ctx->enforce, ctx->uid, ctx->gid); bug_on(gettimeofday(&start, NULL)); while (likely(sigint == 0 && num > 0 && plen > 0)) { pktd = &packet_dyn[i]; if (pktd->clen + pktd->rlen + pktd->slen) { apply_counter(i); apply_randomizer(i); apply_csum16(i); } retry: ret = sendto(sock, packets[i].payload, packets[i].len, 0, (struct sockaddr *) &saddr, sizeof(saddr)); if (unlikely(ret < 0)) { if (errno == ENOBUFS) { sched_yield(); goto retry; } if (ctx->smoke_test) panic("Sendto error: %s!\n", strerror(errno)); } tx_bytes += packets[i].len; tx_packets++; if (ctx->smoke_test) { ret = xmit_smoke_probe(icmp_sock, ctx); if (unlikely(ret < 0)) { printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end()); printf(" Remote host seems to be unresponsive to ICMP probes!\n"); printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n", i, seed); dump_trafgen_snippet(packets[i].payload, packets[i].len); break; } } if (!ctx->rand) { i++; if (i >= plen) i = 0; } else i = rand() % plen; if (ctx->num > 0) num--; if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0) nanosleep(&ctx->gap, NULL); } bug_on(gettimeofday(&end, NULL)); timersub(&end, &start, &diff); if (ctx->smoke_test) close(icmp_sock); stats[cpu].tx_packets = tx_packets; stats[cpu].tx_bytes = tx_bytes; stats[cpu].tv_sec = diff.tv_sec; stats[cpu].tv_usec = diff.tv_usec; stats[cpu].state |= CPU_STATS_STATE_RES; } static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num) { int ifindex = device_ifindex(ctx->device); uint8_t *out = NULL; unsigned int it = 0; unsigned long num = 1, i = 0, size; struct ring tx_ring; struct frame_map *hdr; struct timeval start, end, diff; struct packet_dyn *pktd; unsigned long long tx_bytes = 0, tx_packets = 0; fmemset(&tx_ring, 0, sizeof(tx_ring)); size = ring_size(ctx->device, ctx->reserve_size); set_sock_prio(sock, 512); set_packet_loss_discard(sock); setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support); create_tx_ring(sock, &tx_ring, ctx->verbose); mmap_tx_ring(sock, &tx_ring); alloc_tx_ring_frames(sock, &tx_ring); bind_tx_ring(sock, &tx_ring, ifindex); drop_privileges(ctx->enforce, ctx->uid, ctx->gid); if (ctx->kpull) interval = ctx->kpull; if (ctx->num > 0) num = ctx->num; if (ctx->num == 0 && orig_num > 0) num = 0; set_itimer_interval_value(&itimer, 0, interval); setitimer(ITIMER_REAL, &itimer, NULL); bug_on(gettimeofday(&start, NULL)); while (likely(sigint == 0 && num > 0 && plen > 0)) { if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) { sched_yield(); continue; } hdr = tx_ring.frames[it].iov_base; out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll); hdr->tp_h.tp_snaplen = packets[i].len; hdr->tp_h.tp_len = packets[i].len; pktd = &packet_dyn[i]; if (pktd->clen + pktd->rlen + pktd->slen) { apply_counter(i); apply_randomizer(i); apply_csum16(i); } fmemcpy(out, packets[i].payload, packets[i].len); tx_bytes += packets[i].len; tx_packets++; if (!ctx->rand) { i++; if (i >= plen) i = 0; } else i = rand() % plen; kernel_may_pull_from_tx(&hdr->tp_h); it++; if (it >= tx_ring.layout.tp_frame_nr) it = 0; if (ctx->num > 0) num--; } bug_on(gettimeofday(&end, NULL)); timersub(&end, &start, &diff); timer_purge(); destroy_tx_ring(sock, &tx_ring); stats[cpu].tx_packets = tx_packets; stats[cpu].tx_bytes = tx_bytes; stats[cpu].tv_sec = diff.tv_sec; stats[cpu].tv_usec = diff.tv_usec; stats[cpu].state |= CPU_STATS_STATE_RES; }
void gun_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename) { #ifdef OPENCV int bad_cats[] = {218, 539, 540, 1213, 1501, 1742, 1911, 2415, 4348, 19223, 368, 369, 370, 1133, 1200, 1306, 2122, 2301, 2537, 2823, 3179, 3596, 3639, 4489, 5107, 5140, 5289, 6240, 6631, 6762, 7048, 7171, 7969, 7984, 7989, 8824, 8927, 9915, 10270, 10448, 13401, 15205, 18358, 18894, 18895, 19249, 19697}; printf("Classifier Demo\n"); network net = parse_network_cfg(cfgfile); if(weightfile){ load_weights(&net, weightfile); } set_batch_network(&net, 1); list *options = read_data_cfg(datacfg); srand(2222222); CvCapture * cap; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } int top = option_find_int(options, "top", 1); char *name_list = option_find_str(options, "names", 0); char **names = get_labels(name_list); int *indexes = calloc(top, sizeof(int)); if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow("Threat Detection", CV_WINDOW_NORMAL); cvResizeWindow("Threat Detection", 512, 512); float fps = 0; int i; while(1){ struct timeval tval_before, tval_after, tval_result; gettimeofday(&tval_before, NULL); image in = get_image_from_stream(cap); image in_s = resize_image(in, net.w, net.h); show_image(in, "Threat Detection"); float *predictions = network_predict(net, in_s.data); top_predictions(net, top, indexes); printf("\033[2J"); printf("\033[1;1H"); int threat = 0; for(i = 0; i < sizeof(bad_cats)/sizeof(bad_cats[0]); ++i){ int index = bad_cats[i]; if(predictions[index] > .01){ printf("Threat Detected!\n"); threat = 1; break; } } if(!threat) printf("Scanning...\n"); for(i = 0; i < sizeof(bad_cats)/sizeof(bad_cats[0]); ++i){ int index = bad_cats[i]; if(predictions[index] > .01){ printf("%s\n", names[index]); } } free_image(in_s); free_image(in); cvWaitKey(10); gettimeofday(&tval_after, NULL); timersub(&tval_after, &tval_before, &tval_result); float curr = 1000000.f/((long int)tval_result.tv_usec); fps = .9*fps + .1*curr; } #endif }
int netsnmp_arch_linosdiskio_container_load(netsnmp_container* container) { cpqLinOsDiskTable_entry *entry; netsnmp_index tmp; oid oid_index[2]; long rc = 0; int i; struct timeval curr_time; struct timeval prev_time; struct timeval e_time; int interval; read_line_t *disklines = NULL; int maj, min; char diskname[16]; gettimeofday(&curr_time, NULL); DEBUGMSGTL(("linosdiskio:container:load", "loading\n")); DEBUGMSGTL(("linosdiskio:container:load", "Container=%p\n",container)); if ((disklines = ReadFileLines("/proc/diskstats")) != NULL) { for (i =0; i < disklines->count;i++) { unsigned long long reads, rmerged, read_sec, read_ms, writes, wmerged, write_sec, write_ms, io_inflight, io_ms, io_ms_weightd; if (sscanf(disklines->line[i],"%d %d %s ", &maj, &min, diskname) != 3) continue; if (min % 16) continue; if (!strncmp(diskname,"sd", 2) || !strncmp(diskname,"hd", 2) || !strncmp(diskname,"cciss", 5)) { sscanf(disklines->line[i], "%d %d %s %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu", &maj, &min, diskname, &reads, &rmerged, &read_sec, &read_ms, &writes, &wmerged, &write_sec, &write_ms, &io_inflight, &io_ms, &io_ms_weightd); oid_index[0] = maj; oid_index[1] = min; tmp.len = 2; tmp.oids = &oid_index[0]; entry = CONTAINER_FIND(container, &tmp); if (entry) { entry->prev_time.tv_sec = entry->curr_time.tv_sec; entry->prev_time.tv_usec = entry->curr_time.tv_usec; entry->prev_reads = entry->curr_reads; entry->prev_read_merge = entry->curr_read_merge; entry->prev_read_sectors = entry->curr_read_sectors; entry->prev_read_ms = entry->curr_read_ms; entry->prev_writes = entry->curr_writes; entry->prev_write_merge = entry->curr_write_merge; entry->prev_write_sectors = entry->curr_write_sectors; entry->prev_write_ms = entry->curr_write_ms; entry->curr_reads = reads; entry->curr_read_merge = rmerged; entry->curr_read_sectors = read_sec; entry->curr_read_ms = read_ms; entry->curr_writes = writes; entry->curr_write_merge = wmerged; entry->curr_write_sectors = write_sec; entry->curr_write_ms = write_ms; entry->curr_time.tv_sec = curr_time.tv_sec; entry->curr_time.tv_usec = curr_time.tv_usec; timersub(&entry->curr_time, &entry->prev_time, &e_time); /* interval between samples is in .01 sec */ interval = (e_time.tv_sec*1000 + e_time.tv_usec/1000)/10; if (interval) { entry->cpqLinOsDiskReadIos = (entry->curr_reads - entry->prev_reads); entry->cpqLinOsDiskReadMerges = (entry->curr_read_merge - entry->prev_read_merge); entry->cpqLinOsDiskReadSectors = (entry->curr_read_sectors - entry->prev_read_sectors); entry->cpqLinOsDiskReadDurationMs = (entry->curr_read_ms - entry->prev_read_ms); entry->cpqLinOsDiskReadIosPerSec = entry->cpqLinOsDiskReadIos/(interval/100); entry->cpqLinOsDiskReadSectorsPerSec = entry->cpqLinOsDiskReadSectors/(interval/100); if (entry->cpqLinOsDiskReadIos) entry->cpqLinOsDiskReadDurationMsPerIos = entry->cpqLinOsDiskReadDurationMs/entry->cpqLinOsDiskReadIos; else entry->cpqLinOsDiskReadDurationMsPerIos = 0; entry->cpqLinOsDiskWriteIos = (entry->curr_writes - entry->prev_writes); entry->cpqLinOsDiskWriteMerges = (entry->curr_write_merge - entry->prev_write_merge); entry->cpqLinOsDiskWriteSectors = (entry->curr_write_sectors - entry->prev_write_sectors); entry->cpqLinOsDiskWriteDurationMs = (entry->curr_write_ms - entry->prev_write_ms); entry->cpqLinOsDiskWriteIosPerSec = entry->cpqLinOsDiskWriteIos/(interval/100); entry->cpqLinOsDiskWriteSectorsPerSec = entry->cpqLinOsDiskWriteSectors/(interval/100); if (entry->cpqLinOsDiskWriteIos) entry->cpqLinOsDiskWriteDurationMsPerIos = entry->cpqLinOsDiskWriteDurationMs/entry->cpqLinOsDiskWriteIos; else entry->cpqLinOsDiskWriteDurationMsPerIos = 0; } } else { entry = cpqLinOsDiskTable_createEntry(container, (oid)maj, (oid)min); entry->cpqLinOsDiskScsiIndex = 0; entry->cpqLinOsDiskMajorIndex = maj; entry->cpqLinOsDiskMinorIndex = min; entry->cpqLinOsDiskName_len = strlen(diskname); strncpy(entry->cpqLinOsDiskName, diskname, strlen(diskname)); entry->prev_reads = 0; entry->prev_read_merge = 0; entry->prev_read_sectors = 0; entry->prev_read_ms = 0; entry->prev_writes = 0; entry->prev_write_merge = 0; entry->prev_write_sectors = 0; entry->prev_write_ms = 0; entry->curr_reads = reads; entry->curr_read_merge = rmerged; entry->curr_read_sectors = read_sec; entry->curr_read_ms = read_ms; entry->curr_writes = writes; entry->curr_write_merge = wmerged; entry->curr_write_sectors = write_sec; entry->curr_write_ms = write_ms; entry->cpqLinOsDiskReadIos = 0; entry->cpqLinOsDiskReadMerges = 0; entry->cpqLinOsDiskReadSectors = 0; entry->cpqLinOsDiskReadDurationMs = 0; entry->cpqLinOsDiskWriteIos = 0; entry->cpqLinOsDiskWriteMerges =0; entry->cpqLinOsDiskWriteSectors = 0; entry->cpqLinOsDiskWriteDurationMs = 0; entry->cpqLinOsDiskReadIosPerSec = 0; entry->cpqLinOsDiskReadSectorsPerSec = 0; entry->cpqLinOsDiskReadDurationMsPerIos = 0; entry->cpqLinOsDiskWriteIosPerSec = 0; entry->cpqLinOsDiskWriteSectorsPerSec = 0; entry->cpqLinOsDiskWriteDurationMsPerIos = 0; entry->curr_time.tv_sec = curr_time.tv_sec; entry->curr_time.tv_usec = curr_time.tv_usec; rc = CONTAINER_INSERT(container, entry); DEBUGMSGTL(("linosdiskio:container:load", "Entry created\n")); } } } free(disklines->read_buf); free(disklines); } return(rc); }
static void ping(char *svr) { struct sigaction sa; struct sockaddr_l2 addr; socklen_t optlen; unsigned char *send_buf; unsigned char *recv_buf; char str[18]; int i, sk, lost; uint8_t id; memset(&sa, 0, sizeof(sa)); sa.sa_handler = stat; sigaction(SIGINT, &sa, NULL); send_buf = malloc(L2CAP_CMD_HDR_SIZE + size); recv_buf = malloc(L2CAP_CMD_HDR_SIZE + size); if (!send_buf || !recv_buf) { perror("Can't allocate buffer"); exit(1); } /* Create socket */ sk = socket(PF_BLUETOOTH, SOCK_RAW, BTPROTO_L2CAP); if (sk < 0) { perror("Can't create socket"); goto error; } /* Bind to local address */ memset(&addr, 0, sizeof(addr)); addr.l2_family = AF_BLUETOOTH; bacpy(&addr.l2_bdaddr, &bdaddr); if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { perror("Can't bind socket"); goto error; } /* Connect to remote device */ memset(&addr, 0, sizeof(addr)); addr.l2_family = AF_BLUETOOTH; str2ba(svr, &addr.l2_bdaddr); if (connect(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { perror("Can't connect"); goto error; } /* Get local address */ memset(&addr, 0, sizeof(addr)); optlen = sizeof(addr); if (getsockname(sk, (struct sockaddr *) &addr, &optlen) < 0) { perror("Can't get local address"); goto error; } ba2str(&addr.l2_bdaddr, str); printf("Ping: %s from %s (data size %d) ...\n", svr, str, size); /* Initialize send buffer */ for (i = 0; i < size; i++) send_buf[L2CAP_CMD_HDR_SIZE + i] = (i % 40) + 'A'; id = ident; while (count == -1 || count-- > 0) { struct timeval tv_send, tv_recv, tv_diff; l2cap_cmd_hdr *send_cmd = (l2cap_cmd_hdr *) send_buf; l2cap_cmd_hdr *recv_cmd = (l2cap_cmd_hdr *) recv_buf; /* Build command header */ send_cmd->ident = id; send_cmd->len = htobs(size); if (reverse) send_cmd->code = L2CAP_ECHO_RSP; else send_cmd->code = L2CAP_ECHO_REQ; gettimeofday(&tv_send, NULL); /* Send Echo Command */ if (send(sk, send_buf, L2CAP_CMD_HDR_SIZE + size, 0) <= 0) { perror("Send failed"); goto error; } /* Wait for Echo Response */ lost = 0; while (1) { struct pollfd pf[1]; int err; pf[0].fd = sk; pf[0].events = POLLIN; if ((err = poll(pf, 1, timeout * 1000)) < 0) { perror("Poll failed"); goto error; } if (!err) { lost = 1; break; } if ((err = recv(sk, recv_buf, L2CAP_CMD_HDR_SIZE + size, 0)) < 0) { perror("Recv failed"); goto error; } if (!err){ printf("Disconnected\n"); goto error; } recv_cmd->len = btohs(recv_cmd->len); /* Check for our id */ if (recv_cmd->ident != id) continue; /* Check type */ if (!reverse && recv_cmd->code == L2CAP_ECHO_RSP) break; if (recv_cmd->code == L2CAP_COMMAND_REJ) { printf("Peer doesn't support Echo packets\n"); goto error; } } sent_pkt++; if (!lost) { recv_pkt++; gettimeofday(&tv_recv, NULL); timersub(&tv_recv, &tv_send, &tv_diff); if (verify) { /* Check payload length */ if (recv_cmd->len != size) { fprintf(stderr, "Received %d bytes, expected %d\n", recv_cmd->len, size); goto error; } /* Check payload */ if (memcmp(&send_buf[L2CAP_CMD_HDR_SIZE], &recv_buf[L2CAP_CMD_HDR_SIZE], size)) { fprintf(stderr, "Response payload different.\n"); goto error; } } printf("%d bytes from %s id %d time %.2fms\n", recv_cmd->len, svr, id - ident, tv2fl(tv_diff)); if (delay) sleep(delay); } else { printf("no response from %s: id %d\n", svr, id - ident); } if (++id > 254) id = ident; } stat(0); free(send_buf); free(recv_buf); return; error: close(sk); free(send_buf); free(recv_buf); exit(1); }
static dc_status_t serial_ftdi_write (dc_custom_io_t *io, const void *data, size_t size, size_t *actual) { ftdi_serial_t *device = (ftdi_serial_t*) io->userdata; if (device == NULL) return DC_STATUS_INVALIDARGS; struct timeval tve, tvb; if (device->halfduplex) { // Get the current time. if (gettimeofday (&tvb, NULL) != 0) { SYSERROR (device->context, errno); return DC_STATUS_IO; } } unsigned int nbytes = 0; while (nbytes < size) { int n = ftdi_write_data (device->ftdi_ctx, (char *) data + nbytes, size - nbytes); if (n < 0) { if (n == LIBUSB_ERROR_INTERRUPTED) continue; // Retry. ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; // Error during write call. } else if (n == 0) { break; // EOF. } nbytes += n; } if (device->halfduplex) { // Get the current time. if (gettimeofday (&tve, NULL) != 0) { SYSERROR (device->context, errno); return DC_STATUS_IO; } // Calculate the elapsed time (microseconds). struct timeval tvt; timersub (&tve, &tvb, &tvt); unsigned long elapsed = tvt.tv_sec * 1000000 + tvt.tv_usec; // Calculate the expected duration (microseconds). A 2 millisecond fudge // factor is added because it improves the success rate significantly. unsigned long expected = 1000000.0 * device->nbits / device->baudrate * size + 0.5 + 2000; // Wait for the remaining time. if (elapsed < expected) { unsigned long remaining = expected - elapsed; // The remaining time is rounded up to the nearest millisecond to // match the Windows implementation. The higher resolution is // pointless anyway, since we already added a fudge factor above. serial_ftdi_sleep (device, (remaining + 999) / 1000); } } INFO (device->context, "Wrote %d bytes", nbytes); if (actual) *actual = nbytes; return DC_STATUS_SUCCESS; }
static DWORD WINAPI #else static void * #endif handle_connection(void *arg) { ssize_t n; unsigned long long sum = 0, first_length = 0; char *buf; #ifdef _WIN32 HANDLE tid; #else pthread_t tid; #endif struct socket *conn_sock; struct timeval start_time, now, diff_time; double seconds; unsigned long messages = 0; unsigned long recv_calls = 0; unsigned long notifications = 0; int flags; struct sockaddr_in addr; socklen_t len; union sctp_notification *snp; struct sctp_paddr_change *spc; struct timeval note_time; unsigned int infotype; struct sctp_recvv_rn rn; socklen_t infolen = sizeof(struct sctp_recvv_rn); conn_sock = *(struct socket **)arg; #ifdef _WIN32 tid = GetCurrentThread(); #else tid = pthread_self(); pthread_detach(tid); #endif buf = malloc(BUFFERSIZE); flags = 0; len = (socklen_t)sizeof(struct sockaddr_in); infotype = 0; memset(&rn, 0, sizeof(struct sctp_recvv_rn)); n = usrsctp_recvv(conn_sock, buf, BUFFERSIZE, (struct sockaddr *) &addr, &len, (void *)&rn, &infolen, &infotype, &flags); gettimeofday(&start_time, NULL); while (n > 0) { recv_calls++; if (flags & MSG_NOTIFICATION) { notifications++; gettimeofday(¬e_time, NULL); printf("notification arrived at %f\n", note_time.tv_sec+(double)note_time.tv_usec/1000000.0); snp = (union sctp_notification *)buf; if (snp->sn_header.sn_type==SCTP_PEER_ADDR_CHANGE) { spc = &snp->sn_paddr_change; printf("SCTP_PEER_ADDR_CHANGE: state=%d, error=%d\n",spc->spc_state, spc->spc_error); } } else { if (very_verbose) { printf("Message received\n"); } sum += n; if (flags & MSG_EOR) { messages++; if (first_length == 0) first_length = sum; } } flags = 0; len = (socklen_t)sizeof(struct sockaddr_in); infolen = sizeof(struct sctp_recvv_rn); infotype = 0; memset(&rn, 0, sizeof(struct sctp_recvv_rn)); n = usrsctp_recvv(conn_sock, (void *) buf, BUFFERSIZE, (struct sockaddr *) &addr, &len, (void *)&rn, &infolen, &infotype, &flags); } if (n < 0) perror("sctp_recvv"); gettimeofday(&now, NULL); timersub(&now, &start_time, &diff_time); seconds = diff_time.tv_sec + (double)diff_time.tv_usec/1000000.0; printf("%llu, %lu, %lu, %lu, %llu, %f, %f\n", first_length, messages, recv_calls, notifications, sum, seconds, (double)first_length * (double)messages / seconds); fflush(stdout); usrsctp_close(conn_sock); free(buf); #ifdef _WIN32 return 0; #else return (NULL); #endif }
int getDiffTimeval(struct timeval stop, struct timeval start){ struct timeval diffTimeval; timersub(&stop, &start, &diffTimeval); return (int) (diffTimeval.tv_sec * 1000000 + diffTimeval.tv_usec); }
static int do_seek(void) { demux_attr_t *attr; int seconds, new_seek_Bps; long long offset; struct timeval now, delta; static int count = 0; count++; attr = demux_get_attr(handle); gettimeofday(&now, NULL); timersub(&now, &seek_timeval, &delta); /* * Give up after 2 seconds */ if ((delta.tv_sec >= 2) && seeking) { seeking = 0; printf("SEEK ABORTED (%lu.%.2lu) %d\n", delta.tv_sec, delta.tv_usec/10000, count); count = 0; return 0; } if (!attr->gop_valid) { if ( --seek_attempts > 0 ) { PRINTF("GOP retry\n"); return -1; } printf("SEEK RETRY due to lack of GOP\n"); demux_flush(handle); demux_seek(handle); seek_attempts = 16; return -1; } if (pts_seek_attempts > 0) { seconds = attr->gop.pts/PTS_HZ; } else if (gop_seek_attempts > 0) { seconds = (attr->gop.hour * 3600) + (attr->gop.minute * 60) + attr->gop.second; } else { seconds = 0; } /* * Recompute Bps from actual time and position differences * provided the time difference is big enough */ if ( abs(seconds - seek_start_seconds) > SEEK_FUDGE ) { offset = video_functions->seek(0, SEEK_CUR); new_seek_Bps = (offset - seek_start_pos) / (seconds - seek_start_seconds); if ( new_seek_Bps > 10000 ) /* Sanity check */ seek_Bps = new_seek_Bps; } PRINTF("New Bps %d\n", seek_Bps); if ( abs(seconds - seek_seconds) <= SEEK_FUDGE ) { seeking = 0; printf("SEEK DONE: to %d at %d (%lu.%.2lu) %d\n", seek_seconds, seconds, delta.tv_sec, delta.tv_usec/10000, count); } else { offset = video_functions->seek(0, SEEK_CUR); PRINTF("RESEEK: From %lld + %d\n", offset, seek_Bps * (seek_seconds-seconds)); offset = video_functions->seek(seek_Bps * (seek_seconds-seconds), SEEK_CUR); demux_flush(handle); demux_seek(handle); seek_attempts--; PRINTF("SEEKING 1: %d/%d %lld\n", seconds, seek_seconds, offset); return -1; } count = 0; return 0; }
int ipmi_transaction(struct ipmi *ipmi, uint8_t netfn, uint8_t cmd, uint8_t *req_buf, uint16_t req_len, uint8_t *resp_buf, uint16_t *resp_len, int timeout_ms) { struct timeval start, now, delta; struct pollfd pollfds[1]; struct flock lock; int expired_ms, rc; memset(&lock, 0, sizeof(lock)); lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; rc = fcntl(ipmi->fd, F_SETLKW, &lock); if (rc == -1) { pb_log("IPMI: error locking IPMI device: %m\n"); return rc; } rc = ipmi_send(ipmi, netfn, cmd, req_buf, req_len); if (rc) goto out; pollfds[0].fd = ipmi->fd; pollfds[0].events = POLLIN; gettimeofday(&start, NULL); expired_ms = 0; for (;;) { uint8_t resp_netfn, resp_cmd; long seq; rc = poll(pollfds, 1, timeout_ms - expired_ms); if (rc < 0) { pb_log("IPMI: poll() error %m"); break; } if (rc == 0) { pb_log("IPMI: timeout waiting for response " "(netfn %d, cmd %d)\n", netfn, cmd); rc = -1; break; } if (!(pollfds[0].revents & POLLIN)) { pb_log("IPMI: unexpected fd status from poll?\n"); rc = -1; break; } rc = ipmi_recv(ipmi, &resp_netfn, &resp_cmd, &seq, resp_buf, resp_len); if (rc) break; if (seq != ipmi->seq - 1) { pb_log("IPMI: out-of-sequence reply: " "exp %ld, got %ld\n", ipmi->seq, seq); if (timeout_ms) { gettimeofday(&now, NULL); timersub(&now, &start, &delta); expired_ms = (delta.tv_sec * 1000) + (delta.tv_usec / 1000); if (expired_ms >= timeout_ms) { rc = -1; break; } } } else { pb_debug("IPMI: netfn(%x->%x), cmd(%x->%x)\n", netfn, resp_netfn, cmd, resp_cmd); rc = 0; goto out; } } out: lock.l_type = F_UNLCK; if (fcntl(ipmi->fd, F_SETLKW, &lock) == -1) pb_log("IPMI: error unlocking IPMI device: %m\n"); return rc ? -1 : 0; }
int main(int argc, char const* argv[]) { int i, j, bsize; int ptc[2]; int ctp[2]; double avg; char *arr; pid_t pid; struct timeval sum, start, end, timeDiff; if (argc != 2) { fprintf(stderr, "Usage: pipe <size>\n"); exit(1); } bsize = atoi(argv[1]); sum.tv_sec = 0; sum.tv_usec = 0; pipe(ptc); pipe(ctp); pid = fork(); if (pid > 0) { close(ptc[0]); close(ctp[1]); arr = malloc(MB * bsize); if (arr == NULL) { fprintf(stderr, "malloc returned null. X_X\n"); exit(1); } for (j = 0; j < MB * bsize; ++j) { arr[j] = 1; } for (i = 0; i < ITERS; ++i) { gettimeofday(&start, NULL); write(ptc[1], arr, MB * bsize); read(ctp[0], arr, MB * bsize); gettimeofday(&end, NULL); timersub(&end, &start, &timeDiff); timeradd(&sum, &timeDiff, &sum); } close(ctp[0]); close(ptc[1]); } else if (pid == 0) { close(ptc[1]); close(ctp[0]); arr = malloc(MB * bsize); if (arr == NULL) { fprintf(stderr, "malloc returned null. X_X\n"); exit(1); } for (i = 0; i < ITERS; ++i) { read(ptc[0], arr, MB * bsize); write(ctp[1], arr, MB * bsize); } free(arr); exit(0); } else { fprintf(stderr, "Problem with fork()! I'll just die now. X_X\n"); exit(1); } avg = ((double)sum.tv_sec * 1000000 + (double)sum.tv_usec) / ITERS; printf("%d\t%f\n", bsize, avg); free(arr); return 0; }
int main(int argc, char *argv[]) { struct timeval lastcommand, now, diff; struct timezone here; char *servIP; /* Server IP address (dotted quad) */ unsigned short servPort; /* Echo server port */ char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ unsigned int echoStringLen; /* Length of string to echo */ int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */ int fd; int readevent; struct js_event e; /* Set signal handler */ signal(SIGINT, handle_kill); /* Set the starting time */ gettimeofday(&lastcommand,&here); if (argc < 3) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server IP> <Port>\n", argv[0]); exit(1); } /* Open the Joystick device */ fd = open ("/dev/input/js0", O_RDONLY|O_NONBLOCK); if(fd < 0) { printf("Cannot open joystick(/dev/input/js0)\r\n"); exit(1); } servIP = argv[1]; /* First arg: server IP address (dotted quad) */ servPort = atoi(argv[2]); /* Use given port, if any */ ksock_init('\n',2048); sock = ksock_connect(servIP, servPort); if(sock > 0) printf("Connected to %s:%d\r\n",servIP,servPort); /* Start reading event from the joystick */ readevent = read (fd, &e, sizeof(struct js_event)); while (readevent >=0 || sendflag || errno == EAGAIN) { if(readevent >= 0) { /* A new event is available */ e.type &= ~JS_EVENT_INIT; switch (e.type) { /* Handle joystick button event */ case JS_EVENT_BUTTON: //printf("Button %d at pos %d\n", e.number, e.value); handle_joybutton(e.number,e.value,echoBuffer); break; /* Handle joystick axis event */ case JS_EVENT_AXIS: //printf("Axis %d at pos %d\n", e.number, e.value); handle_joyaxis(e.number,e.value,echoBuffer); break; } } /* Send the command to the server if required */ if(sendflag) { /* check timing between to commands */ gettimeofday(&now,&here); timersub(&now,&lastcommand,&diff); //printf("elapsed: %ld.%.6ld\r\n",diff.tv_sec,diff.tv_usec); if(diff.tv_usec > 100000 || !timeflag) { lastcommand.tv_sec = now.tv_sec; lastcommand.tv_usec = now.tv_usec; printf("%s\n",echoBuffer); /* Send the command to the robot */ echoStringLen = strlen(echoBuffer); if (send(sock, echoBuffer, echoStringLen, 0) != echoStringLen) DieWithError("send() sent a different number of bytes than expected"); /* Receive the same string back from the server */ totalBytesRcvd = 0; printf("Received: "); /* Setup to print the echoed string */ while (totalBytesRcvd < echoStringLen) { /* Receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender */ if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */ echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */ printf(echoBuffer); /* Print the echo buffer */ } printf("\n"); /* Print a final linefeed */ sendflag = 0; } } /* Read the next event */ readevent = read (fd, &e, sizeof(struct js_event)); } close(fd); close(sock); exit(0); }
static int64_t opencl_scanhash(struct thr_info *thr, struct work *work, int64_t __maybe_unused max_nonce) { const int thr_id = thr->id; struct opencl_thread_data *thrdata = thr->cgpu_data; struct cgpu_info *gpu = thr->cgpu; _clState *clState = clStates[thr_id]; const cl_kernel *kernel = &clState->kernel; const int dynamic_us = opt_dynamic_interval * 1000; cl_bool blocking; cl_int status; size_t globalThreads[1]; size_t localThreads[1] = { clState->wsize }; unsigned int threads; int64_t hashes; if (gpu->dynamic) blocking = CL_TRUE; else blocking = CL_FALSE; /* This finish flushes the readbuffer set with CL_FALSE later */ if (!blocking) clFinish(clState->commandQueue); if (gpu->dynamic) { struct timeval diff; suseconds_t gpu_us; gettimeofday(&gpu->tv_gpuend, NULL); timersub(&gpu->tv_gpuend, &gpu->tv_gpustart, &diff); gpu_us = diff.tv_sec * 1000000 + diff.tv_usec; if (likely(gpu_us >= 0)) { gpu->gpu_us_average = (gpu->gpu_us_average + gpu_us * 0.63) / 1.63; /* Try to not let the GPU be out for longer than * opt_dynamic_interval in ms, but increase * intensity when the system is idle in dynamic mode */ if (gpu->gpu_us_average > dynamic_us) { if (gpu->intensity > MIN_INTENSITY) --gpu->intensity; } else if (gpu->gpu_us_average < dynamic_us / 2) { if (gpu->intensity < MAX_INTENSITY) ++gpu->intensity; } } } set_threads_hashes(clState->vwidth, &threads, &hashes, globalThreads, localThreads[0], gpu->intensity); if (hashes > gpu->max_hashes) gpu->max_hashes = hashes; status = thrdata->queue_kernel_parameters(clState, &work->blk, globalThreads[0]); if (unlikely(status != CL_SUCCESS)) { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); return -1; } /* MAXBUFFERS entry is used as a flag to say nonces exist */ if (thrdata->res[FOUND]) { /* Clear the buffer again */ status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, blocking, 0, BUFFERSIZE, blank_res, 0, NULL, NULL); if (unlikely(status != CL_SUCCESS)) { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); return -1; } if (unlikely(thrdata->last_work)) { applog(LOG_DEBUG, "GPU %d found something in last work?", gpu->device_id); postcalc_hash_async(thr, thrdata->last_work, thrdata->res); thrdata->last_work = NULL; } else { applog(LOG_DEBUG, "GPU %d found something?", gpu->device_id); postcalc_hash_async(thr, work, thrdata->res); } memset(thrdata->res, 0, BUFFERSIZE); if (!blocking) clFinish(clState->commandQueue); } gettimeofday(&gpu->tv_gpustart, NULL); if (clState->goffset) { size_t global_work_offset[1]; global_work_offset[0] = work->blk.nonce; status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, global_work_offset, globalThreads, localThreads, 0, NULL, NULL); } else status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL, globalThreads, localThreads, 0, NULL, NULL); if (unlikely(status != CL_SUCCESS)) { applog(LOG_ERR, "Error %d: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)", status); return -1; } status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, blocking, 0, BUFFERSIZE, thrdata->res, 0, NULL, NULL); if (unlikely(status != CL_SUCCESS)) { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed error %d. (clEnqueueReadBuffer)", status); return -1; } /* The amount of work scanned can fluctuate when intensity changes * and since we do this one cycle behind, we increment the work more * than enough to prevent repeating work */ work->blk.nonce += gpu->max_hashes; return hashes; }
static void runtest(struct alg *alg, int count, int size, u_long cmd, struct timeval *tv) { int i, fd = crget(); struct timeval start, stop, dt; char *cleartext, *ciphertext, *originaltext; struct session2_op sop; struct crypt_op cop; char iv[EALG_MAX_BLOCK_LEN]; bzero(&sop, sizeof(sop)); if (!alg->ishash) { sop.keylen = (alg->minkeylen + alg->maxkeylen)/2; sop.key = (char *) malloc(sop.keylen); if (sop.key == NULL) err(1, "malloc (key)"); for (i = 0; i < sop.keylen; i++) sop.key[i] = rdigit(); sop.cipher = alg->code; } else { sop.mackeylen = (alg->minkeylen + alg->maxkeylen)/2; sop.mackey = (char *) malloc(sop.mackeylen); if (sop.mackey == NULL) err(1, "malloc (mac)"); for (i = 0; i < sop.mackeylen; i++) sop.mackey[i] = rdigit(); sop.mac = alg->code; } sop.crid = crid; if (ioctl(fd, cmd, &sop) < 0) { if (cmd == CIOCGSESSION || cmd == CIOCGSESSION2) { close(fd); if (verbose) { printf("cipher %s", alg->name); if (alg->ishash) printf(" mackeylen %u\n", sop.mackeylen); else printf(" keylen %u\n", sop.keylen); perror("CIOCGSESSION"); } /* hardware doesn't support algorithm; skip it */ return; } printf("cipher %s keylen %u mackeylen %u\n", alg->name, sop.keylen, sop.mackeylen); err(1, "CIOCGSESSION"); } originaltext = malloc(3*size); if (originaltext == NULL) err(1, "malloc (text)"); cleartext = originaltext+size; ciphertext = cleartext+size; for (i = 0; i < size; i++) cleartext[i] = rdigit(); memcpy(originaltext, cleartext, size); for (i = 0; i < N(iv); i++) iv[i] = rdigit(); if (verbose) { printf("session = 0x%x\n", sop.ses); printf("device = %s\n", crfind(sop.crid)); printf("count = %d, size = %d\n", count, size); if (!alg->ishash) { printf("iv:"); hexdump(iv, sizeof iv); } printf("cleartext:"); hexdump(cleartext, MIN(size, CHUNK)); } gettimeofday(&start, NULL); if (!alg->ishash) { for (i = 0; i < count; i++) { cop.ses = sop.ses; cop.op = COP_ENCRYPT; cop.flags = opflags; cop.len = size; cop.src = cleartext; cop.dst = ciphertext; cop.mac = 0; cop.iv = iv; if (ioctl(fd, CIOCCRYPT, &cop) < 0) err(1, "ioctl(CIOCCRYPT)"); if (verify && bcmp(ciphertext, cleartext, size) == 0) { printf("cipher text unchanged:"); hexdump(ciphertext, size); } memset(cleartext, 'x', MIN(size, CHUNK)); cop.ses = sop.ses; cop.op = COP_DECRYPT; cop.flags = opflags; cop.len = size; cop.src = ciphertext; cop.dst = cleartext; cop.mac = 0; cop.iv = iv; if (ioctl(fd, CIOCCRYPT, &cop) < 0) err(1, "ioctl(CIOCCRYPT)"); if (verify && bcmp(cleartext, originaltext, size) != 0) { printf("decrypt mismatch:\n"); printf("original:"); hexdump(originaltext, size); printf("cleartext:"); hexdump(cleartext, size); } } } else { for (i = 0; i < count; i++) { cop.ses = sop.ses; cop.op = 0; cop.flags = opflags; cop.len = size; cop.src = cleartext; cop.dst = 0; cop.mac = ciphertext; cop.iv = 0; if (ioctl(fd, CIOCCRYPT, &cop) < 0) err(1, "ioctl(CIOCCRYPT)"); } } gettimeofday(&stop, NULL); if (ioctl(fd, CIOCFSESSION, &sop.ses) < 0) perror("ioctl(CIOCFSESSION)"); if (verbose) { printf("cleartext:"); hexdump(cleartext, MIN(size, CHUNK)); } timersub(&stop, &start, tv); free(originaltext); close(fd); }