int main(void)
{
	LCD_Init();
	LCD_LayerInit();

	SysTick_init ();

	pushbutton_init();

	/* Enable the LTDC */
	LTDC_Cmd(ENABLE);

	/* Set LCD foreground layer */
	LCD_SetLayer(LCD_FOREGROUND_LAYER);
	LCD_SetTransparency(0);

	/* Set LCD background layer */
	LCD_SetLayer(LCD_BACKGROUND_LAYER);

	/* LCD display message */
	LCD_Clear(LCD_COLOR_BLUE);
	LCD_SetBackColor(LCD_COLOR_BLUE);
	LCD_SetTextColor(LCD_COLOR_WHITE);

	std::stringstream output;
	std::string outputstring;
	const char * chararray;

	Timer mytimerobject(12,34,56);

	LCD_DisplayStringLine(LCD_LINE_0,(uint8_t*)"h_da    ");
	LCD_DisplayStringLine(LCD_LINE_1,(uint8_t*)"RZS     ");
	LCD_DisplayStringLine(LCD_LINE_2,(uint8_t*)"WS 15/16     ");

	STM_EVAL_LEDInit(LED3);
	STM_EVAL_LEDInit(LED4);

	// Super loop
	while(1)
	{
		switch(get_event()){

		case TICK:
			if(mystate==RUNNING)
				systick_count++;
			output.str(std::string());
			mytimerobject.setMin(systick_count/100/60);
			mytimerobject.setSec(systick_count/100);
			mytimerobject.setHun(systick_count/1);
			output << "Time " << mytimerobject.printtime();
			outputstring = "";
			outputstring = output.str();
			chararray = "";
			chararray = outputstring.c_str();
			LCD_DisplayStringLine(LCD_LINE_3,(uint8_t*) chararray);
			LCD_ClearLine(LCD_LINE_4);
			break;

		case START_STOP:
			LCD_DisplayStringLine(LCD_LINE_4,(uint8_t*) "START_STOP");

			if(mystate == RUNNING)
			{
				mystate = HALTED;
				LCD_ClearLine(LCD_LINE_5);
				LCD_DisplayStringLine(LCD_LINE_5,(uint8_t*) "HALTED");
			}
			else if(mystate == HALTED)
			{
				mystate = RUNNING;
				LCD_DisplayStringLine(LCD_LINE_5,(uint8_t*) "RUNNING");
			}
			break;

		default:
			break;
		}
	}
}
Example #2
0
int
parse_eis (uint8_t * eis, EIS * p)
{
  uint16_t section_length;
  uint16_t svid;
  uint16_t onid;
  uint16_t tsid;
  uint32_t crc;
  uint8_t version_number;
  uint8_t current_next;
  uint8_t section_number;
  uint8_t last_section_number;
  uint8_t segment_last_section_number;
  uint8_t last_table_id;
  SizeStack s;
  uint8_t *ptr;
  int i, j, k;


  if (sizeStackInit (&s, eis) || sizeStackPush (&s, MAX_SEC_SIZE))      //maximum section size
    return 1;

  if (sizeStackAdvance (&s, 1, 2))
    return 1;
  ptr = sizeStackPtr (&s);
  section_length = bitsGet (ptr, 0, 4, 12);

  if (sizeStackAdvance (&s, 2, 1))
    return 1;

  if (sizeStackPush (&s, section_length))
    return 1;

  if (sizeStackAdvance (&s, 0, 11))
    return 1;

  ptr = sizeStackPtr (&s);

  svid = bitsGet (ptr, 0, 0, 16);
  version_number = bitsGet (ptr, 2, 2, 5);
  current_next = bitsGet (ptr, 2, 7, 1);
  section_number = ptr[3];
  last_section_number = ptr[4];
  tsid = bitsGet (ptr, 5, 0, 16);
  onid = bitsGet (ptr, 7, 0, 16);
  segment_last_section_number = ptr[9];
  last_table_id = ptr[10];
  debugPri (1,
            "EIS: svid: %u, tsid: %u, onid: %u, slast: %u lastid: %u ver: %u, cur/nxt: %u, secnr: %u, lastnr: %u\n",
            svid, tsid, onid, segment_last_section_number, last_table_id,
            version_number, current_next, section_number,
            last_section_number);

  if (sizeStackAdvance (&s, 11, 0))
    return 1;
  ptr = sizeStackPtr (&s);

  section_length -= 11 + 4;     //header+crc
  //count number of event blocks
  p->num_events = 0;
  i = section_length;
  j = 0;
  k = 0;
  while (i > 0)
  {
    j += 10;
    k = bitsGet (ptr, j, 4, 12) + 2;    //descriptor_loop_length
    j += k;
    i -= 10;
    i -= k;
    p->num_events++;
  }
  if (!p->num_events)
  {
    debugPri (1, "num_events=0\n");
    p->events = NULL;
    return 1;
  }
  p->events = utlCalloc (p->num_events, sizeof (EVT));
  if (!p->events)
    return 1;
  i = 0;
  while (p->num_events > i)
  {
    if (get_event (&s, &(p->events[i])))
    {
      while (i--)
      {
        evtClear (&(p->events[i]));
      }
      utlFAN (p->events);
      return 1;
    }
    i++;
  }
  sizeStackPop (&s);
  if (sizeStackAdvance (&s, 0, 4))
  {
    while (i--)
    {
      evtClear (&(p->events[i]));
    }
    utlFAN (p->events);
    debugPri (1, "bound error\n");
    return 1;
  }
  ptr = sizeStackPtr (&s);
  crc = bitsGet (ptr, 0, 0, 32);
  debugPri (1, "CRC: 0x%X\n", crc);
  sizeStackPop (&s);
  p->svc_id = svid;
  p->onid = onid;
  p->tsid = tsid;
  p->segment_last_section_number = segment_last_section_number;
  p->last_table_id = last_table_id;
  p->type = eis[0];
  p->c.version = version_number;
  p->c.current = current_next;
  p->c.section = section_number;
  p->c.last_section = last_section_number;
  return 0;
}
Example #3
0
int main() {
    int what_next, nodes_n, tracks_n, courses_n, entrants_n;
    //print title for the program
    printf("       __  ___   ____     _   __    ____  ______   ____     ____ \n");
    printf("      /  |/  /  / __ )   / | / /   /  _/ /_  __/  / __ (   / _  ( \n");
    printf("     / /|_/ /  / / / /  /  |/ /    / /    / /    / / / /  / /_/ / \n");
    printf("    / /  / /  / /_/ /  / /|  /   _/ /    / /    / /_/ /  / _, _/ \n");
    printf("   /_/  /_/   (____/  /_/ |_/   /___/   /_/     (____/  /_/ |_| \n\n\n");

    /*Set up arrays of structures for each of the groups of data, then pass these
     to the data functions which read in the information from the text files. 
     Populate the structs there.
     
     For the event structure, simply pass a pointer to the structure. */
    struct Event event_name;
    get_event(&event_name);

    struct Node nodes[30];
    nodes_n = get_nodes(nodes);

    struct Track tracks[30];
    tracks_n = get_tracks(tracks);

    struct Course courses[26];
    courses_n = get_courses(courses);

    struct Record entrants[30];
    entrants_n = get_entrants(entrants, courses, courses_n);

    //print the event information out
    printf("Welcome to system developed for:\n");
    printf("    %s\n", event_name.event);
    printf("    %s\n", event_name.date);
    printf("    %s\n\n", event_name.time);

    do {
        printf("       ******************************************************\n");
        printf("       *                                                    *\n");
        printf("       *             Please Select An Option:               *\n");
        printf("       *----------------------------------------------------*\n");
        printf("       * %2d.Locate Competitor                               *\n", LOCATE_COMPETITOR);
        printf("       * %2d.Count Competitors That Have Not Started         *\n", NOT_STARTED);
        printf("       * %2d.Count Competitors On Course                     *\n", ON_COURSE);
        printf("       * %2d.Count Competitors Finished                      *\n", HAVE_FINISHED);
        printf("       * %2d.Manually Supply Times                           *\n", MANUALLY_SUPPLY);
        printf("       * %2d.Supply Checkpoint Files                         *\n", CHECKPOINT);
        printf("       * %2d.Print Results                                   *\n", RESULTS_LIST);
        printf("       *----------------------------------------------------*\n");
        printf("       * %2d.Quit                                            *\n", QUIT);
        printf("       ******************************************************\n");
        scanf("%d", &what_next);
        //print out the options, using the header file options

        /* based on the user's choice, do what they want */

        switch (what_next) {
            case LOCATE_COMPETITOR: /*Check user input to check if
                                                 the entrant number actually 
                                                 exists*/
                printf("\nPlease Input Competitor Number: ");
                int comp;
                scanf("%d", &comp);
                while (comp > entrants_n || comp < 1) {
                    printf("\nInvalid Competitor Number. Try Again: ");
                    scanf("%d", &comp);
                } /* pass in the structure argument to the function, along
                         the selected entrant number*/
                locate_competitor(entrants, comp);
                printf("Type 'c' to continue..."); /* once complete, get the 
                                                       user to type 'c' to 
                                                       continue. then create
                                                       line space.*/
                while (getchar() != 'c') {
                }
                printf("\n\n\n\n\n\n\n\n");
                break;
            case NOT_STARTED:
                count_competitors_not_started(entrants, entrants_n);
                printf("Type 'c' to continue...");
                while (getchar() != 'c') {
                }
                printf("\n\n\n\n\n\n\n\n");
                break;
            case ON_COURSE:
                count_competitors_started(entrants, entrants_n);
                printf("Type 'c' to continue...");
                while (getchar() != 'c') {
                }
                printf("\n\n\n\n\n\n\n\n");
                break;
            case HAVE_FINISHED:
                count_competitors_finished(entrants, entrants_n);
                printf("Type 'c' to continue...");
                while (getchar() != 'c') {
                }
                printf("\n\n\n\n\n\n\n\n");
                break;
            case MANUALLY_SUPPLY:
                printf("\nPlease Input Competitor Number: ");
                scanf("%d", &comp);
                while (comp > entrants_n || comp < 1) {
                    printf("\nInvalid Competitor Number. Try Again: ");
                    scanf("%d", &comp);
                }
                if (entrants[comp].excluded == 0) {
                    supply_manually(entrants, comp, nodes, tracks, tracks_n);
                } else {
                    printf("Sorry, Competitor Excluded.\n");
                }
                printf("Type 'c' to continue...");
                while (getchar() != 'c') {
                }
                printf("\n\n\n\n\n\n\n\n");
                break;
            case CHECKPOINT:
                supply_checkpoints(entrants, nodes, nodes_n, tracks, tracks_n);
                printf("Type 'c' to continue...");
                while (getchar() != 'c') {
                }
                printf("\n\n\n\n\n\n\n\n");
                break;
            case RESULTS_LIST:
                print_results(entrants, entrants_n);
                printf("Type 'c' to continue...");
                while (getchar() != 'c') {
                }
                printf("\n\n\n\n\n\n\n\n");
                break;
            case QUIT:
                break;
            default: // if the user does not type a number from the list
                printf("Incorrect Input\n\n"); // inform them, and loop.
                break;
        }
    } while (what_next != QUIT);



    return (EXIT_SUCCESS);
}
Example #4
0
APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset,
                                           apr_interval_time_t timeout,
                                           apr_int32_t *num,
                                           const apr_pollfd_t **descriptors)
{
    apr_os_sock_t fd;
    int ret, i;
    unsigned int nget;
    pfd_elem_t *ep;
    struct timespec tv, *tvptr;
    apr_status_t rv = APR_SUCCESS;

    if (timeout < 0) {
        tvptr = NULL;
    }
    else {
        tv.tv_sec = (long) apr_time_sec(timeout);
        tv.tv_nsec = (long) apr_time_msec(timeout);
        tvptr = &tv;
    }

    nget = 1;

    pollset_lock_rings();

    while (!APR_RING_EMPTY(&(pollset->add_ring), pfd_elem_t, link)) {
        ep = APR_RING_FIRST(&(pollset->add_ring));
        APR_RING_REMOVE(ep, link);

        if (ep->pfd.desc_type == APR_POLL_SOCKET) {
            fd = ep->pfd.desc.s->socketdes;
        }
        else {
            fd = ep->pfd.desc.f->filedes;
        }

        port_associate(pollset->port_fd, PORT_SOURCE_FD, 
                           fd, get_event(ep->pfd.reqevents), ep);

        APR_RING_INSERT_TAIL(&(pollset->query_ring), ep, pfd_elem_t, link);

    }

    pollset_unlock_rings();

    ret = port_getn(pollset->port_fd, pollset->port_set, pollset->nalloc,
                    &nget, tvptr);

    (*num) = nget;

    if (ret == -1) {
        (*num) = 0;
        if (errno == ETIME || errno == EINTR) {
            rv = APR_TIMEUP;
        }
        else {
            rv = APR_EGENERAL;
        }
    }
    else if (nget == 0) {
        rv = APR_TIMEUP;
    }
    else {

        pollset_lock_rings();

        for (i = 0; i < nget; i++) {
            pollset->result_set[i] =
                (((pfd_elem_t*)(pollset->port_set[i].portev_user))->pfd);
            pollset->result_set[i].rtnevents =
                get_revent(pollset->port_set[i].portev_events);

            APR_RING_REMOVE((pfd_elem_t*)pollset->port_set[i].portev_user, link);

            APR_RING_INSERT_TAIL(&(pollset->add_ring), 
                                 (pfd_elem_t*)pollset->port_set[i].portev_user,
                                 pfd_elem_t, link);
        }

        pollset_unlock_rings();

        if (descriptors) {
            *descriptors = pollset->result_set;
        }
    }


    pollset_lock_rings();

    /* Shift all PFDs in the Dead Ring to be Free Ring */
    APR_RING_CONCAT(&(pollset->free_ring), &(pollset->dead_ring), pfd_elem_t, link);

    pollset_unlock_rings();

    return rv;
}
Example #5
0
void add_interupt_event(int type, unsigned int delay)
{
#ifdef NEW_COUNT
	unsigned int count = ((Count + delay) & 0x0FFFFFFF);
#else
    unsigned int count = Count + delay/**2*/;
#endif
#ifdef USE_SPECIAL
    int special = 0;
#endif
    interupt_queue *aux = q;

#ifdef USE_SPECIAL
    if(type == SPECIAL_INT /*|| type == COMPARE_INT*/) special = 1;
	if(Count > 0x80000000) SPECIAL_done = 0;
#endif

	DEBUG_PRINT("add_interupt_event() type %d, at %u, Count %u\n",type,count, Count);

    if (get_event(type)) {
        DebugMessage(M64MSG_WARNING, "two events of type 0x%x in interrupt queue", type);
    }
   
    if (q == NULL)
    {
        q = (interupt_queue *) queue_malloc(sizeof(interupt_queue));
        q->next = NULL;
        q->count = count;
        q->type = type;
        next_interupt = q->count;
        //print_queue();
        return;
    }
   
#ifdef USE_SPECIAL
    if(before_event(count, q->count, q->type) && !special)
#else
	if(before_event(count, q->count, q->type))
#endif
    {
        q = (interupt_queue *) queue_malloc(sizeof(interupt_queue));
        q->next = aux;
        q->count = count;
        q->type = type;
        next_interupt = q->count;
        //print_queue();
        return;
    }
   
//if not at end of list and (count is after next item of type or special) then get next
#ifdef USE_SPECIAL
    while (aux->next != NULL && (!before_event(count, aux->next->count, aux->next->type) || special))
#else
    while (aux->next != NULL && (!before_event(count, aux->next->count, aux->next->type)))
#endif
    {
		aux = aux->next;
	}   

    if (aux->next == NULL)
    {
        aux->next = (interupt_queue *) queue_malloc(sizeof(interupt_queue));
        aux = aux->next;
        aux->next = NULL;
        aux->count = count;
        aux->type = type;
    }
    else
    {
        interupt_queue *aux2;
#ifdef USE_SPECIAL
        if (type != SPECIAL_INT)
#endif
            while(aux->next != NULL && aux->next->count == count)
                aux = aux->next;
        aux2 = aux->next;
        aux->next = (interupt_queue *) queue_malloc(sizeof(interupt_queue));
        aux = aux->next;
        aux->next = aux2;
        aux->count = count;
        aux->type = type;
    }
}
Example #6
0
int main(int n, char **v)
{
  extern int volatile gui_logd;
  char *database_filename = NULL;
  void *database;
  char *ip = DEFAULT_REMOTE_IP;
  int port = DEFAULT_REMOTE_PORT;
  char **on_off_name;
  int *on_off_action;
  int on_off_n = 0;
  int *is_on;
  int number_of_events;
  int i;
  event_handler *h;
  gui *g;
  vcd_data vcd_data;

  /* write on a socket fails if the other end is closed and we get SIGPIPE */
  if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) abort();

  on_off_name = malloc(n * sizeof(char *)); if (on_off_name == NULL) abort();
  on_off_action = malloc(n * sizeof(int)); if (on_off_action == NULL) abort();

  for (i = 1; i < n; i++) {
    if (!strcmp(v[i], "-h") || !strcmp(v[i], "--help")) usage();
    if (!strcmp(v[i], "-d"))
      { if (i > n-2) usage(); database_filename = v[++i]; continue; }
    if (!strcmp(v[i], "-ip")) { if (i > n-2) usage(); ip = v[++i]; continue; }
    if (!strcmp(v[i], "-p"))
      { if (i > n-2) usage(); port = atoi(v[++i]); continue; }
    if (!strcmp(v[i], "-on")) { if (i > n-2) usage();
      on_off_name[on_off_n]=v[++i]; on_off_action[on_off_n++]=1; continue; }
    if (!strcmp(v[i], "-off")) { if (i > n-2) usage();
      on_off_name[on_off_n]=v[++i]; on_off_action[on_off_n++]=0; continue; }
    if (!strcmp(v[i], "-ON"))
      { on_off_name[on_off_n]=NULL; on_off_action[on_off_n++]=1; continue; }
    if (!strcmp(v[i], "-OFF"))
      { on_off_name[on_off_n]=NULL; on_off_action[on_off_n++]=0; continue; }
    if (!strcmp(v[i], "-debug-gui")) { gui_logd = 1; continue; }
    usage();
  }

  if (database_filename == NULL) {
    printf("ERROR: provide a database file (-d)\n");
    exit(1);
  }

  database = parse_database(database_filename);

  load_config_file(database_filename);

  number_of_events = number_of_ids(database);
  is_on = calloc(number_of_events, sizeof(int));
  if (is_on == NULL) abort();

  h = new_handler(database);

  g = gui_init();
  new_thread(gui_thread, g);

  vcd_main_gui(g, h, database);

  on_off(database, "VCD_FUNCTION", is_on, 1);

  for (i = 0; i < on_off_n; i++)
    on_off(database, on_off_name[i], is_on, on_off_action[i]);

  vcd_data.socket = -1;
  vcd_data.is_on = is_on;
  vcd_data.nevents = number_of_events;
  if (pthread_mutex_init(&vcd_data.lock, NULL)) abort();
  setup_event_selector(g, database, is_on, is_on_changed, &vcd_data);

  vcd_data.socket = connect_to(ip, port);

  /* send the first message - activate selected traces */
  is_on_changed(&vcd_data);

  /* read messages */
  while (1) {
    char v[T_BUFFER_MAX];
    event e;
    e = get_event(vcd_data.socket, v, database);
    if (e.type == -1) abort();
    handle_event(h, e);
  }

  return 0;
}
Example #7
0
void gen_interupt()
{
  if (stop == 1) {
    dyna_stop();
  }

  if (savestates_job & LOADSTATE) {
    savestates_load();
    savestates_job &= ~LOADSTATE;
    return;
  }
  if (skip_jump) {
    if (q->count > Count || (Count - q->count) < 0x80000000) {
      next_interupt = q->count;
    }
    else {
      next_interupt = 0;
    }
    interp_addr = skip_jump;
    last_addr = interp_addr;
    skip_jump=0;
    return;
  } 

  switch(q->type) {
    case SPECIAL_INT:
      if (Count > 0x10000000) {
        return;
      }
      remove_interupt_event();
      add_interupt_event_count(SPECIAL_INT, 0);
      return;
    break;
    case VI_INT:
      updateScreen();
#ifdef PROFILE
      refresh_stat();
#endif
      new_vi();
      vi_register.vi_delay = (vi_register.vi_v_sync == 0) ? 500000 : ((vi_register.vi_v_sync + 1)*1500);
      next_vi += vi_register.vi_delay;
      vi_field = (vi_register.vi_status&0x40) ? 1-vi_field : 0; 
      remove_interupt_event();
      add_interupt_event_count(VI_INT, next_vi);
  
      MI_register.mi_intr_reg |= 0x08;
      if(!chk_status(1)) {
        return;
      }
    break;
  
    case COMPARE_INT:
      remove_interupt_event();
      Count+=2;
      add_interupt_event_count(COMPARE_INT, Compare);
      Count-=2;
  
      Cause = (Cause | 0x8000) & 0xFFFFFF83;
      if(!chk_status(0)) {
        return;
      }
    break;
  
    case CHECK_INT:
      remove_interupt_event();
    break;
  
    case SI_INT:
      PIF_RAMb[0x3F] = 0x0;
      remove_interupt_event();
      MI_register.mi_intr_reg |= 0x02;
      si_register.si_status |= 0x1000;
      if(!chk_status(1)) {
        return;
      }
    break;
  
    case PI_INT:
      remove_interupt_event();
      MI_register.mi_intr_reg |= 0x10;
      pi_register.read_pi_status_reg &= ~3;
      if(!chk_status(1)) {
        return;
      }
    break;
  
    case AI_INT:
      if (ai_register.ai_status & 0x80000000) { // full
        unsigned long ai_event = get_event(AI_INT);
        remove_interupt_event();
        ai_register.ai_status &= ~0x80000000;
        ai_register.current_delay = ai_register.next_delay;
        ai_register.current_len = ai_register.next_len;
        add_interupt_event_count(AI_INT, ai_event+ai_register.next_delay);
      }
      else {
        remove_interupt_event();
        ai_register.ai_status &= ~0x40000000;
      }
      MI_register.mi_intr_reg |= 0x04;
      if(!chk_status(1)) {
        return;
      }
    break;

    default:
      remove_interupt_event();
    break;
  }
  exception_general();
   
  if (savestates_job & SAVESTATE) {
    savestates_save();
    savestates_job &= ~SAVESTATE;
  }
}
Example #8
0
int main (int argc, char **argv)
{
    int ret = 0;
    version_info ();
    if (argc < 2)
    {
        dt_info ("", " no enough args\n");
        show_usage ();
        return 0;
    }
    memset(&ply_ctx,0,sizeof(ply_ctx_t));
    ply_ctx.disp_width = 720;
    ply_ctx.disp_height = 480;

    player_register_all();
    register_ex_all();

    dtplayer_para_t para;
    parse_cmd(argc,argv,&para);
    
    void *player_priv = dtplayer_init (&para);
    if (!player_priv)
        return -1;

    //get media info
	dt_media_info_t info;
	ret = dtplayer_get_mediainfo(player_priv, &info);
	if(ret < 0)
	{
		dt_info(TAG,"Get mediainfo failed, quit \n");
		return -1;
	}
	dt_info(TAG,"Get Media Info Ok,filesize:%lld fulltime:%lld S \n",info.file_size,info.duration);

    //set display win size
    int width = 720;
    int height = 480;
    if(info.has_video)
    {
        vstream_info_t *vstream = info.vstreams[0];
        width = vstream->width;
        height = vstream->height;
    }
    if(width <= 0 || width > 1280)
        width = 720;
    if(height <= 0 || height >720)
        height = 480;

    dtplayer_set_video_size(player_priv, width, height);

    ui_init(width,height); 
    render_init();

	dtplayer_start (player_priv);

    //event handle
    player_event_t event = EVENT_NONE;
    int arg = -1;
    while(1)
    {
        if(ply_ctx.exit_flag == 1)
            break;
        event = get_event(&arg,&ply_ctx);
        if(event == EVENT_NONE)
        {
            usleep(100);
            continue;
        }
        
        switch(event)
        {
            case EVENT_PAUSE:
                dtplayer_pause (player_priv);
                break;
            case EVENT_RESUME:
                dtplayer_resume (player_priv);
                break;
            case EVENT_SEEK:
                dtplayer_seekto (player_priv, arg);
                break;
            case EVENT_STOP:
                dtplayer_stop (player_priv);
                goto QUIT_CHECK;
                break;
            default:
                dt_info(TAG,"UNKOWN CMD, IGNORE \n");
                break;
        }

    }
QUIT_CHECK:
    while(!ply_ctx.exit_flag)
    {
        usleep(100);
        break;
    }
    render_stop();
    ui_stop(); 
    dt_info ("", "QUIT DTPLAYER-TEST\n");
    return 0;
}
Example #9
0
/*----------------------------------------------*/
VOID event_loop( VOID )
{
	T_SYS_EVENT t_sys_event = E_EVENT_IDLE;
	T_SYS_EVENT_TBL *pt_sys_event_tbl;
	UINT ui_loopnum;

#ifdef CO_ENABLE_EVENT_TRACE_LOG
	Usart_Set_Stderr();
#endif

	while( 1 ) {
//#ifdef CO_ENABLE_EVENT_TRACE_LOG
//	fprintf_P( stderr, PSTR( "wait next event\n") );
//#endif

#ifdef CO_ENABLE_I2C_SLAVE_READ
	if( t_sys_event == E_EVENT_I2C_SLAVE_READ ) {
		i2c_slave_read_event_finish();
	}
#endif

#ifdef CO_SLEEP_ENABLE
		sleep_cpu();
#endif

		t_sys_event = get_event();

//#ifdef CO_ENABLE_EVENT_TRACE_LOG
//		fprintf_P( stderr, PSTR( "recv event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
//#endif

#ifdef CO_SLEEP_ENABLE
		// すべての割り込みハンドラ内でsleep_disable()を実施している。
		// そうすることで、ループ先頭のsleep_enable()~ループ終端のsleep()までの間に割り込みが
		// 発生してもsleep()しなくなる。
		// sleep()するのは、sleep_enable()~sleep()までの間に割り込みが一度も発生しない場合のみとなる。
		cli();
		sleep_enable();
		sei();
#endif

#ifdef CO_ENABLE_EVENT_TRACE_LOG
		if( t_sys_event != E_EVENT_IDLE ) {
			fprintf_P( stderr, PSTR( "begin event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
		}
#endif

		/* TODO:ステータスチェンジはgo_sys_stat()でやれば良い */
		pt_sys_event_tbl = NULL;
		for( ui_loopnum = 0; gt_sys_stat_tbl[ui_loopnum].pt_sys_event_tbl != NULL; ui_loopnum++ ) {
			if( gt_sys_stat_tbl[ui_loopnum].t_sys_stat == _gt_sys_stat ) {
				pt_sys_event_tbl = gt_sys_stat_tbl[ui_loopnum].pt_sys_event_tbl;
				break;
			}
		}
		if( pt_sys_event_tbl == NULL ) {
#ifdef CO_ENABLE_EVENT_TRACE_LOG
			fprintf_P( stderr, PSTR("unknown sys stat event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
#endif
			continue;
		}


		for( ui_loopnum = 0; pt_sys_event_tbl[ui_loopnum].fn_hdl != NULL; ui_loopnum++ ) {
			if( pt_sys_event_tbl[ui_loopnum].t_sys_event == t_sys_event ) {
#ifdef CO_ENABLE_EVENT_TRACE_LOG
				int i_ret = pt_sys_event_tbl[ui_loopnum].fn_hdl();
				if( i_ret != 0 ) {
					fprintf_P( stderr, PSTR("event handler error returned, ret=%d\n"), i_ret );
				}
#else
				(VOID)pt_sys_event_tbl[ui_loopnum].fn_hdl();
#endif
				break;
			}
		}
		if( pt_sys_event_tbl[ui_loopnum].fn_hdl == NULL ) {
#ifdef CO_ENABLE_EVENT_TRACE_LOG
			fprintf_P( stderr, PSTR("unknown sys event event=%u, stat=%u\n"), t_sys_event, _gt_sys_stat );
#endif
			continue;
		}


#ifdef CO_ENABLE_EVENT_TRACE_LOG
		if( t_sys_event != E_EVENT_IDLE ) {
			fprintf_P( stderr, PSTR("return event loop stat=%u\n\n"), _gt_sys_stat );
		}
#endif
	}
}
void mm_one_queue_simulator_with_initail_bias(long nr_customer, double average_interarrival_time, double average_service_time, long *next_seed_interarrival, long *next_seed_service, struct mm_one_simulation_result *result, long initial_bias) {
  struct event *event_list = NULL;
  struct queue system_queue;
  enum server_state server_state = IDLE;
  double system_clock = 0.0;
  struct event *event;

  enum event_type event_type;
  int customer_number = 0;
  double clock_time;
  double arrival_time;
  double interarrival_time;
  double departure_time;
  double service_time;

  struct customer *customer;

  double lamda_interarrival_rate = 1.0 / average_interarrival_time; /* interarrival rate: lamda = 1 / average_time */
  double mu_service_rate = 1.0 / average_service_time; /* service_rate: mu = 1 / arverage_service_time */

  double total_customer_in_system_time = 0.0; 
  /* initial system */
  init_queue(&system_queue);

  /* step 0: initial first event and add into event list */
#ifdef DEBUG
  printf("Info: simulation starts.\n");
#endif
  if (customer_number < nr_customer) {
    event_type = ARRIVAL;
    clock_time = 1.0;
    customer = init_customer(customer_number);
    customer->arrival_time = clock_time;
    customer_number++;
    add_event(&event_list, event_type, clock_time, (void *) customer);
  }
  /* step 1: pop event from event list */
  event = get_event(event_list);
  while (event) {
    /* step 2: addvance clock */
    system_clock = event->clock_time;
    pop_event(&event_list);
    /* get customer */
    customer = (struct customer *) event->content;
    event->content = NULL;
    switch (event->event_type) {
      case ARRIVAL:
#ifdef DEBUG
        /* print info */
        printf("Info: [time: %12f] [customer: %8d] event: ARRIVAL\n", system_clock, customer->no);
#endif
        /* generate service time */
        service_time = exponential_random_generator(mu_service_rate, next_seed_service);
        add_service_time_to_customer(customer, service_time);
        /* step 3: update state */
        if (server_state == IDLE) {
          server_state = BUSY;
          /* set service time and departure time */
          service_time = customer->service_time;
          departure_time = system_clock + service_time;
          event_type = DEPARTURE;
          customer->departure_time = departure_time;
          add_event(&event_list, event_type, departure_time, (void *) customer);
        } else if (server_state == BUSY) {
          /* add customer into queue */
          enqueue(&system_queue, (void *) customer);
        }
        /* step 4: generate future event into event list */
        /* if customer_number < nr_customer, generate next arrival event */
        if (customer_number < nr_customer) {
          interarrival_time = exponential_random_generator(lamda_interarrival_rate, next_seed_interarrival);
          arrival_time = system_clock + interarrival_time;
          event_type = ARRIVAL;
          customer = init_customer(customer_number);
          customer->arrival_time = arrival_time;
          customer_number++;
          add_event(&event_list, event_type, arrival_time, (void *) customer);
        }
     
        break;
      case DEPARTURE:
#ifdef DEBUG
        /* print info */
        printf("Info: [time: %12f] --------------------------------------- [customer: %8d] event: DEPARTURE\n", system_clock, customer->no);
#endif
        /* store each customer's system time in result */
        if (result && result->customer_in_system_time) {
          result->customer_in_system_time[customer->no] = customer->departure_time - customer->arrival_time;
        }

        /* initial bias */
        if (customer->no >= initial_bias) {
          total_customer_in_system_time += customer->departure_time - customer->arrival_time;
        }

        free(customer);
        customer = NULL;
        /* step 3: update state */
        if (system_queue.count > 0) {
          customer = (struct customer *) dequeue(&system_queue);
          /* set service time and departure time */
          service_time = get_service_time_from_customer(customer);
          departure_time = system_clock + service_time;
          event_type = DEPARTURE;
          customer->departure_time = departure_time;
          add_event(&event_list, event_type, departure_time, (void *) customer);
        } else if (system_queue.count == 0) {
          server_state = IDLE;
        }

        /* step 4: generate future event into event list */
        break;
      default:
        fprintf(stderr, "Error: unkown event type.\n");
        exit(EXIT_FAILURE);
    }
    free(event);
    event = NULL;

    /* get next event */
    event = get_event(event_list);
  }
  if (result) {
    result->average_customer_in_system_time = total_customer_in_system_time / (nr_customer - initial_bias);
#ifdef DEBUG
    printf("Info: average time of a customer in system: %12f\n", result->average_customer_in_system_time);
#endif
  }
#ifdef DEBUG
  printf("Info: event list is empty.\n");
  printf("Info: simulation ends.\n");
#endif
}
void mm_one_queue_simulator_for_batch_means(long nr_customer, double average_interarrival_time, double average_service_time, long *next_seed_interarrival, long *next_seed_service, long nr_batch, long batch_size, long initial_bias, double correlation_bound, double half_alpha, double eps_relative, struct batch_means_output *result) {
  struct event *event_list = NULL;
  struct queue system_queue;
  enum server_state server_state = IDLE;
  double system_clock = 0.0;
  struct event *event;

  enum event_type event_type;
  int customer_number = 0;
  double clock_time;
  double arrival_time;
  double interarrival_time;
  double departure_time;
  double service_time;

  struct customer *customer;

  double lamda_interarrival_rate = 1.0 / average_interarrival_time; /* interarrival rate: lamda = 1 / average_time */
  double mu_service_rate = 1.0 / average_service_time; /* service_rate: mu = 1 / arverage_service_time */

  double total_customer_in_system_time = 0.0; 

  /* for batch means */
  double *batch_mean;
  batch_mean = malloc(nr_batch * sizeof(double));
  memset(batch_mean, 0, nr_batch * sizeof(double));
  double *batch_sum;
  batch_sum = malloc(nr_batch * sizeof(double));
  memset(batch_sum, 0, nr_batch * sizeof(double));

  double lag_1_corr;
  double t; /* student t distribution */
  double dev;
  double avg;
  double ci_hw;
  double ci_hb;
  long batch_index;
  int i;

  /* initial system */
  init_queue(&system_queue);

  /* step 0: initial first event and add into event list */
#ifdef DEBUG
  printf("Info: simulation starts.\n");
#endif
  if (customer_number < nr_customer) {
    event_type = ARRIVAL;
    clock_time = 1.0;
    customer = init_customer(customer_number);
    customer->arrival_time = clock_time;
    customer_number++;
    add_event(&event_list, event_type, clock_time, (void *) customer);
  }
  /* step 1: pop event from event list */
  event = get_event(event_list);
  while (event) {
    /* step 2: addvance clock */
    system_clock = event->clock_time;
    pop_event(&event_list);
    /* get customer */
    customer = (struct customer *) event->content;
    event->content = NULL;
    switch (event->event_type) {
      case ARRIVAL:
#ifdef DEBUG
        /* print info */
        printf("Info: [time: %12f] [customer: %8d] event: ARRIVAL\n", system_clock, customer->no);
#endif
        /* generate service time */
        service_time = exponential_random_generator(mu_service_rate, next_seed_service);
        add_service_time_to_customer(customer, service_time);
        /* step 3: update state */
        if (server_state == IDLE) {
          server_state = BUSY;
          /* set service time and departure time */
          service_time = customer->service_time;
          departure_time = system_clock + service_time;
          event_type = DEPARTURE;
          customer->departure_time = departure_time;
          add_event(&event_list, event_type, departure_time, (void *) customer);
        } else if (server_state == BUSY) {
          /* add customer into queue */
          enqueue(&system_queue, (void *) customer);
        }
        /* step 4: generate future event into event list */
        /* if customer_number < nr_customer, generate next arrival event */
        if (customer_number < nr_customer) {
          interarrival_time = exponential_random_generator(lamda_interarrival_rate, next_seed_interarrival);
          arrival_time = system_clock + interarrival_time;
          event_type = ARRIVAL;
          customer = init_customer(customer_number);
          customer->arrival_time = arrival_time;
          customer_number++;
          add_event(&event_list, event_type, arrival_time, (void *) customer);
        }
     
        break;
      case DEPARTURE:
#ifdef DEBUG
        /* print info */
        printf("Info: [time: %12f] --------------------------------------- [customer: %8d] event: DEPARTURE\n", system_clock, customer->no);
#endif
        if (customer->no >= (initial_bias + nr_batch * batch_size)) {
          for (i = 0; i < nr_batch; i++) {
            batch_mean[i] = batch_sum[i] / batch_size;
          }
          /* check correlation */
          lag_1_corr = sample_lag1_corr_sequence(batch_mean, nr_batch);
          if (fabs(lag_1_corr) < correlation_bound) {
            /* check confidence interval */
            t = gsl_cdf_tdist_Pinv(1.0-half_alpha, nr_batch - 1); 
            avg = avg_sequence(batch_mean, nr_batch);
            dev = dev_sequence(batch_mean, nr_batch);
            ci_hw = t * dev / sqrt((double) nr_batch);
            ci_hb = avg * eps_relative;
            if (ci_hw < ci_hb) {
              if (result) {
                result->avg = avg;
                result->ci_hw = ci_hw;
                result->lag_1 = lag_1_corr;
              }
              return;
            }
          }
          /* not satisfy constraint, double batch_size */
          batch_size *= 2;
          for (i = 0; i < nr_batch / 2; i++) {
            batch_sum[i] = batch_sum[i*2] + batch_sum[i*2+1];
          }
          for (i = nr_batch / 2; i < nr_batch; i++) {
            batch_sum[i] = 0.0;
          }
        }
        if (customer->no >= initial_bias) {
          batch_index = (customer->no - initial_bias) / batch_size;
          batch_sum[batch_index] += customer->departure_time - customer->arrival_time;
          total_customer_in_system_time += customer->departure_time - customer->arrival_time;
        }
        free(customer);
        customer = NULL;
        /* step 3: update state */
        if (system_queue.count > 0) {
          customer = (struct customer *) dequeue(&system_queue);
          /* set service time and departure time */
          service_time = get_service_time_from_customer(customer);
          departure_time = system_clock + service_time;
          event_type = DEPARTURE;
          customer->departure_time = departure_time;
          add_event(&event_list, event_type, departure_time, (void *) customer);
        } else if (system_queue.count == 0) {
          server_state = IDLE;
        }

        /* step 4: generate future event into event list */
        break;
      default:
        fprintf(stderr, "Error: unkown event type.\n");
        exit(EXIT_FAILURE);
    }
    free(event);
    event = NULL;

    /* get next event */
    event = get_event(event_list);
  }
#ifdef DEBUG
  printf("Info: event list is empty.\n");
  printf("Info: simulation ends.\n");
#endif
}
Example #12
0
int
main(int argc, char **argv)
{
	int c, opt_index;
	int verbose = 0;
	int opt_e = 0, opt_r = 0, opt_s = 0, opt_u = 0;
	char *server;

	while ((c=getopt_long(argc, argv, "hersuv", opts, &opt_index)) != -1) {
		switch (c) {
		case 'h':
			print_help(argv[0]);
			exit(0);
			break;
		case 'e':
			opt_e = 1;
			break;
		case 'r':
			opt_r = 1;
			break;
		case 's':
			opt_s = 1;
			break;
		case 'u':
			opt_u = 1;
			break;
		case 'v':
			verbose++;
			break;
		default:
			print_help(argv[0]);
			exit(1);
			break;
		}
	}

	if (optind == argc) {
		fprintf(stderr, "no server given!\n");
		return -1;
	}

	server = argv[optind];

	if (!is_alive(server)) {
		printf("%s is not responding.\n", server);
		return 1;
	}

	printf("%s is alive.\n", server);

	if (cmyth_conn_block_shutdown(control) < 0) {
		printf("Failed to block backend shutdown!\n");
	}

	if (verbose) {
		int version, count;
		cmyth_proglist_t list;
		long long total, used;

		printf("libcmyth version %s\n", cmyth_version());
		printf("librefmem version %s\n", ref_version());

		version = cmyth_conn_get_protocol_version(control);

		printf("\tprotocol version: %d\n", version);

		list = cmyth_proglist_get_all_recorded(control);
		count = cmyth_proglist_get_count(list);

		printf("\trecordings: %d\n", count);

		if (cmyth_conn_get_freespace(control, &total, &used) == 0) {
			printf("\ttotal space: %lld bytes\n", total);
			printf("\tused space:  %lld bytes\n", used);
		}

		get_event(server);

		ref_release(list);
	}

	if (opt_e) {
		get_recordings(verbose);
	}

	if (opt_r) {
		get_recorders(verbose);
	}

	if (opt_s) {
		get_scheduled(verbose);
	}

	if (opt_u) {
		get_upcoming(verbose);
	}

	if (cmyth_conn_allow_shutdown(control) < 0) {
		printf("Failed to allow backend shutdown!\n");
	}

	ref_release(control);

	if (verbose > 1) {
		unsigned int refs, bytes;

		ref_get_usage(&refs, &bytes);

		printf("Refmem: refs  %d\n", refs);
		printf("Refmem: bytes %d\n", bytes);

		if (refs > 0) {
			ref_alloc_show();
		}
	}

	return 0;
}
Example #13
0
APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset,
                                          const apr_pollfd_t *descriptor)
{
#ifndef HAVE_POLL
    apr_os_sock_t fd;
#endif

    if (pollset->nelts == pollset->nalloc) {
        return APR_ENOMEM;
    }

    pollset->query_set[pollset->nelts] = *descriptor;
#ifdef HAVE_POLL

    if (descriptor->desc_type == APR_POLL_SOCKET) {
        pollset->pollset[pollset->nelts].fd = descriptor->desc.s->socketdes;
    }
    else {
        pollset->pollset[pollset->nelts].fd = descriptor->desc.f->filedes;
    }

    pollset->pollset[pollset->nelts].events = get_event(descriptor->reqevents);
#else
    if (descriptor->desc_type == APR_POLL_SOCKET) {
#ifdef NETWARE
        /* NetWare can't handle mixed descriptor types in select() */
        if (HAS_PIPES(pollset->set_type)) {
            return APR_EBADF;
        }
        else {
            pollset->set_type = APR_POLL_SOCKET;
        }
#endif
        fd = descriptor->desc.s->socketdes;
    }
    else {
#if !APR_FILES_AS_SOCKETS
        return APR_EBADF;
#else
#ifdef NETWARE
        /* NetWare can't handle mixed descriptor types in select() */
        if (descriptor->desc.f->is_pipe && !HAS_SOCKETS(pollset->set_type)) {
            pollset->set_type = APR_POLL_FILE;
            fd = descriptor->desc.f->filedes;
        }
        else {
            return APR_EBADF;
        }
#else
        fd = descriptor->desc.f->filedes;
#endif
#endif
    }
#if !defined(WIN32) && !defined(NETWARE) /* socket sets handled with array of handles */
    if (fd >= FD_SETSIZE) {
        /* XXX invent new error code so application has a clue */
        return APR_EBADF;
    }
#endif
    if (descriptor->reqevents & APR_POLLIN) {
        FD_SET(fd, &(pollset->readset));
    }
    if (descriptor->reqevents & APR_POLLOUT) {
        FD_SET(fd, &(pollset->writeset));
    }
    if (descriptor->reqevents &
        (APR_POLLPRI | APR_POLLERR | APR_POLLHUP | APR_POLLNVAL)) {
        FD_SET(fd, &(pollset->exceptset));
    }
    if ((int)fd > pollset->maxfd) {
        pollset->maxfd = (int)fd;
    }
#endif
    pollset->nelts++;
    return APR_SUCCESS;
}
Example #14
0
void add_interupt_event_count(int type, unsigned count)
{
   struct node *event = NULL;
   struct node *e = NULL;
   int special;

   special = (type == SPECIAL_INT);

   if(g_cp0_regs[CP0_COUNT_REG] > UINT32_C(0x80000000))
      SPECIAL_done = 0;

   if (get_event(type))
   {
      //DebugMessage(M64MSG_WARNING, "two events of type 0x%x in interrupt queue", type);
      return;
   }

   event = alloc_node(&q.pool);
   if (event == NULL)
   {
      DebugMessage(M64MSG_ERROR, "Failed to allocate node for new interrupt event");
      return;
   }

   event->data.count = count;
   event->data.type  = type;

   if (q.first == NULL)
   {
      q.first = event;
      event->next = NULL;
      next_interupt = q.first->data.count;
   }
   else if (before_event(count, q.first->data.count, q.first->data.type) && !special)
   {
      event->next = q.first;
      q.first = event;
      next_interupt = q.first->data.count;
   }
   else
   {
      for(e = q.first;
            e && e->next != NULL &&
            (!before_event(count, e->next->data.count, e->next->data.type) || special);
            e = e->next);

      if (e->next == NULL)
      {
         e->next = event;
         event->next = NULL;
      }
      else
      {
         if (!special)
            for(; e->next != NULL && e->next->data.count == count; e = e->next);

         event->next = e->next;
         e->next = event;
      }
   }
}
Example #15
0
int main(int argc, char **argv){
  int ram_fd;
  char *ram, *ram_filename;
  struct stat ram_fs;
  //int num_vms;
  int num_vcpus;
  pid_t creator;
  int vmfd;
  int rv;
  int sc[3];
  struct kvm_regs regs;
  struct kvm_sregs sregs;
  union event_data event_data;
  
  go = 1;
  
  signal(SIGINT, sig_handler);
  
  
  if (argc < 3){
    printf("Usage: [qemu pid] [guest ram filename]\n");
    return -1;
  }
  
  ram_filename = argv[2];
  
  printf("Mapping Guest Memory...\n");
  if (stat(ram_filename, &ram_fs) == -1){
    perror("stat");
    return -1;
  }
  
  if ((ram_fd = open(ram_filename,O_RDWR)) == -1){
    perror("open");
    return -1;
  }
  
  if((ram = mmap(NULL, ram_fs.st_size, (PROT_READ | PROT_WRITE), MAP_SHARED, ram_fd, 0)) == (void*)-1){
    perror("mmap");
    close(ram_fd);
    return -1;
  }
  
  
  
  printf("Initializing KVM...\n");
  if(init_kvm()){
    printf("Unable to initialize kvm, exiting.\n");
    return -1;
  }
  printf("Initialized\n\n");
  
  creator = (pid_t)atoi(argv[1]);
  printf("calling attach_vm() with creator pid: %d...\n",creator);
  vmfd = attach_vm(creator);
  if(vmfd < 0){
    printf("Error attaching to VM, exiting\n");
    return -1;
  }
  printf("attach_vm() returned %d\n\n",vmfd);
  
  printf("calling attach_vcpus()...\n");
  num_vcpus = attach_vcpus();
  printf("attach_vcpus() returned %d\n\n",num_vcpus);
  
/*
  printf("calling get_regs()...\n");
  if(get_regs(0,&regs)){
    printf("Error getting regs, exiting\n");
    return -1;
  }
  printf("get_regs() returned rip: 0x%llX\n\n",regs.rip);
  
  printf("calling get_sregs()...\n");
  if(get_sregs(0,&sregs)){
    printf("Error getting sregs, exiting\n");
    return -1;
  }
  printf("get_sregs() returned cr0: 0x%llX\n\n",sregs.cr0);
*/

  
  printf("calling set_syscall_trap()...\n");
  sc[0] = 0x9f;
  sc[1] = 0x4a;
  sc[2] = 0xaa;
  rv = set_syscall_trap(sc,3);
  printf("set_syscall_trap() returned %d\n\n",rv);
  
  while(go){
    rv = get_event(0,&event_data);
    
    if(get_regs(0,&regs)){
      printf("Error getting regs, exiting\n");
      continue_vm(0);
      break;
    }
    if(get_sregs(0,&sregs)){
      printf("Error getting sregs, exiting\n");
      continue_vm(0);
      break;
    }
    if(rv == KVM_NITRO_EVENT_SYSCALL)
      printf("Syscall trapped key: 0x%lX cr3: 0x%llX rax: 0x%llX\n",event_data.syscall,sregs.cr3,regs.rax);
    else if(rv == KVM_NITRO_EVENT_SYSRET)
      printf("Sysret trapped key: 0x%lX cr3: 0x%llX\n",event_data.syscall,sregs.cr3);
    rv = continue_vm(0);
  }

  
  printf("calling unset_syscall_trap()...\n");
  rv = unset_syscall_trap();
  printf("unset_syscall_trap() returned %d\n\n",rv);
  
  close_kvm();
  
  munmap(ram,ram_fs.st_size);
  close(ram_fd);
  
  return 0;
}
Example #16
0
APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t num,
                                   apr_int32_t *nsds, 
                                   apr_interval_time_t timeout)
{
    int i, num_to_poll;
#ifdef HAVE_VLA
    /* XXX: I trust that this is a segv when insufficient stack exists? */
    struct pollfd pollset[num];
#elif defined(HAVE_ALLOCA)
    struct pollfd *pollset = alloca(sizeof(struct pollfd) * num);
    if (!pollset)
        return APR_ENOMEM;
#else
    struct pollfd tmp_pollset[SMALL_POLLSET_LIMIT];
    struct pollfd *pollset;

    if (num <= SMALL_POLLSET_LIMIT) {
        pollset = tmp_pollset;
    }
    else {
        /* This does require O(n) to copy the descriptors to the internal
         * mapping.
         */
        pollset = malloc(sizeof(struct pollfd) * num);
        /* The other option is adding an apr_pool_abort() fn to invoke
         * the pool's out of memory handler
         */
        if (!pollset)
            return APR_ENOMEM;
    }
#endif
    for (i = 0; i < num; i++) {
        if (aprset[i].desc_type == APR_POLL_SOCKET) {
            pollset[i].fd = aprset[i].desc.s->socketdes;
        }
        else if (aprset[i].desc_type == APR_POLL_FILE) {
            pollset[i].fd = aprset[i].desc.f->filedes;
        }
        else {
            break;
        }
        pollset[i].events = get_event(aprset[i].reqevents);
    }
    num_to_poll = i;

    if (timeout > 0) {
        timeout /= 1000; /* convert microseconds to milliseconds */
    }

    i = poll(pollset, num_to_poll, timeout);
    (*nsds) = i;

    if (i > 0) { /* poll() sets revents only if an event was signalled;
                  * we don't promise to set rtnevents unless an event
                  * was signalled
                  */
        for (i = 0; i < num; i++) {
            aprset[i].rtnevents = get_revent(pollset[i].revents);
        }
    }
    
#if !defined(HAVE_VLA) && !defined(HAVE_ALLOCA)
    if (num > SMALL_POLLSET_LIMIT) {
        free(pollset);
    }
#endif

    if ((*nsds) < 0) {
        return apr_get_netos_error();
    }
    if ((*nsds) == 0) {
        return APR_TIMEUP;
    }
    return APR_SUCCESS;
}
Example #17
0
/**
 * Wait for matching event
 */
unique_ptr<inotify_event> inotify_watch::await_match() const {
  auto event = get_event();
  return event->mask & m_mask ? std::move(event) : nullptr;
}
Example #18
0
File: port.c Project: Ga-vin/apache
static apr_status_t impl_pollset_poll(apr_pollset_t *pollset,
                                      apr_interval_time_t timeout,
                                      apr_int32_t *num,
                                      const apr_pollfd_t **descriptors)
{
    apr_os_sock_t fd;
    int ret, i, j;
    unsigned int nget;
    pfd_elem_t *ep;
    apr_status_t rv = APR_SUCCESS;
    apr_pollfd_t fp;

    nget = 1;

    pollset_lock_rings();

    apr_atomic_inc32(&pollset->p->waiting);

    while (!APR_RING_EMPTY(&(pollset->p->add_ring), pfd_elem_t, link)) {
        ep = APR_RING_FIRST(&(pollset->p->add_ring));
        APR_RING_REMOVE(ep, link);

        if (ep->pfd.desc_type == APR_POLL_SOCKET) {
            fd = ep->pfd.desc.s->socketdes;
        }
        else {
            fd = ep->pfd.desc.f->filedes;
        }

        ret = port_associate(pollset->p->port_fd, PORT_SOURCE_FD, 
                             fd, get_event(ep->pfd.reqevents), ep);
        if (ret < 0) {
            rv = apr_get_netos_error();
            APR_RING_INSERT_TAIL(&(pollset->p->free_ring), ep, pfd_elem_t, link);
            break;
        }

        ep->on_query_ring = 1;
        APR_RING_INSERT_TAIL(&(pollset->p->query_ring), ep, pfd_elem_t, link);
    }

    pollset_unlock_rings();

    if (rv != APR_SUCCESS) {
        apr_atomic_dec32(&pollset->p->waiting);
        return rv;
    }

    rv = call_port_getn(pollset->p->port_fd, pollset->p->port_set, 
                        pollset->nalloc, &nget, timeout);

    /* decrease the waiting ASAP to reduce the window for calling 
       port_associate within apr_pollset_add() */
    apr_atomic_dec32(&pollset->p->waiting);

    (*num) = nget;
    if (nget) {

        pollset_lock_rings();

        for (i = 0, j = 0; i < nget; i++) {
            fp = (((pfd_elem_t*)(pollset->p->port_set[i].portev_user))->pfd);
            if ((pollset->flags & APR_POLLSET_WAKEABLE) &&
                fp.desc_type == APR_POLL_FILE &&
                fp.desc.f == pollset->wakeup_pipe[0]) {
                apr_pollset_drain_wakeup_pipe(pollset);
                rv = APR_EINTR;
            }
            else {
                pollset->p->result_set[j] = fp;            
                pollset->p->result_set[j].rtnevents =
                    get_revent(pollset->p->port_set[i].portev_events);

                /* If the ring element is still on the query ring, move it
                 * to the add ring for re-association with the event port
                 * later.  (It may have already been moved to the dead ring
                 * by a call to pollset_remove on another thread.)
                 */
                ep = (pfd_elem_t *)pollset->p->port_set[i].portev_user;
                if (ep->on_query_ring) {
                    APR_RING_REMOVE(ep, link);
                    ep->on_query_ring = 0;
                    APR_RING_INSERT_TAIL(&(pollset->p->add_ring), ep,
                                         pfd_elem_t, link);
                }
                j++;
            }
        }
        pollset_unlock_rings();
        if ((*num = j)) { /* any event besides wakeup pipe? */
            rv = APR_SUCCESS;
            if (descriptors) {
                *descriptors = pollset->p->result_set;
            }
        }
    }

    pollset_lock_rings();

    /* Shift all PFDs in the Dead Ring to the Free Ring */
    APR_RING_CONCAT(&(pollset->p->free_ring), &(pollset->p->dead_ring), pfd_elem_t, link);

    pollset_unlock_rings();

    return rv;
}
Example #19
0
void add_interupt_event(int type, unsigned long delay)
{
  unsigned long count = Count + delay;
  int special = 0;
  
  if(type == SPECIAL_INT) {
    special = 1;
  }
  if(Count > 0x80000000) {
    SPECIAL_done = 0;
  }
     
  if (get_event(type)) {
    //printf("two events of type %x in queue\n", type);
  }
   
  interupt_queue *aux = q;
  if (q == NULL) {
    q = queue_malloc(sizeof(interupt_queue));
    q->next = NULL;
    q->count = count;
    q->type = type;
    next_interupt = q->count;
    return;
  }
   
  if(before_event(count, q->count, q->type) && !special) {
    q = queue_malloc(sizeof(interupt_queue));
    q->next = aux;
    q->count = count;
    q->type = type;
    next_interupt = q->count;
    return;
  }

  while (aux->next != NULL && (!before_event(count, aux->next->count, aux->next->type) || special)) {
    aux = aux->next;
  }

  if (aux->next == NULL) {
    aux->next = queue_malloc(sizeof(interupt_queue));
    aux = aux->next;
    aux->next = NULL;
    aux->count = count;
    aux->type = type;
  }
  else {
    interupt_queue *aux2;
    if (type != SPECIAL_INT) {
      while(aux->next != NULL && aux->next->count == count) {
        aux = aux->next;
      }
    }
    aux2 = aux->next;
    aux->next = queue_malloc(sizeof(interupt_queue));
    aux = aux->next;
    aux->next = aux2;
    aux->count = count;
    aux->type = type;
  }
}
Example #20
0
int update_pua(ua_pres_t* p)
{
	str* str_hdr= NULL;
	int expires;
	int result;
	uac_req_t uac_r;
	int ret_code = 0;
	dlg_t* td = NULL;

	if(p->desired_expires== 0)
		expires= 3600;
	else
		expires= p->desired_expires- (int)time(NULL);

	if(p->watcher_uri == NULL || p->watcher_uri->len == 0)
	{
		str met= {"PUBLISH", 7};
		ua_pres_t* cb_param;

		str_hdr = publ_build_hdr(expires, get_event(p->event), NULL,
				&p->etag, p->extra_headers, 0);
		if(str_hdr == NULL)
		{
			LM_ERR("while building extra_headers\n");
			ret_code = -1;
			goto done;
		}
		LM_DBG("str_hdr:\n%.*s\n ", str_hdr->len, str_hdr->s);

		cb_param= build_uppubl_cbparam(p);
		if(cb_param== NULL)
		{
			LM_ERR("while constructing publ callback param\n");
			ret_code = -1;
			goto done;
		}

		set_uac_req(&uac_r, &met, str_hdr, 0, 0, TMCB_LOCAL_COMPLETED,
				publ_cback_func, (void*)cb_param);
		result= tmb.t_request(&uac_r,
				p->pres_uri,					/* Request-URI */
				p->pres_uri,					/* To */
				p->pres_uri,					/* From */
				&outbound_proxy					/* Outbound proxy*/
				);
		if(result< 0)
		{
			LM_ERR("in t_request function\n");
			shm_free(cb_param);
			ret_code = -1;
			goto done;
		}
	}
	else
	{
		str met= {"SUBSCRIBE", 9};
		ua_pres_t* cb_param= NULL;

		td= pua_build_dlg_t(p);
		if(td== NULL)
		{
			LM_ERR("while building tm dlg_t structure");
			ret_code = -1;
			goto done;
		};

		str_hdr= subs_build_hdr(&p->contact, expires,p->event,p->extra_headers);
		if(str_hdr== NULL || str_hdr->s== NULL)
		{
			if(p->event!=0)
				LM_ERR("while building extra headers\n");
			ret_code = -1;
			goto done;
		}
		cb_param= subs_cbparam_indlg(p, expires, REQ_ME);
		if(cb_param== NULL)
		{
			LM_ERR("while constructing subs callback param\n");
			ret_code = -1;
			goto done;
		}

		set_uac_req(&uac_r, &met, str_hdr, 0, td, TMCB_LOCAL_COMPLETED,
				subs_cback_func, (void*)cb_param);

		result= tmb.t_request_within(&uac_r);
		if(result< 0)
		{
			LM_ERR("in t_request function\n");
			shm_free(cb_param);
			ret_code = -1;
			goto done;
		}
	}
done:
	if(td!=NULL)
	{
		if(td->route_set)
			free_rr(&td->route_set);
		pkg_free(td);
		td= NULL;
	}
	if(str_hdr)
		pkg_free(str_hdr);

	return ret_code;

}
Example #21
0
str* subs_build_hdr(str* contact, int expires, int event, str* extra_headers)
{
	str* str_hdr= NULL;
	static char buf[3000];
	char* subs_expires= NULL;
	int len= 1;
	pua_event_t* ev;	

	str_hdr= (str*)pkg_malloc(sizeof(str));
	if(str_hdr== NULL)
	{
		LM_ERR("no more memory\n");
		return NULL;
	}
	memset(str_hdr, 0, sizeof(str));
	str_hdr->s= buf;
	
	ev= get_event(event);	
	if(ev== NULL)
	{
		LM_ERR("getting event from list\n");
		goto error;
	}

	memcpy(str_hdr->s ,"Max-Forwards: ", 14);
	str_hdr->len = 14;
	str_hdr->len+= sprintf(str_hdr->s+ str_hdr->len,"%d", MAX_FORWARD);
	memcpy(str_hdr->s+str_hdr->len, CRLF, CRLF_LEN);
	str_hdr->len += CRLF_LEN;

	memcpy(str_hdr->s+ str_hdr->len ,"Event: ", 7);
	str_hdr->len+= 7;
	memcpy(str_hdr->s+ str_hdr->len, ev->name.s, ev->name.len);
	str_hdr->len+= ev->name.len;
	memcpy(str_hdr->s+str_hdr->len, CRLF, CRLF_LEN);
	str_hdr->len += CRLF_LEN;
	
	memcpy(str_hdr->s+ str_hdr->len ,"Contact: <", 10);
	str_hdr->len += 10;
	memcpy(str_hdr->s +str_hdr->len, contact->s, 
			contact->len);
	str_hdr->len+= contact->len;
	memcpy(str_hdr->s+ str_hdr->len, ">", 1);
	str_hdr->len+= 1;
	memcpy(str_hdr->s+str_hdr->len, CRLF, CRLF_LEN);
	str_hdr->len += CRLF_LEN;

	memcpy(str_hdr->s+ str_hdr->len ,"Expires: ", 9);
	str_hdr->len += 9;

	if( expires<= min_expires)
		subs_expires= int2str(min_expires, &len);  
	else
		subs_expires= int2str(expires+ 10, &len);
		
	if(subs_expires == NULL || len == 0)
	{
		LM_ERR("while converting int to str\n");
		pkg_free(str_hdr);
		return NULL;
	}
	memcpy(str_hdr->s+str_hdr->len, subs_expires, len);
	str_hdr->len += len;
	memcpy(str_hdr->s+str_hdr->len, CRLF, CRLF_LEN);
	str_hdr->len += CRLF_LEN;

	if(extra_headers && extra_headers->len)
	{
		memcpy(str_hdr->s+str_hdr->len, extra_headers->s, extra_headers->len);
		str_hdr->len += extra_headers->len;
	}

	str_hdr->s[str_hdr->len]= '\0';

	return str_hdr;

error:
	if(str_hdr)
		pkg_free(str_hdr);
	return NULL;
}	
static int dtmf_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
{
	pjsip_msg_body *body = rdata->msg_info.msg->body;
	char buf[body ? body->len : 0];
	char *cur = buf;
	char *line;

	char event = '\0';
	unsigned int duration = 100;

	char is_dtmf = is_media_type(rdata, "dtmf");

	if (!is_dtmf && !is_media_type(rdata, "dtmf-relay")) {
		return 0;
	}

	if (!body || !body->len) {
		/* need to return 200 OK on empty body */
		send_response(session, rdata, 200);
		return 0;
	}

	body->print_body(body, buf, body->len);

	if (is_dtmf) {
		/* directly use what is in the message body */
		event = get_event(cur);
	} else { /* content type = application/dtmf-relay */
		while ((line = strsep(&cur, "\r\n"))) {
			char *c;

			if (!(c = strchr(line, '='))) {
				continue;
			}

			*c++ = '\0';
			c = ast_skip_blanks(c);

			if (!strcasecmp(line, "signal")) {
				if (!(event = get_event(c))) {
					break;
				}
			} else if (!strcasecmp(line, "duration")) {
				sscanf(c, "%30u", &duration);
			}
		}
	}

	if (event == '!') {
		struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
		ast_queue_frame(session->channel, &f);
	} else if (event != '\0') {
		struct ast_frame f = { AST_FRAME_DTMF, };
		f.len = duration;
		f.subclass.integer = event;
		ast_queue_frame(session->channel, &f);
	} else {
		ast_log(LOG_ERROR, "Invalid DTMF event signal in INFO message.\n");
	}

	send_response(session, rdata, event ? 200 : 500);
	return event ? 0 : -1;
}
Example #23
0
void add_interupt_event_count(int type, unsigned int count)
{
    struct node* event;
    struct node* e;
    int special;

    special = (type == SPECIAL_INT);

    if(g_cp0_regs[CP0_COUNT_REG] > UINT32_C(0x80000000)) SPECIAL_done = 0;

    if (get_event(type)) {
        DebugMessage(M64MSG_WARNING, "two events of type 0x%x in interrupt queue", type);
        /* FIXME: hack-fix for freezing in Perfect Dark
         * http://code.google.com/p/mupen64plus/issues/detail?id=553
         * https://github.com/mupen64plus-ae/mupen64plus-ae/commit/802d8f81d46705d64694d7a34010dc5f35787c7d
         */
        return;
    }

    event = alloc_node(&q.pool);
    if (event == NULL)
    {
        DebugMessage(M64MSG_ERROR, "Failed to allocate node for new interrupt event");
        return;
    }

    event->data.count = count;
    event->data.type = type;

    if (q.first == NULL)
    {
        q.first = event;
        event->next = NULL;
        next_interupt = q.first->data.count;
    }
    else if (before_event(count, q.first->data.count, q.first->data.type) && !special)
    {
        event->next = q.first;
        q.first = event;
        next_interupt = q.first->data.count;
    }
    else
    {
        for(e = q.first;
                e->next != NULL &&
                (!before_event(count, e->next->data.count, e->next->data.type) || special);
                e = e->next);

        if (e->next == NULL)
        {
            e->next = event;
            event->next = NULL;
        }
        else
        {
            if (!special)
                for(; e->next != NULL && e->next->data.count == count; e = e->next);

            event->next = e->next;
            e->next = event;
        }
    }
}
int send_publish( publ_info_t* publ )
{
	str met = {"PUBLISH", 7};
	str* str_hdr = NULL;
	ua_pres_t* presentity= NULL;
	str* body= NULL;
	str* tuple_id= NULL;
	ua_pres_t* cb_param= NULL;
	unsigned int hash_code=0;
	str etag= {0, 0};
	int ver= 0;
	int result;
	int ret_code= 0;
	pua_event_t* ev= NULL;
	uac_req_t uac_r;
	db1_res_t *res=NULL;
	ua_pres_t dbpres; 
	str pres_uri={0,0}, watcher_uri={0,0}, extra_headers={0,0};
	int ret = -1;

	LM_DBG("pres_uri=%.*s\n", publ->pres_uri->len, publ->pres_uri->s );
	
	if (dbmode == PUA_DB_ONLY && pua_dbf.start_transaction)
	{
		if (pua_dbf.start_transaction(pua_db, DB_LOCKING_WRITE) < 0)
		{
			LM_ERR("in start_transaction\n");
			goto error;
		}
	}

	/* get event from list */
	ev= get_event(publ->event);
	if(ev== NULL)
	{
		LM_ERR("event not found in list\n");
		goto error;
	}	

	if (dbmode==PUA_DB_ONLY)
	{
		memset(&dbpres, 0, sizeof(dbpres));
		dbpres.pres_uri = &pres_uri;
		dbpres.watcher_uri = &watcher_uri;
		dbpres.extra_headers = &extra_headers;
		presentity = get_record_puadb(publ->id, publ->etag, &dbpres, &res);
	}
	else
	{
		ua_pres_t pres;

		memset(&pres, 0, sizeof(ua_pres_t));
		pres.pres_uri = publ->pres_uri;
		pres.flag = publ->source_flag;
		pres.id = publ->id;
		pres.event = publ->event;
		if(publ->etag)
			pres.etag = *publ->etag;

		hash_code= core_hash(publ->pres_uri, NULL, HASH_SIZE);
		lock_get(&HashT->p_records[hash_code].lock);
		presentity= search_htable(&pres, hash_code);
	}

	if(publ->etag && presentity== NULL)
	{
		if (dbmode!=PUA_DB_ONLY) 
			lock_release(&HashT->p_records[hash_code].lock);
		ret = 418;
		goto error;
	}

	if(publ->flag & INSERT_TYPE)
	{
		LM_DBG("Insert flag set\n");
		goto insert;
	}
	
	if(presentity== NULL)
	{
insert:	
		if (dbmode!=PUA_DB_ONLY) 
			lock_release(&HashT->p_records[hash_code].lock);
		LM_DBG("insert type\n"); 
		
		if(publ->flag & UPDATE_TYPE )
		{
			LM_DBG("UPDATE_TYPE and no record found \n");
			publ->flag= INSERT_TYPE;
		}
		if(publ->expires== 0)
		{
			LM_DBG("request for a publish with expires 0 and"
					" no record found\n");
			goto done;
			
		}
		if(publ->body== NULL)
		{
			LM_ERR("New PUBLISH and no body found- invalid request\n");
			ret = ERR_PUBLISH_NO_BODY;
			goto error;
		}
	}
	else
	{
		LM_DBG("record found in hash_table\n");
		publ->flag= UPDATE_TYPE;
		etag.s= (char*)pkg_malloc(presentity->etag.len* sizeof(char));
		if(etag.s== NULL)
		{
			LM_ERR("while allocating memory\n");
			if (dbmode!=PUA_DB_ONLY) 
				lock_release(&HashT->p_records[hash_code].lock);
			goto error;
		}
		memcpy(etag.s, presentity->etag.s, presentity->etag.len);
		etag.len= presentity->etag.len;

		if(presentity->tuple_id.s && presentity->tuple_id.len)
		{	
			/* get tuple_id*/
			tuple_id=(str*)pkg_malloc(sizeof(str));
			if(tuple_id== NULL)
			{
				LM_ERR("No more memory\n");
				if (dbmode!=PUA_DB_ONLY) 
					lock_release(&HashT->p_records[hash_code].lock);
				goto error;
			}	
			tuple_id->s= (char*)pkg_malloc(presentity->tuple_id.len* sizeof(char));
			if(tuple_id->s== NULL)
			{
				LM_ERR("No more memory\n");
				if (dbmode!=PUA_DB_ONLY) 
					lock_release(&HashT->p_records[hash_code].lock);
				goto error;
			}	
			memcpy(tuple_id->s, presentity->tuple_id.s, presentity->tuple_id.len);
			tuple_id->len= presentity->tuple_id.len;
		}

		if(publ->expires== 0)
		{
			LM_DBG("expires= 0- delete from hash table\n");
			if (dbmode!=PUA_DB_ONLY) 
				lock_release(&HashT->p_records[hash_code].lock);
			goto send_publish;
		}

		presentity->version++; 
		ver= presentity->version;

		if (dbmode==PUA_DB_ONLY)
		{ 
			update_version_puadb(presentity);
		}
		else
		{
			lock_release(&HashT->p_records[hash_code].lock);
		}
	}

	/* handle body */
	if(publ->body && publ->body->s)
	{
		ret_code= ev->process_body(publ, &body, ver, &tuple_id );
		if( ret_code< 0 || body== NULL)
		{
			LM_ERR("while processing body\n");
			if(body== NULL)
				LM_ERR("NULL body\n");
			goto error;
		}
	}
	if(tuple_id)
		LM_DBG("tuple_id= %.*s\n", tuple_id->len, tuple_id->s  );
	
send_publish:
	
	/* construct the callback parameter */
	if(etag.s && etag.len)
		publ->etag = &etag;

	cb_param= publish_cbparam(publ, body, tuple_id, REQ_OTHER);
	if(cb_param== NULL)
	{
		LM_ERR("constructing callback parameter\n");
		goto error;
	}

	if(publ->flag & UPDATE_TYPE)
		LM_DBG("etag:%.*s\n", etag.len, etag.s);
	str_hdr = publ_build_hdr((publ->expires< 0)?3600:publ->expires, ev, &publ->content_type, 
				(publ->flag & UPDATE_TYPE)?&etag:NULL, publ->extra_headers, (body)?1:0);

	if(str_hdr == NULL)
	{
		LM_ERR("while building extra_headers\n");
		goto error;
	}

	LM_DBG("publ->pres_uri:\n%.*s\n ", publ->pres_uri->len, publ->pres_uri->s);
	LM_DBG("str_hdr:\n%.*s %d\n ", str_hdr->len, str_hdr->s, str_hdr->len);
	if(body && body->len && body->s )
		LM_DBG("body:\n%.*s\n ", body->len, body->s);

	set_uac_req(&uac_r, &met, str_hdr, body, 0, TMCB_LOCAL_COMPLETED,
			publ_cback_func, (void*)cb_param);
	result= tmb.t_request(&uac_r,
			publ->pres_uri,			/*! Request-URI */
			publ->pres_uri,			/*! To */
			publ->pres_uri,			/*! From */
			&outbound_proxy		/*! Outbound proxy*/
			);

	if(result< 0)
	{
		LM_ERR("in t_request tm module function\n");
		goto error;
	}

done:
	ret = 0;

	if (dbmode == PUA_DB_ONLY && pua_dbf.end_transaction)
	{
		if (pua_dbf.end_transaction(pua_db) < 0)
		{
			LM_ERR("in end_transaction\n");
			goto error;
		}
	}
	goto finish;

error:
	ret = -1;
	if(cb_param)
		shm_free(cb_param);

	if (dbmode == PUA_DB_ONLY && pua_dbf.abort_transaction)
	{
		if (pua_dbf.abort_transaction(pua_db) < 0)
			LM_ERR("in abort_transaction\n");
	}

finish:
	if(etag.s)
		pkg_free(etag.s);

	if(body && ret_code)
	{
		if(body->s)
			xmlFree(body->s);
		pkg_free(body);
	}	
	if(str_hdr)
		pkg_free(str_hdr);
	if(tuple_id)
	{
		if(tuple_id->s)
			pkg_free(tuple_id->s);
		pkg_free(tuple_id);
	}
	free_results_puadb(res);

	return ret;
}
Example #25
0
void gen_interupt(void)
{
    if (stop == 1)
    {
        vi_counter = 0; // debug
        dyna_stop();
    }

    if (!interupt_unsafe_state)
    {
        if (savestates_get_job() == savestates_job_load)
        {
            savestates_load();
            return;
        }

        if (reset_hard_job)
        {
            reset_hard();
            reset_hard_job = 0;
            return;
        }
    }
   
    if (skip_jump)
    {
        unsigned int dest = skip_jump;
        skip_jump = 0;

        if (q->count > Count || (Count - q->count) < 0x80000000)
            next_interupt = q->count;
        else
            next_interupt = 0;
        
        generic_jump_to(dest);
        return;
    } 

    switch(q->type)
    {
        case SPECIAL_INT:
            if (Count > 0x10000000) return;
            remove_interupt_event();
            add_interupt_event_count(SPECIAL_INT, 0);
            return;
            break;
        case VI_INT:
            if(vi_counter < 60)
            {
                if (vi_counter == 0)
                    cheat_apply_cheats(ENTRY_BOOT);
                vi_counter++;
            }
            else
            {
                cheat_apply_cheats(ENTRY_VI);
            }
            gfx.updateScreen();
#ifdef WITH_LIRC
            lircCheckInput();
#endif
            SDL_PumpEvents();

            refresh_stat();

            // if paused, poll for input events
            if(rompause)
            {
                osd_render();  // draw Paused message in case gfx.updateScreen didn't do it
                VidExt_GL_SwapBuffers();
                while(rompause)
                {
                    SDL_Delay(10);
                    SDL_PumpEvents();
#ifdef WITH_LIRC
                    lircCheckInput();
#endif //WITH_LIRC
                }
            }

            new_vi();
            if (vi_register.vi_v_sync == 0) vi_register.vi_delay = 500000;
            else vi_register.vi_delay = ((vi_register.vi_v_sync + 1)*1500);
            next_vi += vi_register.vi_delay;
            if (vi_register.vi_status&0x40) vi_field=1-vi_field;
            else vi_field=0;

            remove_interupt_event();
            add_interupt_event_count(VI_INT, next_vi);
    
            MI_register.mi_intr_reg |= 0x08;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case COMPARE_INT:
            remove_interupt_event();
            Count+=2;
            add_interupt_event_count(COMPARE_INT, Compare);
            Count-=2;
    
            Cause = (Cause | 0x8000) & 0xFFFFFF83;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case CHECK_INT:
            remove_interupt_event();
            break;
    
        case SI_INT:
#ifdef WITH_LIRC
            lircCheckInput();
#endif //WITH_LIRC
            SDL_PumpEvents();
            PIF_RAMb[0x3F] = 0x0;
            remove_interupt_event();
            MI_register.mi_intr_reg |= 0x02;
            si_register.si_stat |= 0x1000;
            si_register.si_stat &= ~0x1;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case PI_INT:
            remove_interupt_event();
            MI_register.mi_intr_reg |= 0x10;
            pi_register.read_pi_status_reg &= ~3;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case AI_INT:
            if (ai_register.ai_status & 0x80000000) // full
            {
                unsigned int ai_event = get_event(AI_INT);
                remove_interupt_event();
                ai_register.ai_status &= ~0x80000000;
                ai_register.current_delay = ai_register.next_delay;
                ai_register.current_len = ai_register.next_len;
                add_interupt_event_count(AI_INT, ai_event+ai_register.next_delay);
         
                MI_register.mi_intr_reg |= 0x04;
                if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                    Cause = (Cause | 0x400) & 0xFFFFFF83;
                else
                    return;
                if ((Status & 7) != 1) return;
                if (!(Status & Cause & 0xFF00)) return;
            }
            else
            {
                remove_interupt_event();
                ai_register.ai_status &= ~0x40000000;

                //-------
                MI_register.mi_intr_reg |= 0x04;
                if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                    Cause = (Cause | 0x400) & 0xFFFFFF83;
                else
                    return;
                if ((Status & 7) != 1) return;
                if (!(Status & Cause & 0xFF00)) return;
            }
            break;

        case SP_INT:
            remove_interupt_event();
            sp_register.sp_status_reg |= 0x203;
            // sp_register.sp_status_reg |= 0x303;
    
            if (!(sp_register.sp_status_reg & 0x40)) return; // !intr_on_break
            MI_register.mi_intr_reg |= 0x01;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;
    
        case DP_INT:
            remove_interupt_event();
            dpc_register.dpc_status &= ~2;
            dpc_register.dpc_status |= 0x81;
            MI_register.mi_intr_reg |= 0x20;
            if (MI_register.mi_intr_reg & MI_register.mi_intr_mask_reg)
                Cause = (Cause | 0x400) & 0xFFFFFF83;
            else
                return;
            if ((Status & 7) != 1) return;
            if (!(Status & Cause & 0xFF00)) return;
            break;

        case HW2_INT:
            // Hardware Interrupt 2 -- remove interrupt event from queue
            remove_interupt_event();
            // setup r4300 Status flags: reset TS, and SR, set IM2
            Status = (Status & ~0x00380000) | 0x1000;
            Cause = (Cause | 0x1000) & 0xFFFFFF83;
            /* the exception_general() call below will jump to the interrupt vector (0x80000180) and setup the
             * interpreter or dynarec
             */
            break;

        case NMI_INT:
            // Non Maskable Interrupt -- remove interrupt event from queue
            remove_interupt_event();
            // setup r4300 Status flags: reset TS and SR, set BEV, ERL, and SR
            Status = (Status & ~0x00380000) | 0x00500004;
            Cause  = 0x00000000;
            // simulate the soft reset code which would run from the PIF ROM
            r4300_reset_soft();
            // clear all interrupts, reset interrupt counters back to 0
            Count = 0;
            vi_counter = 0;
            init_interupt();
            // clear the audio status register so that subsequent write_ai() calls will work properly
            ai_register.ai_status = 0;
            // set ErrorEPC with the last instruction address
            ErrorEPC = PC->addr;
            // reset the r4300 internal state
            if (r4300emu != CORE_PURE_INTERPRETER)
            {
                // clear all the compiled instruction blocks and re-initialize
                free_blocks();
                init_blocks();
            }
            // set next instruction address to reset vector
            generic_jump_to(0xa4000040);
            last_addr = PC->addr;
            // adjust ErrorEPC if we were in a delay slot, and clear the delay_slot and dyna_interp flags
            if(delay_slot==1 || delay_slot==3)
            {
                ErrorEPC-=4;
            }
            delay_slot = 0;
            dyna_interp = 0;
            return;

        default:
            DebugMessage(M64MSG_ERROR, "Unknown interrupt queue event type %.8X.", q->type);
            remove_interupt_event();
            break;
    }

#ifdef NEW_DYNAREC
    EPC = pcaddr;
    pcaddr = 0x80000180;
    Status |= 2;
    Cause &= 0x7FFFFFFF;
    pending_exception=1;
#else
    exception_general();
#endif

    if (!interupt_unsafe_state)
    {
        if (savestates_get_job() == savestates_job_save)
        {
            savestates_save();
            return;
        }
    }
}
Example #26
0
static void sodna_nextKeyOrMouseEvent(
        rogueEvent *returnEvent, boolean textInput, boolean colorsDance) {
    int time, waitTime;
    boolean mouseMoved = false;
    for (;;) {
        time = sodna_ms_elapsed();
        if (colorsDance) {
            shuffleTerrainColors(3, true);
            commitDraws();
        }
        sodna_flush();

        sodna_Event e = get_event(true);

        // We get lots of mouse events, loop to flush out several consecutive
        // ones. Do break at some point though.
        if (e.type == SODNA_EVENT_MOUSE_MOVED) {
            for (;;) {
                if (mouse_pos_changed())
                    mouseMoved = true;
                // Peek at the future event, try to stop this loop at the last
                // mouse moved event of the sequence.
                if (get_event(false).type != SODNA_EVENT_MOUSE_MOVED)
                    break;
                if (sodna_ms_elapsed() - time > PAUSE_BETWEEN_EVENT_POLLING)
                    break;
                e = get_event(true);
            }
        }

        returnEvent->controlKey = ctrl_pressed;
        returnEvent->shiftKey = shift_pressed;

        if (e.type == SODNA_EVENT_CLOSE_WINDOW) {
            rogue.gameHasEnded = true;
            rogue.nextGame = NG_QUIT; // causes the menu to drop out immediately
            returnEvent->eventType = KEYSTROKE;
            returnEvent->param1 = ESCAPE_KEY;
            return;
        }


        if (e.type == SODNA_EVENT_MOUSE_DOWN) {
            returnEvent->param1 = mouse_x;
            returnEvent->param2 = mouse_y;
            if (e.button.id == SODNA_LEFT_BUTTON) {
                returnEvent->eventType = MOUSE_DOWN;
                return;
            }
            if (e.button.id == SODNA_RIGHT_BUTTON) {
                returnEvent->eventType = RIGHT_MOUSE_DOWN;
                return;
            }
        }

        if (e.type == SODNA_EVENT_MOUSE_UP) {
            returnEvent->param1 = mouse_x;
            returnEvent->param2 = mouse_y;
            if (e.button.id == SODNA_LEFT_BUTTON) {
                returnEvent->eventType = MOUSE_UP;
                return;
            }
            if (e.button.id == SODNA_RIGHT_BUTTON) {
                returnEvent->eventType = RIGHT_MOUSE_UP;
                return;
            }
        }

        // Reverse the effect of caps lock if it's on.
        if (e.type == SODNA_EVENT_CHARACTER) {
            // XXX: Due to a bug in SDL2, used as backend by Sodna, caps lock
            // state isn't maintained robustly. So we can't rely on the
            // modifier. Look at shift state and the character case instead.
            //if (caps_lock) {
            if ((isupper(e.ch.code) && !shift_pressed) || (islower(e.ch.code) && shift_pressed)) {
                if (isupper(e.ch.code)) {
                    e.ch.code = tolower(e.ch.code);
                } else if (islower(e.ch.code)) {
                    e.ch.code = toupper(e.ch.code);
                }
            }
        }

        // Keymap translation.
        if (e.type == SODNA_EVENT_CHARACTER && e.ch.code < 128) {
            int km = printable_mappings[e.ch.code];
            if (km > 0) {
                e.ch.code = km;
            } else if (km < 0) {
                e.type = SODNA_EVENT_KEY_DOWN;
                e.key.layout = -km;
            }
        } else if (e.type == SODNA_EVENT_KEY_DOWN && e.key.layout < 128) {
            int km = unprintable_mappings[e.key.layout];
            if (km > 0) {
                e.key.layout = km;
            } else if (km < 0) {
                e.type = SODNA_EVENT_CHARACTER;
                e.ch.code = -km;
            }
        }

        // Back to event handling.
        if (e.type == SODNA_EVENT_CHARACTER) {
            returnEvent->param1 = e.ch.code;
            returnEvent->eventType = KEYSTROKE;
            return;
        }

        if (e.type == SODNA_EVENT_KEY_DOWN) {
            returnEvent->eventType = KEYSTROKE;

            switch (e.key.layout) {
#define K(sodna, brogue) case sodna: returnEvent->param1 = brogue; return;
                K(SODNA_KEY_UP, UP_ARROW)
                K(SODNA_KEY_DOWN, DOWN_ARROW)
                K(SODNA_KEY_LEFT, LEFT_ARROW)
                K(SODNA_KEY_RIGHT, RIGHT_ARROW)
                K(SODNA_KEY_KP_1, NUMPAD_1)
                K(SODNA_KEY_KP_2, NUMPAD_2)
                K(SODNA_KEY_KP_3, NUMPAD_3)
                K(SODNA_KEY_KP_4, NUMPAD_4)
                K(SODNA_KEY_KP_5, NUMPAD_5)
                K(SODNA_KEY_KP_6, NUMPAD_6)
                K(SODNA_KEY_KP_7, NUMPAD_7)
                K(SODNA_KEY_KP_8, NUMPAD_8)
                K(SODNA_KEY_KP_9, NUMPAD_9)
                K(SODNA_KEY_KP_0, NUMPAD_0)
                K(SODNA_KEY_TAB, TAB_KEY)
                K(SODNA_KEY_ENTER, RETURN_KEY)
                K(SODNA_KEY_KP_ENTER, ENTER_KEY)
                K(SODNA_KEY_BACKSPACE, DELETE_KEY)
                K(SODNA_KEY_ESCAPE, ESCAPE_KEY)
#undef K
                    break;
            }
        }

        if (mouseMoved) {
            returnEvent->eventType = MOUSE_ENTERED_CELL;
            returnEvent->param1 = mouse_x;
            returnEvent->param2 = mouse_y;
            return;
        }

        waitTime = time + PAUSE_BETWEEN_EVENT_POLLING - sodna_ms_elapsed();
        if (waitTime > 0 && waitTime <= PAUSE_BETWEEN_EVENT_POLLING) {
            sodna_sleep_ms(waitTime);
        }
    }
Example #27
0
 friend event * get_event(shared_future& x) { return get_event(x.listener); }
Example #28
0
int main() {
    int sm_ret;
    EVENT *event = NULL;

    event = get_event();
    event->nodes = get_nodes();
    event->tracks = get_tracks(event->nodes);
    event->courses = get_courses(event->nodes, event->tracks);

    event->entrants = get_entrants();

/*
    event = read_event("data/name.txt");
    event->nodes = read_nodes("data/nodes.txt");
    event->tracks = read_tracks("data/tracks.txt", event->nodes);
    event->courses = read_courses("data/courses.txt", event->nodes, event->tracks);
    event->entrants = read_entrants("data/entrants.txt");

    read_event_data("data/cp_times_1.txt", event);*/


    do {
        sm_ret = show_menu();
        
        if(sm_ret == 1) {
            ENTRANT *ent = NULL;
            ent = query_entrant(event);

            if(ent == NULL) {
                continue;
            }
            
            print_entrant_header();
            print_entrant(ent);
        }
        
        else if (sm_ret == 2) {
            load_cp_data(event);
        }
        
        else if (sm_ret == 3) {
            print_all(event);
        }
        
        else if (sm_ret == 4) {
            not_started(event);
        }
        
        else if (sm_ret == 5) {
            finished(event);
        }
        
        else if (sm_ret == 6) {
            out_track(event);
        }
        
        else if(sm_ret == 0) {
            return EXIT_SUCCESS;
        }

    }while(1);
    
    return EXIT_SUCCESS;
}
Example #29
0
int main(int argc, char *argv[])
{
     if(argc != 2)
     {
          fprintf(stderr, "Usage:\nsaplayer <filename>\n");
          return 1;
     }
     
     // FIXME: add SDL_INIT_EVENTTHREAD on Windows and Mac?
     SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER);
     
     SASDL_init();
     SASDLContext *sasdl_ctx = SASDL_open(argv[1]);
     if(sasdl_ctx == NULL)
     {
          fprintf(stderr, "failed to open video file?\n");
          SDL_Quit();
          return 1;
     }

     // still very ugly...
     if(Mix_OpenAudio(sasdl_ctx->sa_ctx->a_codec_ctx->sample_rate, AUDIO_S16SYS,
                      sasdl_ctx->sa_ctx->a_codec_ctx->channels, 512) < 0) {
          fprintf(stderr, "Mix_OpenAudio: %s\n", SDL_GetError());
          SASDL_close(sasdl_ctx);
          SDL_Quit();
          return 1;
     }
     Mix_SetPostMix(SASDL_audio_decode, sasdl_ctx);

     double delta = 0.0f;
     SDL_Event event;
     int width = SASDL_get_video_width(sasdl_ctx);
     int height = SASDL_get_video_height(sasdl_ctx);
     
     SDL_Surface *screen = SDL_SetVideoMode(width, height, 32, SDL_SWSURFACE);
     int (*get_event)(SDL_Event *) = SDL_PollEvent;
     
     printf("video duration: %.3fs\n", SASDL_get_video_duration(sasdl_ctx));
     SASDL_play(sasdl_ctx);

     while(SASDL_eof(sasdl_ctx) == FALSE)
     {
          SASDL_draw(sasdl_ctx, screen);
          SDL_Flip(screen);

          while(get_event(&event))
               if(event.type == SDL_QUIT) {
                    goto PROGRAM_QUIT;
               } else if(event.type == SDL_KEYDOWN) {
                    switch(event.key.keysym.sym) {
                    case SDLK_LEFT:
                         delta = -10.0;
                         break;
                    case SDLK_RIGHT:
                         delta = 10.0;
                         break;
                    case SDLK_UP:
                         delta = -60.0;
                         break;
                    case SDLK_DOWN:
                         delta = 60.0;
                         break;
                    case SDLK_SPACE:
                         if(SASDL_get_video_status(sasdl_ctx) == SASDL_is_playing)
                         {
                              SASDL_pause(sasdl_ctx);
                              get_event = SDL_WaitEvent;
                              continue;
                         } else
                         {
                              SASDL_play(sasdl_ctx);
                              get_event = SDL_PollEvent;
                              goto NEXT_LOOP;
                         }
                    case SDLK_s:
                         SASDL_stop(sasdl_ctx);
                         SASDL_draw(sasdl_ctx, screen); // fill screen with black
                         SDL_Flip(screen);
                         get_event = SDL_WaitEvent;
                         continue;
                    default:
                         // ignore this event. get the next one.
                         continue;
                    }

                    double seek_dst = SASDL_get_video_clock(sasdl_ctx) + delta;
                    if(SASDL_seek_accurate(sasdl_ctx, seek_dst) < 0)
                         goto PROGRAM_QUIT;

                    SASDL_draw(sasdl_ctx, screen);
                    SDL_Flip(screen);
               }

          SASDL_wait_for_next_frame(sasdl_ctx);
     NEXT_LOOP:;
     }

PROGRAM_QUIT:
     Mix_CloseAudio();
     SASDL_close(sasdl_ctx);
     SDL_Quit();
     
     return 0;
}
Example #30
0
 static std::size_t dismiss_wait_many(waiter * w, Iter begin, Iter end) {
     std::size_t count = 0;
     for (auto  i = begin; i != end; ++i)
         if (auto e = get_event(*i)) count += e->dismiss_wait(w);
     return count;
 }