Example #1
0
/**
 * @brief   Write always performes to shadow bank
 */
bool WpDB::write(const mavlink_mission_item_t *wpp, uint16_t seq) {

  size_t bytecnt = 0;
  const size_t shadow_bank = next_bank(active_bank);

  chDbgCheck(nullptr != this->dbfile);
  chDbgCheck(nullptr != wpp);

  memcpy(buf, wpp, sizeof(*wpp));
  seal_with_crc(buf);

  /* actual write */
  dbfile->setPosition(calc_offset(seq, shadow_bank));
  bytecnt = dbfile->write(buf, WAYPOINT_FOOTPRINT);
  if (WAYPOINT_FOOTPRINT != bytecnt)
    return OSAL_FAILED;

  /* read back and verify checksum */
  dbfile->setPosition(calc_offset(seq, shadow_bank));
  bytecnt = dbfile->read(buf, WAYPOINT_FOOTPRINT);
  if (WAYPOINT_FOOTPRINT != bytecnt)
    return OSAL_FAILED;

  if (crc_valid(buf)) {
    shadow_count++;
    return OSAL_SUCCESS;
  }
  else {
    return OSAL_FAILED;
  }
}
static void test_alternative_patching(void)
{
	extern unsigned int ftr_fixup_test2;
	extern unsigned int end_ftr_fixup_test2;
	extern unsigned int ftr_fixup_test2_orig;
	extern unsigned int ftr_fixup_test2_alt;
	extern unsigned int ftr_fixup_test2_expected;
	int size = &end_ftr_fixup_test2 - &ftr_fixup_test2;

	fixup.value = fixup.mask = 0xF;
	fixup.start_off = calc_offset(&fixup, &ftr_fixup_test2 + 1);
	fixup.end_off = calc_offset(&fixup, &ftr_fixup_test2 + 2);
	fixup.alt_start_off = calc_offset(&fixup, &ftr_fixup_test2_alt);
	fixup.alt_end_off = calc_offset(&fixup, &ftr_fixup_test2_alt + 1);

	/* Sanity check */
	check(memcmp(&ftr_fixup_test2, &ftr_fixup_test2_orig, size) == 0);

	/* Check we don't patch if the value matches */
	patch_feature_section(0xF, &fixup);
	check(memcmp(&ftr_fixup_test2, &ftr_fixup_test2_orig, size) == 0);

	/* Check we do patch if the value doesn't match */
	patch_feature_section(0, &fixup);
	check(memcmp(&ftr_fixup_test2, &ftr_fixup_test2_expected, size) == 0);

	/* Check we do patch if the mask doesn't match */
	memcpy(&ftr_fixup_test2, &ftr_fixup_test2_orig, size);
	check(memcmp(&ftr_fixup_test2, &ftr_fixup_test2_orig, size) == 0);
	patch_feature_section(~0xF, &fixup);
	check(memcmp(&ftr_fixup_test2, &ftr_fixup_test2_expected, size) == 0);
}
static void test_basic_patching(void)
{
	extern unsigned int ftr_fixup_test1;
	extern unsigned int end_ftr_fixup_test1;
	extern unsigned int ftr_fixup_test1_orig;
	extern unsigned int ftr_fixup_test1_expected;
	int size = &end_ftr_fixup_test1 - &ftr_fixup_test1;

	fixup.value = fixup.mask = 8;
	fixup.start_off = calc_offset(&fixup, &ftr_fixup_test1 + 1);
	fixup.end_off = calc_offset(&fixup, &ftr_fixup_test1 + 2);
	fixup.alt_start_off = fixup.alt_end_off = 0;

	/* Sanity check */
	check(memcmp(&ftr_fixup_test1, &ftr_fixup_test1_orig, size) == 0);

	/* Check we don't patch if the value matches */
	patch_feature_section(8, &fixup);
	check(memcmp(&ftr_fixup_test1, &ftr_fixup_test1_orig, size) == 0);

	/* Check we do patch if the value doesn't match */
	patch_feature_section(0, &fixup);
	check(memcmp(&ftr_fixup_test1, &ftr_fixup_test1_expected, size) == 0);

	/* Check we do patch if the mask doesn't match */
	memcpy(&ftr_fixup_test1, &ftr_fixup_test1_orig, size);
	check(memcmp(&ftr_fixup_test1, &ftr_fixup_test1_orig, size) == 0);
	patch_feature_section(~8, &fixup);
	check(memcmp(&ftr_fixup_test1, &ftr_fixup_test1_expected, size) == 0);
}
static void test_alternative_case_too_small(void)
{
	extern unsigned int ftr_fixup_test4;
	extern unsigned int end_ftr_fixup_test4;
	extern unsigned int ftr_fixup_test4_orig;
	extern unsigned int ftr_fixup_test4_alt;
	extern unsigned int ftr_fixup_test4_expected;
	int size = &end_ftr_fixup_test4 - &ftr_fixup_test4;
	unsigned long flag;

	/* Check a high-bit flag */
	flag = 1UL << ((sizeof(unsigned long) - 1) * 8);
	fixup.value = fixup.mask = flag;
	fixup.start_off = calc_offset(&fixup, &ftr_fixup_test4 + 1);
	fixup.end_off = calc_offset(&fixup, &ftr_fixup_test4 + 5);
	fixup.alt_start_off = calc_offset(&fixup, &ftr_fixup_test4_alt);
	fixup.alt_end_off = calc_offset(&fixup, &ftr_fixup_test4_alt + 2);

	/* Sanity check */
	check(memcmp(&ftr_fixup_test4, &ftr_fixup_test4_orig, size) == 0);

	/* Check we don't patch if the value matches */
	patch_feature_section(flag, &fixup);
	check(memcmp(&ftr_fixup_test4, &ftr_fixup_test4_orig, size) == 0);

	/* Check we do patch if the value doesn't match */
	patch_feature_section(0, &fixup);
	check(memcmp(&ftr_fixup_test4, &ftr_fixup_test4_expected, size) == 0);

	/* Check we do patch if the mask doesn't match */
	memcpy(&ftr_fixup_test4, &ftr_fixup_test4_orig, size);
	check(memcmp(&ftr_fixup_test4, &ftr_fixup_test4_orig, size) == 0);
	patch_feature_section(~flag, &fixup);
	check(memcmp(&ftr_fixup_test4, &ftr_fixup_test4_expected, size) == 0);
}
static void test_alternative_case_too_big(void)
{
	extern unsigned int ftr_fixup_test3;
	extern unsigned int end_ftr_fixup_test3;
	extern unsigned int ftr_fixup_test3_orig;
	extern unsigned int ftr_fixup_test3_alt;
	int size = &end_ftr_fixup_test3 - &ftr_fixup_test3;

	fixup.value = fixup.mask = 0xC;
	fixup.start_off = calc_offset(&fixup, &ftr_fixup_test3 + 1);
	fixup.end_off = calc_offset(&fixup, &ftr_fixup_test3 + 2);
	fixup.alt_start_off = calc_offset(&fixup, &ftr_fixup_test3_alt);
	fixup.alt_end_off = calc_offset(&fixup, &ftr_fixup_test3_alt + 2);

	/* Sanity check */
	check(memcmp(&ftr_fixup_test3, &ftr_fixup_test3_orig, size) == 0);

	/* Expect nothing to be patched, and the error returned to us */
	check(patch_feature_section(0xF, &fixup) == 1);
	check(memcmp(&ftr_fixup_test3, &ftr_fixup_test3_orig, size) == 0);
	check(patch_feature_section(0, &fixup) == 1);
	check(memcmp(&ftr_fixup_test3, &ftr_fixup_test3_orig, size) == 0);
	check(patch_feature_section(~0xF, &fixup) == 1);
	check(memcmp(&ftr_fixup_test3, &ftr_fixup_test3_orig, size) == 0);
}
static int init_sbd_ipc(struct sbd_link_device *sl,
			struct sbd_ipc_device ipc_dev[],
			struct sbd_link_attr link_attr[])
{
	int i;

	setup_desc_rgn(sl);

	for (i = 0; i < sl->num_channels; i++) {
		struct sbd_rb_channel *rb_ch = &sl->g_desc->rb_ch[i];
		struct sbd_rb_desc *rb_desc;
		struct sbd_ring_buffer *rb;
		int ret;

		ipc_dev[i].id = link_attr[i].id;
		ipc_dev[i].ch = link_attr[i].ch;

		/*
		Setup UL Ring Buffer in the ipc_dev[$i]
		*/
		rb = &ipc_dev[i].rb[UL];
		ret = setup_sbd_rb(sl, rb, UL, &link_attr[i]);
		if (ret < 0)
			return ret;

		/*
		Setup UL RB_DESC & UL RB_CH in the g_desc
		*/
		rb_desc = &sl->g_desc->rb_desc[i][UL];
		setup_sbd_rb_desc(rb_desc, rb);
		rb_ch->ul_rbd_offset = calc_offset(rb_desc, sl->shmem);
		rb_ch->ul_sbdv_offset = calc_offset(rb->addr_v, sl->shmem);

		/*
		Setup DL Ring Buffer in the ipc_dev[$i]
		*/
		rb = &ipc_dev[i].rb[DL];
		ret = setup_sbd_rb(sl, rb, DL, &link_attr[i]);
		if (ret < 0)
			return ret;

		/*
		Setup DL RB_DESC & DL RB_CH in the g_desc
		*/
		rb_desc = &sl->g_desc->rb_desc[i][DL];
		setup_sbd_rb_desc(rb_desc, rb);
		rb_ch->dl_rbd_offset = calc_offset(rb_desc, sl->shmem);
		rb_ch->dl_sbdv_offset = calc_offset(rb->addr_v, sl->shmem);
	}

	return 0;
}
static void setup_desc_rgn(struct sbd_link_device *sl)
{
	unsigned int size;

#if 0
	mif_err("SHMEM {base:0x%08X size:%d}\n",
		(int)sl->shmem, sl->shmem_size);
#endif

	/*
	Allocate @g_desc.
	*/
	size = sizeof(struct sbd_global_desc);
	sl->g_desc = (struct sbd_global_desc *)desc_alloc(sl, size);

#if 0
	mif_err("G_DESC_OFFSET = %d(0x%08X)\n",
		calc_offset(sl->g_desc, sl->shmem),
		(int)sl->g_desc);

	mif_err("RB_CH_OFFSET = %d (0x%08X)\n",
		calc_offset(sl->g_desc->rb_ch, sl->shmem),
		(int)sl->g_desc->rb_ch);

	mif_err("RBD_PAIR_OFFSET = %d (0x%08X)\n",
		calc_offset(sl->g_desc->rb_desc, sl->shmem),
		(int)sl->g_desc->rb_desc);
#endif

	size = sizeof(u16) * ULDL * RDWR * sl->num_channels;
	sl->rbps = (u16 *)desc_alloc(sl, size);
#if 0
	mif_err("RBP_SET_OFFSET = %d (0x%08X)\n",
		calc_offset(sl->rbps, sl->shmem), (int)sl->rbps);
#endif

	/*
	Set up @g_desc.
	*/
	sl->g_desc->version = sl->version;
	sl->g_desc->num_channels = sl->num_channels;
	sl->g_desc->rbps_offset = calc_offset(sl->rbps, sl->shmem);

	/*
	Set up pointers to each RBP array.
	*/
	sl->rp[UL] = sl->rbps + sl->num_channels * 0;
	sl->wp[UL] = sl->rbps + sl->num_channels * 1;
	sl->rp[DL] = sl->rbps + sl->num_channels * 2;
	sl->wp[DL] = sl->rbps + sl->num_channels * 3;
}
Example #8
0
int Ctbg::collect_spellrefs()
{
  int *strref_opcodes;
  int pos;
  int count;
  int i;

  strref_opcodes=get_strref_opcodes();
  pos=0;
  count=4; //item header contains 4 strrefs
  for(i=0;i<the_spell.featblkcount;i++)//not header, we need ALL feature blocks
  {
    if(member_array(the_spell.featblocks[i].feature,strref_opcodes)!=-1)
    {
      count++;
    }
  }
  tlkentries=new tbg_tlk_reference[count];
  if(!tlkentries) return -3;
  tlkentrycount=count;        //physical size
  strrefs=new unsigned long[count];
  if(!strrefs)
  {
    delete [] tlkentries;
    return -3;
  }
  strrefcount=count;

  strrefs[pos]=calc_offset(the_spell.header, desc);
  if(!resolve_tbg_entry(the_spell.header.desc,tlkentries[pos])) pos++;
  strrefs[pos]=calc_offset(the_spell.header, spellname);
  if(!resolve_tbg_entry(the_spell.header.spellname,tlkentries[pos])) pos++;
//  strrefs[pos]=calc_offset(the_spell.header, unknown4c);
//  if(!resolve_tbg_entry(the_spell.header.unknown4c,tlkentries[pos])) pos++;
  strrefs[pos]=calc_offset(the_spell.header, idname);
  if(!resolve_tbg_entry(the_spell.header.idname,tlkentries[pos])) pos++;

  for(i=0;i<the_spell.featblkcount;i++)
  {
    if(member_array(the_spell.featblocks[i].feature,strref_opcodes)!=-1)
    {
      strrefs[pos]=the_spell.header.featureoffs+calc_offset2(the_spell.featblocks[0],the_spell.featblocks[i].par1.parl);
      resolve_tbg_entry(the_spell.featblocks[i].par1.parl,tlkentries[pos++]);
    }
  }
  header.tlkentrycount=pos;   //logical size
  header.strrefcount=pos;
  return 0;
}
Example #9
0
int Ctbg::collect_prorefs()
{ 
  int count, pos;

  if(!(the_projectile.header.extflags&PROJ_TEXT))
  {
    return 0;
  }

  count=1;
  pos=0;
  tlkentries=new tbg_tlk_reference[count];
  if(!tlkentries) return -3;
  tlkentrycount=count;        //physical size
  strrefs=new unsigned long[count];
  if(!strrefs)
  {
    delete [] tlkentries;
    return -3;
  }
  strrefcount=count;

  strrefs[0]=calc_offset(the_projectile.header,text);
  if(!resolve_tbg_entry(the_projectile.header.text,tlkentries[0])) pos=1;
  header.tlkentrycount=pos;   //logical size
  header.strrefcount=pos;
  return 0;
}
Example #10
0
/**
 * Get a bit at a particular location
 */
unsigned char get_bit(bit_vector_t *vec, unsigned int pos) {
    unsigned int offset = calc_offset(pos);
    unsigned int bitpos = pos - (offset * sizeof(unsigned char));

    unsigned char mask = get_on_mask(bitpos);
    return vec->bits[offset] & mask;
}
Example #11
0
int Ctbg::collect_effectrefs()
{
  int *strref_opcodes;
  int pos;
  int count;

  strref_opcodes=get_strref_opcodes();
  pos=0;
  if(member_array(the_effect.header.feature,strref_opcodes)!=-1)
  {
    count=1;
  }
  else
  {
    count=0;
  }
  if(!count) return 0;
  tlkentries=new tbg_tlk_reference[count];
  if(!tlkentries) return -3;
  tlkentrycount=count;        //physical size
  strrefs=new unsigned long[count];
  if(!strrefs)
  {
    delete [] tlkentries;
    return -3;
  }
  strrefcount=count;

  strrefs[0]=calc_offset(the_effect.header,par1.parl);
  if(!resolve_tbg_entry(the_effect.header.par1.parl,tlkentries[0])) pos=1;
  header.tlkentrycount=pos;   //logical size
  header.strrefcount=pos;
  return 0;
}
Example #12
0
int Ctbg::collect_storerefs()
{
  int pos;
  int count;
  int i;

  pos=0;
  count=1+the_store.header.drinkcount;
  tlkentries=new tbg_tlk_reference[count];
  if(!tlkentries) return -3;
  tlkentrycount=count;        //physical size
  strrefs=new unsigned long[count];
  if(!strrefs)
  {
    delete [] tlkentries;
    return -3;
  }
  strrefcount=count;

  strrefs[pos]=calc_offset(the_store.header, strref);
  if(!resolve_tbg_entry(the_store.header.strref,tlkentries[pos])) pos++;
  for(i=0;i<the_store.header.drinkcount;i++)
  {
    strrefs[pos]=the_store.header.drinkoffset+calc_offset2(the_store.drinks[0],the_store.drinks[i].drinkname);
    if(!resolve_tbg_entry(the_store.drinks[i].drinkname,tlkentries[pos]) ) pos++;
  }
  header.tlkentrycount=pos;   //logical size
  header.strrefcount=pos;
  return 0;
}
Example #13
0
 RANGES_CXX14_CONSTEXPR
 stride_view_base(Rng &&rng, range_difference_type_t<Rng> const stride)
     noexcept(std::is_nothrow_constructible<stride_view_adaptor<Rng>, Rng>::value &&
         noexcept(std::declval<stride_view_base &>().calc_offset(SizedRange<Rng>())))
   : stride_view_adaptor<Rng>{std::move(rng)},
     stride_{(RANGES_EXPECT(0 < stride), stride)},
     offset_{calc_offset(SizedRange<Rng>())}
 {}
Example #14
0
FRESULT fdd_writesector(FDDImage* fdd) {
	FRESULT r;
	UINT bytesread;
	
	uint32_t offset = calc_offset(fdd);
	if ((r = f_lseek(fdd->file, offset)) != FR_OK) return r;
	
	r = f_write_inplace(fdd->file, fdd->buffer, FDD_SECTOR_SIZE, &bytesread);
	
	return r;
}
Example #15
0
/**
 * Set a bit at a particular location
 */
void set_bit(bit_vector_t *vec, unsigned int pos, unsigned char val) {
    unsigned int offset = calc_offset(pos);
    unsigned int bitpos = pos - (offset * sizeof(unsigned char));

    if (val) {
        unsigned char mask = get_on_mask(bitpos);
        vec->bits[offset] = vec->bits[offset] | mask;
    } else {
        unsigned char mask = get_off_mask(bitpos);
        vec->bits[offset] = vec->bits[offset] & mask;
    }

    return;
}
Example #16
0
int Ctbg::collect_arearefs()
{
  int pos;
  int count;
  int i;

  pos=0;
  count=the_area.containercount+the_area.triggercount+the_area.doorcount+the_area.mapnotecount+the_area.intheader.creaturecnt;
//additional counts
  tlkentries=new tbg_tlk_reference[count];
  if(!tlkentries) return -3;
  tlkentrycount=count;        //physical size
  strrefs=new unsigned long[count];
  if(!strrefs)
  {
    delete [] tlkentries;
    return -3;
  }
  strrefcount=count;

  for(i=0;i<the_area.containercount;i++)
  {
    strrefs[pos]=the_area.header.containeroffset+calc_offset2(the_area.containerheaders[0],the_area.containerheaders[i].strref);
    if(!resolve_tbg_entry(the_area.containerheaders[i].strref,tlkentries[pos]) ) pos++;
  }
  for(i=0;i<the_area.triggercount;i++)
  {
    strrefs[pos]=the_area.header.infooffset+calc_offset2(the_area.triggerheaders[0],the_area.triggerheaders[i].strref);
    if(!resolve_tbg_entry(the_area.triggerheaders[i].strref,tlkentries[pos]) ) pos++;
  }
  for(i=0;i<the_area.doorcount;i++)
  {
    strrefs[pos]=the_area.header.dooroffset+calc_offset2(the_area.doorheaders[0],the_area.doorheaders[i].strref);
    if(!resolve_tbg_entry(the_area.doorheaders[i].strref,tlkentries[pos]) ) pos++;
  }
  for(i=0;i<the_area.mapnotecount;i++)
  {
    strrefs[pos]=the_area.header.mapnoteoffset+calc_offset2(the_area.mapnoteheaders[0],the_area.mapnoteheaders[i].strref);
    if(!resolve_tbg_entry(the_area.mapnoteheaders[i].strref,tlkentries[pos]) ) pos++;
  }
  for(i=0;i<the_area.intheader.creaturecnt;i++)
  {
    strrefs[pos]=the_area.header.intoffset+calc_offset(the_area.intheader,strrefs[i]);
    if(!resolve_tbg_entry(the_area.intheader.strrefs[i],tlkentries[pos]) ) pos++;
  }
//additional stores
  header.tlkentrycount=pos;   //logical size
  header.strrefcount=pos;
  return 0;
}
Example #17
0
File: common.c Project: VVer/opal
/****************************************************************************************
 Function:    categorize

 Syntax:      void categorize(Word16 number_of_available_bits,   
                              Word16 number_of_regions,
                              Word16 num_categorization_control_possibilities,
                              Word16 rms_index,                  
                              Word16 power_categories,           
                              Word16 category_balances)          

                  inputs:   number_of_regions
                            num_categorization_control_possibilities
                            number_of_available_bits
                            rms_index[MAX_NUMBER_OF_REGIONS]                              
                  
                  outputs:  power_categories[MAX_NUMBER_OF_REGIONS]                       
                            category_balances[MAX_NUM_CATEGORIZATION_CONTROL_POSSIBILITIES-1]

 Description: Computes a series of categorizations 

 WMOPS:     7kHz |    24kbit    |     32kbit
          -------|--------------|----------------
            AVG  |    0.14      |     0.14
          -------|--------------|----------------  
            MAX  |    0.15      |     0.15
          -------|--------------|---------------- 
   			
           14kHz |    24kbit    |     32kbit     |     48kbit
          -------|--------------|----------------|----------------
            AVG  |    0.42      |     0.45       |     0.48   
          -------|--------------|----------------|----------------
            MAX  |    0.47      |     0.52       |     0.52   
          -------|--------------|----------------|----------------

****************************************************************************************/
void categorize(Word16 number_of_available_bits,
		        Word16 number_of_regions,
		        Word16 num_categorization_control_possibilities,
		        Word16 *rms_index,
		        Word16 *power_categories,
		        Word16 *category_balances)
{
    
    Word16 offset;
    Word16 temp;
    Word16 frame_size;

    /* At higher bit rates, there is an increase for most categories in average bit
       consumption per region. We compensate for this by pretending we have fewer
       available bits. */
    test();
    if (number_of_regions == NUMBER_OF_REGIONS)
    {
        frame_size = DCT_LENGTH;
    }
    else
    {
        frame_size = MAX_DCT_LENGTH;
    }

    temp = sub(number_of_available_bits,frame_size);
    
    test();
    if (temp > 0)
    {
        number_of_available_bits = sub(number_of_available_bits,frame_size);
        number_of_available_bits = extract_l(L_mult0(number_of_available_bits,5));
        number_of_available_bits = shr(number_of_available_bits,3);
        number_of_available_bits = add(number_of_available_bits,frame_size);
    }

    /* calculate the offset using the original category assignments */
    offset = calc_offset(rms_index,number_of_regions,number_of_available_bits);



    /* compute the power categories based on the uniform offset */
    compute_raw_pow_categories(power_categories,rms_index,number_of_regions,offset);
    
    
    /* adjust the category assignments */
    /* compute the new power categories and category balances */
    comp_powercat_and_catbalance(power_categories,category_balances,rms_index,number_of_available_bits,number_of_regions,num_categorization_control_possibilities,offset);

}
Example #18
0
FRESULT fdd_readsector(FDDImage* fdd) {
	FRESULT r;
	UINT bytesread;
	
	uint32_t offset = calc_offset(fdd);
	
	//FDD_NSIDES*fdd->cur_track + (1-fdd->cur_side);
	//offset *= FDD_NSECTORS; 
	//offset += fdd->cur_sector - 1;
	//offset *= FDD_SECTOR_SIZE;
	
	if ((r = f_lseek(fdd->file, offset)) != FR_OK) return r;
	
	r = f_read(fdd->file, fdd->buffer, FDD_SECTOR_SIZE, &bytesread);
	
	return r;
}
static
void uprobe_post_ssout(struct uprobe_task *utask, struct uprobe_probept *ppt,
		struct pt_regs *regs)
{
	unsigned long copy_nip;

	copy_nip = (unsigned long) ppt->slot->insn;
	up_read(&ppt->slot->rwsem);

	/*
	 * If the single stepped instruction is non-branch instruction
	 * then update the IP to be relative to probepoint.
	 */
	if (regs->nip == copy_nip + MAX_UINSN_BYTES)
		regs->nip = ppt->vaddr + MAX_UINSN_BYTES;
	else
		calc_offset(ppt,regs);
}
Example #20
0
uint16_t WpDB::start(void) {

  size_t readcnt;

  dbfile = NvramTryOpen(WPDB_FILE_NAME, BOOTSTRAP_WPDB_FILE_SIZE);
  osalDbgCheck(nullptr != dbfile);

  /* precalculate capacity for single bank */
  this->capacity = (dbfile->getSize() - HEADER_SIZE) / (WAYPOINT_FOOTPRINT  * 2);

  dbfile->setPosition(0);
  dbfile->get(&count);
  this->shadow_count = 0;

  /* deduce what bank contains valid data and adjust 'count' when needed */
  if (0 == (count & (1U << 15))){
    active_bank = 0;
  }
  else {
    active_bank = 1;
    count &= ~(1U << 15);
  }

  /* validate data in current bank */
  for (size_t seq=0; seq<count; seq++) {
    dbfile->setPosition(calc_offset(seq, active_bank));
    readcnt = dbfile->read(buf, WAYPOINT_FOOTPRINT);
    if (WAYPOINT_FOOTPRINT != readcnt)
      goto FAILED;

    if (! crc_valid(buf)) {
      goto FAILED;
    }
  }
  return count;

FAILED:
  count = 0;
  return 0;
}
Example #21
0
bool WpDB::read(mavlink_mission_item_t *wpp, uint16_t seq) {

  size_t result;

  osalDbgCheck(nullptr != this->dbfile);
  osalDbgCheck(nullptr != wpp);
  osalDbgCheck(active_bank <= 1);

  if (seq >= count)
    return OSAL_FAILED;
  else {
    dbfile->setPosition(calc_offset(seq, active_bank));

    result = dbfile->read(buf, WAYPOINT_FOOTPRINT);
    if (WAYPOINT_FOOTPRINT != result)
      return OSAL_FAILED;

    if (! crc_valid(buf))
      return OSAL_FAILED;

    memcpy(wpp, buf, sizeof(*wpp));
    return OSAL_SUCCESS;
  }
}
Example #22
0
void get(struct request *req)
{
  int i, ret, fd, diff_sec, nok = 0;
  long soffset, foffset;
  char *fmt;

  if (req->proto == PROTO_HTTP)
    http_head_req (req);

  /* According to the content-length, get the
   * suggested number of threads to open.
   * if the user insists on his value, let it be that way,
   * use the user's value.
   */
  ret = numofthreads (req->clength);

  if (fsuggested == 0)
    {
      if (ret == 0)
	nthreads = 1;
      else
	nthreads = ret;
    }

  wthread = (struct thread_data *) malloc (nthreads * sizeof (struct thread_data));

  Log ("Downloading %s (%d bytes) from site %s(%s:%d). Number of Threads: %d",
       req->url, req->clength, req->host, req->ip, req->port, nthreads);

  if (strlen (req->lfile) != 0)
    {
      if ((fd = open (req->lfile, O_CREAT | O_RDWR, S_IRWXU)) == -1)
	{
	  fprintf (stderr, "get: cannot open file %s for writing: %s\n",
		   req->lfile, strerror (errno));
	  exit (1);
	}

    }
  else
    {
      if ((fd = open (req->file, O_CREAT | O_RDWR, S_IRWXU)) == -1)
	{
	  fprintf (stderr, "get: cannot open file %s for writing: %s\n",
		   req->lfile, strerror (errno));
	  exit (1);
	}
    }

  if ((lseek (fd, req->clength - 1, SEEK_SET)) == -1)
    {
      fprintf (stderr, "get: couldn't lseek:  %s\n", strerror (errno));
      exit (1);
    }

  if ((write (fd, "0", 1)) == -1)
    {
      fprintf (stderr, "get: couldn't allocate space for download file: %s\n",
	       strerror (errno));
      exit (1);
    }

  /* Get the starting time, prepare GET format string, and start the threads */
  fmt = (char *) malloc ((GETREQSIZ - 2) * sizeof (char));
  memset(fmt, 0, ((GETREQSIZ - 2) * sizeof (char)));

  time (&t_start);
  for (i = 0; i < nthreads; i++)
    {
      soffset = calc_offset (req->clength, i, nthreads);
      foffset = calc_offset (req->clength, i + 1, nthreads);
      wthread[i].soffset = soffset;
      wthread[i].foffset = (i == nthreads - 1 ? req->clength : foffset);
      wthread[i].sin.sin_family = AF_INET;
      wthread[i].sin.sin_addr.s_addr = inet_addr (req->ip);
      wthread[i].sin.sin_port = htons (req->port);
      wthread[i].fd = dup (fd);
      wthread[i].clength = req->clength;
      snprintf (fmt, GETREQSIZ, GETREQ, req->url, req->host, PROGVERSION,
		soffset);
      strncpy (wthread[i].getstr, fmt, GETREQSIZ);
      pthread_create (&(wthread[i].tid), NULL, http_get, &(wthread[i]));
    }
  free (fmt);


  /* Wait for all of the threads to finish... 
   * 
   * TODO: If a thread fails, restart that!
   */
  for (i = 0; i < nthreads; i++)
    {
      pthread_join (wthread[i].tid, NULL);
      if (wthread[i].status == STAT_OK)
	nok++;
    }

/*   if (nok == nthreads) */
/*     pthread_cancel (hthread); */
/*   else */
/*     pthread_join (hthread, NULL); */

  /* Get the finish time, derive some stats       */
  time (&t_finish);
  if ((diff_sec = t_finish - t_start) == 0)
    diff_sec = 1;		/* Avoid division by zero       */

  Log ("Download completed, job completed in %d seconds. (%d Kb/sec)",
       diff_sec, (req->clength / diff_sec) / 1024);
  Log ("Shutting down...");
  close (fd);
}
Example #23
0
int Ctbg::collect_creaturerefs(int alternate)
{
  int *strref_opcodes;
  int pos;
  int count;
  int i;
  int feat;

  strref_opcodes=get_strref_opcodes();
  pos=0;
  if(alternate) count=SND_SLOT_COUNT;
  else count=SND_SLOT_COUNT+2+the_creature.effectcount; //names+soundset+effects
  tlkentries=new tbg_tlk_reference[count];
  if(!tlkentries) return -3;
  tlkentrycount=count;        //physical size
  strrefs=new unsigned long [count];
  if(!strrefs)
  {
    delete [] tlkentries;
    return -3;
  }
  strrefcount=count;

  if(!alternate)
  {
    strrefs[pos]=calc_offset(the_creature.header, longname);
    if(!resolve_tbg_entry(the_creature.header.longname,tlkentries[pos])) pos++;
    strrefs[pos]=calc_offset(the_creature.header, shortname);
    if(!resolve_tbg_entry(the_creature.header.shortname,tlkentries[pos])) pos++;
  }

  for(i=0;i<100;i++)
  {    
    if(alternate) strrefs[pos]=i*sizeof(long);
    else strrefs[pos]=calc_offset(the_creature.header,strrefs[i]);
    if(!resolve_tbg_entry(the_creature.header.strrefs[i],tlkentries[pos]) ) pos++;
  }
  if(!alternate)
  {
    for(i=0;i<the_creature.effectcount;i++)
    {
      if(the_creature.header.effbyte)
      {
        feat=the_creature.effects[i].feature;
      }
      else
      {
        feat=the_creature.oldeffects[i].feature;
      }
      if(member_array(feat,strref_opcodes)!=-1)
      {
        if(the_creature.header.effbyte)
        {
          strrefs[pos]=the_creature.header.effectoffs+calc_offset2(the_creature.effects[0],the_creature.effects[i].par1.parl);
          if(!resolve_tbg_entry(the_creature.effects[i].par1.parl,tlkentries[pos]) ) pos++;
        }
        else
        {
          strrefs[pos]=the_creature.header.effectoffs+calc_offset2(the_creature.oldeffects[0],the_creature.oldeffects[i].par1.parl);
          if(!resolve_tbg_entry(the_creature.oldeffects[i].par1.parl,tlkentries[pos]) ) pos++;
        }
      }
    }
  }

  header.tlkentrycount=pos;   //logical size
  header.strrefcount=pos;
  return 0;
}
Example #24
0
void CardRegion::PrepareDragBitmaps(int numtodrag)
{
    RECT rect;
    HDC hdc;
    int icard;
    int numcards = cardstack.NumCards();
    int xoff, yoff;

    if(nThreedCount > 1)
    {
        PrepareDragBitmapsThreed(numtodrag);
        return;
    }

    //work out how big the bitmaps need to be
    nDragCardWidth  = (numtodrag - 1) * abs(xoffset) + __cardwidth;
    nDragCardHeight = (numtodrag - 1) * abs(yoffset) + __cardheight;

    //Create bitmap for the back-buffer
    hdc = GetDC(NULL);
    hdcBackGnd = CreateCompatibleDC(hdc);
    hbmBackGnd = CreateCompatibleBitmap(hdc, nDragCardWidth, nDragCardHeight);
    SelectObject(hdcBackGnd, hbmBackGnd);

    //Create bitmap for the drag-image
    hdcDragCard = CreateCompatibleDC(hdc);
    hbmDragCard = CreateCompatibleBitmap(hdc, nDragCardWidth, nDragCardHeight);
    SelectObject(hdcDragCard, hbmDragCard);
    ReleaseDC(NULL, hdc);

    UseNicePalette(hdcBackGnd,  __hPalette);
    UseNicePalette(hdcDragCard, __hPalette);

    int realvisible = numcards / nThreedCount;

    //if(numcards > 0 && realvisible == 0) realvisible = 1;
    int iwhichcard = numcards - 1;
    if(nThreedCount == 1) iwhichcard = 0;

    //grab the first bit of background so we can prep the back buffer; do this by
    //rendering the card stack (minus the card we are dragging) to the temporary
    //background buffer, so it appears if we have lifted the card from the stack
    //PaintRect(hdcBackGnd, &rect, crBackgnd);
    SetRect(&rect, 0, 0, nDragCardWidth, nDragCardHeight);

    xoff = calc_offset(xoffset, numcards, numtodrag, realvisible);
    yoff = calc_offset(yoffset, numcards, numtodrag, realvisible);

    parentWnd.PaintCardRgn(hdcBackGnd, 0, 0, nDragCardWidth, nDragCardHeight, xpos - xoff,    ypos - yoff);

    //
    //    Render the cardstack into the back-buffer. The stack
    //    has already had the dragcards removed, so just draw
    //    what is left
    //
    for(icard = 0; icard < realvisible; icard++)
    {
        Card card = cardstack.cardlist[iwhichcard];
        int nCardVal;

        nCardVal = card.FaceUp() ? card.Idx() : nBackCardIdx;

        xoff = xoffset * icard + calc_offset(xoffset, numcards, numtodrag, realvisible);//- xoffset * ((numcards+numtodrag) / nThreedCount - numtodrag);
        yoff = yoffset * icard + calc_offset(yoffset, numcards, numtodrag, realvisible);//- yoffset * ((numcards+numtodrag) / nThreedCount - numtodrag);

        CardBlt(hdcBackGnd, xoff, yoff, nCardVal);
        iwhichcard++;
    }

    //
    // If there are no cards under this one, just draw the place holder
    //
    if(numcards == 0)
    {
        int xoff = 0, yoff = 0;

        if(xoffset < 0)    xoff = nDragCardWidth  -  __cardwidth;
        if(yoffset < 0)    yoff = nDragCardHeight -  __cardheight;

        switch(uEmptyImage)
        {
        case CS_EI_NONE:
            //No need to draw anything: We already cleared the
            //back-buffer before the main loop..

            //SetRect(&rc, xoff, yoff, xoff+ __cardwidth, yoff + __cardheight);
            //PaintRect(hdcBackGnd, &rc, MAKE_PALETTERGB(crBackgnd));
            //parentWnd.PaintCardRgn(hdcBackGnd, xoff, yoff, __cardwidth, __cardheight, xpos, ypos);// + xoff, ypos + yoff);
            break;

        case CS_EI_SUNK:
            DrawCard(hdcBackGnd, xoff, yoff, __hdcPlaceHolder, __cardwidth, __cardheight);
            break;

        case CS_EI_CIRC:
        case CS_EI_X:
            CardBlt(hdc, xoff, yoff, uEmptyImage);
            break;
        }
    }

    //
    //    now render the drag-cards into the dragcard image
    //
    PaintRect(hdcDragCard, &rect, crBackgnd);

    for(icard = 0; icard < numtodrag; icard++)
    {
        int nCardVal;

        if(xoffset >= 0) xoff =  xoffset * icard;
        else              xoff = -xoffset * (numtodrag - icard - 1);

        if(yoffset >= 0) yoff =  yoffset * icard;
        else             yoff = -yoffset * (numtodrag - icard - 1);

        Card card = dragstack.cardlist[icard];

        nCardVal = card.FaceUp() ? card.Idx() : nBackCardIdx;

        CardBlt(hdcDragCard, xoff, yoff, nCardVal);
    }
}
Example #25
0
void CardRegion::PrepareDragBitmapsThreed(int numtodrag)
{
    RECT rect;
    HDC hdc;
    int icard;
    int numunder = 0;
    int iwhichcard;

    int numcards = cardstack.NumCards();

    //work out how big the bitmaps need to be
    nDragCardWidth  = (numtodrag - 1) * abs(xoffset) + __cardwidth;
    nDragCardHeight = (numtodrag - 1) * abs(yoffset) + __cardheight;

    //Create bitmap for the back-buffer
    hdc = GetDC(NULL);
    hdcBackGnd = CreateCompatibleDC(hdc);
    hbmBackGnd = CreateCompatibleBitmap(hdc, nDragCardWidth, nDragCardHeight);
    SelectObject(hdcBackGnd, hbmBackGnd);

    //create bitmap for the drag-image
    hdcDragCard = CreateCompatibleDC(hdc);
    hbmDragCard = CreateCompatibleBitmap(hdc, nDragCardWidth, nDragCardHeight);
    SelectObject(hdcDragCard, hbmDragCard);
    ReleaseDC(NULL, hdc);

    UseNicePalette(hdcBackGnd,  __hPalette);
    UseNicePalette(hdcDragCard, __hPalette);

    //grab the first bit of background so we can prep the back buffer; do this by
    //rendering the card stack (minus the card we are dragging) to the temporary
    //background buffer, so it appears if we have lifted the card from the stack
    //--SetRect(&rect, 0, 0, nDragCardWidth, nDragCardHeight);
    //--PaintRect(hdcBackGnd, &rect, crBackgnd);

    int threedadjust = numcards  % nThreedCount == 0;

    numunder = CalcApparentCards(numcards);
    iwhichcard = (numcards+numtodrag) - numunder - 1;
    if(nThreedCount == 1) iwhichcard = 0;

    int xoff = calc_offset(xoffset, numunder, numtodrag, numunder);
    int yoff = calc_offset(yoffset, numunder, numtodrag, numunder);

    parentWnd.PaintCardRgn(hdcBackGnd, 0,0,    nDragCardWidth,nDragCardHeight,    xpos - xoff,ypos - yoff);

    //
    //    Render the cardstack into the back-buffer. The stack
    //    has already had the dragcards removed, so just draw
    //    what is left
    //
    for(icard = 0; icard < numunder; icard++)
    {
        Card card = cardstack.cardlist[iwhichcard];
        int nCardVal = card.FaceUp() ? card.Idx() : nBackCardIdx;

        CardBlt(hdcBackGnd,
                xoffset * icard - xoffset*(numunder-numtodrag+threedadjust),
                yoffset * icard - yoffset*(numunder-numtodrag+threedadjust),
                nCardVal);

        iwhichcard++;
    }

    //
    // If there are no cards under this one, just draw the place holder
    //
    if(numcards == 0)
    {
        switch(uEmptyImage)
        {
        case CS_EI_NONE:
            //no need! we've already cleared the whole
            //back-buffer before the main loop!
            //SetRect(&rect, 0, 0, __cardwidth, __cardheight);
            //PaintRect(hdcBackGnd, &rect, MAKE_PALETTERGB(crBackgnd));
            break;

        case CS_EI_SUNK:
            DrawCard(hdcBackGnd, 0, 0, __hdcPlaceHolder, __cardwidth, __cardheight);
            break;

        case CS_EI_CIRC:
        case CS_EI_X:
            CardBlt(hdc, 0, 0, uEmptyImage);
            break;
        }
    }

    //
    //    now render the drag-cards into the dragcard image
    //
    PaintRect(hdcDragCard, &rect, crBackgnd);

    for(icard = 0; icard < numtodrag; icard++)
    {
        Card card = dragstack.cardlist[icard];
        int nCardVal = card.FaceUp() ? card.Idx() : nBackCardIdx;

        CardBlt(hdcDragCard, xoffset * icard, yoffset * icard, nCardVal);
    }
}
Example #26
0
funcp geracod(FILE* f) {
    int c;
    int linha = 0;
    int vars[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
    int qtdVars = 0;
    int i = 0;
    int j = 0;
    int qtd_while = 0;
    Var_while v_while[10];

    // Alocando espaço na memória para gravar os bytes de instrucões
    codigo = (unsigned char*)malloc(sizeof(unsigned char) * 2048);

    if(codigo == NULL) {
        printf("Nao foi possivel alocar espaco para o codigo.\n");
        exit(1);
    }

    SB_prologo();
    inicia_var_while(v_while, 10);

	// Funcao principal de leitura
	// Analisa cada caso e chama as funcoes apropriadas
    while((c = fgetc(f)) != EOF) {
        switch(c) {

            // Retorno
            case 'r': {
                fscanf(f, "et");

				for(i=0; i<qtd_while; i++) {
					SB_completa_while(v_while[i]);
				}

                SB_retorno();
                break;
            }

            // Atribuição
            case 'v': case 'p': case '$': {
                Var v, v1, v2;
                char op;

                if(fscanf(f, "%d = %c%d %c %c%d", &v.valor, &v1.tipo, &v1.valor, &op, &v2.tipo, &v2.valor) != 6)
                    error("Comando invalido", linha);

                // Mantem uma contagem de quantas variaveis locais foram declaradas no arquivo codigo-fonte SB
                if(c == 'v') {
                    if(vars[v.valor] == -1) {
                        qtdVars++;
                        vars[v.valor] = 1;
                    }
                }

                v.tipo = c;
                checkVar(v, linha);
                if(v1.tipo != '$')
                    checkVar(v1, linha);

                if(v2.tipo != '$')
                    checkVar(v2, linha);

                // Prepara o offset de cada variável, caso não seja uma constante
                // Valor variando de '-4' em '-4' para variáveis locais
                // e variando de '4' em '4' (somado a 8 para o início) para parâmetros
		v.valor = calc_offset(v);
		v1.valor = calc_offset(v1);
		v2.valor = calc_offset(v2);

                SB_atribuicao(v, v1, v2, op);
                break;
            }

            // While
            case 'w': {

                // Este loop roda até achar o primeiro espaço disponível no vetor de struct Var_while
                // para salvar as informações da variável parâmetro da instrução 'while'
				for(i=0; i<10; i++) {
					if(v_while[i].byte_while == -1) {
						if(fscanf(f, "hile %c%d", &v_while[i].tipo, &v_while[i].valor) != 2)
							error("Comando Invalido", linha);
						if(v_while[i].tipo == '$')
							error("Comando Invalido", linha);

						if(v_while[i].tipo == 'v')
							v_while[i].valor = -(4 * v_while[i].valor) - 4;

						else if(v_while[i].tipo == 'p')
							v_while[i].valor = 4 * v_while[i].valor + 8;

						v_while[i].byte_while = SB_while();
						break;
					}
				}
				qtd_while++;
                break;
            }

            // End (while)
            case 'e': {
                // Este loop roda de trás para frente, até achar um espaço no qual uma instrução while
                // já tenha guardado valores na struct Var_while
                // e preenche o campo 'byte_end' e transforma 'ja_usado' em 1 (verdadeiro)
				for(j=9; j >= 0; j--) {
					if(v_while[j].byte_while != -1 && v_while[j].ja_usado != 1) {
						fscanf(f, "nd");
						v_while[j].byte_end = SB_end_while();
						v_while[j].ja_usado = 1;
						break;
					}
				}
                break;
            }

            default:
                error("Comando desconhecido", linha);
        }
        linha++;

        if(linha > MAX_LINHAS)
            error("Numero maximo de linhas excedido", linha);

        fscanf(f, " ");
    }

    // A variável 'qtdVars' serviu como contador de quantas variáveis locais há no código-fonte SB
    // e agora substituimos o byte responsável pela alocação de espaco (em bytes, sendo 4 para cada var. local)
    // através do comando 'sub $0x??, %esp'
    codigo[5] = qtdVars * 4;
    return (funcp)codigo;
}
Example #27
0
/* do everything we need to get the total average offset
 * - we use a certain amount of parallelization with poll() to ensure
 *   we don't waste time sitting around waiting for single packets.
 * - we also "manually" handle resolving host names and connecting, because
 *   we have to do it in a way that our lazy macros don't handle currently :( */
double offset_request(const char *host, int *status){
	int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
	int servers_completed=0, one_written=0, one_read=0, servers_readable=0, best_index=-1;
	time_t now_time=0, start_ts=0;
	ntp_message *req=NULL;
	double avg_offset=0.;
	struct timeval recv_time;
	struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
	struct pollfd *ufds=NULL;
	ntp_server_results *servers=NULL;

	/* setup hints to only return results from getaddrinfo that we'd like */
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = address_family;
	hints.ai_protocol = IPPROTO_UDP;
	hints.ai_socktype = SOCK_DGRAM;

	/* fill in ai with the list of hosts resolved by the host name */
	ga_result = getaddrinfo(host, "123", &hints, &ai);
	if(ga_result!=0){
		die(STATE_UNKNOWN, "error getting address for %s: %s\n",
		    host, gai_strerror(ga_result));
	}

	/* count the number of returned hosts, and allocate stuff accordingly */
	for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
	req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
	if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
	socklist=(int*)malloc(sizeof(int)*num_hosts);
	if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
	ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
	if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
	servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
	if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
	memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
	DBG(printf("Found %d peers to check\n", num_hosts));

	/* setup each socket for writing, and the corresponding struct pollfd */
	ai_tmp=ai;
	for(i=0;ai_tmp;i++){
		socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
		if(socklist[i] == -1) {
			perror(NULL);
			die(STATE_UNKNOWN, "can not create new socket");
		}
		if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
			/* don't die here, because it is enough if there is one server
			   answering in time. This also would break for dual ipv4/6 stacked
			   ntp servers when the client only supports on of them.
			 */
			DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
		} else {
			ufds[i].fd=socklist[i];
			ufds[i].events=POLLIN;
			ufds[i].revents=0;
		}
		ai_tmp = ai_tmp->ai_next;
	}

	/* now do AVG_NUM checks to each host.  we stop before timeout/2 seconds
	 * have passed in order to ensure post-processing and jitter time. */
	now_time=start_ts=time(NULL);
	while(servers_completed<num_hosts && now_time-start_ts <= socket_timeout/2){
		/* loop through each server and find each one which hasn't
		 * been touched in the past second or so and is still lacking
		 * some responses.  for each of these servers, send a new request,
		 * and update the "waiting" timestamp with the current time. */
		one_written=0;
		now_time=time(NULL);

		for(i=0; i<num_hosts; i++){
			if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
				if(verbose && servers[i].waiting != 0) printf("re-");
				if(verbose) printf("sending request to peer %d\n", i);
				setup_request(&req[i]);
				write(socklist[i], &req[i], sizeof(ntp_message));
				servers[i].waiting=now_time;
				one_written=1;
				break;
			}
		}

		/* quickly poll for any sockets with pending data */
		servers_readable=poll(ufds, num_hosts, 100);
		if(servers_readable==-1){
			perror("polling ntp sockets");
			die(STATE_UNKNOWN, "communication errors");
		}

		/* read from any sockets with pending data */
		for(i=0; servers_readable && i<num_hosts; i++){
			if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
				if(verbose) {
					printf("response from peer %d: ", i);
				}

				read(ufds[i].fd, &req[i], sizeof(ntp_message));
				gettimeofday(&recv_time, NULL);
				DBG(print_ntp_message(&req[i]));
				respnum=servers[i].num_responses++;
				servers[i].offset[respnum]=calc_offset(&req[i], &recv_time);
				if(verbose) {
					printf("offset %.10g\n", servers[i].offset[respnum]);
				}
				servers[i].stratum=req[i].stratum;
				servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
				servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
				servers[i].waiting=0;
				servers[i].flags=req[i].flags;
				servers_readable--;
				one_read = 1;
				if(servers[i].num_responses==AVG_NUM) servers_completed++;
			}
		}
		/* lather, rinse, repeat. */
	}

	if (one_read == 0) {
		die(STATE_CRITICAL, "NTP CRITICAL: No response from NTP server\n");
	}

	/* now, pick the best server from the list */
	best_index=best_offset_server(servers, num_hosts);
	if(best_index < 0){
		*status=STATE_UNKNOWN;
	} else {
		/* finally, calculate the average offset */
		for(i=0; i<servers[best_index].num_responses;i++){
			avg_offset+=servers[best_index].offset[i];
		}
		avg_offset/=servers[best_index].num_responses;
	}

	/* cleanup */
	/* FIXME: Not closing the socket to avoid re-use of the local port
	 * which can cause old NTP packets to be read instead of NTP control
	 * pactets in jitter_request(). THERE MUST BE ANOTHER WAY...
	 * for(j=0; j<num_hosts; j++){ close(socklist[j]); } */
	free(socklist);
	free(ufds);
	free(servers);
	free(req);
	freeaddrinfo(ai);

	if(verbose) printf("overall average offset: %.10g\n", avg_offset);
	return avg_offset;
}
Example #28
0
static AvbIOResult mmc_byte_io(AvbOps *ops,
			       const char *partition,
			       s64 offset,
			       size_t num_bytes,
			       void *buffer,
			       size_t *out_num_read,
			       enum mmc_io_type io_type)
{
	ulong ret;
	struct mmc_part *part;
	u64 start_offset, start_sector, sectors, residue;
	u8 *tmp_buf;
	size_t io_cnt = 0;

	if (!partition || !buffer || io_type > IO_WRITE)
		return AVB_IO_RESULT_ERROR_IO;

	part = get_partition(ops, partition);
	if (!part)
		return AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION;

	start_offset = calc_offset(part, offset);
	while (num_bytes) {
		start_sector = start_offset / part->info.blksz;
		sectors = num_bytes / part->info.blksz;
		/* handle non block-aligned reads */
		if (start_offset % part->info.blksz ||
		    num_bytes < part->info.blksz) {
			tmp_buf = get_sector_buf();
			if (start_offset % part->info.blksz) {
				residue = part->info.blksz -
					(start_offset % part->info.blksz);
				if (residue > num_bytes)
					residue = num_bytes;
			} else {
				residue = num_bytes;
			}

			if (io_type == IO_READ) {
				ret = mmc_read_and_flush(part,
							 part->info.start +
							 start_sector,
							 1, tmp_buf);

				if (ret != 1) {
					printf("%s: read error (%ld, %lld)\n",
					       __func__, ret, start_sector);
					return AVB_IO_RESULT_ERROR_IO;
				}
				/*
				 * if this is not aligned at sector start,
				 * we have to adjust the tmp buffer
				 */
				tmp_buf += (start_offset % part->info.blksz);
				memcpy(buffer, (void *)tmp_buf, residue);
			} else {
				ret = mmc_read_and_flush(part,
							 part->info.start +
							 start_sector,
							 1, tmp_buf);

				if (ret != 1) {
					printf("%s: read error (%ld, %lld)\n",
					       __func__, ret, start_sector);
					return AVB_IO_RESULT_ERROR_IO;
				}
				memcpy((void *)tmp_buf +
					start_offset % part->info.blksz,
					buffer, residue);

				ret = mmc_write(part, part->info.start +
						start_sector, 1, tmp_buf);
				if (ret != 1) {
					printf("%s: write error (%ld, %lld)\n",
					       __func__, ret, start_sector);
					return AVB_IO_RESULT_ERROR_IO;
				}
			}

			io_cnt += residue;
			buffer += residue;
			start_offset += residue;
			num_bytes -= residue;
			continue;
		}

		if (sectors) {
			if (io_type == IO_READ) {
				ret = mmc_read_and_flush(part,
							 part->info.start +
							 start_sector,
							 sectors, buffer);
			} else {
				ret = mmc_write(part,
						part->info.start +
						start_sector,
						sectors, buffer);
			}

			if (!ret) {
				printf("%s: sector read error\n", __func__);
				return AVB_IO_RESULT_ERROR_IO;
			}

			io_cnt += ret * part->info.blksz;
			buffer += ret * part->info.blksz;
			start_offset += ret * part->info.blksz;
			num_bytes -= ret * part->info.blksz;
		}
	}

	/* Set counter for read operation */
	if (io_type == IO_READ && out_num_read)
		*out_num_read = io_cnt;

	return AVB_IO_RESULT_OK;
}
Example #29
0
void categorize(Int16 number_of_available_bits,
		        Int16 *rms_index,
		        Int16 *power_categories,
		        Int16 *category_balances)
{
    Int16 offset;
    Int16 temp, temp1;

    /* At higher bit rates, there is an increase for most categories in
       average bit consumption per region. We compensate for this by
       pretending we have fewer available bits. */

    temp = sub(number_of_available_bits, gDct_length);

    if (temp > 0)
    {
		temp1 = temp >> 2;
		temp = temp + temp1;
        number_of_available_bits = temp >> 1;
        number_of_available_bits += gDct_length;
    }

    /* calculate the offset using the original category assignments */
    offset = calc_offset(rms_index, number_of_available_bits);

    /* adjust the category assignments */
    /* compute the new power categories and category balances */
    comp_powercat_and_catbalance(power_categories,category_balances,rms_index,number_of_available_bits, offset);
}

/**
@brief		set up an SBD RB

(1) build an SBD RB instance in the kernel space\n
(2) allocate an SBD array in SHMEM\n
(3) allocate a data buffer array in SHMEM if possible\n
*/
static int setup_sbd_rb(struct sbd_link_device *sl, struct sbd_ring_buffer *rb,
			enum direction dir, struct sbd_link_attr *link_attr)
{
	unsigned int alloc_size;
	int i;

	rb->sl = sl;

	rb->lnk_hdr = link_attr->lnk_hdr;

	rb->more = false;
	rb->total = 0;
	rb->rcvd = 0;

	/*
	Initialize an SBD RB instance in the kernel space.
	*/
	rb->id = link_attr->id;
	rb->ch = link_attr->ch;
	rb->dir = dir;
	rb->len = link_attr->rb_len[dir];
	rb->buff_size = link_attr->buff_size[dir];
	rb->payload_offset = 0;

	/*
	Prepare array of pointers to the data buffer for each SBD
	*/
	alloc_size = (rb->len * sizeof(u8 *));
	rb->buff = kmalloc(alloc_size, GFP_ATOMIC);
	if (!rb->buff)
		return -ENOMEM;

	/*
	(1) Allocate an array of data buffers in SHMEM.
	(2) Register the address of each data buffer.
	*/
	alloc_size = (rb->len * rb->buff_size);
	rb->buff_rgn = (u8 *)buff_alloc(sl, alloc_size);
	if (!rb->buff_rgn)
		return -ENOMEM;

	for (i = 0; i < rb->len; i++)
		rb->buff[i] = rb->buff_rgn + (i * rb->buff_size);

#if 0
	mif_err("RB[%d:%d][%s] buff_rgn {addr:0x%08X offset:%d size:%d}\n",
		rb->id, rb->ch, udl_str(dir), (int)rb->buff_rgn,
		calc_offset(rb->buff_rgn, sl->shmem), alloc_size);
#endif

	/*
	Prepare SBD array in SHMEM.
	*/
	rb->rp = &sl->rp[rb->dir][rb->id];
	rb->wp = &sl->wp[rb->dir][rb->id];

	alloc_size = (rb->len * sizeof(u32));

	rb->addr_v = (u32 *)desc_alloc(sl, alloc_size);
	if (!rb->addr_v)
		return -ENOMEM;

	rb->size_v = (u32 *)desc_alloc(sl, alloc_size);
	if (!rb->size_v)
		return -ENOMEM;

	/*
	Register each data buffer to the corresponding SBD.
	*/
	for (i = 0; i < rb->len; i++) {
		rb->addr_v[i] = calc_offset(rb->buff[i], sl->shmem);
		rb->size_v[i] = 0;
	}

	rb->iod = link_get_iod_with_channel(sl->ld, rb->ch);
	rb->ld = sl->ld;

	return 0;
}