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