Ejemplo n.º 1
0
void msg_process(char * (*handler_request)(char *req_buf, int fd))
{
	LOCALTSS(tss);
	int resp_size;
	RPCREQ* req;
	char* resp;

	int fd;
	MSG_DATA *req_msg;
	MSG_DATA *resp_msg;


	req_msg = NULL;
	resp_msg = NULL;
	
	while(TRUE)
	{
		
		pthread_mutex_lock(&mutex);

		while (msg_list_head == NULL)
			pthread_cond_wait(&cond, &mutex);

	
		req_msg = msg_list_head;
		msg_list_head = msg_list_head->next;
		msg_list_len--;
		pthread_mutex_unlock(&mutex);

		if(!strncasecmp(RPC_RBD_MAGIC, req_msg->data, STRLEN(RPC_RBD_MAGIC)))
		{
			req = conn_build_req(req_msg->block_buffer, req_msg->n_size);
		}
		else
		{
			req = conn_build_req(req_msg->data, req_msg->n_size);
		}
		
		fd = req_msg->fd;

		if(req_msg->n_size)
		{
			resp = handler_request(req->data, fd);

			if (resp == NULL)
			{
				if (tss->tstat & TSS_PARSER_ERR)
				{
					resp = conn_build_resp_byte(RPC_PARSER_ERR, 0, NULL);
				}
				else
				{
					resp = conn_build_resp_byte(RPC_FAIL, 0, NULL);					
				}
			}
		}
		else
		{	resp = conn_build_resp_byte(RPC_FAIL, 0, NULL);
		}

		/* If it's the select where/range session, skip the success operation. */
		if((fd < 0) || (((RPCRESP *)resp)->status_code & RPC_SKIP_SEND))
		{
			//local msg, such as recovery task msg, so no need to response
			goto finish;
		}

		resp_size = conn_get_resp_size((RPCRESP *)resp);

		resp_msg = NULL;
		resp_msg = (MSG_DATA *)msg_mem_alloc();
		resp_msg->n_size = resp_size;
		resp_msg->block_buffer = NULL;
		Assert(resp_size < MSG_SIZE);
		MEMCPY(resp_msg->data, resp, resp_size);
		resp_msg->fd = fd;	
		
		struct epoll_event ev;
		ev.data.ptr = resp_msg;
	
		ev.events = EPOLLOUT | EPOLLET;

		epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &ev);

finish:

		if (req_msg->block_buffer != NULL)
		{
			free(req_msg->block_buffer);
		}
		
		msg_mem_free(req_msg);
  
		conn_destroy_req(req);
		conn_destroy_resp_byte(resp);		
		
		tss_init(tss);
	}
}
Ejemplo n.º 2
0
// Called once per step from python code. Puts the representedInputValues in the proper
// form for processing, then tells each GPU thread to take a step. Once they've finished
// the step, this function puts the representedOutputValues and spikes in the appropriate
// python arrays so that they can be read on the python side when this call returns
void step(float* input, float* output, float* probes, float* spikes, float start, float end, int n_steps)
{
  start_time = start;
  end_time = end;

  NengoGPUData* current_data;

  int i, j, k, l;

  for( i = 0; i < num_devices; i++)
  {
    current_data = nengo_data_array[i];
    memcpy(current_data->input_host->array, input,
           current_data->dimension * current_data->num_steps * sizeof(float));
  }

  // Tell the runner threads to run and then wait for them to finish.
  // The last of them to finish running will wake this thread up.
  pthread_mutex_lock(mutex);
  myCVsignal = 1;
  pthread_cond_broadcast(cv_GPUThreads);
  pthread_cond_wait(cv_JNI, mutex);
  pthread_mutex_unlock(mutex);

  current_data = nengo_data_array[0];
  memset(output, 0.0, current_data->dimension * current_data->num_steps * sizeof(float));

  for(i = 0; i < num_devices; i++)
  {
      current_data = nengo_data_array[i];

      for(j = 0; j < current_data->num_steps * current_data->dimension; j++)
      {
           output[j] += current_data->output_host->array[j];
      }
  }

  int probe_index = 0, spike_index = 0, index = 0;
  for(i = 0; i < nengo_data_array[0]->num_steps; i++)
  {
      for(j = 0; j < num_devices; j++)
      {
          current_data = nengo_data_array[j];

          for(k = 0; k < current_data->num_probes; k++)
          {
              probes[probe_index] =
                  current_data->probes_host->array[i * current_data->num_probes + k];

              if(current_data->num_spikes > 0)
              {
                  index = i * current_data->num_spikes
                          + k * current_data->neurons_per_item;

                  for(l = 0; l < current_data->neurons_per_item; l++)
                  {
                      spikes[spike_index] = current_data->spikes_host->array[index + l];
                      spike_index++;
                  }
              }

              probe_index++;
          }
      }
  }
}
Ejemplo n.º 3
0
void Conduction::wait(){
    pthread_cond_wait(&sig, &(Mutex &mutex));
}
Ejemplo n.º 4
0
static void * run_process(void * data)
{
    vx_world_t * world = data;


    while (world->process_running) {
        vx_world_listener_t * listener = NULL;
        char * buffer_name = NULL;

        // 1) Wait until there's data
        pthread_mutex_lock(&world->queue_mutex);
        while (zarray_size(world->buffer_queue) == 0 && zarray_size(world->listener_queue) == 0 && world->process_running) {
            pthread_cond_wait(&world->queue_cond, &world->queue_mutex);
        }

        if (!world->process_running) { // XXX cleaning out the queue?
            pthread_mutex_unlock(&world->queue_mutex);
            break;
        }

        // Processing new listeners takes priority
        if ( zarray_size(world->listener_queue) > 0) {
            zarray_get(world->listener_queue, 0, &listener);
            zarray_remove_index(world->listener_queue, 0, 0);
        } else {
            assert(zarray_size(world->buffer_queue) > 0);
            zarray_get(world->buffer_queue, 0, &buffer_name);
            zarray_remove_index(world->buffer_queue, 0, 0);
        }
        pthread_mutex_unlock(&world->queue_mutex);

        // Operation A: New listener
        if (listener != NULL) {
            // re-transmit each buffer that has already been serialized
            pthread_mutex_lock(&world->buffer_mutex);
            zhash_iterator_t itr;
            zhash_iterator_init(world->buffer_map, &itr);
            char * name = NULL;
            vx_buffer_t * buffer = NULL;
            while(zhash_iterator_next(&itr, &name, &buffer)) {
                if (buffer->front_codes->pos != 0) {
                    vx_code_output_stream_t * bresc_codes = make_buffer_resource_codes(buffer, buffer->front_resc);

                    // Doing a swap in 3 steps (instead of 4) like this
                    // is only safe if the listener is brand new, which we are
                    // guaranteed is the case in this chunk of code
                    listener->send_codes(listener, bresc_codes->data, bresc_codes->pos);
                    listener->send_resources(listener, buffer->front_resc);
                    listener->send_codes(listener, buffer->front_codes->data, buffer->front_codes->pos);

                    vx_code_output_stream_destroy(bresc_codes);
                }
            }

            pthread_mutex_unlock(&world->buffer_mutex);
        }

        // Operation B: buffer swap
        if (buffer_name != NULL) {
            vx_buffer_t * buffer = NULL;
            pthread_mutex_lock(&world->buffer_mutex);
            zhash_get(world->buffer_map, &buffer_name, &buffer);
            pthread_mutex_unlock(&world->buffer_mutex);

            delayed_swap(buffer);
        }

    }

    pthread_exit(NULL);
}
Ejemplo n.º 5
0
void sys_cond_wait(sys_cond_t *cond, sys_mutex_t *held_mutex)
{
    int result = pthread_cond_wait(&(cond->cond), &(held_mutex->mutex));
    assert(result == 0);
}
Ejemplo n.º 6
0
void __po_hi_gqueue_wait_for_incoming_event (__po_hi_task_id id,
                                             __po_hi_local_port_t* port)
{
#ifdef RTEMS_PURE
  rtems_status_code ret;
#endif

#ifdef _WIN32
  DWORD ret;
#endif

#if defined (POSIX) || defined (RTEMS_POSIX) || defined (XENO_POSIX)
  int error = pthread_mutex_lock (&__po_hi_gqueues_mutexes[id]);
  __DEBUGMSG("*** Locking (%d) %d\n", id, error);
#elif defined (XENO_NATIVE)
  rt_mutex_acquire (&__po_hi_gqueues_mutexes[id], TM_INFINITE);
#elif defined (RTEMS_PURE)
  ret = rtems_semaphore_obtain (__po_hi_gqueues_semaphores[id], RTEMS_WAIT, RTEMS_NO_TIMEOUT);
  if (ret != RTEMS_SUCCESSFUL)
    {
      __DEBUGMSG ("[GQUEUE] Cannot obtain semaphore in __po_hi_gqueue_store_in()\n");
    }
#elif defined (_WIN32)
  EnterCriticalSection(&__po_hi_gqueues_cs[id]);
#endif

  while(__po_hi_gqueues_queue_is_empty[id] == 1)
    {
      __PO_HI_INSTRUMENTATION_VCD_WRITE("0t%d\n", id);

#if defined (POSIX) || defined (RTEMS_POSIX) || defined (XENO_POSIX)
      __DEBUGMSG("*** Waiting (%d)\n", id);
      int error = pthread_cond_wait (&__po_hi_gqueues_conds[id],
                                     &__po_hi_gqueues_mutexes[id]);
      __DEBUGMSG("*** Done Waiting (%d) %d\n", id, error);
#elif defined (XENO_NATIVE)
      rt_cond_wait (&__po_hi_gqueues_conds[id], &__po_hi_gqueues_mutexes[id], TM_INFINITE);
#elif defined (RTEMS_PURE)
      ret = rtems_semaphore_release (__po_hi_gqueues_semaphores[id]);
      if (ret != RTEMS_SUCCESSFUL)
        {
          __DEBUGMSG ("[GQUEUE] Cannot obtain semaphore in __po_hi_gqueue_store_in()\n");
        }
      rtems_task_wake_after (1);
      ret = rtems_semaphore_obtain (__po_hi_gqueues_semaphores[id], RTEMS_WAIT, RTEMS_NO_TIMEOUT);
      if (ret != RTEMS_SUCCESSFUL)
        {
          __DEBUGMSG ("[GQUEUE] Cannot obtain semaphore in __po_hi_gqueue_store_in()\n");
        }
      else
        {
          __PO_HI_DEBUG_CRITICAL ("[GQUEUE] semaphore %d obtained\n", id);
        }
#elif defined (_WIN32)
      LeaveCriticalSection(&__po_hi_gqueues_cs[id]);

      ret = WaitForSingleObject (__po_hi_gqueues_events[id], INFINITE);
      if (ret == WAIT_FAILED)
        {
          __PO_HI_DEBUG_DEBUG ("[GQUEUE] Wait failed\n");
        }
      EnterCriticalSection(&__po_hi_gqueues_cs[id]);
#endif

      __PO_HI_INSTRUMENTATION_VCD_WRITE("1t%d\n", id);
    }

  __DEBUGMSG ("[GQUEUE] Gogo kiki\n");
  *port = __po_hi_gqueues_global_history[id][__po_hi_gqueues_global_history_offset[id]];


#if defined (POSIX) || defined (RTEMS_POSIX) || defined (XENO_POSIX)
  pthread_mutex_unlock (&__po_hi_gqueues_mutexes[id]);
#elif defined (XENO_NATIVE)
  rt_mutex_release (&__po_hi_gqueues_mutexes[id]);
#elif defined (_WIN32)
  LeaveCriticalSection(&__po_hi_gqueues_cs[id]);
#elif defined (RTEMS_PURE)
  ret = rtems_semaphore_release (__po_hi_gqueues_semaphores[id]);
  if (ret != RTEMS_SUCCESSFUL)
    {
      __DEBUGMSG ("[GQUEUE] Cannot release semaphore in __po_hi_gqueue_store_in()\n");
    }

  __PO_HI_DEBUG_CRITICAL ("[GQUEUE] semaphore %d released\n", id);
#endif

}
Ejemplo n.º 7
0
/*----------------------------------------------------------------------------*/
int 
mtcp_epoll_wait(mctx_t mctx, int epid, 
		struct mtcp_epoll_event *events, int maxevents, int timeout)
{
	mtcp_manager_t mtcp;
	struct mtcp_epoll *ep;
	struct event_queue *eq;
	struct event_queue *eq_shadow;
	socket_map_t event_socket;
	int validity;
	int i, cnt, ret;
	int num_events;

	mtcp = GetMTCPManager(mctx);
	if (!mtcp) {
		return -1;
	}

	if (epid < 0 || epid >= CONFIG.max_concurrency) {
		TRACE_API("Epoll id %d out of range.\n", epid);
		errno = EBADF;
		return -1;
	}

	if (mtcp->smap[epid].socktype == MTCP_SOCK_UNUSED) {
		errno = EBADF;
		return -1;
	}

	if (mtcp->smap[epid].socktype != MTCP_SOCK_EPOLL) {
		errno = EINVAL;
		return -1;
	}

	ep = mtcp->smap[epid].ep;
	if (!ep || !events || maxevents <= 0) {
		errno = EINVAL;
		return -1;
	}

	ep->stat.calls++;

#if SPIN_BEFORE_SLEEP
	int spin = 0;
	while (ep->num_events == 0 && spin < SPIN_THRESH) {
		spin++;
	}
#endif /* SPIN_BEFORE_SLEEP */

	if (pthread_mutex_lock(&ep->epoll_lock)) {
		if (errno == EDEADLK)
			perror("mtcp_epoll_wait: epoll_lock blocked\n");
		assert(0);
	}

wait:
	eq = ep->usr_queue;
	eq_shadow = ep->usr_shadow_queue;

	/* wait until event occurs */
	while (eq->num_events == 0 && eq_shadow->num_events == 0 && timeout != 0) {

#if INTR_SLEEPING_MTCP
		/* signal to mtcp thread if it is sleeping */
		if (mtcp->wakeup_flag && mtcp->is_sleeping) {
			pthread_kill(mtcp->ctx->thread, SIGUSR1);
		}
#endif
		ep->stat.waits++;
		ep->waiting = TRUE;
		if (timeout > 0) {
			struct timespec deadline;

			clock_gettime(CLOCK_REALTIME, &deadline);
			if (timeout > 1000) {
				int sec;
				sec = timeout / 1000;
				deadline.tv_sec += sec;
				timeout -= sec * 1000;
			}

			if (deadline.tv_nsec >= 1000000000) {
				deadline.tv_sec++;
				deadline.tv_nsec -= 1000000000;
			}

			//deadline.tv_sec = mtcp->cur_tv.tv_sec;
			//deadline.tv_nsec = (mtcp->cur_tv.tv_usec + timeout * 1000) * 1000;
			ret = pthread_cond_timedwait(&ep->epoll_cond, 
					&ep->epoll_lock, &deadline);
			if (ret && ret != ETIMEDOUT) {
				/* errno set by pthread_cond_timedwait() */
				pthread_mutex_unlock(&ep->epoll_lock);
				TRACE_ERROR("pthread_cond_timedwait failed. ret: %d, error: %s\n", 
						ret, strerror(errno));
				return -1;
			}
			timeout = 0;
		} else if (timeout < 0) {
			ret = pthread_cond_wait(&ep->epoll_cond, &ep->epoll_lock);
			if (ret) {
				/* errno set by pthread_cond_wait() */
				pthread_mutex_unlock(&ep->epoll_lock);
				TRACE_ERROR("pthread_cond_wait failed. ret: %d, error: %s\n", 
						ret, strerror(errno));
				return -1;
			}
		}
		ep->waiting = FALSE;

		if (mtcp->ctx->done || mtcp->ctx->exit || mtcp->ctx->interrupt) {
			mtcp->ctx->interrupt = FALSE;
			//ret = pthread_cond_signal(&ep->epoll_cond);
			pthread_mutex_unlock(&ep->epoll_lock);
			errno = EINTR;
			return -1;
		}
	
	}
	
	/* fetch events from the user event queue */
	cnt = 0;
	num_events = eq->num_events;
	for (i = 0; i < num_events && cnt < maxevents; i++) {
		event_socket = &mtcp->smap[eq->events[eq->start].sockid];
		validity = TRUE;
		if (event_socket->socktype == MTCP_SOCK_UNUSED)
			validity = FALSE;
		if (!(event_socket->epoll & eq->events[eq->start].ev.events))
			validity = FALSE;
		if (!(event_socket->events & eq->events[eq->start].ev.events))
			validity = FALSE;

		if (validity) {
			events[cnt++] = eq->events[eq->start].ev;
			assert(eq->events[eq->start].sockid >= 0);

			TRACE_EPOLL("Socket %d: Handled event. event: %s, "
					"start: %u, end: %u, num: %u\n", 
					event_socket->id, 
					EventToString(eq->events[eq->start].ev.events), 
					eq->start, eq->end, eq->num_events);
			ep->stat.handled++;
		} else {
			TRACE_EPOLL("Socket %d: event %s invalidated.\n", 
					eq->events[eq->start].sockid, 
					EventToString(eq->events[eq->start].ev.events));
			ep->stat.invalidated++;
		}
		event_socket->events &= (~eq->events[eq->start].ev.events);

		eq->start++;
		eq->num_events--;
		if (eq->start >= eq->size) {
			eq->start = 0;
		}
	}

	/* fetch eventes from user shadow event queue */
	eq = ep->usr_shadow_queue;
	num_events = eq->num_events;
	for (i = 0; i < num_events && cnt < maxevents; i++) {
		event_socket = &mtcp->smap[eq->events[eq->start].sockid];
		validity = TRUE;
		if (event_socket->socktype == MTCP_SOCK_UNUSED)
			validity = FALSE;
		if (!(event_socket->epoll & eq->events[eq->start].ev.events))
			validity = FALSE;
		if (!(event_socket->events & eq->events[eq->start].ev.events))
			validity = FALSE;

		if (validity) {
			events[cnt++] = eq->events[eq->start].ev;
			assert(eq->events[eq->start].sockid >= 0);

			TRACE_EPOLL("Socket %d: Handled event. event: %s, "
					"start: %u, end: %u, num: %u\n", 
					event_socket->id, 
					EventToString(eq->events[eq->start].ev.events), 
					eq->start, eq->end, eq->num_events);
			ep->stat.handled++;
		} else {
			TRACE_EPOLL("Socket %d: event %s invalidated.\n", 
					eq->events[eq->start].sockid, 
					EventToString(eq->events[eq->start].ev.events));
			ep->stat.invalidated++;
		}
		event_socket->events &= (~eq->events[eq->start].ev.events);

		eq->start++;
		eq->num_events--;
		if (eq->start >= eq->size) {
			eq->start = 0;
		}
	}

	if (cnt == 0 && timeout != 0)
		goto wait;

	pthread_mutex_unlock(&ep->epoll_lock);

	return cnt;
}
/** RX_PDSCH Decoding Thread */
static void * rx_pdsch_thread(void *param)
{

  //unsigned long cpuid;
  uint8_t dlsch_thread_index = 0;
  uint8_t pilot2,harq_pid,subframe;
  //  uint8_t last_slot;

  uint8_t dual_stream_UE = 0;
  uint8_t i_mod = 0;


#ifdef RTAI
  RT_TASK *task;
#endif

  int m,eNB_id = 0;
  int eNB_id_i = 1;
  PHY_VARS_UE *UE = PHY_vars_UE_g[0][0];

#ifdef RTAI
  task = rt_task_init_schmod(nam2num("RX_PDSCH_THREAD"), 0, 0, 0, SCHED_FIFO, 0xF);

  if (task==NULL) {
    LOG_E(PHY,"[SCHED][RX_PDSCH] Problem starting rx_pdsch thread!!!!\n");
    return 0;
  } else {
    LOG_I(PHY,"[SCHED][RX_PDSCH] rx_pdsch_thread started for with id %p\n",task);
  }

#endif

  mlockall(MCL_CURRENT | MCL_FUTURE);

  //rt_set_runnable_on_cpuid(task,1);
  //cpuid = rtai_cpuid();

#ifdef HARD_RT
  rt_make_hard_real_time();
#endif

  if (UE->lte_frame_parms.Ncp == NORMAL) {  // normal prefix
    pilot2 = 7;
  } else { // extended prefix
    pilot2 = 6;
  }


  while (!oai_exit) {
    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDSCH_THREAD, 0);

    if (pthread_mutex_lock(&rx_pdsch_mutex) != 0) {
      LOG_E(PHY,"[SCHED][RX_PDSCH] error locking mutex.\n");
    } else {
      while (rx_pdsch_instance_cnt < 0) {
        pthread_cond_wait(&rx_pdsch_cond,&rx_pdsch_mutex);
      }

      if (pthread_mutex_unlock(&rx_pdsch_mutex) != 0) {
        LOG_E(PHY,"[SCHED][RX_PDSCH] error unlocking mutex.\n");
      }
    }

    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PDSCH_THREAD, 1);

    //      last_slot = rx_pdsch_slot;
    subframe = UE->slot_rx>>1;
    // Important! assumption that PDCCH procedure of next SF is not called yet
    harq_pid = UE->dlsch_ue[eNB_id][0]->current_harq_pid;
    UE->dlsch_ue[eNB_id][0]->harq_processes[harq_pid]->G = get_G(&UE->lte_frame_parms,
        UE->dlsch_ue[eNB_id][0]->harq_processes[harq_pid]->nb_rb,
        UE->dlsch_ue[eNB_id][0]->harq_processes[harq_pid]->rb_alloc,
        get_Qm(UE->dlsch_ue[eNB_id][0]->harq_processes[harq_pid]->mcs),
        UE->dlsch_ue[eNB_id][0]->harq_processes[harq_pid]->Nl,
        UE->lte_ue_pdcch_vars[eNB_id]->num_pdcch_symbols,
        UE->frame_rx,subframe);

    if ((UE->transmission_mode[eNB_id] == 5) &&
        (UE->dlsch_ue[eNB_id][0]->harq_processes[harq_pid]->dl_power_off==0) &&
        (openair_daq_vars.use_ia_receiver > 0)) {
      dual_stream_UE = 1;
      eNB_id_i = UE->n_connected_eNB;

      if (openair_daq_vars.use_ia_receiver == 2) {
        i_mod =  get_Qm(((UE->frame_rx%1024)/3)%28);
      } else {
        i_mod =  get_Qm(UE->dlsch_ue[eNB_id][0]->harq_processes[harq_pid]->mcs);
      }
    } else {
      dual_stream_UE = 0;
      eNB_id_i = eNB_id+1;
      i_mod = 0;
    }

    if (oai_exit) break;

    LOG_D(PHY,"[SCHED][RX_PDSCH] Frame %d, slot %d: Calling rx_pdsch_decoding with harq_pid %d\n",UE->frame_rx,UE->slot_rx,harq_pid);


    // Check if we are in even or odd slot
    if (UE->slot_rx%2) { // odd slots

      // measure time
      //time0 = rt_get_time_ns();
      //        rt_printk("[SCHED][RX_PDSCH][before rx_pdsch] Frame %d, slot %d, time %llu\n",UE->frame,last_slot,rt_get_time_ns());
      for (m=pilot2; m<UE->lte_frame_parms.symbols_per_tti; m++) {

        rx_pdsch(UE,
                 PDSCH,
                 eNB_id,
                 eNB_id_i,
                 subframe,
                 m,
                 0,
                 dual_stream_UE,
                 i_mod,
                 harq_pid);

      }

      //        time1 = rt_get_time_ns();
      //        rt_printk("[SCHED][RX_PDSCH] Frame %d, slot %d, start %llu, end %llu, proc time: %llu ns\n",UE->frame_rx,last_slot,time0,time1,(time1-time0));

      dlsch_thread_index = harq_pid;

      if (pthread_mutex_lock (&dlsch_mutex[dlsch_thread_index]) != 0) {               // Signal MAC_PHY Scheduler
        LOG_E(PHY,"[UE  %d] ERROR pthread_mutex_lock\n",UE->Mod_id);     // lock before accessing shared resource
        //  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PHY_PROCEDURES_UE_RX, VCD_FUNCTION_OUT);
        //return(-1);
      }

      dlsch_instance_cnt[dlsch_thread_index]++;
      dlsch_subframe[dlsch_thread_index] = subframe;
      pthread_mutex_unlock (&dlsch_mutex[dlsch_thread_index]);

      if (dlsch_instance_cnt[dlsch_thread_index] == 0) {
        if (pthread_cond_signal(&dlsch_cond[dlsch_thread_index]) != 0) {
          LOG_E(PHY,"[UE  %d] ERROR pthread_cond_signal for dlsch_cond[%d]\n",UE->Mod_id,dlsch_thread_index);
          //    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PHY_PROCEDURES_UE_RX, VCD_FUNCTION_OUT);
          //return(-1);
        }
      } else {
        LOG_W(PHY,"[UE  %d] DLSCH thread for dlsch_thread_index %d busy!!!\n",UE->Mod_id,dlsch_thread_index);
        //  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_PHY_PROCEDURES_UE_RX, VCD_FUNCTION_OUT);
        //return(-1);
      }

    } else { // even slots

      for (m=UE->lte_ue_pdcch_vars[eNB_id]->num_pdcch_symbols; m<pilot2; m++) {

        rx_pdsch(UE,
                 PDSCH,
                 eNB_id,
                 eNB_id_i,
                 subframe,
                 m,
                 (m==UE->lte_ue_pdcch_vars[eNB_id]->num_pdcch_symbols)?1:0,   // first_symbol_flag
                 dual_stream_UE,
                 i_mod,
                 harq_pid);
      }
    }


    if (pthread_mutex_lock(&rx_pdsch_mutex) != 0) {
      msg("[openair][SCHED][RX_PDSCH] error locking mutex.\n");
    } else {
      rx_pdsch_instance_cnt--;

      if (pthread_mutex_unlock(&rx_pdsch_mutex) != 0) {
        msg("[openair][SCHED][RX_PDSCH] error unlocking mutex.\n");
      }
    }

  }

#ifdef HARD_RT
  rt_make_soft_real_time();
#endif

  LOG_D(PHY,"[openair][SCHED][RX_PDSCH] RX_PDSCH thread exiting\n");

  return 0;
}
Ejemplo n.º 9
0
 /**
  * Waits until this object is signalled with signal().
  *
  * @param mutex a mutex which is already locked, which is unlocked
  * atomically while we wait
  */
 void Wait(PosixMutex &mutex) {
   pthread_cond_wait(&cond, &mutex.mutex);
 }
Ejemplo n.º 10
0
void get_audio(float *lb, float *rb, int samples)
{
	PlayerCtx *ctx = g_ctx;

	if (ctx->audio_idx == -1) {
		memset(lb, 0, samples * sizeof(*lb));
		memset(rb, 0, samples * sizeof(*rb));
		return;
	}

	pthread_mutex_lock(&ctx->display_mode_mutex);
	DisplayMode display_mode = ctx->display_mode;
	pthread_mutex_unlock(&ctx->display_mode_mutex);

	if (display_mode != PLAY)
	{
		if (display_mode == PAUSE) {
			printf("get_audio: paused\n");
			if (!ctx->cur_frame) {
				next_video_frame(ctx);
			}
			while (ctx->cur_frame->seekid != ctx->cur_seekid &&
				   ctx->cur_frame->seekid != -ctx->cur_seekid) {
				printf("Drop audio due to seek\n");
				drop_audio(ctx, 1);
				next_video_frame(ctx);
				drop_audio(ctx, 1);
			}
			if (ctx->skip_frame) {
				ctx->skip_frame = 0;
				drop_audio(ctx, 1);
				next_video_frame(ctx);
				drop_audio(ctx, 1);
			}
			printf("get_audio: pause complete\n");
		}
		memset(lb, 0, samples * sizeof(*lb));
		memset(rb, 0, samples * sizeof(*rb));
		return;
	}
	pthread_mutex_lock(&ctx->settings_mutex);
	double volume = ctx->settings.volume / 100.0;
	pthread_mutex_unlock(&ctx->settings_mutex);

	while (samples) {
		double pts = -1;

		pthread_mutex_lock(&ctx->a_buf_mutex);
		int have_samples = ctx->a_buf_put - ctx->a_buf_get;
		if (!have_samples) {
			printf("Wait for audio\n");
			pthread_cond_wait(&ctx->a_buf_not_empty, &ctx->a_buf_mutex);
			pthread_mutex_unlock(&ctx->a_buf_mutex);
			continue;
		}
		if (have_samples < 0)
			have_samples += ctx->a_buf_len;
		pthread_mutex_unlock(&ctx->a_buf_mutex);

		int get = ctx->a_buf_get;
		int played = 0;
		while (samples && have_samples--) {
			if (ctx->a_buf[get].seekid == -ctx->cur_seekid) {
				memset(lb, 0, sizeof(*lb) * samples);
				memset(rb, 0, sizeof(*rb) * samples);
				samples = 0;
				break;
			}
			if (ctx->a_buf[get].seekid == ctx->cur_seekid) {
				pts = ctx->a_buf[get].pts;
				*lb++ = ctx->a_buf[get].l / 32768.0 * volume;
				*rb++ = ctx->a_buf[get].r / 32768.0 * volume;
				samples--;
				played++;
			}
			if (++get >= ctx->a_buf_len)
				get = 0;
		}

		pthread_mutex_lock(&ctx->a_buf_mutex);
		ctx->a_buf_get = get;
		pthread_cond_signal(&ctx->a_buf_not_full);
		pthread_mutex_unlock(&ctx->a_buf_mutex);

		printf("Played %d samples, next pts %f\n", played, pts);

		while (1) {
			if (!ctx->cur_frame) {
				next_video_frame(ctx);
				continue;
			}
			if (ctx->cur_frame->seekid == -ctx->cur_seekid)
				break;
			double next_pts = ctx->cur_frame->pts;
			if (ctx->last_frame_pts != -1)
				next_pts = 2 * ctx->cur_frame->pts - ctx->last_frame_pts;
			if (pts > next_pts || ctx->cur_frame->seekid != ctx->cur_seekid) {
				if (next_video_frame(ctx))
					continue;
			}
			break;
		}
	}
}
Ejemplo n.º 11
0
/*
 * Hook called by EGL to acquire a buffer. This call may block if no
 * buffers are available.
 *
 * The window holds a reference to the buffer between dequeueBuffer and
 * either queueBuffer or cancelBuffer, so clients only need their own
 * reference if they might use the buffer after queueing or canceling it.
 * Holding a reference to a buffer after queueing or canceling it is only
 * allowed if a specific buffer count has been set.
 *
 * The libsync fence file descriptor returned in the int pointed to by the
 * fenceFd argument will refer to the fence that must signal before the
 * dequeued buffer may be written to.  A value of -1 indicates that the
 * caller may access the buffer immediately without waiting on a fence.  If
 * a valid file descriptor is returned (i.e. any value except -1) then the
 * caller is responsible for closing the file descriptor.
 *
 * Returns 0 on success or -errno on error.
 */
int FbDevNativeWindow::dequeueBuffer(BaseNativeWindowBuffer** buffer, int *fenceFd)
{
    HYBRIS_TRACE_BEGIN("fbdev-platform", "dequeueBuffer", "");
    FbDevNativeWindowBuffer* fbnb=NULL;

    pthread_mutex_lock(&_mutex);

    if (m_allocateBuffers)
        reallocateBuffers();

    HYBRIS_TRACE_BEGIN("fbdev-platform", "dequeueBuffer-wait", "");
#if defined(DEBUG)

    if (m_frontBuf)
        TRACE("Status: Has front buf %p", m_frontBuf);

    std::list<FbDevNativeWindowBuffer*>::iterator cit = m_bufList.begin();
    for (; cit != m_bufList.end(); ++cit)
    {
        TRACE("Status: Buffer %p with busy %i\n", (*cit), (*cit)->busy);
    }
#endif

    while (m_freeBufs==0)
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    while (1)
    {
        std::list<FbDevNativeWindowBuffer*>::iterator it = m_bufList.begin();
        for (; it != m_bufList.end(); ++it)
        {
            if (*it==m_frontBuf)
                continue;
            if ((*it)->busy==0)
            {
                TRACE("Found a free non-front buffer");
                break;
            }
        }

        if (it == m_bufList.end())
        {
#if ANDROID_VERSION_MAJOR<=4 && ANDROID_VERSION_MINOR<2
            /*
             * This is acceptable in case you are on a stack that calls lock() before starting to render into buffer
             * When you are using fences (>= 2) you'll be waiting on the fence to signal instead. 
             * 
             * This optimization allows eglSwapBuffers to return and you can begin to utilize the GPU for rendering. 
             * The actual lock() probably first comes at glFlush/eglSwapBuffers
            */
            if (m_frontBuf && m_frontBuf->busy == 0)
            {
                TRACE("Used front buffer as buffer");
                fbnb = m_frontBuf;
                break;
            }
#endif
            // have to wait once again
            pthread_cond_wait(&_cond, &_mutex);
            continue;
        }

        fbnb = *it;
        break;
    }

    HYBRIS_TRACE_END("fbdev-platform", "dequeueBuffer-wait", "");
    assert(fbnb!=NULL);
    fbnb->busy = 1;
    m_freeBufs--;

    *buffer = fbnb;
    *fenceFd = -1;

    TRACE("%lu DONE --> %p", pthread_self(), fbnb);
    pthread_mutex_unlock(&_mutex);
    HYBRIS_TRACE_END("fbdev-platform", "dequeueBuffer", "");
    return 0;
}
Ejemplo n.º 12
0
size_t decode_video(PlayerCtx *ctx, AVPacket *packet, int new_packet, int32_t seekid)
{
	int decoded;
	int got_frame;

	if (!new_packet)
		fprintf(stderr, "warn: multi-frame video packets, pts might be inaccurate\n");

	ctx->v_pkt_pts = packet->pts;

	decoded = avcodec_decode_video2(ctx->v_codec_ctx, ctx->v_frame, &got_frame, packet);
	if (decoded < 0) {
		fprintf(stderr, "Error while decoding video frame\n");
		return packet->size;
	}
	if (!got_frame)
		return decoded;

	// The pts magic guesswork
	int64_t pts = AV_NOPTS_VALUE;
	int64_t *p_pts = (int64_t*)ctx->v_frame->opaque;
	int64_t frame_pts = AV_NOPTS_VALUE;
	if (p_pts)
		frame_pts = *p_pts;
	if (packet->dts != AV_NOPTS_VALUE) {
		ctx->v_faulty_dts += packet->dts <= ctx->v_last_dts;
		ctx->v_last_dts = packet->dts;
	}
	if (frame_pts != AV_NOPTS_VALUE) {
		ctx->v_faulty_pts += frame_pts <= ctx->v_last_pts;
		ctx->v_last_pts = frame_pts;
	}
	if ((ctx->v_faulty_pts <= ctx->v_faulty_dts || packet->dts == AV_NOPTS_VALUE)
		&& frame_pts != AV_NOPTS_VALUE)
		pts = frame_pts;
	else
		pts = packet->dts;

	if (pts == AV_NOPTS_VALUE) {
		if (ctx->v_last_pts != AV_NOPTS_VALUE) {
			pts = ctx->v_last_pts++;
		} else if (ctx->v_last_dts != AV_NOPTS_VALUE) {
			pts = ctx->v_last_dts++;
		}
	}

	if (pts == AV_NOPTS_VALUE) {
		if (ctx->v_last_pts != AV_NOPTS_VALUE) {
			pts = ctx->v_last_pts++;
		} else if (ctx->v_last_dts != AV_NOPTS_VALUE) {
			pts = ctx->v_last_dts++;
		} else {
			pts = 0;
		}
	}

	pthread_mutex_lock(&ctx->v_buf_mutex);
	while (((ctx->v_buf_put + 1) % ctx->v_buf_len) == ctx->v_buf_get) {
		printf("Wait for space in video buffer\n");
		pthread_cond_wait(&ctx->v_buf_not_full, &ctx->v_buf_mutex);
	}
	pthread_mutex_unlock(&ctx->v_buf_mutex);

	VideoFrame *frame = ctx->v_bufs[ctx->v_buf_put];
	if (!frame) {
		frame = malloc(sizeof(VideoFrame));
		frame->stride = ctx->v_frame->linesize[0];
		frame->data_size = frame->stride * ctx->height;
		frame->data = malloc(frame->data_size);
		ctx->v_bufs[ctx->v_buf_put] = frame;
	}

	if (frame->stride != ctx->v_frame->linesize[0]) {
		fprintf(stderr, "stride mismatch: %d != %d\n", (int)frame->stride, ctx->v_frame->linesize[0]);
		return decoded;
	}

	if (!ctx->v_sws_ctx) {
		ctx->v_sws_ctx = sws_getContext(ctx->width, ctx->height, ctx->v_codec_ctx->pix_fmt,
										ctx->width, ctx->height, PIX_FMT_GRAY8, SWS_BICUBIC,
										NULL, NULL, NULL);
	}

	AVPicture pict;
	pict.data[0] = frame->data;
	pict.linesize[0] = frame->stride;

	sws_scale(ctx->v_sws_ctx, ctx->v_frame->data, ctx->v_frame->linesize, 0, ctx->height, pict.data, pict.linesize);

	frame->pts = av_q2d(ctx->v_stream->time_base) * pts;
	frame->seekid = seekid;

	printf("Put frame %d (pts:%f seekid:%d)\n", ctx->v_buf_put, frame->pts, seekid);
	pthread_mutex_lock(&ctx->v_buf_mutex);
	if (++ctx->v_buf_put == ctx->v_buf_len)
		ctx->v_buf_put = 0;
	pthread_cond_signal(&ctx->v_buf_not_empty);
	pthread_mutex_unlock(&ctx->v_buf_mutex);

	return decoded;
}
Ejemplo n.º 13
0
size_t decode_audio(PlayerCtx *ctx, AVPacket *packet, int new_packet, int32_t seekid)
{
	int bytes = ctx->a_stride * AVCODEC_MAX_AUDIO_FRAME_SIZE;
	int decoded;

	decoded = avcodec_decode_audio3(ctx->a_codec_ctx, ctx->a_ibuf, &bytes, packet);
	if (decoded < 0) {
		fprintf(stderr, "Error while decoding audio frame\n");
		return packet->size;
	}
	int in_samples = bytes / ctx->a_stride;
	if (!in_samples)
		return decoded;


	int out_samples;
	out_samples = audio_resample(ctx->a_resampler, ctx->a_rbuf, ctx->a_ibuf, in_samples);

	pthread_mutex_lock(&ctx->a_buf_mutex);

	int free_samples;
	while (1) {
		free_samples = ctx->a_buf_get - ctx->a_buf_put;
		if (free_samples <= 0)
			free_samples += ctx->a_buf_len;

		if (free_samples <= out_samples) {
			printf("Wait for space in audio buffer\n");
			pthread_cond_wait(&ctx->a_buf_not_full, &ctx->a_buf_mutex);
		} else {
			break;
		}
	}
	pthread_mutex_unlock(&ctx->a_buf_mutex);

	if (new_packet && packet->pts != AV_NOPTS_VALUE)
		ctx->a_cur_pts = av_q2d(ctx->a_stream->time_base) * packet->pts;

	int put = ctx->a_buf_put;
	short *rbuf = ctx->a_rbuf;
	int i;
	for (i = 0; i < out_samples; i++) {
		ctx->a_buf[put].l = *rbuf++;
		ctx->a_buf[put].r = *rbuf++;
		rbuf += ctx->a_ch - 2;
		ctx->a_buf[put].seekid = seekid;
		ctx->a_buf[put].pts = ctx->a_cur_pts;
		put++;
		ctx->a_cur_pts += 1.0/SAMPLE_RATE;
		if (put == ctx->a_buf_len)
			put = 0;
	}

	printf("Put %d audio samples at pts %f\n", out_samples, ctx->a_cur_pts);

	pthread_mutex_lock(&ctx->a_buf_mutex);
	ctx->a_buf_put = put;
	pthread_cond_signal(&ctx->a_buf_not_empty);
	pthread_mutex_unlock(&ctx->a_buf_mutex);

	return decoded;
}
Ejemplo n.º 14
0
int main(void)
{
	struct sigaction sigact;
	int r = 1;

	r = libusb_init(NULL);
	if (r < 0) {
		fprintf(stderr, "failed to initialise libusb\n");
		exit(1);
	}

	r = find_dpfp_device();
	if (r < 0) {
		fprintf(stderr, "Could not find/open device\n");
		goto out;
	}

	r = libusb_claim_interface(devh, 0);
	if (r < 0) {
		fprintf(stderr, "usb_claim_interface error %d %s\n", r, strerror(-r));
		goto out;
	}
	printf("claimed interface\n");

	r = print_f0_data();
	if (r < 0)
		goto out_release;

	r = do_init();
	if (r < 0)
		goto out_deinit;

	/* async from here onwards */

	sigact.sa_handler = sighandler;
	sigemptyset(&sigact.sa_mask);
	sigact.sa_flags = 0;
	sigaction(SIGINT, &sigact, NULL);
	sigaction(SIGTERM, &sigact, NULL);
	sigaction(SIGQUIT, &sigact, NULL);

	r = pthread_create(&poll_thread, NULL, poll_thread_main, NULL);
	if (r)
		goto out_deinit;

	r = alloc_transfers();
	if (r < 0) {
		request_exit(1);
		pthread_join(poll_thread, NULL);
		goto out_deinit;
	}

	r = init_capture();
	if (r < 0) {
		request_exit(1);
		pthread_join(poll_thread, NULL);
		goto out_deinit;
	}

	while (!do_exit) {
		pthread_mutex_lock(&exit_cond_lock);
		pthread_cond_wait(&exit_cond, &exit_cond_lock);
		pthread_mutex_unlock(&exit_cond_lock);
	}

	printf("shutting down...\n");
	pthread_join(poll_thread, NULL);

	r = libusb_cancel_transfer(irq_transfer);
	if (r < 0) {
		request_exit(1);
		goto out_deinit;
	}

	r = libusb_cancel_transfer(img_transfer);
	if (r < 0) {
		request_exit(1);
		goto out_deinit;
	}

	while (img_transfer || irq_transfer)
		if (libusb_handle_events(NULL) < 0)
			break;

	if (do_exit == 1)
		r = 0;
	else
		r = 1;

out_deinit:
	libusb_free_transfer(img_transfer);
	libusb_free_transfer(irq_transfer);
	set_mode(0);
	set_hwstat(0x80);
out_release:
	libusb_release_interface(devh, 0);
out:
	libusb_close(devh);
	libusb_exit(NULL);
	return r >= 0 ? r : -r;
}
Ejemplo n.º 15
0
void* alarm_thread(void* arg)
{
	alarm_t* alarm;
	struct timespec cond_time;
	time_t now;
	int status,expired;
	status=pthread_mutex_lock(&alarm_mutex);
	if(status!=0)
	{
		err_abort(status,"Lock mutex");
	}
	while(1)
	{
		current_alarm=0;
		while(alarm_list == NULL)
	  	{
			status=pthread_cond_wait(&alarm_cond,&alarm_mutex);
			if(status!=0)
			{
				err_abort(status,"Wait on cond");
			}
		}
		alarm=alarm_list;
		alarm_list=alarm->link;
		now=time(NULL);
		expired=0;
		if(alarm->time > now)
		{
#ifdef DEBUG
			printf("[waiting:%d(%d)\"%s\"]\n",alarm->time,
					alarm->time-time(NULL),alarm->message);
#endif				
			cond_time.tv_sec=alarm->time;
			cond_time.tv_nsec=0;
			current_alarm=alarm->time;
			while(current_alarm==alarm->time)
			{
				status=pthread_cond_timedwait(
						&alarm_cond,&alarm_mutex,&cond_time);
				if(status==ETIMEDOUT)
				{
					expired=1;
					break;
				}
				if(status!=0)
				{
					err_abort(status,"Cond timedwait");
				}
			}
			if(!expired)
			{
				alarm_insert(alarm);
			}
		}			
		else
		{
			expired=1;
		}
		if(expired)
		{
			printf("(%d) %s\n",alarm->seconds,alarm->message);
			free(alarm);
		}
	}
}
Ejemplo n.º 16
0
static int at_send_command_full_nolock (const char *command, ATCommandType type,
                    const char *responsePrefix, const char *smspdu,
                    long long timeoutMsec, ATResponse **pp_outResponse)
{
    int err = 0;
#ifndef USE_NP
    struct timespec ts;
#endif /*USE_NP*/

    if(sp_response != NULL) {
        err = AT_ERROR_COMMAND_PENDING;
        goto error;
    }

    err = writeline (command);

    if (err < 0) {
        goto error;
    }

    s_type = type;
    s_responsePrefix = responsePrefix;
    s_smsPDU = smspdu;
    sp_response = at_response_new();

#ifndef USE_NP
    if (timeoutMsec != 0) {
        setTimespecRelative(&ts, timeoutMsec);
    }
#endif /*USE_NP*/

    while (sp_response->finalResponse == NULL && s_readerClosed == 0) {

        
        if (timeoutMsec != 0) {
#ifdef USE_NP
            err = pthread_cond_timeout_np(&s_commandcond, &s_commandmutex, timeoutMsec);
#else
            err = pthread_cond_timedwait(&s_commandcond, &s_commandmutex, &ts);
#endif /*USE_NP*/
        } else {
            err = pthread_cond_wait(&s_commandcond, &s_commandmutex);
        }

        if (err == ETIMEDOUT) {
            err = AT_ERROR_TIMEOUT;
            goto error;
        }
    }

    if (pp_outResponse == NULL) {
        at_response_free(sp_response);
    } else {
        /* line reader stores intermediate responses in reverse order */
        reverseIntermediates(sp_response);
        *pp_outResponse = sp_response;
    }

    sp_response = NULL;

    if(s_readerClosed > 0) {
        err = AT_ERROR_CHANNEL_CLOSED;
        goto error;
    }

    err = 0;
error:
    clearPendingCommand();

    return err;
}
Ejemplo n.º 17
0
static void fill_sha512(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_sha512 *vh = hdr_priv(hdr);
	struct fio_sha512_ctx sha512_ctx = {
		.buf = vh->sha512,
	};

	fio_sha512_init(&sha512_ctx);
	fio_sha512_update(&sha512_ctx, p, len);
}

static void fill_sha256(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_sha256 *vh = hdr_priv(hdr);
	struct fio_sha256_ctx sha256_ctx = {
		.buf = vh->sha256,
	};

	fio_sha256_init(&sha256_ctx);
	fio_sha256_update(&sha256_ctx, p, len);
}

static void fill_sha1(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_sha1 *vh = hdr_priv(hdr);
	struct fio_sha1_ctx sha1_ctx = {
		.H = vh->sha1,
	};

	fio_sha1_init(&sha1_ctx);
	fio_sha1_update(&sha1_ctx, p, len);
}

static void fill_crc7(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc7 *vh = hdr_priv(hdr);

	vh->crc7 = fio_crc7(p, len);
}

static void fill_crc16(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc16 *vh = hdr_priv(hdr);

	vh->crc16 = fio_crc16(p, len);
}

static void fill_crc32(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc32 *vh = hdr_priv(hdr);

	vh->crc32 = fio_crc32(p, len);
}

static void fill_crc32c(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc32 *vh = hdr_priv(hdr);

	vh->crc32 = fio_crc32c(p, len);
}

static void fill_crc64(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc64 *vh = hdr_priv(hdr);

	vh->crc64 = fio_crc64(p, len);
}

static void fill_md5(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_md5 *vh = hdr_priv(hdr);
	struct fio_md5_ctx md5_ctx = {
		.hash = (uint32_t *) vh->md5_digest,
	};

	fio_md5_init(&md5_ctx);
	fio_md5_update(&md5_ctx, p, len);
}

static void populate_hdr(struct thread_data *td, struct io_u *io_u,
			 struct verify_header *hdr, unsigned int header_num,
			 unsigned int header_len)
{
	unsigned int data_len;
	void *data, *p;

	p = (void *) hdr;

	hdr->magic = FIO_HDR_MAGIC;
	hdr->verify_type = td->o.verify;
	hdr->len = header_len;
	hdr->rand_seed = io_u->rand_seed;
	hdr->crc32 = fio_crc32c(p, offsetof(struct verify_header, crc32));

	data_len = header_len - hdr_size(hdr);

	data = p + hdr_size(hdr);
	switch (td->o.verify) {
	case VERIFY_MD5:
		dprint(FD_VERIFY, "fill md5 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_md5(hdr, data, data_len);
		break;
	case VERIFY_CRC64:
		dprint(FD_VERIFY, "fill crc64 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc64(hdr, data, data_len);
		break;
	case VERIFY_CRC32C:
	case VERIFY_CRC32C_INTEL:
		dprint(FD_VERIFY, "fill crc32c io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc32c(hdr, data, data_len);
		break;
	case VERIFY_CRC32:
		dprint(FD_VERIFY, "fill crc32 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc32(hdr, data, data_len);
		break;
	case VERIFY_CRC16:
		dprint(FD_VERIFY, "fill crc16 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc16(hdr, data, data_len);
		break;
	case VERIFY_CRC7:
		dprint(FD_VERIFY, "fill crc7 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc7(hdr, data, data_len);
		break;
	case VERIFY_SHA256:
		dprint(FD_VERIFY, "fill sha256 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_sha256(hdr, data, data_len);
		break;
	case VERIFY_SHA512:
		dprint(FD_VERIFY, "fill sha512 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_sha512(hdr, data, data_len);
		break;
	case VERIFY_XXHASH:
		dprint(FD_VERIFY, "fill xxhash io_u %p, len %u\n",
						io_u, hdr->len);
		fill_xxhash(hdr, data, data_len);
		break;
	case VERIFY_META:
		dprint(FD_VERIFY, "fill meta io_u %p, len %u\n",
						io_u, hdr->len);
		fill_meta(hdr, td, io_u, header_num);
		break;
	case VERIFY_SHA1:
		dprint(FD_VERIFY, "fill sha1 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_sha1(hdr, data, data_len);
		break;
	case VERIFY_PATTERN:
		/* nothing to do here */
		break;
	default:
		log_err("fio: bad verify type: %d\n", td->o.verify);
		assert(0);
	}
	if (td->o.verify_offset)
		memswp(p, p + td->o.verify_offset, hdr_size(hdr));
}

/*
 * fill body of io_u->buf with random data and add a header with the
 * checksum of choice
 */
void populate_verify_io_u(struct thread_data *td, struct io_u *io_u)
{
	if (td->o.verify == VERIFY_NULL)
		return;

	io_u->numberio = td->io_issues[io_u->ddir];

	fill_pattern_headers(td, io_u, 0, 0);
}

int get_next_verify(struct thread_data *td, struct io_u *io_u)
{
	struct io_piece *ipo = NULL;

	/*
	 * this io_u is from a requeue, we already filled the offsets
	 */
	if (io_u->file)
		return 0;

	if (!RB_EMPTY_ROOT(&td->io_hist_tree)) {
		struct rb_node *n = rb_first(&td->io_hist_tree);

		ipo = rb_entry(n, struct io_piece, rb_node);

		/*
		 * Ensure that the associated IO has completed
		 */
		read_barrier();
		if (ipo->flags & IP_F_IN_FLIGHT)
			goto nothing;

		rb_erase(n, &td->io_hist_tree);
		assert(ipo->flags & IP_F_ONRB);
		ipo->flags &= ~IP_F_ONRB;
	} else if (!flist_empty(&td->io_hist_list)) {
		ipo = flist_first_entry(&td->io_hist_list, struct io_piece, list);

		/*
		 * Ensure that the associated IO has completed
		 */
		read_barrier();
		if (ipo->flags & IP_F_IN_FLIGHT)
			goto nothing;

		flist_del(&ipo->list);
		assert(ipo->flags & IP_F_ONLIST);
		ipo->flags &= ~IP_F_ONLIST;
	}

	if (ipo) {
		td->io_hist_len--;

		io_u->offset = ipo->offset;
		io_u->buflen = ipo->len;
		io_u->numberio = ipo->numberio;
		io_u->file = ipo->file;
		io_u->flags |= IO_U_F_VER_LIST;

		if (ipo->flags & IP_F_TRIMMED)
			io_u->flags |= IO_U_F_TRIMMED;

		if (!fio_file_open(io_u->file)) {
			int r = td_io_open_file(td, io_u->file);

			if (r) {
				dprint(FD_VERIFY, "failed file %s open\n",
						io_u->file->file_name);
				return 1;
			}
		}

		get_file(ipo->file);
		assert(fio_file_open(io_u->file));
		io_u->ddir = DDIR_READ;
		io_u->xfer_buf = io_u->buf;
		io_u->xfer_buflen = io_u->buflen;

		remove_trim_entry(td, ipo);
		free(ipo);
		dprint(FD_VERIFY, "get_next_verify: ret io_u %p\n", io_u);

		if (!td->o.verify_pattern_bytes) {
			io_u->rand_seed = __rand(&td->__verify_state);
			if (sizeof(int) != sizeof(long *))
				io_u->rand_seed *= __rand(&td->__verify_state);
		}
		return 0;
	}

nothing:
	dprint(FD_VERIFY, "get_next_verify: empty\n");
	return 1;
}

void fio_verify_init(struct thread_data *td)
{
	if (td->o.verify == VERIFY_CRC32C_INTEL ||
	    td->o.verify == VERIFY_CRC32C) {
		crc32c_intel_probe();
	}
}

static void *verify_async_thread(void *data)
{
	struct thread_data *td = data;
	struct io_u *io_u;
	int ret = 0;

	if (td->o.verify_cpumask_set &&
	    fio_setaffinity(td->pid, td->o.verify_cpumask)) {
		log_err("fio: failed setting verify thread affinity\n");
		goto done;
	}

	do {
		FLIST_HEAD(list);

		read_barrier();
		if (td->verify_thread_exit)
			break;

		pthread_mutex_lock(&td->io_u_lock);

		while (flist_empty(&td->verify_list) &&
		       !td->verify_thread_exit) {
			ret = pthread_cond_wait(&td->verify_cond,
							&td->io_u_lock);
			if (ret) {
				pthread_mutex_unlock(&td->io_u_lock);
				break;
			}
		}

		flist_splice_init(&td->verify_list, &list);
		pthread_mutex_unlock(&td->io_u_lock);

		if (flist_empty(&list))
			continue;

		while (!flist_empty(&list)) {
			io_u = flist_first_entry(&list, struct io_u, verify_list);
			flist_del_init(&io_u->verify_list);

			io_u->flags |= IO_U_F_NO_FILE_PUT;
			ret = verify_io_u(td, &io_u);

			put_io_u(td, io_u);
			if (!ret)
				continue;
			if (td_non_fatal_error(td, ERROR_TYPE_VERIFY_BIT, ret)) {
				update_error_count(td, ret);
				td_clear_error(td);
				ret = 0;
			}
		}
	} while (!ret);

	if (ret) {
		td_verror(td, ret, "async_verify");
		if (td->o.verify_fatal)
			fio_mark_td_terminate(td);
	}

done:
	pthread_mutex_lock(&td->io_u_lock);
	td->nr_verify_threads--;
	pthread_mutex_unlock(&td->io_u_lock);

	pthread_cond_signal(&td->free_cond);
	return NULL;
}

int verify_async_init(struct thread_data *td)
{
	int i, ret;
	pthread_attr_t attr;

	pthread_attr_init(&attr);
	pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);

	td->verify_thread_exit = 0;

	td->verify_threads = malloc(sizeof(pthread_t) * td->o.verify_async);
	for (i = 0; i < td->o.verify_async; i++) {
		ret = pthread_create(&td->verify_threads[i], &attr,
					verify_async_thread, td);
		if (ret) {
			log_err("fio: async verify creation failed: %s\n",
					strerror(ret));
			break;
		}
		ret = pthread_detach(td->verify_threads[i]);
		if (ret) {
			log_err("fio: async verify thread detach failed: %s\n",
					strerror(ret));
			break;
		}
		td->nr_verify_threads++;
	}

	pthread_attr_destroy(&attr);

	if (i != td->o.verify_async) {
		log_err("fio: only %d verify threads started, exiting\n", i);
		td->verify_thread_exit = 1;
		write_barrier();
		pthread_cond_broadcast(&td->verify_cond);
		return 1;
	}

	return 0;
}
Ejemplo n.º 18
0
static void *item_crawler_thread(void *arg) {
    int i;

    pthread_mutex_lock(&lru_crawler_lock);
    if (settings.verbose > 2)
        fprintf(stderr, "Starting LRU crawler background thread\n");
    while (do_run_lru_crawler_thread) {
    pthread_cond_wait(&lru_crawler_cond, &lru_crawler_lock);

    while (crawler_count) {
        item *search = NULL;
        void *hold_lock = NULL;

        for (i = 0; i < LARGEST_ID; i++) {
            if (crawlers[i].it_flags != 1) {
                continue;
            }
            pthread_mutex_lock(&cache_lock);
            search = crawler_crawl_q((item *)&crawlers[i]);
            if (search == NULL ||
                (crawlers[i].remaining && --crawlers[i].remaining < 1)) {
                if (settings.verbose > 2)
                    fprintf(stderr, "Nothing left to crawl for %d\n", i);
                crawlers[i].it_flags = 0;
                crawler_count--;
                crawler_unlink_q((item *)&crawlers[i]);
                pthread_mutex_unlock(&cache_lock);
                continue;
            }
            uint32_t hv = hash(ITEM_key(search), search->nkey);
            /* Attempt to hash item lock the "search" item. If locked, no
             * other callers can incr the refcount
             */
            if ((hold_lock = item_trylock(hv)) == NULL) {
                pthread_mutex_unlock(&cache_lock);
                continue;
            }
            /* Now see if the item is refcount locked */
            if (refcount_incr(&search->refcount) != 2) {
                refcount_decr(&search->refcount);
                if (hold_lock)
                    item_trylock_unlock(hold_lock);
                pthread_mutex_unlock(&cache_lock);
                continue;
            }

            /* Frees the item or decrements the refcount. */
            /* Interface for this could improve: do the free/decr here
             * instead? */
            item_crawler_evaluate(search, hv, i);

            if (hold_lock)
                item_trylock_unlock(hold_lock);
            pthread_mutex_unlock(&cache_lock);

            if (settings.lru_crawler_sleep)
                usleep(settings.lru_crawler_sleep);
        }
    }
    if (settings.verbose > 2)
        fprintf(stderr, "LRU crawler thread sleeping\n");
    STATS_LOCK();
    stats.lru_crawler_running = false;
    STATS_UNLOCK();
    }
    pthread_mutex_unlock(&lru_crawler_lock);
    if (settings.verbose > 2)
        fprintf(stderr, "LRU crawler thread stopping\n");

    return NULL;
}
Ejemplo n.º 19
0
int __po_hi_gqueue_get_value (__po_hi_task_id      id,
                              __po_hi_local_port_t port,
                              __po_hi_request_t*   request)
{
   __po_hi_request_t* ptr;
#ifdef RTEMS_PURE
   rtems_status_code ret;
#endif

#ifdef _WIN32
   DWORD ret;
#endif


   ptr = &__po_hi_gqueues_most_recent_values[id][port];
#if defined (POSIX) || defined (RTEMS_POSIX) || defined (XENO_POSIX)
   pthread_mutex_lock (&__po_hi_gqueues_mutexes[id]);
#elif defined (XENO_NATIVE)
   rt_mutex_acquire (&__po_hi_gqueues_mutexes[id], TM_INFINITE);
#elif defined (RTEMS_PURE)
   ret = rtems_semaphore_obtain (__po_hi_gqueues_semaphores[id], RTEMS_WAIT, RTEMS_NO_TIMEOUT);
   if (ret != RTEMS_SUCCESSFUL)
   {
      __DEBUGMSG ("[GQUEUE] Cannot obtain semaphore in __po_hi_gqueue_store_in()\n");
   }
#elif defined (_WIN32)
  EnterCriticalSection(&__po_hi_gqueues_cs[id]);
#endif


   /*
    * If the port is an event port, with no value queued, then we block
    * the thread.
    */
   if (__po_hi_gqueues_sizes[id][port] != __PO_HI_GQUEUE_FIFO_INDATA)
   {
      while (__po_hi_gqueues_port_is_empty[id][port] == 1)
      {
#if defined (POSIX) || defined (RTEMS_POSIX) || defined (XENO_POSIX)
         pthread_cond_wait (&__po_hi_gqueues_conds[id],
               &__po_hi_gqueues_mutexes[id]);

#elif defined (XENO_NATIVE)
   rt_cond_wait (&__po_hi_gqueues_conds[id], &__po_hi_gqueues_mutexes[id], TM_INFINITE);
#elif defined (RTEMS_PURE)
         rtems_task_wake_after( RTEMS_YIELD_PROCESSOR );
#elif defined (_WIN32)
   LeaveCriticalSection(&__po_hi_gqueues_cs[id]);

   ret = WaitForSingleObject (__po_hi_gqueues_events[id], INFINITE);
   if (ret == WAIT_FAILED)
   {
      __PO_HI_DEBUG_DEBUG ("[GQUEUE] Wait failed\n");
   }
   EnterCriticalSection(&__po_hi_gqueues_cs[id]);
#endif
      }
   }

#if defined (MONITORING)
   update_sporadic_dispatch (id, port);
#endif

   if (__po_hi_gqueues_used_size[id][port] == 0)
   {
      memcpy (request, ptr, sizeof (__po_hi_request_t));
      //update_runtime (id, port, ptr);
   }
   else
   {
      ptr = ((__po_hi_request_t *) &__po_hi_gqueues[id][port]) +  __po_hi_gqueues_first[id][port] + __po_hi_gqueues_offsets[id][port];
      memcpy (request, ptr, sizeof (__po_hi_request_t));
   }


#if defined (TIMEBENCH)
   po_hi_put_time_stamp(id, port,__po_hi_get_CPU_time( ));
#endif

   __PO_HI_DEBUG_INFO ("[GQUEUE] Task %d get a value on port %d\n", id, port);

#if defined (POSIX) || defined (RTEMS_POSIX) || defined (XENO_POSIX)
   pthread_mutex_unlock (&__po_hi_gqueues_mutexes[id]);
#elif defined (XENO_NATIVE)
   rt_mutex_release (&__po_hi_gqueues_mutexes[id]);
#elif defined (RTEMS_PURE)
   ret = rtems_semaphore_release (__po_hi_gqueues_semaphores[id]);
   if (ret != RTEMS_SUCCESSFUL)
   {
      __DEBUGMSG ("[GQUEUE] Cannot release semaphore in __po_hi_gqueue_store_in()\n");
   }
#elif defined (_WIN32)
   LeaveCriticalSection(&__po_hi_gqueues_cs[id]);
#endif

   return 0;
}
Ejemplo n.º 20
0
/* There's one of these for each RPC client which has received an RPC call. */
static void *cb_context(void *__u)
{
    CLIENT *client = (CLIENT *)__u;
    D("RPC-callback thread for %08x:%08x starting.\n",
      (client->xdr->x_prog | 0x01000000),
      client->xdr->x_vers);
    pthread_mutex_lock(&client->wait_cb_lock);
    while (client->cb_stop == 0) {
        if (!client->got_cb)
            pthread_cond_wait(&client->wait_cb,
                              &client->wait_cb_lock);
        /* We tell the thread it's time to exit by setting cb_stop to nonzero
           and signalling the conditional variable.  When there's no data, we
           skip to the top of the loop and exit. 
        */
        if (!client->got_cb) {
            D("RPC-callback thread for %08x:%08x: signalled but no data.\n",
              (client->xdr->x_prog | 0x01000000),
              client->xdr->x_vers);
            continue;
        }
        client->got_cb = 0;

        /* We dispatch the message to the server representing the callback
         * client.
         */
        if (the_xprt) {
            void *svc;
            rpcprog_t prog =
                ntohl(((uint32 *)(client->xdr->in_msg))[RPC_OFFSET+3]);
            rpcvers_t vers =
                ntohl(((uint32 *)(client->xdr->in_msg))[RPC_OFFSET+4]);
            
            svc = svc_find(the_xprt, prog, vers);
            if (svc) {
                XDR **svc_xdr = (XDR **)svc;
                D("%08x:%08x dispatching RPC call (XID %d, xdr %p) for "
                  "callback client %08x:%08x.\n",
                  client->xdr->x_prog,
                  client->xdr->x_vers,
                  ntohl(((uint32 *)(client->xdr->in_msg))[RPC_OFFSET]),
                  client->xdr,
                  (uint32_t)prog, (int)vers);
                /* We transplant the xdr of the client into the entry 
                   representing the callback client in the list of servers.
                   Note that since we hold the wait_cb_lock for this client,
                   if another call for this callback client arrives before
                   we've finished processing this call, that will block until
                   we're done with this one.  If this happens, it would be
                   most likely a bug in the arm9 rpc router.
                */
                if (*svc_xdr) {
                    D("%08x:%08x expecting XDR == NULL"
                      "callback client %08x:%08x!\n",
                      client->xdr->x_prog,
                      client->xdr->x_vers,
                      (uint32_t)prog, (int)vers);
                    xdr_destroy_common(*svc_xdr);
                }
                

                /* Do these checks before the clone */
                if (client->xdr->in_len < 0) {
                    E("%08x:%08x xdr->in_len = %i error %s (%d)",
                        client->xdr->in_len,
                        client->xdr->x_prog, client->xdr->x_vers,
                        strerror(errno), errno);
                    continue;
                }
                if (client->xdr->out_next < 0) {
                    E("%08x:%08x xdr->out_next = %i error %s (%d)",
                        client->xdr->out_next,
                        client->xdr->x_prog, client->xdr->x_vers,
                    strerror(errno), errno);
                    continue;
                }

                D("%08x:%08x cloning XDR for "
                  "callback client %08x:%08x.\n",
                  client->xdr->x_prog,
                  client->xdr->x_vers,
                  (uint32_t)prog, (int)vers);
                *svc_xdr = xdr_clone(client->xdr);
                
                (*svc_xdr)->x_prog = prog;
                (*svc_xdr)->x_vers = vers;
                memcpy((*svc_xdr)->in_msg,
                       client->xdr->in_msg, client->xdr->in_len);
                memcpy((*svc_xdr)->out_msg,
                       client->xdr->out_msg, client->xdr->out_next);
                (*svc_xdr)->in_len = client->xdr->in_len;
                (*svc_xdr)->out_next = client->xdr->out_next;

                pthread_mutex_lock(&client->input_xdr_lock);
                D("%08x:%08x marking input buffer as free.\n",
                  client->xdr->x_prog, client->xdr->x_vers);
                client->input_xdr_busy = 0;
                pthread_cond_signal(&client->input_xdr_wait);
                pthread_mutex_unlock(&client->input_xdr_lock);

                svc_dispatch(svc, the_xprt);
                xdr_destroy_common(*svc_xdr);
                *svc_xdr = NULL;
            }
            else E("%08x:%08x call packet arrived, but there's no "
                   "RPC server registered for %08x:%08x.\n",
                   client->xdr->x_prog,
                   client->xdr->x_vers,                   
                   (uint32_t)prog, (int)vers);                           
        }
        else E("%08x:%08x call packet arrived, but there's "
               "no RPC transport!\n",
               client->xdr->x_prog,
               client->xdr->x_vers);

        releaseWakeLock();
    }
    pthread_mutex_unlock(&client->wait_cb_lock);


    D("RPC-callback thread for %08x:%08x terminating.\n",
      (client->xdr->x_prog | 0x01000000),
      client->xdr->x_vers);
    return NULL;
}
Ejemplo n.º 21
0
/**
 *
 * Wait
 * wait for an event -- wait for an event object
 * to be set to signaled.  must be paired with a
 * call to reset within the same thread.
 *
 **/
bool NxEvent::wait()
{
    pthread_mutex_lock(&m_lock);
    pthread_cond_wait(&m_ready, &m_lock);
    return true;
}
Ejemplo n.º 22
0
// when asker asks for a consumer they direct here to obtain info from the producer
int get (void *stream, pthread_t *p)
{
	// verify that the request is valid (the connection exists)
	// check which position in the buffer they need
	// see if the buffer position can be dequeued by seeing what everyone else needs
	// 	 if everyone has used the position then pop that posn off the buffer
	//     the asking consumer must not be too far ahead from the other consumer for this to work
	// the buffer gets pushed to when a peek is done on an element that hasn't been used by everyone
	//	 this is because the producer dequeues an item when asked directly
  //...
  ConnectEntry* ptr;
  int ret = -3;
  bool flag;

  // verify we have a connection...
  if(Ce == NULL)
  {
    printf("no connections found...\n");
    return -1;
  }
  if (p != NULL && isEmpty(Q))
  {
    printf("empty buffer...\n");
    return -2;
  }
  else if (p == NULL)
  {
    printf("no thread...\n");
    return -2;
  }

  // FOR DEBUG ONLY...
  if(p == &c1)
    printf("is consumer 1\n");
  else if (p == &c2)
    printf("is consumer 2\n");
  else if (p == &a1)
    printf("is asker\n");
  else
    printf("error in get (thread check)...\n");

  // verify that this connection is legit
  while (ptr != NULL)
  {
    if (ptr->thread == p) break;
    ptr = ptr->next;
  }
  if (ptr == NULL)
  {
    printf("this connection was not found...\n");
    return -1;
  }

  // when available, put a new item into the stream's buffer
  pthread_mutex_lock(Mutex);
  if (nelem(Q) == 0)
    pthread_cond_wait(Empty, Mutex);

  // if all connections have now used the first elem then dequeue
  ret = *(int*)peek(Q, *Ce->first);
  if (ret >= 0)
    *Ce->first = ret;
  // otherwise peek to obtain the val desired

  pthread_cond_broadcast(Empty);
  pthread_mutex_unlock(Mutex);

	return ret;
}
Ejemplo n.º 23
0
/*------------------------------------------------------- 
  main
  ------------------------------------------------------- */
int main(int argc, char *argv[]){

  pthread_t Tid_main, Threads[MAX_THREADS];
  int  i, Acquittes, Nbre_Threads;
  void Un_Thread (void);
  
  
  
  if (argc != 2){
    printf("Utilisation : %s n (nbre de threads)\n", argv[0]);
    exit(1);
  }

  Nbre_Threads = atoi(argv[1]);
  if (Nbre_Threads > MAX_THREADS){
    printf(" Pas plus de  %d threads !\n", Nbre_Threads);
    exit(2);
  }
  srandom(time(NULL));    
  Tid_main=pthread_self();
    
  /* Nombre de threads acquittes */
  Acquittes = 0;

  /* initialisation des donnees partagees */
  Zone_Part.Threads_Finis = 0;
  
  /* initialisation des outils de synchronisation */
  /* initialisation des outils de synchronisation */
  pthread_cond_init(&Zone_Part.Var_Cond, NULL);
  pthread_mutex_init(&Zone_Part.Verrou, NULL);
  pthread_mutex_lock(&Zone_Part.Verrou);

  /* creation des threads */
  for (i=0; i < Nbre_Threads ; i++){ 
    pthread_create(Threads +i,NULL,(void *) Un_Thread,NULL );
    printf("main (Tid (0x)%x vient de creer : (0x)%x\n", (int)Tid_main, (int)Threads[i]);
  }   
  
  /* attendre la fin de TOUS ces threads 
   * on n utilise pas join pour ne pas imposer d ordre.
   * L attente se fait donc en utilisant une variable conditionnelle.
   * On recuperer l identite du thread qui s est termine
   * dans la variable Zone_Part.Thread_Id.
   */
  

  /**************** 111 ****************/
  while (Zone_Part.Threads_Finis < Nbre_Threads){
    pthread_cond_wait(&Zone_Part.Var_Cond, &Zone_Part.Verrou);
    Acquittes++;
    printf("main (Tid (0x)%x) : fin du thread (0x)%x\n", 
	   (int)Tid_main, (int)Zone_Part.Thread_Id);
    pthread_mutex_unlock(&Zone_Part.Verrou_signal);
  
  }   
  pthread_mutex_unlock(&Zone_Part.Verrou);
  printf("main (Tid (0x)%x) : FIN, nbre de threads acquittes : %d, nbre de threads termines : %d\n",
         (int)Tid_main, Acquittes,Zone_Part.Threads_Finis);
  return 0;
}
void *camframe_fb_thread(void *data)
{
  int result = 0;
  static struct timeval td1, td2;
  struct timezone tz;

#ifdef _ANDROID_
  fb_fd = open(ANDROID_FB0, O_RDWR);
  CDBG("%s:android dl '%s', fd=%d\n", __func__, ANDROID_FB0, fb_fd);
#else
  fb_fd = open(LE_FB0, O_RDWR);
  CDBG("%s:LE_FB0 dl, '%s', fd=%d\n", __func__, LE_FB0, fb_fd);
#endif
  if (fb_fd < 0) {
    CDBG_ERROR("cannot open framebuffer %s or %s file node\n",
      ANDROID_FB0, LE_FB0);
    goto fail1;
  }

  if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &vinfo) < 0) {
    CDBG_ERROR("cannot retrieve vscreenInfo!\n");
    goto fail;
  }

  if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) < 0) {
    CDBG_ERROR("can't retrieve fscreenInfo!\n");
    goto fail;
  }

  vinfo.activate = FB_ACTIVATE_VBL;

  camframe_fb_thread_ready_signal();

  pthread_mutex_lock(&camframe_fb_mutex);
  while (!camframe_fb_exit) {
    CDBG("cam_frame_fb_thread: num_of_ready_frames: %d\n", num_of_ready_frames);
    if (num_of_ready_frames <= 0) {
      pthread_cond_wait(&camframe_fb_cond, &camframe_fb_mutex);
    }
    if (num_of_ready_frames > 0) {
      num_of_ready_frames --;

      gettimeofday(&td1, &tz);
      if (use_overlay) {
        result = ioctl(fb_fd, MSMFB_OVERLAY_PLAY, ovp_front);
      } else {
        result = ioctl(fb_fd, FBIOPAN_DISPLAY, &vinfo);
      }

      gettimeofday(&td2, &tz);

      CDBG("Profiling: frame timestamp after FBIO display = %ld ms\n",
        (td2.tv_sec*1000) + (td2.tv_usec/1000));

      CDBG("cam_frame_fb_thread: elapse time for FBIOPAN_DISPLAY = %ld, return = %d\n",
        (td2.tv_sec - td1.tv_sec) * 1000000 + td2.tv_usec - td1.tv_usec, result);

      if (result < 0) {
        CDBG("DISPLAY: Failed\n");
      }
    }
  }

  pthread_mutex_unlock(&camframe_fb_mutex);

  if (use_overlay) {
    if (ioctl(fb_fd, MSMFB_OVERLAY_UNSET, &vid_buf_front_id)) {
      CDBG("\nERROR! MSMFB_OVERLAY_UNSET failed! (Line %d)\n", __LINE__);
      goto fail;
    }
  }

  return NULL;

  fail:
  close(fb_fd);
  fail1:
  camframe_fb_exit = -1;
  camframe_fb_thread_ready_signal();
  return NULL;
}
Ejemplo n.º 25
0
// Called once per GPU device per simulation run. This is the entry point for each processing
// thread. Its input is the NengoGPUData structure that it is to process. The behaviour of
// this function is: wait until we get the signal to step (from the step function),
// process the NengoGPUData structure for one step with run_neural_associative_memory,
// wait again. Eventually manipulateKill(0) will return true, meaning the run is finished and
// the function will break out of the loop and free its resources.
void* start_GPU_thread(void* arg)
{
  NengoGPUData* nengo_data = (NengoGPUData*) arg;

  int num_devicesFinished;

  if (nengo_data->do_print)
    printf("GPU Thread %d: about to acquire device\n", nengo_data->device);

  initGPUDevice(nengo_data->device);

  if (nengo_data->do_print)
    printf("GPU Thread %d: done acquiring device\n", nengo_data->device);

  if (nengo_data->do_print)
    printf("GPU Thread %d: about to move simulation data to device\n", nengo_data->device);

  moveToDeviceNengoGPUData(nengo_data);

  if (nengo_data->do_print)
    printf("GPU Thread %d: done moving simulation data to device\n", nengo_data->device);

  //printVecs(nengo_data);

  // signal to parent thread that initialization is complete, then wait for the other threads to finish initialization.
  pthread_mutex_lock(mutex);
  myCVsignal++;
  if(myCVsignal == num_devices)
  {
    pthread_cond_broadcast(cv_JNI);
  }
  pthread_cond_wait(cv_GPUThreads, mutex);
  pthread_mutex_unlock(mutex);

  // Wait for the signal to step. If that signal has already come, then myCVsignal == 1.
  // In that case, we don't wait (if we did, we'd wait forever).
  pthread_mutex_lock(mutex);
  if(myCVsignal == 0)
  {
    pthread_cond_wait(cv_GPUThreads, mutex);
  }
  pthread_mutex_unlock(mutex);

  // The main loop for the processing threads. The thread is either processing nodes on 
  // the GPU or it is waiting for the call to step.
  while(!manipulateKill(0))
  {
    if(manipulateReset(0))
    {
      reset_neural_associative_memory(nengo_data);
    }
    else
    {
      run_neural_associative_memory(nengo_data, start_time, end_time);
    }

    // signal that this device is finished processing for the step
    num_devicesFinished = manipulateNumDevicesFinished(2, 0);

    pthread_mutex_lock(mutex);
    // Wakeup the main thread if all devices are finished running
    if(num_devicesFinished == num_devices)
    {
      pthread_cond_broadcast(cv_JNI);
      manipulateNumDevicesFinished(3, 0);
    }
    // Wait for call from main thread to step
    pthread_cond_wait(cv_GPUThreads, mutex);
    pthread_mutex_unlock(mutex);
  }

  // Should only get here after run_kill has been called
  freeNengoGPUData(nengo_data);
  shutdownGPUDevice();

  // if this is the last thread to finish, we wake up the main thread,
  // it has to free some things before we finish
  pthread_mutex_lock(mutex);
  myCVsignal++;
  if(myCVsignal == num_devices)
  {
    pthread_cond_broadcast(cv_GPUThreads);
  }
  pthread_mutex_unlock(mutex);
  return NULL;
}
Ejemplo n.º 26
0
static void *acceptloop_th(void *arg)
{
    char buff[BUFFSIZE + 1];
    size_t i;
    struct acceptdata *data = (struct acceptdata*)arg;
    struct fd_data *fds = &data->fds;
    struct fd_data *recv_fds = &data->recv_fds;
    int max_queue = data->max_queue;
    int commandtimeout = data->commandtimeout;

    pthread_mutex_lock(fds->buf_mutex);
    for (;;) {
	/* Block waiting for data to become available for reading */
	int new_sd = fds_poll_recv(fds, -1, 0, event_wake_accept);
#ifdef _WIN32
	ResetEvent(event_wake_accept);
#endif
	/* TODO: what about sockets that get rm-ed? */
	if (!fds->nfds) {
	    /* no more sockets to poll, all gave an error */
	    logg("!Main socket gone: fatal\n");
	    break;
	}

	if (new_sd == -1 && errno != EINTR) {
	    logg("!Failed to poll sockets, fatal\n");
	    pthread_mutex_lock(&exit_mutex);
	    progexit = 1;
	    pthread_mutex_unlock(&exit_mutex);
	    break;
	}

	/* accept() loop */
	for (i=0;i < fds->nfds && new_sd >= 0; i++) {
	    struct fd_buf *buf = &fds->buf[i];
	    if (!buf->got_newdata)
		continue;
#ifndef _WIN32
	    if (buf->fd == data->syncpipe_wake_accept[0]) {
		/* dummy sync pipe, just to wake us */
		if (read(buf->fd, buff, sizeof(buff)) < 0) {
		    logg("^Syncpipe read failed\n");
		}
		continue;
	    }
#endif
	    if (buf->got_newdata == -1) {
		logg("$Acceptloop closed FD: %d\n", buf->fd);
		shutdown(buf->fd, 2);
		closesocket(buf->fd);
		buf->fd = -1;
		continue;
	    }

	    /* don't accept unlimited number of connections, or
	     * we'll run out of file descriptors */
	    pthread_mutex_lock(recv_fds->buf_mutex);
	    while (recv_fds->nfds > (unsigned)max_queue) {
		pthread_mutex_lock(&exit_mutex);
		if(progexit) {
		    pthread_mutex_unlock(&exit_mutex);
		    break;
		}
		pthread_mutex_unlock(&exit_mutex);
		pthread_cond_wait(&data->cond_nfds, recv_fds->buf_mutex);
	    }
	    pthread_mutex_unlock(recv_fds->buf_mutex);

	    pthread_mutex_lock(&exit_mutex);
	    if(progexit) {
		pthread_mutex_unlock(&exit_mutex);
		break;
	    }
	    pthread_mutex_unlock(&exit_mutex);

	    /* listen only socket */
	    new_sd = accept(fds->buf[i].fd, NULL, NULL);

	    if (new_sd >= 0) {
		int ret, flags;
#ifdef F_GETFL
		flags = fcntl(new_sd, F_GETFL, 0);
		if (flags != -1) {
		    if (fcntl(new_sd, F_SETFL, flags | O_NONBLOCK) == -1) {
			logg("^Can't set socket to nonblocking mode, errno %d\n",
			     errno);
		    }
		} else {
			logg("^Can't get socket flags, errno %d\n", errno);
		}
#else
		logg("^Nonblocking sockets not available!\n");
#endif
		logg("$Got new connection, FD %d\n", new_sd);
		pthread_mutex_lock(recv_fds->buf_mutex);
		ret = fds_add(recv_fds, new_sd, 0, commandtimeout);
		pthread_mutex_unlock(recv_fds->buf_mutex);

		if (ret == -1) {
		    logg("!fds_add failed\n");
		    closesocket(new_sd);
		    continue;
		}

		/* notify recvloop */
#ifdef _WIN32
		SetEvent(event_wake_recv);
#else
		if (write(data->syncpipe_wake_recv[1], "", 1) == -1) {
		    logg("!write syncpipe failed\n");
		    continue;
		}
#endif
	    } else if (errno != EINTR) {
		/* very bad - need to exit or restart */
#ifdef HAVE_STRERROR_R
		strerror_r(errno, buff, BUFFSIZE);
		logg("!accept() failed: %s\n", buff);
#else
		logg("!accept() failed\n");
#endif
		/* give the poll loop a chance to close disconnected FDs */
		break;
	    }

	}

	/* handle progexit */
	pthread_mutex_lock(&exit_mutex);
	if (progexit) {
	    pthread_mutex_unlock(&exit_mutex);
	    break;
	}
	pthread_mutex_unlock(&exit_mutex);
    }
    pthread_mutex_unlock(fds->buf_mutex);

    for (i=0;i < fds->nfds; i++) {
	if (fds->buf[i].fd == -1)
	    continue;
	logg("$Shutdown: closed fd %d\n", fds->buf[i].fd);
	shutdown(fds->buf[i].fd, 2);
	closesocket(fds->buf[i].fd);
    }
    fds_free(fds);
    pthread_mutex_destroy(fds->buf_mutex);
    pthread_mutex_lock(&exit_mutex);
    progexit = 1;
    pthread_mutex_unlock(&exit_mutex);
#ifdef _WIN32
    SetEvent(event_wake_recv);
#else
    if (write(data->syncpipe_wake_recv[1], "", 1) < 0) {
	logg("$Syncpipe write failed\n");
    }
#endif
    return NULL;
}
// select the desired clip and play count, and enqueue the first buffer if idle
jboolean Java_com_android_nativeaudiolatency_NativeAudioLatency_selectClip(JNIEnv* env, jclass clazz, jint which,
        jint count) {

    LOGW("%s: ### count = %d",__func__,count);
    unsigned char *oldBuffer = nextBuffer;
    SLresult result;
    pthread_mutex_lock(&lock);
    int j =0;
    switch (which) {
        case 0:     // CLIP_NONE
            LOGW("%s: CLIP_NONE ###",__func__);
            nextSize = 0;
            break;
        case 1:     // COLD_OUTPUT_LATENCY
            LOGW("%s: CLIP_COLD ###",__func__);
            audioLatency = COLD_OUTPUT_LATENCY;
            nextBuffer = (unsigned char *) coldBuffer;
            nextSize = sizeof(coldBuffer);
            LOGW("nextSize = %d", nextSize);
            gettimeofday(&coldPlayApp, NULL);
            LOGW( "Cold output latency - Track.play time: %lld \n", (int64_t)coldPlayApp.tv_sec * 1000 + coldPlayApp.tv_usec/1000);
            break;
        case 2:     // WARM_OUTPUT_LATENCY
            LOGW("%s: CLIP_WARM ###",__func__);
            audioLatency = WARM_OUTPUT_LATENCY;
            nextBuffer = (unsigned char  *) coldBuffer;
            nextSize = sizeof(coldBuffer);
            LOGW("nextSize = %d", nextSize);
            break;
        case 3:     // CONTINUOUS_OUTPUT_LATENCY
            LOGW("%s: CLIP_CONTINUOUS ###",__func__);
            audioLatency = CONTINUOUS_OUTPUT_LATENCY;
            nextBuffer = (unsigned char *)coldBuffer;
            nextSize = sizeof(coldBuffer);
            LOGW("nextSize = %d", nextSize);
            break;
        default:
            LOGW("%s: default ###",__func__);
            nextSize = 0;
            break;
    }
    nextCount = count;
    if (nextSize > 0) {
        // here we only enqueue one buffer because it is a long clip,
        // but for streaming playback we would typically enqueue at least 2 buffers to start
        // set the player's state to playing
        result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING);
        assert(SL_RESULT_SUCCESS == result);

        result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, nextBuffer, nextSize);
        if (SL_RESULT_SUCCESS != result) {
            pthread_mutex_unlock(&lock);
            return JNI_FALSE;
        }
        pthread_cond_wait(&asyncCompletion,&lock);
        LOGW("Wait Play --");
        if(audioLatency == WARM_OUTPUT_LATENCY) {
            result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PAUSED);
            assert(SL_RESULT_SUCCESS == result);
            result = (*bqPlayerBufferQueue)->Clear(bqPlayerBufferQueue);
            assert(SL_RESULT_SUCCESS == result);
            LOGW("sleep++");
            usleep (1000 * 1000);
            LOGW("sleep--");
            result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING);
            assert(SL_RESULT_SUCCESS == result);
            gettimeofday(&warmPlayApp, NULL);
            LOGW( "CB-Warm output latency -  time: %lld \n", (int64_t)warmPlayApp.tv_sec * 1000 + warmPlayApp.tv_usec/1000);
            result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, warmBuffer, nextSize);
        }
    }
    pthread_mutex_unlock(&lock);
    return JNI_TRUE;
}
Ejemplo n.º 28
0
void * io_thread (void *arg) {
	jack_thread_info_t *info = (jack_thread_info_t *) arg;

	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
	pthread_mutex_lock(&io_thread_lock);

	while (run) {
		const int pkhld = ceilf(2.0 / ( (info->delay/1000000.0) + ((float)info->buffersize / (float)info->samplerate)));

		if (info->can_capture) {
			int chn;
			memcpy(info->peak, info->pcur, sizeof(float)*info->channels);
			for (chn = 0; chn < info->channels; ++chn) { info->pcur[chn]=0.0; }

			if ((info->format&1)==0) {
				if (flock(fileno(info->outfd), LOCK_EX)) continue; // pthread_cond_wait ?
				fseek(info->outfd, 0L, SEEK_SET);
			}
			switch (info->format&6) {
				case 6:
				case 4:
					fprintf(info->outfd,"{\"cnt\":%d,\"peak\":[", info->channels);
					break;
				default:
					break;
			}
			for (chn = 0; chn < info->channels; ++chn) {
				switch (info->format&6) {
					case 0:
						printf("%3.3f  ", info->peak[chn]); break;
						//printf("%s  ", info->address); break;
					case 2:
						fprintf(info->outfd,"%3d  ", peak_db(info->peak[chn], 1.0, info->iecmult)); break;
					case 4:
						printf("%.3f,", info->peak[chn]); break;
					case 6:
						fprintf(info->outfd,"%d,", peak_db(info->peak[chn], 1.0, info->iecmult)); break;
				}

				/* Insert OSC stuff here */
				UdpTransmitSocket transmitSocket( IpEndpointName( info->address, info->port ) );
    		
				char buffer[OUTPUT_BUFFER_SIZE];
				osc::OutboundPacketStream stream( buffer, OUTPUT_BUFFER_SIZE );
		
				stream //<< osc::BeginBundleImmediate
					<< osc::BeginMessage( info->message ) 
			    			<< (float)info->peak[chn] << osc::EndMessage
				;//<< osc::EndBundle;

				transmitSocket.Send( stream.Data(), stream.Size() );

				if (info->peak[chn] > info->pmax[chn]) {
					info->pmax[chn] = info->peak[chn];
					info->ptme[chn] = 0;
				} else if (info->ptme[chn] <= pkhld) {
					(info->ptme[chn])++;
				} else {
					info->pmax[chn] = info->peak[chn];
				}
			}
			if (info->format&8) { // add peak-hold
				if (info->format&4) {
					fprintf(info->outfd,"],\"max\":[");
				} else {
					fprintf(info->outfd," | ");
				}

				for (chn = 0; chn < info->channels; ++chn) {
					switch (info->format&6) {
						case 0:
							printf("%3.3f  ", info->pmax[chn]); break;
						case 2:
							fprintf(info->outfd,"%3d  ", peak_db(info->pmax[chn], 1.0, info->iecmult)); break;
						case 4:
							printf("%.3f,", info->pmax[chn]); break;
						case 6:
							fprintf(info->outfd,"%d,", peak_db(info->pmax[chn], 1.0, info->iecmult)); break;
					}
				}
			}
			switch (info->format&6) {
				case 6:
				case 4:
					fprintf(info->outfd,"]}");
					break;
				default:
					break;
			}

			if (info->format&1)
				fprintf(info->outfd, "\r");
			else {
				ftruncate(fileno(info->outfd), ftell(info->outfd));
				fprintf(info->outfd, "\n");
				flock(fileno(info->outfd), LOCK_UN);
			}

			fflush(info->outfd);

			if (info->delay>0) usleep(info->delay);
		}
		pthread_cond_wait(&data_ready, &io_thread_lock);
	}

	pthread_mutex_unlock(&io_thread_lock);
	return 0;
}
Ejemplo n.º 29
0
static void
native_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
    pthread_cond_wait(cond, mutex);
}
Ejemplo n.º 30
0
static int
event_dispatch_epoll (struct event_pool *event_pool)
{
        struct epoll_event *events = NULL;
        int                 size = 0;
        int                 i = 0;
        int                 ret = -1;

	syslog(LOG_INFO | LOG_LOCAL1, "%s", "event_dispatch_epoll");
        GF_VALIDATE_OR_GOTO ("event", event_pool, out);

        while (1) {
                pthread_mutex_lock (&event_pool->mutex);
                {
                        while (event_pool->used == 0)
                                pthread_cond_wait (&event_pool->cond,
                                                   &event_pool->mutex);

                        if (event_pool->used > event_pool->evcache_size) {
                                GF_FREE (event_pool->evcache);

                                event_pool->evcache = events = NULL;

                                event_pool->evcache_size =
                                        event_pool->used + 256;

                                events = GF_CALLOC (event_pool->evcache_size,
                                                    sizeof (struct epoll_event),
                                                    gf_common_mt_epoll_event);
                                if (!events)
                                        break;

                                event_pool->evcache = events;
                        }
                }
                pthread_mutex_unlock (&event_pool->mutex);

                ret = epoll_wait (event_pool->fd, event_pool->evcache,
                                  event_pool->evcache_size, -1);

                if (ret == 0)
                        /* timeout */
                        continue;

                if (ret == -1 && errno == EINTR)
                        /* sys call */
                        continue;

                size = ret;

                for (i = 0; i < size; i++) {
                        if (!events || !events[i].events)
                                continue;

                        ret = event_dispatch_epoll_handler (event_pool,
                                                            events, i);
                }
        }

out:
        return ret;
}