/*-------------------------------------------------------------------------*\ * Creates a serial object \*-------------------------------------------------------------------------*/ static int global_create(lua_State *L) { const char* path = luaL_checkstring(L, 1); /* allocate unix object */ p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix)); /* open serial device */ t_socket sock = open(path, O_NOCTTY|O_RDWR, 00700); /*printf("open %s on %d\n", path, sock);*/ if (sock < 0) { lua_pushnil(L); lua_pushstring(L, socket_strerror(errno)); lua_pushnumber(L, errno); return 3; } /* set its type as client object */ auxiliar_setclass(L, "serial{client}", -1); /* initialize remaining structure fields */ socket_setnonblocking(&sock); un->sock = sock; io_init(&un->io, (p_send) socket_write, (p_recv) socket_read, (p_error) socket_ioerror, &un->sock); timeout_init(&un->tm, -1, -1); buffer_init(&un->buf, &un->io, &un->tm); return 1; }
static void init(void) { /* set modes before to enable the port */ gpio_dir(PROG_BUTTON, GPIO_INPUT); pin_mode(PROG_BUTTON, PIN_MODE_PULLUP); gpio_dir(TARGET_RESET, GPIO_INPUT); gpio_dir(TARGET_LED, GPIO_INPUT); /* set digital debounce/filter */ pin_physport_from_pin(PROG_BUTTON)->dfcr.cs = PORT_CS_LPO; pin_physport_from_pin(PROG_BUTTON)->dfwr.filt = 31; /* button interrupt */ pin_physport_from_pin(PROG_BUTTON)->dfer |= 1 << pin_physpin_from_pin(PROG_BUTTON); pin_physport_from_pin(PROG_BUTTON)->pcr[pin_physpin_from_pin(PROG_BUTTON)].irqc = PCR_IRQC_INT_FALLING; /* reset interrupt */ pin_physport_from_pin(TARGET_RESET)->pcr[pin_physpin_from_pin(TARGET_RESET)].irqc = PCR_IRQC_INT_RISING; /* LED interrupt */ pin_physport_from_pin(TARGET_LED)->pcr[pin_physpin_from_pin(TARGET_LED)].irqc = PCR_IRQC_INT_FALLING; int_enable(IRQ_PORTD); gpio_dir(LED_SUCCESS, GPIO_OUTPUT); gpio_dir(LED_FAIL, GPIO_OUTPUT); timeout_init(); }
static void mysleep(int msec) { struct timeval tmo; struct timeval t1,t2; int ms; //printf("SLEEP %d\n", msec); timeout_init(&tmo, msec); getmonotime(&t1,0); while( (ms = timeout_left(&tmo)) > 0 ) { printf("dbus wait io %d\n", ms); dbus_connection_read_write(connection, ms); do { printf("dbus dispatch\n"); } while( dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS ); } getmonotime(&t2,0); timersub(&t2,&t1,&t1); printf("SLEPT %.3f / %.3f s\n", t1.tv_sec + t1.tv_usec * 1e-6, msec * 1e-3); }
/*-------------------------------------------------------------------------*\ * Creates a master tcp object \*-------------------------------------------------------------------------*/ static int tcp_create(lua_State *L, int family) { t_socket sock; const char *err = inet_trycreate(&sock, family, SOCK_STREAM); /* try to allocate a system socket */ if (!err) { /* allocate tcp object */ p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); memset(tcp, 0, sizeof(t_tcp)); /* set its type as master object */ auxiliar_setclass(L, "tcp{master}", -1); /* initialize remaining structure fields */ socket_setnonblocking(&sock); if (family == PF_INET6) { int yes = 1; setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&yes, sizeof(yes)); } tcp->sock = sock; io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, (p_error) socket_ioerror, &tcp->sock); timeout_init(&tcp->tm, -1, -1); buffer_init(&tcp->buf, &tcp->io, &tcp->tm); tcp->family = family; return 1; } else { lua_pushnil(L); lua_pushstring(L, err); return 2; } }
/*-------------------------------------------------------------------------*\ * Waits for and returns a client object attempting connection to the * server object \*-------------------------------------------------------------------------*/ static int meth_accept(lua_State *L) { p_tcp server = (p_tcp) auxiliar_checkclass(L, "tcp{server}", 1); p_timeout tm = timeout_markstart(&server->tm); t_socket sock; const char *err = inet_tryaccept(&server->sock, server->family, &sock, tm); /* if successful, push client socket */ if (err == NULL) { p_tcp clnt = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); auxiliar_setclass(L, "tcp{client}", -1); /* initialize structure fields */ memset(clnt, 0, sizeof(t_tcp)); socket_setnonblocking(&sock); clnt->sock = sock; io_init(&clnt->io, (p_send) socket_send, (p_recv) socket_recv, (p_error) socket_ioerror, &clnt->sock); timeout_init(&clnt->tm, -1, -1); buffer_init(&clnt->buf, &clnt->io, &clnt->tm); clnt->family = server->family; return 1; } else { lua_pushnil(L); lua_pushstring(L, err); return 2; } }
//开机初始化 void All_Init( void ) { const uint32_t NewDeviationAddr = 0x4000; /* BootLoad引导程序时,必须在Main中添加,同时更改“魔术棒--Target选项卡的ROM偏移地址” */ NVIC_SetVectorTable(NVIC_VectTab_FLASH,NewDeviationAddr); /* 外设初始化 */ lcd_init(); rtc_init(); led_init(); uart3_init(BAUD_38400); print_init(); //波特率19200 timeout_init(); TIM5_TimeoutInit(); link_init(); tf_init(); eep_init(); delay_init_t2(); beep_init(); SysTick_Config(SYSTICK_10MS); // PrintSystemParameter(); //串口打印系统参数信息,用于调试 #ifdef ENABLE_BEEP BEEP_START(); #endif set_page(system_init); }
/*-------------------------------------------------------------------------*\ * Creates a master tcp object \*-------------------------------------------------------------------------*/ static int tcp_create(lua_State *L, int family) { p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); memset(tcp, 0, sizeof(t_tcp)); /* set its type as master object */ auxiliar_setclass(L, "tcp{master}", -1); /* if family is AF_UNSPEC, we leave the socket invalid and * store AF_UNSPEC into family. This will allow it to later be * replaced with an AF_INET6 or AF_INET socket upon first use. */ tcp->sock = SOCKET_INVALID; tcp->family = family; io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, (p_error) socket_ioerror, &tcp->sock); timeout_init(&tcp->tm, -1, -1); buffer_init(&tcp->buf, &tcp->io, &tcp->tm); if (family != AF_UNSPEC) { const char *err = inet_trycreate(&tcp->sock, family, SOCK_STREAM, 0); if (err != NULL) { lua_pushnil(L); lua_pushstring(L, err); return 2; } socket_setnonblocking(&tcp->sock); } return 1; }
/*-------------------------------------------------------------------------*\ * Creates a master udp object \*-------------------------------------------------------------------------*/ static int udp_create(lua_State *L, int family) { t_socket sock; const char *err = inet_trycreate(&sock, family, SOCK_DGRAM); /* try to allocate a system socket */ if (!err) { /* allocate udp object */ p_udp udp = (p_udp) lua_newuserdata(L, sizeof(t_udp)); auxiliar_setclass(L, "udp{unconnected}", -1); /* initialize remaining structure fields */ socket_setnonblocking(&sock); if (family == PF_INET6) { int yes = 1; setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&yes, sizeof(yes)); } udp->sock = sock; timeout_init(&udp->tm, -1, -1); udp->family = family; return 1; } else { lua_pushnil(L); lua_pushstring(L, err); return 2; } }
/*-------------------------------------------------------------------------*\ * Creates a master tcp object \*-------------------------------------------------------------------------*/ static int global_create(lua_State *L) { short family; const char *af_opts[] = {"AF_INET", "AF_INET6"}; const char *def_af = "AF_INET"; const char *err; t_socket sock; switch(luaL_checkoption(L, 1, def_af, af_opts)) { case 0 : family = PF_INET ; break; case 1 : family = PF_INET6 ; break; default: family = PF_INET ; break; } /* try to allocate a system socket */ err = inet_trycreate(&sock, SOCK_STREAM, family); if (!err) { /* allocate tcp object */ p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); /* set its type as master object */ auxiliar_setclass(L, "tcp{master}", -1); /* initialize remaining structure fields */ socket_setnonblocking(&sock); tcp->sock = sock; io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, (p_error) socket_ioerror, &tcp->sock); timeout_init(&tcp->tm, -1, -1); buffer_init(&tcp->buf, &tcp->io, &tcp->tm); return 1; } else { lua_pushnil(L); lua_pushstring(L, err); return 2; } }
/*-------------------------------------------------------------------------*\ * Creates a master tcp object \*-------------------------------------------------------------------------*/ static int global_create(lua_State *L) { t_socket sock; const char *err = NULL; int fd = luaL_optnumber(L, 1, -1); if (fd < 1) err = inet_trycreate(&sock, SOCK_STREAM); else sock = fd; /* try to allocate a system socket */ if (!err) { /* allocate tcp object */ p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); if (fd >= 1) auxiliar_setclass(L, "tcp{client}", -1); else auxiliar_setclass(L, "tcp{master}", -1); /* initialize remaining structure fields */ socket_setnonblocking(&sock); tcp->sock = sock; io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, (p_error) socket_ioerror, &tcp->sock); timeout_init(&tcp->tm, -1, -1); buffer_init(&tcp->buf, &tcp->io, &tcp->tm); return 1; } else { lua_pushnil(L); lua_pushstring(L, err); return 2; } }
/*-------------------------------------------------------------------------*\ * Waits for a set of sockets until a condition is met or timeout. \*-------------------------------------------------------------------------*/ static int global_select(lua_State *L) { int rtab, wtab, itab, ret, ndirty; t_socket max_fd; fd_set rset, wset; t_timeout tm; double t = luaL_optnumber(L, 3, -1); FD_ZERO(&rset); FD_ZERO(&wset); lua_settop(L, 3); lua_newtable(L); itab = lua_gettop(L); lua_newtable(L); rtab = lua_gettop(L); lua_newtable(L); wtab = lua_gettop(L); max_fd = collect_fd(L, 1, SOCKET_INVALID, itab, &rset); ndirty = check_dirty(L, 1, rtab, &rset); t = ndirty > 0? 0.0: t; timeout_init(&tm, t, -1); timeout_markstart(&tm); max_fd = collect_fd(L, 2, max_fd, itab, &wset); ret = socket_select(max_fd+1, &rset, &wset, NULL, &tm); if (ret > 0 || ndirty > 0) { return_fd(L, &rset, max_fd+1, itab, rtab, ndirty); return_fd(L, &wset, max_fd+1, itab, wtab, 0); make_assoc(L, rtab); make_assoc(L, wtab); return 2; } else if (ret == 0) { lua_pushstring(L, "timeout"); return 3; } else { lua_pushstring(L, "error"); return 3; } }
int main(void) { timeout_init(); /* blink will also setup a timer to itself */ blink(NULL); sys_yield_for_frogs(); }
/** * Allocate and return a new timer, with given callback and argument. */ tor_timer_t * timer_new(timer_cb_fn_t cb, void *arg) { tor_timer_t *t = tor_malloc(sizeof(tor_timer_t)); timeout_init(t, 0); timer_set_cb(t, cb, arg); return t; }
int main(void) { halInit(); chSysInit(); chThdSleepMilliseconds(1000); hw_init_gpio(); LED_RED_OFF(); LED_GREEN_OFF(); conf_general_init(); ledpwm_init(); mc_configuration mcconf; conf_general_read_mc_configuration(&mcconf); mc_interface_init(&mcconf); commands_init(); comm_usb_init(); app_configuration appconf; conf_general_read_app_configuration(&appconf); app_init(&appconf); timeout_init(); timeout_configure(appconf.timeout_msec, appconf.timeout_brake_current); #if CAN_ENABLE comm_can_init(); #endif #if WS2811_ENABLE ws2811_init(); led_external_init(); #endif #if ENCODER_ENABLE encoder_init(); #endif #if SERVO_OUT_ENABLE #if SERVO_OUT_SIMPLE servo_simple_init(); #else servo_init(); #endif #endif // Threads chThdCreateStatic(periodic_thread_wa, sizeof(periodic_thread_wa), NORMALPRIO, periodic_thread, NULL); chThdCreateStatic(sample_send_thread_wa, sizeof(sample_send_thread_wa), NORMALPRIO - 1, sample_send_thread, NULL); chThdCreateStatic(timer_thread_wa, sizeof(timer_thread_wa), NORMALPRIO, timer_thread, NULL); for(;;) { chThdSleepMilliseconds(5000); } }
void main(void) { //leds: LED_INIT(); //init clock source XOSC: clocksource_init(); //init uart uart_init(); //init wdt timer wdt_init(); apa102_init(); //init storage storage_init(); //enable timeout routines timeout_init(); //apa102_init(); //init frsky core frsky_init(); //init adc adc_init(); //init output #if SBUS_ENABLED sbus_init(); #else ppm_init(); #endif //init failsafe failsafe_init(); debug("main: init done\n"); //run main //frsky_frame_sniffer(); frsky_main(); LED_RED_ON(); while (1) { LED_RED_ON(); delay_ms(200); LED_RED_OFF(); delay_ms(200); } }
int main(void) { // leds: led_init(); // init clock sources: clocksource_init(); // init ios io_init(); // init debug debug_init(); // init wdt timer wdt_init(); // enable timeout routines timeout_init(); // init storage storage_init(); // init frsky core frsky_init(); // init adc adc_init(); // init output #ifdef SBUS_ENABLED sbus_init(); #else // SBUS_ENABLED ppm_init(); #endif // SBUS_ENABLED // init failsafe failsafe_init(); // init telemetry telemetry_init(); // run main debug("main: init done\n"); // frsky_frame_sniffer(); frsky_main(); debug("main: frsky main ended?! THIS SHOULD NOT HAPPEN!"); while (1) {} }
static int global_connect(lua_State *L) { const char *remoteaddr = luaL_checkstring(L, 1); const char *remoteserv = luaL_checkstring(L, 2); const char *localaddr = luaL_optstring(L, 3, NULL); const char *localserv = luaL_optstring(L, 4, "0"); int family = inet_optfamily(L, 5, "unspec"); p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); struct addrinfo bindhints, connecthints; const char *err = NULL; /* initialize tcp structure */ memset(tcp, 0, sizeof(t_tcp)); io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, (p_error) socket_ioerror, &tcp->sock); timeout_init(&tcp->tm, -1, -1); buffer_init(&tcp->buf, &tcp->io, &tcp->tm); tcp->sock = SOCKET_INVALID; tcp->family = AF_UNSPEC; /* allow user to pick local address and port */ memset(&bindhints, 0, sizeof(bindhints)); bindhints.ai_socktype = SOCK_STREAM; bindhints.ai_family = family; bindhints.ai_flags = AI_PASSIVE; if (localaddr) { err = inet_trybind(&tcp->sock, &tcp->family, localaddr, localserv, &bindhints); if (err) { lua_pushnil(L); lua_pushstring(L, err); return 2; } } /* try to connect to remote address and port */ memset(&connecthints, 0, sizeof(connecthints)); connecthints.ai_socktype = SOCK_STREAM; /* make sure we try to connect only to the same family */ connecthints.ai_family = tcp->family; err = inet_tryconnect(&tcp->sock, &tcp->family, remoteaddr, remoteserv, &tcp->tm, &connecthints); if (err) { socket_destroy(&tcp->sock); lua_pushnil(L); lua_pushstring(L, err); return 2; } auxiliar_setclass(L, "tcp{client}", -1); return 1; }
/** * Create a new TLS/SSL object and mark it as new. */ static int meth_create(lua_State *L) { p_ssl ssl; int mode = lsec_getmode(L, 1); SSL_CTX *ctx = lsec_checkcontext(L, 1); if (mode == LSEC_MODE_INVALID) { lua_pushnil(L); lua_pushstring(L, "invalid mode"); return 2; } ssl = (p_ssl)lua_newuserdata(L, sizeof(t_ssl)); if (!ssl) { lua_pushnil(L); lua_pushstring(L, "error creating SSL object"); return 2; } ssl->ssl = SSL_new(ctx); if (!ssl->ssl) { lua_pushnil(L); lua_pushfstring(L, "error creating SSL object (%s)", ERR_reason_error_string(ERR_get_error())); return 2; } ssl->state = LSEC_STATE_NEW; SSL_set_fd(ssl->ssl, (int)SOCKET_INVALID); SSL_set_mode(ssl->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #if defined(SSL_MODE_RELEASE_BUFFERS) SSL_set_mode(ssl->ssl, SSL_MODE_RELEASE_BUFFERS); #endif if (mode == LSEC_MODE_SERVER) SSL_set_accept_state(ssl->ssl); else SSL_set_connect_state(ssl->ssl); io_init(&ssl->io, (p_send)ssl_send, (p_recv)ssl_recv, (p_error) ssl_ioerror, ssl); timeout_init(&ssl->tm, -1, -1); buffer_init(&ssl->buf, &ssl->io, &ssl->tm); luaL_getmetatable(L, "SSL:Connection"); lua_setmetatable(L, -2); return 1; }
/*-------------------------------------------------------------------------*\ * Creates a master udp object \*-------------------------------------------------------------------------*/ static int global_create(lua_State *L) { t_socket sock; const char *err = inet_trycreate(&sock, SOCK_DGRAM); /* try to allocate a system socket */ if (!err) { /* allocate tcp object */ p_udp udp = (p_udp) lua_newuserdata(L, sizeof(t_udp)); auxiliar_setclass(L, "udp{unconnected}", -1); /* initialize remaining structure fields */ socket_setnonblocking(&sock); udp->sock = sock; timeout_init(&udp->tm, -1, -1); return 1; } else { lua_pushnil(L); lua_pushstring(L, err); return 2; } }
/** * \brief Timeout example 2 main application routine */ int main( void ) { // Initialize drivers sysclk_init(); board_init(); pmic_init(); timeout_init(); cpu_irq_enable(); bool button_pressed; bool button_previous_state_pressed = false; // Initialize LEDs gpio_set_pin_group_high(LED_PORT, LED_PORT_MASK); while (1) { button_pressed = gpio_pin_is_low(GPIO_PUSH_BUTTON_0); // Test for any change in state since last sample if (button_previous_state_pressed != button_pressed) { /* Start debounce timeout. This will cancel any currently running timeout for selected id. */ timeout_start_singleshot(DEBOUNCE_TIMEOUT, DEBOUNCE_TICKS); button_previous_state_pressed = button_pressed; } // Check for debounce timeout expire if (timeout_test_and_clear_expired(DEBOUNCE_TIMEOUT)) { // Toggle LED0 if button is pressed down if (button_pressed) { gpio_toggle_pin(LED0_GPIO); } } // No debounce filter on button 1 if (gpio_pin_is_low(GPIO_PUSH_BUTTON_1)) { gpio_toggle_pin(LED1_GPIO); } } }
static int global_select(lua_State *L, const sigset_t* mask, int sigreceived) { int rtab, wtab, etab, itab, ret, ndirty; t_socket max_fd; fd_set rset, wset, eset; t_timeout tm; double t = luaL_optnumber(L, 4, -1); FD_ZERO(&rset); FD_ZERO(&wset); FD_ZERO(&eset); lua_settop(L, 4); lua_newtable(L); itab = lua_gettop(L); lua_newtable(L); rtab = lua_gettop(L); lua_newtable(L); wtab = lua_gettop(L); lua_newtable(L); etab = lua_gettop(L); max_fd = collect_fd(L, 1, SOCKET_INVALID, itab, &rset); ndirty = check_dirty(L, 1, rtab, &rset); t = ndirty > 0? 0.0: t; timeout_init(&tm, t, -1); timeout_markstart(&tm); max_fd = collect_fd(L, 2, max_fd, itab, &wset); max_fd = collect_fd(L, 3, max_fd, itab, &eset); //printf("+enter select\n"); if (sigreceived) { ret = -1; } else { ret = socket_select(max_fd+1, &rset, &wset, &eset, &tm, mask); } //printf("+exit select\n"); if (ret > 0 || ndirty > 0) { return_fd(L, &rset, max_fd+1, itab, rtab, ndirty); return_fd(L, &wset, max_fd+1, itab, wtab, 0); return_fd(L, &eset, max_fd+1, itab, etab, 0); make_assoc(L, rtab); make_assoc(L, wtab); make_assoc(L, etab); return 3; //3 values pushed: 3 result tables } else if (ret == 0) { lua_pushstring(L, "timeout"); return 4; //4 values pushed: 3 result tables + timeout msg } else { lua_pushstring(L, strerror(errno)); return 4; //4 values pushed: 3 result tables + errno msg } }
/*-------------------------------------------------------------------------*\ * Creates a master udp object \*-------------------------------------------------------------------------*/ static int udp_create(lua_State *L, int family) { /* allocate udp object */ p_udp udp = (p_udp) lua_newuserdata(L, sizeof(t_udp)); auxiliar_setclass(L, "udp{unconnected}", -1); /* if family is AF_UNSPEC, we leave the socket invalid and * store AF_UNSPEC into family. This will allow it to later be * replaced with an AF_INET6 or AF_INET socket upon first use. */ udp->sock = SOCKET_INVALID; timeout_init(&udp->tm, -1, -1); udp->family = family; if (family != AF_UNSPEC) { const char *err = inet_trycreate(&udp->sock, family, SOCK_DGRAM, 0); if (err != NULL) { lua_pushnil(L); lua_pushstring(L, err); return 2; } socket_setnonblocking(&udp->sock); } return 1; }
int main (void) { /// Status LED DDRB = _BV (PB7); steering_init (); timeout_init (); timeout_set (100, blinker_timeout, 0); //CLKPR = _BV (CLKPCE); //CLKPR = 0; //_BV (CLKPS0); /// Scale master clock by 2 sei (); for (;;) { //draw_rpm_bargraph (can_impl_get_dta_struct ()->data1.rpm); } return 0; }
/*-------------------------------------------------------------------------*\ * Creates a master unix object \*-------------------------------------------------------------------------*/ static int global_create(lua_State *L) { t_socket sock; int err = socket_create(&sock, AF_UNIX, SOCK_STREAM, 0); /* try to allocate a system socket */ if (err == IO_DONE) { /* allocate unix object */ p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix)); /* set its type as master object */ auxiliar_setclass(L, "unix{master}", -1); /* initialize remaining structure fields */ socket_setnonblocking(&sock); un->sock = sock; io_init(&un->io, (p_send) socket_send, (p_recv) socket_recv, (p_error) socket_ioerror, &un->sock); timeout_init(&un->tm, -1, -1); buffer_init(&un->buf, &un->io, &un->tm); return 1; } else { lua_pushnil(L); lua_pushstring(L, socket_strerror(err)); return 2; } }
/*-------------------------------------------------------------------------*\ * Waits for and returns a client object attempting connection to the * server object \*-------------------------------------------------------------------------*/ static int meth_accept(lua_State *L) { p_unix server = (p_unix) auxiliar_checkclass(L, "unix{server}", 1); p_timeout tm = timeout_markstart(&server->tm); t_socket sock; int err = socket_accept(&server->sock, &sock, NULL, NULL, tm); /* if successful, push client socket */ if (err == IO_DONE) { p_unix clnt = (p_unix) lua_newuserdata(L, sizeof(t_unix)); auxiliar_setclass(L, "unix{client}", -1); /* initialize structure fields */ socket_setnonblocking(&sock); clnt->sock = sock; io_init(&clnt->io, (p_send)socket_send, (p_recv)socket_recv, (p_error) socket_ioerror, &clnt->sock); timeout_init(&clnt->tm, -1, -1); buffer_init(&clnt->buf, &clnt->io, &clnt->tm); return 1; } else { lua_pushnil(L); lua_pushstring(L, socket_strerror(err)); return 2; } }
static void timeout_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; timeout_t *ptr; unsigned int inmem, outmem, filemem; int i; ptr = (timeout_t *) arg; assert(ptr != NULL); assert(ptr->clockevent.ev_base != NULL); // reset the timer to go off again in 1 second. evtimer_del(&ptr->clockevent); evtimer_set(&ptr->clockevent, timeout_handler, arg); event_base_set(ptr->clockevent.ev_base, &ptr->clockevent); evtimer_add(&ptr->clockevent, &t); assert(fd == INVALID_HANDLE); assert(ptr->server != NULL); assert(ptr->stats != NULL); if (ptr->stats->in_bytes || ptr->stats->out_bytes || ptr->stats->commands || ptr->stats->operations) { inmem=0; outmem=0; filemem = 0; for(i=0; i<ptr->server->maxconns; i++) { if (ptr->server->nodes[i] != NULL) { inmem += ptr->server->nodes[i]->in.length; outmem += ptr->server->nodes[i]->out.length; filemem += ptr->server->nodes[i]->filebuf.length; } } if (inmem > 0) { inmem /= 1024; } if (outmem > 0) { outmem /= 1024; } if (filemem > 0) { filemem /= 1024; } printf("Bytes [%u/%u], Commands [%u], Operations[%u], Mem[%uk/%uk/%uk], Cycles[%u], Undone[%u], RW[%u/%u]\n", ptr->stats->in_bytes, ptr->stats->out_bytes, ptr->stats->commands, ptr->stats->operations, inmem, outmem, filemem, ptr->stats->cycles, ptr->stats->undone, ptr->stats->reads, ptr->stats->writes); ptr->stats->in_bytes = 0; ptr->stats->out_bytes = 0; ptr->stats->commands = 0; ptr->stats->operations = 0; ptr->stats->cycles = 0; ptr->stats->undone = 0; ptr->stats->reads = 0; ptr->stats->writes = 0; } } void timeout_init(timeout_t *ptr, struct event_base *base) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; assert(ptr != NULL); assert(ptr->clockevent.ev_base == NULL); evtimer_set(&ptr->clockevent, timeout_handler, (void *) ptr); event_base_set(ptr->clockevent.ev_base, &ptr->clockevent); evtimer_add(&ptr->clockevent, &t); assert(ptr->clockevent.ev_base != NULL); } //----------------------------------------------------------------------------- // Main... process command line parameters, and then setup our listening // sockets and event loop. int main(int argc, char **argv) { int c; settings_t *settings = NULL; server_t *server = NULL; timeout_t *timeout = NULL; stats_t *stats = NULL; risp_t *risp = NULL; // handle SIGINT signal(SIGINT, sig_handler); // init settings settings = (settings_t *) malloc(sizeof(settings_t)); assert(settings != NULL); settings_init(settings); // set stderr non-buffering (for running under, say, daemontools) setbuf(stderr, NULL); // process arguments /// Need to check the options in here, there're possibly ones that we dont need. while ((c = getopt(argc, argv, "p:k:c:hvd:u:P:l:s:")) != -1) { switch (c) { case 'p': settings->port = atoi(optarg); assert(settings->port > 0); break; case 'c': settings->maxconns = atoi(optarg); assert(settings->maxconns > 0); break; case 'h': usage(); exit(EXIT_SUCCESS); case 'v': settings->verbose++; break; case 'd': assert(settings->daemonize == false); settings->daemonize = true; break; case 's': assert(settings->storepath == NULL); settings->storepath = optarg; assert(settings->storepath != NULL); assert(settings->storepath[0] != '\0'); break; case 'u': assert(settings->username == NULL); settings->username = optarg; assert(settings->username != NULL); assert(settings->username[0] != '\0'); break; case 'P': assert(settings->pid_file == NULL); settings->pid_file = optarg; assert(settings->pid_file != NULL); assert(settings->pid_file[0] != '\0'); break; case 'l': assert(settings->interface == NULL); settings->interface = strdup(optarg); assert(settings->interface != NULL); assert(settings->interface[0] != '\0'); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } if (settings->verbose) printf("Finished processing command-line args\n"); // If needed, increase rlimits to allow as many connections as needed. if (settings->verbose) printf("Settings Max connections: %d\n", settings->maxconns); assert(settings->maxconns > 0); set_maxconns(settings->maxconns); // if we are supplied with a username, drop privs to it. This will only // work if we are running as root, and is really only needed when running as // a daemon. if (settings->username != NULL) { if (settings->verbose) printf("Dropping privs and changing username: '******'\n", settings->username); if (drop_privs(settings->username) != 0) { usage(); exit(EXIT_FAILURE); } } // daemonize if requested // if we want to ensure our ability to dump core, don't chdir to / if (settings->daemonize) { int res; if (settings->verbose) printf("Daemonising\n"); res = daemon(0, settings->verbose); if (res == -1) { fprintf(stderr, "failed to daemon() in order to daemonize\n"); exit(EXIT_FAILURE); } } // initialize main thread libevent instance if (settings->verbose) printf("Initialising the event system.\n"); main_event_base = event_init(); if (settings->verbose) printf("Ignoring SIGPIPE interrupts\n"); ignore_sigpipe(); // save the PID in if we're a daemon, do this after thread_init due to a // file descriptor handling bug somewhere in libevent if (settings->daemonize && settings->pid_file) { if (settings->verbose) printf("Saving Pid file: %s\n", settings->pid_file); save_pid(getpid(), settings->pid_file); } // create and init the 'server' structure. if (settings->verbose) printf("Starting server listener on port %d.\n", settings->port); server = server_new(settings->port, settings->maxconns, settings->interface); if (server == NULL) { fprintf(stderr, "Failed to listen on port %d\n", settings->port); exit(EXIT_FAILURE); } assert(server != NULL); server->verbose = settings->verbose; server->storepath = settings->storepath; // add the server to the event base assert(main_event_base != NULL); server_add_event(server, main_event_base); // initialise clock event. The clock event is used to keep up our node // network. If we dont have enough connections, we will need to make some // requests. // create the timeout structure, and the timeout event. This is used to // perform certain things spread over time. Such as indexing the // 'complete' paths that we have, and ensuring that the 'chunks' parts are // valid. if (settings->verbose) printf("Setting up Timeout event.\n"); timeout = (timeout_t *) malloc(sizeof(timeout_t)); assert(timeout != NULL); assert(main_event_base != NULL); if (settings->verbose) printf("Initialising timeout.\n"); timeout_init(timeout, main_event_base); timeout->server = server; stats = (stats_t *) malloc(sizeof(stats_t)); stats->out_bytes = 0; stats->in_bytes = 0; stats->commands = 0; stats->operations = 0; server->stats = stats; timeout->stats = stats; // Initialise the risp system. risp = risp_init(); assert(risp != NULL); risp_add_invalid(risp, cmdInvalid); risp_add_command(risp, CMD_CLEAR, &cmdClear); risp_add_command(risp, CMD_EXECUTE, &cmdExecute); risp_add_command(risp, CMD_LIST, &cmdList); risp_add_command(risp, CMD_LISTING, &cmdListing); risp_add_command(risp, CMD_LISTING_DONE, &cmdListingDone); risp_add_command(risp, CMD_PUT, &cmdPut); risp_add_command(risp, CMD_GET, &cmdGet); risp_add_command(risp, CMD_SIZE, &cmdSize); risp_add_command(risp, CMD_OFFSET, &cmdOffset); risp_add_command(risp, CMD_FILE, &cmdFile); risp_add_command(risp, CMD_DATA, &cmdData); assert(server->risp == NULL); server->risp = risp; // enter the event loop. if (settings->verbose) printf("Starting Event Loop\n\n"); event_base_loop(main_event_base, 0); // cleanup risp library. risp_shutdown(risp); risp = NULL; // cleanup 'server', which should cleanup all the 'nodes' if (settings->verbose) printf("\n\nExiting.\n"); // remove the PID file if we're a daemon if (settings->daemonize && settings->pid_file != NULL) { if (settings->verbose) printf("Removing pid file: %s\n", settings->pid_file); remove_pidfile(settings->pid_file); } assert(settings != NULL); settings_cleanup(settings); settings = NULL; return 0; }
/* * Running in virtual memory, on the interrupt stack. * Does not return. Dispatches initial thread. * * Assumes that master_cpu is set. */ void setup_main(void) { thread_t startup_thread; printf_init(); panic_init(); sched_init(); vm_mem_bootstrap(); ipc_bootstrap(); vm_mem_init(); ipc_init(); /* * As soon as the virtual memory system is up, we record * that this CPU is using the kernel pmap. */ PMAP_ACTIVATE_KERNEL(master_cpu); init_timers(); timeout_init(); #if CDLI > 0 ns_init(); /* Initialize CDLI */ #endif /* CDLI > 0 */ dev_lookup_init(); timeout_init(); machine_init(); machine_info.max_cpus = NCPUS; machine_info.memory_size = mem_size; machine_info.avail_cpus = 0; machine_info.major_version = KERNEL_MAJOR_VERSION; machine_info.minor_version = KERNEL_MINOR_VERSION; #if XPR_DEBUG xprbootstrap(); #endif /* XPR_DEBUG */ /* * Initialize the IPC, task, and thread subsystems. */ clock_init(); utime_init(); ledger_init(); #if THREAD_SWAPPER thread_swapper_init(); #endif /* THREAD_SWAPPER */ #if TASK_SWAPPER task_swapper_init(); #endif /* TASK_SWAPPER */ task_init(); act_init(); thread_init(); subsystem_init(); #if TASK_SWAPPER task_swappable(&realhost, kernel_task, FALSE); #endif /* TASK_SWAPPER */ #if MACH_HOST pset_sys_init(); #endif /* MACH_HOST */ /* * Kick off the time-out driven routines by calling * them the first time. */ recompute_priorities(); compute_mach_factor(); /* * Initialize the Event Trace Analysis Package. * Dynamic Phase: 2 of 2 */ etap_init_phase2(); /* * Create a kernel thread to start the other kernel * threads. Thread_resume (from kernel_thread) calls * thread_setrun, which may look at current thread; * we must avoid this, since there is no current thread. */ /* * Create the thread, and point it at the routine. */ (void) thread_create_at(kernel_task, &startup_thread, start_kernel_threads); #if NCPUS > 1 && PARAGON860 thread_bind(startup_thread, cpu_to_processor(master_cpu)); #endif /* * Pretend it is already running, and resume it. * Since it looks as if it is running, thread_resume * will not try to put it on the run queues. * * We can do all of this without locking, because nothing * else is running yet. */ startup_thread->state |= TH_RUN; (void) thread_resume(startup_thread->top_act); /* * Start the thread. */ cpu_launch_first_thread(startup_thread); /*NOTREACHED*/ panic("cpu_launch_first_thread returns!"); }
int main(int argc, char **argv) { char *file; int i; int size_w = 0, size_h = 0; int head_only = 0; int page = 0; if (argc < 2) return -1; // file is ALWAYS first arg, other options come after file = argv[1]; for (i = 2; i < argc; i++) { if (!strcmp(argv[i], "-head")) // asked to only load header, not body/data head_only = 1; else if (!strcmp(argv[i], "-key")) { i++; page = atoi(argv[i]); i++; } else if (!strcmp(argv[i], "-opt-scale-down-by")) { // not used by ps loader i++; // int scale_down = atoi(argv[i]); } else if (!strcmp(argv[i], "-opt-dpi")) { i++; } else if (!strcmp(argv[i], "-opt-size")) { // not used by ps loader i++; size_w = atoi(argv[i]); i++; size_h = atoi(argv[i]); } } timeout_init(10); D("_gst_init_file\n"); if (!_gst_init(file)) return -1; D("_gst_init done\n"); if (!head_only) { _gst_load_image(size_w, size_h); } D("size...: %ix%i\n", width, height); D("alpha..: 0\n"); printf("size %i %i\n", width, height); printf("alpha 0\n"); if (!head_only) { if (shm_fd >= 0) { printf("shmfile %s\n", shmfile); } else { // could also to "tmpfile %s\n" like shmfile but just // a mmaped tmp file on the system printf("data\n"); fwrite(data, width * height * sizeof(DATA32), 1, stdout); } shm_free(); } else printf("done\n"); _gst_shutdown(); return 0; }
int check_intervals(struct intervals_cfg *cfg) { int i, err; int rv = 1; struct timeout *to; struct timeout *t = calloc(cfg->n_timeouts, sizeof(struct timeout)); unsigned *fired = calloc(cfg->n_timeouts, sizeof(unsigned)); struct timeouts *tos = timeouts_open(0, &err); timeout_t now = cfg->start_at; if (!t || !tos || !fired) FAIL(); timeouts_update(tos, now); for (i = 0; i < cfg->n_timeouts; ++i) { if (&t[i] != timeout_init(&t[i], TIMEOUT_INT)) FAIL(); if (timeout_pending(&t[i])) FAIL(); if (timeout_expired(&t[i])) FAIL(); timeouts_add(tos, &t[i], cfg->timeouts[i]); if (! timeout_pending(&t[i])) FAIL(); if (timeout_expired(&t[i])) FAIL(); } while (now < cfg->end_at) { timeout_t delay = timeouts_timeout(tos); if (cfg->skip && delay < cfg->skip) delay = cfg->skip; timeouts_step(tos, delay); now += delay; while (NULL != (to = timeouts_get(tos))) { i = to - &t[0]; assert(&t[i] == to); fired[i]++; if (0 != (to->expires - cfg->start_at) % cfg->timeouts[i]) FAIL(); if (to->expires <= now) FAIL(); if (to->expires > now + cfg->timeouts[i]) FAIL(); } if (!timeouts_check(tos, stderr)) FAIL(); } timeout_t duration = now - cfg->start_at; for (i = 0; i < cfg->n_timeouts; ++i) { if (cfg->skip) { if (fired[i] > duration / cfg->timeouts[i]) FAIL(); } else { if (fired[i] != duration / cfg->timeouts[i]) FAIL(); } if (!timeout_pending(&t[i])) FAIL(); } rv = 0; done: if (t) free(t); if (fired) free(fired); if (tos) free(tos); return rv; }
static int check_randomized(const struct rand_cfg *cfg) { #define FAIL() do { \ printf("Failure on line %d\n", __LINE__); \ goto done; \ } while (0) int i, err; int rv = 1; struct timeout *t = calloc(cfg->n_timeouts, sizeof(struct timeout)); timeout_t *timeouts = calloc(cfg->n_timeouts, sizeof(timeout_t)); uint8_t *fired = calloc(cfg->n_timeouts, sizeof(uint8_t)); uint8_t *found = calloc(cfg->n_timeouts, sizeof(uint8_t)); uint8_t *deleted = calloc(cfg->n_timeouts, sizeof(uint8_t)); struct timeouts *tos = timeouts_open(0, &err); timeout_t now = cfg->start_at; int n_added_pending = 0, cnt_added_pending = 0; int n_added_expired = 0, cnt_added_expired = 0; struct timeouts_it it_p, it_e, it_all; int p_done = 0, e_done = 0, all_done = 0; struct timeout *to = NULL; const int rel = cfg->relative; if (!t || !timeouts || !tos || !fired || !found || !deleted) FAIL(); timeouts_update(tos, cfg->start_at); for (i = 0; i < cfg->n_timeouts; ++i) { if (&t[i] != timeout_init(&t[i], rel ? 0 : TIMEOUT_ABS)) FAIL(); if (timeout_pending(&t[i])) FAIL(); if (timeout_expired(&t[i])) FAIL(); timeouts[i] = random_to(cfg->min_timeout, cfg->max_timeout); timeouts_add(tos, &t[i], timeouts[i] - (rel ? now : 0)); if (timeouts[i] <= cfg->start_at) { if (timeout_pending(&t[i])) FAIL(); if (! timeout_expired(&t[i])) FAIL(); ++n_added_expired; } else { if (! timeout_pending(&t[i])) FAIL(); if (timeout_expired(&t[i])) FAIL(); ++n_added_pending; } } if (!!n_added_pending != timeouts_pending(tos)) FAIL(); if (!!n_added_expired != timeouts_expired(tos)) FAIL(); /* Test foreach, interleaving a few iterators. */ TIMEOUTS_IT_INIT(&it_p, TIMEOUTS_PENDING); TIMEOUTS_IT_INIT(&it_e, TIMEOUTS_EXPIRED); TIMEOUTS_IT_INIT(&it_all, TIMEOUTS_ALL); while (! (p_done && e_done && all_done)) { if (!p_done) { to = timeouts_next(tos, &it_p); if (to) { i = to - &t[0]; ++found[i]; ++cnt_added_pending; } else { p_done = 1; } } if (!e_done) { to = timeouts_next(tos, &it_e); if (to) { i = to - &t[0]; ++found[i]; ++cnt_added_expired; } else { e_done = 1; } } if (!all_done) { to = timeouts_next(tos, &it_all); if (to) { i = to - &t[0]; ++found[i]; } else { all_done = 1; } } } for (i = 0; i < cfg->n_timeouts; ++i) { if (found[i] != 2) FAIL(); } if (cnt_added_expired != n_added_expired) FAIL(); if (cnt_added_pending != n_added_pending) FAIL(); while (NULL != (to = timeouts_get(tos))) { i = to - &t[0]; assert(&t[i] == to); if (timeouts[i] > cfg->start_at) FAIL(); /* shouldn't have happened yet */ --n_added_expired; /* drop expired timeouts. */ ++fired[i]; } if (n_added_expired != 0) FAIL(); while (now < cfg->end_at) { int n_fired_this_time = 0; timeout_t first_at = timeouts_timeout(tos) + now; timeout_t oldtime = now; timeout_t step = random_to(1, cfg->max_step); int another; now += step; if (rel) timeouts_step(tos, step); else timeouts_update(tos, now); for (i = 0; i < cfg->try_removing; ++i) { int idx = random() % cfg->n_timeouts; if (! fired[idx]) { timeout_del(&t[idx]); ++deleted[idx]; } } another = (timeouts_timeout(tos) == 0); while (NULL != (to = timeouts_get(tos))) { if (! another) FAIL(); /* Thought we saw the last one! */ i = to - &t[0]; assert(&t[i] == to); if (timeouts[i] > now) FAIL(); /* shouldn't have happened yet */ if (timeouts[i] <= oldtime) FAIL(); /* should have happened already */ if (timeouts[i] < first_at) FAIL(); /* first_at should've been earlier */ fired[i]++; n_fired_this_time++; another = (timeouts_timeout(tos) == 0); } if (n_fired_this_time && first_at > now) FAIL(); /* first_at should've been earlier */ if (another) FAIL(); /* Huh? We think there are more? */ if (!timeouts_check(tos, stderr)) FAIL(); } for (i = 0; i < cfg->n_timeouts; ++i) { if (fired[i] > 1) FAIL(); /* Nothing fired twice. */ if (timeouts[i] <= now) { if (!(fired[i] || deleted[i])) FAIL(); } else { if (fired[i]) FAIL(); } if (fired[i] && deleted[i]) FAIL(); if (cfg->finalize > 1) { if (!fired[i]) timeout_del(&t[i]); } } /* Now nothing more should fire between now and the end of time. */ if (cfg->finalize) { timeouts_update(tos, THE_END_OF_TIME); if (cfg->finalize > 1) { if (timeouts_get(tos)) FAIL(); TIMEOUTS_FOREACH(to, tos, TIMEOUTS_ALL) FAIL(); } } rv = 0; done: if (tos) timeouts_close(tos); if (t) free(t); if (timeouts) free(timeouts); if (fired) free(fired); if (found) free(found); if (deleted) free(deleted); return rv; }