Change MemoryAccess dprintfs to print the data as well
[gem5.git] / src / mem / physical.cc
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 #include "arch/isa_traits.hh"
43 #include "base/misc.hh"
44 #include "config/full_system.hh"
45 #include "mem/packet_access.hh"
46 #include "mem/physical.hh"
47 #include "sim/builder.hh"
48 #include "sim/eventq.hh"
49 #include "sim/host.hh"
50
51 using namespace std;
52 using namespace TheISA;
53
54 PhysicalMemory::PhysicalMemory(Params *p)
55 : MemObject(p->name), pmemAddr(NULL), port(NULL), lat(p->latency), _params(p)
56 {
57 if (params()->addrRange.size() % TheISA::PageBytes != 0)
58 panic("Memory Size not divisible by page size\n");
59
60 int map_flags = MAP_ANON | MAP_PRIVATE;
61 pmemAddr = (uint8_t *)mmap(NULL, params()->addrRange.size(), PROT_READ | PROT_WRITE,
62 map_flags, -1, 0);
63
64 if (pmemAddr == (void *)MAP_FAILED) {
65 perror("mmap");
66 fatal("Could not mmap!\n");
67 }
68
69 //If requested, initialize all the memory to 0
70 if(params()->zero)
71 memset(pmemAddr, 0, params()->addrRange.size());
72
73 pagePtr = 0;
74 }
75
76 void
77 PhysicalMemory::init()
78 {
79 if (!port)
80 panic("PhysicalMemory not connected to anything!");
81 port->sendStatusChange(Port::RangeChange);
82 }
83
84 PhysicalMemory::~PhysicalMemory()
85 {
86 if (pmemAddr)
87 munmap(pmemAddr, params()->addrRange.size());
88 //Remove memPorts?
89 }
90
91 Addr
92 PhysicalMemory::new_page()
93 {
94 Addr return_addr = pagePtr << LogVMPageSize;
95 return_addr += params()->addrRange.start;
96
97 ++pagePtr;
98 return return_addr;
99 }
100
101 int
102 PhysicalMemory::deviceBlockSize()
103 {
104 //Can accept anysize request
105 return 0;
106 }
107
108 Tick
109 PhysicalMemory::calculateLatency(PacketPtr pkt)
110 {
111 return lat;
112 }
113
114
115
116 // Add load-locked to tracking list. Should only be called if the
117 // operation is a load and the LOCKED flag is set.
118 void
119 PhysicalMemory::trackLoadLocked(Request *req)
120 {
121 Addr paddr = LockedAddr::mask(req->getPaddr());
122
123 // first we check if we already have a locked addr for this
124 // xc. Since each xc only gets one, we just update the
125 // existing record with the new address.
126 list<LockedAddr>::iterator i;
127
128 for (i = lockedAddrList.begin(); i != lockedAddrList.end(); ++i) {
129 if (i->matchesContext(req)) {
130 DPRINTF(LLSC, "Modifying lock record: cpu %d thread %d addr %#x\n",
131 req->getCpuNum(), req->getThreadNum(), paddr);
132 i->addr = paddr;
133 return;
134 }
135 }
136
137 // no record for this xc: need to allocate a new one
138 DPRINTF(LLSC, "Adding lock record: cpu %d thread %d addr %#x\n",
139 req->getCpuNum(), req->getThreadNum(), paddr);
140 lockedAddrList.push_front(LockedAddr(req));
141 }
142
143
144 // Called on *writes* only... both regular stores and
145 // store-conditional operations. Check for conventional stores which
146 // conflict with locked addresses, and for success/failure of store
147 // conditionals.
148 bool
149 PhysicalMemory::checkLockedAddrList(Request *req)
150 {
151 Addr paddr = LockedAddr::mask(req->getPaddr());
152 bool isLocked = req->isLocked();
153
154 // Initialize return value. Non-conditional stores always
155 // succeed. Assume conditional stores will fail until proven
156 // otherwise.
157 bool success = !isLocked;
158
159 // Iterate over list. Note that there could be multiple matching
160 // records, as more than one context could have done a load locked
161 // to this location.
162 list<LockedAddr>::iterator i = lockedAddrList.begin();
163
164 while (i != lockedAddrList.end()) {
165
166 if (i->addr == paddr) {
167 // we have a matching address
168
169 if (isLocked && i->matchesContext(req)) {
170 // it's a store conditional, and as far as the memory
171 // system can tell, the requesting context's lock is
172 // still valid.
173 DPRINTF(LLSC, "StCond success: cpu %d thread %d addr %#x\n",
174 req->getCpuNum(), req->getThreadNum(), paddr);
175 success = true;
176 }
177
178 // Get rid of our record of this lock and advance to next
179 DPRINTF(LLSC, "Erasing lock record: cpu %d thread %d addr %#x\n",
180 i->cpuNum, i->threadNum, paddr);
181 i = lockedAddrList.erase(i);
182 }
183 else {
184 // no match: advance to next record
185 ++i;
186 }
187 }
188
189 if (isLocked) {
190 req->setScResult(success ? 1 : 0);
191 }
192
193 return success;
194 }
195
196 void
197 PhysicalMemory::doFunctionalAccess(PacketPtr pkt)
198 {
199 assert(pkt->getAddr() >= params()->addrRange.start &&
200 pkt->getAddr() + pkt->getSize() <= params()->addrRange.start +
201 params()->addrRange.size());
202
203 if (pkt->isRead()) {
204 if (pkt->req->isLocked()) {
205 trackLoadLocked(pkt->req);
206 }
207 memcpy(pkt->getPtr<uint8_t>(),
208 pmemAddr + pkt->getAddr() - params()->addrRange.start,
209 pkt->getSize());
210 #if TRACING_ON
211 switch (pkt->getSize()) {
212 case sizeof(uint64_t):
213 DPRINTF(MemoryAccess, "Read of size %i on address 0x%x data 0x%x\n",
214 pkt->getSize(), pkt->getAddr(),pkt->get<uint64_t>());
215 break;
216 case sizeof(uint32_t):
217 DPRINTF(MemoryAccess, "Read of size %i on address 0x%x data 0x%x\n",
218 pkt->getSize(), pkt->getAddr(),pkt->get<uint32_t>());
219 break;
220 case sizeof(uint16_t):
221 DPRINTF(MemoryAccess, "Read of size %i on address 0x%x data 0x%x\n",
222 pkt->getSize(), pkt->getAddr(),pkt->get<uint16_t>());
223 break;
224 case sizeof(uint8_t):
225 DPRINTF(MemoryAccess, "Read of size %i on address 0x%x data 0x%x\n",
226 pkt->getSize(), pkt->getAddr(),pkt->get<uint8_t>());
227 break;
228 default:
229 DPRINTF(MemoryAccess, "Read of size %i on address 0x%x\n",
230 pkt->getSize(), pkt->getAddr());
231 }
232 #endif
233 }
234 else if (pkt->isWrite()) {
235 if (writeOK(pkt->req)) {
236 memcpy(pmemAddr + pkt->getAddr() - params()->addrRange.start,
237 pkt->getPtr<uint8_t>(), pkt->getSize());
238 #if TRACING_ON
239 switch (pkt->getSize()) {
240 case sizeof(uint64_t):
241 DPRINTF(MemoryAccess, "Write of size %i on address 0x%x data 0x%x\n",
242 pkt->getSize(), pkt->getAddr(),pkt->get<uint64_t>());
243 break;
244 case sizeof(uint32_t):
245 DPRINTF(MemoryAccess, "Write of size %i on address 0x%x data 0x%x\n",
246 pkt->getSize(), pkt->getAddr(),pkt->get<uint32_t>());
247 break;
248 case sizeof(uint16_t):
249 DPRINTF(MemoryAccess, "Write of size %i on address 0x%x data 0x%x\n",
250 pkt->getSize(), pkt->getAddr(),pkt->get<uint16_t>());
251 break;
252 case sizeof(uint8_t):
253 DPRINTF(MemoryAccess, "Write of size %i on address 0x%x data 0x%x\n",
254 pkt->getSize(), pkt->getAddr(),pkt->get<uint8_t>());
255 break;
256 default:
257 DPRINTF(MemoryAccess, "Write of size %i on address 0x%x\n",
258 pkt->getSize(), pkt->getAddr());
259 }
260 #endif
261 }
262 }
263 else if (pkt->isInvalidate()) {
264 //upgrade or invalidate
265 pkt->flags |= SATISFIED;
266 }
267 else {
268 panic("unimplemented");
269 }
270
271 pkt->result = Packet::Success;
272 }
273
274 Port *
275 PhysicalMemory::getPort(const std::string &if_name, int idx)
276 {
277 if (if_name == "port" && idx == -1) {
278 if (port != NULL)
279 panic("PhysicalMemory::getPort: additional port requested to memory!");
280 port = new MemoryPort(name() + "-port", this);
281 return port;
282 } else if (if_name == "functional") {
283 /* special port for functional writes at startup. And for memtester */
284 return new MemoryPort(name() + "-funcport", this);
285 } else {
286 panic("PhysicalMemory::getPort: unknown port %s requested", if_name);
287 }
288 }
289
290 void
291 PhysicalMemory::recvStatusChange(Port::Status status)
292 {
293 }
294
295 PhysicalMemory::MemoryPort::MemoryPort(const std::string &_name,
296 PhysicalMemory *_memory)
297 : SimpleTimingPort(_name), memory(_memory)
298 { }
299
300 void
301 PhysicalMemory::MemoryPort::recvStatusChange(Port::Status status)
302 {
303 memory->recvStatusChange(status);
304 }
305
306 void
307 PhysicalMemory::MemoryPort::getDeviceAddressRanges(AddrRangeList &resp,
308 AddrRangeList &snoop)
309 {
310 memory->getAddressRanges(resp, snoop);
311 }
312
313 void
314 PhysicalMemory::getAddressRanges(AddrRangeList &resp, AddrRangeList &snoop)
315 {
316 snoop.clear();
317 resp.clear();
318 resp.push_back(RangeSize(params()->addrRange.start,
319 params()->addrRange.size()));
320 }
321
322 int
323 PhysicalMemory::MemoryPort::deviceBlockSize()
324 {
325 return memory->deviceBlockSize();
326 }
327
328 Tick
329 PhysicalMemory::MemoryPort::recvAtomic(PacketPtr pkt)
330 {
331 memory->doFunctionalAccess(pkt);
332 return memory->calculateLatency(pkt);
333 }
334
335 void
336 PhysicalMemory::MemoryPort::recvFunctional(PacketPtr pkt)
337 {
338 //Since we are overriding the function, make sure to have the impl of the
339 //check or functional accesses here.
340 std::list<std::pair<Tick,PacketPtr> >::iterator i = transmitList.begin();
341 std::list<std::pair<Tick,PacketPtr> >::iterator end = transmitList.end();
342 bool notDone = true;
343
344 while (i != end && notDone) {
345 PacketPtr target = i->second;
346 // If the target contains data, and it overlaps the
347 // probed request, need to update data
348 if (target->intersect(pkt))
349 notDone = fixPacket(pkt, target);
350 i++;
351 }
352
353 // Default implementation of SimpleTimingPort::recvFunctional()
354 // calls recvAtomic() and throws away the latency; we can save a
355 // little here by just not calculating the latency.
356 memory->doFunctionalAccess(pkt);
357 }
358
359 unsigned int
360 PhysicalMemory::drain(Event *de)
361 {
362 int count = port->drain(de);
363 if (count)
364 changeState(Draining);
365 else
366 changeState(Drained);
367 return count;
368 }
369
370 void
371 PhysicalMemory::serialize(ostream &os)
372 {
373 gzFile compressedMem;
374 string filename = name() + ".physmem";
375
376 SERIALIZE_SCALAR(filename);
377
378 // write memory file
379 string thefile = Checkpoint::dir() + "/" + filename.c_str();
380 int fd = creat(thefile.c_str(), 0664);
381 if (fd < 0) {
382 perror("creat");
383 fatal("Can't open physical memory checkpoint file '%s'\n", filename);
384 }
385
386 compressedMem = gzdopen(fd, "wb");
387 if (compressedMem == NULL)
388 fatal("Insufficient memory to allocate compression state for %s\n",
389 filename);
390
391 if (gzwrite(compressedMem, pmemAddr, params()->addrRange.size()) != params()->addrRange.size()) {
392 fatal("Write failed on physical memory checkpoint file '%s'\n",
393 filename);
394 }
395
396 if (gzclose(compressedMem))
397 fatal("Close failed on physical memory checkpoint file '%s'\n",
398 filename);
399 }
400
401 void
402 PhysicalMemory::unserialize(Checkpoint *cp, const string &section)
403 {
404 gzFile compressedMem;
405 long *tempPage;
406 long *pmem_current;
407 uint64_t curSize;
408 uint32_t bytesRead;
409 const int chunkSize = 16384;
410
411
412 string filename;
413
414 UNSERIALIZE_SCALAR(filename);
415
416 filename = cp->cptDir + "/" + filename;
417
418 // mmap memoryfile
419 int fd = open(filename.c_str(), O_RDONLY);
420 if (fd < 0) {
421 perror("open");
422 fatal("Can't open physical memory checkpoint file '%s'", filename);
423 }
424
425 compressedMem = gzdopen(fd, "rb");
426 if (compressedMem == NULL)
427 fatal("Insufficient memory to allocate compression state for %s\n",
428 filename);
429
430 // unmap file that was mmaped in the constructor
431 // This is done here to make sure that gzip and open don't muck with our
432 // nice large space of memory before we reallocate it
433 munmap(pmemAddr, params()->addrRange.size());
434
435 pmemAddr = (uint8_t *)mmap(NULL, params()->addrRange.size(), PROT_READ | PROT_WRITE,
436 MAP_ANON | MAP_PRIVATE, -1, 0);
437
438 if (pmemAddr == (void *)MAP_FAILED) {
439 perror("mmap");
440 fatal("Could not mmap physical memory!\n");
441 }
442
443 curSize = 0;
444 tempPage = (long*)malloc(chunkSize);
445 if (tempPage == NULL)
446 fatal("Unable to malloc memory to read file %s\n", filename);
447
448 /* Only copy bytes that are non-zero, so we don't give the VM system hell */
449 while (curSize < params()->addrRange.size()) {
450 bytesRead = gzread(compressedMem, tempPage, chunkSize);
451 if (bytesRead != chunkSize && bytesRead != params()->addrRange.size() - curSize)
452 fatal("Read failed on physical memory checkpoint file '%s'"
453 " got %d bytes, expected %d or %d bytes\n",
454 filename, bytesRead, chunkSize, params()->addrRange.size()-curSize);
455
456 assert(bytesRead % sizeof(long) == 0);
457
458 for (int x = 0; x < bytesRead/sizeof(long); x++)
459 {
460 if (*(tempPage+x) != 0) {
461 pmem_current = (long*)(pmemAddr + curSize + x * sizeof(long));
462 *pmem_current = *(tempPage+x);
463 }
464 }
465 curSize += bytesRead;
466 }
467
468 free(tempPage);
469
470 if (gzclose(compressedMem))
471 fatal("Close failed on physical memory checkpoint file '%s'\n",
472 filename);
473
474 }
475
476
477 BEGIN_DECLARE_SIM_OBJECT_PARAMS(PhysicalMemory)
478
479 Param<string> file;
480 Param<Range<Addr> > range;
481 Param<Tick> latency;
482 Param<bool> zero;
483
484 END_DECLARE_SIM_OBJECT_PARAMS(PhysicalMemory)
485
486 BEGIN_INIT_SIM_OBJECT_PARAMS(PhysicalMemory)
487
488 INIT_PARAM_DFLT(file, "memory mapped file", ""),
489 INIT_PARAM(range, "Device Address Range"),
490 INIT_PARAM(latency, "Memory access latency"),
491 INIT_PARAM(zero, "Zero initialize memory")
492
493 END_INIT_SIM_OBJECT_PARAMS(PhysicalMemory)
494
495 CREATE_SIM_OBJECT(PhysicalMemory)
496 {
497 PhysicalMemory::Params *p = new PhysicalMemory::Params;
498 p->name = getInstanceName();
499 p->addrRange = range;
500 p->latency = latency;
501 p->zero = zero;
502 return new PhysicalMemory(p);
503 }
504
505 REGISTER_SIM_OBJECT("PhysicalMemory", PhysicalMemory)