static void buffer_init(buffer_t * b)
{
  b->data = create_semaphore(DATA_SEMAPHORE_NAME, 0);
  b->free = create_semaphore(FREE_SEMAPHORE_NAME, BUFFER_MAX);

  pthread_mutex_init(&b->mutex_in, NULL);
  pthread_mutex_init(&b->mutex_out, NULL);

  b->in = 0;
  b->out = 0;
}
Exemplo n.º 2
0
BufferPool::BufferPool()
	:
	fFirstFree(NULL)
{
	fLock = create_semaphore("buffer lock", 1, 0);
	fFreeBuffers = create_semaphore("free buffers", 0, 0);

#ifndef USER
	//set_sem_owner(fLock, B_SYSTEM_TEAM);
	//set_sem_owner(fFreeBuffers, B_SYSTEM_TEAM);
#endif
}
Exemplo n.º 3
0
void init_msg_ports( void )
{
	register_debug_cmd( "ls_pubports", "list all public message ports.", db_list_public_ports );
	g_hPortListSema = create_semaphore( "port_list__bad1", 1, 0 );
	g_hPortListSema = create_semaphore( "port_list__bad2", 1, 0 );
	g_hPortListSema = create_semaphore( "port_list__bad3", 1, 0 );
	g_hPortListSema = create_semaphore( "port_list", 1, 0 );
	MArray_Init( &g_sMsgPorts );

	g_hPubPortListSema = create_semaphore( "public_port_list", 1, 0 );
	g_psPubPortListHead = NULL;

}
Exemplo n.º 4
0
mutex create_mutex()
    //@ requires exists<real>(?fs) &*& [fs]obligation_space(?space, ?termScope) &*& exists<level>(?level) &*& exists<predicate()>(?inv) &*& inv();
    //@ ensures mutex(result, space, termScope, fs, level, inv);
    //@ terminates;
{
    //@ open exists(level);
    //@ open exists(inv);
    semaphore s = create_semaphore(1);
    mutex m = malloc(sizeof(struct mutex));
    if (m == 0) abort();
    m->semaphore = s;
    //@ m->space = space;
    //@ m->termScope = termScope;
    //@ m->spaceFrac = fs;
    //@ m->level = level;
    //@ m->inv_ = inv;
    //@ int blockeesId = create_ghost_list<real>();
    //@ m->blockeesId = blockeesId;
    //@ open obligation_space(space, termScope);
    //@ assert [_]ghost_cell<pair<int, real> >(space, pair(?scopeId, ?olevel));
    //@ close [fs]obligation_space0(space, termScope);
    //@ close mutex_inv(m, termScope, fs, s, scopeId, level, inv, blockeesId)();
    //@ create_atomic_space(olevel + 1, mutex_inv(m, termScope, fs, s, scopeId, level, inv, blockeesId));
    return m;
}
Exemplo n.º 5
0
Arquivo: tcp.c Projeto: ebichu/dd-wrt
static CONNECT_THREAD_DATA *create_connect_data(void *p_data)
{
	CONNECT_THREAD_DATA	*p_thread_data=NULL;


	p_thread_data=safe_malloc(sizeof(CONNECT_THREAD_DATA));


	if (!(p_thread_data)) {

		DBG_PRINTF((LOG_CRIT,"C:" MODULE_TAG "failed allocating connect thread data in create_connect_data...\n"));

		return NULL;
	}
	else {

		memset(p_thread_data,0,sizeof(CONNECT_THREAD_DATA));
		p_thread_data->p_self=p_data;
		p_thread_data->rc=RC_IP_CONNECT_FAILED;

		create_mutex(&p_thread_data->t_data_mutex);
		create_semaphore(&p_thread_data->t_data_sem);

		return p_thread_data;
	}
}
Exemplo n.º 6
0
/* 
 * test program
 * checking semaphore behaviour
 */
int main(int argc, char **argv)
{
    int semid, status;

    printf("%s\n", argv[1]);

    //down sempahore
    wait((int *)up_semaphore(DESC, SEM_DOWN));

    sleep(3);
    //up sempahore
    if ((semid = up_semaphore(DESC, SEM_UP)) == -1) {
        perror("down semaphore");
	exit(EXIT_FAILURE);
    }

    sleep(1);
    //close semaphore
    if ((semid = create_semaphore(DESC, INHERIT, SEM_CLOSE)) == -1) {
        perror("closing semaphore");
	exit(EXIT_FAILURE);
    }

    return 0;
}
Exemplo n.º 7
0
sema create_sema()
    //@ requires exists<real>(?fs) &*& [fs]obligation_space(?space, ?termScope) &*& obspace_credit_object(?creditObject, space, ?level, 0, 0) &*& exists<predicate()>(?inv);
    //@ ensures sema_handle(result, 1, space, termScope, fs, level, creditObject, inv, 0);
    //@ terminates;
{
    //@ obspace_credit_object_get_info();
    //@ open exists<predicate()>(inv);
    sema sema = malloc(sizeof(struct sema));
    if (sema == 0) abort();
    sema->semaphore = create_semaphore(0);
    //@ semaphore semaphore = sema->semaphore;
    //@ sema->space = space;
    //@ sema->termScope = termScope;
    //@ sema->spaceFrac = fs;
    //@ sema->level = level;
    //@ sema->creditObject = creditObject;
    //@ sema->inv_ = inv;
    //@ int countingId = create_counting_handle_id_reservation();
    //@ sema->countingId = countingId;
    //@ open [fs]obligation_space(space, termScope);
    //@ assert [_]ghost_cell<pair<int, real> >(space, pair(?scope, ?olevel));
    //@ close n_times(0, inv);
    //@ close n_times(0, sema_release_token_(sema, space, termScope, level, creditObject, inv));
    //@ open obspace_credit_object(creditObject, space, level, 0, 0);
    //@ close sema_inv(sema, sema->semaphore, space, termScope, fs, level, creditObject, inv)();
    //@ create_atomic_space(olevel + 2, sema_inv(sema, sema->semaphore, space, termScope, fs, level, creditObject, inv));
    return sema;
    //@ close [fs]obligation_space0(space, termScope);
    //@ close sema(sema, space, termScope, fs, level, creditObject, inv, countingId);
    //@ close sema_(sema)();
    //@ create_counting_handle(sema_(sema));
    //@ close sema_handle(sema, 1, space, termScope, fs, level, creditObject, inv, 0);
}
Exemplo n.º 8
0
Arquivo: serial.c Projeto: PyroOS/Pyro
status_t ser_open( void* pNode, uint32 nFlags, void **pCookie )
{
    SerPort_s* psPort = pNode;
    uint	     nDivisor = 115200 / psPort->sp_nBaudRate;
    uint32     nFlg;

    if ( psPort->sp_bOpen == true ) {
	printk( "ser_open(): port is already open\n" );
	return( -EBUSY );
    }
    psPort->sp_bOpen = true;
    psPort->sp_nFlags         = nFlags;
    psPort->sp_hRecvMutex	    = create_semaphore( "ser_recv_mutex", 1, 0 );
    psPort->sp_hRecvWaitQueue = create_semaphore( "ser_recv_queue", 0, 0 );
    psPort->sp_nRecvInPos	    = 0;
    psPort->sp_nRecvOutPos    = 0;
    psPort->sp_nRecvSize	    = 0;
    psPort->sp_nMCR	    = 0x0f;
  
    nFlg = spinlock_disable( &g_sSPinLock );
  
    ser_out( psPort, UART_LCR, UART_LCR_DLAB | UART_LCR_WLEN7 | UART_LCR_STOP ); // Set UART_LCR_DLAB to enable baud rate divisors
  
    ser_out( psPort, UART_DLL, nDivisor & 0xff ); // Baud rate divisor LSB
    ser_out( psPort, UART_DLM, nDivisor >> 8  ); // Baud rate divisor MSB
 
    ser_out( psPort, UART_LCR, UART_LCR_WLEN7 | UART_LCR_STOP ); // Clr UART_LCR_DLAB to disable baud rate divisors


      // Enable FIFO, IRQ when 8 bytes received
    ser_out( psPort, UART_FCR, /*UART_FCR_ENABLE_FIFO | UART_FCR6_R_TRIGGER_24*/ 0 ); 
    ser_out( psPort, UART_IER, UART_IER_RDI ); // receive irq enabled

    ser_out( psPort, UART_MCR, psPort->sp_nMCR );
  


      // Clear interrupt registers
    ser_in( psPort, UART_LSR );  // Line status (LSR)
    ser_in( psPort, UART_RX );
    ser_in( psPort, UART_IIR );  // Check interrupt type (IIR)
    ser_in( psPort, UART_MSR );  // Check modem status (MSR)

    spinunlock_enable( &g_sSPinLock, nFlg );
  
    return( 0 );
}
Exemplo n.º 9
0
int main()
{
	int key = 123 ;
	int memsize = sizeof(int) ;	
	
	int shmemId = create_shmem(key, memsize) ;
	if (shmemId == -1) {
		perror("shared segment creation error") ;
		exit(EXIT_FAILURE) ;
	}
	
	int* buffer = (int*) attach_shmem(shmemId) ;
	*buffer = 0 ;
	
	int emptySemKey = 100 ;
	int emptySemId = create_semaphore(emptySemKey) ;
	
	int fullSemKey = 101 ;
	int fullSemId = create_semaphore(fullSemKey) ;
	
	if ((emptySemId == -1) || (fullSemId == -1)) {
		perror("semaphore creation error") ;
		exit(EXIT_FAILURE) ;
	}
	
	init_semaphore(fullSemId, 0) ;
	init_semaphore(emptySemId, 1) ;
	
	while (*buffer >= 0) {
		down(emptySemId) ;
		if (!scanf("%d", buffer))
			*buffer = -1 ;
		up(fullSemId) ;
	}

	remove_semaphore(fullSemId) ;
	remove_semaphore(emptySemId) ;
	detach_shmem(buffer) ;
	remove_shmem(shmemId) ;	
}
Exemplo n.º 10
0
port_id sys_create_port( const char *const pzName, int nMaxCount )
{
	int nError;
	MsgPort_s *psPort;

	lock_mutex( g_hPortListSema, true );

	psPort = kmalloc( sizeof( MsgPort_s ), MEMF_CLEAR | MEMF_KERNEL | MEMF_LOCKED | MEMF_OKTOFAIL );

	if ( psPort == NULL )
	{
		nError = -ENOMEM;
		goto error1;
	}
	psPort->mp_hSyncSema = create_semaphore( "port_sync", 0, 0 );

	if ( psPort->mp_hSyncSema < 0 )
	{
		printk( "Error: sys_create_port() failed to allocate semaphore\n" );
		nError = psPort->mp_hSyncSema;
		goto error2;
	}
	psPort->mp_hPortID = MArray_Insert( &g_sMsgPorts, psPort, false );

	if ( psPort->mp_hPortID < 0 )
	{
		printk( "Failed to alloc descriptor for msg port %s\n", pzName );
		nError = psPort->mp_hPortID;
		goto error3;
	}
	psPort->mp_nMaxCount = nMaxCount;
	psPort->mp_nFlags = 0;
	strncpy_from_user( psPort->mp_zName, pzName, OS_NAME_LENGTH );
	psPort->mp_zName[OS_NAME_LENGTH - 1] = '\0';

	link_port( CURRENT_PROC, psPort );

	unlock_mutex( g_hPortListSema );

	atomic_inc( &g_sSysBase.ex_nMessagePortCount );

	return ( psPort->mp_hPortID );

      error3:
	delete_semaphore( psPort->mp_hSyncSema );
      error2:
	kfree( psPort );
      error1:
	unlock_mutex( g_hPortListSema );

	return ( nError );
}
Exemplo n.º 11
0
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
{
	int flags;
	pthread_mutexattr_t* mutex_attr = NULL;

	if( mutex == NULL )
		return( EINVAL );

	if( attr == NULL )
	{
		mutex_attr = &mutex->__def_attr;
		pthread_mutexattr_init( mutex_attr ); 
	}
	else
		mutex_attr = (pthread_mutexattr_t*)attr;

	mutex->__owner = pthread_self();		/* Mutex owner */
	mutex->__count = 0;						/* Lock count  */
	mutex->__attr = mutex_attr;				/* Our own copy of the mutex attributes */

	switch( mutex_attr->__mutexkind )
	{
		case PTHREAD_MUTEX_DEFAULT:			/* DEFAULT is undefined, this'll do */
		case PTHREAD_MUTEX_NORMAL:			/* As per the standard              */
			flags = 0;
			break;

		case PTHREAD_MUTEX_ERRORCHECK:
			flags = SEM_WARN_DBL_LOCK | SEM_WARN_DBL_UNLOCK;
			break;

		case PTHREAD_MUTEX_RECURSIVE:
			flags = SEM_RECURSIVE;
			break;

		default:
		{
			pthread_mutex_destroy( mutex );
			return( EINVAL );
		}
	};

	if( mutex_attr->__pshared == PTHREAD_PROCESS_SHARED )
		flags |= SEM_GLOBAL;		/* Technically not 100% correct, but close enough */
									/* for our purposes                               */

	/* Create the mutex itself */
	mutex->__mutex = create_semaphore( "pthread_sem", 1, flags | SEM_WARN_DBL_LOCK );

	return( 0 );
}
Exemplo n.º 12
0
int main()
{
    getcontext(&uctx_main);  //AMJAD: Added uctx_main
    int thread_num = 10;
    int j;
    char* thread_names[] = {
        "thread 0",
        "thread 1",
        "thread 2",
        "thread 3",
        "thread 4",
        "thread 5",
        "thread 6",
        "thread 7",
        "thread 8",
        "thread 9"
    };

    /* Initialize MyThreads library. */
    mythread_init();

    /* 250 ms */
    set_quantum_size(250);

    counter_mutex = create_semaphore(1);

    for(j=0; j<thread_num; j++)
    {
        mythread_create(thread_names[j], (void *) &handler, 6004);
    }

    /* Print threads informations before run */
    mythread_state();

    /* When this function returns, all threads should have exited. */
    runthreads();
    
    destroy_semaphore(counter_mutex);

    /* Print threads informations after run */
    mythread_state();

    printf("The counter is %d\n", counter);
    printf("The result is %f\n", result);

    if (counter == 50 &&
	(result - 151402.656521) < 0.000001)
      printf(">>> Thread library PASSED the Test 1\n");

    exit(0);
}
int main(int argc, char** argv)
{
  char semaphore_name[32];
  int optchar;
  pthread_t tid1;
  pthread_t tid2;

  while ((optchar = getopt(argc, argv, "q")) != EOF)
  {
    switch (optchar)
    {
    case 'q': s_quiet = 1; break;
    default:
      fprintf(stderr, "Error: unknown option '%c'.\n", optchar);
      return 1;
    }
  }

  /* Initialize synchronization objects. */
  snprintf(semaphore_name, sizeof(semaphore_name), "semaphore-%d", getpid());
  s_sem = create_semaphore(semaphore_name);
  PTH_CALL(pthread_cond_init(&s_cond, 0));
  PTH_CALL(pthread_mutex_init(&s_mutex1, 0));
  PTH_CALL(pthread_mutex_init(&s_mutex2, 0));

  /* Create two threads. */
  PTH_CALL(pthread_create(&tid1, 0, &thread_func, &s_mutex1));
  PTH_CALL(pthread_create(&tid2, 0, &thread_func, &s_mutex2));

  /* Wait until both threads have called sem_post(). */
  sem_wait(s_sem);
  sem_wait(s_sem);
  destroy_semaphore(semaphore_name, s_sem);
  s_sem = 0;

  /* Wait until both threads are waiting inside pthread_cond_wait(). */
  PTH_CALL(pthread_mutex_lock(&s_mutex1));
  PTH_CALL(pthread_mutex_lock(&s_mutex2));
  PTH_CALL(pthread_mutex_unlock(&s_mutex2));
  PTH_CALL(pthread_mutex_unlock(&s_mutex1));

  /* Signal s_cond twice. */
  PTH_CALL(pthread_cond_signal(&s_cond));
  PTH_CALL(pthread_cond_signal(&s_cond));

  /* Join both threads. */
  PTH_CALL(pthread_join(tid1, 0));
  PTH_CALL(pthread_join(tid2, 0));

  return 0;
}
Exemplo n.º 14
0
static void create_semaphore_serial(semaphore_t *sem)
{

	if (!(sem))

		return;

	get_mutex(&crit_sec_create_sem);

	if (!(sem->is_init))

		create_semaphore(sem);

	release_mutex(&crit_sec_create_sem);
}
Exemplo n.º 15
0
Arquivo: ps2.c Projeto: PyroOS/Pyro
/* Initializes the controller and the keyboard part */
static status_t ps2_keyboard_init()
{
	int nError = 0;
	g_nKbdLedStatus = 0;
	
	memset( &g_sKbdPort, 0, sizeof( g_sKbdPort ) );
	
	/* Flush buffer */
	ps2_flush();
	
	/* Read control register */
	uint8 nControl = 0;
	nError = ps2_read_command( PS2_CMD_RCTR, &nControl );
	
	if( nError < 0 ) {
		printk( "PS2 I/O error\n" );
		return( -EIO );
	}
	
	/* TODO: Disable keyboard */
	nControl |= PS2_CTR_KBDDIS;
	nControl &= ~PS2_CTR_KBDINT;
	
	/* Check if translated mode is enabled */
	if( !( nControl & PS2_CTR_XLATE ) )
	{
		printk( "Keyboard is in non-translated mode. This is not supported\n" );
		return( -ENOENT );
	}
	
	/* Write control register */
	nError = ps2_write_command( PS2_CMD_WCTR, nControl );
	if( nError < 0 ) {
		printk( "PS2 I/O error\n" );
		return( -EIO );
	}
	
	g_sKbdPort.bPresent = true;
	g_sKbdPort.hWait = create_semaphore( "ps2_wait", 0, 0 );
	g_sKbdPort.nIrq = 1;
	g_sKbdPort.nDevHandle = register_device( "", "isa" );
	claim_device( g_nDevNum, g_sKbdPort.nDevHandle, "PS/2 or AT keyboard", DEVICE_INPUT );
	set_device_data( g_sKbdPort.nDevHandle, &g_sKbdPort );
	nError = create_device_node( g_nDevNum, g_sKbdPort.nDevHandle, "keybd", &g_sOperations, &g_sKbdPort );
	
	printk( "PS2 or AT Keyboard detected\n" );
	return( 0 );
}
Exemplo n.º 16
0
int main()
{
    int thread_num = 10;
    int j;
    char* thread_names[] = {
        "thread 0",
        "thread 1",
        "thread 2",
        "thread 3",
        "thread 4",
        "thread 5",
        "thread 6",
        "thread 7",
        "thread 8",
        "thread 9"
    };

    /* Initialize MyThreads library. */
    init_my_threads();

    /* 250 ms */
    set_quantum_size(250);

    counter_mutex = create_semaphore(1);

    for(j=0; j<thread_num; j++)
    {
        create_my_thread(thread_names[j], (void *) &handler, 64000);
    }

    /* Print threads informations before run */
    my_threads_state();

    /* When this function returns, all threads should have exited. */
    runthreads();
    
    destroy_semaphore(counter_mutex);

    /* Print threads informations after run */
    my_threads_state();

    printf("The counter is %d\n", counter);
    printf("The result is %f\n", result);

    exit(0);
}
Exemplo n.º 17
0
/* Create a counting semaphore */
SDL_sem *SDL_CreateSemaphore(Uint32 initial_value)
{
	SDL_sem *sem;

	sem = (SDL_sem *)malloc(sizeof(*sem));
	if ( sem ) {
		sem->id = create_semaphore("SDL semaphore", initial_value, 0);
		if ( sem->id < 0 ) {
			SDL_SetError("create_sem() failed");
			free(sem);
			sem = NULL;
		}
	} else {
		SDL_OutOfMemory();
	}
	return(sem);
}
Exemplo n.º 18
0
Arquivo: osl.c Projeto: PyroOS/Pyro
acpi_status
acpi_os_create_semaphore(
	u32		max_units,
	u32		initial_units,
	acpi_handle	*handle)
{
	sem_id	*sem = NULL;

	ACPI_FUNCTION_TRACE ("os_create_semaphore");

	sem = acpi_os_allocate(sizeof(sem_id));
	if (!sem)
		return_ACPI_STATUS (AE_NO_MEMORY);
	memset(sem, 0, sizeof(sem_id));

	*sem = create_semaphore( "acpi_semaphore", initial_units, 0 );

	*handle = (acpi_handle*)sem;

	ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Creating semaphore[%p|%d].\n", *handle, initial_units));

	return_ACPI_STATUS (AE_OK);
}
Exemplo n.º 19
0
int main(int argc, char **argv) {
  int merge, interp, purge, i, gotfile;
#ifdef USE_GRIB_UPDATE_TIME
  int    update, tsset;
  time_t update_time;
#endif /* USE_GRIB_UPDATE_TIME */

  int shmid, semid;
  void *segmaddr;
  struct sembuf sem_op[2];
  
  /* TODO add options like -merge -interp -replace */
  global_vlmc_context = calloc(1, sizeof(vlmc_context));
  init_context_default(global_vlmc_context);

  if (argc == 1) {
    usage(*argv);
  }
  
#ifdef USE_GRIB_UPDATE_TIME
  gotfile = merge = interp = purge = update = tsset = 0;
  update_time = 0;
#else
  gotfile = merge = interp = purge = 0;
#endif /* USE_GRIB_UPDATE_TIME */
  for (i=1; i<argc; i++) {
#ifdef USE_GRIB_UPDATE_TIME
    if (!strncmp(argv[i], "-update", 8)) {
      update = 1;
      continue;
    }
    if (!strncmp(argv[i], "-set", 5)) {
      i++;
      if (i<argc) {
	update_time = atol(argv[i]);
	tsset = 1;
      }
      continue;
    }
#endif /* USE_GRIB_UPDATE_TIME */
    if (!strncmp(argv[i], "-merge", 7)) {
      merge = 1;
      continue;
    }
    if (!strncmp(argv[i], "-purge", 7)) {
      purge = 1;
      continue;
    }
    if (!strncmp(argv[i], "-interp", 8)) {
      interp = 1;
      continue;
    }
    /* unknown option */
    if (*argv[i] == '-') {
      usage(argv[0]);
    }
    set_grib_filename(global_vlmc_context, argv[i]);
    break;
  }

  shmid = -1;
  segmaddr = NULL;
  /* first we read the grib before locking things */
#ifdef USE_GRIB_UPDATE_TIME
  if (merge||update) {
    /* first we need to read the grib from the segment */
    /* no need to lock as we are the one to lock it when doing the update */
    shmid = get_grib_shmid(0);
    if (shmid == -1) {
      fprintf(stderr, "Can't attach segment, impossible to merge data\n");
    } else {
      segmaddr = get_shmem(shmid, 0);
      allocate_grib_array_from_shmem(&global_vlmc_context->windtable, segmaddr);
      if (merge) {
	merge_gribs(purge);
      } else if (update) { /* no need for the if there, but for sanity... */
	/* we save the previous timestamp, as it's only an update
	   and not a replacement */
	update_time = get_grib_update_time();
	tsset = 1; /* force setting the time stamp */
	init_grib();
	if (purge) {
	  purge_gribs();
	}
      }
    }
  } 
#else
  if (merge) {
    /* first we need to read the grib from the segment */
    /* no need to lock as we are the one to lock it when doing the update */
    shmid = get_grib_shmid(0);
    if (shmid == -1) {
      fprintf(stderr, "Can't attach segment, impossible to merge data\n");
    } else {
      segmaddr = get_shmem(shmid, 0);
      allocate_grib_array_from_shmem(&global_vlmc_context->windtable, segmaddr);
      merge_gribs(purge);
    }
  } 
#endif /* USE_GRIB_UPDATE_TIME */

  if (!segmaddr) { /* no merge, or failed one */
    init_grib();
    if (purge) {
      purge_gribs();
    }
  }

  if (!global_vlmc_context->windtable.nb_prevs) {
    fprintf(stderr, "Invalid GRIB entry\n");
    exit(1);
  }
#ifdef USE_GRIB_UPDATE_TIME
  if (tsset) {
    set_grib_update_time(update_time);
  }
#endif /* USE_GRIB_UPDATE_TIME */
  
  semid = get_semaphore_id();
  if (semid == -1) {
    semid = create_semaphore();
    if (semid == -1) {
      fprintf(stderr, "Unable to create the semaphore\n");
      exit(1);
    }
  }
  sem_op[0].sem_num = 0;
  sem_op[0].sem_op  = 0;
  sem_op[0].sem_flg = SEM_UNDO;
  sem_op[1].sem_num = 0;
  sem_op[1].sem_op  = 1;
  sem_op[1].sem_flg = SEM_UNDO|IPC_NOWAIT;
  if (semop(semid, sem_op, 2) == -1) {
    fprintf(stderr, "Fail to lock the semaphore\n");
    exit(1);
  }
  
  if (shmid == -1) { /* uninitialized ? (we might have got it already) */
    shmid = get_grib_shmid(0);
  }
  if (shmid == -1) {
    /* not there, we create it */
    shmid = create_grib_shmid(&global_vlmc_context->windtable);
    if (shmid == -1) {
      fprintf(stderr, "Fail to create the GRIB memory segment\n");
      exit(1);
    }
  }

  /* copy the grib */
  if (!segmaddr) { /* did we got it from a merge ? */
    segmaddr = get_shmem(shmid, 0);
  }
  copy_grib_array_to_shmem(shmid, &global_vlmc_context->windtable, segmaddr);
  shmdt(segmaddr);

  sem_op[0].sem_num = 0;
  sem_op[0].sem_op  = -1;
  sem_op[0].sem_flg = SEM_UNDO|IPC_NOWAIT;
  if (semop(semid, sem_op, 1) == -1) {
    fprintf(stderr, "Fail to unlock the semaphore\n");
    exit(1);
  }
  printf("Grib segment successfully updated\n");
  return 0;
}
Exemplo n.º 20
0
int
main(int argc, char **argv)
{
    int jitter_plot[101];
    int latency_plot[101];
    int long_index = 0;
    struct option long_options[] = {
        {"help", 0, NULL, 'h'},
        {"message-size", 1, NULL, 'm'},
        {"samples", 1, NULL, 's'},
        {"timeout", 1, NULL, 't'}
    };
    size_t name_arg_count;
    size_t name_size;
    char *option_string = "hm:s:t:";
    int show_usage = 0;
    connections_established = 0;
    error_message = NULL;
    message_size = 3;
    program_name = argv[0];
    remote_in_port = 0;
    remote_out_port = 0;
    samples = 1024;
    timeout = 5;

    for (;;) {
        signed char c = getopt_long(argc, argv, option_string, long_options,
                             &long_index);
        switch (c) {
        case 'h':
            show_usage = 1;
            break;
        case 'm':
            message_size = parse_positive_number_arg(optarg, "message-size");
            break;
        case 's':
            samples = parse_positive_number_arg(optarg, "samples");
            break;
        case 't':
            timeout = parse_positive_number_arg(optarg, "timeout");
            break;
        default:
            {
                char *s = "'- '";
                s[2] = c;
                die(s, "invalid switch");
            }
        case -1:
            if (show_usage) {
                output_usage();
                exit(EXIT_SUCCESS);
            }
            goto parse_port_names;
        case 1:
            /* end of switch :) */
            ;
        }
    }
 parse_port_names:
    name_arg_count = argc - optind;
    switch (name_arg_count) {
    case 2:
        target_in_port_name = argv[optind + 1];
        target_out_port_name = argv[optind];
        break;
    case 0:
        target_in_port_name = 0;
        target_out_port_name = 0;
        break;
    default:
        output_usage();
        return EXIT_FAILURE;
    }
    name_size = jack_port_name_size();
    alias1 = malloc(name_size * sizeof(char));
    if (alias1 == NULL) {
        error_message = strerror(errno);
        error_source = "malloc";
        goto show_error;
    }
    alias2 = malloc(name_size * sizeof(char));
    if (alias2 == NULL) {
        error_message = strerror(errno);
        error_source = "malloc";
        goto free_alias1;
    }
    latency_values = malloc(sizeof(jack_nframes_t) * samples);
    if (latency_values == NULL) {
        error_message = strerror(errno);
        error_source = "malloc";
        goto free_alias2;
    }
    latency_time_values = malloc(sizeof(jack_time_t) * samples);
    if (latency_time_values == NULL) {
        error_message = strerror(errno);
        error_source = "malloc";
        goto free_latency_values;
    }
    message_1 = malloc(message_size * sizeof(jack_midi_data_t));
    if (message_1 == NULL) {
        error_message = strerror(errno);
        error_source = "malloc";
        goto free_latency_time_values;
    }
    message_2 = malloc(message_size * sizeof(jack_midi_data_t));
    if (message_2 == NULL) {
        error_message = strerror(errno);
        error_source = "malloc";
        goto free_message_1;
    }
    switch (message_size) {
    case 1:
        message_1[0] = 0xf6;
        message_2[0] = 0xfe;
        break;
    case 2:
        message_1[0] = 0xc0;
        message_1[1] = 0x00;
        message_2[0] = 0xd0;
        message_2[1] = 0x7f;
        break;
    case 3:
        message_1[0] = 0x80;
        message_1[1] = 0x00;
        message_1[2] = 0x00;
        message_2[0] = 0x90;
        message_2[1] = 0x7f;
        message_2[2] = 0x7f;
        break;
    default:
        message_1[0] = 0xf0;
        memset(message_1 + 1, 0,
               (message_size - 2) * sizeof(jack_midi_data_t));
        message_1[message_size - 1] = 0xf7;
        message_2[0] = 0xf0;
        memset(message_2 + 1, 0x7f,
               (message_size - 2) * sizeof(jack_midi_data_t));
        message_2[message_size - 1] = 0xf7;
    }
    client = jack_client_open(program_name, JackNullOption, NULL);
    if (client == NULL) {
        error_message = "failed to open JACK client";
        error_source = "jack_client_open";
        goto free_message_2;
    }
    in_port = jack_port_register(client, "in", JACK_DEFAULT_MIDI_TYPE,
                                 JackPortIsInput, 0);
    if (in_port == NULL) {
        error_message = "failed to register MIDI-in port";
        error_source = "jack_port_register";
        goto close_client;
    }
    out_port = jack_port_register(client, "out", JACK_DEFAULT_MIDI_TYPE,
                                  JackPortIsOutput, 0);
    if (out_port == NULL) {
        error_message = "failed to register MIDI-out port";
        error_source = "jack_port_register";
        goto unregister_in_port;
    }
    if (jack_set_process_callback(client, handle_process, NULL)) {
        error_message = "failed to set process callback";
        error_source = "jack_set_process_callback";
        goto unregister_out_port;
    }
    if (jack_set_xrun_callback(client, handle_xrun, NULL)) {
        error_message = "failed to set xrun callback";
        error_source = "jack_set_xrun_callback";
        goto unregister_out_port;
    }
    if (jack_set_port_connect_callback(client, handle_port_connection_change,
                                       NULL)) {
        error_message = "failed to set port connection callback";
        error_source = "jack_set_port_connect_callback";
        goto unregister_out_port;
    }
    jack_on_shutdown(client, handle_shutdown, NULL);
    jack_set_info_function(handle_info);
    process_state = 0;

    connect_semaphore = create_semaphore(0);
    if (connect_semaphore == NULL) {
        error_message = get_semaphore_error();
        error_source = "create_semaphore";
        goto unregister_out_port;
    }
    init_semaphore = create_semaphore(1);
    if (init_semaphore == NULL) {
        error_message = get_semaphore_error();
        error_source = "create_semaphore";
        goto destroy_connect_semaphore;;
    }
    process_semaphore = create_semaphore(2);
    if (process_semaphore == NULL) {
        error_message = get_semaphore_error();
        error_source = "create_semaphore";
        goto destroy_init_semaphore;
    }
    if (jack_activate(client)) {
        error_message = "could not activate client";
        error_source = "jack_activate";
        goto destroy_process_semaphore;
    }
    if (name_arg_count) {
        if (jack_connect(client, jack_port_name(out_port),
                         target_out_port_name)) {
            error_message = "could not connect MIDI out port";
            error_source = "jack_connect";
            goto deactivate_client;
        }
        if (jack_connect(client, target_in_port_name,
                         jack_port_name(in_port))) {
            error_message = "could not connect MIDI in port";
            error_source = "jack_connect";
            goto deactivate_client;
        }
    }
    if (! register_signal_handler(handle_signal)) {
        error_message = strerror(errno);
        error_source = "register_signal_handler";
        goto deactivate_client;
    }
    printf("Waiting for connections ...\n");
    if (wait_semaphore(connect_semaphore, 1) == -1) {
        error_message = get_semaphore_error();
        error_source = "wait_semaphore";
        goto deactivate_client;
    }
    if (connections_established) {
        printf("Waiting for test completion ...\n\n");
        if (wait_semaphore(process_semaphore, 1) == -1) {
            error_message = get_semaphore_error();
            error_source = "wait_semaphore";
            goto deactivate_client;
        }
    }
    if (! register_signal_handler(SIG_DFL)) {
        error_message = strerror(errno);
        error_source = "register_signal_handler";
        goto deactivate_client;
    }
    if (process_state == 2) {
        double average_latency = ((double) total_latency) / samples;
        double average_latency_time = total_latency_time / samples;
        size_t i;
        double latency_plot_offset =
            floor(((double) lowest_latency_time) / 100.0) / 10.0;
        double sample_rate = (double) jack_get_sample_rate(client);
        jack_nframes_t total_jitter = 0;
        jack_time_t total_jitter_time = 0;
        for (i = 0; i <= 100; i++) {
            jitter_plot[i] = 0;
            latency_plot[i] = 0;
        }
        for (i = 0; i < samples; i++) {
            double latency_time_value = (double) latency_time_values[i];
            double latency_plot_time =
                (latency_time_value / 1000.0) - latency_plot_offset;
            double jitter_time = ABS(average_latency_time -
                                     latency_time_value);
            if (latency_plot_time >= 10.0) {
                (latency_plot[100])++;
            } else {
                (latency_plot[(int) (latency_plot_time * 10.0)])++;
            }
            if (jitter_time >= 10000.0) {
                (jitter_plot[100])++;
            } else {
                (jitter_plot[(int) (jitter_time / 100.0)])++;
            }
            total_jitter += ABS(average_latency -
                                ((double) latency_values[i]));
            total_jitter_time += jitter_time;
        }
        printf("Reported out-port latency: %.2f-%.2f ms (%u-%u frames)\n"
               "Reported in-port latency: %.2f-%.2f ms (%u-%u frames)\n"
               "Average latency: %.2f ms (%.2f frames)\n"
               "Lowest latency: %.2f ms (%u frames)\n"
               "Highest latency: %.2f ms (%u frames)\n"
               "Peak MIDI jitter: %.2f ms (%u frames)\n"
               "Average MIDI jitter: %.2f ms (%.2f frames)\n",
               (out_latency_range.min / sample_rate) * 1000.0,
               (out_latency_range.max / sample_rate) * 1000.0,
               out_latency_range.min, out_latency_range.max,
               (in_latency_range.min / sample_rate) * 1000.0,
               (in_latency_range.max / sample_rate) * 1000.0,
               in_latency_range.min, in_latency_range.max,
               average_latency_time / 1000.0, average_latency,
               lowest_latency_time / 1000.0, lowest_latency,
               highest_latency_time / 1000.0, highest_latency,
               (highest_latency_time - lowest_latency_time) / 1000.0,
               highest_latency - lowest_latency,
               (total_jitter_time / 1000.0) / samples,
               ((double) total_jitter) / samples);
        printf("\nJitter Plot:\n");
        for (i = 0; i < 100; i++) {
            if (jitter_plot[i]) {
                printf("%.1f - %.1f ms: %d\n", ((float) i) / 10.0,
                       ((float) (i + 1)) / 10.0, jitter_plot[i]);
            }
        }
        if (jitter_plot[100]) {
            printf("     > 10 ms: %d\n", jitter_plot[100]);
        }
        printf("\nLatency Plot:\n");
        for (i = 0; i < 100; i++) {
            if (latency_plot[i]) {
                printf("%.1f - %.1f ms: %d\n",
                       latency_plot_offset + (((float) i) / 10.0),
                       latency_plot_offset + (((float) (i + 1)) / 10.0),
                       latency_plot[i]);
            }
        }
        if (latency_plot[100]) {
            printf("     > %.1f ms: %d\n", latency_plot_offset + 10.0,
                   latency_plot[100]);
        }
    }
 deactivate_client:
    jack_deactivate(client);
    printf("\nMessages sent: %d\nMessages received: %d\n", messages_sent,
           messages_received);
    if (unexpected_messages) {
        printf("Unexpected messages received: %d\n", unexpected_messages);
    }
    if (xrun_count) {
        printf("Xruns: %d\n", xrun_count);
    }
 destroy_process_semaphore:
    destroy_semaphore(process_semaphore, 2);
 destroy_init_semaphore:
    destroy_semaphore(init_semaphore, 1);
 destroy_connect_semaphore:
    destroy_semaphore(connect_semaphore, 0);
 unregister_out_port:
    jack_port_unregister(client, out_port);
 unregister_in_port:
    jack_port_unregister(client, in_port);
 close_client:
    jack_client_close(client);
 free_message_2:
    free(message_2);
 free_message_1:
    free(message_1);
 free_latency_time_values:
    free(latency_time_values);
 free_latency_values:
    free(latency_values);
 free_alias2:
    free(alias2);
 free_alias1:
    free(alias1);
    if (error_message != NULL) {
    show_error:
        output_error(error_source, error_message);
        exit(EXIT_FAILURE);
    }
    return EXIT_SUCCESS;
}
Exemplo n.º 21
0
Arquivo: ps2.c Projeto: PyroOS/Pyro
static status_t ps2_aux_init()
{
	int nError = 0;
	struct RMREGS rm;

	/* TODO: Do this without calling the bios */
	memset( &rm, 0, sizeof( struct RMREGS ) );
	realint( 0x11, &rm );

	if( ( rm.EAX & 0x04 ) == 0 ) {
		printk( "No PS2 mouse present\n" );
		return( -EIO );
    }
	
	memset( &g_sAuxPort, 0, sizeof( g_sAuxPort ) );
	g_sAuxPort.bIsAux = true;
	
	/* Flush buffer */
	ps2_flush();
	
	/* Test loop command */
	uint8 nData = 0x5a;
	
	nError = ps2_write_read_command( PS2_CMD_AUX_LOOP, &nData );
	
	if( nError < 0 || nData != 0x5a )
	{
		/* According to linux driver the loop test fails on some chipsets */
		printk( "PS2 Aux loop test failed (error = %i, data = %x)! Trying test command...\n", nError, (uint)nData );
		if( ps2_read_command( PS2_CMD_AUX_TEST, &nData ) < 0 )
		{
			printk( "Failed -> Aux port not present!\n" );
			return( -ENOENT );
		}
		printk( "Test command returned %x\n", (uint)nData );
		if( nData && nData != 0xfa && nData != 0xff )
		{
			printk( "Invalid return code!\n" );
			return( -ENOENT );
		}
	}
	
	/* Disable and then enable the auxport */
	if( ps2_command( PS2_CMD_AUX_DISABLE ) < 0 )
		return( -ENOENT );
	if( ps2_command( PS2_CMD_AUX_ENABLE ) < 0 )
		return( -ENOENT );
	if( ps2_read_command( PS2_CMD_RCTR, &nData ) < 0 || ( nData & PS2_CTR_AUXDIS ) )
		return( -EIO );
		
	/* Disable aux port */
	nData |= PS2_CTR_AUXDIS;
	nData &= ~PS2_CTR_AUXINT;
	
	/* Write control register */
	nError = ps2_write_command( PS2_CMD_WCTR, nData );
	if( nError < 0 ) {
		printk( "PS2 I/O error\n" );
		return( -EIO );
	}

	printk( "PS2 AUX port detected\n" );
	
	/* Register device */
	
	g_sAuxPort.bPresent = true;
	g_sAuxPort.hWait = create_semaphore( "ps2_wait", 0, 0 );
	g_sAuxPort.nDevHandle = register_device( "", "isa" );
	g_sAuxPort.nIrq = 12;
	claim_device( g_nDevNum, g_sAuxPort.nDevHandle, "PS/2 Aux port", DEVICE_PORT );
	set_device_data( g_sAuxPort.nDevHandle, &g_sAuxPort );
	nError = create_device_node( g_nDevNum, g_sAuxPort.nDevHandle, "misc/ps2aux", &g_sOperations, &g_sAuxPort );
	
	if( nError < 0 )
		return( -EIO );
	
	return( 0 );
}
Exemplo n.º 22
0
// FIFO front offset
#define FIFO_2_CO SUM+2*sizeof(int)
#define FIFO_2_FO SUM+3*sizeof(int)

#define MSEC 1000
/*}}}*/
// Globals/*{{{*/
int remaining_A1 = A1_SIZE;
int remaining_A2 = A2_SIZE;
int remaining_A3 = A3_SIZE;
int remaining_B1 = B1_SIZE;
int remaining_B2 = B2_SIZE;

char *shm;

semaphore mutex = create_semaphore(1);
semaphore a1 = create_semaphore(1);
semaphore a2 = create_semaphore(1);
semaphore a3 = create_semaphore(1);
semaphore b1_1 = create_semaphore(1);
semaphore b1_2 = create_semaphore(1);
semaphore b2_1 = create_semaphore(1);
semaphore b2_2 = create_semaphore(1);
/*}}}*/
int *count(int q) {/*{{{*/
  // Returns pointer to integer containing queue element count
  if ( q == FIFO_1 ) 
    return (int*)shm + FIFO_1_CO;
  else
    return (int*)shm + FIFO_2_CO;
}/*}}}*/