abstract_mem.cc revision 9053
1/*
2 * Copyright (c) 2010-2012 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 *          Andreas Hansson
43 */
44
45#include <sys/mman.h>
46#include <sys/types.h>
47#include <sys/user.h>
48#include <fcntl.h>
49#include <unistd.h>
50#include <zlib.h>
51
52#include <cerrno>
53#include <cstdio>
54#include <iostream>
55#include <string>
56
57#include "arch/registers.hh"
58#include "config/the_isa.hh"
59#include "debug/LLSC.hh"
60#include "debug/MemoryAccess.hh"
61#include "mem/abstract_mem.hh"
62#include "mem/packet_access.hh"
63#include "sim/system.hh"
64
65using namespace std;
66
67AbstractMemory::AbstractMemory(const Params *p) :
68    MemObject(p), range(params()->range), pmemAddr(NULL),
69    confTableReported(p->conf_table_reported), inAddrMap(p->in_addr_map),
70    _system(NULL)
71{
72    if (size() % TheISA::PageBytes != 0)
73        panic("Memory Size not divisible by page size\n");
74
75    if (params()->null)
76        return;
77
78    if (params()->file == "") {
79        int map_flags = MAP_ANON | MAP_PRIVATE;
80        pmemAddr = (uint8_t *)mmap(NULL, size(),
81                                   PROT_READ | PROT_WRITE, map_flags, -1, 0);
82    } else {
83        int map_flags = MAP_PRIVATE;
84        int fd = open(params()->file.c_str(), O_RDONLY);
85        long _size = lseek(fd, 0, SEEK_END);
86        if (_size != range.size()) {
87            warn("Specified size %d does not match file %s %d\n", range.size(),
88                 params()->file, _size);
89            range = RangeSize(range.start, _size);
90        }
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);
94    }
95
96    if (pmemAddr == (void *)MAP_FAILED) {
97        perror("mmap");
98        if (params()->file == "")
99            fatal("Could not mmap!\n");
100        else
101            fatal("Could not find file: %s\n", params()->file);
102    }
103
104    //If requested, initialize all the memory to 0
105    if (p->zero)
106        memset(pmemAddr, 0, size());
107}
108
109
110AbstractMemory::~AbstractMemory()
111{
112    if (pmemAddr)
113        munmap((char*)pmemAddr, size());
114}
115
116void
117AbstractMemory::regStats()
118{
119    using namespace Stats;
120
121    assert(system());
122
123    bytesRead
124        .init(system()->maxMasters())
125        .name(name() + ".bytes_read")
126        .desc("Number of bytes read from this memory")
127        .flags(total | nozero | nonan)
128        ;
129    for (int i = 0; i < system()->maxMasters(); i++) {
130        bytesRead.subname(i, system()->getMasterName(i));
131    }
132    bytesInstRead
133        .init(system()->maxMasters())
134        .name(name() + ".bytes_inst_read")
135        .desc("Number of instructions bytes read from this memory")
136        .flags(total | nozero | nonan)
137        ;
138    for (int i = 0; i < system()->maxMasters(); i++) {
139        bytesInstRead.subname(i, system()->getMasterName(i));
140    }
141    bytesWritten
142        .init(system()->maxMasters())
143        .name(name() + ".bytes_written")
144        .desc("Number of bytes written to this memory")
145        .flags(total | nozero | nonan)
146        ;
147    for (int i = 0; i < system()->maxMasters(); i++) {
148        bytesWritten.subname(i, system()->getMasterName(i));
149    }
150    numReads
151        .init(system()->maxMasters())
152        .name(name() + ".num_reads")
153        .desc("Number of read requests responded to by this memory")
154        .flags(total | nozero | nonan)
155        ;
156    for (int i = 0; i < system()->maxMasters(); i++) {
157        numReads.subname(i, system()->getMasterName(i));
158    }
159    numWrites
160        .init(system()->maxMasters())
161        .name(name() + ".num_writes")
162        .desc("Number of write requests responded to by this memory")
163        .flags(total | nozero | nonan)
164        ;
165    for (int i = 0; i < system()->maxMasters(); i++) {
166        numWrites.subname(i, system()->getMasterName(i));
167    }
168    numOther
169        .init(system()->maxMasters())
170        .name(name() + ".num_other")
171        .desc("Number of other requests responded to by this memory")
172        .flags(total | nozero | nonan)
173        ;
174    for (int i = 0; i < system()->maxMasters(); i++) {
175        numOther.subname(i, system()->getMasterName(i));
176    }
177    bwRead
178        .name(name() + ".bw_read")
179        .desc("Total read bandwidth from this memory (bytes/s)")
180        .precision(0)
181        .prereq(bytesRead)
182        .flags(total | nozero | nonan)
183        ;
184    for (int i = 0; i < system()->maxMasters(); i++) {
185        bwRead.subname(i, system()->getMasterName(i));
186    }
187
188    bwInstRead
189        .name(name() + ".bw_inst_read")
190        .desc("Instruction read bandwidth from this memory (bytes/s)")
191        .precision(0)
192        .prereq(bytesInstRead)
193        .flags(total | nozero | nonan)
194        ;
195    for (int i = 0; i < system()->maxMasters(); i++) {
196        bwInstRead.subname(i, system()->getMasterName(i));
197    }
198    bwWrite
199        .name(name() + ".bw_write")
200        .desc("Write bandwidth from this memory (bytes/s)")
201        .precision(0)
202        .prereq(bytesWritten)
203        .flags(total | nozero | nonan)
204        ;
205    for (int i = 0; i < system()->maxMasters(); i++) {
206        bwWrite.subname(i, system()->getMasterName(i));
207    }
208    bwTotal
209        .name(name() + ".bw_total")
210        .desc("Total bandwidth to/from this memory (bytes/s)")
211        .precision(0)
212        .prereq(bwTotal)
213        .flags(total | nozero | nonan)
214        ;
215    for (int i = 0; i < system()->maxMasters(); i++) {
216        bwTotal.subname(i, system()->getMasterName(i));
217    }
218    bwRead = bytesRead / simSeconds;
219    bwInstRead = bytesInstRead / simSeconds;
220    bwWrite = bytesWritten / simSeconds;
221    bwTotal = (bytesRead + bytesWritten) / simSeconds;
222}
223
224Range<Addr>
225AbstractMemory::getAddrRange()
226{
227    return range;
228}
229
230// Add load-locked to tracking list.  Should only be called if the
231// operation is a load and the LLSC flag is set.
232void
233AbstractMemory::trackLoadLocked(PacketPtr pkt)
234{
235    Request *req = pkt->req;
236    Addr paddr = LockedAddr::mask(req->getPaddr());
237
238    // first we check if we already have a locked addr for this
239    // xc.  Since each xc only gets one, we just update the
240    // existing record with the new address.
241    list<LockedAddr>::iterator i;
242
243    for (i = lockedAddrList.begin(); i != lockedAddrList.end(); ++i) {
244        if (i->matchesContext(req)) {
245            DPRINTF(LLSC, "Modifying lock record: context %d addr %#x\n",
246                    req->contextId(), paddr);
247            i->addr = paddr;
248            return;
249        }
250    }
251
252    // no record for this xc: need to allocate a new one
253    DPRINTF(LLSC, "Adding lock record: context %d addr %#x\n",
254            req->contextId(), paddr);
255    lockedAddrList.push_front(LockedAddr(req));
256}
257
258
259// Called on *writes* only... both regular stores and
260// store-conditional operations.  Check for conventional stores which
261// conflict with locked addresses, and for success/failure of store
262// conditionals.
263bool
264AbstractMemory::checkLockedAddrList(PacketPtr pkt)
265{
266    Request *req = pkt->req;
267    Addr paddr = LockedAddr::mask(req->getPaddr());
268    bool isLLSC = pkt->isLLSC();
269
270    // Initialize return value.  Non-conditional stores always
271    // succeed.  Assume conditional stores will fail until proven
272    // otherwise.
273    bool success = !isLLSC;
274
275    // Iterate over list.  Note that there could be multiple matching
276    // records, as more than one context could have done a load locked
277    // to this location.
278    list<LockedAddr>::iterator i = lockedAddrList.begin();
279
280    while (i != lockedAddrList.end()) {
281
282        if (i->addr == paddr) {
283            // we have a matching address
284
285            if (isLLSC && i->matchesContext(req)) {
286                // it's a store conditional, and as far as the memory
287                // system can tell, the requesting context's lock is
288                // still valid.
289                DPRINTF(LLSC, "StCond success: context %d addr %#x\n",
290                        req->contextId(), paddr);
291                success = true;
292            }
293
294            // Get rid of our record of this lock and advance to next
295            DPRINTF(LLSC, "Erasing lock record: context %d addr %#x\n",
296                    i->contextId, paddr);
297            i = lockedAddrList.erase(i);
298        }
299        else {
300            // no match: advance to next record
301            ++i;
302        }
303    }
304
305    if (isLLSC) {
306        req->setExtraData(success ? 1 : 0);
307    }
308
309    return success;
310}
311
312
313#if TRACING_ON
314
315#define CASE(A, T)                                                      \
316  case sizeof(T):                                                       \
317    DPRINTF(MemoryAccess,"%s of size %i on address 0x%x data 0x%x\n",   \
318            A, pkt->getSize(), pkt->getAddr(), pkt->get<T>());          \
319  break
320
321
322#define TRACE_PACKET(A)                                                 \
323    do {                                                                \
324        switch (pkt->getSize()) {                                       \
325          CASE(A, uint64_t);                                            \
326          CASE(A, uint32_t);                                            \
327          CASE(A, uint16_t);                                            \
328          CASE(A, uint8_t);                                             \
329          default:                                                      \
330            DPRINTF(MemoryAccess, "%s of size %i on address 0x%x\n",    \
331                    A, pkt->getSize(), pkt->getAddr());                 \
332            DDUMP(MemoryAccess, pkt->getPtr<uint8_t>(), pkt->getSize());\
333        }                                                               \
334    } while (0)
335
336#else
337
338#define TRACE_PACKET(A)
339
340#endif
341
342void
343AbstractMemory::access(PacketPtr pkt)
344{
345    assert(pkt->getAddr() >= range.start &&
346           (pkt->getAddr() + pkt->getSize() - 1) <= range.end);
347
348    if (pkt->memInhibitAsserted()) {
349        DPRINTF(MemoryAccess, "mem inhibited on 0x%x: not responding\n",
350                pkt->getAddr());
351        return;
352    }
353
354    uint8_t *hostAddr = pmemAddr + pkt->getAddr() - range.start;
355
356    if (pkt->cmd == MemCmd::SwapReq) {
357        TheISA::IntReg overwrite_val;
358        bool overwrite_mem;
359        uint64_t condition_val64;
360        uint32_t condition_val32;
361
362        if (!pmemAddr)
363            panic("Swap only works if there is real memory (i.e. null=False)");
364        assert(sizeof(TheISA::IntReg) >= pkt->getSize());
365
366        overwrite_mem = true;
367        // keep a copy of our possible write value, and copy what is at the
368        // memory address into the packet
369        std::memcpy(&overwrite_val, pkt->getPtr<uint8_t>(), pkt->getSize());
370        std::memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
371
372        if (pkt->req->isCondSwap()) {
373            if (pkt->getSize() == sizeof(uint64_t)) {
374                condition_val64 = pkt->req->getExtraData();
375                overwrite_mem = !std::memcmp(&condition_val64, hostAddr,
376                                             sizeof(uint64_t));
377            } else if (pkt->getSize() == sizeof(uint32_t)) {
378                condition_val32 = (uint32_t)pkt->req->getExtraData();
379                overwrite_mem = !std::memcmp(&condition_val32, hostAddr,
380                                             sizeof(uint32_t));
381            } else
382                panic("Invalid size for conditional read/write\n");
383        }
384
385        if (overwrite_mem)
386            std::memcpy(hostAddr, &overwrite_val, pkt->getSize());
387
388        assert(!pkt->req->isInstFetch());
389        TRACE_PACKET("Read/Write");
390        numOther[pkt->req->masterId()]++;
391    } else if (pkt->isRead()) {
392        assert(!pkt->isWrite());
393        if (pkt->isLLSC()) {
394            trackLoadLocked(pkt);
395        }
396        if (pmemAddr)
397            memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
398        TRACE_PACKET(pkt->req->isInstFetch() ? "IFetch" : "Read");
399        numReads[pkt->req->masterId()]++;
400        bytesRead[pkt->req->masterId()] += pkt->getSize();
401        if (pkt->req->isInstFetch())
402            bytesInstRead[pkt->req->masterId()] += pkt->getSize();
403    } else if (pkt->isWrite()) {
404        if (writeOK(pkt)) {
405            if (pmemAddr)
406                memcpy(hostAddr, pkt->getPtr<uint8_t>(), pkt->getSize());
407            assert(!pkt->req->isInstFetch());
408            TRACE_PACKET("Write");
409            numWrites[pkt->req->masterId()]++;
410            bytesWritten[pkt->req->masterId()] += pkt->getSize();
411        }
412    } else if (pkt->isInvalidate()) {
413        // no need to do anything
414    } else {
415        panic("unimplemented");
416    }
417
418    if (pkt->needsResponse()) {
419        pkt->makeResponse();
420    }
421}
422
423void
424AbstractMemory::functionalAccess(PacketPtr pkt)
425{
426    assert(pkt->getAddr() >= range.start &&
427           (pkt->getAddr() + pkt->getSize() - 1) <= range.end);
428
429    uint8_t *hostAddr = pmemAddr + pkt->getAddr() - range.start;
430
431    if (pkt->isRead()) {
432        if (pmemAddr)
433            memcpy(pkt->getPtr<uint8_t>(), hostAddr, pkt->getSize());
434        TRACE_PACKET("Read");
435        pkt->makeResponse();
436    } else if (pkt->isWrite()) {
437        if (pmemAddr)
438            memcpy(hostAddr, pkt->getPtr<uint8_t>(), pkt->getSize());
439        TRACE_PACKET("Write");
440        pkt->makeResponse();
441    } else if (pkt->isPrint()) {
442        Packet::PrintReqState *prs =
443            dynamic_cast<Packet::PrintReqState*>(pkt->senderState);
444        assert(prs);
445        // Need to call printLabels() explicitly since we're not going
446        // through printObj().
447        prs->printLabels();
448        // Right now we just print the single byte at the specified address.
449        ccprintf(prs->os, "%s%#x\n", prs->curPrefix(), *hostAddr);
450    } else {
451        panic("AbstractMemory: unimplemented functional command %s",
452              pkt->cmdString());
453    }
454}
455
456void
457AbstractMemory::serialize(ostream &os)
458{
459    if (!pmemAddr)
460        return;
461
462    gzFile compressedMem;
463    string filename = name() + ".physmem";
464    long _size = range.size();
465
466    SERIALIZE_SCALAR(filename);
467    SERIALIZE_SCALAR(_size);
468
469    // write memory file
470    string thefile = Checkpoint::dir() + "/" + filename.c_str();
471    int fd = creat(thefile.c_str(), 0664);
472    if (fd < 0) {
473        perror("creat");
474        fatal("Can't open physical memory checkpoint file '%s'\n", filename);
475    }
476
477    compressedMem = gzdopen(fd, "wb");
478    if (compressedMem == NULL)
479        fatal("Insufficient memory to allocate compression state for %s\n",
480                filename);
481
482    if (gzwrite(compressedMem, pmemAddr, size()) != (int)size()) {
483        fatal("Write failed on physical memory checkpoint file '%s'\n",
484              filename);
485    }
486
487    if (gzclose(compressedMem))
488        fatal("Close failed on physical memory checkpoint file '%s'\n",
489              filename);
490
491    list<LockedAddr>::iterator i = lockedAddrList.begin();
492
493    vector<Addr> lal_addr;
494    vector<int> lal_cid;
495    while (i != lockedAddrList.end()) {
496        lal_addr.push_back(i->addr);
497        lal_cid.push_back(i->contextId);
498        i++;
499    }
500    arrayParamOut(os, "lal_addr", lal_addr);
501    arrayParamOut(os, "lal_cid", lal_cid);
502}
503
504void
505AbstractMemory::unserialize(Checkpoint *cp, const string &section)
506{
507    if (!pmemAddr)
508        return;
509
510    gzFile compressedMem;
511    long *tempPage;
512    long *pmem_current;
513    uint64_t curSize;
514    uint32_t bytesRead;
515    const uint32_t chunkSize = 16384;
516
517    string filename;
518
519    UNSERIALIZE_SCALAR(filename);
520
521    filename = cp->cptDir + "/" + filename;
522
523    // mmap memoryfile
524    int fd = open(filename.c_str(), O_RDONLY);
525    if (fd < 0) {
526        perror("open");
527        fatal("Can't open physical memory checkpoint file '%s'", filename);
528    }
529
530    compressedMem = gzdopen(fd, "rb");
531    if (compressedMem == NULL)
532        fatal("Insufficient memory to allocate compression state for %s\n",
533                filename);
534
535    // unmap file that was mmapped in the constructor
536    // This is done here to make sure that gzip and open don't muck with our
537    // nice large space of memory before we reallocate it
538    munmap((char*)pmemAddr, size());
539
540    long _size;
541    UNSERIALIZE_SCALAR(_size);
542    if (_size > params()->range.size())
543        fatal("Memory size has changed! size %lld, param size %lld\n",
544              _size, params()->range.size());
545
546    pmemAddr = (uint8_t *)mmap(NULL, size(),
547        PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
548
549    if (pmemAddr == (void *)MAP_FAILED) {
550        perror("mmap");
551        fatal("Could not mmap physical memory!\n");
552    }
553
554    curSize = 0;
555    tempPage = (long*)malloc(chunkSize);
556    if (tempPage == NULL)
557        fatal("Unable to malloc memory to read file %s\n", filename);
558
559    /* Only copy bytes that are non-zero, so we don't give the VM system hell */
560    while (curSize < size()) {
561        bytesRead = gzread(compressedMem, tempPage, chunkSize);
562        if (bytesRead == 0)
563            break;
564
565        assert(bytesRead % sizeof(long) == 0);
566
567        for (uint32_t x = 0; x < bytesRead / sizeof(long); x++)
568        {
569             if (*(tempPage+x) != 0) {
570                 pmem_current = (long*)(pmemAddr + curSize + x * sizeof(long));
571                 *pmem_current = *(tempPage+x);
572             }
573        }
574        curSize += bytesRead;
575    }
576
577    free(tempPage);
578
579    if (gzclose(compressedMem))
580        fatal("Close failed on physical memory checkpoint file '%s'\n",
581              filename);
582
583    vector<Addr> lal_addr;
584    vector<int> lal_cid;
585    arrayParamIn(cp, section, "lal_addr", lal_addr);
586    arrayParamIn(cp, section, "lal_cid", lal_cid);
587    for(int i = 0; i < lal_addr.size(); i++)
588        lockedAddrList.push_front(LockedAddr(lal_addr[i], lal_cid[i]));
589}
590