abstract_mem.cc revision 8992:e68dd2ba4fa4
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        assert(prs);
394        // Need to call printLabels() explicitly since we're not going
395        // through printObj().
396        prs->printLabels();
397        // Right now we just print the single byte at the specified address.
398        ccprintf(prs->os, "%s%#x\n", prs->curPrefix(), *hostAddr);
399    } else {
400        panic("AbstractMemory: unimplemented functional command %s",
401              pkt->cmdString());
402    }
403}
404
405void
406AbstractMemory::serialize(ostream &os)
407{
408    if (!pmemAddr)
409        return;
410
411    gzFile compressedMem;
412    string filename = name() + ".physmem";
413    long _size = range.size();
414
415    SERIALIZE_SCALAR(filename);
416    SERIALIZE_SCALAR(_size);
417
418    // write memory file
419    string thefile = Checkpoint::dir() + "/" + filename.c_str();
420    int fd = creat(thefile.c_str(), 0664);
421    if (fd < 0) {
422        perror("creat");
423        fatal("Can't open physical memory checkpoint file '%s'\n", filename);
424    }
425
426    compressedMem = gzdopen(fd, "wb");
427    if (compressedMem == NULL)
428        fatal("Insufficient memory to allocate compression state for %s\n",
429                filename);
430
431    if (gzwrite(compressedMem, pmemAddr, size()) != (int)size()) {
432        fatal("Write failed on physical memory checkpoint file '%s'\n",
433              filename);
434    }
435
436    if (gzclose(compressedMem))
437        fatal("Close failed on physical memory checkpoint file '%s'\n",
438              filename);
439
440    list<LockedAddr>::iterator i = lockedAddrList.begin();
441
442    vector<Addr> lal_addr;
443    vector<int> lal_cid;
444    while (i != lockedAddrList.end()) {
445        lal_addr.push_back(i->addr);
446        lal_cid.push_back(i->contextId);
447        i++;
448    }
449    arrayParamOut(os, "lal_addr", lal_addr);
450    arrayParamOut(os, "lal_cid", lal_cid);
451}
452
453void
454AbstractMemory::unserialize(Checkpoint *cp, const string &section)
455{
456    if (!pmemAddr)
457        return;
458
459    gzFile compressedMem;
460    long *tempPage;
461    long *pmem_current;
462    uint64_t curSize;
463    uint32_t bytesRead;
464    const uint32_t chunkSize = 16384;
465
466    string filename;
467
468    UNSERIALIZE_SCALAR(filename);
469
470    filename = cp->cptDir + "/" + filename;
471
472    // mmap memoryfile
473    int fd = open(filename.c_str(), O_RDONLY);
474    if (fd < 0) {
475        perror("open");
476        fatal("Can't open physical memory checkpoint file '%s'", filename);
477    }
478
479    compressedMem = gzdopen(fd, "rb");
480    if (compressedMem == NULL)
481        fatal("Insufficient memory to allocate compression state for %s\n",
482                filename);
483
484    // unmap file that was mmapped in the constructor
485    // This is done here to make sure that gzip and open don't muck with our
486    // nice large space of memory before we reallocate it
487    munmap((char*)pmemAddr, size());
488
489    long _size;
490    UNSERIALIZE_SCALAR(_size);
491    if (_size > params()->range.size())
492        fatal("Memory size has changed! size %lld, param size %lld\n",
493              _size, params()->range.size());
494
495    pmemAddr = (uint8_t *)mmap(NULL, size(),
496        PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
497
498    if (pmemAddr == (void *)MAP_FAILED) {
499        perror("mmap");
500        fatal("Could not mmap physical memory!\n");
501    }
502
503    curSize = 0;
504    tempPage = (long*)malloc(chunkSize);
505    if (tempPage == NULL)
506        fatal("Unable to malloc memory to read file %s\n", filename);
507
508    /* Only copy bytes that are non-zero, so we don't give the VM system hell */
509    while (curSize < size()) {
510        bytesRead = gzread(compressedMem, tempPage, chunkSize);
511        if (bytesRead == 0)
512            break;
513
514        assert(bytesRead % sizeof(long) == 0);
515
516        for (uint32_t x = 0; x < bytesRead / sizeof(long); x++)
517        {
518             if (*(tempPage+x) != 0) {
519                 pmem_current = (long*)(pmemAddr + curSize + x * sizeof(long));
520                 *pmem_current = *(tempPage+x);
521             }
522        }
523        curSize += bytesRead;
524    }
525
526    free(tempPage);
527
528    if (gzclose(compressedMem))
529        fatal("Close failed on physical memory checkpoint file '%s'\n",
530              filename);
531
532    vector<Addr> lal_addr;
533    vector<int> lal_cid;
534    arrayParamIn(cp, section, "lal_addr", lal_addr);
535    arrayParamIn(cp, section, "lal_cid", lal_cid);
536    for(int i = 0; i < lal_addr.size(); i++)
537        lockedAddrList.push_front(LockedAddr(lal_addr[i], lal_cid[i]));
538}
539