Browse Source

commit inicial

juninho95 6 years ago
commit
bbe858d06e

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+/dist/
+/build/

BIN
CacheEmpobrecimentoVersao2.jar


+ 3 - 0
README.md

@@ -0,0 +1,3 @@
+# README #
+
+Implementação do simulador da cache versão uncacheable. Nesta versão, o bloco com erro continua sendo possível de mapeamento, mas, quando mapeado, o acesso será feito direto na memória principal (uncacheable).

+ 73 - 0
build.xml

@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- You may freely edit this file. See commented blocks below for -->
+<!-- some examples of how to customize the build. -->
+<!-- (If you delete it and reopen the project it will be recreated.) -->
+<!-- By default, only the Clean and Build commands use this build script. -->
+<!-- Commands such as Run, Debug, and Test only use this build script if -->
+<!-- the Compile on Save feature is turned off for the project. -->
+<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
+<!-- in the project's Project Properties dialog box.-->
+<project name="CacheEmpobrecimentoVersao2" default="default" basedir=".">
+    <description>Builds, tests, and runs the project CacheEmpobrecimentoVersao2.</description>
+    <import file="nbproject/build-impl.xml"/>
+    <!--
+
+    There exist several targets which are by default empty and which can be 
+    used for execution of your tasks. These targets are usually executed 
+    before and after some main targets. They are: 
+
+      -pre-init:                 called before initialization of project properties
+      -post-init:                called after initialization of project properties
+      -pre-compile:              called before javac compilation
+      -post-compile:             called after javac compilation
+      -pre-compile-single:       called before javac compilation of single file
+      -post-compile-single:      called after javac compilation of single file
+      -pre-compile-test:         called before javac compilation of JUnit tests
+      -post-compile-test:        called after javac compilation of JUnit tests
+      -pre-compile-test-single:  called before javac compilation of single JUnit test
+      -post-compile-test-single: called after javac compilation of single JUunit test
+      -pre-jar:                  called before JAR building
+      -post-jar:                 called after JAR building
+      -post-clean:               called after cleaning build products
+
+    (Targets beginning with '-' are not intended to be called on their own.)
+
+    Example of inserting an obfuscator after compilation could look like this:
+
+        <target name="-post-compile">
+            <obfuscate>
+                <fileset dir="${build.classes.dir}"/>
+            </obfuscate>
+        </target>
+
+    For list of available properties check the imported 
+    nbproject/build-impl.xml file. 
+
+
+    Another way to customize the build is by overriding existing main targets.
+    The targets of interest are: 
+
+      -init-macrodef-javac:     defines macro for javac compilation
+      -init-macrodef-junit:     defines macro for junit execution
+      -init-macrodef-debug:     defines macro for class debugging
+      -init-macrodef-java:      defines macro for class execution
+      -do-jar:                  JAR building
+      run:                      execution of project 
+      -javadoc-build:           Javadoc generation
+      test-report:              JUnit report generation
+
+    An example of overriding the target for project execution could look like this:
+
+        <target name="run" depends="CacheEmpobrecimentoVersao2-impl.jar">
+            <exec dir="bin" executable="launcher.exe">
+                <arg file="${dist.jar}"/>
+            </exec>
+        </target>
+
+    Notice that the overridden target depends on the jar target and not only on 
+    the compile target as the regular run target does. Again, for a list of available 
+    properties which you can use, check the target you are overriding in the
+    nbproject/build-impl.xml file. 
+
+    -->
+</project>

+ 3 - 0
manifest.mf

@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+X-COMMENT: Main-Class will be added automatically by build
+

File diff suppressed because it is too large
+ 1419 - 0
nbproject/build-impl.xml


+ 8 - 0
nbproject/genfiles.properties

@@ -0,0 +1,8 @@
+build.xml.data.CRC32=8112f452
+build.xml.script.CRC32=ff586e60
+build.xml.stylesheet.CRC32=8064a381@1.79.1.48
+# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
+# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
+nbproject/build-impl.xml.data.CRC32=8112f452
+nbproject/build-impl.xml.script.CRC32=feb67fd8
+nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48

+ 0 - 0
nbproject/private/config.properties


+ 7 - 0
nbproject/private/private.properties

@@ -0,0 +1,7 @@
+application.args="C:\\\\Users\\\\Juninho Carlos\\\\Dropbox\\\\Prototipagens na De2-115 FPGA\\\\nova brincadeira\\\\26.txt" "C:\\\\Users\\\\Juninho Carlos\\\\Dropbox\\\\Prototipagens na De2-115 FPGA\\\\nova brincadeira\\\\trace_bitcnt_75k_vetor.txt"
+compile.on.save=true
+do.depend=false
+do.jar=true
+javac.debug=true
+javadoc.preview=true
+user.properties.file=/home/juninho/.netbeans/8.0.2/build.properties

+ 13 - 0
nbproject/private/private.xml

@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
+    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
+    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
+        <group>
+            <file>file:/home/juninho/repositorios/modelo-empobrecimento-versao-2/src/cache/Cache.java</file>
+            <file>file:/home/juninho/repositorios/modelo-empobrecimento-versao-2/src/cache/ConstanteDeTempo.java</file>
+            <file>file:/home/juninho/repositorios/modelo-empobrecimento-versao-2/src/cache/Bloco.java</file>
+            <file>file:/home/juninho/repositorios/modelo-empobrecimento-versao-2/src/cache/Requisicao.java</file>
+            <file>file:/home/juninho/repositorios/modelo-empobrecimento-versao-2/src/simuladorcache/SimuladorCache.java</file>
+        </group>
+    </open-files>
+</project-private>

+ 76 - 0
nbproject/project.properties

@@ -0,0 +1,76 @@
+annotation.processing.enabled=true
+annotation.processing.enabled.in.editor=false
+annotation.processing.processors.list=
+annotation.processing.run.all.processors=true
+annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
+application.title=CacheEmpobrecimentoVersao2
+application.vendor=Juninho Carlos
+build.classes.dir=${build.dir}/classes
+build.classes.excludes=**/*.java,**/*.form
+# This directory is removed when the project is cleaned:
+build.dir=build
+build.generated.dir=${build.dir}/generated
+build.generated.sources.dir=${build.dir}/generated-sources
+# Only compile against the classpath explicitly listed here:
+build.sysclasspath=ignore
+build.test.classes.dir=${build.dir}/test/classes
+build.test.results.dir=${build.dir}/test/results
+# Uncomment to specify the preferred debugger connection transport:
+#debug.transport=dt_socket
+debug.classpath=\
+    ${run.classpath}
+debug.test.classpath=\
+    ${run.test.classpath}
+# Os arquivos em build.classes.dir que devem ser exclu\u00eddos do jar de distribui\u00e7\u00e3o
+dist.archive.excludes=
+# This directory is removed when the project is cleaned:
+dist.dir=dist
+dist.jar=${dist.dir}/CacheEmpobrecimentoVersao2.jar
+dist.javadoc.dir=${dist.dir}/javadoc
+endorsed.classpath=
+excludes=
+includes=**
+jar.compress=false
+javac.classpath=
+# Space-separated list of extra javac options
+javac.compilerargs=
+javac.deprecation=false
+javac.external.vm=true
+javac.processorpath=\
+    ${javac.classpath}
+javac.source=1.7
+javac.target=1.7
+javac.test.classpath=\
+    ${javac.classpath}:\
+    ${build.classes.dir}
+javac.test.processorpath=\
+    ${javac.test.classpath}
+javadoc.additionalparam=
+javadoc.author=false
+javadoc.encoding=${source.encoding}
+javadoc.noindex=false
+javadoc.nonavbar=false
+javadoc.notree=false
+javadoc.private=false
+javadoc.splitindex=true
+javadoc.use=true
+javadoc.version=false
+javadoc.windowtitle=
+main.class=simuladorcache.SimuladorCache
+manifest.file=manifest.mf
+meta.inf.dir=${src.dir}/META-INF
+mkdist.disabled=false
+platform.active=default_platform
+run.classpath=\
+    ${javac.classpath}:\
+    ${build.classes.dir}
+# Space-separated list of JVM arguments used when running the project.
+# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
+# To set system properties for unit tests define test-sys-prop.name=value:
+run.jvmargs=
+run.test.classpath=\
+    ${javac.test.classpath}:\
+    ${build.test.classes.dir}
+source.encoding=UTF-8
+src.dir=src
+test.src.dir=test

+ 15 - 0
nbproject/project.xml

@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://www.netbeans.org/ns/project/1">
+    <type>org.netbeans.modules.java.j2seproject</type>
+    <configuration>
+        <data xmlns="http://www.netbeans.org/ns/j2se-project/3">
+            <name>CacheEmpobrecimentoVersao2</name>
+            <source-roots>
+                <root id="src.dir"/>
+            </source-roots>
+            <test-roots>
+                <root id="test.src.dir"/>
+            </test-roots>
+        </data>
+    </configuration>
+</project>

+ 1 - 0
src/1.txt

@@ -0,0 +1 @@
+4/2/26 4/2/23 4/2/21 4/2/25 7/1/17 7/1/22;

+ 38 - 0
src/cache/Arquivo.java

@@ -0,0 +1,38 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.util.Scanner;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class Arquivo {
+    private Scanner in;    
+    String s;
+    
+    public Arquivo(String path) throws FileNotFoundException {        
+        in = new Scanner(new FileReader(path));        
+    }
+    
+    public boolean lerArquivo(){        
+        return this.in.hasNextLine();
+    }
+    
+    public Requisicao getRequisicao(){
+        this.s = in.nextLine();
+        boolean read = s.contains("r");
+        String teste = s.substring(1);
+        Long add = new Long(teste);
+        return new Requisicao(add, read);
+    }
+    
+    
+
+}

+ 118 - 0
src/cache/Bloco.java

@@ -0,0 +1,118 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+import java.util.Arrays;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+
+public class Bloco {
+    
+    private boolean isDirty;
+    private Boolean[] palavraComErro;
+    private boolean valido;
+    private boolean firstWrite;
+    private long limiteInf;              //valor do menor endereço do bloco
+    private long limiteSuperior;        // valor do maior endereço do bloco
+    private boolean cachavel;
+    
+    public Bloco(){
+        this.cachavel = true;
+        this.firstWrite = true;
+        this.valido = false;
+        this.isDirty = false;
+        this.palavraComErro = new Boolean[32];
+        Arrays.fill(palavraComErro, Boolean.FALSE);       
+    }
+    
+    public void setarComoInvalido(){
+        this.cachavel = false;
+        if(this.firstWrite == true){
+            this.firstWrite = false;
+        }
+    }
+    
+    public boolean isCachavel(){
+        return this.cachavel;
+    }
+    
+    public void inserirErro(int palavra){
+        this.palavraComErro[palavra] = true;
+    }
+            
+    public boolean isFirstWrite(){
+        return this.firstWrite;
+    }
+    
+    public Boolean[] getErroDasPalavraDoBloco(){
+        return this.palavraComErro;
+    }
+    
+    public boolean isSujo(){
+        return this.isDirty;
+    }
+    
+    public boolean hasErrorInBloco() {
+        Boolean[] palavras = this.palavraComErro;
+        for (Boolean erro : palavras) {
+            if (erro == true) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    
+    public void setLimitesDoBloco(long limInf,long limSup){
+        this.limiteInf = limInf;
+        this.limiteSuperior = limSup;
+    }
+    
+    public boolean getErroFromPalavra(int palavra){
+        return this.palavraComErro[palavra];
+    }
+    
+    public boolean verificaBloco(long address){
+        return address >= limiteInf && address < limiteSuperior+4;
+    }
+    
+    public void setValidadeDoBloco(boolean validade){
+        this.valido = validade;
+        if(this.firstWrite == true){
+            this.firstWrite = false;
+        }
+    }
+    
+    public void setSujeira(boolean dirty){
+        this.isDirty = dirty;
+    }
+    
+    public boolean isValido(){
+        return this.valido;
+    }
+    
+    @Override
+    public String toString() {
+        String s;
+        s = "Sujo: " + this.isDirty +"\n";
+        s += "Valido: " + this.valido + "\n";
+        s += "Erro: " + this.hasErrorInBloco() + "\n";
+        s += "Cachavel: " + this.cachavel + "\n";
+        s += "range: " + "[ " + this.limiteInf + " - " + this.limiteSuperior + " ]\n";
+     /*   s += "Palavras com erro: ";        
+        int i = 0;
+        for (Boolean boolean1 : palavraComErro) {
+            s += i + " " + boolean1 + "\n";
+            i++;
+        }        */
+        return s;
+    }
+    
+    
+}

+ 268 - 0
src/cache/Cache.java

@@ -0,0 +1,268 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+import java.util.ArrayList;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class Cache {
+
+    private long escritaCache;  //Done
+    private long leituraCache;  //Done
+
+    private long contadorDeCiclos; //ToDo
+    private long contadorDeWB;    //Done
+
+    private long contadorDeHit;   //Done
+    private long contadorDeMiss;  //Done
+
+    private long escritaSDRAM;
+    private long leituraSDRAM;
+    
+    private long leituraSDRAMDevidoAERRO;
+    private long escritaSDRAMDevidoAERRO;
+    
+    private Conjunto[] conjuntos;
+
+    public Cache() {
+
+        this.escritaCache = 0;
+        this.leituraCache = 0;
+
+        this.contadorDeCiclos = 0;
+        this.contadorDeWB = 0;
+
+        this.contadorDeHit = 0;
+        this.contadorDeMiss = 0;
+
+        this.escritaSDRAM = 0;
+        this.leituraSDRAM = 0;
+        
+        this.leituraSDRAMDevidoAERRO = 0;
+        this.escritaSDRAMDevidoAERRO = 0;
+        
+        this.conjuntos = new Conjunto[32];
+        for (int i = 0; i < 32; i++) {
+            this.conjuntos[i] = new Conjunto();
+        }
+    }
+    
+    public long getLeituraSDRAMDevidoErro(){
+        return this.leituraSDRAMDevidoAERRO;
+    }
+    
+    public long getEscritaSDRAMDevidoErro(){
+        return this.escritaSDRAMDevidoAERRO;
+    }
+    
+    public long getHit() {
+        return this.contadorDeHit;
+    }
+
+    public long getMiss() {
+        return this.contadorDeMiss;
+    }
+
+    public long getEscritaSDRAM() {
+        return this.escritaSDRAM;
+    }
+
+    public long getLeituraSDRAM() {
+        return this.leituraSDRAM;
+    }
+
+    public long getEscritaCache() {
+        return this.escritaCache;
+    }
+
+    public long getLeituraCache() {
+        return this.leituraCache;
+    }
+
+    /**
+     *
+     * @param address endereço solicitado à cache
+     * @param read true -> leitura(lw), false -> escrita(sw)
+     */
+    public void requisicaoParaCache(long address, boolean read) {
+        Requisicao end = new Requisicao(address, read);
+        //    System.out.println("pal = "+end.palavra);
+        if (isHit(end)) { //Verifica se é hit, e, se for, atualiza o bit de sujeira, caso necessário.
+            this.contadorDeHit++;
+            //   System.out.println("HIT: endereco: " + end.endereco);
+            //    System.err.println("");
+            if (read) {
+                this.contadorDeCiclos += ConstanteDeTempo.hit_read;
+                this.leituraCache++;
+            } else {
+                this.contadorDeCiclos += ConstanteDeTempo.hit_write; //contabiliza ciclos, inclusive os da comparação
+                this.escritaCache++;
+            }
+
+        } else {
+            //Deu miss
+            //System.out.println("MISS " + address);
+            this.contadorDeMiss++;
+
+            if (read) {
+                this.contadorDeCiclos += ConstanteDeTempo.leitura_miss;
+            } else {
+                this.contadorDeCiclos += ConstanteDeTempo.escrita_miss;
+            }
+
+            this.requisicaoDeBlocoNoConjunto(end);
+            //conjuntos[end.conjunto].requisicaoDeBlocoNoConjunto(end,this.redundancia);          
+
+        }
+    }
+
+    public long getWB() {
+        return this.contadorDeWB;
+    }
+
+    public long getCiclos() {
+        return this.contadorDeCiclos;
+    }
+
+    private void tratarWB(Requisicao req, int numBloco) {
+        Conjunto c = this.conjuntos[req.conjunto];
+        //System.out.println("WB do bloco - "+numBloco);
+        if (c.getBloco(numBloco).isSujo()) {
+            this.leituraCache += 32;
+            //Contabilizar um WB   
+            this.contadorDeCiclos += ConstanteDeTempo.WB;
+            this.contadorDeWB++;
+            this.escritaSDRAM += 32;
+            //   System.err.println("fazer WB");
+        }
+        c.desalocaBloco(numBloco);
+    }
+
+    public Conjunto[] getConjuntos() {
+        return this.conjuntos;
+    }
+
+    private void requisicaoDeBlocoNoConjunto(Requisicao req) {
+        Conjunto c = this.conjuntos[req.conjunto];
+        int blocoSelecionado;
+
+        if (c.usaRR()) {   //VAI USAR RR
+            //System.out.println("usando RR");
+            blocoSelecionado = c.getRR();
+            if (!c.getBloco(blocoSelecionado).isCachavel()) {
+         //       System.out.println("Mapeado para um bloco não cachavel");
+                if (req.read) {
+                    this.leituraSDRAMDevidoAERRO += 1;
+                    this.leituraSDRAM += 1;
+                    this.contadorDeCiclos += ConstanteDeTempo.acesso_1_palavra_na_SDRAM;
+                }else{
+                    this.escritaSDRAMDevidoAERRO += 1;
+                    this.escritaSDRAM += 1;
+                    this.contadorDeCiclos += ConstanteDeTempo.acesso_1_palavra_na_SDRAM;
+                }
+            } else if (c.getBloco(blocoSelecionado).hasErrorInBloco()) {
+
+                c.setarBlocoAsInvalid(blocoSelecionado);
+                
+                this.escritaCache += 32;
+                //verificar se é escrita. Se for, fazer "WB"
+                if (!req.read) {
+                    this.escritaSDRAMDevidoAERRO += 1;
+                    this.escritaSDRAM += 1;
+                    this.contadorDeCiclos += ConstanteDeTempo.acesso_1_palavra_na_SDRAM;
+                }
+
+                //Contabiliza o que for necessário aqui em embaixo
+            } else {
+                this.escritaCache += 32;
+                
+                if(!req.read){
+                    this.escritaCache++;
+                }
+                //verifica WB
+                if(c.getBloco(blocoSelecionado).isValido() && c.getBloco(blocoSelecionado).isSujo()){
+                    this.tratarWB(req, blocoSelecionado);
+                }
+                
+                c.alocarBloco(req, blocoSelecionado);
+            }
+            //Atualiza as variáves da política de substituição de bloco            
+            c.lru.atualizaLRU(blocoSelecionado);
+            c.atualizaRR();
+
+        } else {
+            //System.out.println("LRU");
+            //Usa LRU          
+            blocoSelecionado = c.lru.getBlocoFromLru();
+
+            if (!c.getBloco(blocoSelecionado).isCachavel()) {
+                //Contabilizar ao acesso à memória principal e seus ciclos
+                //System.out.println("Conjunto incachavel");
+                if (req.read) {
+                    this.leituraSDRAMDevidoAERRO += 1;
+                    this.leituraSDRAM += 1;
+                } else {
+                    this.escritaSDRAMDevidoAERRO += 1;
+                    this.contadorDeCiclos += ConstanteDeTempo.acesso_1_palavra_na_SDRAM;
+                    this.escritaSDRAM += 1;
+                }
+            } else {
+                this.leituraSDRAM += 32;
+                this.escritaCache += 32;
+
+                if (req.read) {
+                    this.leituraCache++;
+                } else {
+                    this.escritaCache += 1;
+                }
+
+                this.tratarWB(req, blocoSelecionado); //Já contabiliza ciclos e WB                
+                c.alocarBloco(req, blocoSelecionado);
+                c.lru.atualizaLRU(blocoSelecionado);
+            }
+        }
+    }
+
+    /**
+     * Insere erro na memória cache
+     *
+     * @param conjunto - Número do conjunto
+     * @param bloco - Número do bloco
+     * @param palavra - Número da palavra
+     */
+    public void inserirErro(int conjunto, int bloco, int palavra) {
+        this.conjuntos[conjunto].getBloco(bloco).inserirErro(palavra);
+    }
+
+    private boolean isHit(Requisicao address) {
+        return conjuntos[address.conjunto].verificaHit(address);
+    }
+
+    @Override
+    public String toString() {
+        String s = "";
+        Bloco[] b;
+        int i = 0;
+        for (Conjunto conjunto : conjuntos) {
+            s += "Conjunto " + i + "\n";
+            //s += conjunto;
+            b = conjunto.getBlocos();
+            int j = 0;
+            for (Bloco bloco : b) {
+                s += "Bloco " + j + "\n";
+                s += bloco + "\n";
+                j++;
+            }
+            s += "\n\n\n";
+            i++;
+        }
+        return s; //To change body of generated methods, choose Tools | Templates.
+    }
+
+}

+ 143 - 0
src/cache/Conjunto.java

@@ -0,0 +1,143 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+import java.util.ArrayList;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class Conjunto {
+
+    private Bloco[] blocosDoConjunto;
+
+    private int RR;
+    public LRU lru;
+    
+   
+    
+    public Conjunto() {
+        this.RR = 0;
+        this.lru = new LRU();
+        
+        this.blocosDoConjunto = new Bloco[4];
+        for (int i = 0; i < 4; i++) {
+            this.blocosDoConjunto[i] = new Bloco();
+        }
+    }
+    
+    public boolean hasBlocoLivre() {
+        for (int i = 0; i < 4; i++) {
+            if (!this.blocosDoConjunto[i].isValido()) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    public boolean usaRR(){
+        for(int i = 0; i < 4; i++){
+            if (this.blocosDoConjunto[i].isFirstWrite()) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+
+    public boolean isBlocoOcupado(int num_bloco) {
+        return this.blocosDoConjunto[num_bloco].isValido();
+    }
+    
+            
+    public boolean arrayHasTheValue(ArrayList<Integer> v, Integer num) {
+        for (Integer integer : v) {
+            if (integer == num) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public int getRR(){
+       return this.RR;
+    }
+    
+    
+
+    public LRU getLRU() {
+        return this.lru;
+    }
+    
+    public void desalocaBloco(int numBloco){
+        this.blocosDoConjunto[numBloco].setValidadeDoBloco(false);
+        this.blocosDoConjunto[numBloco].setSujeira(false);        
+    }
+    
+    public void alocarBloco(Requisicao req, int numBloco) {
+        this.blocosDoConjunto[numBloco].setSujeira(!req.read);
+        this.blocosDoConjunto[numBloco].setValidadeDoBloco(true);
+        this.blocosDoConjunto[numBloco].setLimitesDoBloco(req.limiteInf, req.limiteSup);      
+    }
+    
+    public Bloco getBloco(int numBloco){
+        return this.blocosDoConjunto[numBloco];
+    }
+    
+    public void setarBlocoAsInvalid(int num){
+        this.blocosDoConjunto[num].setarComoInvalido();        
+    }
+    
+    public void atualizaRR() {
+        this.RR++;
+        if (this.RR == 4) {
+            this.RR = 0;
+        }
+    }
+
+    public Bloco[] getBlocos() {
+        return this.blocosDoConjunto;
+    }
+    
+    /*public int getBlocoIndexFromAddress(int a){
+        
+    }*/
+    
+    /**
+     * Verifica se o bloco está nesse conjunto e atualiza o bit de sujeira do bloco se for um write
+     *
+     * @param req
+     * @return
+     */
+    public boolean verificaHit(Requisicao req) {
+        for (int i = 0; i < 4; i++) {
+            //verifica o hit
+            if (this.blocosDoConjunto[i].isValido() && this.blocosDoConjunto[i].verificaBloco(req.endereco)) {
+
+                //atualiza a política LRU
+                this.lru.atualizaLRU(i);
+
+                if (!req.read) {//Se for uma escrita, atualiza para bloco sujo
+                    this.blocosDoConjunto[i].setSujeira(true);
+                }
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    public int getBlocoFromReq(Requisicao req) {
+        for (int i = 0; i < 4; i++) {
+            //verifica o hit
+            if (this.blocosDoConjunto[i].isValido() && this.blocosDoConjunto[i].verificaBloco(req.endereco)) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+}

+ 19 - 0
src/cache/ConstanteDeTempo.java

@@ -0,0 +1,19 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class ConstanteDeTempo {
+    static final int WB = 84; //(32 + 50 + 2)
+    static final int hit_write = 4; //(2 + 2)
+    static final int hit_read = 2; //(2)
+    static final int leitura_miss = 118; //(2 (verifica hit) + 50(SDRAM) + 32(escreve cache) + 32(waitFIFO) + 2(controle))
+    static final int escrita_miss = 121;//(2 (verifica hit) + 50(SDRAM) + 32(escreve cache) + 34(waitFIFO) + 2(controle) + 1)
+    static final int acesso_1_palavra_na_SDRAM = 19; //(1 + 19)    
+}

+ 40 - 0
src/cache/Erro.java

@@ -0,0 +1,40 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class Erro {
+    private int conjunto;
+    private int bloco;
+    private int palavra;
+    
+    public Erro(int conjunto,int bloco,int palavra){
+        this.conjunto = conjunto;
+        this.bloco = bloco;
+        this.palavra = palavra;
+    }
+    
+    public int getConjunto(){
+        return this.conjunto;
+    }
+    
+    public int getBloco(){
+        return this.bloco;
+    }
+    
+    public int getPalavra(){
+        return this.palavra;
+    }
+
+    @Override
+    public String toString() {
+        return conjunto+" "+bloco+" "+palavra; //To change body of generated methods, choose Tools | Templates.
+    }
+    
+}

+ 52 - 0
src/cache/Erros.java

@@ -0,0 +1,52 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+import java.util.ArrayList;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class Erros {
+    private ArrayList<Erro> erroCache;
+    private ArrayList<Erro> erroRed;
+    
+    public Erros(ArrayList<Erro> erroCache,ArrayList<Erro> erroRed){
+        this.erroCache = erroCache;
+        this.erroRed = erroRed;        
+    }
+    
+    public ArrayList<Erro> getErroCache() {
+        return erroCache;
+    }
+
+    public void setErroCache(ArrayList<Erro> erroCache) {
+        this.erroCache = erroCache;
+    }
+
+    public ArrayList<Erro> getErroRed() {
+        return erroRed;
+    }
+
+    public void setErroRed(ArrayList<Erro> erroRed) {
+        this.erroRed = erroRed;
+    }
+
+    @Override
+    public String toString() {
+        String s = "cache: "+this.erroCache.toString();
+        
+        if(this.erroRed != null)
+            s += "\nred: "+ this.erroRed.toString();
+        
+        return s; //To change body of generated methods, choose Tools | Templates.
+    }
+    
+    
+    
+    
+}

+ 113 - 0
src/cache/LRU.java

@@ -0,0 +1,113 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+import java.util.ArrayList;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class LRU {    
+    ArrayList<Integer> traceLRU;
+    private boolean firstTime;
+    private int TAM;
+    
+    public LRU(){
+        this.TAM = 4;
+        this.firstTime = true;
+        this.traceLRU = new ArrayList<>(); 
+        
+    }
+    
+    public ArrayList<Integer> getTraceLRU(){
+        return this.traceLRU;
+    }
+    
+    private boolean isCheio(){        
+        return this.traceLRU.size() == TAM;
+    }
+    
+    private int getIndexFromBloco(int num_bloco){
+        for(int i = 0; i < this.traceLRU.size(); i++){
+            if(this.traceLRU.get(i) == num_bloco){
+                return i;
+            }            
+        }
+        return -1;
+    }
+    
+    private boolean containsBloco(int num_bloco){
+        for(int i = 0; i < this.traceLRU.size(); i++){
+            if(this.traceLRU.get(i) == num_bloco){
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    private void atualizaTraceLRU(int indexDoAcesso){
+        int bloco = this.traceLRU.get(indexDoAcesso);
+        
+        for(; indexDoAcesso < this.traceLRU.size()-1; indexDoAcesso++){
+            this.traceLRU.set(indexDoAcesso,this.traceLRU.get(indexDoAcesso+1));
+        }        
+        this.traceLRU.set(indexDoAcesso, bloco);
+    }
+    
+    private void insereNoFinal(int numBloco){
+        this.traceLRU.add(numBloco);
+    }
+    
+    public void atualizaLRU(int bloco){        
+        //Caso o trace ainda não tenha sido preenchido
+        if(!isCheio() && containsBloco(bloco)){
+            this.atualizaTraceLRU(getIndexFromBloco(bloco));
+            return;
+        }else if(!isCheio()){
+            
+            this.insereNoFinal(bloco);
+            return;
+        }
+        
+        
+        //Caso já tenha sido preenchido
+        int indiceBloco = 0;
+        for(; indiceBloco < this.traceLRU.size(); indiceBloco++){
+            if(this.traceLRU.get(indiceBloco) == bloco){
+                break;
+            }
+        }
+        
+        for(; indiceBloco < this.traceLRU.size()-1;indiceBloco++){
+            this.traceLRU.set(indiceBloco, this.traceLRU.get(indiceBloco+1));
+        }
+        
+        this.traceLRU.set(this.traceLRU.size()-1, bloco);        
+    }
+    
+    public int getBlocoFromLru(){
+        if(this.firstTime){
+            this.firstTime = false;
+            this.TAM = this.traceLRU.size();
+        }
+        if(this.traceLRU.isEmpty()){
+            return -1;
+        }
+        return this.traceLRU.get(0);
+    }    
+
+    @Override
+    public String toString() {
+        String s = this.traceLRU.toString();        
+        s += "\n";
+        
+        return s; //To change body of generated methods, choose Tools | Templates.
+    }
+    
+    
+    
+}

+ 50 - 0
src/cache/PalavrasRedundancia.java

@@ -0,0 +1,50 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class PalavrasRedundancia {
+    private boolean validade;
+    private int tag; //A tag é o número do conjunto
+    private boolean erro;
+    
+    public PalavrasRedundancia(){
+        this.validade = false;
+        this.erro = false;
+        this.tag = 0;
+    }
+    
+    public void leituraEspecial(int tag){
+        if(this.tag == tag){            
+            this.validade = false;
+            this.tag = -1;
+        }
+    }
+    
+    public void inserirErro(){
+        this.erro = true;        
+    }
+    
+    public boolean hasError(){
+        return this.erro;
+    }
+    
+    public int getTag(){
+        return this.tag;
+    }
+    
+    public boolean isValid(){
+        return this.validade;
+    }
+    
+    public void writeAWord(int tag){
+        this.validade = true;
+        this.tag = tag;
+    }
+}

+ 44 - 0
src/cache/Requisicao.java

@@ -0,0 +1,44 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package cache;
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class Requisicao {
+    public int palavra;
+    public int conjunto;   
+    public long endereco;
+    
+    public long limiteSup;
+    public long limiteInf;
+    
+    public boolean read;
+    
+    
+    public Requisicao(long address,boolean read){
+        long aux;
+        
+        this.read = read;
+        this.palavra = (int)(address/4)%32;
+        
+        this.endereco = address;
+        
+        aux = address/128;
+        
+        if(aux > 31){
+            aux = aux%32;
+            this.conjunto = (int)aux;
+        }else{
+            this.conjunto = (int)aux;
+        }
+        
+        this.limiteInf = address - palavra*4;
+        this.limiteSup = limiteInf + 124;        
+    }
+    
+}

+ 220 - 0
src/simuladorcache/SimuladorCache.java

@@ -0,0 +1,220 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package simuladorcache;
+
+import cache.*;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.util.ArrayList;
+import java.util.Scanner;
+
+
+/**
+ *
+ * @author Juninho Carlos
+ */
+public class SimuladorCache {
+
+    public static Cache teste1() {
+        Cache c = new Cache();
+
+        c.inserirErro(0, 0, 0);
+        c.inserirErro(0, 0, 5);
+        c.inserirErro(0, 0, 12);
+        c.inserirErro(0, 0, 15);
+
+        c.requisicaoParaCache(0, false);
+        c.requisicaoParaCache(16, true);
+        c.requisicaoParaCache(4096, false);
+        c.requisicaoParaCache(8192, true);
+        c.requisicaoParaCache(12288, false);
+        c.requisicaoParaCache(16384, true);
+
+        return c;
+    }
+
+    public static Cache teste2() {
+        Cache c = new Cache();
+
+        c.inserirErro(0, 0, 0);
+        c.inserirErro(4, 0, 5);
+        c.inserirErro(8, 0, 12);
+        c.inserirErro(8, 0, 13);
+        c.inserirErro(12, 0, 15);
+
+        c.inserirErro(16, 0, 0);
+        c.inserirErro(16, 0, 5);
+        c.inserirErro(16, 0, 12);
+        c.inserirErro(16, 0, 15);
+
+        c.requisicaoParaCache(0, false);
+        c.requisicaoParaCache(4, false);
+        c.requisicaoParaCache(512, false);
+        c.requisicaoParaCache(1024, false);
+        c.requisicaoParaCache(1536, false);
+        c.requisicaoParaCache(2048, true);
+
+        return c;
+    }
+
+    public static Cache teste3() {
+        Cache c = new Cache();
+
+        c.inserirErro(0, 0, 0);
+        c.inserirErro(4, 0, 5);
+        c.inserirErro(8, 0, 12);
+        c.inserirErro(8, 0, 13);
+        c.inserirErro(12, 0, 15);
+
+        c.inserirErro(16, 0, 0);
+        c.inserirErro(16, 0, 5);
+        c.inserirErro(16, 0, 12);
+        c.inserirErro(16, 0, 15);
+
+        c.requisicaoParaCache(0, false);
+        c.requisicaoParaCache(512, true);
+        c.requisicaoParaCache(1024, true);
+        c.requisicaoParaCache(1536, true);
+        c.requisicaoParaCache(2048, true);
+
+        return c;
+    }
+
+    public static Cache teste4() {
+        Cache c = new Cache();
+
+        c.inserirErro(0, 0, 0);
+       
+
+        c.requisicaoParaCache(0, true);
+        c.requisicaoParaCache(4096, true);
+        c.requisicaoParaCache(8192, true);
+        c.requisicaoParaCache(12288, true);
+        c.requisicaoParaCache(16384, true);
+
+        return c;
+    }
+    public static ArrayList<Erro> trataString(String erro){
+        String[] erros = erro.split(" ");
+        
+        ArrayList<Erro> arrayDeErros = new ArrayList<>();
+        
+        for (String erro1 : erros){
+            String[] partes = erro1.split("/");
+            Integer conjunto = Integer.parseInt(partes[0]);
+            Integer bloco = Integer.parseInt(partes[1]);
+            Integer palavra = Integer.parseInt(partes[2]);
+            Erro e = new Erro(conjunto, bloco, palavra);
+            arrayDeErros.add(e);
+        }
+        
+        return arrayDeErros;
+    }
+    /**
+     * Retorna um array onde a posição zero tem os erros da cache o a posicao 1 tem os erros da red
+     * @param path
+     * @return
+     * @throws FileNotFoundException 
+     */
+    public static Erros initErro(String path) throws FileNotFoundException{
+        Scanner in = new Scanner(new FileReader(path));
+        String s = in.nextLine();
+        String []erros = s.split(";");
+        
+        String erroCache = erros[0];        
+        String erroRed;
+        
+        
+        ArrayList<Erro> red = null;
+        
+         ArrayList<Erro> cache = trataString(erroCache);
+        if(erros.length > 1){
+            erroRed = erros[1];
+            red = trataString(erroRed);
+        }
+        
+        Erros aux = new Erros(cache, red);
+       // System.err.println(teste.toString());
+        return aux;
+    }
+    
+    /**
+     * @param args the command line arguments
+     */
+    public static void main(String[] args) throws FileNotFoundException {
+        /*/Area de debug
+        Cache cache = new Cache();
+        cache.inserirErro(0, 0, 5);  
+        cache.inserirErro(0, 1, 5);  
+//        cache.inserirErro(0, 2, 5);  
+//        cache.inserirErro(0, 3, 5);  
+        
+        cache.requisicaoParaCache(20, true);
+        cache.requisicaoParaCache(20, false);
+        cache.requisicaoParaCache(20, true);
+        cache.requisicaoParaCache(4096, false);
+        cache.requisicaoParaCache(8192, true);
+        cache.requisicaoParaCache(12288, true);
+        cache.requisicaoParaCache(16384, true);
+        cache.requisicaoParaCache(20, false);
+        
+//        cache.requisicaoParaCache(1024, true);
+//        System.out.println("LRU: "+cache.getConjuntos()[0].lru);
+        
+        
+        
+        
+//        cache.requisicaoParaCache(512, true);
+//        cache.requisicaoParaCache(512, true);
+        
+//        System.out.println("Cache: "+ cache);
+        System.out.println("Hit = " + cache.getHit());
+        System.out.println("Miss = " + cache.getMiss());
+        System.out.println("Writeback = " + cache.getWB());
+        System.out.println("LeituraCache = " + cache.getLeituraCache());
+        System.out.println("EscritaCache = " + cache.getEscritaCache()); 
+        System.out.println("LeituraSDRAM = " + cache.getLeituraSDRAM());
+        System.out.println("EscritaSDRAM = " + cache.getEscritaSDRAM()); 
+        System.out.println("Ciclos = " + cache.getCiclos());  
+        
+//       */
+///*        
+        Cache cache = new Cache();
+        
+        String pathErros = args[0];
+        String pathTrace = args[1];
+        
+        Erros errosInit = initErro(pathErros);
+        
+        //inicializa os erros da cache
+        for (Erro arg : errosInit.getErroCache()) {
+            cache.inserirErro(arg.getConjunto(), arg.getBloco(), arg.getPalavra());
+        }
+        
+        
+        //Executa as requisições do trace
+        Arquivo trace = new Arquivo(pathTrace);
+        while(trace.lerArquivo()){
+            Requisicao atual = trace.getRequisicao();
+            cache.requisicaoParaCache(atual.endereco, atual.read);
+        }
+        
+        
+        System.out.println("Hit = " + cache.getHit());
+        System.out.println("Miss = " + cache.getMiss());
+        System.out.println("Writeback = " + cache.getWB());
+        System.out.println("LeituraCache = " + cache.getLeituraCache());
+        System.out.println("EscritaCache = " + cache.getEscritaCache()); 
+        System.out.println("LeituraSDRAM = " + cache.getLeituraSDRAM());
+        System.out.println("EscritaSDRAM = " + cache.getEscritaSDRAM()); 
+        System.out.println("LeituraSDRAMDevidoAERRO = " + cache.getLeituraSDRAMDevidoErro()); 
+        System.out.println("EscritaSDRAMDevidoAERRO = " + cache.getEscritaSDRAMDevidoErro());         
+        System.out.println("Ciclos = " + cache.getCiclos());                    
+        
+//        */
+    }
+
+}

+ 15 - 0
src/teste.txt

@@ -0,0 +1,15 @@
+w1204
+w4294967292
+w4294967288
+w4294967284
+w4294967280
+w4294967260
+w4294967256
+w4294967252
+w4294967248
+w4294967264
+w4294967268
+w4294967272
+r4294967268
+r4294967272
+r4294967264