table_walker.cc revision 11575:0005b28685f0
1/*
2 * Copyright (c) 2010, 2012-2016 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 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Authors: Ali Saidi
38 *          Giacomo Gabrielli
39 */
40#include "arch/arm/table_walker.hh"
41
42#include <memory>
43
44#include "arch/arm/faults.hh"
45#include "arch/arm/stage2_mmu.hh"
46#include "arch/arm/system.hh"
47#include "arch/arm/tlb.hh"
48#include "cpu/base.hh"
49#include "cpu/thread_context.hh"
50#include "debug/Checkpoint.hh"
51#include "debug/Drain.hh"
52#include "debug/TLB.hh"
53#include "debug/TLBVerbose.hh"
54#include "dev/dma_device.hh"
55#include "sim/system.hh"
56
57using namespace ArmISA;
58
59TableWalker::TableWalker(const Params *p)
60    : MemObject(p),
61      stage2Mmu(NULL), port(NULL), masterId(Request::invldMasterId),
62      isStage2(p->is_stage2), tlb(NULL),
63      currState(NULL), pending(false),
64      numSquashable(p->num_squash_per_cycle),
65      pendingReqs(0),
66      pendingChangeTick(curTick()),
67      doL1DescEvent(this), doL2DescEvent(this),
68      doL0LongDescEvent(this), doL1LongDescEvent(this), doL2LongDescEvent(this),
69      doL3LongDescEvent(this),
70      doProcessEvent(this)
71{
72    sctlr = 0;
73
74    // Cache system-level properties
75    if (FullSystem) {
76        ArmSystem *armSys = dynamic_cast<ArmSystem *>(p->sys);
77        assert(armSys);
78        haveSecurity = armSys->haveSecurity();
79        _haveLPAE = armSys->haveLPAE();
80        _haveVirtualization = armSys->haveVirtualization();
81        physAddrRange = armSys->physAddrRange();
82        _haveLargeAsid64 = armSys->haveLargeAsid64();
83    } else {
84        haveSecurity = _haveLPAE = _haveVirtualization = false;
85        _haveLargeAsid64 = false;
86        physAddrRange = 32;
87    }
88
89}
90
91TableWalker::~TableWalker()
92{
93    ;
94}
95
96void
97TableWalker::setMMU(Stage2MMU *m, MasterID master_id)
98{
99    stage2Mmu = m;
100    port = &m->getPort();
101    masterId = master_id;
102}
103
104void
105TableWalker::init()
106{
107    fatal_if(!stage2Mmu, "Table walker must have a valid stage-2 MMU\n");
108    fatal_if(!port, "Table walker must have a valid port\n");
109    fatal_if(!tlb, "Table walker must have a valid TLB\n");
110}
111
112BaseMasterPort&
113TableWalker::getMasterPort(const std::string &if_name, PortID idx)
114{
115    if (if_name == "port") {
116        if (!isStage2) {
117            return *port;
118        } else {
119            fatal("Cannot access table walker port through stage-two walker\n");
120        }
121    }
122    return MemObject::getMasterPort(if_name, idx);
123}
124
125TableWalker::WalkerState::WalkerState() :
126    tc(nullptr), aarch64(false), el(EL0), physAddrRange(0), req(nullptr),
127    asid(0), vmid(0), isHyp(false), transState(nullptr),
128    vaddr(0), vaddr_tainted(0), isWrite(false), isFetch(false), isSecure(false),
129    secureLookup(false), rwTable(false), userTable(false), xnTable(false),
130    pxnTable(false), stage2Req(false), doingStage2(false),
131    stage2Tran(nullptr), timing(false), functional(false),
132    mode(BaseTLB::Read), tranType(TLB::NormalTran), l2Desc(l1Desc),
133    delayed(false), tableWalker(nullptr)
134{
135}
136
137void
138TableWalker::completeDrain()
139{
140    if (drainState() == DrainState::Draining &&
141        stateQueues[L1].empty() && stateQueues[L2].empty() &&
142        pendingQueue.empty()) {
143
144        DPRINTF(Drain, "TableWalker done draining, processing drain event\n");
145        signalDrainDone();
146    }
147}
148
149DrainState
150TableWalker::drain()
151{
152    bool state_queues_not_empty = false;
153
154    for (int i = 0; i < MAX_LOOKUP_LEVELS; ++i) {
155        if (!stateQueues[i].empty()) {
156            state_queues_not_empty = true;
157            break;
158        }
159    }
160
161    if (state_queues_not_empty || pendingQueue.size()) {
162        DPRINTF(Drain, "TableWalker not drained\n");
163        return DrainState::Draining;
164    } else {
165        DPRINTF(Drain, "TableWalker free, no need to drain\n");
166        return DrainState::Drained;
167    }
168}
169
170void
171TableWalker::drainResume()
172{
173    if (params()->sys->isTimingMode() && currState) {
174        delete currState;
175        currState = NULL;
176        pendingChange();
177    }
178}
179
180Fault
181TableWalker::walk(RequestPtr _req, ThreadContext *_tc, uint16_t _asid,
182                  uint8_t _vmid, bool _isHyp, TLB::Mode _mode,
183                  TLB::Translation *_trans, bool _timing, bool _functional,
184                  bool secure, TLB::ArmTranslationType tranType)
185{
186    assert(!(_functional && _timing));
187    ++statWalks;
188
189    WalkerState *savedCurrState = NULL;
190
191    if (!currState && !_functional) {
192        // For atomic mode, a new WalkerState instance should be only created
193        // once per TLB. For timing mode, a new instance is generated for every
194        // TLB miss.
195        DPRINTF(TLBVerbose, "creating new instance of WalkerState\n");
196
197        currState = new WalkerState();
198        currState->tableWalker = this;
199    } else if (_functional) {
200        // If we are mixing functional mode with timing (or even
201        // atomic), we need to to be careful and clean up after
202        // ourselves to not risk getting into an inconsistent state.
203        DPRINTF(TLBVerbose, "creating functional instance of WalkerState\n");
204        savedCurrState = currState;
205        currState = new WalkerState();
206        currState->tableWalker = this;
207    } else if (_timing) {
208        // This is a translation that was completed and then faulted again
209        // because some underlying parameters that affect the translation
210        // changed out from under us (e.g. asid). It will either be a
211        // misprediction, in which case nothing will happen or we'll use
212        // this fault to re-execute the faulting instruction which should clean
213        // up everything.
214        if (currState->vaddr_tainted == _req->getVaddr()) {
215            ++statSquashedBefore;
216            return std::make_shared<ReExec>();
217        }
218    }
219    pendingChange();
220
221    currState->startTime = curTick();
222    currState->tc = _tc;
223    // ARM DDI 0487A.f (ARMv8 ARM) pg J8-5672
224    // aarch32/translation/translation/AArch32.TranslateAddress dictates
225    // even AArch32 EL0 will use AArch64 translation if EL1 is in AArch64.
226    currState->aarch64 = isStage2 || opModeIs64(currOpMode(_tc)) ||
227                         ((currEL(_tc) == EL0) && ELIs64(_tc, EL1));
228    currState->el = currEL(_tc);
229    currState->transState = _trans;
230    currState->req = _req;
231    currState->fault = NoFault;
232    currState->asid = _asid;
233    currState->vmid = _vmid;
234    currState->isHyp = _isHyp;
235    currState->timing = _timing;
236    currState->functional = _functional;
237    currState->mode = _mode;
238    currState->tranType = tranType;
239    currState->isSecure = secure;
240    currState->physAddrRange = physAddrRange;
241
242    /** @todo These should be cached or grabbed from cached copies in
243     the TLB, all these miscreg reads are expensive */
244    currState->vaddr_tainted = currState->req->getVaddr();
245    if (currState->aarch64)
246        currState->vaddr = purifyTaggedAddr(currState->vaddr_tainted,
247                                            currState->tc, currState->el);
248    else
249        currState->vaddr = currState->vaddr_tainted;
250
251    if (currState->aarch64) {
252        if (isStage2) {
253            currState->sctlr = currState->tc->readMiscReg(MISCREG_SCTLR_EL1);
254            currState->vtcr = currState->tc->readMiscReg(MISCREG_VTCR_EL2);
255        } else switch (currState->el) {
256          case EL0:
257          case EL1:
258            currState->sctlr = currState->tc->readMiscReg(MISCREG_SCTLR_EL1);
259            currState->tcr = currState->tc->readMiscReg(MISCREG_TCR_EL1);
260            break;
261          case EL2:
262            assert(_haveVirtualization);
263            currState->sctlr = currState->tc->readMiscReg(MISCREG_SCTLR_EL2);
264            currState->tcr = currState->tc->readMiscReg(MISCREG_TCR_EL2);
265            break;
266          case EL3:
267            assert(haveSecurity);
268            currState->sctlr = currState->tc->readMiscReg(MISCREG_SCTLR_EL3);
269            currState->tcr = currState->tc->readMiscReg(MISCREG_TCR_EL3);
270            break;
271          default:
272            panic("Invalid exception level");
273            break;
274        }
275        currState->hcr = currState->tc->readMiscReg(MISCREG_HCR_EL2);
276    } else {
277        currState->sctlr = currState->tc->readMiscReg(flattenMiscRegNsBanked(
278            MISCREG_SCTLR, currState->tc, !currState->isSecure));
279        currState->ttbcr = currState->tc->readMiscReg(flattenMiscRegNsBanked(
280            MISCREG_TTBCR, currState->tc, !currState->isSecure));
281        currState->htcr  = currState->tc->readMiscReg(MISCREG_HTCR);
282        currState->hcr   = currState->tc->readMiscReg(MISCREG_HCR);
283        currState->vtcr  = currState->tc->readMiscReg(MISCREG_VTCR);
284    }
285    sctlr = currState->sctlr;
286
287    currState->isFetch = (currState->mode == TLB::Execute);
288    currState->isWrite = (currState->mode == TLB::Write);
289
290    statRequestOrigin[REQUESTED][currState->isFetch]++;
291
292    // We only do a second stage of translation if we're not secure, or in
293    // hyp mode, the second stage MMU is enabled, and this table walker
294    // instance is the first stage.
295    currState->doingStage2 = false;
296    currState->stage2Req = currState->hcr.vm && !isStage2 &&
297                           !currState->isSecure && !currState->isHyp;
298
299    bool long_desc_format = currState->aarch64 || _isHyp || isStage2 ||
300                            longDescFormatInUse(currState->tc);
301
302    if (long_desc_format) {
303        // Helper variables used for hierarchical permissions
304        currState->secureLookup = currState->isSecure;
305        currState->rwTable = true;
306        currState->userTable = true;
307        currState->xnTable = false;
308        currState->pxnTable = false;
309
310        ++statWalksLongDescriptor;
311    } else {
312        ++statWalksShortDescriptor;
313    }
314
315    if (!currState->timing) {
316        Fault fault = NoFault;
317        if (currState->aarch64)
318            fault = processWalkAArch64();
319        else if (long_desc_format)
320            fault = processWalkLPAE();
321        else
322            fault = processWalk();
323
324        // If this was a functional non-timing access restore state to
325        // how we found it.
326        if (currState->functional) {
327            delete currState;
328            currState = savedCurrState;
329        }
330        return fault;
331    }
332
333    if (pending || pendingQueue.size()) {
334        pendingQueue.push_back(currState);
335        currState = NULL;
336        pendingChange();
337    } else {
338        pending = true;
339        pendingChange();
340        if (currState->aarch64)
341            return processWalkAArch64();
342        else if (long_desc_format)
343            return processWalkLPAE();
344        else
345            return processWalk();
346    }
347
348    return NoFault;
349}
350
351void
352TableWalker::processWalkWrapper()
353{
354    assert(!currState);
355    assert(pendingQueue.size());
356    pendingChange();
357    currState = pendingQueue.front();
358
359    ExceptionLevel target_el = EL0;
360    if (currState->aarch64)
361        target_el = currEL(currState->tc);
362    else
363        target_el = EL1;
364
365    // Check if a previous walk filled this request already
366    // @TODO Should this always be the TLB or should we look in the stage2 TLB?
367    TlbEntry* te = tlb->lookup(currState->vaddr, currState->asid,
368            currState->vmid, currState->isHyp, currState->isSecure, true, false,
369            target_el);
370
371    // Check if we still need to have a walk for this request. If the requesting
372    // instruction has been squashed, or a previous walk has filled the TLB with
373    // a match, we just want to get rid of the walk. The latter could happen
374    // when there are multiple outstanding misses to a single page and a
375    // previous request has been successfully translated.
376    if (!currState->transState->squashed() && !te) {
377        // We've got a valid request, lets process it
378        pending = true;
379        pendingQueue.pop_front();
380        // Keep currState in case one of the processWalk... calls NULLs it
381        WalkerState *curr_state_copy = currState;
382        Fault f;
383        if (currState->aarch64)
384            f = processWalkAArch64();
385        else if (longDescFormatInUse(currState->tc) ||
386                 currState->isHyp || isStage2)
387            f = processWalkLPAE();
388        else
389            f = processWalk();
390
391        if (f != NoFault) {
392            curr_state_copy->transState->finish(f, curr_state_copy->req,
393                    curr_state_copy->tc, curr_state_copy->mode);
394
395            delete curr_state_copy;
396        }
397        return;
398    }
399
400
401    // If the instruction that we were translating for has been
402    // squashed we shouldn't bother.
403    unsigned num_squashed = 0;
404    ThreadContext *tc = currState->tc;
405    while ((num_squashed < numSquashable) && currState &&
406           (currState->transState->squashed() || te)) {
407        pendingQueue.pop_front();
408        num_squashed++;
409        statSquashedBefore++;
410
411        DPRINTF(TLB, "Squashing table walk for address %#x\n",
412                      currState->vaddr_tainted);
413
414        if (currState->transState->squashed()) {
415            // finish the translation which will delete the translation object
416            currState->transState->finish(
417                std::make_shared<UnimpFault>("Squashed Inst"),
418                currState->req, currState->tc, currState->mode);
419        } else {
420            // translate the request now that we know it will work
421            statWalkServiceTime.sample(curTick() - currState->startTime);
422            tlb->translateTiming(currState->req, currState->tc,
423                        currState->transState, currState->mode);
424
425        }
426
427        // delete the current request
428        delete currState;
429
430        // peak at the next one
431        if (pendingQueue.size()) {
432            currState = pendingQueue.front();
433            te = tlb->lookup(currState->vaddr, currState->asid,
434                currState->vmid, currState->isHyp, currState->isSecure, true,
435                false, target_el);
436        } else {
437            // Terminate the loop, nothing more to do
438            currState = NULL;
439        }
440    }
441    pendingChange();
442
443    // if we still have pending translations, schedule more work
444    nextWalk(tc);
445    currState = NULL;
446}
447
448Fault
449TableWalker::processWalk()
450{
451    Addr ttbr = 0;
452
453    // If translation isn't enabled, we shouldn't be here
454    assert(currState->sctlr.m || isStage2);
455
456    DPRINTF(TLB, "Beginning table walk for address %#x, TTBCR: %#x, bits:%#x\n",
457            currState->vaddr_tainted, currState->ttbcr, mbits(currState->vaddr, 31,
458                                                      32 - currState->ttbcr.n));
459
460    statWalkWaitTime.sample(curTick() - currState->startTime);
461
462    if (currState->ttbcr.n == 0 || !mbits(currState->vaddr, 31,
463                                          32 - currState->ttbcr.n)) {
464        DPRINTF(TLB, " - Selecting TTBR0\n");
465        // Check if table walk is allowed when Security Extensions are enabled
466        if (haveSecurity && currState->ttbcr.pd0) {
467            if (currState->isFetch)
468                return std::make_shared<PrefetchAbort>(
469                    currState->vaddr_tainted,
470                    ArmFault::TranslationLL + L1,
471                    isStage2,
472                    ArmFault::VmsaTran);
473            else
474                return std::make_shared<DataAbort>(
475                    currState->vaddr_tainted,
476                    TlbEntry::DomainType::NoAccess, currState->isWrite,
477                    ArmFault::TranslationLL + L1, isStage2,
478                    ArmFault::VmsaTran);
479        }
480        ttbr = currState->tc->readMiscReg(flattenMiscRegNsBanked(
481            MISCREG_TTBR0, currState->tc, !currState->isSecure));
482    } else {
483        DPRINTF(TLB, " - Selecting TTBR1\n");
484        // Check if table walk is allowed when Security Extensions are enabled
485        if (haveSecurity && currState->ttbcr.pd1) {
486            if (currState->isFetch)
487                return std::make_shared<PrefetchAbort>(
488                    currState->vaddr_tainted,
489                    ArmFault::TranslationLL + L1,
490                    isStage2,
491                    ArmFault::VmsaTran);
492            else
493                return std::make_shared<DataAbort>(
494                    currState->vaddr_tainted,
495                    TlbEntry::DomainType::NoAccess, currState->isWrite,
496                    ArmFault::TranslationLL + L1, isStage2,
497                    ArmFault::VmsaTran);
498        }
499        ttbr = currState->tc->readMiscReg(flattenMiscRegNsBanked(
500            MISCREG_TTBR1, currState->tc, !currState->isSecure));
501        currState->ttbcr.n = 0;
502    }
503
504    Addr l1desc_addr = mbits(ttbr, 31, 14 - currState->ttbcr.n) |
505        (bits(currState->vaddr, 31 - currState->ttbcr.n, 20) << 2);
506    DPRINTF(TLB, " - Descriptor at address %#x (%s)\n", l1desc_addr,
507            currState->isSecure ? "s" : "ns");
508
509    // Trickbox address check
510    Fault f;
511    f = testWalk(l1desc_addr, sizeof(uint32_t),
512                 TlbEntry::DomainType::NoAccess, L1);
513    if (f) {
514        DPRINTF(TLB, "Trickbox check caused fault on %#x\n", currState->vaddr_tainted);
515        if (currState->timing) {
516            pending = false;
517            nextWalk(currState->tc);
518            currState = NULL;
519        } else {
520            currState->tc = NULL;
521            currState->req = NULL;
522        }
523        return f;
524    }
525
526    Request::Flags flag = Request::PT_WALK;
527    if (currState->sctlr.c == 0) {
528        flag.set(Request::UNCACHEABLE);
529    }
530
531    if (currState->isSecure) {
532        flag.set(Request::SECURE);
533    }
534
535    bool delayed;
536    delayed = fetchDescriptor(l1desc_addr, (uint8_t*)&currState->l1Desc.data,
537                              sizeof(uint32_t), flag, L1, &doL1DescEvent,
538                              &TableWalker::doL1Descriptor);
539    if (!delayed) {
540       f = currState->fault;
541    }
542
543    return f;
544}
545
546Fault
547TableWalker::processWalkLPAE()
548{
549    Addr ttbr, ttbr0_max, ttbr1_min, desc_addr;
550    int tsz, n;
551    LookupLevel start_lookup_level = L1;
552
553    DPRINTF(TLB, "Beginning table walk for address %#x, TTBCR: %#x\n",
554            currState->vaddr_tainted, currState->ttbcr);
555
556    statWalkWaitTime.sample(curTick() - currState->startTime);
557
558    Request::Flags flag = Request::PT_WALK;
559    if (currState->isSecure)
560        flag.set(Request::SECURE);
561
562    // work out which base address register to use, if in hyp mode we always
563    // use HTTBR
564    if (isStage2) {
565        DPRINTF(TLB, " - Selecting VTTBR (long-desc.)\n");
566        ttbr = currState->tc->readMiscReg(MISCREG_VTTBR);
567        tsz  = sext<4>(currState->vtcr.t0sz);
568        start_lookup_level = currState->vtcr.sl0 ? L1 : L2;
569    } else if (currState->isHyp) {
570        DPRINTF(TLB, " - Selecting HTTBR (long-desc.)\n");
571        ttbr = currState->tc->readMiscReg(MISCREG_HTTBR);
572        tsz  = currState->htcr.t0sz;
573    } else {
574        assert(longDescFormatInUse(currState->tc));
575
576        // Determine boundaries of TTBR0/1 regions
577        if (currState->ttbcr.t0sz)
578            ttbr0_max = (1ULL << (32 - currState->ttbcr.t0sz)) - 1;
579        else if (currState->ttbcr.t1sz)
580            ttbr0_max = (1ULL << 32) -
581                (1ULL << (32 - currState->ttbcr.t1sz)) - 1;
582        else
583            ttbr0_max = (1ULL << 32) - 1;
584        if (currState->ttbcr.t1sz)
585            ttbr1_min = (1ULL << 32) - (1ULL << (32 - currState->ttbcr.t1sz));
586        else
587            ttbr1_min = (1ULL << (32 - currState->ttbcr.t0sz));
588
589        // The following code snippet selects the appropriate translation table base
590        // address (TTBR0 or TTBR1) and the appropriate starting lookup level
591        // depending on the address range supported by the translation table (ARM
592        // ARM issue C B3.6.4)
593        if (currState->vaddr <= ttbr0_max) {
594            DPRINTF(TLB, " - Selecting TTBR0 (long-desc.)\n");
595            // Check if table walk is allowed
596            if (currState->ttbcr.epd0) {
597                if (currState->isFetch)
598                    return std::make_shared<PrefetchAbort>(
599                        currState->vaddr_tainted,
600                        ArmFault::TranslationLL + L1,
601                        isStage2,
602                        ArmFault::LpaeTran);
603                else
604                    return std::make_shared<DataAbort>(
605                        currState->vaddr_tainted,
606                        TlbEntry::DomainType::NoAccess,
607                        currState->isWrite,
608                        ArmFault::TranslationLL + L1,
609                        isStage2,
610                        ArmFault::LpaeTran);
611            }
612            ttbr = currState->tc->readMiscReg(flattenMiscRegNsBanked(
613                MISCREG_TTBR0, currState->tc, !currState->isSecure));
614            tsz = currState->ttbcr.t0sz;
615            if (ttbr0_max < (1ULL << 30))  // Upper limit < 1 GB
616                start_lookup_level = L2;
617        } else if (currState->vaddr >= ttbr1_min) {
618            DPRINTF(TLB, " - Selecting TTBR1 (long-desc.)\n");
619            // Check if table walk is allowed
620            if (currState->ttbcr.epd1) {
621                if (currState->isFetch)
622                    return std::make_shared<PrefetchAbort>(
623                        currState->vaddr_tainted,
624                        ArmFault::TranslationLL + L1,
625                        isStage2,
626                        ArmFault::LpaeTran);
627                else
628                    return std::make_shared<DataAbort>(
629                        currState->vaddr_tainted,
630                        TlbEntry::DomainType::NoAccess,
631                        currState->isWrite,
632                        ArmFault::TranslationLL + L1,
633                        isStage2,
634                        ArmFault::LpaeTran);
635            }
636            ttbr = currState->tc->readMiscReg(flattenMiscRegNsBanked(
637                MISCREG_TTBR1, currState->tc, !currState->isSecure));
638            tsz = currState->ttbcr.t1sz;
639            if (ttbr1_min >= (1ULL << 31) + (1ULL << 30))  // Lower limit >= 3 GB
640                start_lookup_level = L2;
641        } else {
642            // Out of boundaries -> translation fault
643            if (currState->isFetch)
644                return std::make_shared<PrefetchAbort>(
645                    currState->vaddr_tainted,
646                    ArmFault::TranslationLL + L1,
647                    isStage2,
648                    ArmFault::LpaeTran);
649            else
650                return std::make_shared<DataAbort>(
651                    currState->vaddr_tainted,
652                    TlbEntry::DomainType::NoAccess,
653                    currState->isWrite, ArmFault::TranslationLL + L1,
654                    isStage2, ArmFault::LpaeTran);
655        }
656
657    }
658
659    // Perform lookup (ARM ARM issue C B3.6.6)
660    if (start_lookup_level == L1) {
661        n = 5 - tsz;
662        desc_addr = mbits(ttbr, 39, n) |
663            (bits(currState->vaddr, n + 26, 30) << 3);
664        DPRINTF(TLB, " - Descriptor at address %#x (%s) (long-desc.)\n",
665                desc_addr, currState->isSecure ? "s" : "ns");
666    } else {
667        // Skip first-level lookup
668        n = (tsz >= 2 ? 14 - tsz : 12);
669        desc_addr = mbits(ttbr, 39, n) |
670            (bits(currState->vaddr, n + 17, 21) << 3);
671        DPRINTF(TLB, " - Descriptor at address %#x (%s) (long-desc.)\n",
672                desc_addr, currState->isSecure ? "s" : "ns");
673    }
674
675    // Trickbox address check
676    Fault f = testWalk(desc_addr, sizeof(uint64_t),
677                       TlbEntry::DomainType::NoAccess, start_lookup_level);
678    if (f) {
679        DPRINTF(TLB, "Trickbox check caused fault on %#x\n", currState->vaddr_tainted);
680        if (currState->timing) {
681            pending = false;
682            nextWalk(currState->tc);
683            currState = NULL;
684        } else {
685            currState->tc = NULL;
686            currState->req = NULL;
687        }
688        return f;
689    }
690
691    if (currState->sctlr.c == 0) {
692        flag.set(Request::UNCACHEABLE);
693    }
694
695    currState->longDesc.lookupLevel = start_lookup_level;
696    currState->longDesc.aarch64 = false;
697    currState->longDesc.grainSize = Grain4KB;
698
699    Event *event = start_lookup_level == L1 ? (Event *) &doL1LongDescEvent
700                                            : (Event *) &doL2LongDescEvent;
701
702    bool delayed = fetchDescriptor(desc_addr, (uint8_t*)&currState->longDesc.data,
703                                   sizeof(uint64_t), flag, start_lookup_level,
704                                   event, &TableWalker::doLongDescriptor);
705    if (!delayed) {
706        f = currState->fault;
707    }
708
709    return f;
710}
711
712unsigned
713TableWalker::adjustTableSizeAArch64(unsigned tsz)
714{
715    if (tsz < 25)
716        return 25;
717    if (tsz > 48)
718        return 48;
719    return tsz;
720}
721
722bool
723TableWalker::checkAddrSizeFaultAArch64(Addr addr, int currPhysAddrRange)
724{
725    return (currPhysAddrRange != MaxPhysAddrRange &&
726            bits(addr, MaxPhysAddrRange - 1, currPhysAddrRange));
727}
728
729Fault
730TableWalker::processWalkAArch64()
731{
732    assert(currState->aarch64);
733
734    DPRINTF(TLB, "Beginning table walk for address %#llx, TCR: %#llx\n",
735            currState->vaddr_tainted, currState->tcr);
736
737    static const GrainSize GrainMapDefault[] =
738      { Grain4KB, Grain64KB, Grain16KB, ReservedGrain };
739    static const GrainSize GrainMap_EL1_tg1[] =
740      { ReservedGrain, Grain16KB, Grain4KB, Grain64KB };
741
742    statWalkWaitTime.sample(curTick() - currState->startTime);
743
744    // Determine TTBR, table size, granule size and phys. address range
745    Addr ttbr = 0;
746    int tsz = 0, ps = 0;
747    GrainSize tg = Grain4KB; // grain size computed from tg* field
748    bool fault = false;
749
750    LookupLevel start_lookup_level = MAX_LOOKUP_LEVELS;
751
752    switch (currState->el) {
753      case EL0:
754      case EL1:
755        if (isStage2) {
756            DPRINTF(TLB, " - Selecting VTTBR0 (AArch64 stage 2)\n");
757            ttbr = currState->tc->readMiscReg(MISCREG_VTTBR_EL2);
758            tsz = 64 - currState->vtcr.t0sz64;
759            tg = GrainMapDefault[currState->vtcr.tg0];
760            // ARM DDI 0487A.f D7-2148
761            // The starting level of stage 2 translation depends on
762            // VTCR_EL2.SL0 and VTCR_EL2.TG0
763            LookupLevel __ = MAX_LOOKUP_LEVELS; // invalid level
764            uint8_t sl_tg = (currState->vtcr.sl0 << 2) | currState->vtcr.tg0;
765            static const LookupLevel SLL[] = {
766                L2, L3, L3, __, // sl0 == 0
767                L1, L2, L2, __, // sl0 == 1, etc.
768                L0, L1, L1, __,
769                __, __, __, __
770            };
771            start_lookup_level = SLL[sl_tg];
772            panic_if(start_lookup_level == MAX_LOOKUP_LEVELS,
773                     "Cannot discern lookup level from vtcr.{sl0,tg0}");
774        } else switch (bits(currState->vaddr, 63,48)) {
775          case 0:
776            DPRINTF(TLB, " - Selecting TTBR0 (AArch64)\n");
777            ttbr = currState->tc->readMiscReg(MISCREG_TTBR0_EL1);
778            tsz = adjustTableSizeAArch64(64 - currState->tcr.t0sz);
779            tg = GrainMapDefault[currState->tcr.tg0];
780            if (bits(currState->vaddr, 63, tsz) != 0x0 ||
781                currState->tcr.epd0)
782              fault = true;
783            break;
784          case 0xffff:
785            DPRINTF(TLB, " - Selecting TTBR1 (AArch64)\n");
786            ttbr = currState->tc->readMiscReg(MISCREG_TTBR1_EL1);
787            tsz = adjustTableSizeAArch64(64 - currState->tcr.t1sz);
788            tg = GrainMap_EL1_tg1[currState->tcr.tg1];
789            if (bits(currState->vaddr, 63, tsz) != mask(64-tsz) ||
790                currState->tcr.epd1)
791              fault = true;
792            break;
793          default:
794            // top two bytes must be all 0s or all 1s, else invalid addr
795            fault = true;
796        }
797        ps = currState->tcr.ips;
798        break;
799      case EL2:
800      case EL3:
801        switch(bits(currState->vaddr, 63,48)) {
802            case 0:
803                DPRINTF(TLB, " - Selecting TTBR0 (AArch64)\n");
804                if (currState->el == EL2)
805                    ttbr = currState->tc->readMiscReg(MISCREG_TTBR0_EL2);
806                else
807                    ttbr = currState->tc->readMiscReg(MISCREG_TTBR0_EL3);
808                tsz = adjustTableSizeAArch64(64 - currState->tcr.t0sz);
809                tg = GrainMapDefault[currState->tcr.tg0];
810                break;
811            default:
812                // invalid addr if top two bytes are not all 0s
813                fault = true;
814        }
815        ps = currState->tcr.ips;
816        break;
817    }
818
819    if (fault) {
820        Fault f;
821        if (currState->isFetch)
822            f =  std::make_shared<PrefetchAbort>(
823                currState->vaddr_tainted,
824                ArmFault::TranslationLL + L0, isStage2,
825                ArmFault::LpaeTran);
826        else
827            f = std::make_shared<DataAbort>(
828                currState->vaddr_tainted,
829                TlbEntry::DomainType::NoAccess,
830                currState->isWrite,
831                ArmFault::TranslationLL + L0,
832                isStage2, ArmFault::LpaeTran);
833
834        if (currState->timing) {
835            pending = false;
836            nextWalk(currState->tc);
837            currState = NULL;
838        } else {
839            currState->tc = NULL;
840            currState->req = NULL;
841        }
842        return f;
843
844    }
845
846    if (tg == ReservedGrain) {
847        warn_once("Reserved granule size requested; gem5's IMPLEMENTATION "
848                  "DEFINED behavior takes this to mean 4KB granules\n");
849        tg = Grain4KB;
850    }
851
852    // Determine starting lookup level
853    // See aarch64/translation/walk in Appendix G: ARMv8 Pseudocode Library
854    // in ARM DDI 0487A.  These table values correspond to the cascading tests
855    // to compute the lookup level and are of the form
856    // (grain_size + N*stride), for N = {1, 2, 3}.
857    // A value of 64 will never succeed and a value of 0 will always succeed.
858    if (start_lookup_level == MAX_LOOKUP_LEVELS) {
859        struct GrainMap {
860            GrainSize grain_size;
861            unsigned lookup_level_cutoff[MAX_LOOKUP_LEVELS];
862        };
863        static const GrainMap GM[] = {
864            { Grain4KB,  { 39, 30,  0, 0 } },
865            { Grain16KB, { 47, 36, 25, 0 } },
866            { Grain64KB, { 64, 42, 29, 0 } }
867        };
868
869        const unsigned *lookup = NULL; // points to a lookup_level_cutoff
870
871        for (unsigned i = 0; i < 3; ++i) { // choose entry of GM[]
872            if (tg == GM[i].grain_size) {
873                lookup = GM[i].lookup_level_cutoff;
874                break;
875            }
876        }
877        assert(lookup);
878
879        for (int L = L0; L != MAX_LOOKUP_LEVELS; ++L) {
880            if (tsz > lookup[L]) {
881                start_lookup_level = (LookupLevel) L;
882                break;
883            }
884        }
885        panic_if(start_lookup_level == MAX_LOOKUP_LEVELS,
886                 "Table walker couldn't find lookup level\n");
887    }
888
889    int stride = tg - 3;
890
891    // Determine table base address
892    int base_addr_lo = 3 + tsz - stride * (3 - start_lookup_level) - tg;
893    Addr base_addr = mbits(ttbr, 47, base_addr_lo);
894
895    // Determine physical address size and raise an Address Size Fault if
896    // necessary
897    int pa_range = decodePhysAddrRange64(ps);
898    // Clamp to lower limit
899    if (pa_range > physAddrRange)
900        currState->physAddrRange = physAddrRange;
901    else
902        currState->physAddrRange = pa_range;
903    if (checkAddrSizeFaultAArch64(base_addr, currState->physAddrRange)) {
904        DPRINTF(TLB, "Address size fault before any lookup\n");
905        Fault f;
906        if (currState->isFetch)
907            f = std::make_shared<PrefetchAbort>(
908                currState->vaddr_tainted,
909                ArmFault::AddressSizeLL + start_lookup_level,
910                isStage2,
911                ArmFault::LpaeTran);
912        else
913            f = std::make_shared<DataAbort>(
914                currState->vaddr_tainted,
915                TlbEntry::DomainType::NoAccess,
916                currState->isWrite,
917                ArmFault::AddressSizeLL + start_lookup_level,
918                isStage2,
919                ArmFault::LpaeTran);
920
921
922        if (currState->timing) {
923            pending = false;
924            nextWalk(currState->tc);
925            currState = NULL;
926        } else {
927            currState->tc = NULL;
928            currState->req = NULL;
929        }
930        return f;
931
932   }
933
934    // Determine descriptor address
935    Addr desc_addr = base_addr |
936        (bits(currState->vaddr, tsz - 1,
937              stride * (3 - start_lookup_level) + tg) << 3);
938
939    // Trickbox address check
940    Fault f = testWalk(desc_addr, sizeof(uint64_t),
941                       TlbEntry::DomainType::NoAccess, start_lookup_level);
942    if (f) {
943        DPRINTF(TLB, "Trickbox check caused fault on %#x\n", currState->vaddr_tainted);
944        if (currState->timing) {
945            pending = false;
946            nextWalk(currState->tc);
947            currState = NULL;
948        } else {
949            currState->tc = NULL;
950            currState->req = NULL;
951        }
952        return f;
953    }
954
955    Request::Flags flag = Request::PT_WALK;
956    if (currState->sctlr.c == 0) {
957        flag.set(Request::UNCACHEABLE);
958    }
959
960    if (currState->isSecure) {
961        flag.set(Request::SECURE);
962    }
963
964    currState->longDesc.lookupLevel = start_lookup_level;
965    currState->longDesc.aarch64 = true;
966    currState->longDesc.grainSize = tg;
967
968    if (currState->timing) {
969        Event *event;
970        switch (start_lookup_level) {
971          case L0:
972            event = (Event *) &doL0LongDescEvent;
973            break;
974          case L1:
975            event = (Event *) &doL1LongDescEvent;
976            break;
977          case L2:
978            event = (Event *) &doL2LongDescEvent;
979            break;
980          case L3:
981            event = (Event *) &doL3LongDescEvent;
982            break;
983          default:
984            panic("Invalid table lookup level");
985            break;
986        }
987        port->dmaAction(MemCmd::ReadReq, desc_addr, sizeof(uint64_t),
988                       event, (uint8_t*) &currState->longDesc.data,
989                       currState->tc->getCpuPtr()->clockPeriod(), flag);
990        DPRINTF(TLBVerbose,
991                "Adding to walker fifo: queue size before adding: %d\n",
992                stateQueues[start_lookup_level].size());
993        stateQueues[start_lookup_level].push_back(currState);
994        currState = NULL;
995    } else if (!currState->functional) {
996        fetchDescriptor(desc_addr, (uint8_t*)&currState->longDesc.data,
997                        sizeof(uint64_t), flag, -1, NULL,
998                        &TableWalker::doLongDescriptor);
999        f = currState->fault;
1000    } else {
1001        RequestPtr req = new Request(desc_addr, sizeof(uint64_t), flag,
1002                                     masterId);
1003        PacketPtr pkt = new Packet(req, MemCmd::ReadReq);
1004        pkt->dataStatic((uint8_t*) &currState->longDesc.data);
1005        port->sendFunctional(pkt);
1006        doLongDescriptor();
1007        delete req;
1008        delete pkt;
1009        f = currState->fault;
1010    }
1011
1012    return f;
1013}
1014
1015void
1016TableWalker::memAttrs(ThreadContext *tc, TlbEntry &te, SCTLR sctlr,
1017                      uint8_t texcb, bool s)
1018{
1019    // Note: tc and sctlr local variables are hiding tc and sctrl class
1020    // variables
1021    DPRINTF(TLBVerbose, "memAttrs texcb:%d s:%d\n", texcb, s);
1022    te.shareable = false; // default value
1023    te.nonCacheable = false;
1024    te.outerShareable = false;
1025    if (sctlr.tre == 0 || ((sctlr.tre == 1) && (sctlr.m == 0))) {
1026        switch(texcb) {
1027          case 0: // Stongly-ordered
1028            te.nonCacheable = true;
1029            te.mtype = TlbEntry::MemoryType::StronglyOrdered;
1030            te.shareable = true;
1031            te.innerAttrs = 1;
1032            te.outerAttrs = 0;
1033            break;
1034          case 1: // Shareable Device
1035            te.nonCacheable = true;
1036            te.mtype = TlbEntry::MemoryType::Device;
1037            te.shareable = true;
1038            te.innerAttrs = 3;
1039            te.outerAttrs = 0;
1040            break;
1041          case 2: // Outer and Inner Write-Through, no Write-Allocate
1042            te.mtype = TlbEntry::MemoryType::Normal;
1043            te.shareable = s;
1044            te.innerAttrs = 6;
1045            te.outerAttrs = bits(texcb, 1, 0);
1046            break;
1047          case 3: // Outer and Inner Write-Back, no Write-Allocate
1048            te.mtype = TlbEntry::MemoryType::Normal;
1049            te.shareable = s;
1050            te.innerAttrs = 7;
1051            te.outerAttrs = bits(texcb, 1, 0);
1052            break;
1053          case 4: // Outer and Inner Non-cacheable
1054            te.nonCacheable = true;
1055            te.mtype = TlbEntry::MemoryType::Normal;
1056            te.shareable = s;
1057            te.innerAttrs = 0;
1058            te.outerAttrs = bits(texcb, 1, 0);
1059            break;
1060          case 5: // Reserved
1061            panic("Reserved texcb value!\n");
1062            break;
1063          case 6: // Implementation Defined
1064            panic("Implementation-defined texcb value!\n");
1065            break;
1066          case 7: // Outer and Inner Write-Back, Write-Allocate
1067            te.mtype = TlbEntry::MemoryType::Normal;
1068            te.shareable = s;
1069            te.innerAttrs = 5;
1070            te.outerAttrs = 1;
1071            break;
1072          case 8: // Non-shareable Device
1073            te.nonCacheable = true;
1074            te.mtype = TlbEntry::MemoryType::Device;
1075            te.shareable = false;
1076            te.innerAttrs = 3;
1077            te.outerAttrs = 0;
1078            break;
1079          case 9 ... 15:  // Reserved
1080            panic("Reserved texcb value!\n");
1081            break;
1082          case 16 ... 31: // Cacheable Memory
1083            te.mtype = TlbEntry::MemoryType::Normal;
1084            te.shareable = s;
1085            if (bits(texcb, 1,0) == 0 || bits(texcb, 3,2) == 0)
1086                te.nonCacheable = true;
1087            te.innerAttrs = bits(texcb, 1, 0);
1088            te.outerAttrs = bits(texcb, 3, 2);
1089            break;
1090          default:
1091            panic("More than 32 states for 5 bits?\n");
1092        }
1093    } else {
1094        assert(tc);
1095        PRRR prrr = tc->readMiscReg(flattenMiscRegNsBanked(MISCREG_PRRR,
1096                                    currState->tc, !currState->isSecure));
1097        NMRR nmrr = tc->readMiscReg(flattenMiscRegNsBanked(MISCREG_NMRR,
1098                                    currState->tc, !currState->isSecure));
1099        DPRINTF(TLBVerbose, "memAttrs PRRR:%08x NMRR:%08x\n", prrr, nmrr);
1100        uint8_t curr_tr = 0, curr_ir = 0, curr_or = 0;
1101        switch(bits(texcb, 2,0)) {
1102          case 0:
1103            curr_tr = prrr.tr0;
1104            curr_ir = nmrr.ir0;
1105            curr_or = nmrr.or0;
1106            te.outerShareable = (prrr.nos0 == 0);
1107            break;
1108          case 1:
1109            curr_tr = prrr.tr1;
1110            curr_ir = nmrr.ir1;
1111            curr_or = nmrr.or1;
1112            te.outerShareable = (prrr.nos1 == 0);
1113            break;
1114          case 2:
1115            curr_tr = prrr.tr2;
1116            curr_ir = nmrr.ir2;
1117            curr_or = nmrr.or2;
1118            te.outerShareable = (prrr.nos2 == 0);
1119            break;
1120          case 3:
1121            curr_tr = prrr.tr3;
1122            curr_ir = nmrr.ir3;
1123            curr_or = nmrr.or3;
1124            te.outerShareable = (prrr.nos3 == 0);
1125            break;
1126          case 4:
1127            curr_tr = prrr.tr4;
1128            curr_ir = nmrr.ir4;
1129            curr_or = nmrr.or4;
1130            te.outerShareable = (prrr.nos4 == 0);
1131            break;
1132          case 5:
1133            curr_tr = prrr.tr5;
1134            curr_ir = nmrr.ir5;
1135            curr_or = nmrr.or5;
1136            te.outerShareable = (prrr.nos5 == 0);
1137            break;
1138          case 6:
1139            panic("Imp defined type\n");
1140          case 7:
1141            curr_tr = prrr.tr7;
1142            curr_ir = nmrr.ir7;
1143            curr_or = nmrr.or7;
1144            te.outerShareable = (prrr.nos7 == 0);
1145            break;
1146        }
1147
1148        switch(curr_tr) {
1149          case 0:
1150            DPRINTF(TLBVerbose, "StronglyOrdered\n");
1151            te.mtype = TlbEntry::MemoryType::StronglyOrdered;
1152            te.nonCacheable = true;
1153            te.innerAttrs = 1;
1154            te.outerAttrs = 0;
1155            te.shareable = true;
1156            break;
1157          case 1:
1158            DPRINTF(TLBVerbose, "Device ds1:%d ds0:%d s:%d\n",
1159                    prrr.ds1, prrr.ds0, s);
1160            te.mtype = TlbEntry::MemoryType::Device;
1161            te.nonCacheable = true;
1162            te.innerAttrs = 3;
1163            te.outerAttrs = 0;
1164            if (prrr.ds1 && s)
1165                te.shareable = true;
1166            if (prrr.ds0 && !s)
1167                te.shareable = true;
1168            break;
1169          case 2:
1170            DPRINTF(TLBVerbose, "Normal ns1:%d ns0:%d s:%d\n",
1171                    prrr.ns1, prrr.ns0, s);
1172            te.mtype = TlbEntry::MemoryType::Normal;
1173            if (prrr.ns1 && s)
1174                te.shareable = true;
1175            if (prrr.ns0 && !s)
1176                te.shareable = true;
1177            break;
1178          case 3:
1179            panic("Reserved type");
1180        }
1181
1182        if (te.mtype == TlbEntry::MemoryType::Normal){
1183            switch(curr_ir) {
1184              case 0:
1185                te.nonCacheable = true;
1186                te.innerAttrs = 0;
1187                break;
1188              case 1:
1189                te.innerAttrs = 5;
1190                break;
1191              case 2:
1192                te.innerAttrs = 6;
1193                break;
1194              case 3:
1195                te.innerAttrs = 7;
1196                break;
1197            }
1198
1199            switch(curr_or) {
1200              case 0:
1201                te.nonCacheable = true;
1202                te.outerAttrs = 0;
1203                break;
1204              case 1:
1205                te.outerAttrs = 1;
1206                break;
1207              case 2:
1208                te.outerAttrs = 2;
1209                break;
1210              case 3:
1211                te.outerAttrs = 3;
1212                break;
1213            }
1214        }
1215    }
1216    DPRINTF(TLBVerbose, "memAttrs: shareable: %d, innerAttrs: %d, "
1217            "outerAttrs: %d\n",
1218            te.shareable, te.innerAttrs, te.outerAttrs);
1219    te.setAttributes(false);
1220}
1221
1222void
1223TableWalker::memAttrsLPAE(ThreadContext *tc, TlbEntry &te,
1224    LongDescriptor &lDescriptor)
1225{
1226    assert(_haveLPAE);
1227
1228    uint8_t attr;
1229    uint8_t sh = lDescriptor.sh();
1230    // Different format and source of attributes if this is a stage 2
1231    // translation
1232    if (isStage2) {
1233        attr = lDescriptor.memAttr();
1234        uint8_t attr_3_2 = (attr >> 2) & 0x3;
1235        uint8_t attr_1_0 =  attr       & 0x3;
1236
1237        DPRINTF(TLBVerbose, "memAttrsLPAE MemAttr:%#x sh:%#x\n", attr, sh);
1238
1239        if (attr_3_2 == 0) {
1240            te.mtype        = attr_1_0 == 0 ? TlbEntry::MemoryType::StronglyOrdered
1241                                            : TlbEntry::MemoryType::Device;
1242            te.outerAttrs   = 0;
1243            te.innerAttrs   = attr_1_0 == 0 ? 1 : 3;
1244            te.nonCacheable = true;
1245        } else {
1246            te.mtype        = TlbEntry::MemoryType::Normal;
1247            te.outerAttrs   = attr_3_2 == 1 ? 0 :
1248                              attr_3_2 == 2 ? 2 : 1;
1249            te.innerAttrs   = attr_1_0 == 1 ? 0 :
1250                              attr_1_0 == 2 ? 6 : 5;
1251            te.nonCacheable = (attr_3_2 == 1) || (attr_1_0 == 1);
1252        }
1253    } else {
1254        uint8_t attrIndx = lDescriptor.attrIndx();
1255
1256        // LPAE always uses remapping of memory attributes, irrespective of the
1257        // value of SCTLR.TRE
1258        MiscRegIndex reg = attrIndx & 0x4 ? MISCREG_MAIR1 : MISCREG_MAIR0;
1259        int reg_as_int = flattenMiscRegNsBanked(reg, currState->tc,
1260                                                !currState->isSecure);
1261        uint32_t mair = currState->tc->readMiscReg(reg_as_int);
1262        attr = (mair >> (8 * (attrIndx % 4))) & 0xff;
1263        uint8_t attr_7_4 = bits(attr, 7, 4);
1264        uint8_t attr_3_0 = bits(attr, 3, 0);
1265        DPRINTF(TLBVerbose, "memAttrsLPAE AttrIndx:%#x sh:%#x, attr %#x\n", attrIndx, sh, attr);
1266
1267        // Note: the memory subsystem only cares about the 'cacheable' memory
1268        // attribute. The other attributes are only used to fill the PAR register
1269        // accordingly to provide the illusion of full support
1270        te.nonCacheable = false;
1271
1272        switch (attr_7_4) {
1273          case 0x0:
1274            // Strongly-ordered or Device memory
1275            if (attr_3_0 == 0x0)
1276                te.mtype = TlbEntry::MemoryType::StronglyOrdered;
1277            else if (attr_3_0 == 0x4)
1278                te.mtype = TlbEntry::MemoryType::Device;
1279            else
1280                panic("Unpredictable behavior\n");
1281            te.nonCacheable = true;
1282            te.outerAttrs   = 0;
1283            break;
1284          case 0x4:
1285            // Normal memory, Outer Non-cacheable
1286            te.mtype = TlbEntry::MemoryType::Normal;
1287            te.outerAttrs = 0;
1288            if (attr_3_0 == 0x4)
1289                // Inner Non-cacheable
1290                te.nonCacheable = true;
1291            else if (attr_3_0 < 0x8)
1292                panic("Unpredictable behavior\n");
1293            break;
1294          case 0x8:
1295          case 0x9:
1296          case 0xa:
1297          case 0xb:
1298          case 0xc:
1299          case 0xd:
1300          case 0xe:
1301          case 0xf:
1302            if (attr_7_4 & 0x4) {
1303                te.outerAttrs = (attr_7_4 & 1) ? 1 : 3;
1304            } else {
1305                te.outerAttrs = 0x2;
1306            }
1307            // Normal memory, Outer Cacheable
1308            te.mtype = TlbEntry::MemoryType::Normal;
1309            if (attr_3_0 != 0x4 && attr_3_0 < 0x8)
1310                panic("Unpredictable behavior\n");
1311            break;
1312          default:
1313            panic("Unpredictable behavior\n");
1314            break;
1315        }
1316
1317        switch (attr_3_0) {
1318          case 0x0:
1319            te.innerAttrs = 0x1;
1320            break;
1321          case 0x4:
1322            te.innerAttrs = attr_7_4 == 0 ? 0x3 : 0;
1323            break;
1324          case 0x8:
1325          case 0x9:
1326          case 0xA:
1327          case 0xB:
1328            te.innerAttrs = 6;
1329            break;
1330          case 0xC:
1331          case 0xD:
1332          case 0xE:
1333          case 0xF:
1334            te.innerAttrs = attr_3_0 & 1 ? 0x5 : 0x7;
1335            break;
1336          default:
1337            panic("Unpredictable behavior\n");
1338            break;
1339        }
1340    }
1341
1342    te.outerShareable = sh == 2;
1343    te.shareable       = (sh & 0x2) ? true : false;
1344    te.setAttributes(true);
1345    te.attributes |= (uint64_t) attr << 56;
1346}
1347
1348void
1349TableWalker::memAttrsAArch64(ThreadContext *tc, TlbEntry &te, uint8_t attrIndx,
1350                             uint8_t sh)
1351{
1352    DPRINTF(TLBVerbose, "memAttrsAArch64 AttrIndx:%#x sh:%#x\n", attrIndx, sh);
1353
1354    // Select MAIR
1355    uint64_t mair;
1356    switch (currState->el) {
1357      case EL0:
1358      case EL1:
1359        mair = tc->readMiscReg(MISCREG_MAIR_EL1);
1360        break;
1361      case EL2:
1362        mair = tc->readMiscReg(MISCREG_MAIR_EL2);
1363        break;
1364      case EL3:
1365        mair = tc->readMiscReg(MISCREG_MAIR_EL3);
1366        break;
1367      default:
1368        panic("Invalid exception level");
1369        break;
1370    }
1371
1372    // Select attributes
1373    uint8_t attr = bits(mair, 8 * attrIndx + 7, 8 * attrIndx);
1374    uint8_t attr_lo = bits(attr, 3, 0);
1375    uint8_t attr_hi = bits(attr, 7, 4);
1376
1377    // Memory type
1378    te.mtype = attr_hi == 0 ? TlbEntry::MemoryType::Device : TlbEntry::MemoryType::Normal;
1379
1380    // Cacheability
1381    te.nonCacheable = false;
1382    if (te.mtype == TlbEntry::MemoryType::Device ||  // Device memory
1383        attr_hi == 0x8 ||  // Normal memory, Outer Non-cacheable
1384        attr_lo == 0x8) {  // Normal memory, Inner Non-cacheable
1385        te.nonCacheable = true;
1386    }
1387
1388    te.shareable       = sh == 2;
1389    te.outerShareable = (sh & 0x2) ? true : false;
1390    // Attributes formatted according to the 64-bit PAR
1391    te.attributes = ((uint64_t) attr << 56) |
1392        (1 << 11) |     // LPAE bit
1393        (te.ns << 9) |  // NS bit
1394        (sh << 7);
1395}
1396
1397void
1398TableWalker::doL1Descriptor()
1399{
1400    if (currState->fault != NoFault) {
1401        return;
1402    }
1403
1404    DPRINTF(TLB, "L1 descriptor for %#x is %#x\n",
1405            currState->vaddr_tainted, currState->l1Desc.data);
1406    TlbEntry te;
1407
1408    switch (currState->l1Desc.type()) {
1409      case L1Descriptor::Ignore:
1410      case L1Descriptor::Reserved:
1411        if (!currState->timing) {
1412            currState->tc = NULL;
1413            currState->req = NULL;
1414        }
1415        DPRINTF(TLB, "L1 Descriptor Reserved/Ignore, causing fault\n");
1416        if (currState->isFetch)
1417            currState->fault =
1418                std::make_shared<PrefetchAbort>(
1419                    currState->vaddr_tainted,
1420                    ArmFault::TranslationLL + L1,
1421                    isStage2,
1422                    ArmFault::VmsaTran);
1423        else
1424            currState->fault =
1425                std::make_shared<DataAbort>(
1426                    currState->vaddr_tainted,
1427                    TlbEntry::DomainType::NoAccess,
1428                    currState->isWrite,
1429                    ArmFault::TranslationLL + L1, isStage2,
1430                    ArmFault::VmsaTran);
1431        return;
1432      case L1Descriptor::Section:
1433        if (currState->sctlr.afe && bits(currState->l1Desc.ap(), 0) == 0) {
1434            /** @todo: check sctlr.ha (bit[17]) if Hardware Access Flag is
1435              * enabled if set, do l1.Desc.setAp0() instead of generating
1436              * AccessFlag0
1437              */
1438
1439            currState->fault = std::make_shared<DataAbort>(
1440                currState->vaddr_tainted,
1441                currState->l1Desc.domain(),
1442                currState->isWrite,
1443                ArmFault::AccessFlagLL + L1,
1444                isStage2,
1445                ArmFault::VmsaTran);
1446        }
1447        if (currState->l1Desc.supersection()) {
1448            panic("Haven't implemented supersections\n");
1449        }
1450        insertTableEntry(currState->l1Desc, false);
1451        return;
1452      case L1Descriptor::PageTable:
1453        {
1454            Addr l2desc_addr;
1455            l2desc_addr = currState->l1Desc.l2Addr() |
1456                (bits(currState->vaddr, 19, 12) << 2);
1457            DPRINTF(TLB, "L1 descriptor points to page table at: %#x (%s)\n",
1458                    l2desc_addr, currState->isSecure ? "s" : "ns");
1459
1460            // Trickbox address check
1461            currState->fault = testWalk(l2desc_addr, sizeof(uint32_t),
1462                                        currState->l1Desc.domain(), L2);
1463
1464            if (currState->fault) {
1465                if (!currState->timing) {
1466                    currState->tc = NULL;
1467                    currState->req = NULL;
1468                }
1469                return;
1470            }
1471
1472            Request::Flags flag = Request::PT_WALK;
1473            if (currState->isSecure)
1474                flag.set(Request::SECURE);
1475
1476            bool delayed;
1477            delayed = fetchDescriptor(l2desc_addr,
1478                                      (uint8_t*)&currState->l2Desc.data,
1479                                      sizeof(uint32_t), flag, -1, &doL2DescEvent,
1480                                      &TableWalker::doL2Descriptor);
1481            if (delayed) {
1482                currState->delayed = true;
1483            }
1484
1485            return;
1486        }
1487      default:
1488        panic("A new type in a 2 bit field?\n");
1489    }
1490}
1491
1492void
1493TableWalker::doLongDescriptor()
1494{
1495    if (currState->fault != NoFault) {
1496        return;
1497    }
1498
1499    DPRINTF(TLB, "L%d descriptor for %#llx is %#llx (%s)\n",
1500            currState->longDesc.lookupLevel, currState->vaddr_tainted,
1501            currState->longDesc.data,
1502            currState->aarch64 ? "AArch64" : "long-desc.");
1503
1504    if ((currState->longDesc.type() == LongDescriptor::Block) ||
1505        (currState->longDesc.type() == LongDescriptor::Page)) {
1506        DPRINTF(TLBVerbose, "Analyzing L%d descriptor: %#llx, pxn: %d, "
1507                "xn: %d, ap: %d, af: %d, type: %d\n",
1508                currState->longDesc.lookupLevel,
1509                currState->longDesc.data,
1510                currState->longDesc.pxn(),
1511                currState->longDesc.xn(),
1512                currState->longDesc.ap(),
1513                currState->longDesc.af(),
1514                currState->longDesc.type());
1515    } else {
1516        DPRINTF(TLBVerbose, "Analyzing L%d descriptor: %#llx, type: %d\n",
1517                currState->longDesc.lookupLevel,
1518                currState->longDesc.data,
1519                currState->longDesc.type());
1520    }
1521
1522    TlbEntry te;
1523
1524    switch (currState->longDesc.type()) {
1525      case LongDescriptor::Invalid:
1526        if (!currState->timing) {
1527            currState->tc = NULL;
1528            currState->req = NULL;
1529        }
1530
1531        DPRINTF(TLB, "L%d descriptor Invalid, causing fault type %d\n",
1532                currState->longDesc.lookupLevel,
1533                ArmFault::TranslationLL + currState->longDesc.lookupLevel);
1534        if (currState->isFetch)
1535            currState->fault = std::make_shared<PrefetchAbort>(
1536                currState->vaddr_tainted,
1537                ArmFault::TranslationLL + currState->longDesc.lookupLevel,
1538                isStage2,
1539                ArmFault::LpaeTran);
1540        else
1541            currState->fault = std::make_shared<DataAbort>(
1542                currState->vaddr_tainted,
1543                TlbEntry::DomainType::NoAccess,
1544                currState->isWrite,
1545                ArmFault::TranslationLL + currState->longDesc.lookupLevel,
1546                isStage2,
1547                ArmFault::LpaeTran);
1548        return;
1549      case LongDescriptor::Block:
1550      case LongDescriptor::Page:
1551        {
1552            bool fault = false;
1553            bool aff = false;
1554            // Check for address size fault
1555            if (checkAddrSizeFaultAArch64(
1556                    mbits(currState->longDesc.data, MaxPhysAddrRange - 1,
1557                          currState->longDesc.offsetBits()),
1558                    currState->physAddrRange)) {
1559                fault = true;
1560                DPRINTF(TLB, "L%d descriptor causing Address Size Fault\n",
1561                        currState->longDesc.lookupLevel);
1562            // Check for access fault
1563            } else if (currState->longDesc.af() == 0) {
1564                fault = true;
1565                DPRINTF(TLB, "L%d descriptor causing Access Fault\n",
1566                        currState->longDesc.lookupLevel);
1567                aff = true;
1568            }
1569            if (fault) {
1570                if (currState->isFetch)
1571                    currState->fault = std::make_shared<PrefetchAbort>(
1572                        currState->vaddr_tainted,
1573                        (aff ? ArmFault::AccessFlagLL : ArmFault::AddressSizeLL) +
1574                        currState->longDesc.lookupLevel,
1575                        isStage2,
1576                        ArmFault::LpaeTran);
1577                else
1578                    currState->fault = std::make_shared<DataAbort>(
1579                        currState->vaddr_tainted,
1580                        TlbEntry::DomainType::NoAccess, currState->isWrite,
1581                        (aff ? ArmFault::AccessFlagLL : ArmFault::AddressSizeLL) +
1582                        currState->longDesc.lookupLevel,
1583                        isStage2,
1584                        ArmFault::LpaeTran);
1585            } else {
1586                insertTableEntry(currState->longDesc, true);
1587            }
1588        }
1589        return;
1590      case LongDescriptor::Table:
1591        {
1592            // Set hierarchical permission flags
1593            currState->secureLookup = currState->secureLookup &&
1594                currState->longDesc.secureTable();
1595            currState->rwTable = currState->rwTable &&
1596                currState->longDesc.rwTable();
1597            currState->userTable = currState->userTable &&
1598                currState->longDesc.userTable();
1599            currState->xnTable = currState->xnTable ||
1600                currState->longDesc.xnTable();
1601            currState->pxnTable = currState->pxnTable ||
1602                currState->longDesc.pxnTable();
1603
1604            // Set up next level lookup
1605            Addr next_desc_addr = currState->longDesc.nextDescAddr(
1606                currState->vaddr);
1607
1608            DPRINTF(TLB, "L%d descriptor points to L%d descriptor at: %#x (%s)\n",
1609                    currState->longDesc.lookupLevel,
1610                    currState->longDesc.lookupLevel + 1,
1611                    next_desc_addr,
1612                    currState->secureLookup ? "s" : "ns");
1613
1614            // Check for address size fault
1615            if (currState->aarch64 && checkAddrSizeFaultAArch64(
1616                    next_desc_addr, currState->physAddrRange)) {
1617                DPRINTF(TLB, "L%d descriptor causing Address Size Fault\n",
1618                        currState->longDesc.lookupLevel);
1619                if (currState->isFetch)
1620                    currState->fault = std::make_shared<PrefetchAbort>(
1621                        currState->vaddr_tainted,
1622                        ArmFault::AddressSizeLL
1623                        + currState->longDesc.lookupLevel,
1624                        isStage2,
1625                        ArmFault::LpaeTran);
1626                else
1627                    currState->fault = std::make_shared<DataAbort>(
1628                        currState->vaddr_tainted,
1629                        TlbEntry::DomainType::NoAccess, currState->isWrite,
1630                        ArmFault::AddressSizeLL
1631                        + currState->longDesc.lookupLevel,
1632                        isStage2,
1633                        ArmFault::LpaeTran);
1634                return;
1635            }
1636
1637            // Trickbox address check
1638            currState->fault = testWalk(
1639                next_desc_addr, sizeof(uint64_t), TlbEntry::DomainType::Client,
1640                toLookupLevel(currState->longDesc.lookupLevel +1));
1641
1642            if (currState->fault) {
1643                if (!currState->timing) {
1644                    currState->tc = NULL;
1645                    currState->req = NULL;
1646                }
1647                return;
1648            }
1649
1650            Request::Flags flag = Request::PT_WALK;
1651            if (currState->secureLookup)
1652                flag.set(Request::SECURE);
1653
1654            currState->longDesc.lookupLevel =
1655                (LookupLevel) (currState->longDesc.lookupLevel + 1);
1656            Event *event = NULL;
1657            switch (currState->longDesc.lookupLevel) {
1658              case L1:
1659                assert(currState->aarch64);
1660                event = &doL1LongDescEvent;
1661                break;
1662              case L2:
1663                event = &doL2LongDescEvent;
1664                break;
1665              case L3:
1666                event = &doL3LongDescEvent;
1667                break;
1668              default:
1669                panic("Wrong lookup level in table walk\n");
1670                break;
1671            }
1672
1673            bool delayed;
1674            delayed = fetchDescriptor(next_desc_addr, (uint8_t*)&currState->longDesc.data,
1675                                      sizeof(uint64_t), flag, -1, event,
1676                                      &TableWalker::doLongDescriptor);
1677            if (delayed) {
1678                 currState->delayed = true;
1679            }
1680        }
1681        return;
1682      default:
1683        panic("A new type in a 2 bit field?\n");
1684    }
1685}
1686
1687void
1688TableWalker::doL2Descriptor()
1689{
1690    if (currState->fault != NoFault) {
1691        return;
1692    }
1693
1694    DPRINTF(TLB, "L2 descriptor for %#x is %#x\n",
1695            currState->vaddr_tainted, currState->l2Desc.data);
1696    TlbEntry te;
1697
1698    if (currState->l2Desc.invalid()) {
1699        DPRINTF(TLB, "L2 descriptor invalid, causing fault\n");
1700        if (!currState->timing) {
1701            currState->tc = NULL;
1702            currState->req = NULL;
1703        }
1704        if (currState->isFetch)
1705            currState->fault = std::make_shared<PrefetchAbort>(
1706                    currState->vaddr_tainted,
1707                    ArmFault::TranslationLL + L2,
1708                    isStage2,
1709                    ArmFault::VmsaTran);
1710        else
1711            currState->fault = std::make_shared<DataAbort>(
1712                currState->vaddr_tainted, currState->l1Desc.domain(),
1713                currState->isWrite, ArmFault::TranslationLL + L2,
1714                isStage2,
1715                ArmFault::VmsaTran);
1716        return;
1717    }
1718
1719    if (currState->sctlr.afe && bits(currState->l2Desc.ap(), 0) == 0) {
1720        /** @todo: check sctlr.ha (bit[17]) if Hardware Access Flag is enabled
1721          * if set, do l2.Desc.setAp0() instead of generating AccessFlag0
1722          */
1723         DPRINTF(TLB, "Generating access fault at L2, afe: %d, ap: %d\n",
1724                 currState->sctlr.afe, currState->l2Desc.ap());
1725
1726        currState->fault = std::make_shared<DataAbort>(
1727            currState->vaddr_tainted,
1728            TlbEntry::DomainType::NoAccess, currState->isWrite,
1729            ArmFault::AccessFlagLL + L2, isStage2,
1730            ArmFault::VmsaTran);
1731    }
1732
1733    insertTableEntry(currState->l2Desc, false);
1734}
1735
1736void
1737TableWalker::doL1DescriptorWrapper()
1738{
1739    currState = stateQueues[L1].front();
1740    currState->delayed = false;
1741    // if there's a stage2 translation object we don't need it any more
1742    if (currState->stage2Tran) {
1743        delete currState->stage2Tran;
1744        currState->stage2Tran = NULL;
1745    }
1746
1747
1748    DPRINTF(TLBVerbose, "L1 Desc object host addr: %p\n",&currState->l1Desc.data);
1749    DPRINTF(TLBVerbose, "L1 Desc object      data: %08x\n",currState->l1Desc.data);
1750
1751    DPRINTF(TLBVerbose, "calling doL1Descriptor for vaddr:%#x\n", currState->vaddr_tainted);
1752    doL1Descriptor();
1753
1754    stateQueues[L1].pop_front();
1755    // Check if fault was generated
1756    if (currState->fault != NoFault) {
1757        currState->transState->finish(currState->fault, currState->req,
1758                                      currState->tc, currState->mode);
1759        statWalksShortTerminatedAtLevel[0]++;
1760
1761        pending = false;
1762        nextWalk(currState->tc);
1763
1764        currState->req = NULL;
1765        currState->tc = NULL;
1766        currState->delayed = false;
1767        delete currState;
1768    }
1769    else if (!currState->delayed) {
1770        // delay is not set so there is no L2 to do
1771        // Don't finish the translation if a stage 2 look up is underway
1772        if (!currState->doingStage2) {
1773            statWalkServiceTime.sample(curTick() - currState->startTime);
1774            DPRINTF(TLBVerbose, "calling translateTiming again\n");
1775            currState->fault = tlb->translateTiming(currState->req, currState->tc,
1776                currState->transState, currState->mode);
1777            statWalksShortTerminatedAtLevel[0]++;
1778        }
1779
1780        pending = false;
1781        nextWalk(currState->tc);
1782
1783        currState->req = NULL;
1784        currState->tc = NULL;
1785        currState->delayed = false;
1786        delete currState;
1787    } else {
1788        // need to do L2 descriptor
1789        stateQueues[L2].push_back(currState);
1790    }
1791    currState = NULL;
1792}
1793
1794void
1795TableWalker::doL2DescriptorWrapper()
1796{
1797    currState = stateQueues[L2].front();
1798    assert(currState->delayed);
1799    // if there's a stage2 translation object we don't need it any more
1800    if (currState->stage2Tran) {
1801        delete currState->stage2Tran;
1802        currState->stage2Tran = NULL;
1803    }
1804
1805    DPRINTF(TLBVerbose, "calling doL2Descriptor for vaddr:%#x\n",
1806            currState->vaddr_tainted);
1807    doL2Descriptor();
1808
1809    // Check if fault was generated
1810    if (currState->fault != NoFault) {
1811        currState->transState->finish(currState->fault, currState->req,
1812                                      currState->tc, currState->mode);
1813        statWalksShortTerminatedAtLevel[1]++;
1814    }
1815    else {
1816        // Don't finish the translation if a stage 2 look up is underway
1817        if (!currState->doingStage2) {
1818            statWalkServiceTime.sample(curTick() - currState->startTime);
1819            DPRINTF(TLBVerbose, "calling translateTiming again\n");
1820            currState->fault = tlb->translateTiming(currState->req,
1821                currState->tc, currState->transState, currState->mode);
1822            statWalksShortTerminatedAtLevel[1]++;
1823        }
1824    }
1825
1826
1827    stateQueues[L2].pop_front();
1828    pending = false;
1829    nextWalk(currState->tc);
1830
1831    currState->req = NULL;
1832    currState->tc = NULL;
1833    currState->delayed = false;
1834
1835    delete currState;
1836    currState = NULL;
1837}
1838
1839void
1840TableWalker::doL0LongDescriptorWrapper()
1841{
1842    doLongDescriptorWrapper(L0);
1843}
1844
1845void
1846TableWalker::doL1LongDescriptorWrapper()
1847{
1848    doLongDescriptorWrapper(L1);
1849}
1850
1851void
1852TableWalker::doL2LongDescriptorWrapper()
1853{
1854    doLongDescriptorWrapper(L2);
1855}
1856
1857void
1858TableWalker::doL3LongDescriptorWrapper()
1859{
1860    doLongDescriptorWrapper(L3);
1861}
1862
1863void
1864TableWalker::doLongDescriptorWrapper(LookupLevel curr_lookup_level)
1865{
1866    currState = stateQueues[curr_lookup_level].front();
1867    assert(curr_lookup_level == currState->longDesc.lookupLevel);
1868    currState->delayed = false;
1869
1870    // if there's a stage2 translation object we don't need it any more
1871    if (currState->stage2Tran) {
1872        delete currState->stage2Tran;
1873        currState->stage2Tran = NULL;
1874    }
1875
1876    DPRINTF(TLBVerbose, "calling doLongDescriptor for vaddr:%#x\n",
1877            currState->vaddr_tainted);
1878    doLongDescriptor();
1879
1880    stateQueues[curr_lookup_level].pop_front();
1881
1882    if (currState->fault != NoFault) {
1883        // A fault was generated
1884        currState->transState->finish(currState->fault, currState->req,
1885                                      currState->tc, currState->mode);
1886
1887        pending = false;
1888        nextWalk(currState->tc);
1889
1890        currState->req = NULL;
1891        currState->tc = NULL;
1892        currState->delayed = false;
1893        delete currState;
1894    } else if (!currState->delayed) {
1895        // No additional lookups required
1896        // Don't finish the translation if a stage 2 look up is underway
1897        if (!currState->doingStage2) {
1898            DPRINTF(TLBVerbose, "calling translateTiming again\n");
1899            statWalkServiceTime.sample(curTick() - currState->startTime);
1900            currState->fault = tlb->translateTiming(currState->req, currState->tc,
1901                                                    currState->transState,
1902                                                    currState->mode);
1903            statWalksLongTerminatedAtLevel[(unsigned) curr_lookup_level]++;
1904        }
1905
1906        pending = false;
1907        nextWalk(currState->tc);
1908
1909        currState->req = NULL;
1910        currState->tc = NULL;
1911        currState->delayed = false;
1912        delete currState;
1913    } else {
1914        if (curr_lookup_level >= MAX_LOOKUP_LEVELS - 1)
1915            panic("Max. number of lookups already reached in table walk\n");
1916        // Need to perform additional lookups
1917        stateQueues[currState->longDesc.lookupLevel].push_back(currState);
1918    }
1919    currState = NULL;
1920}
1921
1922
1923void
1924TableWalker::nextWalk(ThreadContext *tc)
1925{
1926    if (pendingQueue.size())
1927        schedule(doProcessEvent, clockEdge(Cycles(1)));
1928    else
1929        completeDrain();
1930}
1931
1932bool
1933TableWalker::fetchDescriptor(Addr descAddr, uint8_t *data, int numBytes,
1934    Request::Flags flags, int queueIndex, Event *event,
1935    void (TableWalker::*doDescriptor)())
1936{
1937    bool isTiming = currState->timing;
1938
1939    DPRINTF(TLBVerbose, "Fetching descriptor at address: 0x%x stage2Req: %d\n",
1940            descAddr, currState->stage2Req);
1941
1942    // If this translation has a stage 2 then we know descAddr is an IPA and
1943    // needs to be translated before we can access the page table. Do that
1944    // check here.
1945    if (currState->stage2Req) {
1946        Fault fault;
1947        flags = flags | TLB::MustBeOne;
1948
1949        if (isTiming) {
1950            Stage2MMU::Stage2Translation *tran = new
1951                Stage2MMU::Stage2Translation(*stage2Mmu, data, event,
1952                                             currState->vaddr);
1953            currState->stage2Tran = tran;
1954            stage2Mmu->readDataTimed(currState->tc, descAddr, tran, numBytes,
1955                                     flags);
1956            fault = tran->fault;
1957        } else {
1958            fault = stage2Mmu->readDataUntimed(currState->tc,
1959                currState->vaddr, descAddr, data, numBytes, flags,
1960                currState->functional);
1961        }
1962
1963        if (fault != NoFault) {
1964            currState->fault = fault;
1965        }
1966        if (isTiming) {
1967            if (queueIndex >= 0) {
1968                DPRINTF(TLBVerbose, "Adding to walker fifo: queue size before adding: %d\n",
1969                        stateQueues[queueIndex].size());
1970                stateQueues[queueIndex].push_back(currState);
1971                currState = NULL;
1972            }
1973        } else {
1974            (this->*doDescriptor)();
1975        }
1976    } else {
1977        if (isTiming) {
1978            port->dmaAction(MemCmd::ReadReq, descAddr, numBytes, event, data,
1979                           currState->tc->getCpuPtr()->clockPeriod(),flags);
1980            if (queueIndex >= 0) {
1981                DPRINTF(TLBVerbose, "Adding to walker fifo: queue size before adding: %d\n",
1982                        stateQueues[queueIndex].size());
1983                stateQueues[queueIndex].push_back(currState);
1984                currState = NULL;
1985            }
1986        } else if (!currState->functional) {
1987            port->dmaAction(MemCmd::ReadReq, descAddr, numBytes, NULL, data,
1988                           currState->tc->getCpuPtr()->clockPeriod(), flags);
1989            (this->*doDescriptor)();
1990        } else {
1991            RequestPtr req = new Request(descAddr, numBytes, flags, masterId);
1992            req->taskId(ContextSwitchTaskId::DMA);
1993            PacketPtr  pkt = new Packet(req, MemCmd::ReadReq);
1994            pkt->dataStatic(data);
1995            port->sendFunctional(pkt);
1996            (this->*doDescriptor)();
1997            delete req;
1998            delete pkt;
1999        }
2000    }
2001    return (isTiming);
2002}
2003
2004void
2005TableWalker::insertTableEntry(DescriptorBase &descriptor, bool longDescriptor)
2006{
2007    TlbEntry te;
2008
2009    // Create and fill a new page table entry
2010    te.valid          = true;
2011    te.longDescFormat = longDescriptor;
2012    te.isHyp          = currState->isHyp;
2013    te.asid           = currState->asid;
2014    te.vmid           = currState->vmid;
2015    te.N              = descriptor.offsetBits();
2016    te.vpn            = currState->vaddr >> te.N;
2017    te.size           = (1<<te.N) - 1;
2018    te.pfn            = descriptor.pfn();
2019    te.domain         = descriptor.domain();
2020    te.lookupLevel    = descriptor.lookupLevel;
2021    te.ns             = !descriptor.secure(haveSecurity, currState) || isStage2;
2022    te.nstid          = !currState->isSecure;
2023    te.xn             = descriptor.xn();
2024    if (currState->aarch64)
2025        te.el         = currState->el;
2026    else
2027        te.el         = 1;
2028
2029    statPageSizes[pageSizeNtoStatBin(te.N)]++;
2030    statRequestOrigin[COMPLETED][currState->isFetch]++;
2031
2032    // ASID has no meaning for stage 2 TLB entries, so mark all stage 2 entries
2033    // as global
2034    te.global         = descriptor.global(currState) || isStage2;
2035    if (longDescriptor) {
2036        LongDescriptor lDescriptor =
2037            dynamic_cast<LongDescriptor &>(descriptor);
2038
2039        te.xn |= currState->xnTable;
2040        te.pxn = currState->pxnTable || lDescriptor.pxn();
2041        if (isStage2) {
2042            // this is actually the HAP field, but its stored in the same bit
2043            // possitions as the AP field in a stage 1 translation.
2044            te.hap = lDescriptor.ap();
2045        } else {
2046           te.ap = ((!currState->rwTable || descriptor.ap() >> 1) << 1) |
2047               (currState->userTable && (descriptor.ap() & 0x1));
2048        }
2049        if (currState->aarch64)
2050            memAttrsAArch64(currState->tc, te, currState->longDesc.attrIndx(),
2051                            currState->longDesc.sh());
2052        else
2053            memAttrsLPAE(currState->tc, te, lDescriptor);
2054    } else {
2055        te.ap = descriptor.ap();
2056        memAttrs(currState->tc, te, currState->sctlr, descriptor.texcb(),
2057                 descriptor.shareable());
2058    }
2059
2060    // Debug output
2061    DPRINTF(TLB, descriptor.dbgHeader().c_str());
2062    DPRINTF(TLB, " - N:%d pfn:%#x size:%#x global:%d valid:%d\n",
2063            te.N, te.pfn, te.size, te.global, te.valid);
2064    DPRINTF(TLB, " - vpn:%#x xn:%d pxn:%d ap:%d domain:%d asid:%d "
2065            "vmid:%d hyp:%d nc:%d ns:%d\n", te.vpn, te.xn, te.pxn,
2066            te.ap, static_cast<uint8_t>(te.domain), te.asid, te.vmid, te.isHyp,
2067            te.nonCacheable, te.ns);
2068    DPRINTF(TLB, " - domain from L%d desc:%d data:%#x\n",
2069            descriptor.lookupLevel, static_cast<uint8_t>(descriptor.domain()),
2070            descriptor.getRawData());
2071
2072    // Insert the entry into the TLB
2073    tlb->insert(currState->vaddr, te);
2074    if (!currState->timing) {
2075        currState->tc  = NULL;
2076        currState->req = NULL;
2077    }
2078}
2079
2080ArmISA::TableWalker *
2081ArmTableWalkerParams::create()
2082{
2083    return new ArmISA::TableWalker(this);
2084}
2085
2086LookupLevel
2087TableWalker::toLookupLevel(uint8_t lookup_level_as_int)
2088{
2089    switch (lookup_level_as_int) {
2090      case L1:
2091        return L1;
2092      case L2:
2093        return L2;
2094      case L3:
2095        return L3;
2096      default:
2097        panic("Invalid lookup level conversion");
2098    }
2099}
2100
2101/* this method keeps track of the table walker queue's residency, so
2102 * needs to be called whenever requests start and complete. */
2103void
2104TableWalker::pendingChange()
2105{
2106    unsigned n = pendingQueue.size();
2107    if ((currState != NULL) && (currState != pendingQueue.front())) {
2108        ++n;
2109    }
2110
2111    if (n != pendingReqs) {
2112        Tick now = curTick();
2113        statPendingWalks.sample(pendingReqs, now - pendingChangeTick);
2114        pendingReqs = n;
2115        pendingChangeTick = now;
2116    }
2117}
2118
2119Fault
2120TableWalker::testWalk(Addr pa, Addr size, TlbEntry::DomainType domain,
2121                      LookupLevel lookup_level)
2122{
2123    return tlb->testWalk(pa, size, currState->vaddr, currState->isSecure,
2124                         currState->mode, domain, lookup_level);
2125}
2126
2127
2128uint8_t
2129TableWalker::pageSizeNtoStatBin(uint8_t N)
2130{
2131    /* for statPageSizes */
2132    switch(N) {
2133        case 12: return 0; // 4K
2134        case 14: return 1; // 16K (using 16K granule in v8-64)
2135        case 16: return 2; // 64K
2136        case 20: return 3; // 1M
2137        case 21: return 4; // 2M-LPAE
2138        case 24: return 5; // 16M
2139        case 25: return 6; // 32M (using 16K granule in v8-64)
2140        case 29: return 7; // 512M (using 64K granule in v8-64)
2141        case 30: return 8; // 1G-LPAE
2142        default:
2143            panic("unknown page size");
2144            return 255;
2145    }
2146}
2147
2148void
2149TableWalker::regStats()
2150{
2151    ClockedObject::regStats();
2152
2153    statWalks
2154        .name(name() + ".walks")
2155        .desc("Table walker walks requested")
2156        ;
2157
2158    statWalksShortDescriptor
2159        .name(name() + ".walksShort")
2160        .desc("Table walker walks initiated with short descriptors")
2161        .flags(Stats::nozero)
2162        ;
2163
2164    statWalksLongDescriptor
2165        .name(name() + ".walksLong")
2166        .desc("Table walker walks initiated with long descriptors")
2167        .flags(Stats::nozero)
2168        ;
2169
2170    statWalksShortTerminatedAtLevel
2171        .init(2)
2172        .name(name() + ".walksShortTerminationLevel")
2173        .desc("Level at which table walker walks "
2174              "with short descriptors terminate")
2175        .flags(Stats::nozero)
2176        ;
2177    statWalksShortTerminatedAtLevel.subname(0, "Level1");
2178    statWalksShortTerminatedAtLevel.subname(1, "Level2");
2179
2180    statWalksLongTerminatedAtLevel
2181        .init(4)
2182        .name(name() + ".walksLongTerminationLevel")
2183        .desc("Level at which table walker walks "
2184              "with long descriptors terminate")
2185        .flags(Stats::nozero)
2186        ;
2187    statWalksLongTerminatedAtLevel.subname(0, "Level0");
2188    statWalksLongTerminatedAtLevel.subname(1, "Level1");
2189    statWalksLongTerminatedAtLevel.subname(2, "Level2");
2190    statWalksLongTerminatedAtLevel.subname(3, "Level3");
2191
2192    statSquashedBefore
2193        .name(name() + ".walksSquashedBefore")
2194        .desc("Table walks squashed before starting")
2195        .flags(Stats::nozero)
2196        ;
2197
2198    statSquashedAfter
2199        .name(name() + ".walksSquashedAfter")
2200        .desc("Table walks squashed after completion")
2201        .flags(Stats::nozero)
2202        ;
2203
2204    statWalkWaitTime
2205        .init(16)
2206        .name(name() + ".walkWaitTime")
2207        .desc("Table walker wait (enqueue to first request) latency")
2208        .flags(Stats::pdf | Stats::nozero | Stats::nonan)
2209        ;
2210
2211    statWalkServiceTime
2212        .init(16)
2213        .name(name() + ".walkCompletionTime")
2214        .desc("Table walker service (enqueue to completion) latency")
2215        .flags(Stats::pdf | Stats::nozero | Stats::nonan)
2216        ;
2217
2218    statPendingWalks
2219        .init(16)
2220        .name(name() + ".walksPending")
2221        .desc("Table walker pending requests distribution")
2222        .flags(Stats::pdf | Stats::dist | Stats::nozero | Stats::nonan)
2223        ;
2224
2225    statPageSizes // see DDI 0487A D4-1661
2226        .init(9)
2227        .name(name() + ".walkPageSizes")
2228        .desc("Table walker page sizes translated")
2229        .flags(Stats::total | Stats::pdf | Stats::dist | Stats::nozero)
2230        ;
2231    statPageSizes.subname(0, "4K");
2232    statPageSizes.subname(1, "16K");
2233    statPageSizes.subname(2, "64K");
2234    statPageSizes.subname(3, "1M");
2235    statPageSizes.subname(4, "2M");
2236    statPageSizes.subname(5, "16M");
2237    statPageSizes.subname(6, "32M");
2238    statPageSizes.subname(7, "512M");
2239    statPageSizes.subname(8, "1G");
2240
2241    statRequestOrigin
2242        .init(2,2) // Instruction/Data, requests/completed
2243        .name(name() + ".walkRequestOrigin")
2244        .desc("Table walker requests started/completed, data/inst")
2245        .flags(Stats::total)
2246        ;
2247    statRequestOrigin.subname(0,"Requested");
2248    statRequestOrigin.subname(1,"Completed");
2249    statRequestOrigin.ysubname(0,"Data");
2250    statRequestOrigin.ysubname(1,"Inst");
2251}
2252