Browse Source

Commit inicial

juninho95 6 years ago
commit
2689e5b3c6
47 changed files with 3154 additions and 0 deletions
  1. 1 0
      .gitignore
  2. BIN
      SimuladorCache.jar
  3. 73 0
      build.xml
  4. 4 0
      build/built-jar.properties
  5. 0 0
      build/classes/.netbeans_automatic_build
  6. 0 0
      build/classes/.netbeans_update_resources
  7. 1 0
      build/classes/1.txt
  8. BIN
      build/classes/cache/Arquivo.class
  9. BIN
      build/classes/cache/Bloco.class
  10. BIN
      build/classes/cache/BlocoRedundancia.class
  11. BIN
      build/classes/cache/Cache.class
  12. BIN
      build/classes/cache/Conjunto.class
  13. BIN
      build/classes/cache/ConjuntoRedundancia.class
  14. BIN
      build/classes/cache/ConstanteDeTempo.class
  15. BIN
      build/classes/cache/Erro.class
  16. BIN
      build/classes/cache/Erros.class
  17. BIN
      build/classes/cache/LRU.class
  18. BIN
      build/classes/cache/PalavrasRedundancia.class
  19. BIN
      build/classes/cache/Redundancia.class
  20. BIN
      build/classes/cache/Requisicao.class
  21. BIN
      build/classes/simuladorcache/SimuladorCache.class
  22. 15 0
      build/classes/teste.txt
  23. 1 0
      duvida.txt
  24. 3 0
      manifest.mf
  25. 1419 0
      nbproject/build-impl.xml
  26. 8 0
      nbproject/genfiles.properties
  27. 0 0
      nbproject/private/config.properties
  28. 7 0
      nbproject/private/private.properties
  29. 15 0
      nbproject/private/private.xml
  30. 76 0
      nbproject/project.properties
  31. 15 0
      nbproject/project.xml
  32. 1 0
      src/1.txt
  33. 38 0
      src/cache/Arquivo.java
  34. 112 0
      src/cache/Bloco.java
  35. 55 0
      src/cache/BlocoRedundancia.java
  36. 489 0
      src/cache/Cache.java
  37. 148 0
      src/cache/Conjunto.java
  38. 41 0
      src/cache/ConjuntoRedundancia.java
  39. 20 0
      src/cache/ConstanteDeTempo.java
  40. 40 0
      src/cache/Erro.java
  41. 52 0
      src/cache/Erros.java
  42. 117 0
      src/cache/LRU.java
  43. 50 0
      src/cache/PalavrasRedundancia.java
  44. 79 0
      src/cache/Redundancia.java
  45. 44 0
      src/cache/Requisicao.java
  46. 215 0
      src/simuladorcache/SimuladorCache.java
  47. 15 0
      src/teste.txt

+ 1 - 0
.gitignore

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

BIN
SimuladorCache.jar


+ 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="SimuladorCache" default="default" basedir=".">
+    <description>Builds, tests, and runs the project SimuladorCache.</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="SimuladorCache-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>

+ 4 - 0
build/built-jar.properties

@@ -0,0 +1,4 @@
+#Tue, 07 Mar 2017 13:18:43 -0300
+
+
+C\:\\Users\\Juninho\ Carlos\\Documents\\NetBeansProjects\\SimuladorCache=

+ 0 - 0
build/classes/.netbeans_automatic_build


+ 0 - 0
build/classes/.netbeans_update_resources


+ 1 - 0
build/classes/1.txt

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

BIN
build/classes/cache/Arquivo.class


BIN
build/classes/cache/Bloco.class


BIN
build/classes/cache/BlocoRedundancia.class


BIN
build/classes/cache/Cache.class


BIN
build/classes/cache/Conjunto.class


BIN
build/classes/cache/ConjuntoRedundancia.class


BIN
build/classes/cache/ConstanteDeTempo.class


BIN
build/classes/cache/Erro.class


BIN
build/classes/cache/Erros.class


BIN
build/classes/cache/LRU.class


BIN
build/classes/cache/PalavrasRedundancia.class


BIN
build/classes/cache/Redundancia.class


BIN
build/classes/cache/Requisicao.class


BIN
build/classes/simuladorcache/SimuladorCache.class


+ 15 - 0
build/classes/teste.txt

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

+ 1 - 0
duvida.txt

@@ -0,0 +1 @@
+Como é feito quando tem mais de uma escrita na redundacia? Compara só a primeira palavra?

+ 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=43d807eb
+build.xml.script.CRC32=81d4f580
+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=43d807eb
+nbproject/build-impl.xml.script.CRC32=d46a7093
+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\\\\24.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=C:\\Users\\Juninho Carlos\\AppData\\Roaming\\NetBeans\\8.1\\build.properties

+ 15 - 0
nbproject/private/private.xml

@@ -0,0 +1,15 @@
+<?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:/C:/Users/Juninho%20Carlos/Documents/NetBeansProjects/SimuladorCache/src/cache/Bloco.java</file>
+            <file>file:/C:/Users/Juninho%20Carlos/Documents/NetBeansProjects/SimuladorCache/src/simuladorcache/SimuladorCache.java</file>
+            <file>file:/C:/Users/Juninho%20Carlos/Documents/NetBeansProjects/SimuladorCache/src/cache/Redundancia.java</file>
+            <file>file:/C:/Users/Juninho%20Carlos/Documents/NetBeansProjects/SimuladorCache/src/cache/Requisicao.java</file>
+            <file>file:/C:/Users/Juninho%20Carlos/Documents/NetBeansProjects/SimuladorCache/src/cache/Conjunto.java</file>
+            <file>file:/C:/Users/Juninho%20Carlos/Documents/NetBeansProjects/SimuladorCache/src/cache/LRU.java</file>
+            <file>file:/C:/Users/Juninho%20Carlos/Documents/NetBeansProjects/SimuladorCache/src/cache/Cache.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=SimuladorCache
+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}/SimuladorCache.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>SimuladorCache</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);
+    }
+    
+    
+
+}

+ 112 - 0
src/cache/Bloco.java

@@ -0,0 +1,112 @@
+/*
+ * 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;
+    }
+    
+    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;
+    }
+    
+    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;
+    }
+    
+    
+}

+ 55 - 0
src/cache/BlocoRedundancia.java

@@ -0,0 +1,55 @@
+/*
+ * 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 BlocoRedundancia{    
+    private PalavrasRedundancia[] palavras;
+    
+    public BlocoRedundancia(){
+        this.palavras = new PalavrasRedundancia[32];
+        for(int i = 0 ; i < 32; i++){
+            this.palavras[i] = new PalavrasRedundancia();
+        }
+    }
+    
+    public void leituraEspecialNoBloco(int tag){
+        for(int i = 0; i < 32; i++){
+            this.palavras[i].leituraEspecial(tag);
+        }
+    }
+    
+    public PalavrasRedundancia getPalavra(int index){
+        return this.palavras[index];
+    }
+    
+    public PalavrasRedundancia[] getPalavras(){
+        return this.palavras;
+    }
+    
+    public int getTagFromAWord(int palavra){
+        return this.palavras[palavra].getTag();
+    }
+            
+    public void writeAWord(int palavra,int tag){
+        this.palavras[palavra].writeAWord(tag);
+    }
+
+    @Override
+    public String toString() {
+        String s = "";
+        int i = 0;
+        for (PalavrasRedundancia palavra : palavras) {
+            s += i + " - " + palavra.isValid()+ " "+ palavra.getTag()+"\n";            
+            i++;
+        }        
+        return s; //To change body of generated methods, choose Tools | Templates.
+    }
+    
+}

+ 489 - 0
src/cache/Cache.java

@@ -0,0 +1,489 @@
+/*
+ * 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;  //Ultimo contador que fiz
+    private long leituraCache;  //done
+    private long escritaRedundancia; //done
+    private long leituraRedundancia;
+    
+    private long contadorDeCiclos; //feito
+    private long contadorDeWB;     //feito
+    private long contadorDeWBForcado; //feito
+    
+    private long contadorDeLeituraEspecial;  //feito
+    
+    private long contadorDeHit;   //feito
+    private long contadorDeMiss;  //feito
+    
+    private long ContadorIncachavel;
+    
+    private long escritaSDRAM;
+    private long leituraSDRAM;
+    
+    private Redundancia redundancia;
+    private Conjunto[] conjuntos;
+
+    public Cache() {
+        this.redundancia = new Redundancia();
+        
+        this.escritaCache = 0;
+        this.escritaRedundancia = 0;
+        
+        this.leituraCache = 0;
+        this.leituraRedundancia = 0;
+        
+        
+        
+        this.contadorDeCiclos = 0;
+        this.contadorDeWB = 0;
+        this.contadorDeWBForcado = 0;
+        this.contadorDeLeituraEspecial = 0;
+        
+        this.contadorDeHit = 0;
+        this.contadorDeMiss = 0;
+        
+        this.ContadorIncachavel = 0;
+        
+        this.escritaSDRAM = 0;
+        this.leituraSDRAM = 0;
+        
+        this.conjuntos = new Conjunto[32];
+        for (int i = 0; i < 32; i++) {
+            this.conjuntos[i] = new Conjunto();
+        }
+    }
+    
+    public long getEscritaSDRAM(){
+        return this.escritaSDRAM;
+    }
+        
+    public long getLeituraSDRAM(){
+        return this.leituraSDRAM;
+    }
+    public long getContadorIncachavel(){
+        return this.ContadorIncachavel;
+    }
+    
+    public long getcontadorLeituraEspecial(){
+        return this.contadorDeLeituraEspecial;
+    }
+    public long getWBForcado(){
+        return this.contadorDeWBForcado;
+    }
+    
+    public long getHit(){
+        return this.contadorDeHit;
+    }
+    
+    public long getMiss(){
+        return this.contadorDeMiss;
+    }
+    
+    public long getEscritaCache(){
+        return this.escritaCache;
+    }
+    
+    public long getEscritaRedundancia(){
+        return this.escritaRedundancia;
+    }
+    
+    public long getLeituraCache(){
+        return this.leituraCache;
+    }
+    
+    public long getLeituraRedundancia(){
+        return this.leituraRedundancia;
+    }
+    
+    /**
+     *
+     * @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.err.println("HIT: endereco: " + end.endereco);
+        //    System.err.println("");
+            if (read) {
+                this.contadorDeCiclos += ConstanteDeTempo.hit_read;                
+            } else {
+                this.contadorDeCiclos += ConstanteDeTempo.hit_write; //contabiliza ciclos, inclusive os da comparação
+            }
+            
+            int bloco = this.conjuntos[end.conjunto].getBlocoFromReq(end);
+            
+            boolean erro = this.conjuntos[end.conjunto].getBloco(bloco).getErroFromPalavra(end.palavra);
+            if(!read){
+                if(erro){
+                    this.escritaRedundancia++;                    
+                }else{
+                    this.escritaCache++; 
+                }
+            }else{
+                if(erro){
+                    this.leituraRedundancia++;
+                }else{
+                    this.leituraCache++;
+                }
+            }
+            //Tem que atualizar bit de sujeira caso seja escrita            
+            //Deu hit e tem que verificar se tá na cache ou na redundancia            
+            //contadorDeHit++;
+        } else {
+            //Deu miss
+            //System.err.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 void inserirErroRedundancia(int conjunto, int bloco, int palavra) {
+        this.redundancia.inserirErro(conjunto, bloco, palavra);
+    }
+
+    private ArrayList<Integer> escreverBlocoNaRed(Requisicao requisicao, int bloco) {
+        
+        Requisicao req = new Requisicao(requisicao.endereco, requisicao.read);
+                
+        ArrayList<Integer> enderecosToWB = new ArrayList<>();
+        Conjunto c = this.conjuntos[req.conjunto];
+        for (int i = 0; i < 32; i++) {
+            Requisicao aux = req;
+            aux.palavra = i;
+            if (c.getBloco(bloco).getErroDasPalavraDoBloco()[i]) {
+                
+                this.contadorDeCiclos += 3; //1 ciclo para escreve, um para ler, outro para comparar
+                this.leituraRedundancia++;
+                this.escritaRedundancia++;
+                
+                Integer numToWB = redundancia.escreverPalavraNaRedMiss(aux, bloco);
+                if (numToWB != null && numToWB == -1) {
+                    //Deu bosta
+                    ArrayList<Integer> bosta = new ArrayList<>();
+                    bosta.add(-1);
+                    return bosta;
+
+                }
+
+                if (numToWB != null) {
+                    if (!c.arrayHasTheValue(enderecosToWB, numToWB)) {
+                        enderecosToWB.add(numToWB);
+                    }
+                }
+            }else{
+                this.escritaCache++;
+            }
+        }
+        return enderecosToWB;
+    }
+
+    private void leituraEspecial(int tag, int bloco) {
+        this.leituraRedundancia += 32;
+        this.redundancia.leituraEspecial(tag, tag % 4, bloco);
+    }
+
+    /**
+     * Escreve palavra com erro na redundancia e faz os wb forçados/LE dos
+     * blocos necessários
+     *
+     * @param req
+     * @param c
+     *
+     * Retorna true quando detecta o erro na redundacia e false quando ñ tem
+     * erro na red
+     */
+    private boolean trataBlocoComErro(Requisicao req, Conjunto c, int bloco) {
+        ArrayList<Integer> enderecosToWB = escreverBlocoNaRed(req, bloco);
+
+        if (enderecosToWB.size() == 1 && enderecosToWB.get(0) == -1) { //Tentou escrever na Red e deu erro
+            return true;
+        }
+
+        if (enderecosToWB.size() > 0) { //Tratar WBs ou LE
+            //Requisicao r = new Requisicao(RR, true)
+        //    System.err.println("Fazendo WB forçado");
+        //    System.err.println("conjuntos wbackado/LE: " + enderecosToWB.toString());
+        //    System.err.println("bloco: " + bloco);
+
+            for (Integer integer : enderecosToWB) {
+                this.leituraEspecial(integer, bloco);
+                Conjunto wb = this.conjuntos[integer];
+
+                if (wb.getBlocos()[bloco].isSujo()) {
+                    //Faz WB-FORCADO
+        //            System.err.println("Fazendo WB-forcado do conjunto " + integer);
+                    
+                    this.contadorDeWBForcado++;                    
+                    this.contadorDeCiclos += ConstanteDeTempo.WB;
+                    this.leituraRedundancia += 32;
+                    this.escritaSDRAM += 32;
+                    wb.desalocaBloco(bloco);
+
+                } else {
+         //           System.err.println("Fazendo LE do conjunto " + integer);
+                    //Contabilizar leitura especial
+                    this.contadorDeLeituraEspecial++;
+                    this.leituraRedundancia+=32;
+                    this.contadorDeCiclos += ConstanteDeTempo.leitura_especial;
+                    wb.desalocaBloco(bloco);
+                }
+            }
+        } 
+        return false;
+    }
+    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];
+        
+        if (c.getBloco(numBloco).hasErrorInBloco()) {
+            this.leituraEspecial(req.conjunto, numBloco);            
+            if(!c.getBloco(numBloco).isSujo()){
+                //Só contabiliza leitura especial se o bloco tiver erro
+                this.contadorDeLeituraEspecial++;
+                this.contadorDeCiclos += ConstanteDeTempo.leitura_especial;
+            }
+        }
+        if (c.getBloco(numBloco).isSujo()) {
+            //Contabilizar um WB   
+            this.contadorDeCiclos += ConstanteDeTempo.WB;
+            this.contadorDeWB++;
+            this.escritaSDRAM += 32;
+         //   System.err.println("fazer WB");
+        }
+        c.desalocaBloco(numBloco);
+    }
+
+    private void tratarErroNaRed(Requisicao req, int numBloco) {
+        Conjunto c = this.conjuntos[req.conjunto];
+        this.leituraEspecial(req.conjunto, c.getRR());
+        c.getBloco(numBloco).setarComoInvalido();
+    }
+    
+    private void contabilizaEscrita(Conjunto c, Requisicao req, int bloco){
+        if(!req.read){
+            if(c.getBloco(bloco).getErroDasPalavraDoBloco()[req.palavra]){                
+                this.escritaRedundancia++;
+            }else{
+                this.escritaCache++;
+            }
+        }
+    }
+    
+    private void contabilizaLeitura(int conjunto,int numBloco, int palavra){
+        boolean erro = this.conjuntos[conjunto].getBloco(numBloco).getErroFromPalavra(palavra);
+        if(erro){
+            this.leituraRedundancia++;
+        }else{
+            this.leituraCache++;
+        }
+    }
+    private void requisicaoDeBlocoNoConjunto(Requisicao req) {
+        //Se está nesse método,é porque deu miss
+        Conjunto c = this.conjuntos[req.conjunto];
+        boolean flagAlocaBloco = true;
+
+        if (c.hasBlocoLivre()) {  //USA RR
+    //        System.err.println("Vai usar RR. Vai para o bloco: "+c.getRR());
+            if (c.getBloco(c.getRR()).isCachavel()) {
+                
+                this.leituraSDRAM +=32;
+                
+                if(req.read){
+                    this.contabilizaLeitura(req.conjunto, c.getRR(), req.palavra);
+                }
+                
+                //Caso seja um bloco ocupado, precisa fazer verificar a necessidade de WB
+                if (c.isBlocoOcupado(c.getRR())) {
+    //                System.err.println("O bloco já estava ocupado. Vai fazer WB");
+                    this.tratarWB(req, c.getRR()); //Aqui já contabiliza ciclos e WB
+                }
+                if (c.getBloco(c.getRR()).hasErrorInBloco()) {  //Verifica se tem erro nas palavras do bloco                
+    //                System.err.println("Tem erro no bloco");
+                    flagAlocaBloco = !this.trataBlocoComErro(req, c, c.getRR());//Contabiliza escrita na cache
+                }else{
+                    this.escritaCache += 32;
+                }
+
+                if (flagAlocaBloco) {
+    //                System.err.println("Vai alocar o bloco");
+    //                System.err.println("");
+                    this.contabilizaEscrita(c,req,c.getRR());
+                    
+                    c.alocarBloco(req, c.getRR());
+                } else {
+     //               System.err.println("ñ Vai alocar o bloco");
+     //               System.err.println("");
+                    this.contadorDeWBForcado++;
+                    this.escritaSDRAM += 32;
+                    //Não foi colocado em Cache pois tem erro na red                    
+                    if (req.read) {
+                        this.contadorDeCiclos += 1 + 1; //1 ciclo para devolver + 1 para acessar vetor de erros
+                    } else {
+                        this.contadorDeCiclos += ConstanteDeTempo.escrita_1_palavra_na_SDRAM;
+                    }
+
+                    this.tratarErroNaRed(req,c.getRR());
+                    //Aqui falta contabilizar algumas coisas (tempo se for write)
+                }
+                //Atualiza as variáves da política de substituição de bloco
+                c.lru.atualizaLRU(c.getRR());
+                c.atualizaRR();
+            } else {
+                this.ContadorIncachavel++;
+                
+                
+                c.atualizaRR();
+        //        System.err.println("Incachavel");
+                //Só contabiliza o custo da operação na memória principal
+                if (req.read) {
+                    this.contadorDeCiclos += 1;
+                    this.leituraSDRAM += 1;
+                } else {
+                    this.escritaSDRAM += 1;                    
+                    this.contadorDeCiclos += ConstanteDeTempo.escrita_1_palavra_na_SDRAM;
+                }
+
+            }
+        } else {
+            //Usa LRU
+        //    System.err.println("Vai usar LRU. Vai para o bloco: "+c.lru.getBlocoFromLru());
+            int blocoSelecionado = c.lru.getBlocoFromLru();
+            if (c.getBloco(blocoSelecionado).isCachavel()) {
+                
+                this.leituraSDRAM +=32;
+                if(req.read){
+                    this.contabilizaLeitura(req.conjunto, blocoSelecionado, req.palavra);
+                }
+                
+                if (c.getBloco(blocoSelecionado).hasErrorInBloco()) {
+                //    System.err.println("Tem erro no bloco");
+                    //Faz WB do bloco que foi selecionado para ser retirado da Cache
+                    this.tratarWB(req, blocoSelecionado); //Já contabiliza ciclos e WB
+
+                    //Escreve novo bloco na cache e os endereços com erro na red. Além disso, faz WBF e LE
+                    flagAlocaBloco = !this.trataBlocoComErro(req, c, blocoSelecionado); //Contabiliza escrita
+
+                    if (flagAlocaBloco) {
+                    //    System.err.println("Vai alocar o bloco\n");
+                    //    System.err.println("");
+                        this.contabilizaEscrita(c, req,blocoSelecionado);
+                        c.alocarBloco(req, c.getRR());
+                    } else {
+                    //    System.err.println("ñ Vai alocar o bloco\n");
+                    //    System.err.println("");
+                        //Não foi colocado em Cache pois tem erro na red
+                        this.contadorDeWBForcado++;
+                        this.tratarErroNaRed(req,blocoSelecionado);
+
+                        if (req.read) {
+                            this.contadorDeCiclos += 1;
+                        } else {
+                            this.contadorDeCiclos += ConstanteDeTempo.escrita_1_palavra_na_SDRAM;
+                        }
+
+                    }
+
+                } else{ //Caso o bloco não tenha erro, tratar as usual                
+                    this.escritaCache += 32;
+                    //Caso o Bloco esteja Sujo, precisa fazer WB
+                    if (c.getBlocos()[blocoSelecionado].isSujo()) {
+                        //Contabilizar WB
+                        this.tratarWB(req, blocoSelecionado);  //Já contabiliza WB
+                        c.alocarBloco(req, blocoSelecionado);
+                    } else {//Caso precise só trocar o bloco, pois está limpo
+                        // Contabiliza nada aqui, pois o bloco tá limpo
+                        c.alocarBloco(req, blocoSelecionado);
+                    }
+                }
+            } else {
+                //System.err.println("Incachavel");
+                //Só contabiliza o custo da operação na memória principal
+                this.ContadorIncachavel++;
+                if(req.read){
+                    this.leituraSDRAM+=1;
+                    this.contadorDeCiclos += 1;
+                }else{
+                    this.escritaSDRAM+=1;
+                    this.contadorDeCiclos += ConstanteDeTempo.escrita_1_palavra_na_SDRAM;
+                }
+            }
+            //Atualiza politica de substituição LRU
+            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].getBlocos()[bloco].inserirErro(palavra);
+    }
+
+    private Conjunto[] getConjuntos() {
+        return this.conjuntos;
+    }
+
+    private boolean isHit(Requisicao address) {
+        return conjuntos[address.conjunto].verificaHit(address);
+    }
+
+    public Redundancia getRedundancia() {
+        return this.redundancia;
+    }
+
+    @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.
+    }
+
+}

+ 148 - 0
src/cache/Conjunto.java

@@ -0,0 +1,148 @@
+/*
+ * 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;
+import java.util.Iterator;
+import java.util.Objects;
+
+/**
+ *
+ * @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 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;
+    }
+    /**
+     * Escreve as palavras com erro, de um bloco, na redundância.
+     * @param req
+     * @param redundancia
+     * @return Retorna os endereços que foram sobrescritos na redundancia
+     * 
+     */
+    
+    /**
+     * Escreve as palavras com erro, de um bloco, na redundância.
+     * @param req
+     * @param redundancia
+     * @param bloco
+     * @return Retorna os endereços que foram sobrescritos na redundancia
+     */
+    
+
+    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 atualizaRR() {
+        this.RR++;
+        if (this.RR == 4) {
+            this.RR = 0;
+        }
+    }
+
+    public boolean hasBlocoLivre() {
+        for (int i = 0; i < 4; i++) {
+            if (!this.blocosDoConjunto[i].isValido()) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    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;
+    }
+
+}

+ 41 - 0
src/cache/ConjuntoRedundancia.java

@@ -0,0 +1,41 @@
+/*
+ * 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 ConjuntoRedundancia {
+    private BlocoRedundancia[] blocosRed;
+    
+    public ConjuntoRedundancia(){
+        this.blocosRed = new BlocoRedundancia[4];
+        for(int i = 0; i < 4; i++){
+            this.blocosRed[i] = new BlocoRedundancia();
+        }
+    }
+    
+    public BlocoRedundancia[] getBlocos(){
+        return this.blocosRed;
+    }
+    
+    public boolean hasErroInPalavra(int bloco, int palavra){
+        return this.blocosRed[bloco].getPalavra(palavra).hasError();
+    }
+    
+    public boolean isPalavraValida(int bloco, int palavra){
+        return this.blocosRed[bloco].getPalavras()[palavra].isValid();
+    }
+    
+    public Integer getTagFromPalavra(int bloco, int palavra){
+        return this.blocosRed[bloco].getTagFromAWord(palavra);
+    }
+    
+    public void writeAWord(int tag, int bloco, int palavra){
+        this.blocosRed[bloco].writeAWord(palavra, tag);
+    }
+}

+ 20 - 0
src/cache/ConstanteDeTempo.java

@@ -0,0 +1,20 @@
+/*
+ * 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 leitura_especial = 34; //(32 + 2)
+    static final int escrita_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.
+    }
+    
+    
+    
+    
+}

+ 117 - 0
src/cache/LRU.java

@@ -0,0 +1,117 @@
+/*
+ * 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 LRU {    
+    private int[] traceLRU;
+    
+    public LRU(){
+        this.traceLRU = new int[4]; 
+        for(int i = 0; i < 4; i++){
+            this.traceLRU[i] = -1;
+        }
+    }
+    
+    public int[] getTraceLRU(){
+        return this.traceLRU;
+    }
+    
+    private boolean isCheio(){
+        for(int i = 0; i < 4; i++){            
+            if(this.traceLRU[i]==-1){
+                return false;
+            }
+        }
+        return true;
+    }
+    
+    private int getIndexFromBloco(int num_bloco){
+        for(int i = 0; i < 4; i++){
+            if(this.traceLRU[i] == num_bloco){
+                return i;
+            }            
+        }
+        return -1;
+    }
+    
+    private boolean containsBloco(int num_bloco){
+        for(int i = 0; i < 4; i++){
+            if(this.traceLRU[i] == num_bloco){
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    private void atualizaTraceLRU(int indexDoAcesso){
+        int bloco = this.traceLRU[indexDoAcesso];
+        
+        for(; indexDoAcesso < 3 && this.traceLRU[indexDoAcesso] != -1 ;indexDoAcesso++){
+            this.traceLRU[indexDoAcesso] = this.traceLRU[indexDoAcesso+1];
+        }        
+        this.traceLRU[indexDoAcesso-1] = bloco;
+    }
+    
+    private void insereNoFinal(int numBloco){
+        for(int i =0; i<4; i++){
+            if(this.traceLRU[i] == -1){
+                this.traceLRU[i] = numBloco;
+                return;
+            }
+        }
+    }
+    
+    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 < 4; indiceBloco++){
+            if(this.traceLRU[indiceBloco] == bloco){
+                break;
+            }
+        }
+        
+        for(; indiceBloco < 3;indiceBloco++){
+            this.traceLRU[indiceBloco] = this.traceLRU[indiceBloco+1];
+        }
+        
+        this.traceLRU[3] = bloco;        
+    }
+    
+    public int getBlocoFromLru(){
+        return this.traceLRU[0];
+    }
+
+    @Override
+    public String toString() {
+        String s = "[";
+        for(int i = 0; i < 4;i++){
+            s += this.traceLRU[i] + ",";
+        }
+        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;
+    }
+}

+ 79 - 0
src/cache/Redundancia.java

@@ -0,0 +1,79 @@
+/*
+ * 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 Redundancia {
+    private ConjuntoRedundancia[] conjuntos;
+    
+    public Redundancia(){
+        this.conjuntos = new ConjuntoRedundancia[4];
+        for(int i = 0; i < 4; i++){
+            this.conjuntos[i] = new ConjuntoRedundancia();            
+        }
+    }
+    
+    public void leituraEspecial(int tag, int conjunto, int bloco){
+        this.conjuntos[conjunto].getBlocos()[bloco].leituraEspecialNoBloco(tag);
+    }
+    
+    public void inserirErro(int conjunto, int bloco, int palavra){
+        this.conjuntos[conjunto].getBlocos()[bloco].getPalavras()[palavra].inserirErro();
+    }
+    
+    /**
+     * QUANDO TEM MISS, É SABIDO QUE, SE TIVER PALAVRA VALIDA, ISSO RESULTARA EM UM WB-FORÇADO OU LE
+     * 
+     * @param address endereço para escrever na redundancia
+     * @param bloco   número do bloco que a palavra está mapeada dentro do conjunto
+     * @return        retorna NULL se escreveu sem a necessidade de sobrescrita,
+     *                caso contrário, retorna o endereço para sofrer o write-back ou leitura especial
+     */
+    public Integer escreverPalavraNaRedMiss(Requisicao address,int bloco){
+        
+        int conjunto = address.conjunto%4;        
+        Integer enderecoToWB = null;
+        
+        if(this.conjuntos[conjunto].hasErroInPalavra(bloco, address.palavra)){
+            return -1;
+        }
+        
+        if(this.conjuntos[conjunto].isPalavraValida(bloco, address.palavra)){            
+            enderecoToWB = this.conjuntos[conjunto].getTagFromPalavra(bloco, address.palavra);
+        }
+        
+        //Escreve a palavra na redundancia
+        this.conjuntos[conjunto].writeAWord(address.conjunto, bloco, address.palavra);
+        
+        return enderecoToWB;
+    }
+
+    @Override
+    public String toString() {
+         String s = "";
+        BlocoRedundancia[] b;
+        int i = 0;
+        for (ConjuntoRedundancia conjunto : conjuntos) {
+            s += "Conjunto "+i+"\n";
+            //s += conjunto;
+            b = conjunto.getBlocos();
+            int j = 0;            
+            for (BlocoRedundancia 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.
+    }
+    
+    
+}

+ 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;        
+    }
+    
+}

+ 215 - 0
src/simuladorcache/SimuladorCache.java

@@ -0,0 +1,215 @@
+/*
+ * 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.inserirErroRedundancia(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(4, 0, 2);
+        cache.requisicaoParaCache(20, true);
+        //cache.requisicaoParaCache(20, true);
+//        cache.requisicaoParaCache(4, true);
+//        cache.requisicaoParaCache(512, true);
+//        cache.requisicaoParaCache(512, true);
+        
+        System.out.println("Hit = " + cache.getHit());
+        System.out.println("Miss = " + cache.getMiss());
+        System.out.println("Writeback = " + cache.getWB());
+        System.out.println("WriteBackForcado = " + cache.getWBForcado());
+        System.out.println("LeituraEspecial = " + cache.getcontadorLeituraEspecial());                
+        System.out.println("LeituraCache = " + cache.getLeituraCache());
+        System.out.println("EscritaCache = " + cache.getEscritaCache());
+        System.out.println("LeituraCacheRedundante = " + cache.getLeituraRedundancia());
+        System.out.println("EscritaCacheRedundante = " + cache.getEscritaRedundancia());
+        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());
+        }
+        
+        //inicializa os erros da redundancia
+        if(errosInit.getErroRed() != null){
+            for (Erro arg : errosInit.getErroRed()) {
+                cache.inserirErroRedundancia(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("WriteBackForcado = " + cache.getWBForcado());
+        System.out.println("LeituraEspecial = " + cache.getcontadorLeituraEspecial());                
+        System.out.println("LeituraCache = " + cache.getLeituraCache());
+        System.out.println("EscritaCache = " + cache.getEscritaCache());
+        System.out.println("LeituraCacheRedundante = " + cache.getLeituraRedundancia());
+        System.out.println("EscritaCacheRedundante = " + cache.getEscritaRedundancia());
+        System.out.println("Ciclos = " + cache.getCiclos());              
+        System.out.println("Incachavel = " + cache.getContadorIncachavel());              
+        System.out.println("EscritaSDRAM = "+cache.getEscritaSDRAM());
+        System.out.println("LeituraSDRAM = "+cache.getLeituraSDRAM());
+//        */
+    }
+
+}

+ 15 - 0
src/teste.txt

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