2 * Copyright (c) 2010-2011 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");
79 // create the appropriate number of ports
80 for (int i
= 0; i
< p
->port_port_connection_count
; ++i
) {
81 ports
.push_back(new MemoryPort(csprintf("%s-port%d", name(), i
),
89 if (params()->file
== "") {
90 int map_flags
= MAP_ANON
| MAP_PRIVATE
;
91 pmemAddr
= (uint8_t *)mmap(NULL
, size(),
92 PROT_READ
| PROT_WRITE
, map_flags
, -1, 0);
94 int map_flags
= MAP_PRIVATE
;
95 int fd
= open(params()->file
.c_str(), O_RDONLY
);
96 _size
= lseek(fd
, 0, SEEK_END
);
97 lseek(fd
, 0, SEEK_SET
);
98 pmemAddr
= (uint8_t *)mmap(NULL
, roundUp(size(), sysconf(_SC_PAGESIZE
)),
99 PROT_READ
| PROT_WRITE
, map_flags
, fd
, 0);
102 if (pmemAddr
== (void *)MAP_FAILED
) {
104 if (params()->file
== "")
105 fatal("Could not mmap!\n");
107 fatal("Could not find file: %s\n", params()->file
);
110 //If requested, initialize all the memory to 0
112 memset(pmemAddr
, 0, size());
116 PhysicalMemory::init()
118 for (PortIterator p
= ports
.begin(); p
!= ports
.end(); ++p
) {
119 if (!(*p
)->isConnected()) {
120 fatal("PhysicalMemory port %s is unconnected!\n", (*p
)->name());
122 (*p
)->sendRangeChange();
127 PhysicalMemory::~PhysicalMemory()
130 munmap((char*)pmemAddr
, size());
134 PhysicalMemory::regStats()
136 using namespace Stats
;
139 .name(name() + ".bytes_read")
140 .desc("Number of bytes read from this memory")
143 .name(name() + ".bytes_inst_read")
144 .desc("Number of instructions bytes read from this memory")
147 .name(name() + ".bytes_written")
148 .desc("Number of bytes written to this memory")
151 .name(name() + ".num_reads")
152 .desc("Number of read requests responded to by this memory")
155 .name(name() + ".num_writes")
156 .desc("Number of write requests responded to by this memory")
159 .name(name() + ".num_other")
160 .desc("Number of other requests responded to by this memory")
163 .name(name() + ".bw_read")
164 .desc("Total read bandwidth from this memory (bytes/s)")
169 .name(name() + ".bw_inst_read")
170 .desc("Instruction read bandwidth from this memory (bytes/s)")
172 .prereq(bytesInstRead
)
175 .name(name() + ".bw_write")
176 .desc("Write bandwidth from this memory (bytes/s)")
178 .prereq(bytesWritten
)
181 .name(name() + ".bw_total")
182 .desc("Total bandwidth to/from this memory (bytes/s)")
186 bwRead
= bytesRead
/ simSeconds
;
187 bwInstRead
= bytesInstRead
/ simSeconds
;
188 bwWrite
= bytesWritten
/ simSeconds
;
189 bwTotal
= (bytesRead
+ bytesWritten
) / simSeconds
;
193 PhysicalMemory::deviceBlockSize() const
195 //Can accept anysize request
200 PhysicalMemory::calculateLatency(PacketPtr pkt
)
204 latency
+= random_mt
.random
<Tick
>(0, lat_var
);
210 // Add load-locked to tracking list. Should only be called if the
211 // operation is a load and the LLSC flag is set.
213 PhysicalMemory::trackLoadLocked(PacketPtr pkt
)
215 Request
*req
= pkt
->req
;
216 Addr paddr
= LockedAddr::mask(req
->getPaddr());
218 // first we check if we already have a locked addr for this
219 // xc. Since each xc only gets one, we just update the
220 // existing record with the new address.
221 list
<LockedAddr
>::iterator i
;
223 for (i
= lockedAddrList
.begin(); i
!= lockedAddrList
.end(); ++i
) {
224 if (i
->matchesContext(req
)) {
225 DPRINTF(LLSC
, "Modifying lock record: context %d addr %#x\n",
226 req
->contextId(), paddr
);
232 // no record for this xc: need to allocate a new one
233 DPRINTF(LLSC
, "Adding lock record: context %d addr %#x\n",
234 req
->contextId(), paddr
);
235 lockedAddrList
.push_front(LockedAddr(req
));
239 // Called on *writes* only... both regular stores and
240 // store-conditional operations. Check for conventional stores which
241 // conflict with locked addresses, and for success/failure of store
244 PhysicalMemory::checkLockedAddrList(PacketPtr pkt
)
246 Request
*req
= pkt
->req
;
247 Addr paddr
= LockedAddr::mask(req
->getPaddr());
248 bool isLLSC
= pkt
->isLLSC();
250 // Initialize return value. Non-conditional stores always
251 // succeed. Assume conditional stores will fail until proven
253 bool success
= !isLLSC
;
255 // Iterate over list. Note that there could be multiple matching
256 // records, as more than one context could have done a load locked
258 list
<LockedAddr
>::iterator i
= lockedAddrList
.begin();
260 while (i
!= lockedAddrList
.end()) {
262 if (i
->addr
== paddr
) {
263 // we have a matching address
265 if (isLLSC
&& i
->matchesContext(req
)) {
266 // it's a store conditional, and as far as the memory
267 // system can tell, the requesting context's lock is
269 DPRINTF(LLSC
, "StCond success: context %d addr %#x\n",
270 req
->contextId(), paddr
);
274 // Get rid of our record of this lock and advance to next
275 DPRINTF(LLSC
, "Erasing lock record: context %d addr %#x\n",
276 i
->contextId
, paddr
);
277 i
= lockedAddrList
.erase(i
);
280 // no match: advance to next record
286 req
->setExtraData(success
? 1 : 0);
297 DPRINTF(MemoryAccess,"%s of size %i on address 0x%x data 0x%x\n", \
298 A, pkt->getSize(), pkt->getAddr(), pkt->get<T>()); \
302 #define TRACE_PACKET(A) \
304 switch (pkt->getSize()) { \
310 DPRINTF(MemoryAccess, "%s of size %i on address 0x%x\n", \
311 A, pkt->getSize(), pkt->getAddr()); \
312 DDUMP(MemoryAccess, pkt->getPtr<uint8_t>(), pkt->getSize());\
318 #define TRACE_PACKET(A)
323 PhysicalMemory::doAtomicAccess(PacketPtr pkt
)
325 assert(pkt
->getAddr() >= start() &&
326 pkt
->getAddr() + pkt
->getSize() <= start() + size());
328 if (pkt
->memInhibitAsserted()) {
329 DPRINTF(MemoryAccess
, "mem inhibited on 0x%x: not responding\n",
334 uint8_t *hostAddr
= pmemAddr
+ pkt
->getAddr() - start();
336 if (pkt
->cmd
== MemCmd::SwapReq
) {
337 IntReg overwrite_val
;
339 uint64_t condition_val64
;
340 uint32_t condition_val32
;
343 panic("Swap only works if there is real memory (i.e. null=False)");
344 assert(sizeof(IntReg
) >= pkt
->getSize());
346 overwrite_mem
= true;
347 // keep a copy of our possible write value, and copy what is at the
348 // memory address into the packet
349 std::memcpy(&overwrite_val
, pkt
->getPtr
<uint8_t>(), pkt
->getSize());
350 std::memcpy(pkt
->getPtr
<uint8_t>(), hostAddr
, pkt
->getSize());
352 if (pkt
->req
->isCondSwap()) {
353 if (pkt
->getSize() == sizeof(uint64_t)) {
354 condition_val64
= pkt
->req
->getExtraData();
355 overwrite_mem
= !std::memcmp(&condition_val64
, hostAddr
,
357 } else if (pkt
->getSize() == sizeof(uint32_t)) {
358 condition_val32
= (uint32_t)pkt
->req
->getExtraData();
359 overwrite_mem
= !std::memcmp(&condition_val32
, hostAddr
,
362 panic("Invalid size for conditional read/write\n");
366 std::memcpy(hostAddr
, &overwrite_val
, pkt
->getSize());
368 assert(!pkt
->req
->isInstFetch());
369 TRACE_PACKET("Read/Write");
371 } else if (pkt
->isRead()) {
372 assert(!pkt
->isWrite());
374 trackLoadLocked(pkt
);
377 memcpy(pkt
->getPtr
<uint8_t>(), hostAddr
, pkt
->getSize());
378 TRACE_PACKET(pkt
->req
->isInstFetch() ? "IFetch" : "Read");
380 bytesRead
+= pkt
->getSize();
381 if (pkt
->req
->isInstFetch())
382 bytesInstRead
+= pkt
->getSize();
383 } else if (pkt
->isWrite()) {
386 memcpy(hostAddr
, pkt
->getPtr
<uint8_t>(), pkt
->getSize());
387 assert(!pkt
->req
->isInstFetch());
388 TRACE_PACKET("Write");
390 bytesWritten
+= pkt
->getSize();
392 } else if (pkt
->isInvalidate()) {
393 //upgrade or invalidate
394 if (pkt
->needsResponse()) {
395 pkt
->makeAtomicResponse();
398 panic("unimplemented");
401 if (pkt
->needsResponse()) {
402 pkt
->makeAtomicResponse();
404 return calculateLatency(pkt
);
409 PhysicalMemory::doFunctionalAccess(PacketPtr pkt
)
411 assert(pkt
->getAddr() >= start() &&
412 pkt
->getAddr() + pkt
->getSize() <= start() + size());
415 uint8_t *hostAddr
= pmemAddr
+ pkt
->getAddr() - start();
419 memcpy(pkt
->getPtr
<uint8_t>(), hostAddr
, pkt
->getSize());
420 TRACE_PACKET("Read");
421 pkt
->makeAtomicResponse();
422 } else if (pkt
->isWrite()) {
424 memcpy(hostAddr
, pkt
->getPtr
<uint8_t>(), pkt
->getSize());
425 TRACE_PACKET("Write");
426 pkt
->makeAtomicResponse();
427 } else if (pkt
->isPrint()) {
428 Packet::PrintReqState
*prs
=
429 dynamic_cast<Packet::PrintReqState
*>(pkt
->senderState
);
430 // Need to call printLabels() explicitly since we're not going
431 // through printObj().
433 // Right now we just print the single byte at the specified address.
434 ccprintf(prs
->os
, "%s%#x\n", prs
->curPrefix(), *hostAddr
);
436 panic("PhysicalMemory: unimplemented functional command %s",
443 PhysicalMemory::getSlavePort(const std::string
&if_name
, int idx
)
445 if (if_name
!= "port") {
446 return MemObject::getSlavePort(if_name
, idx
);
448 if (idx
>= static_cast<int>(ports
.size())) {
449 fatal("PhysicalMemory::getSlavePort: unknown index %d\n", idx
);
456 PhysicalMemory::MemoryPort::MemoryPort(const std::string
&_name
,
457 PhysicalMemory
*_memory
)
458 : SimpleTimingPort(_name
, _memory
), memory(_memory
)
462 PhysicalMemory::MemoryPort::getAddrRanges()
464 return memory
->getAddrRanges();
468 PhysicalMemory::getAddrRanges()
470 AddrRangeList ranges
;
471 ranges
.push_back(RangeSize(start(), size()));
476 PhysicalMemory::MemoryPort::deviceBlockSize() const
478 return memory
->deviceBlockSize();
482 PhysicalMemory::MemoryPort::recvAtomic(PacketPtr pkt
)
484 return memory
->doAtomicAccess(pkt
);
488 PhysicalMemory::MemoryPort::recvFunctional(PacketPtr pkt
)
490 pkt
->pushLabel(memory
->name());
492 if (!queue
.checkFunctional(pkt
)) {
493 // Default implementation of SimpleTimingPort::recvFunctional()
494 // calls recvAtomic() and throws away the latency; we can save a
495 // little here by just not calculating the latency.
496 memory
->doFunctionalAccess(pkt
);
503 PhysicalMemory::drain(Event
*de
)
506 for (PortIterator pi
= ports
.begin(); pi
!= ports
.end(); ++pi
) {
507 count
+= (*pi
)->drain(de
);
511 changeState(Draining
);
513 changeState(Drained
);
518 PhysicalMemory::serialize(ostream
&os
)
523 gzFile compressedMem
;
524 string filename
= name() + ".physmem";
526 SERIALIZE_SCALAR(filename
);
527 SERIALIZE_SCALAR(_size
);
530 string thefile
= Checkpoint::dir() + "/" + filename
.c_str();
531 int fd
= creat(thefile
.c_str(), 0664);
534 fatal("Can't open physical memory checkpoint file '%s'\n", filename
);
537 compressedMem
= gzdopen(fd
, "wb");
538 if (compressedMem
== NULL
)
539 fatal("Insufficient memory to allocate compression state for %s\n",
542 if (gzwrite(compressedMem
, pmemAddr
, size()) != (int)size()) {
543 fatal("Write failed on physical memory checkpoint file '%s'\n",
547 if (gzclose(compressedMem
))
548 fatal("Close failed on physical memory checkpoint file '%s'\n",
551 list
<LockedAddr
>::iterator i
= lockedAddrList
.begin();
553 vector
<Addr
> lal_addr
;
555 while (i
!= lockedAddrList
.end()) {
556 lal_addr
.push_back(i
->addr
);
557 lal_cid
.push_back(i
->contextId
);
560 arrayParamOut(os
, "lal_addr", lal_addr
);
561 arrayParamOut(os
, "lal_cid", lal_cid
);
565 PhysicalMemory::unserialize(Checkpoint
*cp
, const string
§ion
)
570 gzFile compressedMem
;
575 const uint32_t chunkSize
= 16384;
579 UNSERIALIZE_SCALAR(filename
);
581 filename
= cp
->cptDir
+ "/" + filename
;
584 int fd
= open(filename
.c_str(), O_RDONLY
);
587 fatal("Can't open physical memory checkpoint file '%s'", filename
);
590 compressedMem
= gzdopen(fd
, "rb");
591 if (compressedMem
== NULL
)
592 fatal("Insufficient memory to allocate compression state for %s\n",
595 // unmap file that was mmapped in the constructor
596 // This is done here to make sure that gzip and open don't muck with our
597 // nice large space of memory before we reallocate it
598 munmap((char*)pmemAddr
, size());
600 UNSERIALIZE_SCALAR(_size
);
601 if (size() > params()->range
.size())
602 fatal("Memory size has changed! size %lld, param size %lld\n",
603 size(), params()->range
.size());
605 pmemAddr
= (uint8_t *)mmap(NULL
, size(),
606 PROT_READ
| PROT_WRITE
, MAP_ANON
| MAP_PRIVATE
, -1, 0);
608 if (pmemAddr
== (void *)MAP_FAILED
) {
610 fatal("Could not mmap physical memory!\n");
614 tempPage
= (long*)malloc(chunkSize
);
615 if (tempPage
== NULL
)
616 fatal("Unable to malloc memory to read file %s\n", filename
);
618 /* Only copy bytes that are non-zero, so we don't give the VM system hell */
619 while (curSize
< size()) {
620 bytesRead
= gzread(compressedMem
, tempPage
, chunkSize
);
624 assert(bytesRead
% sizeof(long) == 0);
626 for (uint32_t x
= 0; x
< bytesRead
/ sizeof(long); x
++)
628 if (*(tempPage
+x
) != 0) {
629 pmem_current
= (long*)(pmemAddr
+ curSize
+ x
* sizeof(long));
630 *pmem_current
= *(tempPage
+x
);
633 curSize
+= bytesRead
;
638 if (gzclose(compressedMem
))
639 fatal("Close failed on physical memory checkpoint file '%s'\n",
642 vector
<Addr
> lal_addr
;
644 arrayParamIn(cp
, section
, "lal_addr", lal_addr
);
645 arrayParamIn(cp
, section
, "lal_cid", lal_cid
);
646 for(int i
= 0; i
< lal_addr
.size(); i
++)
647 lockedAddrList
.push_front(LockedAddr(lal_addr
[i
], lal_cid
[i
]));
651 PhysicalMemoryParams::create()
653 return new PhysicalMemory(this);