Exemplo n.º 1
0
void INIT_ATTR headphone_init(void)
{
    /* A thread is required to monitor the remote ADC and jack state. */
    semaphore_init(&headphone_wakeup, 1, 0);
    headphone_thread_id = create_thread(headphone_thread, 
                                        headphone_stack,
                                        sizeof(headphone_stack),
                                        0, headphone_thread_name
                                        IF_PRIO(, PRIORITY_REALTIME)
                                        IF_COP(, CPU));

    /* Initially poll and then enable PMIC event */
    headphone_detect_event();
    mc13783_enable_event(MC13783_ONOFD2_EVENT);
}
Exemplo n.º 2
0
void kmain()
{
	irq_disable();
	/* 
	 * A primeira coisa a se fazer é iniciar todo o gerenciador
	 * de memória.
	 */
	mm_init();
	arch_early_init();
	ioremap_init();
	irq_init();
	sched_init();
	timer_init();
	/* 
	 * Neste momento temos o gerenciador de memória e escalonador prontos,
	 * já podemos habilitar as interrupções, que podem ser utilizadas
	 * pelos drivers.
	 */
	irq_enable();

	/* Inicia os drivers da plataforma */
	arch_setup();

	/* Requisita um modo se existir um framebuffer*/
	fb_set_mode();
	/* Inicia o console sobre o framebuffer */
	fb_console_init();
	kernel_info();

#if 1
	irq_disable();
	semaphore_init(&sem, 1);
	create_task("a", 4);
	create_task("b", 5);
	create_task("c", 6);
	create_task("d", 7);
	create_task("b", 8);
	create_task("b", 9);
	irq_enable();
	/* Fica de boas esperando as trocas de contexto */
#endif
	/* Como queremos imprimir para depuração do driver, inicializamos ele agora */
	//bcm2835_emmc_init();
	for (;;) {
		led_blink();
		//printk("-");
	}
}
Exemplo n.º 3
0
void imx233_lradc_init(void)
{
    mutex_init(&free_bm_mutex);
    semaphore_init(&free_bm_sema, HW_LRADC_NUM_CHANNELS, HW_LRADC_NUM_CHANNELS);
    free_bm = (1 << HW_LRADC_NUM_CHANNELS) - 1;
    // enable block
    imx233_reset_block(&HW_LRADC_CTRL0);
    // disable ground ref
    __REG_CLR(HW_LRADC_CTRL0) = HW_LRADC_CTRL0__ONCHIP_GROUNDREF;
    // disable temperature sensors
    __REG_CLR(HW_LRADC_CTRL2) = HW_LRADC_CTRL2__TEMP_SENSOR_IENABLE0 |
        HW_LRADC_CTRL2__TEMP_SENSOR_IENABLE1;
    __REG_SET(HW_LRADC_CTRL2) = HW_LRADC_CTRL2__TEMPSENSE_PWD;
    // set frequency
    __REG_CLR(HW_LRADC_CTRL3) = HW_LRADC_CTRL3__CYCLE_TIME_BM;
    __REG_SET(HW_LRADC_CTRL3) = HW_LRADC_CTRL3__CYCLE_TIME__6MHz;
}
Exemplo n.º 4
0
Arquivo: init.c Projeto: Quest-V/quest
/* Allocate a basic TSS */
static uint16
alloc_TSS (void *pPageDirectory, void *pEntry, int mod_num)
{

  int i;
  descriptor *ad = (idt + 256); /* Get address of GDT from IDT address */
  quest_tss *pTSS = (quest_tss *) ul_tss[mod_num];

  /* Search 2KB GDT for first free entry */
  for (i = 1; i < 256; i++)
    if (!(ad[i].fPresent))
      break;

  if (i == 256)
    panic ("No free selector for TSS");

  ad[i].uLimit0 = sizeof (ul_tss[mod_num]) - 1;
  ad[i].uLimit1 = 0;
  ad[i].pBase0 = (u32) pTSS & 0xFFFF;
  ad[i].pBase1 = ((u32) pTSS >> 16) & 0xFF;
  ad[i].pBase2 = (u32) pTSS >> 24;
  ad[i].uType = 0x09;           /* 32-bit tss */
  ad[i].uDPL = 0;               /* Only let kernel perform task-switching */
  ad[i].fPresent = 1;
  ad[i].f0 = 0;
  ad[i].fX = 0;
  ad[i].fGranularity = 0;       /* Set granularity of tss in bytes */

  pTSS->CR3 = (u32) pPageDirectory;
  pTSS->initial_EIP = (u32) pEntry;

  if (mod_num != 1)
    pTSS->EFLAGS = F_1 | F_IF | F_IOPL0;
  else
    pTSS->EFLAGS = F_1 | F_IF | F_IOPL;       /* Give terminal server access to
                                               * screen memory */

  pTSS->ESP = 0x400000 - 100;
  pTSS->EBP = 0x400000 - 100;

  semaphore_init (&pTSS->Msem, 1, 0);

  /* Return the index into the GDT for the segment */
  return i << 3;
}
Exemplo n.º 5
0
void pca9555_target_init(void)
{
    GPIO_PFCON &= ~(1<<2); /* PF2 for PCA9555 input INT */

    pca9555_ports_init();
    semaphore_init(&pca9555_sem, 1, 0);

    INTC_IMR |= IRQ_ARM_GPIO1;
    INTC_IECR |= IRQ_ARM_GPIO1;
    GPIO_ISF |= (1<<2);

    create_thread(pca9555_read_thread,
                  pca9555_thread_stack,
                  sizeof(pca9555_thread_stack),
                  0,
                  "pca9555_read" IF_PRIO(, PRIORITY_SYSTEM)
                  IF_COP(, CPU));
}
Exemplo n.º 6
0
void lcd_remote_init_device(void)
{
    /* reset */
    remote_dev_enable(false);
    rc_status |= RC_FORCE_DETECT; /* force detection at startup */

    /* unknown */
    GPIO_SET_BITWISE(GPIOL_ENABLE, 0x80);
    GPIO_CLEAR_BITWISE(GPIOL_OUTPUT_VAL, 0x80);
    GPIO_SET_BITWISE(GPIOL_OUTPUT_EN, 0x80);

    /* a thread is required to poll & update the remote */
    semaphore_init(&rc_thread_wakeup, 1, 0);
    remote_thread_id = create_thread(remote_thread, remote_stack,
                            sizeof(remote_stack), 0, remote_thread_name
                            IF_PRIO(, PRIORITY_SYSTEM)
                            IF_COP(, CPU));
}
Exemplo n.º 7
0
int dbg_read_memory(CH_DbgProgramState* state, CH_Address addr, uint32_t len,
                    uint8_t* result, uint8_t* valid) {
  ExaminationClosure* cl = state->closure;
  CH_Range* range = safe_malloc(sizeof(CH_Range));
  DbgReadMemoryClosure inner = { cl, result, valid, addr };
  CH_Semaphore sem;

  range->start = addr;
  range->length = len;
  memset(valid, 0, len);
  semaphore_init(&sem);
  effect_map_reader_do_scan(get_builtin_write_map(),
                            cl->query, 0, state->tstamp, range, 1,
                            MODE_FIND_FIRST_COVER, -1, 0, read_memory_callback,
                            &inner, &sem);
  semaphore_wait_for_all_removed(&sem);
  semaphore_destroy(&sem);
  return 1;
}
Exemplo n.º 8
0
e_int32 lm_init(laser_control_t *lc) {
	int ret;
	e_assert(!lm->state, E_ERROR_INVALID_STATUS);
	lm->state = STATE_PAUSE;
	lm->is_paused = 0;
	semaphore_init(&lm->wakeup, 0);

	lm->lc = lc;

	DMSG((STDOUT, "laser machine starting main routine...\r\n"));
	//启动sick数据读取线程
	ret = createthread("laser_machine", (thread_func) &main_loop, lm, NULL,
			&lm->main_thread);
	e_assert(ret>0, ret);

	ret = resumethread(lm->main_thread);
	e_assert(ret>0, ret);

	return E_OK;
}
Exemplo n.º 9
0
void usb_init_device(void)
{
    unsigned int i;
    for (i = 0; i < sizeof(endpoints)/sizeof(struct ep_type); i++)
        semaphore_init(&endpoints[i].complete, 1, 0);

    /* Power up the core clocks to allow writing
       to some registers needed to power it down */
    PCGCCTL = 0;
#if CONFIG_CPU==S5L8701
    PWRCON &= ~0x4000;
    PWRCONEXT &= ~0x800;
    INTMSK |= INTMSK_USB_OTG;
#elif CONFIG_CPU==S5L8702
    PWRCON(0) &= ~0x4;
    PWRCON(1) &= ~0x8;
    VIC0INTENABLE |= 1 << 19;
#endif

    usb_drv_exit();
}
Exemplo n.º 10
0
void imx233_dcp_init(void)
{
    /* Reset block */
    imx233_reset_block(&HW_DCP_CTRL);
    /* Setup contexte pointer */
    HW_DCP_CONTEXT = (uint32_t)PHYSICAL_ADDR(&dcp_context);
    /* Enable context switching and caching */
    __REG_SET(HW_DCP_CTRL) = HW_DCP_CTRL__ENABLE_CONTEXT_CACHING |
        HW_DCP_CTRL__ENABLE_CONTEXT_SWITCHING;
    /* Check that there are sufficiently many channels */
    if(__XTRACT(HW_DCP_CAPABILITY0, NUM_CHANNELS) != HW_DCP_NUM_CHANNELS)
        panicf("DCP has %lu channels but was configured to use %d !",
               __XTRACT(HW_DCP_CAPABILITY0, NUM_CHANNELS), HW_DCP_NUM_CHANNELS);
    /* Setup channel arbiter to use */
    arbiter_init(&channel_arbiter, HW_DCP_NUM_CHANNELS);
    /* Merge channel0 interrupt */
    __REG_SET(HW_DCP_CHANNELCTRL) = HW_DCP_CHANNELCTRL__CH0_IRQ_MERGED;
    /* setup semaphores */
    for(int i = 0; i< HW_DCP_NUM_CHANNELS; i++)
        semaphore_init(&channel_sema[i], 1, 0);
}
Exemplo n.º 11
0
void usb_drv_init(void)
{
    for (unsigned i = 0; i < sizeof(endpoints)/(2*sizeof(struct ep_type)); i++)
        for (unsigned dir = 0; dir < 2; dir++)
            semaphore_init(&endpoints[i][dir].complete, 1, 0);

    /* Enable USB clock */
#if CONFIG_CPU==S5L8701
    PWRCON &= ~0x4000;
    PWRCONEXT &= ~0x800;
    INTMSK |= INTMSK_USB_OTG;
#elif CONFIG_CPU==S5L8702
    PWRCON(0) &= ~0x4;
    PWRCON(1) &= ~0x8;
    VIC0INTENABLE |= 1 << 19;
#endif
    PCGCCTL = 0;

    /* reset the beast */
    usb_reset();
}
Exemplo n.º 12
0
//如果不存在,创建,存在直接打开
//
//./a.out ./
int main(int argc,char *argv[])
{
    char *shm_addr = NULL;
	int shmid = 0;
    int semid = 0;

    if( -1 == semaphore_init( &semid, argv[1], NSEMS) )
    {
        perror("Failed to semaphore_init");
        return -1;
    }

    if( -1 == shm_init( &shmid, &shm_addr, argv[1], SIZE, 0666) )
    {
        perror("Failed to shm_init");
        return -1;
    }
	
    while(1)
	{
		P(semid,WRITERS);

		printf(">");
		fgets(shm_addr,1024,stdin);
		shm_addr[strlen(shm_addr) - 1] = '\0';

		if( 0 == strncmp(shm_addr,"quit",4) )
		{
            shm_del(&shmid, shm_addr);
			break;
		}
		
        V(semid,READRS);
	}
	
	exit(EXIT_SUCCESS);
}
void Init()
{

	int i = 0;
	int ret;
	semaphore_init();
	ACoreOs_task_wake_after(3000);
	//scanf("%d",&delay_time);
	delay_time = 10;
	printk_spinLock("delay_time = %d\n",delay_time);

    for(i = 0; i < LES_TASKNUMS; i ++){

    	ret = ACoreOs_task_create_smp( task_nams[i], 20,&task_stack[i][0],
    			ACOREOS_MINIMUM_STACK_SIZE*4,
				ACOREOS_PREEMPT | ACOREOS_TIMESLICE,NULL, &task_id[i], i%2+1);
		printk_spinLock("task id = 0x%x \n",task_id[i]);
		ret = ACoreOs_task_start( task_id[i], (ACoreOs_task_entry)task_entry[i], g_msg[i]);
		if(ret)
			printk_spinLock("start task%d failed\n",i);
    }
	CREATE_MONITOR();

}
Exemplo n.º 14
0
/*
 *  This function initializes shared variables of the fsal.
 */
fsal_status_t fsal_internal_init_global(fsal_init_info_t * fsal_info,
                                        fs_common_initinfo_t * fs_common_info)
{

  /* sanity check */
  if(!fsal_info || !fs_common_info)
    ReturnCode(ERR_FSAL_FAULT, 0);

  /* inits FS call semaphore */
  if(fsal_info->max_fs_calls > 0)
    {
      int rc;

      limit_calls = TRUE;

      rc = semaphore_init(&sem_fs_calls, fsal_info->max_fs_calls);

      if(rc != 0)
        ReturnCode(ERR_FSAL_SERVERFAULT, rc);

      LogDebug(COMPONENT_FSAL,
               "FSAL INIT: Max simultaneous calls to filesystem is limited to %u.",
               fsal_info->max_fs_calls);

    }
  else
    {
      LogDebug(COMPONENT_FSAL,
               "FSAL INIT: Max simultaneous calls to filesystem is unlimited.");
    }

  /* setting default values. */
  global_fs_info = default_hpss_info;

  /* Analyzing fs_common_info struct */

  if((fs_common_info->behaviors.maxfilesize != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.maxlink != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.maxnamelen != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.maxpathlen != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.no_trunc != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.case_insensitive != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.case_preserving != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.named_attr != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.lease_time != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.supported_attrs != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.homogenous != FSAL_INIT_FS_DEFAULT))
    ReturnCode(ERR_FSAL_NOTSUPP, 0);

  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, symlink_support);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, link_support);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, lock_support);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, lock_support_owner);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, lock_support_async_block);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, cansettime);

  SET_INTEGER_PARAM(global_fs_info, fs_common_info, maxread);
  SET_INTEGER_PARAM(global_fs_info, fs_common_info, maxwrite);

  SET_BITMAP_PARAM(global_fs_info, fs_common_info, umask);

  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, auth_exportpath_xdev);

  SET_BITMAP_PARAM(global_fs_info, fs_common_info, xattr_access_rights);

  LogDebug(COMPONENT_FSAL, "FileSystem info :");
  LogDebug(COMPONENT_FSAL, "  maxfilesize  = %llX    ",
           global_fs_info.maxfilesize);
  LogDebug(COMPONENT_FSAL, "  maxlink  = %lu   ", global_fs_info.maxlink);
  LogDebug(COMPONENT_FSAL, "  maxnamelen  = %lu  ",
           global_fs_info.maxnamelen);
  LogDebug(COMPONENT_FSAL, "  maxpathlen  = %lu  ",
           global_fs_info.maxpathlen);
  LogDebug(COMPONENT_FSAL, "  no_trunc  = %d ", global_fs_info.no_trunc);
  LogDebug(COMPONENT_FSAL, "  chown_restricted  = %d ",
           global_fs_info.chown_restricted);
  LogDebug(COMPONENT_FSAL, "  case_insensitive  = %d ",
           global_fs_info.case_insensitive);
  LogDebug(COMPONENT_FSAL, "  case_preserving  = %d ",
           global_fs_info.case_preserving);
  LogDebug(COMPONENT_FSAL, "  fh_expire_type  = %hu ",
           global_fs_info.fh_expire_type);
  LogDebug(COMPONENT_FSAL, "  link_support  = %d  ",
           global_fs_info.link_support);
  LogDebug(COMPONENT_FSAL, "  symlink_support  = %d  ",
           global_fs_info.symlink_support);
  LogDebug(COMPONENT_FSAL, "  lock_support  = %d  ",
           global_fs_info.lock_support);
  LogDebug(COMPONENT_FSAL, "  lock_support_owner  = %d  ",
           global_fs_info.lock_support_owner);
  LogDebug(COMPONENT_FSAL, "  lock_support_async_block  = %d  ",
           global_fs_info.lock_support_async_block);
  LogDebug(COMPONENT_FSAL, "  named_attr  = %d  ",
           global_fs_info.named_attr);
  LogDebug(COMPONENT_FSAL, "  unique_handles  = %d  ",
           global_fs_info.unique_handles);
  LogDebug(COMPONENT_FSAL, "  lease_time  = %u.%u     ",
           global_fs_info.lease_time.seconds,
           global_fs_info.lease_time.nseconds);
  LogDebug(COMPONENT_FSAL, "  acl_support  = %hu  ",
           global_fs_info.acl_support);
  LogDebug(COMPONENT_FSAL, "  cansettime  = %d  ",
           global_fs_info.cansettime);
  LogDebug(COMPONENT_FSAL, "  homogenous  = %d  ",
           global_fs_info.homogenous);
  LogDebug(COMPONENT_FSAL, "  supported_attrs  = %llX  ",
           global_fs_info.supported_attrs);
  LogDebug(COMPONENT_FSAL, "  maxread  = %llX     ",
           global_fs_info.maxread);
  LogDebug(COMPONENT_FSAL, "  maxwrite  = %llX     ",
           global_fs_info.maxwrite);
  LogDebug(COMPONENT_FSAL, "  umask  = %#o ", global_fs_info.umask);
  LogDebug(COMPONENT_FSAL, "  auth_exportpath_xdev  = %d  ",
           global_fs_info.auth_exportpath_xdev);
  LogDebug(COMPONENT_FSAL, "  xattr_access_rights = %#o ",
           global_fs_info.xattr_access_rights);

  ReturnCode(ERR_FSAL_NO_ERROR, 0);
}
Exemplo n.º 15
0
 semaphore_wrapper(int initialCount)
 {  semaphore_init(&m_sem, initialCount);  }
Exemplo n.º 16
0
void    semaphore_reset(t_semaphore *semaphore)
{
    semaphore_init(semaphore, 0);
}
Exemplo n.º 17
0
/*
 * probe function for new CPC-USB devices
 */
static int cpcusb_probe(struct usb_interface *interface,
			const struct usb_device_id *id)
{
	CPC_USB_T *card = NULL;
	CPC_CHAN_T *chan = NULL;

	struct usb_device *udev = interface_to_usbdev(interface);
	struct usb_host_interface *iface_desc;
	struct usb_endpoint_descriptor *endpoint;

	int i, j, retval = -ENOMEM, slot;

	slot = cpcusb_get_free_slot();
	if (slot < 0) {
		info("No more devices supported");
		return -ENOMEM;
	}

	/* allocate memory for our device state and initialize it */
	card = kzalloc(sizeof(CPC_USB_T), GFP_KERNEL);
	if (!card) {
		err("Out of memory");
		return -ENOMEM;
	}
	CPCUSB_Table[slot] = card;

	/* allocate and initialize the channel struct */
	card->chan = kmalloc(sizeof(CPC_CHAN_T), GFP_KERNEL);
	if (!card->chan) {
		kfree(card);
		err("Out of memory");
		return -ENOMEM;
	}

	chan = card->chan;
	memset(chan, 0, sizeof(CPC_CHAN_T));
	ResetBuffer(chan);

	semaphore_init(&card->sem);
	spin_lock_init(&card->slock);

	card->udev = udev;
	card->interface = interface;
	if (udev->descriptor.iSerialNumber) {
		usb_string(udev, udev->descriptor.iSerialNumber, card->serialNumber,
				   128);
		info("Serial %s", card->serialNumber);
	}

	card->productId = udev->descriptor.idProduct;
	info("Product %s",
	     card->productId == USB_CPCUSB_LPC2119_PRODUCT_ID ?
			 "CPC-USB/ARM7" : "CPC-USB/M16C");

	/* set up the endpoint information */
	/* check out the endpoints */
	/* use only the first bulk-in and bulk-out endpoints */
	iface_desc = &interface->altsetting[0];
	for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
		endpoint = &iface_desc->endpoint[i].desc;

		if (!card->num_intr_in &&
		    (endpoint->bEndpointAddress & USB_DIR_IN) &&
		    ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
		     == USB_ENDPOINT_XFER_INT)) {
			card->intr_in_urb = usb_alloc_urb(0, GFP_KERNEL);
			card->num_intr_in = 1;

			if (!card->intr_in_urb) {
				err("No free urbs available");
				goto error;
			}

			dbg("intr_in urb %d", card->num_intr_in);
		}

		if (!card->num_bulk_in &&
		    (endpoint->bEndpointAddress & USB_DIR_IN) &&
		    ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
		     == USB_ENDPOINT_XFER_BULK)) {
			card->num_bulk_in = 2;
			for (j = 0; j < CPC_USB_URB_CNT; j++) {
				card->urbs[j].size = endpoint->wMaxPacketSize;
				card->urbs[j].urb = usb_alloc_urb(0, GFP_KERNEL);
				if (!card->urbs[j].urb) {
					err("No free urbs available");
					goto error;
				}
				card->urbs[j].buffer =
				    usb_buffer_alloc(udev,
						     card->urbs[j].size,
						     GFP_KERNEL,
						     &card->urbs[j].urb->transfer_dma);
				if (!card->urbs[j].buffer) {
					err("Couldn't allocate bulk_in_buffer");
					goto error;
				}
			}
			info("%s - %d reading URB's allocated",
			     __func__, CPC_USB_URB_CNT);
		}

		if (!card->num_bulk_out &&
		    !(endpoint->bEndpointAddress & USB_DIR_IN) &&
		    ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
		     == USB_ENDPOINT_XFER_BULK)) {

			card->num_bulk_out = 2;

			for (j = 0; j < CPC_USB_URB_CNT; j++) {
				card->wrUrbs[j].size =
				    endpoint->wMaxPacketSize;
				card->wrUrbs[j].urb =
				    usb_alloc_urb(0, GFP_KERNEL);
				if (!card->wrUrbs[j].urb) {
					err("No free urbs available");
					goto error;
				}
				card->wrUrbs[j].buffer = usb_buffer_alloc(udev,
							       card->wrUrbs[j].size, GFP_KERNEL,
							       &card->wrUrbs[j].urb->transfer_dma);

				if (!card->wrUrbs[j].buffer) {
					err("Couldn't allocate bulk_out_buffer");
					goto error;
				}

				usb_fill_bulk_urb(card->wrUrbs[j].urb, udev,
						usb_sndbulkpipe(udev, endpoint->bEndpointAddress),
						card->wrUrbs[j].buffer,
						card->wrUrbs[j].size,
						cpcusb_write_bulk_callback,
						card);
			}

			info("%s - %d writing URB's allocated", __func__, CPC_USB_URB_CNT);
		}
	}

	if (!(card->num_bulk_in && card->num_bulk_out)) {
		err("Couldn't find both bulk-in and bulk-out endpoints");
		goto error;
	}

	/* allow device read, write and ioctl */
	card->present = 1;

	/* we can register the device now, as it is ready */
	usb_set_intfdata(interface, card);
	retval = usb_register_dev(interface, &cpcusb_class);

	if (retval) {
		/* something prevented us from registering this driver */
		err("Not able to get a minor for this device.");
		usb_set_intfdata(interface, NULL);
		goto error;
	}

	card->chan->minor = card->minor = interface->minor;

	chan->buf = vmalloc(sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT);
	if (chan->buf == NULL) {
		err("Out of memory");
		retval = -ENOMEM;
		goto error;
	}
	info("Allocated memory for %d messages (%lu kbytes)",
	     CPC_MSG_BUF_CNT, (long unsigned int)(sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT) / 1000);
	memset(chan->buf, 0, sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT);

	ResetBuffer(chan);

	card->chan->CPCWait_q = kmalloc(sizeof(wait_queue_head_t), GFP_KERNEL);
	if (!card->chan->CPCWait_q) {
		err("Out of memory");
		retval = -ENOMEM;
		goto error;
	}
	init_waitqueue_head(card->chan->CPCWait_q);

	CPCUSB_Table[slot] = card;
	card->idx = slot;
	CPCUsbCnt++;

	/* let the user know what node this device is now attached to */
	info("Device now attached to USB-%d", card->minor);
	return 0;

error:
	for (j = 0; j < CPC_USB_URB_CNT; j++) {
		if (card->urbs[j].buffer) {
			usb_buffer_free(card->udev, card->urbs[j].size,
					card->urbs[j].buffer,
					card->urbs[j].urb->transfer_dma);
			card->urbs[j].buffer = NULL;
		}
		if (card->urbs[j].urb) {
			usb_free_urb(card->urbs[j].urb);
			card->urbs[j].urb = NULL;
		}
	}

	cpcusb_delete(card);
	return retval;
}
Exemplo n.º 18
0
/*
 *  This function initializes shared variables of the fsal.
 */
fsal_status_t fsal_internal_init_global(fsal_init_info_t * fsal_info,
                                        fs_common_initinfo_t * fs_common_info)
{

  /* sanity check */
  if(!fsal_info || !fs_common_info)
    ReturnCode(ERR_FSAL_FAULT, 0);

  /* inits FS call semaphore */
  if(fsal_info->max_fs_calls > 0)
    {
      int rc;

      limit_calls = TRUE;

      rc = semaphore_init(&sem_fs_calls, fsal_info->max_fs_calls);

      if(rc != 0)
        ReturnCode(ERR_FSAL_SERVERFAULT, rc);

      LogDebug(COMPONENT_FSAL,
               "FSAL INIT: Max simultaneous calls to filesystem is limited to %u.",
               fsal_info->max_fs_calls);

    }
  else
    {
      LogDebug(COMPONENT_FSAL
               "FSAL INIT: Max simultaneous calls to filesystem is unlimited.");
    }

  /* setting default values. */
  global_fs_info = default_hpss_info;

  /* Analyzing fs_common_info struct */

  if((fs_common_info->behaviors.maxfilesize != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.maxlink != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.maxnamelen != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.maxpathlen != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.no_trunc != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.case_insensitive != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.case_preserving != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.named_attr != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.lease_time != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.supported_attrs != FSAL_INIT_FS_DEFAULT) ||
     (fs_common_info->behaviors.homogenous != FSAL_INIT_FS_DEFAULT))
    ReturnCode(ERR_FSAL_NOTSUPP, 0);

  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, symlink_support);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, link_support);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, lock_support);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, lock_support_owner);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, lock_support_async_block);
  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, cansettime);

  SET_INTEGER_PARAM(global_fs_info, fs_common_info, maxread);
  SET_INTEGER_PARAM(global_fs_info, fs_common_info, maxwrite);

  SET_BITMAP_PARAM(global_fs_info, fs_common_info, umask);

  SET_BOOLEAN_PARAM(global_fs_info, fs_common_info, auth_exportpath_xdev);

  SET_BITMAP_PARAM(global_fs_info, fs_common_info, xattr_access_rights);

  display_fsinfo(&global_fs_info);

  ReturnCode(ERR_FSAL_NO_ERROR, 0);
}
Exemplo n.º 19
0
 posix_semaphore(unsigned int initialCount)
 {  semaphore_init(&m_sem, initialCount);  }
Exemplo n.º 20
0
void KERNEL_CALL
semaphores_install(void)
{
    memsetd(gSemaphores, 0, NUM_SEMAPHORES);
    semaphore_init(KEYBOARD_SEMAPHORE, 1);
}
Exemplo n.º 21
0
 semaphore_wrapper(unsigned int initialCount)
 {  semaphore_init(&m_sem, initialCount);  }
Exemplo n.º 22
0
Arquivo: main.c Projeto: cfrost/buenos
void init(void)
{
    TID_t startup_thread;
    int numcpus;

    /* Initialize polling TTY driver for kprintf() usage. */
    polltty_init();

    kwrite("BUENOS is a University Educational Nutshell Operating System\n");
    kwrite("==========================================================\n");
    kwrite("\n");

    kwrite("Copyright (C) 2003-2006  Juha Aatrokoski, Timo Lilja,\n");
    kwrite("  Leena Salmela, Teemu Takanen, Aleksi Virtanen\n");
    kwrite("See the file COPYING for licensing details.\n");
    kwrite("\n");

    kwrite("Initializing memory allocation system\n");
    kmalloc_init();

    kwrite("Reading boot arguments\n");
    bootargs_init();

    /* Seed the random number generator. */
    if (bootargs_get("randomseed") == NULL) {
	_set_rand_seed(0);
    } else {
	int seed = atoi(bootargs_get("randomseed"));
	kprintf("Seeding pseudorandom number generator with %i\n", seed);
	_set_rand_seed(seed);
    }

    numcpus = cpustatus_count();
    kprintf("Detected %i CPUs\n", numcpus);
    KERNEL_ASSERT(numcpus <= CONFIG_MAX_CPUS);

    kwrite("Initializing interrupt handling\n");
    interrupt_init(numcpus);

    kwrite("Initializing threading system\n");
    thread_table_init();

    kwrite("Initializing user process system\n");
    process_init();

    kwrite("Initializing sleep queue\n");
    sleepq_init();

    kwrite("Initializing semaphores\n");
    semaphore_init();

    kwrite("Initializing device drivers\n");
    device_init();

    kprintf("Initializing virtual filesystem\n");
    vfs_init();

    kwrite("Initializing scheduler\n");
    scheduler_init();

    kwrite("Initializing virtual memory\n");
    vm_init();

    kprintf("Creating initialization thread\n");
    startup_thread = thread_create(&init_startup_thread, 0);
    thread_run(startup_thread);

    kprintf("Starting threading system and SMP\n");

    /* Let other CPUs run */
    kernel_bootstrap_finished = 1;
    
    _interrupt_clear_bootstrap();
    _interrupt_enable();

    /* Enter context switch, scheduler will be run automatically,
       since thread_switch() behaviour is identical to timer tick
       (thread timeslice is over). */
    thread_switch();

    /* We should never get here */
    KERNEL_PANIC("Threading system startup failed.");
}
Exemplo n.º 23
0
void lock_init(Lock *lock) {
  semaphore_init(&lock->sema, 1);
}
Exemplo n.º 24
0
int jpege_main(void *Param) {
    OMX_PARAM_PORTDEFINITIONTYPE asPortDefinition[2];
    OMX_PORT_PARAM_TYPE sImageInit;
    OMX_IMAGE_PARAM_PORTFORMATTYPE sImageParamPortformatType;
    OMX_CALLBACKTYPE sCallbacks;
    OMX_IMAGE_PARAM_QFACTORTYPE sImageParamQFacttype;
    int i = 0, j = 0;
    OMX_ERRORTYPE err = OMX_ErrorNone;
    OMX_STATETYPE state = OMX_StateMax;
    OMX_U32 nQFactor = 0;
    OMX_S8 **cName;
    OMX_U32 numComp;
    char ConfigFileName[256];
    OMX_S8 componentName[256];
    OMX_VERSIONTYPE componentVer;
    OMX_VERSIONTYPE specVer;
    OMX_UUIDTYPE componentUUID;
    void *InputPortRet, *OutputPortRet, *OutputDataRet;

    memset(asPortDefinition, 0, sizeof(asPortDefinition));
    memset(&sImageInit, 0, sizeof(sImageInit));
    memset(&sImageParamPortformatType, 0, sizeof(sImageParamPortformatType));
    memset(&sCallbacks, 0, sizeof(sCallbacks));

    output_mode = ((VIDEODECFUNCPARAMTYPE *) Param)->Mode;
    nFrameWidth = ((VIDEODECFUNCPARAMTYPE *) Param)->nFrameWidth;
    nFrameHeight = ((VIDEODECFUNCPARAMTYPE *) Param)->nFrameHeight;
    eColorFormat = ((VIDEODECFUNCPARAMTYPE *) Param)->eColorFormat;
    nQFactor = ((VIDEODECFUNCPARAMTYPE *) Param)->nQFactor;
    int ret = 0, hasHandle = 0, commandValue = 0, hasNoWait = 1; /* */

    ef = ff = 0;

    if ((frameSize = yuv_framesize(nFrameWidth, nFrameHeight, eColorFormat)) <= 0) {
        FILE_DBG1("[emxx_jpeglib][%d] yuv_init\n", __LINE__);
        return -1;
    }

    strcpy(ConfigFileName, AV_CODEC_CONFIG_FILE_NAME);

    err = OMF_SetLogMode(0x00000001);
    if (err != OMX_ErrorNone)
    {
        FILE_DBG1("[emxx_jpeglib] Can't set log mode! error code = 0x%08x\n", err);
        goto jpege_end;
    }

    err = OMF_SetConfiguration(ConfigFileName);
    if (err != OMX_ErrorNone)
    {
        FILE_DBG1("[emxx_jpeglib] Can't set configuration file! error code = 0x%08x\n", err);
        goto jpege_end;
    }

    err = OMX_Init();

    if (err != OMX_ErrorNone) {
        FILE_DBG("can't initialize OMX LIb, exit\n");
        goto jpege_end;
    }

    /* Get MC Name */
    cName = (OMX_U8 **) malloc(sizeof(OMX_U8 *));
    cName[0] = (OMX_U8 *) malloc(128 * sizeof(OMX_U8));
    numComp = 1;
    err = OMX_GetComponentsOfRole(JPEGE_ROLE, &numComp, cName);
    if (err != OMX_ErrorNone) {
        FILE_DBG1("[emxx_jpeglib] Can't get component name! error code = 0x%8x\n", err);
    } else {
        FILE_DBG1("OMF Name = %s\n", cName[0]);
    }

    /* Get Media Component handle. */
    sCallbacks.EventHandler = event_handler;
    sCallbacks.EmptyBufferDone = empty_buffer_done;
    sCallbacks.FillBufferDone = fill_buffer_done;
    err = OMX_GetHandle(&Video_hComponent, cName[0], NULL, &sCallbacks);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get handle! erro code = 0x%08x\n", __LINE__,
                err);
        free(cName[0]);
        free(cName);
        ret = -1;
        goto jpege_end;
    }
    hasHandle = 1;
    free(cName[0]);
    free(cName);

    /* GetComponentVersion */
    err = OMX_GetComponentVersion(Video_hComponent, componentName,
            &componentVer, &specVer, &componentUUID);
    if (err != OMX_ErrorNone) {
        FILE_DBG2(
                "[emxx_jpeglib][%d] Can't get component version! error code = 0x%08x\n",
                __LINE__, err);
        return -1;
    } else {
        printf("Component Version = 0x%08x\n", componentVer);
        printf("Spec      Version = 0x%08x\n", specVer);
    }

    /* Get OMX_IndexParamImageInit. */
    sImageInit.nSize = sizeof(OMX_PORT_PARAM_TYPE);
    err = OMX_GetParameter(Video_hComponent, OMX_IndexParamImageInit,
            &sImageInit);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    /* Get & Set OMX_IndexParamPortDefinition. */
    for (i = 0; i < sImageInit.nPorts; i++) {
        asPortDefinition[i].nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
        asPortDefinition[i].nPortIndex = sImageInit.nStartPortNumber + i;
        err = OMX_GetParameter(Video_hComponent, OMX_IndexParamPortDefinition,
                &asPortDefinition[i]);
        if (err != OMX_ErrorNone) {
            FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                    __LINE__, err);
            ret = -1;
            goto jpege_end;
        }

        if (i == PORT_OFFSET_INPUT) /* VPB+0 */
        {
            asPortDefinition[PORT_OFFSET_INPUT].format.image.nFrameWidth
                    = nFrameWidth;
            asPortDefinition[PORT_OFFSET_INPUT].format.image.nFrameHeight
                    = nFrameHeight;
            asPortDefinition[PORT_OFFSET_INPUT].format.image.eColorFormat
                    = eColorFormat;
            err = OMX_SetParameter(Video_hComponent,
                    OMX_IndexParamPortDefinition,
                    &asPortDefinition[PORT_OFFSET_INPUT]);
            if (err != OMX_ErrorNone) {
                extern int end_flag;
                printf(
                        "[emxx_jpeglib][%d] Can't set parameter! erro code = 0x%08x\n",
                        __LINE__, err);
                ret = -1;
                goto jpege_end;
            }
        }
    }

    nVideoPortIndex[PORT_OFFSET_INPUT]
            = asPortDefinition[PORT_OFFSET_INPUT].nPortIndex;
    nVideoPortIndex[PORT_OFFSET_OUTPUT]
            = asPortDefinition[PORT_OFFSET_OUTPUT].nPortIndex;

    VideoInputBuffNum = asPortDefinition[PORT_OFFSET_INPUT].nBufferCountActual;
    VideoOutputBuffNum
            = asPortDefinition[PORT_OFFSET_OUTPUT].nBufferCountActual;

    printf("VideoInputBuffNum, %d    VideoOutputBuffNum, %d\n", VideoInputBuffNum, VideoOutputBuffNum);
    /* Get & Set OMX_IndexParamImagePortFormat. */
    sImageParamPortformatType.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
    sImageParamPortformatType.nPortIndex = PORT_OFFSET_INPUT;
    sImageParamPortformatType.nIndex = nVideoPortIndex[PORT_OFFSET_INPUT];
    err = OMX_GetParameter(Video_hComponent, OMX_IndexParamImagePortFormat,
            &sImageParamPortformatType);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    sImageParamPortformatType.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
    sImageParamPortformatType.eColorFormat = eColorFormat;
    err = OMX_SetParameter(Video_hComponent, OMX_IndexParamImagePortFormat,
            &sImageParamPortformatType);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }
    /* Change state to OMX_StateIdle from OMX_StateLoaded. */
    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet, OMX_StateIdle,
            NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't send command! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    /* Allocate stream buffer. */
    for (i = 0; i < sImageInit.nPorts; i++) {
        for (j = 0; j < asPortDefinition[i].nBufferCountActual; j++) {
            err = OMX_AllocateBuffer(Video_hComponent, &apsVideoBuffer[i][j],
                    asPortDefinition[i].nPortIndex, NULL,
                    asPortDefinition[i].nBufferSize);
            if (err != OMX_ErrorNone) {
                FILE_DBG2(
                        "[emxx_jpeglib][%d] Can't allocate buffer! erro code = 0x%08x\n",
                        __LINE__, err);
                ret = -1;
                goto jpege_end;
            }

            FILE_DBG2("[%d][%d] allocated\n", i, j);
        }
    }

    /* Complete state transition. */
    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    semaphore_init(CODEC_VIDEO, output_mode);
#if 1 
    /* Create data input thread. */
    if (pthread_create(&VideoInputThreadId, NULL,
            (void*) jpeg_input_port_thread, NULL) != 0) {
        FILE_DBG1("[emxx_jpeglib][%d] failed pthread_create input_port_thread\n",
                __LINE__);
        ret = -1;
        goto jpege_end;
    }

    /* Create data output thread. */
    if (pthread_create(&VideoOutputThreadId, NULL,
            (void*) jpeg_output_port_thread, NULL) != 0) {
        FILE_DBG1("[emxx_jpeglib][%d] failed output_port_thread\n", __LINE__);
        ret = -1;
        goto jpege_end;
    }

    /* Create data output thread */
    if (pthread_create(&VideoOutputDataThreadId, NULL,
            (void*) jpeg_output_data_thread, NULL) != 0) {
        FILE_DBG1("[emxx_jpeglib][%d] pthread_create output_data_thread\n", __LINE__);
        ret = -1;
        goto jpege_end;
    }
#endif
    /* Change state to OMX_StateExecuting form OMX_StateIdle. */
    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet,
            OMX_StateExecuting, NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't send command! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    /* Complete state transition. */
    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    FILE_DBG("state has been changed to executing\n");
    VideoOutputPortThreadLoopFlag = 1;

    while (!ef || !ff)
    {
        printf(".");
    }

    FILE_DBG("start close OMX\n");
    hasNoWait = 0;

    VideoOutputPortThreadLoopFlag = 0;

    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet, OMX_StateIdle, NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG("can't send command\n");
        ret = -1;
        goto jpege_end;
    }

    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    /* Change state to OMX_StateLoaded from OMX_StateIdle. */
    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet,OMX_StateLoaded, NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't send command! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    FILE_DBG("changed to loaded state\n");

    /* Free buffer. */
    for (i = 0; i < sImageInit.nPorts; i++) {
        for (j = 0; j < asPortDefinition[i].nBufferCountActual; j++) {
            err = OMX_FreeBuffer(Video_hComponent,
                    asPortDefinition[i].nPortIndex, apsVideoBuffer[i][j]);
            if (err != OMX_ErrorNone) {
                FILE_DBG2("[emxx_jpeglib][%d] Can't free buffer! erro code = 0x%08x\n",
                        __LINE__, err);
                ret = -1;
                goto jpege_end;
            }
        }
    }

    /* Complete state transition. */
    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    jpege_end:
    FILE_DBG("free buffer\n");
    /* Free JPEG Media Component handle. */
    if (hasHandle) {
        err = OMX_FreeHandle(Video_hComponent);
        if (err != OMX_ErrorNone) {
            FILE_DBG2("[emxx_jpeglib][%d] Can't free handle! erro code = 0x%08x\n",
                    __LINE__, err);
            ret = -1;
        }
    }

    semaphore_deinit(CODEC_VIDEO, output_mode);
    FILE_DBG("close debug file");
    FILE_DBG_CLOSE();
    return 0;
}
Exemplo n.º 25
0
Arquivo: main.c Projeto: JanmanX/KUDOS
void init(void)
{
    TID_t startup_thread;
    int numcpus;

    /* Initialise Static Allocation */
    stalloc_init();

    /* Initialize polling TTY driver for kprintf() usage. */
    polltty_init();

    kwrite("Kudos is an educational operating system by the University of Copenhagen\n");
    kwrite("========================================================================\n");
    kwrite("Based on the Buenos operating system skeleton\n");
    kwrite("\n");

    kprintf("Copyright (C) 2003-2016  Juha Aatrokoski, Timo Lilja,\n");
    kprintf("  Leena Salmela, Teemu Takanen, Aleksi Virtanen, Philip Meulengracht,\n");
    kprintf("  Troels Henriksen, Annie Jane Pinder, Niels Gustav Westphal Serup,\n");
    kprintf("  Nicklas Warming Jacobsen, Oleksandr Shturmov.\n");
    kwrite("See the file COPYING for licensing details.\n");
    kwrite("\n");

    kwrite("Reading boot arguments\n");
    bootargs_init((void*)BOOT_ARGUMENT_AREA);

    /* Seed the random number generator. */
    if (bootargs_get("randomseed") == NULL) {
        _set_rand_seed(0);
    } else {
        int seed = atoi(bootargs_get("randomseed"));
        kprintf("Seeding pseudorandom number generator with %i\n", seed);
        _set_rand_seed(seed);
    }

    numcpus = cpustatus_count();
    kprintf("Detected %i CPUs\n", numcpus);
    KERNEL_ASSERT(numcpus <= CONFIG_MAX_CPUS);

    kwrite("Initializing interrupt handling\n");
    interrupt_init(numcpus);

    kwrite("Initializing threading system\n");
    thread_table_init();

    kwrite("Initializing sleep queue\n");
    sleepq_init();

    kwrite("Initializing semaphores\n");
    semaphore_init();

    kwrite("Initializing device drivers\n");
    device_init();

    kprintf("Initializing virtual filesystem\n");
    vfs_init();

    kwrite("Initializing scheduler\n");
    scheduler_init();

    kwrite("Initializing virtual memory\n");
    vm_init();

    kprintf("Creating initialization thread\n");
    startup_thread = thread_create(&init_startup_thread, 0);
    thread_run(startup_thread);

    kprintf("Starting threading system and SMP\n");

    /* Let other CPUs run */
    kernel_bootstrap_finished = 1;

    _interrupt_clear_bootstrap();
    _interrupt_enable();

    /* Enter context switch, scheduler will be run automatically,
       since thread_switch() behaviour is identical to timer tick
       (thread timeslice is over). */
    thread_switch();

    /* We should never get here */
    KERNEL_PANIC("Threading system startup failed.");
}
void usb_drv_init(void)
{
    logf("usb_drv_init() !!!!\n");

    if (!initialized)
    {
        int i;
        for (i = 0; i < USB_NUM_EPS; i++)
        {
            semaphore_init(&endpoints[i][0].complete, 1, 0);
            semaphore_init(&endpoints[i][1].complete, 1, 0);
        }

        initialized = true;
    }

    usb_enable_pll();

    /* we have external power, so boost cpu */
    cpu_boost(1);

    /* length regulator: normal operation */
    ascodec_write(AS3514_CVDD_DCDC3, ascodec_read(AS3514_CVDD_DCDC3) | 1<<2);

    /* AHB part */
    bitset32(&CGU_PERI, CGU_USB_CLOCK_ENABLE);

    /* reset AHB */
    CCU_SRC = CCU_SRC_USB_AHB_EN;
    CCU_SRL = CCU_SRL_MAGIC_NUMBER;
    mdelay(1);
    CCU_SRC = CCU_SRL = 0;

    USB_GPIO_CSR = USB_GPIO_TX_ENABLE_N
                 | USB_GPIO_TX_BIT_STUFF_EN
                 | USB_GPIO_XO_ON
                 | USB_GPIO_CLK_SEL10; /* 0x06180000; */

    /* bug workaround according to linux patch */
    USB_DEV_CFG = (USB_DEV_CFG & ~3) | 1; /* full speed */

    /* enable soft disconnect */
    USB_DEV_CTRL |= USB_DEV_CTRL_SOFT_DISCONN;

    usb_phy_on();
    usb_phy_suspend();
    USB_DEV_CTRL |= USB_DEV_CTRL_SOFT_DISCONN;

    /* We don't care about SVC or SOF events */
    /* Right now we don't handle suspend, so mask those too */
    USB_DEV_INTR_MASK = USB_DEV_INTR_SVC |
                        USB_DEV_INTR_SOF |
                        USB_DEV_INTR_USB_SUSPEND |
                        USB_DEV_INTR_EARLY_SUSPEND;

    USB_DEV_CFG = USB_DEV_CFG_STAT_ACK      |
                  USB_DEV_CFG_UNI_DIR       |
                  USB_DEV_CFG_PI_16BIT      |
                  USB_DEV_CFG_HS            |
                  USB_DEV_CFG_SELF_POWERED  |
                  USB_DEV_CFG_CSR_PRG       |
                  USB_DEV_CFG_PHY_ERR_DETECT;

    USB_DEV_CTRL = USB_DEV_CTRL_DESC_UPDATE  |
                   USB_DEV_CTRL_THRES_ENABLE |
                   USB_DEV_CTRL_BURST_ENABLE |
                   USB_DEV_CTRL_BLEN_8DWORDS |
                   USB_DEV_CTRL_TLEN_8THMAXSIZE;

    USB_DEV_EP_INTR_MASK &= ~((1<<0) | (1<<16));    /* ep 0 */

    reset_endpoints(1);

    /* clear pending interrupts */
    USB_DEV_EP_INTR = 0xffffffff;
    USB_DEV_INTR    = 0xffffffff;

    VIC_INT_ENABLE = INTERRUPT_USB;

    usb_phy_resume();
    USB_DEV_CTRL &= ~USB_DEV_CTRL_SOFT_DISCONN;

    USB_GPIO_CSR = USB_GPIO_TX_ENABLE_N
                 | USB_GPIO_TX_BIT_STUFF_EN
                 | USB_GPIO_XO_ON
                 | USB_GPIO_HS_INTR
                 | USB_GPIO_CLK_SEL10; /* 0x06180000; */

    tick_add_task(usb_tick);

    usb_enum_timeout = HZ; /* one second timeout for enumeration */
}
/* one time init (once per connection) - basicaly enable usb core */
void usb_drv_init(void)
{
    int ep_num;
        
    /* enable USB clock */
    SCU_CLKCFG &= ~(1<<6);
    
    /* 1. do soft disconnect */
    DEV_CTL = (1<<3); /* DEV_SELF_PWR */

    /* 2. do power on reset to PHY */
    DEV_CTL = (1<<3) | /* DEV_SELF_PWR */
              (1<<7);  /* SOFT_POR */
    
    /* 3. wait more than 10ms */
    udelay(20000);
    
    /* 4. clear SOFT_POR bit */
    DEV_CTL  &= ~(1<<7);
    
    /* 5. configure minimal EN_INT */
    EN_INT = (1<<6) |  /* Enable Suspend Interrupt */
             (1<<5) |  /* Enable Resume Interrupt */
             (1<<4) |  /* Enable USB Reset Interrupt */
             (1<<3) |  /* Enable OUT Token receive Interrupt EP0 */
             (1<<2) |  /* Enable IN Token transmits Interrupt EP0 */
             (1<<1);   /* Enable SETUP Packet Receive Interrupt */
             
    /* 6. configure INTCON */
    INTCON = (1<<2) |  /* interrupt high active */
             (1<<0);   /* enable EP0 interrupts */
    
    /* 7. configure EP0 control registers */
    TX0CON = (1<<6) |  /* Set as one to enable the EP0 tx irq */
             (1<<2);   /* Set as one to response NAK handshake */
             
    RX0CON = (1<<7) |
             (1<<4) |  /* Endpoint 0 Enable. When cleared the endpoint does
                        * not respond to an SETUP or OUT token
                        */

             (1<<3);   /* Set as one to response NAK handshake */
             
    /* 8. write final bits to DEV_CTL */
    DEV_CTL = (1<<8) | /* Configure CSR done */
              (1<<6) | /* 16-bit data path enabled. udc_clk = 30MHz */
              (1<<4) | /* Device soft connect */
              (1<<3);  /* Device self power */

    /* init semaphore of ep0 */
    semaphore_init(&ctrlep[DIR_OUT].complete, 1, 0);
    semaphore_init(&ctrlep[DIR_IN].complete, 1, 0);
    
    for (ep_num = 1; ep_num < USB_NUM_ENDPOINTS; ep_num++)
    {
        semaphore_init(&endpoints[ep_num].complete, 1, 0);
        
        if (ep_num%3 == 0) /* IIN 3, 6, 9, 12, 15 */
        {
            IIN_TXCON(ep_num) |= (ep_num<<8)|(1<<3)|(1<<2); /* ep_num, enable, NAK */
        }
        else if (ep_num%3 == 1) /* BOUT 1, 4, 7, 10, 13 */
        {
            BOUT_RXCON(ep_num) |= (ep_num<<8)|(1<<4)|(1<<3); /* ep_num, NAK, enable */
        }
        else if (ep_num%3 == 2) /* BIN 2, 5, 8, 11, 14 */
        {
            BIN_TXCON(ep_num) |= (ep_num<<8)|(1<<3)|(1<<2); /* ep_num, enable, NAK */
        }
    }
}
Exemplo n.º 28
0
int main(void) {
    char decission[50];
    int s, sem;
    packet* rec = malloc(sizeof (packet));
    if(rec == NULL){
        ERR("malloc");
    }
    packet* tmp = malloc(sizeof (packet));
    if(tmp == NULL){
        ERR("malloc");
    }
    char c;
    int x, y, points,i;
    int isAnyTileAvaliable;
    semaphore_init(&sem, 'E', 1);
    
    /* Set signals handlers */
	if(sethandler(sigint_handler,SIGINT)) ERR("Setting SIGINT:");
	if(sethandler(sigterm_handler,SIGTERM)) ERR("Setting SIGTERM:");

    /*********  TCP IP  *********/
    s = tcp_connect_socket("localhost", 2000);

    printf("##############################\n");
    printf("## WELCOME TO SCRABBLE GAME ##\n");
    printf("##############################\n");


    while (g_doWork) {
        int t;

        if ((t = tcp_socket_read_packet(s, rec)) == 0 && g_doWork==1) {
            perror("Server closed connection client\n");
            break;
        } else if (t < 0) {
            perror("recv");
            break;
        }
        switch (rec->msg) {
            case NO_PLAYER:
                printf("Waiting for another player to connect...\n");
                break;
            case PAIR_MATCH:
                printf("Player found - starting the game...\n");
                break;
            case INFO:
                printf("Player found - starting the game...\n");
                scrabble_game_print_title();
                scrabble_game_print_board(rec->currentBoard);
                scrabble_game_print_wait_for_move();
                break;
            case REQUEST_MOVE:
                /* Print points in the right order */
                scrabble_game_print_title();
                scrabble_game_print_points(rec->p1Points, rec->p2Points, rec->playerType);

                /* Print current board state */
                scrabble_game_print_board(rec->currentBoard);

                /* Print available tiles */
                printf("----------------------------------------\n              ");
                scrabble_game_print_available_tiles(rec->tiles, 5);
                printf("----------------------------------------\n");
                isAnyTileAvaliable = 0;
                for(i=0; i<5;i++){
                    if(rec->tiles[i] != 'x'){
                        isAnyTileAvaliable = 1;
                    }
                }
                if(isAnyTileAvaliable == 1) {
                    points = 0;
                    if(-1 == gather_input(&c, &x, &y, &points, rec->tiles, rec->currentBoard)) {
                        printf("gater input error\n");
                    }else {
                        /* Print updated points */
                        scrabble_game_print_title();
                        if (rec->playerType == FIRST) rec->p1Points += points;
                        if (rec->playerType == SECOND) rec->p2Points += points;
                        scrabble_game_print_points(rec->p1Points, rec->p2Points, rec->playerType);

                        /* Print updated board */
                        rec->currentBoard[x][y] = c;
                        scrabble_game_print_board(rec->currentBoard);

                        /* Send data to server. */
                        tmp->msg = MOVE_DATA;
                        tmp->letter = c;
                        tmp->x_coord = x;
                        tmp->y_coord = y;
                        tmp->p1Points = rec->p1Points;
                        tmp->p2Points = rec->p2Points;
                        tcp_socket_send_packet(s, tmp);
                        scrabble_game_print_wait_for_move();
                    }
                }
                else{
                    printf("##########################################\n");
                    printf("##             END OF MATCH             ##\n");
                    printf("##########################################\n");
                    printf("Do you want to play another game?(Y/N)\n");
                    scanf(" %c", decission);
                    printf("%s \n",decission);
                    tmp->isMatchOngoing = -1;
                    if (decission[0] == 'Y') {
                        tmp->msg = PLAY_ANOTHER_GAME;
                        tcp_socket_send_packet(s, tmp);
                    }
                    else
                    {
                        tmp->msg = FINISH_GAME;
                        printf("isMatchOngoing = %d \n", tmp->isMatchOngoing);
                        tcp_socket_send_packet(s, tmp);
                        return EXIT_SUCCESS;
                    }
                }
                break;
            case DISCONNECTED:

                printf("##########################################\n");
                printf("##            Connection lost!          ##\n");
                printf("##########################################\n");
                printf("Sorry but connection with other player is\n");
                printf("lost. Do you want to play another game?(Y/N)\n");
                scanf(" %c", decission);
                printf("%s \n",decission);
                if (decission[0] == 'Y') {
                    tmp->msg = PLAY_ANOTHER_GAME;
                    tcp_socket_send_packet(s, tmp);
                } 
                else 
                {
                    tmp->msg = FINISH_GAME;
                    tcp_socket_send_packet(s, tmp);
                    return EXIT_SUCCESS;
                }
                break;
                
            case EXIT:
                printf("Server disconnected.\n");
                return EXIT_SUCCESS;
            default:
                printf("Cannot interpret packet's message: %d \n", rec->msg);
        }
    };
    printf("Disconnected\n");
    if(-1 == close(s)){
        ERR("close");
    }
    return 0;
}
Exemplo n.º 29
0
void drd_semaphore_init(const Addr semaphore,
                        const Word pshared, const Word value)
{
  semaphore_init(semaphore, pshared, value);
}
Exemplo n.º 30
0
void usb_drv_init(void)
{
    for (int i = 0; i < USB_NUM_ENDPOINTS; i++)
        for (int dir = 0; dir < 2; dir++)
            semaphore_init(&endpoints[i][dir].complete, 1, 0);

    bitset32(&CGU_PERI, CGU_USB_CLOCK_ENABLE);
    CCU_USB = (CCU_USB & ~(3<<24)) | (1 << 24); /* ?? */
    /* PHY clock */
    CGU_USB = 1<<5  /* enable */
        | 0 << 2
        | 0; /* source = ? (24MHz crystal?) */

    PCGCCTL = 0;
    DCTL = DCTL_pwronprgdone | DCTL_sftdiscon;

    GRSTCTL = GRSTCTL_csftrst;
    while (GRSTCTL & GRSTCTL_csftrst);  /* Wait for OTG to ack reset */
    while (!(GRSTCTL & GRSTCTL_ahbidle));  /* Wait for OTG AHB master idle */

    GRXFSIZ = 512;
    GNPTXFSIZ = MAKE_FIFOSIZE_DATA(512);

    /* FIXME: the current code is for internal DMA only, the clip+ architecture
     *        defines the internal DMA model */
    GAHBCFG = (GAHBCFG_INT_DMA_BURST_INCR << GAHBCFG_hburstlen_bitp)
                | GAHBCFG_dma_enable | GAHBCFG_glblintrmsk;

    /* Select UTMI+ 16 */
    GUSBCFG = GUSBCFG_force_device_mode | GUSBCFG_phy_if | 7 << GUSBCFG_toutcal_bitp;

    /* Do something that is probably CCU related but undocumented*/
    CCU_USB |= 0x1000;
    CCU_USB &= ~0x300000;

    DCFG = DCFG_nzstsouthshk | DCFG_devspd_hs_phy_hs; /* Address 0, high speed */
    DCTL = DCTL_pwronprgdone;

    /* Check hardware capabilities */
    if(extract(GHWCFG2, arch) != GHWCFG2_ARCH_INTERNAL_DMA)
        panicf("usb-drv: wrong architecture (%ld)", extract(GHWCFG2, arch));
    if(extract(GHWCFG2, hs_phy_type) != GHWCFG2_PHY_TYPE_UTMI)
        panicf("usb-drv: wrong HS phy type (%ld)", extract(GHWCFG2, hs_phy_type));
    if(extract(GHWCFG2, fs_phy_type) != GHWCFG2_PHY_TYPE_UNSUPPORTED)
        panicf("usb-drv: wrong FS phy type (%ld)", extract(GHWCFG2, fs_phy_type));
    if(extract(GHWCFG4, utmi_phy_data_width) != 0x2)
        panicf("usb-drv: wrong utmi data width (%ld)", extract(GHWCFG4, utmi_phy_data_width));
    if(!(GHWCFG4 & GHWCFG4_ded_fifo_en)) /* it seems to be multiple tx fifo support */
        panicf("usb-drv: no multiple tx fifo");

    if(USB_NUM_ENDPOINTS != extract(GHWCFG2, num_ep))
        panicf("usb-drv: wrong endpoint number");

    for (int dir = 0; dir < 2; dir++)
        for (unsigned i = 0; i < num_eps(dir == DIR_OUT); i++)
        {
            int ep = ((dir == DIR_IN) ? in_ep_list : out_ep_list)[i];
            int type = (GHWCFG1 >> GHWCFG1_epdir_bitp(ep)) & GHWCFG1_epdir_bits;
            int flag = (dir == DIR_IN) ? GHWCFG1_EPDIR_IN : GHWCFG1_EPDIR_OUT;
            if(type != GHWCFG1_EPDIR_BIDIR && type != flag)
                panicf("usb-drv: EP%d not in correct direction", ep);
        }

    DOEPMSK = DEPINT_xfercompl | DEPINT_ahberr | DOEPINT_setup;
    DIEPMSK = DEPINT_xfercompl | DEPINT_ahberr | DIEPINT_timeout;
    DAINTMSK = 0xffffffff;

    reset_endpoints();

    GINTMSK = GINTMSK_usbreset
            | GINTMSK_enumdone
            | GINTMSK_inepintr
            | GINTMSK_outepintr
            | GINTMSK_disconnect;

    VIC_INT_ENABLE = INTERRUPT_USB;
}