2 * Copyright (c) 2010 ARM Limited
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.
14 * Copyright (c) 2001-2005 The Regents of The University of Michigan
15 * All rights reserved.
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.
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.
40 * Authors: Ron Dreslinski
45 #include <sys/types.h>
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/the_isa.hh"
63 #include "debug/LLSC.hh"
64 #include "debug/MemoryAccess.hh"
65 #include "mem/packet_access.hh"
66 #include "mem/physical.hh"
67 #include "sim/eventq.hh"
70 using namespace TheISA
;
72 PhysicalMemory::PhysicalMemory(const Params
*p
)
73 : MemObject(p
), pmemAddr(NULL
), lat(p
->latency
), lat_var(p
->latency_var
),
74 _size(params()->range
.size()), _start(params()->range
.start
)
76 if (size() % TheISA::PageBytes
!= 0)
77 panic("Memory Size not divisible by page size\n");
83 if (params()->file
== "") {
84 int map_flags
= MAP_ANON
| MAP_PRIVATE
;
85 pmemAddr
= (uint8_t *)mmap(NULL
, size(),
86 PROT_READ
| PROT_WRITE
, map_flags
, -1, 0);
88 int map_flags
= MAP_PRIVATE
;
89 int fd
= open(params()->file
.c_str(), O_RDONLY
);
90 _size
= lseek(fd
, 0, SEEK_END
);
91 lseek(fd
, 0, SEEK_SET
);
92 pmemAddr
= (uint8_t *)mmap(NULL
, roundUp(size(), sysconf(_SC_PAGESIZE
)),
93 PROT_READ
| PROT_WRITE
, map_flags
, fd
, 0);
96 if (pmemAddr
== (void *)MAP_FAILED
) {
98 if (params()->file
== "")
99 fatal("Could not mmap!\n");
101 fatal("Could not find file: %s\n", params()->file
);
104 //If requested, initialize all the memory to 0
106 memset(pmemAddr
, 0, size());
110 PhysicalMemory::init()
112 if (ports
.size() == 0) {
113 fatal("PhysicalMemory object %s is unconnected!", name());
116 for (PortIterator pi
= ports
.begin(); pi
!= ports
.end(); ++pi
) {
118 (*pi
)->sendStatusChange(Port::RangeChange
);
122 PhysicalMemory::~PhysicalMemory()
125 munmap((char*)pmemAddr
, size());
129 PhysicalMemory::deviceBlockSize() const
131 //Can accept anysize request
136 PhysicalMemory::calculateLatency(PacketPtr pkt
)
140 latency
+= random_mt
.random
<Tick
>(0, lat_var
);
146 // Add load-locked to tracking list. Should only be called if the
147 // operation is a load and the LLSC flag is set.
149 PhysicalMemory::trackLoadLocked(PacketPtr pkt
)
151 Request
*req
= pkt
->req
;
152 Addr paddr
= LockedAddr::mask(req
->getPaddr());
154 // first we check if we already have a locked addr for this
155 // xc. Since each xc only gets one, we just update the
156 // existing record with the new address.
157 list
<LockedAddr
>::iterator i
;
159 for (i
= lockedAddrList
.begin(); i
!= lockedAddrList
.end(); ++i
) {
160 if (i
->matchesContext(req
)) {
161 DPRINTF(LLSC
, "Modifying lock record: context %d addr %#x\n",
162 req
->contextId(), paddr
);
168 // no record for this xc: need to allocate a new one
169 DPRINTF(LLSC
, "Adding lock record: context %d addr %#x\n",
170 req
->contextId(), paddr
);
171 lockedAddrList
.push_front(LockedAddr(req
));
175 // Called on *writes* only... both regular stores and
176 // store-conditional operations. Check for conventional stores which
177 // conflict with locked addresses, and for success/failure of store
180 PhysicalMemory::checkLockedAddrList(PacketPtr pkt
)
182 Request
*req
= pkt
->req
;
183 Addr paddr
= LockedAddr::mask(req
->getPaddr());
184 bool isLLSC
= pkt
->isLLSC();
186 // Initialize return value. Non-conditional stores always
187 // succeed. Assume conditional stores will fail until proven
189 bool success
= !isLLSC
;
191 // Iterate over list. Note that there could be multiple matching
192 // records, as more than one context could have done a load locked
194 list
<LockedAddr
>::iterator i
= lockedAddrList
.begin();
196 while (i
!= lockedAddrList
.end()) {
198 if (i
->addr
== paddr
) {
199 // we have a matching address
201 if (isLLSC
&& i
->matchesContext(req
)) {
202 // it's a store conditional, and as far as the memory
203 // system can tell, the requesting context's lock is
205 DPRINTF(LLSC
, "StCond success: context %d addr %#x\n",
206 req
->contextId(), paddr
);
210 // Get rid of our record of this lock and advance to next
211 DPRINTF(LLSC
, "Erasing lock record: context %d addr %#x\n",
212 i
->contextId
, paddr
);
213 i
= lockedAddrList
.erase(i
);
216 // no match: advance to next record
222 req
->setExtraData(success
? 1 : 0);
233 DPRINTF(MemoryAccess,"%s of size %i on address 0x%x data 0x%x\n", \
234 A, pkt->getSize(), pkt->getAddr(), pkt->get<T>()); \
238 #define TRACE_PACKET(A) \
240 switch (pkt->getSize()) { \
246 DPRINTF(MemoryAccess, "%s of size %i on address 0x%x\n", \
247 A, pkt->getSize(), pkt->getAddr()); \
248 DDUMP(MemoryAccess, pkt->getPtr<uint8_t>(), pkt->getSize());\
254 #define TRACE_PACKET(A)
259 PhysicalMemory::doAtomicAccess(PacketPtr pkt
)
261 assert(pkt
->getAddr() >= start() &&
262 pkt
->getAddr() + pkt
->getSize() <= start() + size());
264 if (pkt
->memInhibitAsserted()) {
265 DPRINTF(MemoryAccess
, "mem inhibited on 0x%x: not responding\n",
270 uint8_t *hostAddr
= pmemAddr
+ pkt
->getAddr() - start();
272 if (pkt
->cmd
== MemCmd::SwapReq
) {
273 IntReg overwrite_val
;
275 uint64_t condition_val64
;
276 uint32_t condition_val32
;
279 panic("Swap only works if there is real memory (i.e. null=False)");
280 assert(sizeof(IntReg
) >= pkt
->getSize());
282 overwrite_mem
= true;
283 // keep a copy of our possible write value, and copy what is at the
284 // memory address into the packet
285 std::memcpy(&overwrite_val
, pkt
->getPtr
<uint8_t>(), pkt
->getSize());
286 std::memcpy(pkt
->getPtr
<uint8_t>(), hostAddr
, pkt
->getSize());
288 if (pkt
->req
->isCondSwap()) {
289 if (pkt
->getSize() == sizeof(uint64_t)) {
290 condition_val64
= pkt
->req
->getExtraData();
291 overwrite_mem
= !std::memcmp(&condition_val64
, hostAddr
,
293 } else if (pkt
->getSize() == sizeof(uint32_t)) {
294 condition_val32
= (uint32_t)pkt
->req
->getExtraData();
295 overwrite_mem
= !std::memcmp(&condition_val32
, hostAddr
,
298 panic("Invalid size for conditional read/write\n");
302 std::memcpy(hostAddr
, &overwrite_val
, pkt
->getSize());
304 assert(!pkt
->req
->isInstFetch());
305 TRACE_PACKET("Read/Write");
306 } else if (pkt
->isRead()) {
307 assert(!pkt
->isWrite());
309 trackLoadLocked(pkt
);
312 memcpy(pkt
->getPtr
<uint8_t>(), hostAddr
, pkt
->getSize());
313 TRACE_PACKET(pkt
->req
->isInstFetch() ? "IFetch" : "Read");
314 } else if (pkt
->isWrite()) {
317 memcpy(hostAddr
, pkt
->getPtr
<uint8_t>(), pkt
->getSize());
318 assert(!pkt
->req
->isInstFetch());
319 TRACE_PACKET("Write");
321 } else if (pkt
->isInvalidate()) {
322 //upgrade or invalidate
323 if (pkt
->needsResponse()) {
324 pkt
->makeAtomicResponse();
327 panic("unimplemented");
330 if (pkt
->needsResponse()) {
331 pkt
->makeAtomicResponse();
333 return calculateLatency(pkt
);
338 PhysicalMemory::doFunctionalAccess(PacketPtr pkt
)
340 assert(pkt
->getAddr() >= start() &&
341 pkt
->getAddr() + pkt
->getSize() <= start() + size());
344 uint8_t *hostAddr
= pmemAddr
+ pkt
->getAddr() - start();
348 memcpy(pkt
->getPtr
<uint8_t>(), hostAddr
, pkt
->getSize());
349 TRACE_PACKET("Read");
350 pkt
->makeAtomicResponse();
351 } else if (pkt
->isWrite()) {
353 memcpy(hostAddr
, pkt
->getPtr
<uint8_t>(), pkt
->getSize());
354 TRACE_PACKET("Write");
355 pkt
->makeAtomicResponse();
356 } else if (pkt
->isPrint()) {
357 Packet::PrintReqState
*prs
=
358 dynamic_cast<Packet::PrintReqState
*>(pkt
->senderState
);
359 // Need to call printLabels() explicitly since we're not going
360 // through printObj().
362 // Right now we just print the single byte at the specified address.
363 ccprintf(prs
->os
, "%s%#x\n", prs
->curPrefix(), *hostAddr
);
365 panic("PhysicalMemory: unimplemented functional command %s",
372 PhysicalMemory::getPort(const std::string
&if_name
, int idx
)
374 // Accept request for "functional" port for backwards compatibility
375 // with places where this function is called from C++. I'd prefer
376 // to move all these into Python someday.
377 if (if_name
== "functional") {
378 return new MemoryPort(csprintf("%s-functional", name()), this);
381 if (if_name
!= "port") {
382 panic("PhysicalMemory::getPort: unknown port %s requested", if_name
);
385 if (idx
>= (int)ports
.size()) {
386 ports
.resize(idx
+ 1);
389 if (ports
[idx
] != NULL
) {
390 panic("PhysicalMemory::getPort: port %d already assigned", idx
);
394 new MemoryPort(csprintf("%s-port%d", name(), idx
), this);
402 PhysicalMemory::recvStatusChange(Port::Status status
)
406 PhysicalMemory::MemoryPort::MemoryPort(const std::string
&_name
,
407 PhysicalMemory
*_memory
)
408 : SimpleTimingPort(_name
, _memory
), memory(_memory
)
412 PhysicalMemory::MemoryPort::recvStatusChange(Port::Status status
)
414 memory
->recvStatusChange(status
);
418 PhysicalMemory::MemoryPort::getDeviceAddressRanges(AddrRangeList
&resp
,
421 memory
->getAddressRanges(resp
, snoop
);
425 PhysicalMemory::getAddressRanges(AddrRangeList
&resp
, bool &snoop
)
429 resp
.push_back(RangeSize(start(), size()));
433 PhysicalMemory::MemoryPort::deviceBlockSize() const
435 return memory
->deviceBlockSize();
439 PhysicalMemory::MemoryPort::recvAtomic(PacketPtr pkt
)
441 return memory
->doAtomicAccess(pkt
);
445 PhysicalMemory::MemoryPort::recvFunctional(PacketPtr pkt
)
447 pkt
->pushLabel(memory
->name());
449 if (!checkFunctional(pkt
)) {
450 // Default implementation of SimpleTimingPort::recvFunctional()
451 // calls recvAtomic() and throws away the latency; we can save a
452 // little here by just not calculating the latency.
453 memory
->doFunctionalAccess(pkt
);
460 PhysicalMemory::drain(Event
*de
)
463 for (PortIterator pi
= ports
.begin(); pi
!= ports
.end(); ++pi
) {
464 count
+= (*pi
)->drain(de
);
468 changeState(Draining
);
470 changeState(Drained
);
475 PhysicalMemory::serialize(ostream
&os
)
480 gzFile compressedMem
;
481 string filename
= name() + ".physmem";
483 SERIALIZE_SCALAR(filename
);
484 SERIALIZE_SCALAR(_size
);
487 string thefile
= Checkpoint::dir() + "/" + filename
.c_str();
488 int fd
= creat(thefile
.c_str(), 0664);
491 fatal("Can't open physical memory checkpoint file '%s'\n", filename
);
494 compressedMem
= gzdopen(fd
, "wb");
495 if (compressedMem
== NULL
)
496 fatal("Insufficient memory to allocate compression state for %s\n",
499 if (gzwrite(compressedMem
, pmemAddr
, size()) != (int)size()) {
500 fatal("Write failed on physical memory checkpoint file '%s'\n",
504 if (gzclose(compressedMem
))
505 fatal("Close failed on physical memory checkpoint file '%s'\n",
508 list
<LockedAddr
>::iterator i
= lockedAddrList
.begin();
510 vector
<Addr
> lal_addr
;
512 while (i
!= lockedAddrList
.end()) {
513 lal_addr
.push_back(i
->addr
);
514 lal_cid
.push_back(i
->contextId
);
517 arrayParamOut(os
, "lal_addr", lal_addr
);
518 arrayParamOut(os
, "lal_cid", lal_cid
);
522 PhysicalMemory::unserialize(Checkpoint
*cp
, const string
§ion
)
527 gzFile compressedMem
;
532 const uint32_t chunkSize
= 16384;
536 UNSERIALIZE_SCALAR(filename
);
538 filename
= cp
->cptDir
+ "/" + filename
;
541 int fd
= open(filename
.c_str(), O_RDONLY
);
544 fatal("Can't open physical memory checkpoint file '%s'", filename
);
547 compressedMem
= gzdopen(fd
, "rb");
548 if (compressedMem
== NULL
)
549 fatal("Insufficient memory to allocate compression state for %s\n",
552 // unmap file that was mmapped in the constructor
553 // This is done here to make sure that gzip and open don't muck with our
554 // nice large space of memory before we reallocate it
555 munmap((char*)pmemAddr
, size());
557 UNSERIALIZE_SCALAR(_size
);
558 if (size() > params()->range
.size())
559 fatal("Memory size has changed!\n");
561 pmemAddr
= (uint8_t *)mmap(NULL
, size(),
562 PROT_READ
| PROT_WRITE
, MAP_ANON
| MAP_PRIVATE
, -1, 0);
564 if (pmemAddr
== (void *)MAP_FAILED
) {
566 fatal("Could not mmap physical memory!\n");
570 tempPage
= (long*)malloc(chunkSize
);
571 if (tempPage
== NULL
)
572 fatal("Unable to malloc memory to read file %s\n", filename
);
574 /* Only copy bytes that are non-zero, so we don't give the VM system hell */
575 while (curSize
< size()) {
576 bytesRead
= gzread(compressedMem
, tempPage
, chunkSize
);
580 assert(bytesRead
% sizeof(long) == 0);
582 for (uint32_t x
= 0; x
< bytesRead
/ sizeof(long); x
++)
584 if (*(tempPage
+x
) != 0) {
585 pmem_current
= (long*)(pmemAddr
+ curSize
+ x
* sizeof(long));
586 *pmem_current
= *(tempPage
+x
);
589 curSize
+= bytesRead
;
594 if (gzclose(compressedMem
))
595 fatal("Close failed on physical memory checkpoint file '%s'\n",
598 vector
<Addr
> lal_addr
;
600 arrayParamIn(cp
, section
, "lal_addr", lal_addr
);
601 arrayParamIn(cp
, section
, "lal_cid", lal_cid
);
602 for(int i
= 0; i
< lal_addr
.size(); i
++)
603 lockedAddrList
.push_front(LockedAddr(lal_addr
[i
], lal_cid
[i
]));
607 PhysicalMemoryParams::create()
609 return new PhysicalMemory(this);