tlb.cc revision 9950
1/*
2 * Copyright (c) 2010-2012 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2001-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Ali Saidi
41 *          Nathan Binkert
42 *          Steve Reinhardt
43 */
44
45#include <string>
46#include <vector>
47
48#include "arch/arm/faults.hh"
49#include "arch/arm/pagetable.hh"
50#include "arch/arm/system.hh"
51#include "arch/arm/table_walker.hh"
52#include "arch/arm/tlb.hh"
53#include "arch/arm/utility.hh"
54#include "base/inifile.hh"
55#include "base/str.hh"
56#include "base/trace.hh"
57#include "cpu/thread_context.hh"
58#include "debug/Checkpoint.hh"
59#include "debug/TLB.hh"
60#include "debug/TLBVerbose.hh"
61#include "mem/page_table.hh"
62#include "params/ArmTLB.hh"
63#include "sim/full_system.hh"
64#include "sim/process.hh"
65
66using namespace std;
67using namespace ArmISA;
68
69TLB::TLB(const Params *p)
70    : BaseTLB(p), size(p->size) , tableWalker(p->walker),
71    rangeMRU(1), bootUncacheability(false), miscRegValid(false)
72{
73    table = new TlbEntry[size];
74    memset(table, 0, sizeof(TlbEntry) * size);
75
76    tableWalker->setTlb(this);
77}
78
79TLB::~TLB()
80{
81    if (table)
82        delete [] table;
83}
84
85bool
86TLB::translateFunctional(ThreadContext *tc, Addr va, Addr &pa)
87{
88    if (!miscRegValid)
89        updateMiscReg(tc);
90    TlbEntry *e = lookup(va, contextId, true);
91    if (!e)
92        return false;
93    pa = e->pAddr(va);
94    return true;
95}
96
97Fault
98TLB::finalizePhysical(RequestPtr req, ThreadContext *tc, Mode mode) const
99{
100    return NoFault;
101}
102
103TlbEntry*
104TLB::lookup(Addr va, uint8_t cid, bool functional)
105{
106
107    TlbEntry *retval = NULL;
108
109    // Maitaining LRU array
110
111    int x = 0;
112    while (retval == NULL && x < size) {
113        if (table[x].match(va, cid)) {
114
115            // We only move the hit entry ahead when the position is higher than rangeMRU
116            if (x > rangeMRU && !functional) {
117                TlbEntry tmp_entry = table[x];
118                for(int i = x; i > 0; i--)
119                    table[i] = table[i-1];
120                table[0] = tmp_entry;
121                retval = &table[0];
122            } else {
123                retval = &table[x];
124            }
125            break;
126        }
127        x++;
128    }
129
130    DPRINTF(TLBVerbose, "Lookup %#x, cid %#x -> %s ppn %#x size: %#x pa: %#x ap:%d\n",
131            va, cid, retval ? "hit" : "miss", retval ? retval->pfn : 0,
132            retval ? retval->size : 0, retval ? retval->pAddr(va) : 0,
133            retval ? retval->ap : 0);
134    ;
135    return retval;
136}
137
138// insert a new TLB entry
139void
140TLB::insert(Addr addr, TlbEntry &entry)
141{
142    DPRINTF(TLB, "Inserting entry into TLB with pfn:%#x size:%#x vpn: %#x"
143            " asid:%d N:%d global:%d valid:%d nc:%d sNp:%d xn:%d ap:%#x"
144            " domain:%#x\n", entry.pfn, entry.size, entry.vpn, entry.asid,
145            entry.N, entry.global, entry.valid, entry.nonCacheable, entry.sNp,
146            entry.xn, entry.ap, entry.domain);
147
148    if (table[size-1].valid)
149        DPRINTF(TLB, " - Replacing Valid entry %#x, asn %d ppn %#x size: %#x ap:%d\n",
150                table[size-1].vpn << table[size-1].N, table[size-1].asid,
151                table[size-1].pfn << table[size-1].N, table[size-1].size,
152                table[size-1].ap);
153
154    //inserting to MRU position and evicting the LRU one
155
156    for(int i = size-1; i > 0; i--)
157      table[i] = table[i-1];
158    table[0] = entry;
159
160    inserts++;
161}
162
163void
164TLB::printTlb()
165{
166    int x = 0;
167    TlbEntry *te;
168    DPRINTF(TLB, "Current TLB contents:\n");
169    while (x < size) {
170       te = &table[x];
171       if (te->valid)
172           DPRINTF(TLB, " *  %#x, asn %d ppn %#x size: %#x ap:%d\n",
173                te->vpn << te->N, te->asid, te->pfn << te->N, te->size, te->ap);
174       x++;
175    }
176}
177
178
179void
180TLB::flushAll()
181{
182    DPRINTF(TLB, "Flushing all TLB entries\n");
183    int x = 0;
184    TlbEntry *te;
185    while (x < size) {
186       te = &table[x];
187       if (te->valid) {
188           DPRINTF(TLB, " -  %#x, asn %d ppn %#x size: %#x ap:%d\n",
189                te->vpn << te->N, te->asid, te->pfn << te->N, te->size, te->ap);
190           flushedEntries++;
191       }
192       x++;
193    }
194
195    memset(table, 0, sizeof(TlbEntry) * size);
196
197    flushTlb++;
198}
199
200
201void
202TLB::flushMvaAsid(Addr mva, uint64_t asn)
203{
204    DPRINTF(TLB, "Flushing mva %#x asid: %#x\n", mva, asn);
205    TlbEntry *te;
206
207    te = lookup(mva, asn);
208    while (te != NULL) {
209     DPRINTF(TLB, " -  %#x, asn %d ppn %#x size: %#x ap:%d\n",
210            te->vpn << te->N, te->asid, te->pfn << te->N, te->size, te->ap);
211        te->valid = false;
212        flushedEntries++;
213        te = lookup(mva,asn);
214    }
215    flushTlbMvaAsid++;
216}
217
218void
219TLB::flushAsid(uint64_t asn)
220{
221    DPRINTF(TLB, "Flushing all entries with asid: %#x\n", asn);
222
223    int x = 0;
224    TlbEntry *te;
225
226    while (x < size) {
227        te = &table[x];
228        if (te->asid == asn) {
229            te->valid = false;
230            DPRINTF(TLB, " -  %#x, asn %d ppn %#x size: %#x ap:%d\n",
231                te->vpn << te->N, te->asid, te->pfn << te->N, te->size, te->ap);
232            flushedEntries++;
233        }
234        x++;
235    }
236    flushTlbAsid++;
237}
238
239void
240TLB::flushMva(Addr mva)
241{
242    DPRINTF(TLB, "Flushing all entries with mva: %#x\n", mva);
243
244    int x = 0;
245    TlbEntry *te;
246
247    while (x < size) {
248        te = &table[x];
249        Addr v = te->vpn << te->N;
250        if (mva >= v && mva < v + te->size) {
251            te->valid = false;
252            DPRINTF(TLB, " -  %#x, asn %d ppn %#x size: %#x ap:%d\n",
253                te->vpn << te->N, te->asid, te->pfn << te->N, te->size, te->ap);
254            flushedEntries++;
255        }
256        x++;
257    }
258    flushTlbMva++;
259}
260
261void
262TLB::drainResume()
263{
264    // We might have unserialized something or switched CPUs, so make
265    // sure to re-read the misc regs.
266    miscRegValid = false;
267}
268
269void
270TLB::serialize(ostream &os)
271{
272    DPRINTF(Checkpoint, "Serializing Arm TLB\n");
273
274    SERIALIZE_SCALAR(_attr);
275
276    int num_entries = size;
277    SERIALIZE_SCALAR(num_entries);
278    for(int i = 0; i < size; i++){
279        nameOut(os, csprintf("%s.TlbEntry%d", name(), i));
280        table[i].serialize(os);
281    }
282}
283
284void
285TLB::unserialize(Checkpoint *cp, const string &section)
286{
287    DPRINTF(Checkpoint, "Unserializing Arm TLB\n");
288
289    UNSERIALIZE_SCALAR(_attr);
290    int num_entries;
291    UNSERIALIZE_SCALAR(num_entries);
292    for(int i = 0; i < min(size, num_entries); i++){
293        table[i].unserialize(cp, csprintf("%s.TlbEntry%d", section, i));
294    }
295}
296
297void
298TLB::regStats()
299{
300    instHits
301        .name(name() + ".inst_hits")
302        .desc("ITB inst hits")
303        ;
304
305    instMisses
306        .name(name() + ".inst_misses")
307        .desc("ITB inst misses")
308        ;
309
310    instAccesses
311        .name(name() + ".inst_accesses")
312        .desc("ITB inst accesses")
313        ;
314
315    readHits
316        .name(name() + ".read_hits")
317        .desc("DTB read hits")
318        ;
319
320    readMisses
321        .name(name() + ".read_misses")
322        .desc("DTB read misses")
323        ;
324
325    readAccesses
326        .name(name() + ".read_accesses")
327        .desc("DTB read accesses")
328        ;
329
330    writeHits
331        .name(name() + ".write_hits")
332        .desc("DTB write hits")
333        ;
334
335    writeMisses
336        .name(name() + ".write_misses")
337        .desc("DTB write misses")
338        ;
339
340    writeAccesses
341        .name(name() + ".write_accesses")
342        .desc("DTB write accesses")
343        ;
344
345    hits
346        .name(name() + ".hits")
347        .desc("DTB hits")
348        ;
349
350    misses
351        .name(name() + ".misses")
352        .desc("DTB misses")
353        ;
354
355    accesses
356        .name(name() + ".accesses")
357        .desc("DTB accesses")
358        ;
359
360    flushTlb
361        .name(name() + ".flush_tlb")
362        .desc("Number of times complete TLB was flushed")
363        ;
364
365    flushTlbMva
366        .name(name() + ".flush_tlb_mva")
367        .desc("Number of times TLB was flushed by MVA")
368        ;
369
370    flushTlbMvaAsid
371        .name(name() + ".flush_tlb_mva_asid")
372        .desc("Number of times TLB was flushed by MVA & ASID")
373        ;
374
375    flushTlbAsid
376        .name(name() + ".flush_tlb_asid")
377        .desc("Number of times TLB was flushed by ASID")
378        ;
379
380    flushedEntries
381        .name(name() + ".flush_entries")
382        .desc("Number of entries that have been flushed from TLB")
383        ;
384
385    alignFaults
386        .name(name() + ".align_faults")
387        .desc("Number of TLB faults due to alignment restrictions")
388        ;
389
390    prefetchFaults
391        .name(name() + ".prefetch_faults")
392        .desc("Number of TLB faults due to prefetch")
393        ;
394
395    domainFaults
396        .name(name() + ".domain_faults")
397        .desc("Number of TLB faults due to domain restrictions")
398        ;
399
400    permsFaults
401        .name(name() + ".perms_faults")
402        .desc("Number of TLB faults due to permissions restrictions")
403        ;
404
405    instAccesses = instHits + instMisses;
406    readAccesses = readHits + readMisses;
407    writeAccesses = writeHits + writeMisses;
408    hits = readHits + writeHits + instHits;
409    misses = readMisses + writeMisses + instMisses;
410    accesses = readAccesses + writeAccesses + instAccesses;
411}
412
413Fault
414TLB::translateSe(RequestPtr req, ThreadContext *tc, Mode mode,
415        Translation *translation, bool &delay, bool timing)
416{
417    if (!miscRegValid)
418        updateMiscReg(tc);
419    Addr vaddr = req->getVaddr();
420    uint32_t flags = req->getFlags();
421
422    bool is_fetch = (mode == Execute);
423    bool is_write = (mode == Write);
424
425    if (!is_fetch) {
426        assert(flags & MustBeOne);
427        if (sctlr.a || !(flags & AllowUnaligned)) {
428            if (vaddr & flags & AlignmentMask) {
429                return new DataAbort(vaddr, 0, is_write, ArmFault::AlignmentFault);
430            }
431        }
432    }
433
434    Addr paddr;
435    Process *p = tc->getProcessPtr();
436
437    if (!p->pTable->translate(vaddr, paddr))
438        return Fault(new GenericPageTableFault(vaddr));
439    req->setPaddr(paddr);
440
441    return NoFault;
442}
443
444Fault
445TLB::trickBoxCheck(RequestPtr req, Mode mode, uint8_t domain, bool sNp)
446{
447    return NoFault;
448}
449
450Fault
451TLB::walkTrickBoxCheck(Addr pa, Addr va, Addr sz, bool is_exec,
452        bool is_write, uint8_t domain, bool sNp)
453{
454    return NoFault;
455}
456
457Fault
458TLB::translateFs(RequestPtr req, ThreadContext *tc, Mode mode,
459        Translation *translation, bool &delay, bool timing, bool functional)
460{
461    // No such thing as a functional timing access
462    assert(!(timing && functional));
463
464    if (!miscRegValid) {
465        updateMiscReg(tc);
466        DPRINTF(TLBVerbose, "TLB variables changed!\n");
467    }
468
469    Addr vaddr = req->getVaddr();
470    uint32_t flags = req->getFlags();
471
472    bool is_fetch = (mode == Execute);
473    bool is_write = (mode == Write);
474    bool is_priv = isPriv && !(flags & UserMode);
475
476    req->setAsid(contextId.asid);
477    if (is_priv)
478        req->setFlags(Request::PRIVILEGED);
479
480    DPRINTF(TLBVerbose, "CPSR is priv:%d UserMode:%d\n",
481            isPriv, flags & UserMode);
482    // If this is a clrex instruction, provide a PA of 0 with no fault
483    // This will force the monitor to set the tracked address to 0
484    // a bit of a hack but this effectively clrears this processors monitor
485    if (flags & Request::CLEAR_LL){
486       req->setPaddr(0);
487       req->setFlags(Request::UNCACHEABLE);
488       req->setFlags(Request::CLEAR_LL);
489       return NoFault;
490    }
491    if ((req->isInstFetch() && (!sctlr.i)) ||
492        ((!req->isInstFetch()) && (!sctlr.c))){
493       req->setFlags(Request::UNCACHEABLE);
494    }
495    if (!is_fetch) {
496        assert(flags & MustBeOne);
497        if (sctlr.a || !(flags & AllowUnaligned)) {
498            if (vaddr & flags & AlignmentMask) {
499                alignFaults++;
500                return new DataAbort(vaddr, 0, is_write, ArmFault::AlignmentFault);
501            }
502        }
503    }
504
505    Fault fault;
506
507    if (!sctlr.m) {
508        req->setPaddr(vaddr);
509        if (sctlr.tre == 0) {
510            req->setFlags(Request::UNCACHEABLE);
511        } else {
512            if (nmrr.ir0 == 0 || nmrr.or0 == 0 || prrr.tr0 != 0x2)
513               req->setFlags(Request::UNCACHEABLE);
514        }
515
516        // Set memory attributes
517        TlbEntry temp_te;
518        tableWalker->memAttrs(tc, temp_te, sctlr, 0, 1);
519        temp_te.shareable = true;
520        DPRINTF(TLBVerbose, "(No MMU) setting memory attributes: shareable:\
521                %d, innerAttrs: %d, outerAttrs: %d\n", temp_te.shareable,
522                temp_te.innerAttrs, temp_te.outerAttrs);
523        setAttr(temp_te.attributes);
524
525        return trickBoxCheck(req, mode, 0, false);
526    }
527
528    DPRINTF(TLBVerbose, "Translating vaddr=%#x context=%d\n", vaddr, contextId);
529    // Translation enabled
530
531    TlbEntry *te = lookup(vaddr, contextId);
532    if (te == NULL) {
533        if (req->isPrefetch()){
534           //if the request is a prefetch don't attempt to fill the TLB
535           //or go any further with the memory access
536           prefetchFaults++;
537           return new PrefetchAbort(vaddr, ArmFault::PrefetchTLBMiss);
538        }
539
540        if (is_fetch)
541            instMisses++;
542        else if (is_write)
543            writeMisses++;
544        else
545            readMisses++;
546
547        // start translation table walk, pass variables rather than
548        // re-retreaving in table walker for speed
549        DPRINTF(TLB, "TLB Miss: Starting hardware table walker for %#x(%d)\n",
550                vaddr, contextId);
551        fault = tableWalker->walk(req, tc, contextId, mode, translation,
552                                  timing, functional);
553        if (timing && fault == NoFault) {
554            delay = true;
555            // for timing mode, return and wait for table walk
556            return fault;
557        }
558        if (fault)
559            return fault;
560
561        te = lookup(vaddr, contextId);
562        if (!te)
563            printTlb();
564        assert(te);
565    } else {
566        if (is_fetch)
567            instHits++;
568        else if (is_write)
569            writeHits++;
570        else
571            readHits++;
572    }
573
574    // Set memory attributes
575    DPRINTF(TLBVerbose,
576            "Setting memory attributes: shareable: %d, innerAttrs: %d, \
577            outerAttrs: %d\n",
578            te->shareable, te->innerAttrs, te->outerAttrs);
579    setAttr(te->attributes);
580    if (te->nonCacheable) {
581        req->setFlags(Request::UNCACHEABLE);
582
583        // Prevent prefetching from I/O devices.
584        if (req->isPrefetch()) {
585            return new PrefetchAbort(vaddr, ArmFault::PrefetchUncacheable);
586        }
587    }
588
589    if (!bootUncacheability &&
590            ((ArmSystem*)tc->getSystemPtr())->adderBootUncacheable(vaddr))
591        req->setFlags(Request::UNCACHEABLE);
592
593    switch ( (dacr >> (te->domain * 2)) & 0x3) {
594      case 0:
595        domainFaults++;
596        DPRINTF(TLB, "TLB Fault: Data abort on domain. DACR: %#x domain: %#x"
597               " write:%d sNp:%d\n", dacr, te->domain, is_write, te->sNp);
598        if (is_fetch)
599            return new PrefetchAbort(vaddr,
600                (te->sNp ? ArmFault::Domain0 : ArmFault::Domain1));
601        else
602            return new DataAbort(vaddr, te->domain, is_write,
603                (te->sNp ? ArmFault::Domain0 : ArmFault::Domain1));
604      case 1:
605        // Continue with permissions check
606        break;
607      case 2:
608        panic("UNPRED domain\n");
609      case 3:
610        req->setPaddr(te->pAddr(vaddr));
611        fault = trickBoxCheck(req, mode, te->domain, te->sNp);
612        if (fault)
613            return fault;
614        return NoFault;
615    }
616
617    uint8_t ap = te->ap;
618
619    if (sctlr.afe == 1)
620        ap |= 1;
621
622    bool abt;
623
624   /* if (!sctlr.xp)
625        ap &= 0x3;
626*/
627    switch (ap) {
628      case 0:
629        DPRINTF(TLB, "Access permissions 0, checking rs:%#x\n", (int)sctlr.rs);
630        if (!sctlr.xp) {
631            switch ((int)sctlr.rs) {
632              case 2:
633                abt = is_write;
634                break;
635              case 1:
636                abt = is_write || !is_priv;
637                break;
638              case 0:
639              case 3:
640              default:
641                abt = true;
642                break;
643            }
644        } else {
645            abt = true;
646        }
647        break;
648      case 1:
649        abt = !is_priv;
650        break;
651      case 2:
652        abt = !is_priv && is_write;
653        break;
654      case 3:
655        abt = false;
656        break;
657      case 4:
658        panic("UNPRED premissions\n");
659      case 5:
660        abt = !is_priv || is_write;
661        break;
662      case 6:
663      case 7:
664        abt = is_write;
665        break;
666      default:
667        panic("Unknown permissions\n");
668    }
669    if ((is_fetch) && (abt || te->xn)) {
670        permsFaults++;
671        DPRINTF(TLB, "TLB Fault: Prefetch abort on permission check. AP:%d priv:%d"
672               " write:%d sNp:%d\n", ap, is_priv, is_write, te->sNp);
673        return new PrefetchAbort(vaddr,
674                (te->sNp ? ArmFault::Permission0 :
675                 ArmFault::Permission1));
676    } else if (abt) {
677        permsFaults++;
678        DPRINTF(TLB, "TLB Fault: Data abort on permission check. AP:%d priv:%d"
679               " write:%d sNp:%d\n", ap, is_priv, is_write, te->sNp);
680        return new DataAbort(vaddr, te->domain, is_write,
681                (te->sNp ? ArmFault::Permission0 :
682                 ArmFault::Permission1));
683    }
684
685    req->setPaddr(te->pAddr(vaddr));
686    // Check for a trickbox generated address fault
687    fault = trickBoxCheck(req, mode, te->domain, te->sNp);
688    if (fault)
689        return fault;
690
691    return NoFault;
692}
693
694Fault
695TLB::translateAtomic(RequestPtr req, ThreadContext *tc, Mode mode)
696{
697    bool delay = false;
698    Fault fault;
699    if (FullSystem)
700        fault = translateFs(req, tc, mode, NULL, delay, false);
701    else
702        fault = translateSe(req, tc, mode, NULL, delay, false);
703    assert(!delay);
704    return fault;
705}
706
707Fault
708TLB::translateFunctional(RequestPtr req, ThreadContext *tc, Mode mode)
709{
710    bool delay = false;
711    Fault fault;
712    if (FullSystem)
713        fault = translateFs(req, tc, mode, NULL, delay, false, true);
714    else
715        fault = translateSe(req, tc, mode, NULL, delay, false);
716    assert(!delay);
717    return fault;
718}
719
720Fault
721TLB::translateTiming(RequestPtr req, ThreadContext *tc,
722        Translation *translation, Mode mode)
723{
724    assert(translation);
725    bool delay = false;
726    Fault fault;
727    if (FullSystem)
728        fault = translateFs(req, tc, mode, translation, delay, true);
729    else
730        fault = translateSe(req, tc, mode, translation, delay, true);
731    DPRINTF(TLBVerbose, "Translation returning delay=%d fault=%d\n", delay, fault !=
732            NoFault);
733    if (!delay)
734        translation->finish(fault, req, tc, mode);
735    else
736        translation->markDelayed();
737    return fault;
738}
739
740BaseMasterPort*
741TLB::getMasterPort()
742{
743    return &tableWalker->getMasterPort("port");
744}
745
746
747
748ArmISA::TLB *
749ArmTLBParams::create()
750{
751    return new ArmISA::TLB(this);
752}
753