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