Ejemplo n.º 1
0
int main(int argc, char** argv) {
    int i;	
    int *arr;
    int access_mem_count;
    int seed;

    if(argc<3) {
    	fprintf(stderr,"usage: %s [access_mem_count] [seed]\n",argv[0]);
    	exit(-1);
    }

    access_mem_count=atoi(argv[1]);
    seed=atoi(argv[2]);

    if(access_mem_count<100||access_mem_count>1000000) {
    	fprintf(stderr,"First parameter is wrong range\n");
    	exit(-1);
    }

    arr=(int*)malloc(sizeof(int)*access_mem_count);

	arr = genAddr(access_mem_count, seed);
        
    printf("FIFO: %d\n",fifo(arr,access_mem_count));
    printf("LRU: %d\n",lru(arr,access_mem_count));
    /*
    for(i = 0; i < access_mem_count; i++)
		printf("%dst addr value : %d\n", i, arr[i]);
	*/
	return 0;
}
Ejemplo n.º 2
0
void test_range_constructor() {
	std::string s("Kalahari");
	lru_list<char> lru(s.begin(), s.end());
	ASSERT_EQUAL(6, lru.size());
	std::string lru_string(lru.begin(), lru.end());
	ASSERT_EQUAL("irahlK", lru_string);
}
Ejemplo n.º 3
0
int main()
{
int i,ch;
printf("\nEnter total number of pages:");
scanf("%d",&n);
printf("\nEnter sequence:");
for(i=0;i<n;i++) //accepting sequence
scanf("%d",&pg[i]);
do
{
printf("\n\tMENU\n");
printf("\n1)FIFO");
printf("\n2)OPTIMAL");
printf("\n3)LRU");
printf("\n4)Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: fifo();
break;

case 2: optimal();
break;

case 3: lru();
break;

}
}while(ch!=4);
getchar();
}
Ejemplo n.º 4
0
	void object::test<4>()
	{
		set_test_name("performance");

		const size_t n = 1000; 

		typedef cache::cache_t<int, int, cache::lru_t> LRUCache;
		LRUCache lru(n); 

		std::cout  << std::endl << "lru:" << std::endl;

		// Test a variety of cache load levels 
		benchmark(lru,n,n/2    ,1024*n); 
		benchmark(lru,n,(7*n)/8,1024*n); 
		benchmark(lru,n,n      ,1024*n); 
		benchmark(lru,n, 1.2 * n,		1024*n); 
		benchmark(lru,n, 2 * n    ,1024*n); 
		benchmark(lru,n, 10 * n    ,1024*n);
		benchmark(lru,n, 100 * n    ,1024*n);
		benchmark(lru,n, 1000 * n    ,1024*n);

		

		std::cout << std::endl << "lfu:" << std::endl;

		typedef cache::cache_t<int, int, cache::lfu_t> LFUCache;
		LFUCache lru2(n); 

		// Test a variety of cache load levels 
		benchmark(lru2,n,n/2    ,1024*n); 
		benchmark(lru2,n,(7*n)/8,1024*n); 
		benchmark(lru2,n,n      ,1024*n); 
		benchmark(lru2,n, 1.2 * n,		1024*n); 
		benchmark(lru2,n, 2 * n    ,1024*n); 
		benchmark(lru2,n, 10 * n    ,1024*n);
		benchmark(lru2,n, 100 * n    ,1024*n);
		benchmark(lru2,n, 1000 * n    ,1024*n);

		

		std::cout << std::endl << "fifo:" << std::endl;
		typedef cache::cache_t<int, int, cache::fifo_t> FIFOCache;
		FIFOCache lru3(n); 

		// Test a variety of cache load levels 
		benchmark(lru3,n,n/2    ,1024*n); 
		benchmark(lru3,n,(7*n)/8,1024*n); 
		benchmark(lru3,n,n      ,1024*n); 
		benchmark(lru3,n, 1.2 * n,		1024*n); 
		benchmark(lru3,n, 2 * n    ,1024*n); 
		benchmark(lru3,n, 10 * n    ,1024*n);
		benchmark(lru3,n, 100 * n    ,1024*n);
		benchmark(lru3,n, 1000 * n    ,1024*n);

		
	}
Ejemplo n.º 5
0
int main(void)
{
	int frameSize, i = 0;
	char file[32], *requests = NULL, ch;
	FILE *fp;
	initscr();
	werase(stdscr);
	getmaxyx(stdscr, maxy, maxx);
	mvprintw(maxy/2 - 1, (maxx - 40)/2, "Enter the name of file to be read: ");
	scanw("%s", file);
	if((fp = fopen(file, "r")) == NULL)
	{
		mvprintw(maxy/2 + 1, (maxx - 20) / 2, "Error opening file!!!");
		getch();
		endwin();
		return -1;
	}
	ch = getc(fp);
	while(ch != EOF)
	{
		i++;
		requests = (char *) realloc(requests, sizeof(char) * i);
		requests[i - 1] = ch;
		ch = getc(fp);
	};
	requests = (char *) realloc(requests, sizeof(char) * (i+1));
	requests[i] = '\0';
	fclose(fp);

	mvprintw(maxy/2 + 1, (maxx - 30) / 2, "Enter the number of frames: ");
	scanw("%d", &frameSize);
	while(1)
	{
		switch(menu())
		{
			case 1: fcfs(requests, frameSize);
				break;

			case 2: lru(requests, frameSize);
				break;

			case 3: optimal(requests, frameSize);
				break;

			case 4: endwin();
				return 0;
		}
	}
	return 0;
}
Ejemplo n.º 6
0
//main
int main(void){
	int i = 0;
	 for(i=1;i<=7;i++){
	 	fifo(i);
	 }
	 for(i=1;i<=7;i++){
	 	lru(i);
	 }
	for(i=1;i<=7;i++){
		opt(i);
	}


}
	//called when client want to read any page into memory, it decides on strategy which will be
	//used at the time of page replacement.
	RC pinPage (BM_BufferPool *const bm, BM_PageHandle *const page, const PageNumber pageNum){
	if(bm!=NULL){
		
			if(bm->strategy==RS_FIFO){
				 fifo(bm,page,pageNum);//calls FIFO.
				
			}else if(bm->strategy==RS_LRU){
				lru(bm,page,pageNum);//calls LRU
			}
				return RC_OK;
			}else{
				RC_message="Buffer is not initialized ";
				return RC_BUFFER_NOT_INITIALIZED;
			}
	}
Ejemplo n.º 8
0
unsigned lru_simulate(unsigned pages[], unsigned pages_len, unsigned table_len)
{
    printf("\n\nrunning LRU simulation\n");
    
    
    for(int i=0; i<pages_len; i++)
    {
        printf("%d ", pages[i]);
    }
    
    printf("\n");
    
//    clock(pages, pages_len, table_len);
    lru(pages, pages_len, table_len);
    
    return 0;
}
Ejemplo n.º 9
0
int main()
{
	frame f[10];
	int prs[20],pl,fs,i,j,pf=0;
	int ifpresent(frame f[],int ,int );
	int lru(frame f[],int );
	void dec(frame f[],int ,int );
	void disp(frame f[],int );
	printf("Enter the length of page reference string\n");
	scanf("%d",&pl);
	printf("Enter the elements of page reference string\n");
	for(i=0;i<pl;i++)
	scanf("%d",&prs[i]);
	printf("Enter the frame size\n");
	scanf("%d",&fs);
	for(i=0;i<fs;i++)
	{
		f[i].pid=0;
		f[i].pr=3;
	}
	printf("Allocating using LRU policy\n");
	for(i=0;i<pl;i++)
	{
		if(!(ifpresent(f,fs,prs[i])))
		{
			j=lru(f,fs);
			f[j].pid=prs[i];
			dec(f,fs,f[j].pid);
			pf++;
		}
		else
		dec(f,fs,prs[i]);
		disp(f,fs);
	}
	printf("Number of page faults : %d\n",pf);
	return 0;
}
void pageit(Pentry q[MAXPROCESSES]) { 

    /* This file contains the stub for an LRU pager */
    /* You may need to add/remove/modify any part of this file */
	//printf("%ld",processes[0]->pid);
    /* Static vars */
    static int initialized = 0;
    //static int tick = 1; // artificial time
    
	//printf("here\n");
    /* Local vars */
    int proctmp;
int minPageTwo;
	int secondMinPageOne;
	int secondMinPageTwo;
    int pagetmp;
	int secondMaxPage;
	int secondsecondMaxPage;
	int pc;
	int page;
	static int procount=0;
	int min;
	int pageOne;
	int predOne;
	int predTwo;
	int predThree;

		int swapRow=0;
		int swapCol=0;
		int tmppage;
		int proc;
	int pageTwo;
	int minPage;
	int i;
	int minPageOne;
    /* initialize static vars on first run */
    if(!initialized){
	for(proctmp=0; proctmp < MAXPROCESSES; proctmp++){
	    for(pagetmp=0; pagetmp < MAXPROCPAGES; pagetmp++){
				timestamps[proctmp][pagetmp] = 0;
				pageLastRemovedAt[proctmp][pagetmp]=0; 
				numberofpagesout=0;
		for(i=0; i<2;i++){
			betRevlentPage[proctmp][pagetmp][i]=0;

		}
		for(i=0;i<MAXPROCPAGES;i++){
			revelentPageFreq[proctmp][pagetmp][i]=0;
		}
	    }
		lastPageCalled[proctmp]=0;
	}
	tick=1;
	prevtick=0;
	initialized = 1;
    }
    
	
	//pager();
	for(proc=0; proc <MAXPROCESSES; proc++){
		//printf("1\n");	
		if(q[proc].active){
			
			//printf("2\n");
			pc = q[proc].pc;
			page=pc/PAGESIZE;
			/*if(procount>=4){

				pager(q);
			}*/

			timestamps[proc][page] = tick;
			
			


			tmppage=lastPageCalled[page];
			betRevlentPage[proc][tmppage][1]=betRevlentPage[proc][tmppage][0];
			betRevlentPage[proc][tmppage][0]=page;


			predOne=betRevlentPage[proc][page][0];
			predTwo=betRevlentPage[proc][predOne][0];
			predThree=betRevlentPage[proc][predTwo][0];


			revelentPageFreq[proc][tmppage][page]++;
			lastPageCalled[proc]=page;

			pageOne=arrayMax(proc,page,&secondMaxPage);
			pageTwo=arrayMax(proc,pageOne,&secondsecondMaxPage);

			minPageOne=arrayMin(q,proc,page,&secondMinPageOne);
			minPageTwo=arrayMin(q,proc,pageOne,&secondMinPageTwo);


			minPage=lru(q,proc,page);
			pagein(proc,page);
			pagein(proc,pageTwo);
			pagein(proc,pageOne);
			/*if(secondMaxPage!=-100 && secondMaxPage!=secondMinPageOne){
				pagein(proc,secondMaxPage);
				if(secondMinPageOne!=-100){
					pageout(proc, secondMinPageOne);
				}
			}
			if(secondMaxPage!=-100 && secondMaxPage!=secondMinPageTwo){
				pagein(proc,secondsecondMaxPage);*
				if(secondMinPageTwo!=-100){
					pageout(proc,secondMinPageTwo);
				}
			}*/
			//pagein(proc,predThree);
			//pagein(proc,predTwo);
			//pagein(proc,predOne);


			if(!q[proc].pages[page]){
				effChecker(proc,page);
				if(!pagein(proc,page)){
					pageout(proc,minPage);
					pageout(proc,minPageOne);
					pageout(proc,minPageTwo);
					if(secondMinPageTwo!=-100){
						pageout(proc,secondMinPageTwo);
					}
					if(secondMinPageOne!=-100){
						pageout(proc, secondMinPageOne);
					}
					

				}else if(!pagein(proc,pageTwo)){
					pageout(proc,minPage);
					pageout(proc,minPageOne);
					if(secondMinPageTwo!=-100){
						pageout(proc,secondMinPageTwo);
					}
					if(secondMinPageOne!=-100){
						pageout(proc, secondMinPageOne);
					}
					

				}else if(!pagein(proc,pageOne)){
					//pageout(proc,minPage);
					pageout(proc,minPage);
					pageout(proc,minPageOne);
					pageout(proc,minPageTwo);
					//pageout(proc,minPageOne);
					if(secondMinPageTwo!=-100){
						pageout(proc,secondMinPageTwo);
					}
					if(secondMinPageOne!=-100){
						pageout(proc, secondMinPageOne);
					}
					
				}

			}

			
				


		}else{//remove all things related to the process if not active
			for(i=0;i<MAXPROCPAGES;i++){
				pageout(proc,i);
				procount++;
			}

		}
 		
	}



    /* TODO: Implement LRU Paging */
	//pager(q);

    /* advance time for next pageit iteration */
	pager(q);
    tick++;
} 
Ejemplo n.º 11
0
/** Save the specified mode to file */
void history_t::save_internal()
{
    /* This must be called while locked */
    ASSERT_IS_LOCKED(lock);
    
    /* Nothing to do if there's no new items */
    if (new_items.empty() && deleted_items.empty())
        return;
        
    /* Compact our new items so we don't have duplicates */
    this->compact_new_items();
    
	bool ok = true;
    
    wcstring tmp_name = history_filename(name, L".tmp");    
	if( ! tmp_name.empty() )
	{        
        /* Make an LRU cache to save only the last N elements */
        history_lru_cache_t lru(HISTORY_SAVE_MAX);
        
        /* Insert old items in, from old to new. Merge them with our new items, inserting items with earlier timestamps first. */
        std::vector<history_item_t>::const_iterator new_item_iter = new_items.begin();
        
        /* Map in existing items (which may have changed out from underneath us, so don't trust our old mmap'd data) */
        const char *local_mmap_start = NULL;
        size_t local_mmap_size = 0;
        if (map_file(name, &local_mmap_start, &local_mmap_size)) {
            size_t cursor = 0;
            for (;;) {
                size_t offset = offset_of_next_item(local_mmap_start, local_mmap_size, &cursor, 0);
                /* If we get back -1, we're done */
                if (offset == (size_t)(-1))
                    break;

                /* Try decoding an old item */
                const history_item_t old_item = history_t::decode_item(local_mmap_start + offset, local_mmap_size - offset);
                if (old_item.empty() || is_deleted(old_item))
                {
//                    debug(0, L"Item is deleted : %s\n", old_item.str().c_str());
                    continue;
                }
                /* The old item may actually be more recent than our new item, if it came from another session. Insert all new items at the given index with an earlier timestamp. */
                for (; new_item_iter != new_items.end(); ++new_item_iter) {
                    if (new_item_iter->timestamp() < old_item.timestamp()) {
                        /* This "new item" is in fact older. */
                        lru.add_item(*new_item_iter);
                    } else {
                        /* The new item is not older. */
                        break;
                    }
                }
                
                /* Now add this old item */
                lru.add_item(old_item);
            }
            munmap((void *)local_mmap_start, local_mmap_size);
        }
        
        /* Insert any remaining new items */
        for (; new_item_iter != new_items.end(); ++new_item_iter)
        {
            lru.add_item(*new_item_iter);
        }
                
        signal_block();
    
        FILE *out;
		if( (out=wfopen( tmp_name, "w" ) ) )
		{
            /* Write them out */
            for (history_lru_cache_t::iterator iter = lru.begin(); iter != lru.end(); ++iter) {
                const history_lru_node_t *node = *iter;
                if (! node->write_yaml_to_file(out)) {
                    ok = false;
                    break;
                }
            }
            
			if( fclose( out ) || !ok )
			{
				/*
				  This message does not have high enough priority to
				  be shown by default.
				*/
				debug( 2, L"Error when writing history file" );
			}
			else
			{
                wcstring new_name = history_filename(name, wcstring());
				wrename(tmp_name, new_name);
			}
		}
        
        signal_unblock();
        
        /* Make sure we clear all nodes, since this doesn't happen automatically */
        lru.evict_all_nodes();
        
        /* We've saved everything, so we have no more unsaved items */
        unsaved_item_count = 0;
	}	

	if( ok )
	{
		/* Our history has been written to the file, so clear our state so we can re-reference the file. */
		this->clear_file_state();
	}
}
Ejemplo n.º 12
0
int main(int argc, char * argv[])
{
  int policy; /* replacement policy */
  int current;  /* current page accessed */
  FILE * fp; /* The file containing the page accesses */
  FILE * rp; /* output file */
  char filename[30]={""};
  const char * extension[] ={".fifo", ".lru", "new"};
  float num_accesses = 0.0; /* total number of page accesses */
  float page_faults = 0.0;
  unsigned victim = 0;  /* page to be replaced */
  
  /* Getting and checking the input from the command line */
  if(argc != 4)
  {
    printf("usage: pager policy size filename\n");
    exit(1);
  }
  
  policy = atoi(argv[1]);
  mem_size = atoi(argv[2]);
  
  if( policy < 0 || policy > 2)
  { 
    printf("policy must be 0, 1, or 2\n");
    exit(1);
  }
  
  if(mem_size <= 0 )
  {
    printf("Size must be a positive integer.\n");
    exit(1);
  }
  
  /* Allocate and initialize the memory */
  mem = (int *)calloc(mem_size, sizeof(int));
  if(!mem)
  {
    printf("Cannot allocate mem\n");
    exit(1);
  }
  
  /* open the memory access file */
  fp = fopen(argv[3], "r");
  if(!fp)
  {
    printf("Cannot open file %s\n", argv[3]);
    exit(1);
  }
  
  /* Create the output file */
  strcat(filename, argv[3]);
  strcat(filename,extension[policy]);
  rp = fopen(filename, "w");
  if(!rp)
  {
    printf("Cannot create file %s\n", filename);
    exit(1);
  }
  
  /* The main loop of the program */
  fscanf(fp,"%d", &current);
  while(!feof(fp))
  {
    num_accesses++;
    if(mem_check(current) == PAGEMISS)
      page_faults++;
    
    switch(policy)
    {
      case 0: if( IsFull())
	      {
		victim = fifo();
		mem[victim] = current;
	      }
	      else
		insert(current);
	      break;
	     
      case 1: if( IsFull())
	      {
		victim = lru();
		mem[victim] = current;
	      }
	      else
		insert(current);
	      break;
	      
      case 2: if( IsFull())
	      {
		victim = own();
		mem[victim] = current;
	      }
	      else
		insert(current);
	      break;
	      
	      
      default: printf("Unknown policy ... Exiting\n");
	       exit(1);
      
    }/* end switch-case */
    
    print_mem(rp);
    fscanf(fp,"%d", &current);

  }/* end while */
  fprintf(rp,"percentage of page faults = %f", page_faults/num_accesses);
  
  /* wrap-up */
  fclose(fp);
  fclose(rp);
  free(mem);
  
  return 1;

}
Ejemplo n.º 13
0
void TriSoup::ReindexTriangles(int lruSize, std::vector<int>& outFaceOrder)
{
	////////////////////////////////////////        
	// Init vert and face arrays.
	const int numVerts = NumVertices();
	const int numTris = NumFaces();

	std::vector<CacheSort::Vertex> verts(numVerts);
	std::vector<CacheSort::Face> faces(numTris);

	for(int i = 0, c = NumFaces(); i < c; ++i)
	{
		faces[i].m_indices[0] = m_faces[i].m_vertices[0];
		faces[i].m_indices[1] = m_faces[i].m_vertices[1];
		faces[i].m_indices[2] = m_faces[i].m_vertices[2];
	}

	CacheSort::InitValence(verts, faces);

	outFaceOrder = std::vector<int>(numTris, -1);

	////////////////////////////////////////        
	// Finished init. now start the main loop
	CacheSort::VertexLRU lru(lruSize+3); // 3 extra to hold up to 3 verts which get pushed off.
	const int *cache = lru.GetVertexCache();
	int cacheSize = lru.GetCacheSize();

	int idxDrawList = 0;

	int curFace = CacheSort::FindBestFaceGlobal(verts, faces);
	while(curFace >= 0) 
	{
		ASSERT( idxDrawList < numTris );

		// Add this face to the draw list.
		outFaceOrder[idxDrawList++] = curFace;
		lru.AddFace(&faces[curFace], verts);

		// decrement current valency so we don't keep computing scores for already drawn faces
		CacheSort::Face::RemoveConnections(curFace, verts, faces);

		// Recompute scores of all verts in the LRU
		for(int i = 0; i < cacheSize && cache[i] >= 0; ++i)
		{
			int idxVert = cache[i];
			verts[idxVert].ComputeScore(cacheSize);
		}

		int bestFace = -1;
		float bestFaceScore = 0.f;

		// Recompute scores of all faces whose scores would change due to changes in the LRU
		for(int i = 0; i < cacheSize && cache[i] >= 0; ++i)
		{
			int idxVert = cache[i];
			for(int j = 0; j < verts[idxVert].m_valency; ++j) 
			{
				int idxFace = verts[idxVert].m_clientFaces[j];
				float faceScore = 
					verts[ faces[idxFace].m_indices[0] ].m_score +
					verts[ faces[idxFace].m_indices[1] ].m_score +
					verts[ faces[idxFace].m_indices[2] ].m_score ;

				if (faceScore > bestFaceScore) {
					bestFace = idxFace;
					bestFaceScore = faceScore;
				}
			}
		}
		// Truncate the extra 3 verts. This just means if the next face includes one of the removed verts, it will be added instead of
		// swapped, which will push more verts off. Also it means those 3 verts will NOT be included in scoring next iteration.
		lru.Truncate(lruSize, verts);

		// If for some reason the valency information doesn't link adjacent faces, then just pick the best global face again.
		if( bestFace < 0 ) 
			curFace = CacheSort::FindBestFaceGlobal(verts, faces);
		else
			curFace = bestFace;
	}
}
Ejemplo n.º 14
0
static int copyPageToRam(sim_database_t* sim_db,int pageNum,int isFromSwap)// add lru
{
    int ret;
    missCounter++;

    //find a new frame
    freeFrameNum=freeFrameInBitMap();


    //if we dont have any free frame, use the lru algorithem
    if(freeFrameNum == -1)
      {
        freeFrameNum=lru(sim_db);

        if(freeFrameNum==-1)
        {
          perror("lru returned -1..problem in lru");
          return -1;
        }
      }


    if (isFromSwap==1)
    {
          //go with pointer (fd) to the specific page
         lseek(sim_db->swapfile_fd,pageNum*PAGE_SIZE,SEEK_SET);

        //read page from swap and save page in ram place
         ret= read(sim_db->swapfile_fd,&ramMen[freeFrameNum*PAGE_SIZE],PAGE_SIZE);
        if( ret == -1)
        {
            perror("problem in read() from swap method");
            return -1;
        }

      sim_db->page_table[pageNum].isInSwap=0;
      
    }


    // copy from disk
    else
    {     
          //go with pointer (fd) to the specific page in disk

         ret=lseek(sim_db->executable_fd,pageNum*PAGE_SIZE,SEEK_SET);
         if(ret==-1)
         {
          perror("problem in lseek from disk method");
            return -1;
         }
     
        //read page from disk and save page in ram
         ret= read(sim_db->executable_fd,&ramMen[freeFrameNum*32],32) ;
         if(ret==-1)
         {
          perror("problem in read() from disk method");
            return -1;
         }
    }

    bitMap[freeFrameNum][0]=1;
    bitMap[freeFrameNum][2]=pageNum;
    bitMapAgeUpdate();
    sim_db->page_table[pageNum].valid=1;
    sim_db->page_table[pageNum].frame=freeFrameNum;

      return 0;  
}
Ejemplo n.º 15
0
/**
Vertex cache optimization according to the Forsyth paper:
http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html

The function is thread-safe (read: you can optimize several meshes in different threads)

\param mesh Source mesh for the operation.  */
scene::IMesh* createForsythOptimizedMesh(const scene::IMesh *mesh)
{
	if (!mesh)
		return 0;

	scene::SMesh *newmesh = new scene::SMesh();
	newmesh->BoundingBox = mesh->getBoundingBox();

	const u32 mbcount = mesh->getMeshBufferCount();

	for (u32 b = 0; b < mbcount; ++b)
	{
		const scene::IMeshBuffer *mb = mesh->getMeshBuffer(b);

		if (mb->getIndexType() != video::EIT_16BIT)
		{
			//os::Printer::log("Cannot optimize a mesh with 32bit indices", ELL_ERROR);
			newmesh->drop();
			return 0;
		}

		const u32 icount = mb->getIndexCount();
		const u32 tcount = icount / 3;
		const u32 vcount = mb->getVertexCount();
		const u16 *ind = mb->getIndices();

		vcache *vc = new vcache[vcount];
		tcache *tc = new tcache[tcount];

		f_lru lru(vc, tc);

		// init
		for (u16 i = 0; i < vcount; i++)
		{
			vc[i].score = 0;
			vc[i].cachepos = -1;
			vc[i].NumActiveTris = 0;
		}

		// First pass: count how many times a vert is used
		for (u32 i = 0; i < icount; i += 3)
		{
			vc[ind[i]].NumActiveTris++;
			vc[ind[i + 1]].NumActiveTris++;
			vc[ind[i + 2]].NumActiveTris++;

			const u32 tri_ind = i/3;
			tc[tri_ind].ind[0] = ind[i];
			tc[tri_ind].ind[1] = ind[i + 1];
			tc[tri_ind].ind[2] = ind[i + 2];
		}

		// Second pass: list of each triangle
		for (u32 i = 0; i < tcount; i++)
		{
			vc[tc[i].ind[0]].tris.push_back(i);
			vc[tc[i].ind[1]].tris.push_back(i);
			vc[tc[i].ind[2]].tris.push_back(i);

			tc[i].drawn = false;
		}

		// Give initial scores
		for (u16 i = 0; i < vcount; i++)
		{
			vc[i].score = FindVertexScore(&vc[i]);
		}
		for (u32 i = 0; i < tcount; i++)
		{
			tc[i].score =
					vc[tc[i].ind[0]].score +
					vc[tc[i].ind[1]].score +
					vc[tc[i].ind[2]].score;
		}

		switch(mb->getVertexType())
		{
			case video::EVT_STANDARD:
			{
				video::S3DVertex *v = (video::S3DVertex *) mb->getVertices();

				scene::SMeshBuffer *buf = new scene::SMeshBuffer();
				buf->Material = mb->getMaterial();

				buf->Vertices.reallocate(vcount);
				buf->Indices.reallocate(icount);

				core::map<const video::S3DVertex, const u16> sind; // search index for fast operation
				typedef core::map<const video::S3DVertex, const u16>::Node snode;

				// Main algorithm
				u32 highest = 0;
				u32 drawcalls = 0;
				for (;;)
				{
					if (tc[highest].drawn)
					{
						bool found = false;
						float hiscore = 0;
						for (u32 t = 0; t < tcount; t++)
						{
							if (!tc[t].drawn)
							{
								if (tc[t].score > hiscore)
								{
									highest = t;
									hiscore = tc[t].score;
									found = true;
								}
							}
						}
						if (!found)
							break;
					}

					// Output the best triangle
					u16 newind = buf->Vertices.size();

					snode *s = sind.find(v[tc[highest].ind[0]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[0]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[0]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[1]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[1]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[1]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[2]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[2]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[2]], newind);
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					vc[tc[highest].ind[0]].NumActiveTris--;
					vc[tc[highest].ind[1]].NumActiveTris--;
					vc[tc[highest].ind[2]].NumActiveTris--;

					tc[highest].drawn = true;

					for (u16 j = 0; j < 3; j++)
					{
						vcache *vert = &vc[tc[highest].ind[j]];
						for (u16 t = 0; t < vert->tris.size(); t++)
						{
							if (highest == vert->tris[t])
							{
								vert->tris.erase(t);
								break;
							}
						}
					}

					lru.add(tc[highest].ind[0]);
					lru.add(tc[highest].ind[1]);
					highest = lru.add(tc[highest].ind[2], true);
					drawcalls++;
				}

				buf->setBoundingBox(mb->getBoundingBox());
				newmesh->addMeshBuffer(buf);
				buf->drop();
			}
			break;
			case video::EVT_2TCOORDS:
			{
				video::S3DVertex2TCoords *v = (video::S3DVertex2TCoords *) mb->getVertices();

				scene::SMeshBufferLightMap *buf = new scene::SMeshBufferLightMap();
				buf->Material = mb->getMaterial();

				buf->Vertices.reallocate(vcount);
				buf->Indices.reallocate(icount);

				core::map<const video::S3DVertex2TCoords, const u16> sind; // search index for fast operation
				typedef core::map<const video::S3DVertex2TCoords, const u16>::Node snode;

				// Main algorithm
				u32 highest = 0;
				u32 drawcalls = 0;
				for (;;)
				{
					if (tc[highest].drawn)
					{
						bool found = false;
						float hiscore = 0;
						for (u32 t = 0; t < tcount; t++)
						{
							if (!tc[t].drawn)
							{
								if (tc[t].score > hiscore)
								{
									highest = t;
									hiscore = tc[t].score;
									found = true;
								}
							}
						}
						if (!found)
							break;
					}

					// Output the best triangle
					u16 newind = buf->Vertices.size();

					snode *s = sind.find(v[tc[highest].ind[0]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[0]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[0]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[1]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[1]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[1]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[2]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[2]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[2]], newind);
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					vc[tc[highest].ind[0]].NumActiveTris--;
					vc[tc[highest].ind[1]].NumActiveTris--;
					vc[tc[highest].ind[2]].NumActiveTris--;

					tc[highest].drawn = true;

					for (u16 j = 0; j < 3; j++)
					{
						vcache *vert = &vc[tc[highest].ind[j]];
						for (u16 t = 0; t < vert->tris.size(); t++)
						{
							if (highest == vert->tris[t])
							{
								vert->tris.erase(t);
								break;
							}
						}
					}

					lru.add(tc[highest].ind[0]);
					lru.add(tc[highest].ind[1]);
					highest = lru.add(tc[highest].ind[2]);
					drawcalls++;
				}

				buf->setBoundingBox(mb->getBoundingBox());
				newmesh->addMeshBuffer(buf);
				buf->drop();

			}
			break;
			case video::EVT_TANGENTS:
			{
				video::S3DVertexTangents *v = (video::S3DVertexTangents *) mb->getVertices();

				scene::SMeshBufferTangents *buf = new scene::SMeshBufferTangents();
				buf->Material = mb->getMaterial();

				buf->Vertices.reallocate(vcount);
				buf->Indices.reallocate(icount);

				core::map<const video::S3DVertexTangents, const u16> sind; // search index for fast operation
				typedef core::map<const video::S3DVertexTangents, const u16>::Node snode;

				// Main algorithm
				u32 highest = 0;
				u32 drawcalls = 0;
				for (;;)
				{
					if (tc[highest].drawn)
					{
						bool found = false;
						float hiscore = 0;
						for (u32 t = 0; t < tcount; t++)
						{
							if (!tc[t].drawn)
							{
								if (tc[t].score > hiscore)
								{
									highest = t;
									hiscore = tc[t].score;
									found = true;
								}
							}
						}
						if (!found)
							break;
					}

					// Output the best triangle
					u16 newind = buf->Vertices.size();

					snode *s = sind.find(v[tc[highest].ind[0]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[0]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[0]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[1]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[1]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[1]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[2]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[2]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[2]], newind);
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					vc[tc[highest].ind[0]].NumActiveTris--;
					vc[tc[highest].ind[1]].NumActiveTris--;
					vc[tc[highest].ind[2]].NumActiveTris--;

					tc[highest].drawn = true;

					for (u16 j = 0; j < 3; j++)
					{
						vcache *vert = &vc[tc[highest].ind[j]];
						for (u16 t = 0; t < vert->tris.size(); t++)
						{
							if (highest == vert->tris[t])
							{
								vert->tris.erase(t);
								break;
							}
						}
					}

					lru.add(tc[highest].ind[0]);
					lru.add(tc[highest].ind[1]);
					highest = lru.add(tc[highest].ind[2]);
					drawcalls++;
				}

				buf->setBoundingBox(mb->getBoundingBox());
				newmesh->addMeshBuffer(buf);
				buf->drop();
			}
			break;
		}

		delete [] vc;
		delete [] tc;

	} // for each meshbuffer

	return newmesh;
}
RC pinPage (BM_BufferPool *const bm, BM_PageHandle *const page, 
	    const PageNumber pageNum)
{
	Data_Structure *ds = (Data_Structure *)bm->mgmtData;
	
	if(ds[0].pagenum == -1)
	{
		//printf("\nINSIDE ds[0]->pagenum == -1\n");
		
		SM_FileHandle fh;
		openPageFile (bm->pageFile, &fh);
		ds[0].data = (SM_PageHandle) malloc(PAGE_SIZE);
		ensureCapacity(pageNum,&fh);
		readBlock(pageNum, &fh, ds[0].data);
		ds[0].pagenum = pageNum;
		ds[0].fixedcnt++;
		rear = 0;
		hit = 0;
		ds[0].hitnum = hit;	
		ds[0].numRef = 0;	
		page->pageNum = pageNum;
		page->data = ds[0].data;
		
		/*	
		printf("\nPinPage function buffer");
		int i;
		for(i=0;i<bufferSize; i++)
		{
			printf("\nPagenum: %d fixedcnt: %d dirty: %d",ds[i].pagenum,ds[i].fixedcnt,ds[i].dirtybit);	
		}*/
		
		return RC_OK;		
	}
	else
	{	
		//printf("\nINSIDE front != NULL\n");
		int i,check = 0;
		
		for(i=0;i<bufferSize;i++)
		{
			if(ds[i].pagenum != -1)
			{	
				if(ds[i].pagenum == pageNum)  //if Page already in memory
				{
					ds[i].fixedcnt++;
					check = 1;
					hit++;
					if(bm->strategy == RS_LRU)	
						ds[i].hitnum = hit;
					else if(bm->strategy == RS_CLOCK)		//if bm-> strategy is RS_CLOCK storing the USED bit in hitnum.
						ds[i].hitnum = 1;
					else if(bm->strategy == RS_LFU)
						{
						ds[i].numRef++;
						//printf("Page %d referenced again \n", pageNum);
						//rear = rear + 2;
						//printf(" rear : %d \n", rear);
						}
					
					
					page->pageNum = pageNum;
					page->data = ds[i].data;

					clockptr++;
					
					break;
				}				
			}
			else	//Condition when the buffer has space to add a page
			{
				SM_FileHandle fh;
				openPageFile (bm->pageFile, &fh);
				ds[i].data = (SM_PageHandle) malloc(PAGE_SIZE);
				readBlock(pageNum, &fh, ds[i].data);
				ds[i].pagenum = pageNum;
				ds[i].fixedcnt = 1;
				ds[i].numRef = 0;
				rear++;	
				hit++;
				if(bm->strategy == RS_LRU)
					ds[i].hitnum = hit;				
				else if(bm->strategy == RS_CLOCK)		//if bm-> strategy is RS_CLOCK storing the USED bit in hitnum.
					ds[i].hitnum = 1;
				
								
				page->pageNum = pageNum;
				page->data = ds[i].data;
				
				check = 1;
				break;
			}
		}//end of for
		
		if(check == 0)//Condition when the buffer is full and we need to use a replacement strategy.
		{
			Data_Structure *temp = (Data_Structure *)malloc(sizeof(Data_Structure));		
						
			SM_FileHandle fh;
			openPageFile (bm->pageFile, &fh);
			temp->data = (SM_PageHandle) malloc(PAGE_SIZE);
			readBlock(pageNum, &fh, temp->data);
			temp->pagenum = pageNum;
			temp->dirtybit = 0;		
			temp->fixedcnt = 1;
			temp->numRef = 0;
			rear++;
			hit++;
			//printf("HIT : %d \n", hit); //test by Rakesh
			if(bm->strategy == RS_LRU )
				temp->hitnum = hit;
			else if(bm->strategy == RS_CLOCK)			//if bm-> strategy is RS_CLOCK storing the USED bit in hitnum.
				temp->hitnum = 1;

			page->pageNum = pageNum;
			page->data = temp->data;			

			switch(bm->strategy)
			{			
				case RS_FIFO:	//printf("\n Inside FIFO switch.");
						fifo(bm,temp);
						break;
				case RS_LRU:	//printf("\n Inside LRU switch.");
						lru(bm,temp);  						
						break;
				case RS_CLOCK:	//printf("\n Inside CLOCK switch");
						clock(bm,temp);						
						break;
  				case RS_LFU:	//printf("\n Inside LFU switch");
  						LFU(bm,temp);
						break;
  				case RS_LRU_K:	printf("\n Inside LRU_K switch");
						break;
				default:
								printf("\nAlgorithm Not Implemented\n");
						break;
			}//end of switch
						
		}//end of if(check = 0)
		
		/*
		printf("\nPinPage function buffer");
		for(i=0;i<bufferSize;i++)
			printf("\nPagenum: %d fixedcnt: %d dirty: %d",ds[i].pagenum,ds[i].fixedcnt,ds[i].dirtybit);
		*/		
		return RC_OK;
	}//end of else	
}
Ejemplo n.º 17
0
//Devuelve el numero de marco para asignar o -1 si no había disponibles
int marco_libre(int pid) {

	log_info(logger, "Se busca un marco libre para asignar");

	pid_matchear = pid;

	int paginaNuevoProceso = pagina_matchear;

	if (marcos_libres() == 0) {
		//Si no hay marcos disponibles
		log_info(logger, "No hay marcos libres para asignar");

		if (tiene_marcos_asignados(pid)) {

			loggearInfo(
					"El proceso ya tiene marcos asignados, se swappea alguno existente");

			//Swappea uno que ya tiene

			if (es_fifo()) {
				return fifo();
			}

			if (es_lru()) {
				return lru();
			}

			int marco = clock_m();
			pagina_matchear = paginaNuevoProceso;

			t_item * itemParaMeter = list_find(tabla_paginas,
					coincide_pid_y_pagina);

			list_replace(cola_llegada, posicionVictima, itemParaMeter);

			loggearInfo("Se remplaza la victima con el nuevo elemento");

			return marco;

		} else {
			loggearInfo("No hay marcos disponibles para asignar");
			//No le puedo dar ninguno, se aborta
			return -1;
		}

	} else {

		//Hay marcos libres
		loggearInfo("Hay marcos disponibles para asignar");

		int cantidad_maxima_marcos_proceso = config_get_int_value(memoriaConfig,
				"MAXIMO_MARCOS_POR_PROCESO");

		if (marcos_asignados(pid) < cantidad_maxima_marcos_proceso) {

			loggearInfo(
					"El proceso tiene menos marcos que la cantidad maxima, se le da uno nuevo");

			//Le doy un marco nuevo

			int marco = marco_disponible();

			if (es_clock_modificado()) {

				//Si es clockModificado me fijo si no tiene presentes,
				//significa que este que tengo acá en pid_matchear y pagina_matchear
				//es el único elemento presente y pasa a ser puntero

				t_item * elementoParaHacerPuntero;

				bool algunoPresente = list_any_satisfy(tabla_paginas,
						coincide_pid_y_esta_presente);

				if (!algunoPresente) {

					elementoParaHacerPuntero = list_find(tabla_paginas,
							coincide_pid_y_pagina);

					elementoParaHacerPuntero->puntero = true;

				}

			}

			return marco;

		} else {

			loggearInfo(
					"El proceso ya tiene la cantidad maxima de marcos, se swappea uno existente");
			//Tiene el maximo y necesita swappear uno existente

			if (es_fifo()) {
				return fifo();
			}

			if (es_lru()) {
				return lru();
			}

			int marco = clock_m();
			pagina_matchear = paginaNuevoProceso;

			t_item * itemParaMeter = list_find(tabla_paginas,
					coincide_pid_y_pagina);

			itemParaMeter->uso = true;

			list_replace(cola_llegada, posicionVictima, itemParaMeter);

			loggearInfo("Se remplaza la victima con el nuevo elemento");

			return marco;

		}

	}
}