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()
119 fatal("PhysicalMemory object %s is unconnected!", name());
122 for (PortIterator pi
= ports
.begin(); pi
!= ports
.end(); ++pi
) {
123 (*pi
)->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::getPort(const std::string
&if_name
, int idx
)
445 if (if_name
!= "port") {
446 panic("PhysicalMemory::getPort: unknown port %s requested\n", if_name
);
449 if (idx
>= static_cast<int>(ports
.size())) {
450 panic("PhysicalMemory::getPort: unknown index %d requested\n", idx
);
456 PhysicalMemory::MemoryPort::MemoryPort(const std::string
&_name
,
457 PhysicalMemory
*_memory
)
458 : SimpleTimingPort(_name
, _memory
), memory(_memory
)
462 PhysicalMemory::MemoryPort::recvRangeChange()
464 // memory is a slave and thus should never have to worry about its
465 // neighbours address ranges
469 PhysicalMemory::MemoryPort::getAddrRanges()
471 return memory
->getAddrRanges();
475 PhysicalMemory::getAddrRanges()
477 AddrRangeList ranges
;
478 ranges
.push_back(RangeSize(start(), size()));
483 PhysicalMemory::MemoryPort::deviceBlockSize() const
485 return memory
->deviceBlockSize();
489 PhysicalMemory::MemoryPort::recvAtomic(PacketPtr pkt
)
491 return memory
->doAtomicAccess(pkt
);
495 PhysicalMemory::MemoryPort::recvFunctional(PacketPtr pkt
)
497 pkt
->pushLabel(memory
->name());
499 if (!checkFunctional(pkt
)) {
500 // Default implementation of SimpleTimingPort::recvFunctional()
501 // calls recvAtomic() and throws away the latency; we can save a
502 // little here by just not calculating the latency.
503 memory
->doFunctionalAccess(pkt
);
510 PhysicalMemory::drain(Event
*de
)
513 for (PortIterator pi
= ports
.begin(); pi
!= ports
.end(); ++pi
) {
514 count
+= (*pi
)->drain(de
);
518 changeState(Draining
);
520 changeState(Drained
);
525 PhysicalMemory::serialize(ostream
&os
)
530 gzFile compressedMem
;
531 string filename
= name() + ".physmem";
533 SERIALIZE_SCALAR(filename
);
534 SERIALIZE_SCALAR(_size
);
537 string thefile
= Checkpoint::dir() + "/" + filename
.c_str();
538 int fd
= creat(thefile
.c_str(), 0664);
541 fatal("Can't open physical memory checkpoint file '%s'\n", filename
);
544 compressedMem
= gzdopen(fd
, "wb");
545 if (compressedMem
== NULL
)
546 fatal("Insufficient memory to allocate compression state for %s\n",
549 if (gzwrite(compressedMem
, pmemAddr
, size()) != (int)size()) {
550 fatal("Write failed on physical memory checkpoint file '%s'\n",
554 if (gzclose(compressedMem
))
555 fatal("Close failed on physical memory checkpoint file '%s'\n",
558 list
<LockedAddr
>::iterator i
= lockedAddrList
.begin();
560 vector
<Addr
> lal_addr
;
562 while (i
!= lockedAddrList
.end()) {
563 lal_addr
.push_back(i
->addr
);
564 lal_cid
.push_back(i
->contextId
);
567 arrayParamOut(os
, "lal_addr", lal_addr
);
568 arrayParamOut(os
, "lal_cid", lal_cid
);
572 PhysicalMemory::unserialize(Checkpoint
*cp
, const string
§ion
)
577 gzFile compressedMem
;
582 const uint32_t chunkSize
= 16384;
586 UNSERIALIZE_SCALAR(filename
);
588 filename
= cp
->cptDir
+ "/" + filename
;
591 int fd
= open(filename
.c_str(), O_RDONLY
);
594 fatal("Can't open physical memory checkpoint file '%s'", filename
);
597 compressedMem
= gzdopen(fd
, "rb");
598 if (compressedMem
== NULL
)
599 fatal("Insufficient memory to allocate compression state for %s\n",
602 // unmap file that was mmapped in the constructor
603 // This is done here to make sure that gzip and open don't muck with our
604 // nice large space of memory before we reallocate it
605 munmap((char*)pmemAddr
, size());
607 UNSERIALIZE_SCALAR(_size
);
608 if (size() > params()->range
.size())
609 fatal("Memory size has changed! size %lld, param size %lld\n",
610 size(), params()->range
.size());
612 pmemAddr
= (uint8_t *)mmap(NULL
, size(),
613 PROT_READ
| PROT_WRITE
, MAP_ANON
| MAP_PRIVATE
, -1, 0);
615 if (pmemAddr
== (void *)MAP_FAILED
) {
617 fatal("Could not mmap physical memory!\n");
621 tempPage
= (long*)malloc(chunkSize
);
622 if (tempPage
== NULL
)
623 fatal("Unable to malloc memory to read file %s\n", filename
);
625 /* Only copy bytes that are non-zero, so we don't give the VM system hell */
626 while (curSize
< size()) {
627 bytesRead
= gzread(compressedMem
, tempPage
, chunkSize
);
631 assert(bytesRead
% sizeof(long) == 0);
633 for (uint32_t x
= 0; x
< bytesRead
/ sizeof(long); x
++)
635 if (*(tempPage
+x
) != 0) {
636 pmem_current
= (long*)(pmemAddr
+ curSize
+ x
* sizeof(long));
637 *pmem_current
= *(tempPage
+x
);
640 curSize
+= bytesRead
;
645 if (gzclose(compressedMem
))
646 fatal("Close failed on physical memory checkpoint file '%s'\n",
649 vector
<Addr
> lal_addr
;
651 arrayParamIn(cp
, section
, "lal_addr", lal_addr
);
652 arrayParamIn(cp
, section
, "lal_cid", lal_cid
);
653 for(int i
= 0; i
< lal_addr
.size(); i
++)
654 lockedAddrList
.push_front(LockedAddr(lal_addr
[i
], lal_cid
[i
]));
658 PhysicalMemoryParams::create()
660 return new PhysicalMemory(this);