tlb.cc revision 8752
1/*
2 * Copyright (c) 2007-2008 The Hewlett-Packard Development Company
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: Gabe Black
38 */
39
40#include <cstring>
41
42#include "arch/x86/insts/microldstop.hh"
43#include "arch/x86/regs/misc.hh"
44#include "arch/x86/regs/msr.hh"
45#include "arch/x86/faults.hh"
46#include "arch/x86/pagetable.hh"
47#include "arch/x86/pagetable_walker.hh"
48#include "arch/x86/tlb.hh"
49#include "arch/x86/x86_traits.hh"
50#include "base/bitfield.hh"
51#include "base/trace.hh"
52#include "config/full_system.hh"
53#include "cpu/base.hh"
54#include "cpu/thread_context.hh"
55#include "debug/TLB.hh"
56#include "mem/packet_access.hh"
57#include "mem/request.hh"
58
59#if !FULL_SYSTEM
60#include "mem/page_table.hh"
61#include "sim/process.hh"
62#endif
63
64#include "sim/full_system.hh"
65
66namespace X86ISA {
67
68TLB::TLB(const Params *p) : BaseTLB(p), configAddress(0), size(p->size)
69{
70    tlb = new TlbEntry[size];
71    std::memset(tlb, 0, sizeof(TlbEntry) * size);
72
73    for (int x = 0; x < size; x++)
74        freeList.push_back(&tlb[x]);
75
76    walker = p->walker;
77    walker->setTLB(this);
78}
79
80TlbEntry *
81TLB::insert(Addr vpn, TlbEntry &entry)
82{
83    //TODO Deal with conflicting entries
84
85    TlbEntry *newEntry = NULL;
86    if (!freeList.empty()) {
87        newEntry = freeList.front();
88        freeList.pop_front();
89    } else {
90        newEntry = entryList.back();
91        entryList.pop_back();
92    }
93    *newEntry = entry;
94    newEntry->vaddr = vpn;
95    entryList.push_front(newEntry);
96    return newEntry;
97}
98
99TLB::EntryList::iterator
100TLB::lookupIt(Addr va, bool update_lru)
101{
102    //TODO make this smarter at some point
103    EntryList::iterator entry;
104    for (entry = entryList.begin(); entry != entryList.end(); entry++) {
105        if ((*entry)->vaddr <= va && (*entry)->vaddr + (*entry)->size > va) {
106            DPRINTF(TLB, "Matched vaddr %#x to entry starting at %#x "
107                    "with size %#x.\n", va, (*entry)->vaddr, (*entry)->size);
108            if (update_lru) {
109                entryList.push_front(*entry);
110                entryList.erase(entry);
111                entry = entryList.begin();
112            }
113            break;
114        }
115    }
116    return entry;
117}
118
119TlbEntry *
120TLB::lookup(Addr va, bool update_lru)
121{
122    EntryList::iterator entry = lookupIt(va, update_lru);
123    if (entry == entryList.end())
124        return NULL;
125    else
126        return *entry;
127}
128
129void
130TLB::invalidateAll()
131{
132    DPRINTF(TLB, "Invalidating all entries.\n");
133    while (!entryList.empty()) {
134        TlbEntry *entry = entryList.front();
135        entryList.pop_front();
136        freeList.push_back(entry);
137    }
138}
139
140void
141TLB::setConfigAddress(uint32_t addr)
142{
143    configAddress = addr;
144}
145
146void
147TLB::invalidateNonGlobal()
148{
149    DPRINTF(TLB, "Invalidating all non global entries.\n");
150    EntryList::iterator entryIt;
151    for (entryIt = entryList.begin(); entryIt != entryList.end();) {
152        if (!(*entryIt)->global) {
153            freeList.push_back(*entryIt);
154            entryList.erase(entryIt++);
155        } else {
156            entryIt++;
157        }
158    }
159}
160
161void
162TLB::demapPage(Addr va, uint64_t asn)
163{
164    EntryList::iterator entry = lookupIt(va, false);
165    if (entry != entryList.end()) {
166        freeList.push_back(*entry);
167        entryList.erase(entry);
168    }
169}
170
171Fault
172TLB::translateInt(RequestPtr req, ThreadContext *tc)
173{
174    DPRINTF(TLB, "Addresses references internal memory.\n");
175    Addr vaddr = req->getVaddr();
176    Addr prefix = (vaddr >> 3) & IntAddrPrefixMask;
177    if (prefix == IntAddrPrefixCPUID) {
178        panic("CPUID memory space not yet implemented!\n");
179    } else if (prefix == IntAddrPrefixMSR) {
180        vaddr = (vaddr >> 3) & ~IntAddrPrefixMask;
181        req->setFlags(Request::MMAPPED_IPR);
182
183        MiscRegIndex regNum;
184        if (!msrAddrToIndex(regNum, vaddr))
185            return new GeneralProtection(0);
186
187        //The index is multiplied by the size of a MiscReg so that
188        //any memory dependence calculations will not see these as
189        //overlapping.
190        req->setPaddr((Addr)regNum * sizeof(MiscReg));
191        return NoFault;
192    } else if (prefix == IntAddrPrefixIO) {
193        // TODO If CPL > IOPL or in virtual mode, check the I/O permission
194        // bitmap in the TSS.
195
196        Addr IOPort = vaddr & ~IntAddrPrefixMask;
197        // Make sure the address fits in the expected 16 bit IO address
198        // space.
199        assert(!(IOPort & ~0xFFFF));
200        if (IOPort == 0xCF8 && req->getSize() == 4) {
201            req->setFlags(Request::MMAPPED_IPR);
202            req->setPaddr(MISCREG_PCI_CONFIG_ADDRESS * sizeof(MiscReg));
203        } else if ((IOPort & ~mask(2)) == 0xCFC) {
204            req->setFlags(Request::UNCACHEABLE);
205            Addr configAddress =
206                tc->readMiscRegNoEffect(MISCREG_PCI_CONFIG_ADDRESS);
207            if (bits(configAddress, 31, 31)) {
208                req->setPaddr(PhysAddrPrefixPciConfig |
209                        mbits(configAddress, 30, 2) |
210                        (IOPort & mask(2)));
211            } else {
212                req->setPaddr(PhysAddrPrefixIO | IOPort);
213            }
214        } else {
215            req->setFlags(Request::UNCACHEABLE);
216            req->setPaddr(PhysAddrPrefixIO | IOPort);
217        }
218        return NoFault;
219    } else {
220        panic("Access to unrecognized internal address space %#x.\n",
221                prefix);
222    }
223}
224
225Fault
226TLB::translate(RequestPtr req, ThreadContext *tc, Translation *translation,
227        Mode mode, bool &delayedResponse, bool timing)
228{
229    uint32_t flags = req->getFlags();
230    int seg = flags & SegmentFlagMask;
231    bool storeCheck = flags & (StoreCheck << FlagShift);
232
233    delayedResponse = false;
234
235    // If this is true, we're dealing with a request to a non-memory address
236    // space.
237    if (seg == SEGMENT_REG_MS) {
238        return translateInt(req, tc);
239    }
240
241    Addr vaddr = req->getVaddr();
242    DPRINTF(TLB, "Translating vaddr %#x.\n", vaddr);
243
244    HandyM5Reg m5Reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);
245
246    // If protected mode has been enabled...
247    if (m5Reg.prot) {
248        DPRINTF(TLB, "In protected mode.\n");
249        // If we're not in 64-bit mode, do protection/limit checks
250        if (m5Reg.mode != LongMode) {
251            DPRINTF(TLB, "Not in long mode. Checking segment protection.\n");
252            // Check for a NULL segment selector.
253            if (!(seg == SEGMENT_REG_TSG || seg == SYS_SEGMENT_REG_IDTR ||
254                        seg == SEGMENT_REG_HS || seg == SEGMENT_REG_LS)
255                    && !tc->readMiscRegNoEffect(MISCREG_SEG_SEL(seg)))
256                return new GeneralProtection(0);
257            bool expandDown = false;
258            SegAttr attr = tc->readMiscRegNoEffect(MISCREG_SEG_ATTR(seg));
259            if (seg >= SEGMENT_REG_ES && seg <= SEGMENT_REG_HS) {
260                if (!attr.writable && (mode == Write || storeCheck))
261                    return new GeneralProtection(0);
262                if (!attr.readable && mode == Read)
263                    return new GeneralProtection(0);
264                expandDown = attr.expandDown;
265
266            }
267            Addr base = tc->readMiscRegNoEffect(MISCREG_SEG_BASE(seg));
268            Addr limit = tc->readMiscRegNoEffect(MISCREG_SEG_LIMIT(seg));
269            // This assumes we're not in 64 bit mode. If we were, the default
270            // address size is 64 bits, overridable to 32.
271            int size = 32;
272            bool sizeOverride = (flags & (AddrSizeFlagBit << FlagShift));
273            SegAttr csAttr = tc->readMiscRegNoEffect(MISCREG_CS_ATTR);
274            if ((csAttr.defaultSize && sizeOverride) ||
275                    (!csAttr.defaultSize && !sizeOverride))
276                size = 16;
277            Addr offset = bits(vaddr - base, size-1, 0);
278            Addr endOffset = offset + req->getSize() - 1;
279            if (expandDown) {
280                DPRINTF(TLB, "Checking an expand down segment.\n");
281                warn_once("Expand down segments are untested.\n");
282                if (offset <= limit || endOffset <= limit)
283                    return new GeneralProtection(0);
284            } else {
285                if (offset > limit || endOffset > limit)
286                    return new GeneralProtection(0);
287            }
288        }
289        // If paging is enabled, do the translation.
290        if (m5Reg.paging) {
291            DPRINTF(TLB, "Paging enabled.\n");
292            // The vaddr already has the segment base applied.
293            TlbEntry *entry = lookup(vaddr);
294            if (!entry) {
295                if (FullSystem) {
296                    Fault fault = walker->start(tc, translation, req, mode);
297                    if (timing || fault != NoFault) {
298                        // This gets ignored in atomic mode.
299                        delayedResponse = true;
300                        return fault;
301                    }
302                    entry = lookup(vaddr);
303                    assert(entry);
304                } else {
305#if !FULL_SYSTEM
306                    DPRINTF(TLB, "Handling a TLB miss for "
307                            "address %#x at pc %#x.\n",
308                            vaddr, tc->instAddr());
309
310                    Process *p = tc->getProcessPtr();
311                    TlbEntry newEntry;
312                    bool success = p->pTable->lookup(vaddr, newEntry);
313                    if (!success && mode != Execute) {
314                        // Check if we just need to grow the stack.
315                        if (p->fixupStackFault(vaddr)) {
316                            // If we did, lookup the entry for the new page.
317                            success = p->pTable->lookup(vaddr, newEntry);
318                        }
319                    }
320                    if (!success) {
321                        return new PageFault(vaddr, true, mode, true, false);
322                    } else {
323                        Addr alignedVaddr = p->pTable->pageAlign(vaddr);
324                        DPRINTF(TLB, "Mapping %#x to %#x\n", alignedVaddr,
325                                newEntry.pageStart());
326                        entry = insert(alignedVaddr, newEntry);
327                    }
328                    DPRINTF(TLB, "Miss was serviced.\n");
329#endif
330                }
331            }
332            // Do paging protection checks.
333            bool inUser = (m5Reg.cpl == 3 &&
334                    !(flags & (CPL0FlagBit << FlagShift)));
335            CR0 cr0 = tc->readMiscRegNoEffect(MISCREG_CR0);
336            bool badWrite = (!entry->writable && (inUser || cr0.wp));
337            if ((inUser && !entry->user) || (mode == Write && badWrite)) {
338                // The page must have been present to get into the TLB in
339                // the first place. We'll assume the reserved bits are
340                // fine even though we're not checking them.
341                return new PageFault(vaddr, true, mode, inUser, false);
342            }
343            if (storeCheck && badWrite) {
344                // This would fault if this were a write, so return a page
345                // fault that reflects that happening.
346                return new PageFault(vaddr, true, Write, inUser, false);
347            }
348
349
350            DPRINTF(TLB, "Entry found with paddr %#x, "
351                    "doing protection checks.\n", entry->paddr);
352            Addr paddr = entry->paddr | (vaddr & (entry->size-1));
353            DPRINTF(TLB, "Translated %#x -> %#x.\n", vaddr, paddr);
354            req->setPaddr(paddr);
355            if (entry->uncacheable)
356                req->setFlags(Request::UNCACHEABLE);
357        } else {
358            //Use the address which already has segmentation applied.
359            DPRINTF(TLB, "Paging disabled.\n");
360            DPRINTF(TLB, "Translated %#x -> %#x.\n", vaddr, vaddr);
361            req->setPaddr(vaddr);
362        }
363    } else {
364        // Real mode
365        DPRINTF(TLB, "In real mode.\n");
366        DPRINTF(TLB, "Translated %#x -> %#x.\n", vaddr, vaddr);
367        req->setPaddr(vaddr);
368    }
369    // Check for an access to the local APIC
370#if FULL_SYSTEM
371    LocalApicBase localApicBase = tc->readMiscRegNoEffect(MISCREG_APIC_BASE);
372    Addr baseAddr = localApicBase.base * PageBytes;
373    Addr paddr = req->getPaddr();
374    if (baseAddr <= paddr && baseAddr + PageBytes > paddr) {
375        // The Intel developer's manuals say the below restrictions apply,
376        // but the linux kernel, because of a compiler optimization, breaks
377        // them.
378        /*
379        // Check alignment
380        if (paddr & ((32/8) - 1))
381            return new GeneralProtection(0);
382        // Check access size
383        if (req->getSize() != (32/8))
384            return new GeneralProtection(0);
385        */
386        // Force the access to be uncacheable.
387        req->setFlags(Request::UNCACHEABLE);
388        req->setPaddr(x86LocalAPICAddress(tc->contextId(), paddr - baseAddr));
389    }
390#endif
391    return NoFault;
392};
393
394Fault
395TLB::translateAtomic(RequestPtr req, ThreadContext *tc, Mode mode)
396{
397    bool delayedResponse;
398    return TLB::translate(req, tc, NULL, mode, delayedResponse, false);
399}
400
401void
402TLB::translateTiming(RequestPtr req, ThreadContext *tc,
403        Translation *translation, Mode mode)
404{
405    bool delayedResponse;
406    assert(translation);
407    Fault fault =
408        TLB::translate(req, tc, translation, mode, delayedResponse, true);
409    if (!delayedResponse)
410        translation->finish(fault, req, tc, mode);
411}
412
413#if FULL_SYSTEM
414
415Tick
416TLB::doMmuRegRead(ThreadContext *tc, Packet *pkt)
417{
418    return tc->getCpuPtr()->ticks(1);
419}
420
421Tick
422TLB::doMmuRegWrite(ThreadContext *tc, Packet *pkt)
423{
424    return tc->getCpuPtr()->ticks(1);
425}
426
427Walker *
428TLB::getWalker()
429{
430    return walker;
431}
432
433#endif
434
435void
436TLB::serialize(std::ostream &os)
437{
438}
439
440void
441TLB::unserialize(Checkpoint *cp, const std::string &section)
442{
443}
444
445} // namespace X86ISA
446
447X86ISA::TLB *
448X86TLBParams::create()
449{
450    return new X86ISA::TLB(this);
451}
452