physical.cc revision 3224
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 <errno.h>
35#include <fcntl.h>
36#include <unistd.h>
37#include <zlib.h>
38
39#include <iostream>
40#include <string>
41
42
43#include "base/misc.hh"
44#include "config/full_system.hh"
45#include "mem/packet_impl.hh"
46#include "mem/physical.hh"
47#include "sim/host.hh"
48#include "sim/builder.hh"
49#include "sim/eventq.hh"
50#include "arch/isa_traits.hh"
51
52
53using namespace std;
54using namespace TheISA;
55
56
57PhysicalMemory::PhysicalMemory(Params *p)
58    : MemObject(p->name), pmemAddr(NULL), port(NULL), lat(p->latency), _params(p)
59{
60    if (params()->addrRange.size() % TheISA::PageBytes != 0)
61        panic("Memory Size not divisible by page size\n");
62
63    int map_flags = MAP_ANON | MAP_PRIVATE;
64    pmemAddr = (uint8_t *)mmap(NULL, params()->addrRange.size(), PROT_READ | PROT_WRITE,
65                                map_flags, -1, 0);
66
67    if (pmemAddr == (void *)MAP_FAILED) {
68        perror("mmap");
69        fatal("Could not mmap!\n");
70    }
71
72    pagePtr = 0;
73}
74
75void
76PhysicalMemory::init()
77{
78    if (!port)
79        panic("PhysicalMemory not connected to anything!");
80    port->sendStatusChange(Port::RangeChange);
81}
82
83PhysicalMemory::~PhysicalMemory()
84{
85    if (pmemAddr)
86        munmap(pmemAddr, params()->addrRange.size());
87    //Remove memPorts?
88}
89
90Addr
91PhysicalMemory::new_page()
92{
93    Addr return_addr = pagePtr << LogVMPageSize;
94    return_addr += params()->addrRange.start;
95
96    ++pagePtr;
97    return return_addr;
98}
99
100int
101PhysicalMemory::deviceBlockSize()
102{
103    //Can accept anysize request
104    return 0;
105}
106
107Tick
108PhysicalMemory::calculateLatency(Packet *pkt)
109{
110    return lat;
111}
112
113void
114PhysicalMemory::doFunctionalAccess(Packet *pkt)
115{
116    assert(pkt->getAddr() + pkt->getSize() <= params()->addrRange.size());
117
118    switch (pkt->cmd) {
119      case Packet::ReadReq:
120        memcpy(pkt->getPtr<uint8_t>(),
121               pmemAddr + pkt->getAddr() - params()->addrRange.start,
122               pkt->getSize());
123        break;
124      case Packet::WriteReq:
125        memcpy(pmemAddr + pkt->getAddr() - params()->addrRange.start,
126               pkt->getPtr<uint8_t>(),
127               pkt->getSize());
128        // temporary hack: will need to add real LL/SC implementation
129        // for cacheless systems later.
130        if (pkt->req->getFlags() & LOCKED) {
131            pkt->req->setScResult(1);
132        }
133        break;
134      default:
135        panic("unimplemented");
136    }
137
138    pkt->result = Packet::Success;
139}
140
141Port *
142PhysicalMemory::getPort(const std::string &if_name, int idx)
143{
144    if (if_name == "port" && idx == -1) {
145        if (port != NULL)
146           panic("PhysicalMemory::getPort: additional port requested to memory!");
147        port = new MemoryPort(name() + "-port", this);
148        return port;
149    } else if (if_name == "functional") {
150        /* special port for functional writes at startup. */
151        return new MemoryPort(name() + "-funcport", this);
152    } else {
153        panic("PhysicalMemory::getPort: unknown port %s requested", if_name);
154    }
155}
156
157void
158PhysicalMemory::recvStatusChange(Port::Status status)
159{
160}
161
162PhysicalMemory::MemoryPort::MemoryPort(const std::string &_name,
163                                       PhysicalMemory *_memory)
164    : SimpleTimingPort(_name), memory(_memory)
165{ }
166
167void
168PhysicalMemory::MemoryPort::recvStatusChange(Port::Status status)
169{
170    memory->recvStatusChange(status);
171}
172
173void
174PhysicalMemory::MemoryPort::getDeviceAddressRanges(AddrRangeList &resp,
175                                            AddrRangeList &snoop)
176{
177    memory->getAddressRanges(resp, snoop);
178}
179
180void
181PhysicalMemory::getAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)
182{
183    snoop.clear();
184    resp.clear();
185    resp.push_back(RangeSize(params()->addrRange.start,
186                             params()->addrRange.size()));
187}
188
189int
190PhysicalMemory::MemoryPort::deviceBlockSize()
191{
192    return memory->deviceBlockSize();
193}
194
195Tick
196PhysicalMemory::MemoryPort::recvAtomic(Packet *pkt)
197{
198    memory->doFunctionalAccess(pkt);
199    return memory->calculateLatency(pkt);
200}
201
202void
203PhysicalMemory::MemoryPort::recvFunctional(Packet *pkt)
204{
205    // Default implementation of SimpleTimingPort::recvFunctional()
206    // calls recvAtomic() and throws away the latency; we can save a
207    // little here by just not calculating the latency.
208    memory->doFunctionalAccess(pkt);
209}
210
211unsigned int
212PhysicalMemory::drain(Event *de)
213{
214    int count = port->drain(de);
215    if (count)
216        changeState(Draining);
217    else
218        changeState(Drained);
219    return count;
220}
221
222void
223PhysicalMemory::serialize(ostream &os)
224{
225    gzFile compressedMem;
226    string filename = name() + ".physmem";
227
228    SERIALIZE_SCALAR(filename);
229
230    // write memory file
231    string thefile = Checkpoint::dir() + "/" + filename.c_str();
232    int fd = creat(thefile.c_str(), 0664);
233    if (fd < 0) {
234        perror("creat");
235        fatal("Can't open physical memory checkpoint file '%s'\n", filename);
236    }
237
238    compressedMem = gzdopen(fd, "wb");
239    if (compressedMem == NULL)
240        fatal("Insufficient memory to allocate compression state for %s\n",
241                filename);
242
243    if (gzwrite(compressedMem, pmemAddr, params()->addrRange.size()) != params()->addrRange.size()) {
244        fatal("Write failed on physical memory checkpoint file '%s'\n",
245              filename);
246    }
247
248    if (gzclose(compressedMem))
249        fatal("Close failed on physical memory checkpoint file '%s'\n",
250              filename);
251}
252
253void
254PhysicalMemory::unserialize(Checkpoint *cp, const string &section)
255{
256    gzFile compressedMem;
257    long *tempPage;
258    long *pmem_current;
259    uint64_t curSize;
260    uint32_t bytesRead;
261    const int chunkSize = 16384;
262
263
264    string filename;
265
266    UNSERIALIZE_SCALAR(filename);
267
268    filename = cp->cptDir + "/" + filename;
269
270    // mmap memoryfile
271    int fd = open(filename.c_str(), O_RDONLY);
272    if (fd < 0) {
273        perror("open");
274        fatal("Can't open physical memory checkpoint file '%s'", filename);
275    }
276
277    compressedMem = gzdopen(fd, "rb");
278    if (compressedMem == NULL)
279        fatal("Insufficient memory to allocate compression state for %s\n",
280                filename);
281
282    // unmap file that was mmaped in the constructor
283    // This is done here to make sure that gzip and open don't muck with our
284    // nice large space of memory before we reallocate it
285    munmap(pmemAddr, params()->addrRange.size());
286
287    pmemAddr = (uint8_t *)mmap(NULL, params()->addrRange.size(), PROT_READ | PROT_WRITE,
288                                MAP_ANON | MAP_PRIVATE, -1, 0);
289
290    if (pmemAddr == (void *)MAP_FAILED) {
291        perror("mmap");
292        fatal("Could not mmap physical memory!\n");
293    }
294
295    curSize = 0;
296    tempPage = (long*)malloc(chunkSize);
297    if (tempPage == NULL)
298        fatal("Unable to malloc memory to read file %s\n", filename);
299
300    /* Only copy bytes that are non-zero, so we don't give the VM system hell */
301    while (curSize < params()->addrRange.size()) {
302        bytesRead = gzread(compressedMem, tempPage, chunkSize);
303        if (bytesRead != chunkSize && bytesRead != params()->addrRange.size() - curSize)
304            fatal("Read failed on physical memory checkpoint file '%s'"
305                  " got %d bytes, expected %d or %d bytes\n",
306                  filename, bytesRead, chunkSize, params()->addrRange.size()-curSize);
307
308        assert(bytesRead % sizeof(long) == 0);
309
310        for (int x = 0; x < bytesRead/sizeof(long); x++)
311        {
312             if (*(tempPage+x) != 0) {
313                 pmem_current = (long*)(pmemAddr + curSize + x * sizeof(long));
314                 *pmem_current = *(tempPage+x);
315             }
316        }
317        curSize += bytesRead;
318    }
319
320    free(tempPage);
321
322    if (gzclose(compressedMem))
323        fatal("Close failed on physical memory checkpoint file '%s'\n",
324              filename);
325
326}
327
328
329BEGIN_DECLARE_SIM_OBJECT_PARAMS(PhysicalMemory)
330
331    Param<string> file;
332    Param<Range<Addr> > range;
333    Param<Tick> latency;
334
335END_DECLARE_SIM_OBJECT_PARAMS(PhysicalMemory)
336
337BEGIN_INIT_SIM_OBJECT_PARAMS(PhysicalMemory)
338
339    INIT_PARAM_DFLT(file, "memory mapped file", ""),
340    INIT_PARAM(range, "Device Address Range"),
341    INIT_PARAM(latency, "Memory access latency")
342
343END_INIT_SIM_OBJECT_PARAMS(PhysicalMemory)
344
345CREATE_SIM_OBJECT(PhysicalMemory)
346{
347    PhysicalMemory::Params *p = new PhysicalMemory::Params;
348    p->name = getInstanceName();
349    p->addrRange = range;
350    p->latency = latency;
351    return new PhysicalMemory(p);
352}
353
354REGISTER_SIM_OBJECT("PhysicalMemory", PhysicalMemory)
355