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