physical.cc revision 7730:982b4c6c1470
1/*
2 * Copyright (c) 2001-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Ron Dreslinski
29 *          Ali Saidi
30 */
31
32#include <sys/types.h>
33#include <sys/mman.h>
34#include <sys/user.h>
35#include <errno.h>
36#include <fcntl.h>
37#include <unistd.h>
38#include <zlib.h>
39
40#include <cstdio>
41#include <iostream>
42#include <string>
43
44#include "arch/registers.hh"
45#include "base/intmath.hh"
46#include "base/misc.hh"
47#include "base/random.hh"
48#include "base/types.hh"
49#include "config/full_system.hh"
50#include "config/the_isa.hh"
51#include "mem/packet_access.hh"
52#include "mem/physical.hh"
53#include "sim/eventq.hh"
54
55using namespace std;
56using namespace TheISA;
57
58PhysicalMemory::PhysicalMemory(const Params *p)
59    : MemObject(p), pmemAddr(NULL), pagePtr(0),
60      lat(p->latency), lat_var(p->latency_var),
61      _size(params()->range.size()), _start(params()->range.start)
62{
63    if (size() % TheISA::PageBytes != 0)
64        panic("Memory Size not divisible by page size\n");
65
66    if (params()->null)
67        return;
68
69
70    if (params()->file == "") {
71        int map_flags = MAP_ANON | MAP_PRIVATE;
72        pmemAddr = (uint8_t *)mmap(NULL, size(),
73                                   PROT_READ | PROT_WRITE, map_flags, -1, 0);
74    } else {
75        int map_flags = MAP_PRIVATE;
76        int fd = open(params()->file.c_str(), O_RDONLY);
77        _size = lseek(fd, 0, SEEK_END);
78        lseek(fd, 0, SEEK_SET);
79        pmemAddr = (uint8_t *)mmap(NULL, roundUp(size(), PAGE_SIZE),
80                                   PROT_READ | PROT_WRITE, map_flags, fd, 0);
81    }
82
83    if (pmemAddr == (void *)MAP_FAILED) {
84        perror("mmap");
85        if (params()->file == "")
86            fatal("Could not mmap!\n");
87        else
88            fatal("Could not find file: %s\n", params()->file);
89    }
90
91    //If requested, initialize all the memory to 0
92    if (p->zero)
93        memset(pmemAddr, 0, size());
94}
95
96void
97PhysicalMemory::init()
98{
99    if (ports.size() == 0) {
100        fatal("PhysicalMemory object %s is unconnected!", name());
101    }
102
103    for (PortIterator pi = ports.begin(); pi != ports.end(); ++pi) {
104        if (*pi)
105            (*pi)->sendStatusChange(Port::RangeChange);
106    }
107}
108
109PhysicalMemory::~PhysicalMemory()
110{
111    if (pmemAddr)
112        munmap((char*)pmemAddr, size());
113}
114
115Addr
116PhysicalMemory::new_page()
117{
118    Addr return_addr = pagePtr << LogVMPageSize;
119    return_addr += start();
120
121    ++pagePtr;
122    return return_addr;
123}
124
125unsigned
126PhysicalMemory::deviceBlockSize() const
127{
128    //Can accept anysize request
129    return 0;
130}
131
132Tick
133PhysicalMemory::calculateLatency(PacketPtr pkt)
134{
135    Tick latency = lat;
136    if (lat_var != 0)
137        latency += random_mt.random<Tick>(0, lat_var);
138    return latency;
139}
140
141
142
143// Add load-locked to tracking list.  Should only be called if the
144// operation is a load and the LLSC flag is set.
145void
146PhysicalMemory::trackLoadLocked(PacketPtr pkt)
147{
148    Request *req = pkt->req;
149    Addr paddr = LockedAddr::mask(req->getPaddr());
150
151    // first we check if we already have a locked addr for this
152    // xc.  Since each xc only gets one, we just update the
153    // existing record with the new address.
154    list<LockedAddr>::iterator i;
155
156    for (i = lockedAddrList.begin(); i != lockedAddrList.end(); ++i) {
157        if (i->matchesContext(req)) {
158            DPRINTF(LLSC, "Modifying lock record: context %d addr %#x\n",
159                    req->contextId(), paddr);
160            i->addr = paddr;
161            return;
162        }
163    }
164
165    // no record for this xc: need to allocate a new one
166    DPRINTF(LLSC, "Adding lock record: context %d addr %#x\n",
167            req->contextId(), paddr);
168    lockedAddrList.push_front(LockedAddr(req));
169}
170
171
172// Called on *writes* only... both regular stores and
173// store-conditional operations.  Check for conventional stores which
174// conflict with locked addresses, and for success/failure of store
175// conditionals.
176bool
177PhysicalMemory::checkLockedAddrList(PacketPtr pkt)
178{
179    Request *req = pkt->req;
180    Addr paddr = LockedAddr::mask(req->getPaddr());
181    bool isLLSC = pkt->isLLSC();
182
183    // Initialize return value.  Non-conditional stores always
184    // succeed.  Assume conditional stores will fail until proven
185    // otherwise.
186    bool success = !isLLSC;
187
188    // Iterate over list.  Note that there could be multiple matching
189    // records, as more than one context could have done a load locked
190    // to this location.
191    list<LockedAddr>::iterator i = lockedAddrList.begin();
192
193    while (i != lockedAddrList.end()) {
194
195        if (i->addr == paddr) {
196            // we have a matching address
197
198            if (isLLSC && i->matchesContext(req)) {
199                // it's a store conditional, and as far as the memory
200                // system can tell, the requesting context's lock is
201                // still valid.
202                DPRINTF(LLSC, "StCond success: context %d addr %#x\n",
203                        req->contextId(), paddr);
204                success = true;
205            }
206
207            // Get rid of our record of this lock and advance to next
208            DPRINTF(LLSC, "Erasing lock record: context %d addr %#x\n",
209                    i->contextId, paddr);
210            i = lockedAddrList.erase(i);
211        }
212        else {
213            // no match: advance to next record
214            ++i;
215        }
216    }
217
218    if (isLLSC) {
219        req->setExtraData(success ? 1 : 0);
220    }
221
222    return success;
223}
224
225
226#if TRACING_ON
227
228#define CASE(A, T)                                                      \
229  case sizeof(T):                                                       \
230    DPRINTF(MemoryAccess,"%s of size %i on address 0x%x data 0x%x\n",   \
231            A, pkt->getSize(), pkt->getAddr(), pkt->get<T>());          \
232  break
233
234
235#define TRACE_PACKET(A)                                                 \
236    do {                                                                \
237        switch (pkt->getSize()) {                                       \
238          CASE(A, uint64_t);                                            \
239          CASE(A, uint32_t);                                            \
240          CASE(A, uint16_t);                                            \
241          CASE(A, uint8_t);                                             \
242          default:                                                      \
243            DPRINTF(MemoryAccess, "%s of size %i on address 0x%x\n",    \
244                    A, pkt->getSize(), pkt->getAddr());                 \
245        }                                                               \
246    } while (0)
247
248#else
249
250#define TRACE_PACKET(A)
251
252#endif
253
254Tick
255PhysicalMemory::doAtomicAccess(PacketPtr pkt)
256{
257    assert(pkt->getAddr() >= start() &&
258           pkt->getAddr() + pkt->getSize() <= start() + size());
259
260    if (pkt->memInhibitAsserted()) {
261        DPRINTF(MemoryAccess, "mem inhibited on 0x%x: not responding\n",
262                pkt->getAddr());
263        return 0;
264    }
265
266    uint8_t *hostAddr = pmemAddr + pkt->getAddr() - start();
267
268    if (pkt->cmd == MemCmd::SwapReq) {
269        IntReg overwrite_val;
270        bool overwrite_mem;
271        uint64_t condition_val64;
272        uint32_t condition_val32;
273
274        if (!pmemAddr)
275            panic("Swap only works if there is real memory (i.e. null=False)");
276        assert(sizeof(IntReg) >= pkt->getSize());
277
278        overwrite_mem = true;
279        // keep a copy of our possible write value, and copy what is at the
280        // memory address into the packet
281        std::memcpy(&overwrite_val, pkt->getPtr<uint8_t>(), pkt->getSize());
282        std::memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
283
284        if (pkt->req->isCondSwap()) {
285            if (pkt->getSize() == sizeof(uint64_t)) {
286                condition_val64 = pkt->req->getExtraData();
287                overwrite_mem = !std::memcmp(&condition_val64, hostAddr,
288                                             sizeof(uint64_t));
289            } else if (pkt->getSize() == sizeof(uint32_t)) {
290                condition_val32 = (uint32_t)pkt->req->getExtraData();
291                overwrite_mem = !std::memcmp(&condition_val32, hostAddr,
292                                             sizeof(uint32_t));
293            } else
294                panic("Invalid size for conditional read/write\n");
295        }
296
297        if (overwrite_mem)
298            std::memcpy(hostAddr, &overwrite_val, pkt->getSize());
299
300        assert(!pkt->req->isInstFetch());
301        TRACE_PACKET("Read/Write");
302    } else if (pkt->isRead()) {
303        assert(!pkt->isWrite());
304        if (pkt->isLLSC()) {
305            trackLoadLocked(pkt);
306        }
307        if (pmemAddr)
308            memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
309        TRACE_PACKET(pkt->req->isInstFetch() ? "IFetch" : "Read");
310    } else if (pkt->isWrite()) {
311        if (writeOK(pkt)) {
312            if (pmemAddr)
313                memcpy(hostAddr, pkt->getPtr<uint8_t>(), pkt->getSize());
314            assert(!pkt->req->isInstFetch());
315            TRACE_PACKET("Write");
316        }
317    } else if (pkt->isInvalidate()) {
318        //upgrade or invalidate
319        if (pkt->needsResponse()) {
320            pkt->makeAtomicResponse();
321        }
322    } else {
323        panic("unimplemented");
324    }
325
326    if (pkt->needsResponse()) {
327        pkt->makeAtomicResponse();
328    }
329    return calculateLatency(pkt);
330}
331
332
333void
334PhysicalMemory::doFunctionalAccess(PacketPtr pkt)
335{
336    assert(pkt->getAddr() >= start() &&
337           pkt->getAddr() + pkt->getSize() <= start() + size());
338
339
340    uint8_t *hostAddr = pmemAddr + pkt->getAddr() - start();
341
342    if (pkt->isRead()) {
343        if (pmemAddr)
344            memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
345        TRACE_PACKET("Read");
346        pkt->makeAtomicResponse();
347    } else if (pkt->isWrite()) {
348        if (pmemAddr)
349            memcpy(hostAddr, pkt->getPtr<uint8_t>(), pkt->getSize());
350        TRACE_PACKET("Write");
351        pkt->makeAtomicResponse();
352    } else if (pkt->isPrint()) {
353        Packet::PrintReqState *prs =
354            dynamic_cast<Packet::PrintReqState*>(pkt->senderState);
355        // Need to call printLabels() explicitly since we're not going
356        // through printObj().
357        prs->printLabels();
358        // Right now we just print the single byte at the specified address.
359        ccprintf(prs->os, "%s%#x\n", prs->curPrefix(), *hostAddr);
360    } else {
361        panic("PhysicalMemory: unimplemented functional command %s",
362              pkt->cmdString());
363    }
364}
365
366
367Port *
368PhysicalMemory::getPort(const std::string &if_name, int idx)
369{
370    // Accept request for "functional" port for backwards compatibility
371    // with places where this function is called from C++.  I'd prefer
372    // to move all these into Python someday.
373    if (if_name == "functional") {
374        return new MemoryPort(csprintf("%s-functional", name()), this);
375    }
376
377    if (if_name != "port") {
378        panic("PhysicalMemory::getPort: unknown port %s requested", if_name);
379    }
380
381    if (idx >= (int)ports.size()) {
382        ports.resize(idx + 1);
383    }
384
385    if (ports[idx] != NULL) {
386        panic("PhysicalMemory::getPort: port %d already assigned", idx);
387    }
388
389    MemoryPort *port =
390        new MemoryPort(csprintf("%s-port%d", name(), idx), this);
391
392    ports[idx] = port;
393    return port;
394}
395
396
397void
398PhysicalMemory::recvStatusChange(Port::Status status)
399{
400}
401
402PhysicalMemory::MemoryPort::MemoryPort(const std::string &_name,
403                                       PhysicalMemory *_memory)
404    : SimpleTimingPort(_name, _memory), memory(_memory)
405{ }
406
407void
408PhysicalMemory::MemoryPort::recvStatusChange(Port::Status status)
409{
410    memory->recvStatusChange(status);
411}
412
413void
414PhysicalMemory::MemoryPort::getDeviceAddressRanges(AddrRangeList &resp,
415                                                   bool &snoop)
416{
417    memory->getAddressRanges(resp, snoop);
418}
419
420void
421PhysicalMemory::getAddressRanges(AddrRangeList &resp, bool &snoop)
422{
423    snoop = false;
424    resp.clear();
425    resp.push_back(RangeSize(start(), size()));
426}
427
428unsigned
429PhysicalMemory::MemoryPort::deviceBlockSize() const
430{
431    return memory->deviceBlockSize();
432}
433
434Tick
435PhysicalMemory::MemoryPort::recvAtomic(PacketPtr pkt)
436{
437    return memory->doAtomicAccess(pkt);
438}
439
440void
441PhysicalMemory::MemoryPort::recvFunctional(PacketPtr pkt)
442{
443    pkt->pushLabel(memory->name());
444
445    if (!checkFunctional(pkt)) {
446        // Default implementation of SimpleTimingPort::recvFunctional()
447        // calls recvAtomic() and throws away the latency; we can save a
448        // little here by just not calculating the latency.
449        memory->doFunctionalAccess(pkt);
450    }
451
452    pkt->popLabel();
453}
454
455unsigned int
456PhysicalMemory::drain(Event *de)
457{
458    int count = 0;
459    for (PortIterator pi = ports.begin(); pi != ports.end(); ++pi) {
460        count += (*pi)->drain(de);
461    }
462
463    if (count)
464        changeState(Draining);
465    else
466        changeState(Drained);
467    return count;
468}
469
470void
471PhysicalMemory::serialize(ostream &os)
472{
473    if (!pmemAddr)
474        return;
475
476    gzFile compressedMem;
477    string filename = name() + ".physmem";
478
479    SERIALIZE_SCALAR(filename);
480    SERIALIZE_SCALAR(_size);
481
482    // write memory file
483    string thefile = Checkpoint::dir() + "/" + filename.c_str();
484    int fd = creat(thefile.c_str(), 0664);
485    if (fd < 0) {
486        perror("creat");
487        fatal("Can't open physical memory checkpoint file '%s'\n", filename);
488    }
489
490    compressedMem = gzdopen(fd, "wb");
491    if (compressedMem == NULL)
492        fatal("Insufficient memory to allocate compression state for %s\n",
493                filename);
494
495    if (gzwrite(compressedMem, pmemAddr, size()) != (int)size()) {
496        fatal("Write failed on physical memory checkpoint file '%s'\n",
497              filename);
498    }
499
500    if (gzclose(compressedMem))
501        fatal("Close failed on physical memory checkpoint file '%s'\n",
502              filename);
503}
504
505void
506PhysicalMemory::unserialize(Checkpoint *cp, const string &section)
507{
508    if (!pmemAddr)
509        return;
510
511    gzFile compressedMem;
512    long *tempPage;
513    long *pmem_current;
514    uint64_t curSize;
515    uint32_t bytesRead;
516    const uint32_t chunkSize = 16384;
517
518    string filename;
519
520    UNSERIALIZE_SCALAR(filename);
521
522    filename = cp->cptDir + "/" + filename;
523
524    // mmap memoryfile
525    int fd = open(filename.c_str(), O_RDONLY);
526    if (fd < 0) {
527        perror("open");
528        fatal("Can't open physical memory checkpoint file '%s'", filename);
529    }
530
531    compressedMem = gzdopen(fd, "rb");
532    if (compressedMem == NULL)
533        fatal("Insufficient memory to allocate compression state for %s\n",
534                filename);
535
536    // unmap file that was mmaped in the constructor
537    // This is done here to make sure that gzip and open don't muck with our
538    // nice large space of memory before we reallocate it
539    munmap((char*)pmemAddr, size());
540
541    UNSERIALIZE_SCALAR(_size);
542    if (size() > params()->range.size())
543        fatal("Memory size has changed!\n");
544
545    pmemAddr = (uint8_t *)mmap(NULL, size(),
546        PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
547
548    if (pmemAddr == (void *)MAP_FAILED) {
549        perror("mmap");
550        fatal("Could not mmap physical memory!\n");
551    }
552
553    curSize = 0;
554    tempPage = (long*)malloc(chunkSize);
555    if (tempPage == NULL)
556        fatal("Unable to malloc memory to read file %s\n", filename);
557
558    /* Only copy bytes that are non-zero, so we don't give the VM system hell */
559    while (curSize < size()) {
560        bytesRead = gzread(compressedMem, tempPage, chunkSize);
561        if (bytesRead == 0)
562            break;
563
564        assert(bytesRead % sizeof(long) == 0);
565
566        for (uint32_t x = 0; x < bytesRead / sizeof(long); x++)
567        {
568             if (*(tempPage+x) != 0) {
569                 pmem_current = (long*)(pmemAddr + curSize + x * sizeof(long));
570                 *pmem_current = *(tempPage+x);
571             }
572        }
573        curSize += bytesRead;
574    }
575
576    free(tempPage);
577
578    if (gzclose(compressedMem))
579        fatal("Close failed on physical memory checkpoint file '%s'\n",
580              filename);
581
582}
583
584PhysicalMemory *
585PhysicalMemoryParams::create()
586{
587    return new PhysicalMemory(this);
588}
589