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