Пример #1
0
void ToneMappingDrago03::toneMapping_Drago03(Image<float> *img, float *avLum, float *maxLum, unsigned int *pic, float bias)
{
	image = img;
	picture = pic;

	avLuminance = avLum;
	maxLuminance = maxLum;

	normMaxLum = *maxLum / *avLum; // normalize maximum luminance by average luminance
	const float LOG05 = -0.693147f; // log(0.5)

	divider = log10(normMaxLum + 1.0f);
	biasP = log(bias)/LOG05;
	logFile("divider = %f biasP = %f \n", divider, biasP);

	localWorkSize[0] = BLOCK_SIZE;
	localWorkSize[1] = BLOCK_SIZE;
	
	//round values on upper value
	logFile("%d %d \n", image->getHeight(), image->getWidth());
	globalWorkSize[0] = roundUp(BLOCK_SIZE, image->getHeight());
	globalWorkSize[1] = roundUp(BLOCK_SIZE, image->getWidth());

	//core->runComputeUnit();
	
	
	
	CStopWatch timer;
	timer.startTimer();
	calctoneMapping_Drago03CPU();
	timer.stopTimer();
	logFile("ToneMappingCPU,calc_time, , ,%f, \n", timer.getElapsedTime());
}
Пример #2
0
Файл: du.c Проект: eskirk/MyDu
/*
   Similar to displayAll(), but only prints out folders and the size of those folders
   Also recursively enters sub-directories
*/
void displayFolders(DIR *directory, char *path, long *total, int depth, int human) {
   char *temp = malloc(sizeof(char) * MAX_LEN);
   char *curPath = malloc(sizeof(char) * MAX_LEN);
   struct dirent *tempdir = malloc(sizeof(struct dirent));
   struct stat *stats = malloc(sizeof(struct stat));

   if (directory) {
      while ((tempdir = readdir(directory))) {
         if ((path == NULL) && checkDir(tempdir->d_name) && strcmp(tempdir->d_name, "..") != 0 &&
          strcmp(tempdir->d_name, ".") != 0)
            sprintf(curPath, "./%s", tempdir->d_name);
         else if (checkDir(tempdir->d_name) && strcmp(tempdir->d_name, "..") != 0 && 
          strcmp(tempdir->d_name, ".") != 0)
            sprintf(curPath, "%s/%s", path, tempdir->d_name);

         if (checkDir(tempdir->d_name) && strcmp(tempdir->d_name, "..") != 0 &&
          strcmp(tempdir->d_name, ".") != 0 && depth > 0) {
            sprintf(temp, "./%s", tempdir->d_name);
            chdir(tempdir->d_name);
            displayFolders(opendir("."), curPath, total, depth - 1, human);
            chdir("..");
            lstat(tempdir->d_name, stats);
            *total += roundUp((stats->st_size + (BLOCKSIZE - 1)) / BLOCKSIZE);
            if (!human)
               printf("%d\t%s\n", roundUp((int)(stats->st_size + (BLOCKSIZE - 1)) / BLOCKSIZE), curPath);
            if (human)
               printHuman(stats, -1, curPath);
         }
      }
   }
}
void DateTimeNumericFieldElement::stepUp() {
  int newValue = roundUp(m_hasValue ? m_value + 1 : defaultValueForStepUp());
  if (!m_range.isInRange(newValue))
    newValue = roundUp(m_range.minimum);
  m_typeAheadBuffer.clear();
  setValueAsInteger(newValue, DispatchEvent);
}
void Draft::startDraft(Team *arr, vector<NodeData*>& a, int nTeams, WINDOW **board){
	int pickN, round = 0;
	srand(time(0));

	roundUp(++round, board[34]);

	while(round < 16){
		pickN = 0;

		for(int i = 0; i < nTeams; i++){
			if(arr[i].getUser()){
				pick(arr[i], a, board, pickN);
			}
			else if(!arr[i].getUser()){
				autoP(arr[i], a, board, pickN);
			}
			pickN++;
		}
		roundUp(++round, board[34]);
		for(int i = (nTeams - 1); i > -1; i--){
			if(arr[i].getUser())
				pick(arr[i], a, board, pickN);
			else if(!arr[i].getUser())
				autoP(arr[i], a, board, pickN);
			pickN++;
		}
		roundUp(++round, board[34]);
		clearBoard(board);
	}
}
Пример #5
0
void FDMHeatWidget::updateSystemTexture()
{
    cl_int error;

    error= clEnqueueAcquireGLObjects(clQueue, 1, &textureMem, 0, 0, 0);
    if(checkError(error, "clEnqueueAcquireGLObjects"))
        return;

    // Work group y NDRange de renderKernel
    size_t workGroupSize[2] = { 16, 16 };
    size_t ndRangeSize[2];
    ndRangeSize[0]= roundUp(system->getWidth(), workGroupSize[0]);
    ndRangeSize[1]= roundUp(system->getHeight(), workGroupSize[1]);

    bool suspended= system->isSuspended();
    if(!suspended)
        system->suspend();

    // Ejecutamos el kernel para renderizar el sistema en una imagen
    cl_mem systemData= system->getOutputData();
    error  = clSetKernelArg(renderKernel, 0, sizeof(cl_mem), (void*)&systemData);
    error |= clSetKernelArg(renderKernel, 1, sizeof(cl_mem), (void*)&textureMem);
    error |= clSetKernelArg(renderKernel, 2, sizeof(cl_mem), (void*)&paletteMem);

    error |= clEnqueueNDRangeKernel(clQueue, renderKernel, 2, NULL, ndRangeSize, workGroupSize, 0, NULL, NULL);
    checkError(error, "FDMHeatWidget::updateSystemTexture: clEnqueueNDRangeKernel");

    if(!suspended)
        system->resume();

    error= clEnqueueReleaseGLObjects(clQueue, 1, &textureMem, 0, 0, 0);
    if (checkError(error, "clEnqueueReleaseGLObjects"))
        return;
}
Пример #6
0
void Resistor::moveResistor(int x, int y, bool stepMode) {
	if (stepMode) {
		rPos.x = roundUp(x);
		rPos.y = roundUp(y);
	}
	else {
		rPos.x = x;
		rPos.y = y;
	}
}
Пример #7
0
/**
 * Sets up memory location
 */
void mm_initialize(u32int initrd_location){
  initrd_location = initrd_location;
  //Get the memory map from the multiboot_info
  multiboot_memory_map_t* mmap = (multiboot_memory_map_t*)mbt->mmap_addr;

  //loop through the memory map for a usable (1) portion that is bigger than 0x1000000
  while((u32int)mmap < (mbt->mmap_addr + mbt->mmap_length)) {
    if(mmap->type == 1 && mmap->len > 0x1000000){
      //if found, save that memLoc and memAmt for later use
      memLoc = /*(u32int*)*/mmap->addr;
      memAmt = mmap->len;
    }
    mmap = (multiboot_memory_map_t*) ( (unsigned int)mmap + mmap->size + sizeof(mmap->size) );
   // mmap = (multiboot_memory_map_t) ( (unsigned int)mmap + mmap.size + sizeof(mmap.size) );
  }

  /* Calculate the initrd (ramdisk size) */
  initrd_end = *(u32int*)(mbt->mods_addr+4);
  initrd_size = initrd_end - initrd_location;

  /* Only used to display the start location of Ram, then promptly forgotten */
  u32int startOfRam = memLoc;

  /* Calculate a pointer to the end of physical memory. */
  memEndLoc = memLoc + memAmt;


  /* Add the size of the kernel to memLoc at the nearest 4kb boundry */
  memLoc += roundUp(end - code, 4096); 

  /* Add the size of the initrd to memLoc at the nearest 4kb boundry */
  memLoc += roundUp(initrd_size, 4096); 


  /* Calculate the amount of memory that is usable for heap allocation after kernel*/
  memUsable = memEndLoc - memLoc;

  printf("\nEnd of Kernel           : 0x%x", (u32int) end);
  printf("\nStart of Kernel         : 0x%x", (u32int) code);
  printf("\nSize of Kernel          : 0x%x", (u32int)(end - code));

  printf("\nMemory Found At Location: 0x%x", (u32int) startOfRam);
  printf("\nMemory Amount Located   : 0x%x", memAmt);
  printf("\nEnd of Physical Memory : 0x%x", (u32int) memEndLoc);
  printf("\nInitrd Starts At       : 0x%x", initrd_location);
  printf("\nInitrd Ends At         : 0x%x", initrd_end);
  printf("\nInitrd Size            : 0x%x",  initrd_size);
  printf("\nUsable Memory Starts At: 0x%x", (u32int) memLoc);
  printf("\nUsable Amount of Memory: 0x%x", memUsable);
  placement_address = (u32int)memLoc;
  //while(1);
}
Пример #8
0
gliGenericImage *
loadTextureDecal(gliGenericImage *image, int mipmap)
{
  int needsScaling;
  int nw, nh;

  nw = roundUp(image->width);
  nh = roundUp(image->height);

  if ((nw != image->width) || (nh != image->height)) {
    needsScaling = 1;
  } else {
    needsScaling = 0;
  }
  assert(image->format != GL_COLOR_INDEX);
  if (needsScaling) {
    gliGenericImage *nimage;
      
    nimage = gliScaleImage(image, nw, nh);
    gliFree(image);
    image = nimage;
  }

#ifdef __APPLE__
  mipmap = 0;  /* Why doesn't Apple's gluBuild2DMipmaps work correctly? */
#endif
  if (mipmap) {
    GLint status;

    glTexParameteri(GL_TEXTURE_2D,
      GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    status = gluBuild2DMipmaps(GL_TEXTURE_2D, image->internalFormat,
      nw, nh, image->format, image->type, image->pixels);
    if (status == GLU_INVALID_ENUM) {
      gliConvertImageToCoreFormat(image);
      status = gluBuild2DMipmaps(GL_TEXTURE_2D, image->internalFormat,
        nw, nh, image->format, image->type, image->pixels);
    }
    assert(status == 0);
  } else {
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, image->internalFormat,
      nw, nh, 0,
      image->format, image->type, image->pixels);
  }

  return image;
}
Пример #9
0
//--------------------------------------------------------------
void SalsaScreen::setup()
{
    mainWindowWidth = config.mainWindowWidth;
    
    player.loadSound("sounds/Salsa_instructions.mp3");
    player.setVolume(0.75f);
    player.setMultiPlay(false);
    
    intervall1 = 800; // in ms
    intervall1 = roundUp(intervall1/100);
    intervall2 = 500; // quicker
    intervall2 = roundUp(intervall2/100);
    
    startPlayerPos_R1   =  20800;   // individual
    stopPlayerPos_R1    =  39800;
    startPlayerPos_R2   =  47500;   // move forwards
    stopPlayerPos_R2    =  66599;
    startPlayerPos_R3   =  66600;   // partner
    stopPlayerPos_R3    =  92900;
    startPlayerPos_R4   =  92901;   // faster
    stopPlayerPos_R4    = 115900;
    startPlayerPos_R1 = roundUp(startPlayerPos_R1 /100);
    stopPlayerPos_R1  = roundUp(stopPlayerPos_R1  /100);
    startPlayerPos_R2 = roundUp(startPlayerPos_R2 /100);
    stopPlayerPos_R2  = roundUp(stopPlayerPos_R2  /100);
    startPlayerPos_R3 = roundUp(startPlayerPos_R3 /100);
    stopPlayerPos_R3  = roundUp(stopPlayerPos_R3  /100);
    startPlayerPos_R4 = roundUp(startPlayerPos_R4 /100);
    stopPlayerPos_R4  = roundUp(stopPlayerPos_R4  /100);
    
    prevPlayerPos = startPlayerPos_R1;
    
    // CHOREOGRAPHY --------------------------------------------
    currentStep = 0;
    isStart = true;
    
    boxWidth    = 0;
    boxHeight   = 300;
    role = salsaChoreo.init(0, 0, boxWidth, boxHeight, "Salsa");
    
    // position of each couple
    cX1 = config.mainWindowWidth/4-boxHeight/3;
    cY1 = config.mainWindowHeight/4;
    cX2 = config.mainWindowWidth*3/4-boxHeight+boxHeight/3;
    cY2 = config.mainWindowHeight*3/4;
    
    // lift icon - resize
    newIconSize = config.iconSize;
    biconWasBig = false;
}
Пример #10
0
void GLWidget::runKernel() 
{
    cl_int error;
    
    // block until all gl functions are completed
    glFinish();
    // Le doy a OpenCL el vbo que estaba usando OpenGL para renderizar
    error = clEnqueueAcquireGLObjects(clQueue, 1, &clvbo, 0, 0, 0);
    if (checkError(error, "clEnqueueAcquireGLObjects")) {
	return;
    }

    localWorkSize = 1024;
    globalWorkSize = roundUp(vertexNumber, localWorkSize);
    
    error = clEnqueueNDRangeKernel(clQueue, clKernel, 1, NULL, &globalWorkSize, &localWorkSize, 0, 0, 0);
    if (checkError(error, "clEnqueueNDRangeKernel")) {
	return;
    }

    // unmap buffer object
    error = clEnqueueReleaseGLObjects(clQueue, 1, &clvbo, 0, 0, 0);
    if (checkError(error, "clEnqueueReleaseGLObjects")) {
	return;
    }

    clFinish(clQueue);

}
Пример #11
0
static void
calcNrThreads(
    size_t threads[2],
    const SubproblemDim *subdims,
    const PGranularity *pgran,
    const void *args,
    const void *extra)
{
    size_t yLen;     /* Length of "Y" vector */
    const CLBlasKargs *kargs = args;
    unsigned int subgr = pgran->wgSize[0] / (subdims[0].bwidth / subdims[1].bwidth);

    (void)subdims;
    (void)extra;

    yLen = kargs->transA == clblasNoTrans ? kargs->M : kargs->N;

    if (yLen == 0) {
        yLen = 1;
        //launch one group to avoid CL_INVALID_WORK_GROUP_SIZE error
    }

    //each work item handles y1 lines
    threads[0] = divRoundUp(yLen, subdims[1].y) * subgr;
    threads[0] = roundUp(threads[0], pgran->wgSize[0]);
    threads[1] = 0;
}
Пример #12
0
	void find(double* ptr, size_t size,  double& min, double &max)
	{

		size_t num_wg = 64;
		size_t num_compute_units = 6;
		size_t workgroup_size = 256;

		size_t global_size = num_wg * num_compute_units;

		m_result_min.resize( global_size);
		m_result_max.resize( global_size);

		m_args.p_values = ptr;
		m_args.size = size;
		m_args.p_min_list = &m_result_min[0];
		m_args.p_max_list = &m_result_max[0];
		hsa_signal_t signal;
		Launch_params_t lp {.ndim=1, .gdims={std::min(roundUp(size, workgroup_size), global_size*workgroup_size)}, .ldims={workgroup_size}};
		m_dispatch->dispatchKernel(m_args, signal, lp);
		m_dispatch->waitComplete(signal);
		if (size < workgroup_size)
		{
			min = ptr[ m_result_min[0]];
			max = ptr[ m_result_max[0]];
		}
		return reduce(ptr, size, min,max);
	}
protected:
Пример #13
0
void kma_free(void* ptr, kma_size_t size)
{
  size = roundUp(size);
  kma_page_t *page = *((kma_page_t **) BASEADDR(ptr));
  if (diff(size) == 8) { //if 8196, free the page
    free_page(page);
    PAGE_COUNT--;
  } else {
    page->size += size;
    if (page->size == PAGESIZE - sizeof(kma_page_t*)) {
      derefPage(page->ptr, size); //if page is made of free buffers, derefence the buffer in freelist
      free_page(page);
      PAGE_COUNT--;
    } else {  //not all free, give the buffer back to freelist
      insertAtHead(ptr, size);
    }
  }
  //free everything
  if(PAGE_COUNT == 1) {
    free_page(FREEPAGE);
    INIT = FALSE;
    PAGE_COUNT = 0;
    FREE_LIST_HEAD = NULL;
  }
}
Пример #14
0
//------------------------------------------------------------------------
// ArenaAllocator::alloateMemory:
//    Allocates memory using an `ArenaAllocator`.
//
// Arguments:
//    size - The number of bytes to allocate.
//
// Return Value:
//    A pointer to the allocated memory.
//
// Note:
//    This is the DEBUG-only version of `allocateMemory`; the release
//    version of this method is defined in the corresponding header file.
//    This version of the method has some abilities that the release
//    version does not: it may inject faults into the allocator and
//    seeds all allocations with a specified pattern to help catch
//    use-before-init problems.
void* ArenaAllocator::allocateMemory(size_t size)
{
    assert(size != 0 && (size & (sizeof(int) - 1)) == 0);

    // Ensure that we always allocate in pointer sized increments.
    size = (size_t)roundUp(size, sizeof(size_t));

    if (JitConfig.ShouldInjectFault() != 0)
    {
        // Force the underlying memory allocator (either the OS or the CLR hoster) 
        // to allocate the memory. Any fault injection will kick in.
        void* p = ClrAllocInProcessHeap(0, S_SIZE_T(1));
        if (p != nullptr)
        {
            ClrFreeInProcessHeap(0, p);
        }
        else 
        {
            NOMEM();  // Throw!
        }
    }

    void* block = m_nextFreeByte;
    m_nextFreeByte += size;

    if (m_nextFreeByte > m_lastFreeByte)
    {
        block = allocateNewPage(size);
    }

    memset(block, UninitializedWord<char>(), size);
    return block;
}
Пример #15
0
	double transform(double* ptr, size_t size)
	{

		size_t num_wg = 64;
		size_t num_compute_units = 6;
		size_t global_size = num_wg * num_compute_units;
		size_t workgroup_size = 256;

		m_result.resize( global_size);


		m_local_dispatch->clearArgs();
		FIX_ARGS_STABLE(m_local_dispatch);

		m_local_dispatch->pushPointerArg((void*)ptr);
		m_local_dispatch->pushIntArg((int)size );
		m_local_dispatch->pushPointerArg((void*)&m_result[0]);
		size_t global_dims[3] = { std::min(roundUp(size, workgroup_size), global_size*workgroup_size),1,1};
		size_t local_dims[3] = {workgroup_size,1,1};
		m_local_dispatch->setLaunchAttributes(1, global_dims,  local_dims);
		m_local_dispatch->dispatchKernelWaitComplete();
		if (size < workgroup_size)
		{
			return m_result[0];
		}
		return reduceTail(size);
	}
Пример #16
0
gl::Error VertexBufferInterface::reserveVertexSpace(const gl::VertexAttribute &attrib, GLsizei count, GLsizei instances)
{
    gl::Error error(GL_NO_ERROR);

    unsigned int requiredSpace;
    error = mVertexBuffer->getSpaceRequired(attrib, count, instances, &requiredSpace);
    if (error.isError())
    {
        return error;
    }

    // Protect against integer overflow
    if (mReservedSpace + requiredSpace < mReservedSpace)
    {
        return gl::Error(GL_OUT_OF_MEMORY, "Unable to reserve %u extra bytes in internal vertex buffer, "
                         "it would result in an overflow.", requiredSpace);
    }

    mReservedSpace += requiredSpace;

    // Align to 16-byte boundary
    mReservedSpace = roundUp(mReservedSpace, 16u);

    return gl::Error(GL_NO_ERROR);
}
Пример #17
0
PassRefPtr<MetaAllocatorHandle> MetaAllocator::allocate(size_t sizeInBytes, void* ownerUID)
{
    SpinLockHolder locker(&m_lock);

    if (!sizeInBytes)
        return 0;
    
    sizeInBytes = roundUp(sizeInBytes);
    
    void* start = findAndRemoveFreeSpace(sizeInBytes);
    if (!start) {
        size_t requestedNumberOfPages = (sizeInBytes + m_pageSize - 1) >> m_logPageSize;
        size_t numberOfPages = requestedNumberOfPages;
        
        start = allocateNewSpace(numberOfPages);
        if (!start)
            return 0;
        
        ASSERT(numberOfPages >= requestedNumberOfPages);
        
        size_t roundedUpSize = numberOfPages << m_logPageSize;
        
        ASSERT(roundedUpSize >= sizeInBytes);
        
        m_bytesReserved += roundedUpSize;
        
        if (roundedUpSize > sizeInBytes) {
            void* freeSpaceStart = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(start) + sizeInBytes);
            size_t freeSpaceSize = roundedUpSize - sizeInBytes;
            addFreeSpace(freeSpaceStart, freeSpaceSize);
        }
    }
Пример #18
0
static int processData( const CRYPT_CONTEXT cryptContext, BYTE *buffer,
						const int noBlocks, const int blockSize,
						CRYPT_FUNCTION cryptFunction )
	{
	int offset = 0, i, status;

	/* Encrypt the data in variable-length blocks.  The technique for
	   selecting lengths isn't perfect since it tends to put large blocks
	   at the start and small ones at the end, but it's good enough for
	   general testing */
	for( i = 0; i < noBlocks - 1; i++ )
		{
		int noBytes = rand() % ( DATABUFFER_SIZE - offset - \
								 ( blockSize * ( noBlocks - i  ) ) );
		if( !noBytes )
			noBytes = 1;
		if( blockSize > 1 )
			noBytes = roundUp( noBytes, blockSize );
		status = cryptFunction( cryptContext, buffer + offset, noBytes );
		if( cryptStatusError( status ) )
			return( status );
		offset += noBytes;
		}
	status = cryptFunction( cryptContext, buffer + offset,
							DATABUFFER_SIZE - offset );
	if( cryptStatusOK( status ) )
		status = cryptFunction( cryptContext, "", 0 );
	return( status );
	}
Пример #19
0
Resistor::Resistor(bool vertical, int x, int y, bool stepMode) {
	value = 1000;
	this->horizontal = vertical;
	if (stepMode) {
		rPos.x = roundUp(x);
		rPos.y = roundUp(y);
	}
	else {
		rPos.x = x;
		rPos.y = y;
	}
	ptr2brother = -1;
	ptr2father = -1;
	ptr2son = -1;
	ptr2stepBro = -1;
}
Пример #20
0
quint32 indentForCenteredDimensions(const quint32 outerDimension,const quint32 innerDimension)
{
	if (outerDimension < innerDimension)
		return 0;

	return roundUp(((qreal)(outerDimension-innerDimension))/2.0);
}
Пример #21
0
void task_free(Task *t) {
	ASSERT_int_disable();
	ASSERT(t == task_curr);

	ipc_task_free(t);
	task_curr_free_files();

	uint32_t count_brk = (roundUp(t->pgdir.end_brk) - roundDown(t->pgdir.start_brk)) / 0x1000;
	/* code, heap ve stack alanlari toplami user alanina esit olmali */
	ASSERT(t->pgdir.count_stack + t->pgdir.count_program + count_brk ==
		   t->pgdir.count_user);
	task_free_vm_user(t);
	ASSERT(t->pgdir.count_user == 0);

	/*
	 * kernel stack ve pagedir daha sonra zombie list uzerinden silinecek.
	 * task structini bulundugu listeden cikar, zombie olarak isaretle ve
	 * task_zombie_list'e ekle.
	 */
	t->list_node.__list->erase(t->list_node.get_iterator());
	t->state = Task::State_zombie;
	task_zombie_list.push_back(&t->list_node);

	if (t->alarm_list_node.__list)
		t->alarm_list_node.__list->erase(&t->alarm_list_node);
}
Пример #22
0
GHash::GHash( size_t init_size, hash_fn hf, val_comp vc )
    : m_capacity( 0 )
    , m_size( 0 )
    , m_full_factor( 2 )
    , m_hf( hf )
    , m_vc( vc )
    , m_grow_factor( 2 )
{
    if ( m_hf )
    {
        assert( m_vc );
        m_insert = insert_p;
        m_update = update_p;
        m_find = find_p;
    }
    else
    {
        m_insert = insert_num;
        m_update = update_num;
        m_find = find_num;
    }
    init_size = roundUp( init_size );
    m_table = (HashElem **)malloc( init_size * sizeof( HashElem*) );
    if ( !m_table )
        throw std::bad_alloc();
    ::memset( m_table, 0, init_size * sizeof( HashElem*) );
    m_capacity = init_size;
    m_tableEnd = m_table + init_size;
}
Пример #23
0
quint32 MemoryTablePrivate::allocate(quint32 size, TableMetadata *table, bool indexRequired)
{
    const quint32 availableSpace = freeSpace(table);
    if (indexRequired) {
        // Even if satisfied from the free list, this allocation requires there to be space for expanded index
        if (availableSpace < sizeof(IndexElement)) {
            return 0;
        }
    }

    // Align the allocation so that the header is directly accessible
    quint32 allocationSize = static_cast<quint32>(requiredSpace(size));
    allocationSize = roundUp(allocationSize, sizeof(quint32));

    if (table->freeList) {
        // Try to reuse a freed block
        quint32 *bestOffset = 0;
        Allocation *bestBlock = 0;

        quint32 *freeOffset = &table->freeList;
        while (*freeOffset) {
            Allocation *freeBlock = allocationAt(*freeOffset, table);
            if (freeBlock->size >= allocationSize) {
                // This block is large enough
                if (!bestBlock || bestBlock->size > freeBlock->size) {
                    // It's our best fit so far
                    bestBlock = freeBlock;
                    bestOffset = freeOffset;
                }
            }

            freeOffset = &freeBlock->nextOffset;
        }

        if (bestOffset) {
            // TODO: if this block is too large, should it be partitioned?
            quint32 rv = *bestOffset;
            *bestOffset = bestBlock->nextOffset;
            return rv;
        }
    }

    // Is there enough space for this allocation?
    if (availableSpace < (allocationSize + (indexRequired ? sizeof(IndexElement) : 0))) {
        return 0;
    }

    // Allocate the space immediately below the already-allocated space
    table->freeOffset -= allocationSize;

    Allocation *allocation = allocationAt(table->freeOffset, table);
    allocation->size = allocationSize;

    return table->freeOffset;
}
Пример #24
0
void Buffer11::NativeStorage::fillBufferDesc(D3D11_BUFFER_DESC* bufferDesc, Renderer11 *renderer,
                                                     BufferUsage usage, unsigned int bufferSize)
{
    bufferDesc->ByteWidth = bufferSize;
    bufferDesc->MiscFlags = 0;
    bufferDesc->StructureByteStride = 0;

    switch (usage)
    {
      case BUFFER_USAGE_STAGING:
        bufferDesc->Usage = D3D11_USAGE_STAGING;
        bufferDesc->BindFlags = 0;
        bufferDesc->CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
        break;

      case BUFFER_USAGE_VERTEX_OR_TRANSFORM_FEEDBACK:
        bufferDesc->Usage = D3D11_USAGE_DEFAULT;
        bufferDesc->BindFlags = D3D11_BIND_VERTEX_BUFFER;

        if (renderer->isES3Capable())
        {
            bufferDesc->BindFlags |= D3D11_BIND_STREAM_OUTPUT;
        }

        bufferDesc->CPUAccessFlags = 0;
        break;

      case BUFFER_USAGE_INDEX:
        bufferDesc->Usage = D3D11_USAGE_DEFAULT;
        bufferDesc->BindFlags = D3D11_BIND_INDEX_BUFFER;
        bufferDesc->CPUAccessFlags = 0;
        break;

      case BUFFER_USAGE_PIXEL_UNPACK:
        bufferDesc->Usage = D3D11_USAGE_DEFAULT;
        bufferDesc->BindFlags = D3D11_BIND_SHADER_RESOURCE;
        bufferDesc->CPUAccessFlags = 0;
        break;

      case BUFFER_USAGE_UNIFORM:
        bufferDesc->Usage = D3D11_USAGE_DYNAMIC;
        bufferDesc->BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        bufferDesc->CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

        // Constant buffers must be of a limited size, and aligned to 16 byte boundaries
        // For our purposes we ignore any buffer data past the maximum constant buffer size
        bufferDesc->ByteWidth = roundUp(bufferDesc->ByteWidth, 16u);
        bufferDesc->ByteWidth = std::min<UINT>(bufferDesc->ByteWidth, renderer->getRendererCaps().maxUniformBlockSize);
        break;

      default:
        UNREACHABLE();
    }
}
Пример #25
0
void Rationalizer::FixupIfSIMDLocal(GenTreeLclVarCommon* node)
{
#ifdef FEATURE_SIMD
    if (!comp->featureSIMD)
    {
        return;
    }

    LclVarDsc* varDsc = &(comp->lvaTable[node->gtLclNum]);

    // Don't mark byref of SIMD vector as a SIMD type.
    // Note that struct args though marked as lvIsSIMD=true,
    // the tree node representing such an arg should not be
    // marked as a SIMD type, since it is a byref of a SIMD type.
    if (!varTypeIsSIMD(varDsc))
    {
        return;
    }
    switch (node->OperGet())
    {
        default:
            // Nothing to do for most tree nodes.
            break;

        case GT_LCL_FLD:
            // We may see a lclFld used for pointer-sized structs that have been morphed, in which
            // case we can change it to GT_LCL_VAR.
            // However, we may also see a lclFld with FieldSeqStore::NotAField() for structs that can't
            // be analyzed, e.g. those with overlapping fields such as the IL implementation of Vector<T>.
            if ((node->AsLclFld()->gtFieldSeq == FieldSeqStore::NotAField()) && (node->AsLclFld()->gtLclOffs == 0) &&
                (node->gtType == TYP_I_IMPL) && (varDsc->lvExactSize == TARGET_POINTER_SIZE))
            {
                node->SetOper(GT_LCL_VAR);
                node->gtFlags &= ~(GTF_VAR_USEASG);
            }
            else
            {
                // If we access a field of a SIMD lclVar via GT_LCL_FLD, it cannot have been
                // independently promoted.
                assert(comp->lvaGetPromotionType(varDsc) != Compiler::PROMOTION_TYPE_INDEPENDENT);
                return;
            }
            break;
        case GT_STORE_LCL_FLD:
            assert(node->gtType == TYP_I_IMPL);
            node->SetOper(GT_STORE_LCL_VAR);
            node->gtFlags &= ~(GTF_VAR_USEASG);
            break;
    }
    unsigned simdSize = (unsigned int)roundUp(varDsc->lvExactSize, TARGET_POINTER_SIZE);
    node->gtType      = comp->getSIMDTypeForSize(simdSize);
#endif // FEATURE_SIMD
}
Пример #26
0
void AbgasTemperatureView(void)
{
	uint16_t	i,y;
	MEASUREMENT_VIEW_struct * viewMem = pt100_getViewMem();
	LCD_ClearScreen();
	LCD_SetPenColor(1);
	LCD_SetFont(0);
	LCD_PrintXY(30,0,"ABGAS:");
	LCD_PrintXY(80,0,viewMem->cur_value);
		
	LCD_SetFont(0);
	
  int max = roundUp(viewMem->max);
  int min  = roundDown(viewMem->min);
  int diff = max-min;
  int span;
  if(!diff) {
    span = 10;
    if(min) min -= 10;
  }else {
    span = diff/3;
  }
  
  if(span < 10) span = 10;
  
  char dummy[10];
 
    sprintf(dummy,"%4u-",min+(span*3));
    LCD_PrintXY(0,0, dummy);
    
    sprintf(dummy,"%4u-",min+(span*2));
    LCD_PrintXY(0,18,dummy);
    
    sprintf(dummy,"%4u-",min+(span*1));
    LCD_PrintXY(0,37,dummy);
    
    sprintf(dummy,"%4u-",min);
    LCD_PrintXY(0,56,dummy);

  
	LCD_DrawLine(27,0,27,63);
  diff = (span*3);
  
	for(i=27;i<128;i++)
	{
		y = viewMem->Mem[127-i];
		y =  64 - ((double)(y-min)*(double)(64.0/diff));
		LCD_PutPixel(i,y,1);
		LCD_PutPixel(i,y+1,1);
		
	}
}
Пример #27
0
static void *beosAlloc( const int size )
	{ 
	void *memPtr = NULL; 
	area_id areaID; 

	areaID = create_area( "memory_block", &memPtr, B_ANY_ADDRESS,
						  roundUp( size + MEM_INFO_HEADERSIZE, B_PAGE_SIZE ),
						  B_LAZY_LOCK, B_READ_AREA | B_WRITE_AREA );
	if( areaID < B_NO_ERROR )
		return( NULL );

	return( memPtr );
	}
Пример #28
0
void ProgramLauncher::launch(const Program *program, std::vector<Program::Parameter> &parameters, const Domain &domain, bool blocking) {
	//std::cout << "The program " << program->getName() << std::endl; 

	size_t s[3];
    for (size_t i = 1; i <= 3; i++) {
		//std::cout << "\tis executing on domain size "<< domain.getMeshWithGC((Domain::Dim)i) << std::endl;
        if(i <= (size_t)domain.getDimensions())
			s[i-1] = roundUp(domain.getMeshWithGC((Domain::Dim)i),32);
		else
			s[i-1] = 1;
		//std::cout << "\twhich is padded to " << s[i-1] << std::endl;
    }
    launch(program, parameters, domain.getDimensions(), &s[0], blocking);
}
Пример #29
0
unique_ptr<uchar8, decltype(&alignedFree)> Buffer::Create(size_type size) {
  if (!size)
    ThrowIOE("Trying to allocate 0 bytes sized buffer.");

  unique_ptr<uchar8, decltype(&alignedFree)> data(
      alignedMalloc<uchar8, 16>(roundUp(size + BUFFER_PADDING, 16)),
      &alignedFree);
  if (!data.get())
    ThrowIOE("Failed to allocate %uz bytes memory buffer.", size);

  assert(!ASAN_REGION_IS_POISONED(data.get(), size));

  return data;
}
Пример #30
0
int LegacyPolicy::DetermineCallsiteNativeSizeEstimate(CORINFO_METHOD_INFO* methInfo)
{
    int callsiteSize = 55;   // Direct call take 5 native bytes; indirect call takes 6 native bytes.

    bool hasThis = methInfo->args.hasThis();

    if (hasThis)
    {
        callsiteSize += 30;  // "mov" or "lea"
    }

    CORINFO_ARG_LIST_HANDLE argLst = methInfo->args.args;
    COMP_HANDLE comp = m_Compiler->info.compCompHnd;

    for (unsigned i = (hasThis ? 1 : 0);
         i < methInfo->args.totalILArgs();
         i++, argLst = comp->getArgNext(argLst))
    {
        var_types sigType = (var_types) m_Compiler->eeGetArgType(argLst, &methInfo->args);

        if (sigType == TYP_STRUCT)
        {
            typeInfo  verType  = m_Compiler->verParseArgSigToTypeInfo(&methInfo->args, argLst);

            /*

            IN0028: 00009B      lea     EAX, bword ptr [EBP-14H]
            IN0029: 00009E      push    dword ptr [EAX+4]
            IN002a: 0000A1      push    gword ptr [EAX]
            IN002b: 0000A3      call    [MyStruct.staticGetX2(struct):int]

            */

            callsiteSize += 10; // "lea     EAX, bword ptr [EBP-14H]"

            // NB sizeof (void*) fails to convey intent when cross-jitting.

            unsigned opsz = (unsigned)(roundUp(comp->getClassSize(verType.GetClassHandle()), sizeof(void*)));
            unsigned slots = opsz / sizeof(void*);

            callsiteSize += slots * 20; // "push    gword ptr [EAX+offs]  "
        }
        else
        {
            callsiteSize += 30; // push by average takes 3 bytes.
        }
    }

    return callsiteSize;
}