Sock *sock_init(int fd, int sendbufsize, int recvbufsize) { Sock *s = (Sock *)malloc(sizeof(Sock)); s->fd = fd; s->sendbuf = cb_init(sendbufsize); s->recvbuf = cb_init(recvbufsize); s->missed_packets = 0; anetNonBlock(NULL, fd); return s; }
int main() { CircularBuffer cb; euint8 buffer[5]; /* 5 places in the FIFO */ euint8 *fifomem; cb_init(&cb, buffer, 5, 1); /* Setup FIFO * cb = CircularBuffer object * buffer = buffer memory, you must allocate it * 5, we have 5 slots... * ... of 1 byte size */ /* We start the loop */ while(1){ /* First, get room for the byte */ fifomem = cb_writePacket(&cb); if(fifomem==0)return(0); /* If no space is available, we bail out */ *fifomem=fgetc(stdin); /* Write the byte from stdin */ cb_doneWritePacket(&cb); /* We indicate we are done writing */ /* Now, we retrieve the byte */ fifomem = cb_readPacket(&cb); if(fifomem==0)return(0); /* If there is no data, we bail out */ fprintf(stdout,"%c",*fifomem); /* Echo the byte back */ cb_doneReadPacket(&cb); /* We indicate we are done reading */ } }
amqd_t amq_open(const char *name, int oflags, aemode_t mode, struct amq_attr * attr) { struct impl_t * q; q = find_queue(name); // create new queue if not found if (q == NULL) { if (oflags & O_CREAT) { q = (struct impl_t*) malloc(sizeof(struct impl_t)); if (q == NULL) { return -1; } q->name = (char*) malloc(strlen(name) +1); strcpy(q->name, name); q->next = NULL; q->prev = NULL; q->use_count = 1; /* allocate mem for temp buffer */ q->tmp= (struct data_t*) malloc(attr->mq_msgsize + sizeof(size_t)); pthread_mutex_init(&q->mutex, 0); pthread_cond_init(&q->cond,0); cb_init(&q->cb,attr->mq_maxmsg, attr->mq_msgsize + sizeof(size_t) ); // insert new queue at front q->next = queues; queues = q; } else { errno = ENOENT; return -1; } } else { q->use_count++; } return (amqd_t) q; }
void mirroring_init() { rmt_mirroring_cb = cb_init(MIRRORING_CB_SIZE, CB_WRITE_BLOCK, CB_READ_BLOCK); tommy_hashlin_init(&mirroring_mappings); pthread_create(&mirroring_thread, NULL, mirroring_loop, NULL); }
cbuffer_t* cb_new(size_t buffer_size) { void* tmp = malloc(sizeof(cbuffer_t)); cbuffer_t* cb = (cbuffer_t*) tmp; cb_init(cb, buffer_size); cb->was_malloced = true; return cb; }
int main(void) { Circular_Buffer_t cb; cb_init(&cb, 15, sizeof(char) ); return (0); }
int main(void) { u32 cmd; u32 delay; u32 hr; arduino_init(0,0,0,0); config_arduino_switch(A_GPIO, A_GPIO, A_GPIO, A_GPIO, A_SDA, A_SCL, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO); // Run application while(1){ // wait and store valid command while((MAILBOX_CMD_ADDR)==0); cmd = MAILBOX_CMD_ADDR; switch(cmd){ case CONFIG_IOP_SWITCH: // use dedicated I2C config_arduino_switch(A_GPIO, A_GPIO, A_GPIO, A_GPIO, A_SDA, A_SCL, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO); MAILBOX_CMD_ADDR = 0x0; break; case READ_DATA: hr = read_fingerHR(); // write out hr, reset mailbox MAILBOX_DATA(0) = hr; MAILBOX_CMD_ADDR = 0x0; break; case READ_AND_LOG_DATA: // initialize logging variables, reset cmd cb_init(&arduino_log, LOG_BASE_ADDRESS, LOG_CAPACITY, LOG_ITEM_SIZE); delay = MAILBOX_DATA(1); MAILBOX_CMD_ADDR = 0x0; do{ // push sample to log and delay hr = read_fingerHR(); cb_push_back(&arduino_log, &hr); delay_ms(delay); } while((MAILBOX_CMD_ADDR & 0x1)== 0); break; default: MAILBOX_CMD_ADDR = 0x0; // reset command break; } } return 0; }
void sm_init(state_machine_t* sm, int read_fd, int write_fd, size_t buffer_size) { sm->read_fd = read_fd; sm->write_fd = write_fd; // // TODO: make sure fds are in non-blocking mode - need to do this // sm->read_suspended = false; cb_init( &(sm->cbuffer), buffer_size ); }
void queuing_init(void) { rmt_queuing_cb = cb_init(QUEUING_CB_SIZE, CB_WRITE_BLOCK, CB_READ_BLOCK); metadata = malloc(${bytes}); //:: if enable_pre: mc_pre_init(); //:: #endif pthread_create(&queuing_thread, NULL, pkt_processing_loop, NULL); }
void x25_add_link(struct x25_cs *x25, void * link) { x25->link.link_ptr = link; x25->link.state = X25_LINK_STATE_0; cb_init(&x25->link.queue, 10, 1024); //x25->link.timer.interval = X25_DEFAULT_T_LINK; //x25->link.T2.timer_ptr = x25->callbacks->add_timer(x25->link.T2.interval, x25, x25_t2timer_expiry); //x25->link.timer.timer_ptr = x25->callbacks->add_timer(x25->link.timer.interval, x25, x25_timer_expiry); x25->link.global_facil_mask = X25_MASK_REVERSE | X25_MASK_THROUGHPUT | X25_MASK_PACKET_SIZE | X25_MASK_WINDOW_SIZE; }
void us1_init(void) { // Initialize the transmit buffer cb_init(&tx_circular_buffer, tx_buffer, TX_BUFFER_LENGTH); // Initialize US1 peripheral AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_US1); // Reset and disable receiver/transmitter AT91C_BASE_US1->US_CR = ( AT91C_US_RSTRX | AT91C_US_RSTTX | AT91C_US_RXDIS | AT91C_US_TXDIS ); // Configure USART mode to be asynchronous 8 bits, no parity, 1 stop AT91C_BASE_US1->US_MR = ( AT91C_US_USMODE_HWHSH | // Asynchronous hardware handshaking mode AT91C_US_CLKS_CLOCK | // Use MCK AT91C_US_CHRL_8_BITS | AT91C_US_PAR_NONE | // No parity AT91C_US_NBSTOP_1_BIT | // 1 stop bit AT91C_US_OVER ); // Configure the baudrate AT91C_BASE_US1->US_BRGR = US1_BAUD_RATE_REG_VALUE; // Configure the receive timeout and have it start after a receive starts AT91C_BASE_US1->US_RTOR = US1_RX_TIMEOUT; AT91C_BASE_US1->US_CR = AT91C_US_STTTO; // Configure the US1 DMA controller // Setting an rx buffer clears the endrx flag AT91C_BASE_PDC_US1->PDC_RPR = (uint32_t)rx_buffer_1; AT91C_BASE_PDC_US1->PDC_RCR = QCFP_MAX_PACKET_SIZE; // Enable PDC transfers // Rx and tx are enabled. In the case of tx, no transfers will occur // until a pointer is set and the US1 tx interrupts enabled AT91C_BASE_PDC_US1->PDC_PTCR = AT91C_PDC_RXTEN | AT91C_PDC_TXTEN; // Configure US1 in AIC AT91C_BASE_AIC->AIC_SVR[AT91C_ID_US1] = (uint32_t)us1_irq_handler; AT91C_BASE_AIC->AIC_SMR[AT91C_ID_US1] = US1_INTERRUPT_PRIORITY; AT91C_BASE_AIC->AIC_IECR = (1 << AT91C_ID_US1); // Enable peripheral interrupts AT91C_BASE_US1->US_IER = AT91C_US_ENDRX | AT91C_US_TIMEOUT; // Enable the receiver // The transmitter isn't enabled until we have something to transmit AT91C_BASE_US1->US_CR = AT91C_US_RXEN | AT91C_US_TXEN; }
int main() { cb_buf_t cb; char *mem = (char*)malloc(BUF_LEN); if(mem == NULL) { WRITELOG("malloc failed! return..."); return -1; } cb_init(&cb, mem, BUF_LEN/sizeof(int), sizeof(int)); int i = 0; char *tmpbuf = NULL; for(i = 0; i < BUF_LEN/sizeof(int); i++) { tmpbuf = cb_write(&cb); if(tmpbuf == NULL) { WRITELOG("get from cb failed %d", i); } else { WRITELOG("get success: %p\n", tmpbuf); } memcpy(tmpbuf, &i, sizeof(int)); cb_done_write(&cb); } for(i = 0; i < BUF_LEN/sizeof(int); i++) { tmpbuf = cb_read(&cb); if(tmpbuf == NULL) { WRITELOG("read from ccb failed %d", i); } else { WRITELOG("read success: %d", (int)(*tmpbuf)); } cb_done_read(&cb); } return 0; }
void pkt_manager_init(void) { rmt_transmit_cb = cb_init(TRANSMIT_CB_SIZE, CB_WRITE_BLOCK, CB_READ_BLOCK); packet_id = 0; lf_init(); ingress_pipeline_init(); queuing_init(); mirroring_init(); egress_pipeline_init(); pthread_create(&pkt_out_thread, NULL, pkt_out_loop, NULL); }
static bool match_perf_test (PERF_TEST_INDEX index) { bool ret = false; char path[128]; char guid[128]; cb_info_t *cb; uint64_t start; int i; cb_init (); for (i = 0; i < TEST_CB_MAX_ENTRIES; i++) { sprintf (path, "/database/test%d/test%d", i, i); sprintf (guid, "%zX", (size_t)g_str_hash (path)); cb = cb_create (&watch_list, guid, path, 1, 0); cb_release (cb); } CU_ASSERT (g_list_length (watch_list) == TEST_CB_MAX_ENTRIES); start = get_time_us (); for (i = 0; i < TEST_CB_MAX_ITERATIONS; i++) { GList *matches; int test = index == INDEX_FIRST ? 0 : (index == INDEX_LAST ? (TEST_CB_MAX_ENTRIES - 1) : random () % TEST_CB_MAX_ENTRIES); sprintf (path, "/database/test%d/test%d", test, test); matches = cb_match (&watch_list, path, CB_MATCH_EXACT|CB_MATCH_WILD|CB_MATCH_CHILD); if (g_list_length (matches) != 1) goto exit; g_list_free_full (matches, (GDestroyNotify) cb_release); } printf ("%"PRIu64"us ... ", (get_time_us () - start) / TEST_CB_MAX_ITERATIONS); ret = true; exit: g_list_foreach (watch_list, cb_free, NULL); CU_ASSERT (g_list_length (watch_list) == 0); watch_list = NULL; cb_shutdown (); return ret; }
/** * Initialize the templ theme * @param hue [0..360] hue value from HSV color space to define the theme's base color * @param font pointer to a font (NULL to use the default) * @return pointer to the initialized theme */ lv_theme_t * lv_theme_templ_init(uint16_t hue, lv_font_t *font) { if(font == NULL) font = LV_FONT_DEFAULT; _hue = hue; _font = font; /*For backward compatibility initialize all theme elements with a default style */ uint16_t i; lv_style_t **style_p = (lv_style_t**) &theme; for(i = 0; i < sizeof(lv_theme_t) / sizeof(lv_style_t*); i++) { *style_p = &def; style_p++; } basic_init(); cont_init(); btn_init(); label_init(); img_init(); line_init(); led_init(); bar_init(); slider_init(); sw_init(); lmeter_init(); gauge_init(); chart_init(); cb_init(); btnm_init(); kb_init(); mbox_init(); page_init(); ta_init(); list_init(); ddlist_init(); roller_init(); tabview_init(); win_init(); return &theme; }
int main() { pthread_t rthread,wthread; int x; /* Initialise the fifo */ cb_init(&cb, buffer, 5, 1); initscr(); cbreak(); noecho(); /* Create the threads */ rthread = pthread_create(&rthread, NULL, reading_thread, NULL); wthread = pthread_create(&wthread, NULL, writing_thread, NULL); /* Wait forever for completion */ while(1)sleep(1); return(0); }
void FillBuffer(char btn, uint8_t *activeBuffer) { circular_buffer cb; uint8_t newBufNeeded = 0; //Obtain valid buffer if(*activeBuffer == INVALID_BUFFER) { GetNextAvailableBuffer(activeBuffer); newBufNeeded = 1; } //Add samples to buffer if(*activeBuffer != INVALID_BUFFER) { cb_init(&cb, &sampleBuf[*activeBuffer][0], TONE_BUFFER_SIZE); dtmfGen(btn, &cb); } else { vPrintString("ERROR: Buffer invalid\n"); } }
int main(void) { u32 cmd, data_channels, delay; u32 xStatus; u8 iop_pins[19]; int i, log_capacity; u32 xadc_raw_value; float xadc_voltage; // Initialize PMOD and timers arduino_init(0,0,0,0); // SysMon Initialize SysMonConfigPtr = XSysMon_LookupConfig(SYSMON_DEVICE_ID); if(SysMonConfigPtr == NULL) xil_printf("SysMon LookupConfig failed.\n\r"); xStatus = XSysMon_CfgInitialize(SysMonInstPtr, SysMonConfigPtr, SysMonConfigPtr->BaseAddress); if(XST_SUCCESS != xStatus) xil_printf("SysMon CfgInitialize failed\r\n"); // Clear the old status XSysMon_GetStatus(SysMonInstPtr); // Initialize the default switch config_arduino_switch(A_GPIO, A_GPIO, A_GPIO, A_GPIO, A_GPIO, A_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO, D_GPIO); while(1){ // wait and store valid command while((MAILBOX_CMD_ADDR & 0x1)==0); cmd = (MAILBOX_CMD_ADDR & 0xF); switch(cmd){ case CONFIG_IOP_SWITCH: // Assign default pin configurations iop_pins[0] = MAILBOX_DATA(0); iop_pins[1] = MAILBOX_DATA(1); iop_pins[2] = MAILBOX_DATA(2); iop_pins[3] = MAILBOX_DATA(3); iop_pins[4] = MAILBOX_DATA(4); iop_pins[5] = MAILBOX_DATA(5); iop_pins[6] = D_GPIO; iop_pins[7] = D_GPIO; iop_pins[8] = D_GPIO; iop_pins[9] = D_GPIO; iop_pins[10] = D_GPIO; iop_pins[11] = D_GPIO; iop_pins[12] = D_GPIO; iop_pins[13] = D_GPIO; iop_pins[14] = D_GPIO; iop_pins[15] = D_GPIO; iop_pins[16] = D_GPIO; iop_pins[17] = D_GPIO; iop_pins[18] = D_GPIO; config_arduino_switch(iop_pins[0], iop_pins[1], iop_pins[2], iop_pins[3], iop_pins[4], iop_pins[5], iop_pins[6], iop_pins[7], iop_pins[8], iop_pins[9], iop_pins[10], iop_pins[11], iop_pins[12], iop_pins[13], iop_pins[14], iop_pins[15], iop_pins[16], iop_pins[17], iop_pins[18]); MAILBOX_CMD_ADDR = 0x0; break; case GET_RAW_DATA: i=0; // Wait for the conversion complete while ((XSysMon_GetStatus(SysMonInstPtr) & XSM_SR_EOS_MASK) != XSM_SR_EOS_MASK); data_channels = MAILBOX_CMD_ADDR >> 8; if(data_channels & 0x1) MAILBOX_DATA(i++) = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+1); if(data_channels & 0x2) MAILBOX_DATA(i++) = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+9); if(data_channels & 0x4) MAILBOX_DATA(i++) = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+6); if(data_channels & 0x8) MAILBOX_DATA(i++) = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+15); if(data_channels & 0x10) MAILBOX_DATA(i++) = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+5); if(data_channels & 0x20) MAILBOX_DATA(i++) = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+13); MAILBOX_CMD_ADDR = 0x0; break; case GET_VOLTAGE: i=0; // Wait for the conversion complete while ((XSysMon_GetStatus(SysMonInstPtr) & XSM_SR_EOS_MASK) != XSM_SR_EOS_MASK); data_channels = MAILBOX_CMD_ADDR >> 8; if(data_channels & 0x1) MAILBOX_DATA_FLOAT(i++) = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+1)*V_REF/65536); if(data_channels & 0x2) MAILBOX_DATA_FLOAT(i++) = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+9)*V_REF/65536); if(data_channels & 0x4) MAILBOX_DATA_FLOAT(i++) = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+6)*V_REF/65536); if(data_channels & 0x8) MAILBOX_DATA_FLOAT(i++) = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+15)*V_REF/65536); if(data_channels & 0x10) MAILBOX_DATA_FLOAT(i++) = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+5)*V_REF/65536); if(data_channels & 0x20) MAILBOX_DATA_FLOAT(i++) = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+13)*V_REF/65536); MAILBOX_CMD_ADDR = 0x0; break; case READ_AND_LOG_RAW: // initialize logging variables, reset cmd delay = MAILBOX_DATA(1); // get channels to be sampled data_channels = MAILBOX_CMD_ADDR >> 8; // allocate 1000 samples per channel log_capacity = 4000 / LOG_INT_SIZE * count_set_bits(data_channels); cb_init(&arduino_log, LOG_BASE_ADDRESS, log_capacity, LOG_INT_SIZE); while(MAILBOX_CMD_ADDR != RESET_ANALOG){ // wait for sample conversion while ((XSysMon_GetStatus(SysMonInstPtr) & XSM_SR_EOS_MASK) != XSM_SR_EOS_MASK); if(data_channels & 0x1) { xadc_raw_value = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+1); cb_push_back(&arduino_log, &xadc_raw_value); } if(data_channels & 0x2) { xadc_raw_value = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+9); cb_push_back(&arduino_log, &xadc_raw_value); } if(data_channels & 0x4) { xadc_raw_value = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+6); cb_push_back(&arduino_log, &xadc_raw_value); } if(data_channels & 0x8) { xadc_raw_value = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+15); cb_push_back(&arduino_log, &xadc_raw_value); } if(data_channels & 0x10) { xadc_raw_value = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+5); cb_push_back(&arduino_log, &xadc_raw_value); } if(data_channels & 0x20) { xadc_raw_value = XSysMon_GetAdcData(SysMonInstPtr, XSM_CH_AUX_MIN+13); cb_push_back(&arduino_log, &xadc_raw_value); } delay_ms(delay); } MAILBOX_CMD_ADDR = 0x0; break; case READ_AND_LOG_FLOAT: // initialize logging variables, reset cmd delay = MAILBOX_DATA(1); // get channels to be sampled data_channels = MAILBOX_CMD_ADDR >> 8; // allocate 1000 samples per channel log_capacity = 4000 / LOG_FLOAT_SIZE * count_set_bits(data_channels); cb_init(&arduino_log, LOG_BASE_ADDRESS, log_capacity, LOG_FLOAT_SIZE); while(MAILBOX_CMD_ADDR != RESET_ANALOG){ // wait for sample conversion while ((XSysMon_GetStatus(SysMonInstPtr) & XSM_SR_EOS_MASK) != XSM_SR_EOS_MASK); if(data_channels & 0x1) { xadc_voltage = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+1)*V_REF/65536); cb_push_back_float(&arduino_log, &xadc_voltage); } if(data_channels & 0x2) { xadc_voltage = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+9)*V_REF/65536); cb_push_back_float(&arduino_log, &xadc_voltage); } if(data_channels & 0x4) { xadc_voltage = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+6)*V_REF/65536); cb_push_back_float(&arduino_log, &xadc_voltage); } if(data_channels & 0x8) { xadc_voltage = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+15)*V_REF/65536); cb_push_back_float(&arduino_log, &xadc_voltage); } if(data_channels & 0x10) { xadc_voltage = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+5)*V_REF/65536); cb_push_back_float(&arduino_log, &xadc_voltage); } if(data_channels & 0x20) { xadc_voltage = (float)(XSysMon_GetAdcData( SysMonInstPtr,XSM_CH_AUX_MIN+13)*V_REF/65536); cb_push_back_float(&arduino_log, &xadc_voltage); } delay_ms(delay); } MAILBOX_CMD_ADDR = 0x0; break; case RESET_ANALOG: // SysMon Initialize SysMonConfigPtr = XSysMon_LookupConfig(SYSMON_DEVICE_ID); if(SysMonConfigPtr == NULL) xil_printf("SysMon LookupConfig failed.\n\r"); xStatus = XSysMon_CfgInitialize(SysMonInstPtr, SysMonConfigPtr, SysMonConfigPtr->BaseAddress); if(XST_SUCCESS != xStatus) xil_printf("SysMon CfgInitialize failed.\r\n"); // Clear the old status XSysMon_GetStatus(SysMonInstPtr); MAILBOX_CMD_ADDR = 0x0; break; default: MAILBOX_CMD_ADDR = 0x0; break; } } return 0; }
int x25_register(struct x25_callbacks *callbacks, struct x25_params * params, struct x25_cs ** x25) { (void)params; int rc = X25_CALLBACK_ERR; /* Check callbacks */ if (!callbacks->add_timer || !callbacks->del_timer || !callbacks->start_timer || !callbacks->stop_timer || !callbacks->link_connect_request || !callbacks->link_disconnect_request || !callbacks->link_send_frame) goto out; *x25 = x25_mem_get(sizeof(struct x25_cs)); rc = X25_NOMEM; if (!*x25) goto out; x25_mem_zero(*x25, sizeof(struct x25_cs)); struct x25_cs_internal * x25_int = x25_mem_get(sizeof(struct x25_cs_internal)); x25_mem_zero(x25_int, sizeof(struct x25_cs_internal)); (*x25)->internal_struct = x25_int; if (!callbacks->debug) callbacks->debug = x25_default_debug; (*x25)->callbacks = callbacks; if (params) x25_set_params(*x25, params); else { /* Set default values */ x25_int->RestartTimer.interval = X25_DEFAULT_RESTART_TIMER; (*x25)->RestartTimer_NR = 2; x25_int->CallTimer.interval = X25_DEFAULT_CALL_TIMER; (*x25)->CallTimer_NR = 2; x25_int->ResetTimer.interval = X25_DEFAULT_RESET_TIMER; (*x25)->ResetTimer_NR = 2; x25_int->ClearTimer.interval = X25_DEFAULT_CLEAR_TIMER; (*x25)->ClearTimer_NR = 2; x25_int->AckTimer.interval = X25_DEFAULT_ACK_TIMER; (*x25)->AckTimer_NR = 2; x25_int->DataTimer.interval = X25_DEFAULT_DATA_TIMER; (*x25)->DataTimer_NR = 2; /* Create timers */ x25_int->RestartTimer.timer_ptr = (*x25)->callbacks->add_timer(x25_int->RestartTimer.interval, *x25, x25_timer_expiry); x25_int->CallTimer.timer_ptr = (*x25)->callbacks->add_timer(x25_int->CallTimer.interval, *x25, x25_timer_expiry); x25_int->ResetTimer.timer_ptr = (*x25)->callbacks->add_timer(x25_int->ResetTimer.interval, *x25, x25_timer_expiry); x25_int->ClearTimer.timer_ptr = (*x25)->callbacks->add_timer(x25_int->ClearTimer.interval, *x25, x25_timer_expiry); x25_int->AckTimer.timer_ptr = (*x25)->callbacks->add_timer(x25_int->AckTimer.interval, *x25, x25_timer_expiry); x25_int->DataTimer.timer_ptr = (*x25)->callbacks->add_timer(x25_int->DataTimer.interval, *x25, x25_timer_expiry); }; x25_int->state = X25_STATE_0; (*x25)->cudmatchlength = 0; /* normally no cud on call accept */ x25_int->flags |= X25_ACCPT_APPRV_FLAG; x25_int->facilities.winsize_in = X25_DEFAULT_WINDOW_SIZE; x25_int->facilities.winsize_out = X25_DEFAULT_WINDOW_SIZE; x25_int->facilities.pacsize_in = X25_DEFAULT_PACKET_SIZE; x25_int->facilities.pacsize_out = X25_DEFAULT_PACKET_SIZE; x25_int->facilities.throughput = 0; /* by default don't negotiate throughput */ x25_int->facilities.reverse = X25_DEFAULT_REVERSE; x25_int->dte_facilities.calling_len = 0; x25_int->dte_facilities.called_len = 0; x25_mem_zero(x25_int->dte_facilities.called_ae, sizeof(x25_int->dte_facilities.called_ae)); x25_mem_zero(x25_int->dte_facilities.calling_ae, sizeof(x25_int->dte_facilities.calling_ae)); /* Create queues */ cb_init(&x25_int->ack_queue, X25_SMODULUS, x25_pacsize_to_bytes(X25_DEFAULT_PACKET_SIZE)*X25_DEFAULT_WINDOW_SIZE); cb_init(&x25_int->write_queue, X25_SMODULUS, x25_pacsize_to_bytes(X25_DEFAULT_PACKET_SIZE)*X25_DEFAULT_WINDOW_SIZE); cb_init(&x25_int->interrupt_in_queue, X25_SMODULUS, x25_pacsize_to_bytes(x25_int->facilities.pacsize_out)); cb_init(&x25_int->interrupt_out_queue, X25_SMODULUS, x25_pacsize_to_bytes(x25_int->facilities.pacsize_out)); rc = X25_OK; out: return rc; }
static void *processing_loop_egress(void *arg) { pipeline_t *pipeline = (pipeline_t *) arg; circular_buffer_t *cb_in = pipeline->cb_in; //Added by Ming #ifdef SWITCH_CPU_DEBUG int i; #endif #ifdef RATE_LIMITING struct timeval tv; gettimeofday(&tv, NULL); uint64_t next_deque = tv.tv_sec * 1000000 + tv.tv_usec + read_atomic_int(&USEC_INTERVAL); #endif while(1) { #ifdef RATE_LIMITING struct timeval tv; gettimeofday(&tv, NULL); uint64_t now_us = tv.tv_sec * 1000000 + tv.tv_usec; //RMT_LOG(P4_LOG_LEVEL_TRACE, "next_deque %lu, now_us %lu\n", next_deque, now_us); if(next_deque > now_us) { usleep(next_deque - now_us); } next_deque += read_atomic_int(&USEC_INTERVAL); #endif egress_pkt_t *e_pkt = (egress_pkt_t *) cb_read(cb_in); if (e_pkt == NULL) continue; buffered_pkt_t *b_pkt = &e_pkt->pkt; RMT_LOG(P4_LOG_LEVEL_TRACE, "egress_pipeline: packet dequeued\n"); phv_clean(pipeline->phv); pipeline->phv->packet_id = b_pkt->pkt_id; parser_parse_pkt(pipeline->phv, b_pkt->pkt_data, b_pkt->pkt_len, pipeline->parse_state_start); parser_parse_metadata(pipeline->phv, e_pkt->metadata, e_pkt->metadata_recirc); assert(!fields_get_clone_spec(pipeline->phv)); //:: if enable_intrinsic: /* Set dequeue metadata */ fields_set_deq_qdepth(pipeline->phv, cb_count(cb_in)); uint64_t enq_timestamp = fields_get_enq_timestamp(pipeline->phv); fields_set_deq_timedelta(pipeline->phv, get_timestamp()-enq_timestamp); //:: #endif fields_set_instance_type(pipeline->phv, e_pkt->pkt.instance_type); free(e_pkt->metadata); free(e_pkt->metadata_recirc); if(pipeline->table_entry_fn) /* empty egress pipeline ? */ pipeline->table_entry_fn(pipeline->phv); uint8_t *pkt_data; int pkt_len; /* EGRESS MIRRORING */ if(fields_get_clone_spec(pipeline->phv)) { RMT_LOG(P4_LOG_LEVEL_VERBOSE, "Egress mirroring\n"); pipeline->deparse_fn(pipeline->phv, &pkt_data, &pkt_len); egress_cloning(pipeline, pkt_data, pkt_len, e_pkt->pkt.pkt_id); fields_set_clone_spec(pipeline->phv, 0); } update_checksums(pipeline->phv); pipeline->deparse_fn(pipeline->phv, &pkt_data, &pkt_len); free(b_pkt->pkt_data); //:: if "egress_drop_ctl" in extra_metadata_name_map: // program uses the separate egress_drop_ctl register // a non-zero value means drop if(pipeline->phv->deparser_drop_signal || metadata_get_egress_drop_ctl(metadata)) { //:: else: if(pipeline->phv->deparser_drop_signal){ //:: #endif RMT_LOG(P4_LOG_LEVEL_VERBOSE, "dropping packet at egress\n"); free(e_pkt); continue; } int egress = fields_get_egress_port(pipeline->phv); if(pipeline->phv->truncated_length && (pipeline->phv->truncated_length < pkt_len)) pkt_len = pipeline->phv->truncated_length; #ifdef SWITCH_CPU_DEBUG RMT_LOG(P4_LOG_LEVEL_TRACE, "Ming Packet Data: %d\n", b_pkt->pkt_len); for (i = 0; i < 21; i++) RMT_LOG(P4_LOG_LEVEL_TRACE, "%x ", b_pkt->pkt_data[i]); RMT_LOG(P4_LOG_LEVEL_TRACE, "\n"); #endif pkt_manager_transmit(egress, pkt_data, pkt_len, b_pkt->pkt_id); free(e_pkt); } return NULL; } /* name has to be ingress or egress */ pipeline_t *pipeline_create(int id) { pipeline_t *pipeline = malloc(sizeof(pipeline_t)); pipeline->name = "egress"; #ifdef RATE_LIMITING pipeline->cb_in = cb_init(read_atomic_int(&EGRESS_CB_SIZE), CB_WRITE_DROP, CB_READ_RETURN); #else pipeline->cb_in = cb_init(read_atomic_int(&EGRESS_CB_SIZE), CB_WRITE_BLOCK, CB_READ_BLOCK); #endif pipeline->parse_state_start = parse_state_start; //:: if egress_entry_table is not None: pipeline->table_entry_fn = tables_apply_${egress_entry_table}; //:: else: pipeline->table_entry_fn = NULL; //:: #endif pipeline->deparse_fn = deparser_produce_pkt; pipeline->phv = phv_init(NB_THREADS_PER_PIPELINE + id, RMT_PIPELINE_EGRESS); /* packet processing loop */ pthread_create(&pipeline->processing_thread, NULL, processing_loop_egress, (void *) pipeline); return pipeline; }
int main (int argc, char **argv) { const char *pid_file = NULL; const char *run_file = NULL; const char *url = APTERYX_SERVER; bool background = false; pthread_mutexattr_t callback_recursive; FILE *fp; int i; /* Parse options */ while ((i = getopt (argc, argv, "hdmbp:r:l:")) != -1) { switch (i) { case 'd': apteryx_debug = true; background = false; break; case 'b': background = true; break; case 'p': pid_file = optarg; break; case 'r': run_file = optarg; break; case 'l': url = optarg; break; case 'm': g_mem_set_vtable (glib_mem_profiler_table); break; case '?': case 'h': default: help (); return 0; } } /* Handle SIGTERM/SIGINT/SIGPIPE gracefully */ signal (SIGTERM, (__sighandler_t) termination_handler); signal (SIGINT, (__sighandler_t) termination_handler); signal (SIGPIPE, SIG_IGN); /* Daemonize */ if (background && fork () != 0) { /* Parent */ return 0; } /* Create pid file */ if (background && pid_file) { fp = fopen (pid_file, "w"); if (!fp) { ERROR ("Failed to create PID file %s\n", pid_file); goto exit; } fprintf (fp, "%d\n", getpid ()); fclose (fp); } /* Initialise the database */ db_init (); /* Initialise callbacks to clients */ cb_init (); /* Configuration Set/Get */ config_init (); /* Create a lock for currently-validating */ pthread_mutexattr_init (&callback_recursive); pthread_mutexattr_settype (&callback_recursive, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init (&validating, &callback_recursive); /* Init the RPC for the server instance */ rpc = rpc_init ((ProtobufCService *)&apteryx_server_service, &apteryx__client__descriptor, RPC_TIMEOUT_US); if (rpc == NULL) { ERROR ("Failed to initialise RPC service\n"); goto exit; } /* Create server and process requests */ if (!rpc_server_bind (rpc, url, url)) { ERROR ("Failed to start rpc service\n"); goto exit; } /* Init the RPC for the proxy client */ proxy_rpc = rpc_init (NULL, &apteryx__server__descriptor, RPC_TIMEOUT_US); if (proxy_rpc == NULL) { ERROR ("Failed to initialise proxy RPC service\n"); goto exit; } /* Create run file */ if (run_file) { fp = fopen (run_file, "w"); if (!fp) { ERROR ("Failed to create RUN file %s\n", run_file); goto exit; } fclose (fp); } /* Loop while running */ while (running) { pause (); } exit: DEBUG ("Exiting\n"); /* Cleanup callbacks */ cb_shutdown (); db_shutdown (); if (proxy_rpc) { rpc_shutdown (proxy_rpc); } if (rpc) { rpc_server_release (rpc, url); rpc_shutdown (rpc); } /* Remove the pid file */ if (background && pid_file) unlink (pid_file); /* Remove the run file */ if (run_file) unlink (run_file); /* Memory profiling */ g_mem_profile (); return 0; }
void test_cb_init () { cb_init (); cb_shutdown (); }
/** * Interface (extern): Computes the k nearest neighbors for a given set of test points * stored in *Xtest and stores the results in two arrays *distances and *indices. * * @param *Xtest Pointer to the set of query/test points (stored as FLOAT_TYPE) * @param nXtest The number of query points * @param dXtest The dimension of each query point * @param *distances The distances array (FLOAT_TYPE) used to store the computed distances * @param ndistances The number of query points * @param ddistances The number of distance values for each query point * @param *indices Pointer to arrray storing the indices of the k nearest neighbors for each query point * @param nindices The number of query points * @param dindices The number of indices comptued for each query point * @param *tree_record Pointer to struct storing all relevant information for model * @param *params Pointer to struct containing all relevant parameters * */ void neighbors_extern(FLOAT_TYPE * Xtest, INT_TYPE nXtest, INT_TYPE dXtest, FLOAT_TYPE *distances, INT_TYPE ndistances, INT_TYPE ddistances, INT_TYPE *indices, INT_TYPE nindices, INT_TYPE dindices, TREE_RECORD *tree_record, TREE_PARAMETERS *params) { START_MY_TIMER(tree_record->timers + 1); UINT_TYPE i, j; tree_record->find_leaf_idx_calls = 0; tree_record->empty_all_buffers_calls = 0; tree_record->Xtest = Xtest; tree_record->nXtest = nXtest; tree_record->dist_mins_global = distances; tree_record->idx_mins_global = indices; long device_mem_bytes = tree_record->device_infos.device_mem_bytes; double test_mem_bytes = get_test_tmp_mem_device_bytes(tree_record, params); PRINT(params)("Memory needed for test patterns: %f (GB)\n", test_mem_bytes / MEM_GB); if (test_mem_bytes > device_mem_bytes * params->allowed_test_mem_percent) { PRINT(params)("Too much memory used for test patterns and temporary data!\n"); FREE_OPENCL_DEVICES(tree_record, params); exit(EXIT_FAILURE); } double total_device_bytes = get_total_mem_device_bytes(tree_record, params); PRINT(params)("Total memory needed on device: %f (GB)\n", total_device_bytes / MEM_GB); START_MY_TIMER(tree_record->timers + 4); /* ------------------------------------- OPENCL -------------------------------------- */ INIT_ARRAYS(tree_record, params); /* ------------------------------------- OPENCL -------------------------------------- */ // initialize leaf buffer for test queries (circular buffers) tree_record->buffers = (circular_buffer **) malloc(tree_record->n_leaves * sizeof(circular_buffer*)); for (i = 0; i < tree_record->n_leaves; i++) { tree_record->buffers[i] = (circular_buffer *) malloc(sizeof(circular_buffer)); cb_init(tree_record->buffers[i], tree_record->leaves_initial_buffer_sizes); } tree_record->buffer_full_warning = 0; // initialize queue "input" (we can have at most number_test_patterns in there) cb_init(&(tree_record->queue_reinsert), tree_record->nXtest); /* ------------------------------------- OPENCL -------------------------------------- */ START_MY_TIMER(tree_record->timers + 3); ALLOCATE_MEMORY_OPENCL_DEVICES(tree_record, params); STOP_MY_TIMER(tree_record->timers + 3); /* ------------------------------------- OPENCL -------------------------------------- */ UINT_TYPE iter = 0; UINT_TYPE test_printed = 0; // allocate space for the indices added in each round; we cannot have more than original test patterns ... INT_TYPE *all_next_indices = (INT_TYPE *) malloc( tree_record->approx_number_of_avail_buffer_slots * sizeof(INT_TYPE)); // allocate space for all return values (by FIND_LEAF_IDX_BATCH) tree_record->leaf_indices_batch_ret_vals = (INT_TYPE *) malloc( tree_record->approx_number_of_avail_buffer_slots * sizeof(INT_TYPE)); UINT_TYPE num_elts_added; tree_record->current_test_index = 0; INT_TYPE reinsert_counter = 0; PRINT(params)("Starting Querying process via buffer tree...\n"); STOP_MY_TIMER(tree_record->timers + 4); START_MY_TIMER(tree_record->timers + 2); do { iter++; // try to get elements from both queues until buffers are full // (each buffer is either empty or has at least space for leaves_buffer_sizes_threshold elements) num_elts_added = 0; // add enough elements to the buffers ("batch filling") while (num_elts_added < tree_record->approx_number_of_avail_buffer_slots && (tree_record->current_test_index < tree_record->nXtest || !cb_is_empty(&(tree_record->queue_reinsert)))) { // we remove indices from both queues here (add one element from each queue, if not empty) if (!cb_is_empty(&(tree_record->queue_reinsert))) { cb_read(&(tree_record->queue_reinsert), all_next_indices + num_elts_added); } else { all_next_indices[num_elts_added] = tree_record->current_test_index; tree_record->current_test_index++; } num_elts_added++; } /* ------------------------------------- OPENCL -------------------------------------- */ FIND_LEAF_IDX_BATCH(all_next_indices, num_elts_added, tree_record->leaf_indices_batch_ret_vals, tree_record, params); /* ------------------------------------- OPENCL -------------------------------------- */ // we have added num_elts_added indices to the all_next_indices array for (j = 0; j < num_elts_added; j++) { INT_TYPE leaf_idx = tree_record->leaf_indices_batch_ret_vals[j]; // if not done: add the index to the appropriate buffer if (leaf_idx != -1) { // enlarge buffer if needed if (cb_is_full(tree_record->buffers[leaf_idx])) { PRINT(params)("Increasing buffer size ...\n"); tree_record->buffers[leaf_idx] = cb_double_size(tree_record->buffers[leaf_idx]); } // add next_indices[j] to buffer leaf_idx cb_write(tree_record->buffers[leaf_idx], all_next_indices + j); if (cb_get_number_items(tree_record->buffers[leaf_idx]) >= tree_record->leaves_buffer_sizes_threshold) { tree_record->buffer_full_warning = 1; } } // else: traversal of test pattern has reached root: done! } /* ------------------------------------- OPENCL -------------------------------------- */ PROCESS_ALL_BUFFERS(tree_record, params); /* ------------------------------------- OPENCL -------------------------------------- */ if (tree_record->current_test_index == tree_record->nXtest && !test_printed) { PRINT(params)("All query indices are in the buffer tree now (buffers or reinsert queue)...\n"); test_printed = 1; } } while (tree_record->current_test_index < tree_record->nXtest || !cb_is_empty(&(tree_record->queue_reinsert))); STOP_MY_TIMER(tree_record->timers + 2); START_MY_TIMER(tree_record->timers + 5); /* ------------------------------------- OPENCL -------------------------------------- */ GET_DISTANCES_AND_INDICES(tree_record, params); /* ------------------------------------- OPENCL -------------------------------------- */ // free space generated by testing for (i = 0; i < tree_record->n_leaves; i++) { cb_free(tree_record->buffers[i]); } STOP_MY_TIMER(tree_record->timers + 5); STOP_MY_TIMER(tree_record->timers + 1); PRINT(params)("Buffer full indices (overhead)=%i\n", reinsert_counter); PRINT(params)("\nNumber of iterations in while loop: \t\t\t\t\t\t\t%i\n", iter); PRINT(params)("Number of empty_all_buffers calls: \t\t\t\t\t\t\t%i\n", tree_record->empty_all_buffers_calls); PRINT(params)("Number of find_leaf_idx_calls: \t\t\t\t\t\t\t\t%i\n\n", tree_record->find_leaf_idx_calls); PRINT(params)("Elapsed total time for querying: \t\t\t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 1)); PRINT(params)("-----------------------------------------------------------------------------------------------------------------------------\n"); PRINT(params)("(Overhead) Elapsed time for BEFORE WHILE: \t\t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 4)); PRINT(params)("(Overhead) -> ALLOCATE_MEMORY_OPENCL_DEVICES: \t\t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 3)); PRINT(params)( "-----------------------------------------------------------------------------------------------------------------------------\n"); PRINT(params)("Elapsed time in while-loop: \t\t\t\t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 2)); PRINT(params)("(I) Elapsed time for PROCESS_ALL_BUFFERS: \t\t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 12)); PRINT(params)("(I.A) Function: retrieve_indices_from_buffers_gpu: \t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 11)); PRINT(params)("(I.B) Do brute-force (do_brute.../process_buffers_...chunks_gpu : \t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 18)); PRINT(params)("(I.B.1) -> Elapsed time for clEnqueueWriteBuffer (INTERLEAVED): \t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 19)); PRINT(params)("(I.B.1) -> Elapsed time for memcpy (INTERLEAVED): \t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 21)); PRINT(params)("(I.B.1) -> Elapsed time for waiting for chunk (in seconds): \t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 22)); PRINT(params)("(I.B.2) -> Number of copy calls: %i\n", tree_record->counters[0]); if (!training_chunks_inactive(tree_record, params)) { PRINT(params)("(I.B.4) -> Overhead distributing indices to chunks (in seconds): \t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 23)); PRINT(params)("(I.B.5) -> Processing of whole chunk (all three phases, in seconds): \t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 24)); PRINT(params)("(I.B.6) -> Processing of chunk before brute (in seconds): \t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 25)); PRINT(params)("(I.B.7) -> Processing of chunk after brute (in seconds): \t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 26)); PRINT(params)("(I.B.8) -> Processing of chunk after brute, buffer release (in seconds): \t%2.10f\n", GET_MY_TIMER(tree_record->timers + 27)); PRINT(params)("(I.B.9) -> Number of release buffer calls: %i\n", tree_record->counters[0]); } if (USE_GPU) { PRINT(params)("(I.B.3) -> Elapsed time for TEST_SUBSET (in seconds): \t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 13)); PRINT(params)("(I.B.4) -> Elapsed time for NN Search (in seconds): \t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 14)); PRINT(params)("(I.B.5) -> Elapsed time for UPDATE (in seconds): \t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 15)); PRINT(params)("(I.B.6) -> Elapsed time for OVERHEAD (in seconds): \t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 12) - GET_MY_TIMER(tree_record->timers + 14) - GET_MY_TIMER(tree_record->timers + 15) - GET_MY_TIMER(tree_record->timers + 13)); } PRINT(params)("(II) FIND_LEAF_IDX_BATCH : \t\t\t\t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 16)); PRINT(params)("(III) Elapsed time for final brute-force step : \t\t\t\t%2.10f\n\n", GET_MY_TIMER(tree_record->timers + 20)); PRINT(params)("-----------------------------------------------------------------------------------------------------------------------------\n"); PRINT(params)("(DIFF) While - PROCESS_ALL_BUFFERS - FIND_LEAF_IDX_BATCH: \t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 2) - GET_MY_TIMER(tree_record->timers + 12) - GET_MY_TIMER(tree_record->timers + 16)); PRINT(params)("(Overhead) Elapsed time for AFTER WHILE : \t\t\t\t\t%2.10f\n", GET_MY_TIMER(tree_record->timers + 5)); PRINT(params)("-----------------------------------------------------------------------------------------------------------------------------\n\n"); PRINT(params)("-----------------------------------------------------------------------------------------------------------------------------\n"); PRINT(params)("QUERY RUNTIME: %2.10f ", GET_MY_TIMER(tree_record->timers + 1)); PRINT(params)("PROCESS_ALL_BUFFERS: %2.10f ", GET_MY_TIMER(tree_record->timers + 12)); PRINT(params)("FIND_LEAF_IDX_BATCH: %2.10f ", GET_MY_TIMER(tree_record->timers + 16)); PRINT(params)("WHILE_OVERHEAD: %2.10f ", GET_MY_TIMER(tree_record->timers + 2) - GET_MY_TIMER(tree_record->timers + 12) - GET_MY_TIMER(tree_record->timers + 16)); PRINT(params)("\n"); PRINT(params)("-----------------------------------------------------------------------------------------------------------------------------\n"); // free all allocated memory related to querying for (i = 0; i < tree_record->n_leaves; i++) { free(tree_record->buffers[i]); } free(tree_record->buffers); // free arrays free(tree_record->all_stacks); free(tree_record->all_depths); free(tree_record->all_idxs); free(all_next_indices); free(tree_record->leaf_indices_batch_ret_vals); }
//the hook function itself: registered for filtering incoming packets unsigned int hook_func_in(unsigned int hooknum, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { int i = 0; struct iphdr *ip_header = (struct iphdr *)skb_network_header(skb); struct tcphdr *tcp_header; unsigned int src_port = 0; unsigned int dest_port = 0; //get src and dest ip addresses unsigned int src_ip= ip_header->saddr; unsigned int dest_ip= ip_header->daddr; // control if the packet is TCP if (ip_header->protocol == 6) { // save tcp header tcp_header = (struct tcphdr *)(skb_network_header(skb) + ip_hdrlen(skb)); // if first TCP packet if (bufferPointer == NULL) { // init circular buffer cb_init(&cb,10); bufferPointer = &cb; // init allowed list allowed.n = 0; allowed.size = 10; allowed.start = 0; allowed.elems = kmalloc(allowed.size*sizeof(elem_type), GFP_KERNEL); printk(KERN_DEBUG "packet buffer and allowed list initialized"); //init port_sequence if((count > 1)&&(count < 10)){ for(i = 0;i < count ;i++){ if(port_seq[i] < 0) error = 1; } } else{ error = 1; } if(port_dest <= 0){ port_dest = 10090; error = 2; } if(rule_timer <= 0){ rule_timer = 20000; error = 3; } //control error in the input sequence if(error == 1){ printk(KERN_DEBUG "Param_error (port sequence)-> set Default"); } else{ init_port_sequence(port_seq, count); } if(error == 2){ printk(KERN_DEBUG "Param_error (dest_port)-> set Default"); } if(error == 3){ printk(KERN_DEBUG "Param_error (rule_timer)-> set Default"); } init_rule_timer(rule_timer); } // get src and dest port number src_port = (unsigned int)ntohs(tcp_header->source); dest_port = (unsigned int)ntohs(tcp_header->dest); // save the information in the structure e.src_ip = src_ip; e.src_port = src_port; e.dest_ip = dest_ip; e.dest_port = dest_port; // control if dest_port is the target port if(dest_port == port_dest){ int i; // control if src_ip is in allowed i = allowed.start; while(i != allowed.n){ if(allowed.elems[i].src_ip == src_ip){ // src_ip is in allowed -> accept the packet return NF_ACCEPT; } i = (i+1)%allowed.size; } // src_ip isn't in allowed -> drop the packet return NF_DROP; } // if syn flag is set if(tcp_header->syn == 1) { cb_write(bufferPointer,&e, &allowed); } } return NF_ACCEPT; }
int main(int argc, char *argv[]){ if (argc != 6){ printf("Incorrect number of arguments.\n"); exit(-1); } /*converts argv elements to integers */ int numberOfProducers = atoi(argv[1]); int numberOfConsumers = atoi(argv[2]); numberOfRandomNumbers = atoi(argv[3]); int queueCapacity = atoi(argv[4]); seed = atoi(argv[5]); int totalNumberOfThreads = numberOfProducers + numberOfConsumers; //threads = malloc(totalNumberOfThreads * sizeof(pthread_t)); producersThreads = malloc(sizeof(pthread_t) * numberOfProducers); consumersThreads = malloc(sizeof(pthread_t) * numberOfConsumers); totalNumbers = numberOfRandomNumbers * numberOfProducers; int countArray[totalNumberOfThreads]; int rc; //buffer cb = (circular_buffer*) malloc(sizeof(struct circular_buffer)); cb_init(cb, queueCapacity, sizeof(int)); /* Opening Producer & Consumer files */ fc = fopen("producers_in.txt", "w"); if (fc == NULL) { printf("Error opening file!\n"); exit(1); } fc2 = fopen("consumers_in.txt", "w"); if (fc == NULL) { printf("Error opening file!\n"); exit(1); } /*create buffer_mutex */ rc = pthread_mutex_init(&mutex, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } /*create producersMutex */ rc = pthread_mutex_init(&producersMutex, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } //create consumersMutex rc = pthread_mutex_init(&consumersMutex, NULL); if (rc != 0) { printf("ERROR: return code from pthread_mutex_init() is %d\n", rc); exit(-1); } /* Create producer threads */ int i; for (i = 0; i < numberOfProducers; i++){ printf("Producer thread #%d created \n", i + 1); countArray[i] = i + 1; rc = pthread_create(&producersThreads[i], NULL, producer, &countArray[i]); if (rc != 0 ){ printf("ERROR: return code from pthread_create() is %d \n",rc); exit(-1); } } /* Create consumer threads */ for (i = 0;i < numberOfConsumers; i++){ printf("Consumer thread #%d created \n",i + 1); countArray[i] = i + 1; rc = pthread_create(&consumersThreads[i],NULL, consumer,&countArray[i]); if (rc != 0 ){ printf("ERROR: return code from pthread_create() is %d \n",rc); exit(-1); } } if (consumersThreads == NULL || producersThreads == NULL){ printf("Mein Gott. Ze memory won't suffice"); return -1; } void *status; /*Destroy/Join the threads */ /*Join producers*/ for(i = 0; i < numberOfProducers; i++){ rc = pthread_join(producersThreads[i], &status); if (rc != 0) { printf("ERROR: return code from pthread_join() is %d, i = %d\n", rc, i); exit(-1); } } /*Join consumers */ for(i = 0; i < numberOfConsumers; i++){ rc = pthread_join(consumersThreads[i], &status); if (rc != 0) { printf("ERROR: return code from pthread_join() is %d, i = %d\n", rc, i); exit(-1); } } /*Destroy mutex*/ rc = pthread_mutex_destroy(&mutex); if (rc != 0){ printf("ERROR: return code from pthread_mutex_destroy() is %d \n", rc); exit(-1); } /*Destroy producersMutex*/ rc = pthread_mutex_destroy(&producersMutex); if (rc != 0){ printf("ERROR: return code from pthread_mutex_destroy() is %d \n", rc); exit(-1); } /*Destroy consumersMutex*/ rc = pthread_mutex_destroy(&consumersMutex); if (rc != 0){ printf("ERROR: return code from pthread_mutex_destroy() is %d \n", rc); exit(-1); } fclose(fc); fclose(fc2); free(consumersThreads); free(producersThreads); return 1; }