static l2c_slot_t* alloc_l2c_slot(const bt_bdaddr_t *addr, const char* name, const uint8_t* uuid, int channel, int flags, BOOLEAN server)
{
    int security = 0;
    if(flags & BTSOCK_FLAG_ENCRYPT)
        security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
    if(flags & BTSOCK_FLAG_AUTH) {
        security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;
    }
    l2c_slot_t* ls = find_free_slot();
    if(ls)
    {
        int fds[2] = {-1, -1};
        if(socketpair(AF_LOCAL, SOCK_STREAM, 0, fds))
        {
            APPL_TRACE_ERROR("socketpair failed, errno:%d", errno);
            return NULL;
        }
        ls->fd = fds[0];
        ls->app_fd = fds[1];

        APPL_TRACE_DEBUG("alloc_l2c_slot fd %d and app fd  %d is_server %d", ls->fd, ls->app_fd, server);
        ls->security = security;
        ls->psm = channel;
        if(uuid)
            memcpy(ls->service_uuid, uuid, sizeof(ls->service_uuid));
        else memset(ls->service_uuid, 0, sizeof(ls->service_uuid));
        if(name && *name)
            strlcpy(ls->service_name, name, sizeof(ls->service_name) -1);
        if(addr)
            ls->addr = *addr;
        ls->in_use = TRUE;
        ls->f.server = server;
    }
    return ls;
}
Example #2
0
File: block.c Project: ejrh/ejrh
BLOCK *clone_block(FS *fs, BLOCK *block)
{
    BLOCK *clone;
    
    if (block->pins == 0 && !(block->flags & F_DIRTY))
    {
        set_flag(block, F_CLONE);
        remove_block_from_hash(fs, block);
        return block;
    }
    
    clone = find_free_slot(fs);
    memcpy(clone->buffer, block->buffer, fs->block_size);
    set_flag(clone, F_CACHED);
    set_flag(clone, F_CLONE);
    clone->type = block->type;
    clone->location = block->location;
    if (block->type != B_DATA)
    {
        if (!parse_block(fs, clone))
        {
            printf("Error parsing cloned block %ld\n", block->location);
            return NULL;
        }
    }
    
    return clone;
}
Example #3
0
void do_cache_set(void) {
  struct string *key = string_create();
  read_into_string(key);

  struct cache_entry *entry = cache_lookup(key);
  if (entry == NULL) {
    // There's no existing entry for this key. Find a free slot to put
    // a new entry in.
    entry = find_free_slot();
  }

  if (entry == NULL) {
    // No free slots, tell the client the cache is full :-(
    write(STDOUT_FILENO, &kCacheFull, sizeof(kCacheFull));
    return;
  }

  write(STDOUT_FILENO, &kFound, sizeof(kFound));

  entry->key = key;

  if (entry->value == NULL) {
    entry->value = string_create();
  }

  read_into_string(entry->value);
  entry->lifetime = read_int();
}
Example #4
0
static int detector_add_scan(MSFilter *f, void *arg){
	DetectorState *s=(DetectorState *)f->data;
	MSToneDetectorDef *def=(MSToneDetectorDef*)arg;
	int i=find_free_slot(s);
	if (i!=-1){
		s->tone_def[i]=*def;
		s->nscans++;
		goertzel_state_init(&s->tone_gs[i],def->frequency,s->rate);
		return 0;
	}
	return -1;
}
Example #5
0
void
XboxdrvDaemon::launch_controller_thread(udev_device* udev_dev,
                                        const XPadDevice& dev_type, 
                                        uint8_t busnum, uint8_t devnum)
{
  // FIXME: results must be libusb_unref_device()'ed
  libusb_device* dev = usb_find_device_by_path(busnum, devnum);

  if (!dev)
  {
    log_error("USB device disappeared before it could be opened");
  }
  else
  {
    std::vector<ControllerPtr> controllers = ControllerFactory::create_multiple(dev_type, dev, m_opts);
    for(std::vector<ControllerPtr>::iterator i = controllers.begin();
        i != controllers.end(); 
        ++i)
    {
      ControllerPtr& controller = *i;

      controller->set_disconnect_cb(boost::bind(&g_idle_add, &XboxdrvDaemon::on_controller_disconnect_wrap, this));
      controller->set_activation_cb(boost::bind(&g_idle_add, &XboxdrvDaemon::on_controller_activate_wrap, this));

      // FIXME: Little dirty hack
      controller->set_udev_device(udev_dev);

      if (controller->is_active())
      {
        // controller is active, so launch a thread if we have a free slot
        ControllerSlotPtr slot = find_free_slot(udev_dev);
        if (!slot)
        {
          log_error("no free controller slot found, controller will be ignored: "
                    << boost::format("%03d:%03d %04x:%04x '%s'")
                    % static_cast<int>(busnum)
                    % static_cast<int>(devnum)
                    % dev_type.idVendor
                    % dev_type.idProduct
                    % dev_type.name);
        }
        else
        {
          connect(slot, controller);
        }
      }
      else // if (!controller->is_active())
      {
        m_inactive_controllers.push_back(controller);
      }
    }
  }
}
Example #6
0
int handle_new_client(struct client_data* msg, struct client_data* ss, int sockfd){
	if(next_fid>MAX_CLIENTS){
		printf("next client_id(%d > max_clients(%d)\n", next_fid, MAX_CLIENTS);
		return -1;
	}
	printf("recieved new client request. addr=%s\n", inet_ntoa(msg->destaddr.sin_addr));
	msg->client_id = next_fid;
	memcpy(&ss[next_fid], msg, sizeof(struct client_data));	
	printf("assigned client id=%d ", ss[next_fid].client_id);
	next_fid = find_free_slot(ss);
	printf("and set next_fid=%d\n", next_fid);
	return 0;
}
// returns the number of slot to be used or -1 if there are no free slots
int
tres_mem_arch_pf_store_start(void)
{
  int id;

  DBG_PRINTF("tres_mem_arch_pf_store_start()\n");
  id = find_free_slot();
  if(id >= 0) {
    clear_slot(id);
    cur[id] = SLOT_START_ADDR(id);
    used[id] = 1;
  }
  return id;
}
Example #8
0
void
XboxdrvDaemon::on_controller_activate()
{
  //log_tmp("on_controller_activate");
   
  // check for inactive controller and free the slots
  for(ControllerSlots::iterator i = m_controller_slots.begin(); i != m_controller_slots.end(); ++i)
  {
    // if a slot contains an inactive controller, disconnect it and save
    // the controller for later when it might be active again
    if ((*i)->get_controller() && !(*i)->get_controller()->is_active())
    {
      ControllerPtr controller = disconnect(*i);
      m_inactive_controllers.push_back(controller);
    }
  }

  // check for activated controller and connect them to a slot
  for(Controllers::iterator i = m_inactive_controllers.begin(); i != m_inactive_controllers.end(); ++i)
  {
    if (!*i)
    {
      log_error("NULL in m_inactive_controllers, shouldn't happen");
    }
    else
    {
      if ((*i)->is_active())
      {
        ControllerSlotPtr slot = find_free_slot((*i)->get_udev_device());
        if (!slot)
        {
          log_info("couldn't find a free slot for activated controller");
        }
        else
        {
          connect(slot, *i);

          // successfully connected the controller, so set it to NULL and cleanup later
          *i = ControllerPtr();
        }
      }
    }
  }

  // cleanup inactive controller
  m_inactive_controllers.erase(std::remove(m_inactive_controllers.begin(), m_inactive_controllers.end(),
                                           ControllerPtr()),
                               m_inactive_controllers.end());
}
Example #9
0
static rfc_slot_t *alloc_rfc_slot(const bt_bdaddr_t *addr, const char *name, const uint8_t *uuid, int channel, int flags, bool server) {
  int security = 0;
  if(flags & BTSOCK_FLAG_ENCRYPT)
      security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
  if(flags & BTSOCK_FLAG_AUTH)
      security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;

  rfc_slot_t *slot = find_free_slot();
  if (!slot) {
    LOG_ERROR(LOG_TAG, "%s unable to find free RFCOMM slot.", __func__);
    return NULL;
  }

  int fds[2] = { INVALID_FD, INVALID_FD };
  if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) == -1) {
    LOG_ERROR(LOG_TAG, "%s error creating socketpair: %s", __func__, strerror(errno));
    return NULL;
  }

  // Increment slot id and make sure we don't use id=0.
  if (++rfc_slot_id == 0)
    rfc_slot_id = 1;

  slot->fd = fds[0];
  slot->app_fd = fds[1];
  slot->security = security;
  slot->scn = channel;

  if(!is_uuid_empty(uuid)) {
    memcpy(slot->service_uuid, uuid, sizeof(slot->service_uuid));
    slot->is_service_uuid_valid = true;
  } else {
    memset(slot->service_uuid, 0, sizeof(slot->service_uuid));
    slot->is_service_uuid_valid = false;
  }
  if(name && *name) {
    strlcpy(slot->service_name, name, sizeof(slot->service_name));
  } else {
    memset(slot->service_name, 0, sizeof(slot->service_name));
  }
  if (addr)
    slot->addr = *addr;

  slot->id = rfc_slot_id;
  slot->f.server = server;

  return slot;
}
Example #10
0
File: block.c Project: ejrh/ejrh
static BLOCK *read_block(FS *fs, int location, int parse)
{
    size_t nr;
    BLOCK *block = find_free_slot(fs);
    //printf("R %d %p, %d\n", location, fs->f, fileno(fs->f));
    if (fseek(fs->f, location * fs->block_size, SEEK_SET))
        error("Error seeking for reading block %d", location);
    
    nr = fread(block->buffer, fs->block_size, 1, fs->f);
    if (nr < 1)
    {
        clear_flag(block, F_CACHED);
        if (location != 0)
            printf("Error reading block %d, nr = %d, errno was %d\n", location, nr, errno);
        return NULL;
    }
    block->location = location;
    set_flag(block, F_CACHED);
    block->type = B_DATA;
    block->pins = 0;
    
    if (parse)
    {
        if (!parse_block(fs, block))
        {
            printf("Error parsing block %d\n", location);
            return NULL;
        }
    }
    
    if (is_watched(block->location))
    {
        printf("READ ");
        print_block(fs, block);
    }
    add_block_to_hash(fs, block);

    return block;
}
static rfc_slot_t* alloc_rfc_slot(const bt_bdaddr_t *addr, const char* name, const uint8_t* uuid, int channel, int flags, BOOLEAN server)
{
    int security = 0;
    if(flags & BTSOCK_FLAG_ENCRYPT)
        security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT;
    if(flags & BTSOCK_FLAG_AUTH)
        security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE;

    rfc_slot_t* rs = find_free_slot();
    if(rs)
    {
        int fds[2] = {-1, -1};
        if(socketpair(AF_LOCAL, SOCK_STREAM, 0, fds))
        {
            APPL_TRACE_ERROR1("socketpair failed, errno:%d", errno);
            return NULL;
        }
        rs->fd = fds[0];
        rs->app_fd = fds[1];
        rs->security = security;
        rs->scn = channel;
        if(uuid)
            memcpy(rs->service_uuid, uuid, sizeof(rs->service_uuid));
        else memset(rs->service_uuid, 0, sizeof(rs->service_uuid));
        if(name && *name)
            strncpy(rs->service_name, name, sizeof(rs->service_name) -1);
        if(addr)
            rs->addr = *addr;
        ++rfc_slot_id;
        if(rfc_slot_id == 0)
            rfc_slot_id = 1; //skip 0 when wrapped
        rs->id = rfc_slot_id;
        rs->f.server = server;
    }
    return rs;
}
Example #12
0
File: block.c Project: ejrh/ejrh
BLOCK *allocate_block(FS *fs, BLOCK_TYPE type, LOCATION target)
{
    BLOCK *block;
    LOCATION addr;
    
    if (type != B_SUPER)
        addr = bitmap_search(fs, target);
    else
        addr = 0;

    if (addr != 0)
    {
        struct superblock_header *sbh;

        block = get_block(fs, addr, 0);
        sbh = (struct superblock_header *) fs->superblock->buffer;
        sbh->block_counts[B_FREE]--;
        if (!block)
            error("Error reusing free block!\n");
        remove_block_from_hash(fs, block);
    }
    else
    {
        block = find_free_slot(fs);
        if (!block)
            error("Error allocating block, cache is full!\n");
        
        addr = fs->num_blocks;
        fs->num_blocks++;
    }
    
    memset(block->buffer, 0, fs->block_size);
    set_flag(block, F_CACHED);
    set_flag(block, F_DIRTY);
    block->location = addr;
    block->type = type;
    block->pins = 0;
    
    if (block->type != B_DATA)
    {
        struct block_header *h = (struct block_header *) block->buffer;
        h->version = 1;
        h->location = addr;
        h->type = type;
    }
    
    if (block->type == B_TREE)
    {
        struct tree_block_header *h = (struct tree_block_header *) block->buffer;
        h->height = 0;
        h->num_keys = 0;
        h->string_size = 0;
    }
    
    if (block->type == B_SUPER)
    {
        struct superblock_header *sbh = (struct superblock_header *) block->buffer;
        sbh->block_counts[B_SUPER] = 1;
        fs->max_bitmap_pointers = (fs->block_size - sizeof (struct superblock_header)) / sizeof (unsigned long int);
        fs->num_bitmap_pointers = 0;
        fs->bitmap_size = (fs->block_size - sizeof (struct superblock_header)) * 8;
        fs->bitmaps = (unsigned long int *) (block->buffer + sizeof(struct superblock_header));
        fs->superblock = block;
    }
    else
    {
        struct superblock_header *sbh = (struct superblock_header *) fs->superblock->buffer;
        sbh->block_counts[block->type]++;
    }
    
    flush_block(fs, block);
    set_flag(block, F_CACHED);
    set_flag(block, F_DIRTY);
    add_block_to_hash(fs, block);
    
    if (block->type != B_BITMAP)
        bitmap_set(fs, addr, 1);
    
    //printf("Allocated block %d, type %d\n", block->location, block->type);
    return block;
}
Example #13
0
//-----------------------------------------
// eCos HW scheduling thread
//-----------------------------------------
void reconos_hw_scheduler(cyg_addrword_t data) {

    cyg_bool_t retval;
    rthread_attr_t *t_r;            // thread to reconfigure
    rthread_attr_t *t_y;            // yielding thread
    reconos_slot_t *s_f;            // free slot
    reconos_bitstream_t *t_r_bit;   // bitstream for t_r in s_f
#ifdef UPBFUN_RECONOS_CHECK_HWTHREAD_SIGNATURE
    uint32 signature;               // hardware thread signature
    volatile int z;                 // counter to delay DCR access
#endif

#ifdef UPBDBG_RECONOS_DEBUG
    diag_printf("hw_sched: created\n");
#endif

    // loop forever
    for (;;) {  
        // wait for signal (reschedule request)
        retval = cyg_semaphore_wait( &reconos_hwsched_semaphore );
        CYG_ASSERT(retval, "cyg_semaphore_wait returned false");

#ifdef UPBDBG_RECONOS_DEBUG
        diag_printf("hw_sched: wakeup\n");
#endif

        // lock scheduling mutex
        if (!cyg_mutex_lock(&reconos_hwsched_mutex)) {
            CYG_FAIL("mutex lock failed, aborting thread\n");
        } else {

#ifdef UPBDBG_RECONOS_DEBUG
            {
                int i;
                for (i = 0; i < NUM_OSIFS; i++) {
                    dump_slot( &reconos_slots[i] );
                }
            }
#endif
            // find thread t_r that wants to run (FIXME: no priorities or
            // queuing!)
            t_r = reconos_hwthread_list;
            while ( t_r != NULL && ((t_r->flags & RTHREAD_ATTR_RECONFIGURE) == 0) ) {
                t_r = t_r->next;
            }
            if (t_r == NULL) {
                // no hw threads to reconfigure, nothing to do
#ifdef UPBDBG_RECONOS_DEBUG
                diag_printf("hw_sched: no threads to reconfigure\n");
#endif
                // clear all yield requests!
                while (num_global_yield_requests) {
                    pop_yield_request();
                }
            } else {
#ifdef UPBDBG_RECONOS_DEBUG
                diag_printf("hw_sched: found thread @ 0x%08X to reconfigure\n", (uint32)t_r);
#endif

                CYG_ASSERT( t_r->flags & RTHREAD_ATTR_IS_DYNAMIC, "trying to load a static thread" );

                // find free slot s_f
                s_f = find_free_slot( t_r );

                if ( s_f == NULL ) { // no free slot
                    // try to find thread that yields in a slot we have a
                    // bitstream for
#ifdef UPBDBG_RECONOS_DEBUG
                    diag_printf("hw_sched: no free slots\n");
#endif
                    t_y = reconos_hwthread_list;
                    while ( t_y != NULL &&
                            ( ( (t_y->flags & RTHREAD_ATTR_YIELDS ) == 0) || ( get_bit_for_slot( t_r, t_y->slot ) == NULL ) )
                          ) {
                        t_y = t_y->next;
                    }
                    if (t_y == NULL) {  // no yielding thread
#ifdef UPBDBG_RECONOS_DEBUG
                        diag_printf("hw_sched: no yielding threads, sending yield requests to slots\n");
#endif
                        // ask all slots to yield 
                        // FIXME: this will also ask slots that t_r possibly
                        // doesn't have a bitstream for
                        push_yield_request();
                    } else { // if found
                        CYG_ASSERT( t_y->flags & RTHREAD_ATTR_IS_DYNAMIC, "trying to replace a static thread" );
                        CYG_ASSERT( t_y->slot, "trying to replace a not-resident thread" );
#ifdef UPBDBG_RECONOS_DEBUG
                        diag_printf("hw_sched: found yielding thread @ 0x%08X in slot %d\n", (uint32)t_y, t_y->slot->num);
#endif
                        // use t_y's slot as s_f
                        s_f = t_y->slot;
                        // clear yield flag of t_y
                        t_y->flags = t_y->flags & ~RTHREAD_ATTR_YIELDS;
                        // remove t_y from s_f
                        s_f->thread = NULL;
                        t_y->slot = NULL;
                        s_f->state = FREE;
                    }
                } else {
#ifdef UPBDBG_RECONOS_DEBUG
                    diag_printf("hw_sched: found free slot %d\n", s_f->num);
#endif
                }

                if ( s_f != NULL) {     // if we found a free slot
                    // one way or the other

                    // get bitstream for t_r in s_f
                    t_r_bit = get_bit_for_slot( t_r, s_f );

                    CYG_ASSERT( t_r_bit, "no bitstream" );
                    CYG_ASSERT( s_f->state == FREE || s_f->thread->flags & RTHREAD_ATTR_IS_DYNAMIC, "slot not free or present thread is static" );

#ifdef UPBDBG_RECONOS_DEBUG
                    diag_printf("hw_sched: configuring thread @ 0x%08X into slot %d using bitstream '%s'\n", (uint32)t_r, s_f->num, t_r_bit->filename);
#endif

                    // configure t_r into s_f
                    // NOTE: we don't need to synchronize this with the
                    // slot's mutex, since the slot is yielding and will
                    // not perform any hardware operations while the
                    // scheduling mutex is locked
                    // disable bus macros (just in case)
                    osif_set_busmacro(s_f, OSIF_DATA_BUSMACRO_DISABLE);
#ifdef UPBHWR_VIRTEX4_ICAP
                    icap_load( t_r_bit->data, t_r_bit->size );
#endif
#ifdef UPBFUN_RECONOS_ECAP_NET
					ecap_load( t_r_bit );
#endif
#ifdef UPBFUN_RECONOS_CHECK_HWTHREAD_SIGNATURE
					// reset thread, enable busmacros, reset again (to 
					// retrieve signature), read signature, and disable
					// busmacros
					osif_reset( s_f );
                    cyg_thread_delay(1);
					osif_set_busmacro(s_f, OSIF_DATA_BUSMACRO_ENABLE);
                    // cyg_thread_delay(1);
					osif_reset( s_f );
                    cyg_thread_delay(1);
					osif_read_hwthread_signature(s_f, &signature);
                    // cyg_thread_delay(1);
                    // osif_set_busmacro(s_f, OSIF_DATA_BUSMACRO_DISABLE);
                    // cyg_thread_delay(1);
#ifdef UPBDBG_RECONOS_DEBUG
					diag_printf("hw_sched: read signature: 0x%08X, expected: 0x%08X.\n", signature, t_r->circuit->signature);
#endif
					// check whether the signatures match
					CYG_ASSERT(signature == t_r->circuit->signature, "hwthread signatures don't match");
#endif
                    // assign thread to slot and set slot state to READY
                    s_f->thread = t_r;
                    t_r->slot = s_f;
                    s_f->state = READY;
                    // clear t_r's RECONFIGURE bit
                    t_r->flags = t_r->flags & ~RTHREAD_ATTR_RECONFIGURE;
                    // wake any threads waiting for a scheduling change
                    cyg_cond_broadcast( &reconos_hwsched_condvar );
                    // clear one yield request
                    pop_yield_request();
                }
            }

#ifdef UPBDBG_RECONOS_DEBUG
            diag_printf("hw_sched: done\n");
#endif
            // unlock scheduling mutex
            cyg_mutex_unlock(&reconos_hwsched_mutex);

        }   // if (mutex_lock)

    } // for (;;)
}    
void d3d_batch_string(int sx, int sy, char *s, int bw, int bh, float u_scale, float v_scale, uint color)
{
	int spacing = 0;
	int width;

	int x = sx;
	int y = sy;

	// centered
	x =(sx==0x8000) ? get_centered_x(s) : sx;

  	do
	{
	HRESULT hr;
	int magic_num, magic_num2;
	int len = strlen_magic(s, magic_num, magic_num2);
	int new_id = -1;

	if(len == 0) return;

	// Set to 0 to turn off batching to gfx card memory
#if 1
	// Check the string is of a valid size
	if(len > MIN_STRING_LEN && len < MAX_LG_STR_LEN)
	{
		bool long_str = (len >= MAX_SM_STR_LEN);

		int index = find_string(len, magic_num, magic_num2, sx, sy, color, long_str);
		
		// We have found the string, render and mark as rendered
		if(index != -1)
		{
			StringBatch *array = (long_str) ? long_str_array : small_str_array; 

			extern VertexTypeInfo vertex_types[D3DVT_MAX];

			d3d_SetVertexShader(FONT_VTYPE);
			hr = GlobalD3DVars::lpD3DDevice->SetStreamSource(
				0, array[index].vbuffer, vertex_types[FONT_VTYPE].size);
			
			Assert(SUCCEEDED(hr));
			hr = GlobalD3DVars::lpD3DDevice->DrawPrimitive(
				D3DPT_TRIANGLELIST, 0, array[index].char_count * 2);

   //			Assert(SUCCEEDED(hr));

			array[index].used_this_frame = true;
			return;

		// Prepare to enter the string
		} else {
			new_id = find_free_slot(long_str);
		}
	}
#endif

	IDirect3DVertexBuffer8 *vbuffer = NULL;	
	FONT_VERTEX *locked_buffer = NULL;
	StringBatch *array = NULL;

	if(new_id != -1) {

		array = (len > MAX_SM_STR_LEN) ? long_str_array : small_str_array; 
		vbuffer = array[new_id].vbuffer;
		hr = vbuffer->Lock(0, len * 6 * vertex_types[FONT_VTYPE].size, (BYTE **) &locked_buffer, 0);
		
		array[new_id].used_this_frame = true;
		// We can always bail out at this point
		if(FAILED(hr)) {
			Assert(0);
			new_id = -1;
		} 
	}

	int char_count = 0;

	while (*s)	{
		x += spacing;

		while (*s== '\n' )	{
			s++;
			y += Current_font->h;
			// centered
			x =(sx==0x8000) ? get_centered_x(s) : sx;
		}
		if (*s == 0 ) break;

		int letter = get_char_width(s[0],s[1],&width,&spacing);
		s++;

		//not in font, draw as space
		if (letter<0)	{
			continue;
		}

		int xd, yd, xc, yc;
		int wc, hc;

		// Check if this character is totally clipped
		if ( x + width < gr_screen.clip_left ) continue;
		if ( y + Current_font->h < gr_screen.clip_top ) continue;
		if ( x > gr_screen.clip_right ) continue;
		if ( y > gr_screen.clip_bottom ) continue;

		xd = yd = 0;
		if ( x < gr_screen.clip_left ) xd = gr_screen.clip_left - x;
		if ( y < gr_screen.clip_top ) yd = gr_screen.clip_top - y;
		xc = x+xd;
		yc = y+yd;

		wc = width - xd; hc = Current_font->h - yd;
		if ( xc + wc > gr_screen.clip_right ) wc = gr_screen.clip_right - xc;
		if ( yc + hc > gr_screen.clip_bottom ) hc = gr_screen.clip_bottom - yc;

		if ( wc < 1 ) continue;
		if ( hc < 1 ) continue;

		font_char *ch;
	
		ch = &Current_font->char_data[letter];

		int u = Current_font->bm_u[letter];
		int v = Current_font->bm_v[letter];

		if ( wc < 1 ) continue;
		if ( hc < 1 ) continue;

		FONT_VERTEX *src_v = NULL;

		if(new_id != -1) {
			src_v = &locked_buffer[char_count * 6];
		} else {
			src_v = &d3d_verts[char_count * 6];
		}

#if 0
		// Change the color this way to see which strings are being cached
	  	uint color2 = (new_id == -1) ? color : 0xff00ff00;

		// Marks the end of a batch blue
	  	if(char_count > (MAX_STRING_LEN - 10)) 
	  		color2 = 0xff0000ff;
#endif

	 	d3d_stuff_char(src_v, xc, yc, wc, hc, u+xd, v+yd, bw, bh, u_scale, v_scale, color);

		char_count++;
		if(char_count >= MAX_STRING_LEN) {
			// We've run out of space, we are going to have to go round again
			break;
		}
	}

	if(new_id != -1) {
		vbuffer->Unlock();

		if(char_count == 0) {
			array[new_id].free_slot		  = true;
			array[new_id].used_this_frame = false;
			continue;
		}

		hr = d3d_SetVertexShader(FONT_VTYPE);
		Assert(SUCCEEDED(hr));
		hr = GlobalD3DVars::lpD3DDevice->SetStreamSource(0, vbuffer, vertex_types[FONT_VTYPE].size); 
		Assert(SUCCEEDED(hr));

  		hr = GlobalD3DVars::lpD3DDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, char_count * 2);
//  		Assert(SUCCEEDED(hr));

		// Fill in details
		array[new_id].char_count   = char_count;
		array[new_id].color        = color;
		array[new_id].free_slot    = false;
		array[new_id].len		   = len;
		array[new_id].magic_number = magic_num;
		array[new_id].magic_number2 = magic_num2;
		array[new_id].x			   = sx;
		array[new_id].y			   = sy;
		array[new_id].offsetx      = gr_screen.offset_x; 
		array[new_id].offsety      = gr_screen.offset_y; 

		array[new_id].used_this_frame = true;

	} else if(char_count > 0) {
  	   	d3d_DrawPrimitive(FONT_VTYPE, D3DPT_TRIANGLELIST,(LPVOID)d3d_verts, char_count * 6);
	}

	} while (*s);
}
Example #15
0
int main(void)
{
    int sd, newSd;              //Socket descriptors sd is the one main listens on newSd is the one clients gets.
    struct sockaddr_in cliAddr; //Information about the client
    socklen_t cliLen;           //
    char buffer[32];

    pthread_t server_db_print;  //Debug print thread information
    pthread_t bullet_hit;
    struct client clientInfo[MAX_PLAYERS];  // Where all necessary information about the client is stored
    
    int clientSlot;             // Stores in slot the new connection is going to get 
    
    int i;
    
    load_map_collision_array();
    
    // Init tcp
    sd = tcp_init();
    if (sd == -1)
    {
        return ERROR;           // Exits if error
    }

    //Cleares the Clients structs and makes it ready for use.
    for (i = 0; i < MAX_PLAYERS; i++)
    {
        clear_client_struct(&clientInfo[i]);
    }
    redpoints = 0;
    bluepoints = 0;
    
    //Starts the debug print thread
    pthread_create(&server_db_print,NULL,debeugger_print_thread,clientInfo);
    
    pthread_create(&bullet_hit,NULL,bullet_hit_thread,clientInfo);

    
    while (1)
    {
        cliLen = sizeof(cliAddr);
        newSd = accept(sd, (struct sockaddr *) &cliAddr, &cliLen);
        
        if (newSd == -1)
        {
            perror("accept");
            continue;
        }
        
        //Finds the first free slot
        clientSlot = find_free_slot(clientInfo, MAX_PLAYERS);
                
        if(clientSlot==-1)
        {
            send(newSd,"No free slots, try again later!\n", sizeof("No free slots, try again later!\n"), 0);
            close(newSd); // Close the socket descriptor to indicate to client that
            continue;     // we have no more space for it. Then goto beginning of loop.
        }
        
        clientInfo[clientSlot].free = 1;            // Sets the client slot so it is taken
        clientInfo[clientSlot].sd = newSd;          // Gives the slot the socket descriptor
        clientInfo[clientSlot].mySlot = clientSlot; // Gives the Slot number 
        clientInfo[clientSlot].team = find_team(clientInfo, MAX_PLAYERS);  //Finds a team and givs in to the client
        
        // Gets the clients ip address and stores it
        inet_ntop(cliAddr.sin_family, &cliAddr.sin_addr, clientInfo[clientSlot].client_ip_addr, sizeof (clientInfo[clientSlot].client_ip_addr));
        
        sprintf(buffer, "%d", clientSlot);
        send(newSd, buffer, sizeof(buffer), 0);
        
        //Main thread for the connected client, Main programm will continue serv new connections
        pthread_create( &clientInfo[clientSlot].threadId, NULL, client_handler_function, &(clientInfo[clientSlot]));        
    }

    //This will never happen unless we quit the programm
    
    
    pthread_cancel(server_db_print);
    pthread_cancel(bullet_hit);
    // Will never happen
    close(sd);

    return 0;
}
Example #16
0
static void
read_device_map (const char *dev_map)
{
  FILE *fp;
  char buf[1024];	/* XXX */
  int lineno = 0;

  if (dev_map[0] == '\0')
    {
      grub_util_info ("no device.map");
      return;
    }

  fp = grub_util_fopen (dev_map, "r");
  if (! fp)
    {
      grub_util_info (_("cannot open `%s': %s"), dev_map, strerror (errno));
      return;
    }

  while (fgets (buf, sizeof (buf), fp))
    {
      char *p = buf;
      char *e;
      char *drive_e, *drive_p;
      int drive;

      lineno++;

      /* Skip leading spaces.  */
      while (*p && grub_isspace (*p))
	p++;

      /* If the first character is `#' or NUL, skip this line.  */
      if (*p == '\0' || *p == '#')
	continue;

      if (*p != '(')
	{
	  char *tmp;
	  tmp = xasprintf (_("missing `%c' symbol"), '(');
	  grub_util_error ("%s:%d: %s", dev_map, lineno, tmp);
	}

      p++;
      /* Find a free slot.  */
      drive = find_free_slot ();
      if (drive < 0)
	grub_util_error ("%s:%d: %s", dev_map, lineno, _("device count exceeds limit"));

      e = p;
      p = strchr (p, ')');
      if (! p)
	{
	  char *tmp;
	  tmp = xasprintf (_("missing `%c' symbol"), ')');
	  grub_util_error ("%s:%d: %s", dev_map, lineno, tmp);
	}

      map[drive].drive = 0;
      if ((e[0] == 'f' || e[0] == 'h' || e[0] == 'c') && e[1] == 'd')
	{
	  char *ptr;
	  for (ptr = e + 2; ptr < p; ptr++)
	    if (!grub_isdigit (*ptr))
	      break;
	  if (ptr == p)
	    {
	      map[drive].drive = xmalloc (p - e + sizeof ('\0'));
	      strncpy (map[drive].drive, e, p - e + sizeof ('\0'));
	      map[drive].drive[p - e] = '\0';
	    }
	  if (*ptr == ',')
	    {
	      *p = 0;

	      /* TRANSLATORS: Only one entry is ignored. However the suggestion
		 is to correct/delete the whole file.
		 device.map is a file indicating which
		 devices are available at boot time. Fedora populated it with
		 entries like (hd0,1) /dev/sda1 which would mean that every
		 partition is a separate disk for BIOS. Such entries were
		 inactive in GRUB due to its bug which is now gone. Without
		 this additional check these entries would be harmful now.
	      */
	      grub_util_warn (_("the device.map entry `%s' is invalid. "
				"Ignoring it. Please correct or "
				"delete your device.map"), e);
	      continue;
	    }
	}
      drive_e = e;
      drive_p = p;
      map[drive].device_map = 1;

      p++;
      /* Skip leading spaces.  */
      while (*p && grub_isspace (*p))
	p++;

      if (*p == '\0')
	grub_util_error ("%s:%d: %s", dev_map, lineno, _("filename expected"));

      /* NUL-terminate the filename.  */
      e = p;
      while (*e && ! grub_isspace (*e))
	e++;
      *e = '\0';

      if (!grub_util_check_file_presence (p))
	{
	  free (map[drive].drive);
	  map[drive].drive = NULL;
	  grub_util_info ("Cannot stat `%s', skipping", p);
	  continue;
	}

      /* On Linux, the devfs uses symbolic links horribly, and that
	 confuses the interface very much, so use realpath to expand
	 symbolic links.  */
      map[drive].device = canonicalize_file_name (p);
      if (! map[drive].device)
	map[drive].device = xstrdup (p);
      
      if (!map[drive].drive)
	{
	  char c;
	  map[drive].drive = xmalloc (sizeof ("hostdisk/") + strlen (p));
	  memcpy (map[drive].drive, "hostdisk/", sizeof ("hostdisk/") - 1);
	  strcpy (map[drive].drive + sizeof ("hostdisk/") - 1, p);
	  c = *drive_p;
	  *drive_p = 0;
	  /* TRANSLATORS: device.map is a filename. Not to be translated.
	     device.map specifies disk correspondance overrides. Previously
	     one could create any kind of device name with this. Due to
	     some problems we decided to limit it to just a handful
	     possibilities.  */
	  grub_util_warn (_("the drive name `%s' in device.map is incorrect. "
			    "Using %s instead. "
			    "Please use the form [hfc]d[0-9]* "
			    "(E.g. `hd0' or `cd')"),
			  drive_e, map[drive].drive);
	  *drive_p = c;
	}

      grub_util_info ("adding `%s' -> `%s' from device.map", map[drive].drive,
		      map[drive].device);

      grub_hostdisk_flush_initial_buffer (map[drive].device);
    }

  fclose (fp);
}
int main(int argc, char **argv)
{
  pthread_t db_thread_id;

  int sockfd, newfd; /* Socket descriptor and new descriptor */
  struct sockaddr_in my_addr; // my address information
  struct sockaddr_in their_addr; // connector's address information
  socklen_t sin_size;
  int yes=1, quit;

  struct square_t square[MAX_SQUARES]; // Array that holds runtime data for squares
  init_squares(square,MAX_SQUARES);    // Init this array

  init_the_very_ugly_array (very_ugly_array, MAX_SQUARES);

  if(argc!=2) // Some error handling
  {
    fprintf(stderr,"usage: %s port", argv[0]);
    exit(EXIT_FAILURE);
  }

  if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1) // Create an internet TCP-socket
  {
    perror("socket");
    exit(EXIT_FAILURE);
  }

  if(setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int))==-1)
  {
    perror("setsockopt");
    exit(EXIT_FAILURE);
  }

  my_addr.sin_family = AF_INET; // host byte order
  my_addr.sin_port = htons( atoi(argv[1]) ); // short, network byte order
  my_addr.sin_addr.s_addr = INADDR_ANY; //Automatically fill in my IP
  memset(my_addr.sin_zero,'\0',sizeof(my_addr.sin_zero));

  if(bind(sockfd,(struct sockaddr*)&my_addr, sizeof(my_addr))==-1)
  {
    perror("bind");
    exit(EXIT_FAILURE);
  }

  if(listen(sockfd,BACKLOG)==-1)
  {
    perror("listen");
    exit(EXIT_FAILURE);
  }

  pthread_create(&db_thread_id,NULL,db_thread,square);

  /* Main loop waiting for connections */
  quit = 0;
  while (!quit)
  {

    int newIndex=-1;

    /* This check the sd if there is a pending connection.
    * If there is one, accept that, and open a new socket for communicating */
    sin_size = sizeof(their_addr);
    if ((newfd = accept(sockfd,(struct sockaddr*)&their_addr,&sin_size))==-1)
    {
      perror("accept");
      continue;         // Goto loop beginning immediately. This accept failed.
    }

    newIndex = find_free_slot(square,MAX_SQUARES);
    printf("New index: %d.\n", newIndex);
    if(newIndex==-1)
    {
      close(newfd); // Close the socket descriptor to indicate to client that
      continue;     // we have no more space for it. Then goto beginning of loop.
    }

    square[newIndex].free=0;             // Indicate that this slot is no longer free.
    square[newIndex].csd = newfd;        // Note the desciptor to communicate via.
    square[newIndex].myindex = newIndex; // Note which index the thread has

    /* Now we can communicate with the client using csd socket (from accept)
     * sd will remain opened waiting other connections */

    /* Get the remote address */
    printf("Got connection from %s.\n",inet_ntoa(their_addr.sin_addr));
    strcpy(square[newIndex].remote_ip_str, inet_ntoa(their_addr.sin_addr));

    // Set the server port in square struct
    sprintf(square[newIndex].server_port,"%d",atoi(argv[1]) );


    // Serve the client in a separate thread. Main program will accept other clients.
    pthread_create(&(square[newIndex].thread_id), NULL, do_square, &(square[newIndex]));

  }

  return EXIT_SUCCESS;

}