Deleted Added
sdiff udiff text old ( 8066:cb7bf3919bdd ) new ( 8077:7544ad480a38 )
full compact
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 } \
248 } while (0)
249
250#else
251
252#define TRACE_PACKET(A)
253
254#endif
255
256Tick
257PhysicalMemory::doAtomicAccess(PacketPtr pkt)
258{
259 assert(pkt->getAddr() >= start() &&
260 pkt->getAddr() + pkt->getSize() <= start() + size());
261
262 if (pkt->memInhibitAsserted()) {
263 DPRINTF(MemoryAccess, "mem inhibited on 0x%x: not responding\n",
264 pkt->getAddr());
265 return 0;
266 }
267
268 uint8_t *hostAddr = pmemAddr + pkt->getAddr() - start();
269
270 if (pkt->cmd == MemCmd::SwapReq) {
271 IntReg overwrite_val;
272 bool overwrite_mem;
273 uint64_t condition_val64;
274 uint32_t condition_val32;
275
276 if (!pmemAddr)
277 panic("Swap only works if there is real memory (i.e. null=False)");
278 assert(sizeof(IntReg) >= pkt->getSize());
279
280 overwrite_mem = true;
281 // keep a copy of our possible write value, and copy what is at the
282 // memory address into the packet
283 std::memcpy(&overwrite_val, pkt->getPtr<uint8_t>(), pkt->getSize());
284 std::memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
285
286 if (pkt->req->isCondSwap()) {
287 if (pkt->getSize() == sizeof(uint64_t)) {
288 condition_val64 = pkt->req->getExtraData();
289 overwrite_mem = !std::memcmp(&condition_val64, hostAddr,
290 sizeof(uint64_t));
291 } else if (pkt->getSize() == sizeof(uint32_t)) {
292 condition_val32 = (uint32_t)pkt->req->getExtraData();
293 overwrite_mem = !std::memcmp(&condition_val32, hostAddr,
294 sizeof(uint32_t));
295 } else
296 panic("Invalid size for conditional read/write\n");
297 }
298
299 if (overwrite_mem)
300 std::memcpy(hostAddr, &overwrite_val, pkt->getSize());
301
302 assert(!pkt->req->isInstFetch());
303 TRACE_PACKET("Read/Write");
304 } else if (pkt->isRead()) {
305 assert(!pkt->isWrite());
306 if (pkt->isLLSC()) {
307 trackLoadLocked(pkt);
308 }
309 if (pmemAddr)
310 memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
311 TRACE_PACKET(pkt->req->isInstFetch() ? "IFetch" : "Read");
312 } else if (pkt->isWrite()) {
313 if (writeOK(pkt)) {
314 if (pmemAddr)
315 memcpy(hostAddr, pkt->getPtr<uint8_t>(), pkt->getSize());
316 assert(!pkt->req->isInstFetch());
317 TRACE_PACKET("Write");
318 }
319 } else if (pkt->isInvalidate()) {
320 //upgrade or invalidate
321 if (pkt->needsResponse()) {
322 pkt->makeAtomicResponse();
323 }
324 } else {
325 panic("unimplemented");
326 }
327
328 if (pkt->needsResponse()) {
329 pkt->makeAtomicResponse();
330 }
331 return calculateLatency(pkt);
332}
333
334
335void
336PhysicalMemory::doFunctionalAccess(PacketPtr pkt)
337{
338 assert(pkt->getAddr() >= start() &&
339 pkt->getAddr() + pkt->getSize() <= start() + size());
340
341
342 uint8_t *hostAddr = pmemAddr + pkt->getAddr() - start();
343
344 if (pkt->isRead()) {
345 if (pmemAddr)
346 memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
347 TRACE_PACKET("Read");
348 pkt->makeAtomicResponse();
349 } else if (pkt->isWrite()) {
350 if (pmemAddr)
351 memcpy(hostAddr, pkt->getPtr<uint8_t>(), pkt->getSize());
352 TRACE_PACKET("Write");
353 pkt->makeAtomicResponse();
354 } else if (pkt->isPrint()) {
355 Packet::PrintReqState *prs =
356 dynamic_cast<Packet::PrintReqState*>(pkt->senderState);
357 // Need to call printLabels() explicitly since we're not going
358 // through printObj().
359 prs->printLabels();
360 // Right now we just print the single byte at the specified address.
361 ccprintf(prs->os, "%s%#x\n", prs->curPrefix(), *hostAddr);
362 } else {
363 panic("PhysicalMemory: unimplemented functional command %s",
364 pkt->cmdString());
365 }
366}
367
368
369Port *
370PhysicalMemory::getPort(const std::string &if_name, int idx)
371{
372 // Accept request for "functional" port for backwards compatibility
373 // with places where this function is called from C++. I'd prefer
374 // to move all these into Python someday.
375 if (if_name == "functional") {
376 return new MemoryPort(csprintf("%s-functional", name()), this);
377 }
378
379 if (if_name != "port") {
380 panic("PhysicalMemory::getPort: unknown port %s requested", if_name);
381 }
382
383 if (idx >= (int)ports.size()) {
384 ports.resize(idx + 1);
385 }
386
387 if (ports[idx] != NULL) {
388 panic("PhysicalMemory::getPort: port %d already assigned", idx);
389 }
390
391 MemoryPort *port =
392 new MemoryPort(csprintf("%s-port%d", name(), idx), this);
393
394 ports[idx] = port;
395 return port;
396}
397
398
399void
400PhysicalMemory::recvStatusChange(Port::Status status)
401{
402}
403
404PhysicalMemory::MemoryPort::MemoryPort(const std::string &_name,
405 PhysicalMemory *_memory)
406 : SimpleTimingPort(_name, _memory), memory(_memory)
407{ }
408
409void
410PhysicalMemory::MemoryPort::recvStatusChange(Port::Status status)
411{
412 memory->recvStatusChange(status);
413}
414
415void
416PhysicalMemory::MemoryPort::getDeviceAddressRanges(AddrRangeList &resp,
417 bool &snoop)
418{
419 memory->getAddressRanges(resp, snoop);
420}
421
422void
423PhysicalMemory::getAddressRanges(AddrRangeList &resp, bool &snoop)
424{
425 snoop = false;
426 resp.clear();
427 resp.push_back(RangeSize(start(), size()));
428}
429
430unsigned
431PhysicalMemory::MemoryPort::deviceBlockSize() const
432{
433 return memory->deviceBlockSize();
434}
435
436Tick
437PhysicalMemory::MemoryPort::recvAtomic(PacketPtr pkt)
438{
439 return memory->doAtomicAccess(pkt);
440}
441
442void
443PhysicalMemory::MemoryPort::recvFunctional(PacketPtr pkt)
444{
445 pkt->pushLabel(memory->name());
446
447 if (!checkFunctional(pkt)) {
448 // Default implementation of SimpleTimingPort::recvFunctional()
449 // calls recvAtomic() and throws away the latency; we can save a
450 // little here by just not calculating the latency.
451 memory->doFunctionalAccess(pkt);
452 }
453
454 pkt->popLabel();
455}
456
457unsigned int
458PhysicalMemory::drain(Event *de)
459{
460 int count = 0;
461 for (PortIterator pi = ports.begin(); pi != ports.end(); ++pi) {
462 count += (*pi)->drain(de);
463 }
464
465 if (count)
466 changeState(Draining);
467 else
468 changeState(Drained);
469 return count;
470}
471
472void
473PhysicalMemory::serialize(ostream &os)
474{
475 if (!pmemAddr)
476 return;
477
478 gzFile compressedMem;
479 string filename = name() + ".physmem";
480
481 SERIALIZE_SCALAR(filename);
482 SERIALIZE_SCALAR(_size);
483
484 // write memory file
485 string thefile = Checkpoint::dir() + "/" + filename.c_str();
486 int fd = creat(thefile.c_str(), 0664);
487 if (fd < 0) {
488 perror("creat");
489 fatal("Can't open physical memory checkpoint file '%s'\n", filename);
490 }
491
492 compressedMem = gzdopen(fd, "wb");
493 if (compressedMem == NULL)
494 fatal("Insufficient memory to allocate compression state for %s\n",
495 filename);
496
497 if (gzwrite(compressedMem, pmemAddr, size()) != (int)size()) {
498 fatal("Write failed on physical memory checkpoint file '%s'\n",
499 filename);
500 }
501
502 if (gzclose(compressedMem))
503 fatal("Close failed on physical memory checkpoint file '%s'\n",
504 filename);
505
506 list<LockedAddr>::iterator i = lockedAddrList.begin();
507
508 vector<Addr> lal_addr;
509 vector<int> lal_cid;
510 while (i != lockedAddrList.end()) {
511 lal_addr.push_back(i->addr);
512 lal_cid.push_back(i->contextId);
513 i++;
514 }
515 arrayParamOut(os, "lal_addr", lal_addr);
516 arrayParamOut(os, "lal_cid", lal_cid);
517}
518
519void
520PhysicalMemory::unserialize(Checkpoint *cp, const string &section)
521{
522 if (!pmemAddr)
523 return;
524
525 gzFile compressedMem;
526 long *tempPage;
527 long *pmem_current;
528 uint64_t curSize;
529 uint32_t bytesRead;
530 const uint32_t chunkSize = 16384;
531
532 string filename;
533
534 UNSERIALIZE_SCALAR(filename);
535
536 filename = cp->cptDir + "/" + filename;
537
538 // mmap memoryfile
539 int fd = open(filename.c_str(), O_RDONLY);
540 if (fd < 0) {
541 perror("open");
542 fatal("Can't open physical memory checkpoint file '%s'", filename);
543 }
544
545 compressedMem = gzdopen(fd, "rb");
546 if (compressedMem == NULL)
547 fatal("Insufficient memory to allocate compression state for %s\n",
548 filename);
549
550 // unmap file that was mmaped in the constructor
551 // This is done here to make sure that gzip and open don't muck with our
552 // nice large space of memory before we reallocate it
553 munmap((char*)pmemAddr, size());
554
555 UNSERIALIZE_SCALAR(_size);
556 if (size() > params()->range.size())
557 fatal("Memory size has changed!\n");
558
559 pmemAddr = (uint8_t *)mmap(NULL, size(),
560 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
561
562 if (pmemAddr == (void *)MAP_FAILED) {
563 perror("mmap");
564 fatal("Could not mmap physical memory!\n");
565 }
566
567 curSize = 0;
568 tempPage = (long*)malloc(chunkSize);
569 if (tempPage == NULL)
570 fatal("Unable to malloc memory to read file %s\n", filename);
571
572 /* Only copy bytes that are non-zero, so we don't give the VM system hell */
573 while (curSize < size()) {
574 bytesRead = gzread(compressedMem, tempPage, chunkSize);
575 if (bytesRead == 0)
576 break;
577
578 assert(bytesRead % sizeof(long) == 0);
579
580 for (uint32_t x = 0; x < bytesRead / sizeof(long); x++)
581 {
582 if (*(tempPage+x) != 0) {
583 pmem_current = (long*)(pmemAddr + curSize + x * sizeof(long));
584 *pmem_current = *(tempPage+x);
585 }
586 }
587 curSize += bytesRead;
588 }
589
590 free(tempPage);
591
592 if (gzclose(compressedMem))
593 fatal("Close failed on physical memory checkpoint file '%s'\n",
594 filename);
595
596 vector<Addr> lal_addr;
597 vector<int> lal_cid;
598 arrayParamIn(cp, section, "lal_addr", lal_addr);
599 arrayParamIn(cp, section, "lal_cid", lal_cid);
600 for(int i = 0; i < lal_addr.size(); i++)
601 lockedAddrList.push_front(LockedAddr(lal_addr[i], lal_cid[i]));
602}
603
604PhysicalMemory *
605PhysicalMemoryParams::create()
606{
607 return new PhysicalMemory(this);
608}