abstract_mem.cc revision 9053
1545SN/A/*
21762SN/A * Copyright (c) 2010-2012 ARM Limited
3545SN/A * All rights reserved
4545SN/A *
5545SN/A * The license below extends only to copyright in the software and shall
6545SN/A * not be construed as granting a license to any other intellectual
7545SN/A * property including but not limited to intellectual property relating
8545SN/A * to a hardware implementation of the functionality of the software
9545SN/A * licensed hereunder.  You may use the software subject to the license
10545SN/A * terms below provided that you ensure that this notice is replicated
11545SN/A * unmodified and in its entirety in all distributions of the software,
12545SN/A * modified or unmodified, in source code or in binary form.
13545SN/A *
14545SN/A * Copyright (c) 2001-2005 The Regents of The University of Michigan
15545SN/A * All rights reserved.
16545SN/A *
17545SN/A * Redistribution and use in source and binary forms, with or without
18545SN/A * modification, are permitted provided that the following conditions are
19545SN/A * met: redistributions of source code must retain the above copyright
20545SN/A * notice, this list of conditions and the following disclaimer;
21545SN/A * redistributions in binary form must reproduce the above copyright
22545SN/A * notice, this list of conditions and the following disclaimer in the
23545SN/A * documentation and/or other materials provided with the distribution;
24545SN/A * neither the name of the copyright holders nor the names of its
25545SN/A * contributors may be used to endorse or promote products derived from
26545SN/A * this software without specific prior written permission.
272665Ssaidi@eecs.umich.edu *
282665Ssaidi@eecs.umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
292665Ssaidi@eecs.umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30545SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31545SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
321310SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
331310SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34545SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
352542SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
363348Sbinkertn@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
373348Sbinkertn@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
382489SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39545SN/A *
403090Sstever@eecs.umich.edu * Authors: Ron Dreslinski
411310SN/A *          Ali Saidi
422384SN/A *          Andreas Hansson
432489SN/A */
442522SN/A
45545SN/A#include <sys/mman.h>
462489SN/A#include <sys/types.h>
472489SN/A#include <sys/user.h>
482489SN/A#include <fcntl.h>
492489SN/A#include <unistd.h>
502489SN/A#include <zlib.h>
513090Sstever@eecs.umich.edu
523090Sstever@eecs.umich.edu#include <cerrno>
532914Ssaidi@eecs.umich.edu#include <cstdio>
54545SN/A#include <iostream>
55545SN/A#include <string>
562489SN/A
572384SN/A#include "arch/registers.hh"
582384SN/A#include "config/the_isa.hh"
593349Sbinkertn@umich.edu#include "debug/LLSC.hh"
602384SN/A#include "debug/MemoryAccess.hh"
613090Sstever@eecs.umich.edu#include "mem/abstract_mem.hh"
624475Sstever@eecs.umich.edu#include "mem/packet_access.hh"
632384SN/A#include "sim/system.hh"
642384SN/A
653091Sstever@eecs.umich.eduusing namespace std;
662901Ssaidi@eecs.umich.edu
672384SN/AAbstractMemory::AbstractMemory(const Params *p) :
682384SN/A    MemObject(p), range(params()->range), pmemAddr(NULL),
692565SN/A    confTableReported(p->conf_table_reported), inAddrMap(p->in_addr_map),
702384SN/A    _system(NULL)
712384SN/A{
722384SN/A    if (size() % TheISA::PageBytes != 0)
732784Ssaidi@eecs.umich.edu        panic("Memory Size not divisible by page size\n");
742784Ssaidi@eecs.umich.edu
752784Ssaidi@eecs.umich.edu    if (params()->null)
762784Ssaidi@eecs.umich.edu        return;
772784Ssaidi@eecs.umich.edu
782784Ssaidi@eecs.umich.edu    if (params()->file == "") {
792784Ssaidi@eecs.umich.edu        int map_flags = MAP_ANON | MAP_PRIVATE;
802784Ssaidi@eecs.umich.edu        pmemAddr = (uint8_t *)mmap(NULL, size(),
812784Ssaidi@eecs.umich.edu                                   PROT_READ | PROT_WRITE, map_flags, -1, 0);
822784Ssaidi@eecs.umich.edu    } else {
832784Ssaidi@eecs.umich.edu        int map_flags = MAP_PRIVATE;
842784Ssaidi@eecs.umich.edu        int fd = open(params()->file.c_str(), O_RDONLY);
852784Ssaidi@eecs.umich.edu        long _size = lseek(fd, 0, SEEK_END);
862784Ssaidi@eecs.umich.edu        if (_size != range.size()) {
872784Ssaidi@eecs.umich.edu            warn("Specified size %d does not match file %s %d\n", range.size(),
882784Ssaidi@eecs.umich.edu                 params()->file, _size);
892784Ssaidi@eecs.umich.edu            range = RangeSize(range.start, _size);
902784Ssaidi@eecs.umich.edu        }
912784Ssaidi@eecs.umich.edu        lseek(fd, 0, SEEK_SET);
922784Ssaidi@eecs.umich.edu        pmemAddr = (uint8_t *)mmap(NULL, roundUp(_size, sysconf(_SC_PAGESIZE)),
932565SN/A                                   PROT_READ | PROT_WRITE, map_flags, fd, 0);
943349Sbinkertn@umich.edu    }
952384SN/A
962901Ssaidi@eecs.umich.edu    if (pmemAddr == (void *)MAP_FAILED) {
972565SN/A        perror("mmap");
982901Ssaidi@eecs.umich.edu        if (params()->file == "")
992565SN/A            fatal("Could not mmap!\n");
1002565SN/A        else
1012565SN/A            fatal("Could not find file: %s\n", params()->file);
1022384SN/A    }
1032901Ssaidi@eecs.umich.edu
1042901Ssaidi@eecs.umich.edu    //If requested, initialize all the memory to 0
1052901Ssaidi@eecs.umich.edu    if (p->zero)
1062901Ssaidi@eecs.umich.edu        memset(pmemAddr, 0, size());
1072901Ssaidi@eecs.umich.edu}
1082901Ssaidi@eecs.umich.edu
1092901Ssaidi@eecs.umich.edu
1104435Ssaidi@eecs.umich.eduAbstractMemory::~AbstractMemory()
1114435Ssaidi@eecs.umich.edu{
1124435Ssaidi@eecs.umich.edu    if (pmemAddr)
1134435Ssaidi@eecs.umich.edu        munmap((char*)pmemAddr, size());
1144435Ssaidi@eecs.umich.edu}
1154435Ssaidi@eecs.umich.edu
1164435Ssaidi@eecs.umich.eduvoid
1174435Ssaidi@eecs.umich.eduAbstractMemory::regStats()
1183349Sbinkertn@umich.edu{
1193349Sbinkertn@umich.edu    using namespace Stats;
1203918Ssaidi@eecs.umich.edu
1213349Sbinkertn@umich.edu    assert(system());
1222384SN/A
1232384SN/A    bytesRead
1242384SN/A        .init(system()->maxMasters())
1252384SN/A        .name(name() + ".bytes_read")
1262384SN/A        .desc("Number of bytes read from this memory")
1272657Ssaidi@eecs.umich.edu        .flags(total | nozero | nonan)
1282384SN/A        ;
1293090Sstever@eecs.umich.edu    for (int i = 0; i < system()->maxMasters(); i++) {
1304475Sstever@eecs.umich.edu        bytesRead.subname(i, system()->getMasterName(i));
1314475Sstever@eecs.umich.edu    }
1322384SN/A    bytesInstRead
1334435Ssaidi@eecs.umich.edu        .init(system()->maxMasters())
1344435Ssaidi@eecs.umich.edu        .name(name() + ".bytes_inst_read")
1354435Ssaidi@eecs.umich.edu        .desc("Number of instructions bytes read from this memory")
1364435Ssaidi@eecs.umich.edu        .flags(total | nozero | nonan)
1374435Ssaidi@eecs.umich.edu        ;
1382489SN/A    for (int i = 0; i < system()->maxMasters(); i++) {
1392384SN/A        bytesInstRead.subname(i, system()->getMasterName(i));
1402901Ssaidi@eecs.umich.edu    }
1412565SN/A    bytesWritten
1422641Sstever@eecs.umich.edu        .init(system()->maxMasters())
1432641Sstever@eecs.umich.edu        .name(name() + ".bytes_written")
1442565SN/A        .desc("Number of bytes written to this memory")
1452565SN/A        .flags(total | nozero | nonan)
1462384SN/A        ;
1474263Ssaidi@eecs.umich.edu    for (int i = 0; i < system()->maxMasters(); i++) {
1482901Ssaidi@eecs.umich.edu        bytesWritten.subname(i, system()->getMasterName(i));
1492384SN/A    }
1502384SN/A    numReads
1512489SN/A        .init(system()->maxMasters())
1522489SN/A        .name(name() + ".num_reads")
1532489SN/A        .desc("Number of read requests responded to by this memory")
1542489SN/A        .flags(total | nozero | nonan)
1552489SN/A        ;
1562489SN/A    for (int i = 0; i < system()->maxMasters(); i++) {
1572489SN/A        numReads.subname(i, system()->getMasterName(i));
1582542SN/A    }
1592384SN/A    numWrites
1602384SN/A        .init(system()->maxMasters())
1612384SN/A        .name(name() + ".num_writes")
1622489SN/A        .desc("Number of write requests responded to by this memory")
1632489SN/A        .flags(total | nozero | nonan)
1641310SN/A        ;
1652384SN/A    for (int i = 0; i < system()->maxMasters(); i++) {
1662901Ssaidi@eecs.umich.edu        numWrites.subname(i, system()->getMasterName(i));
1672901Ssaidi@eecs.umich.edu    }
1682489SN/A    numOther
1692489SN/A        .init(system()->maxMasters())
1702384SN/A        .name(name() + ".num_other")
1712384SN/A        .desc("Number of other requests responded to by this memory")
1722521SN/A        .flags(total | nozero | nonan)
1732384SN/A        ;
1743090Sstever@eecs.umich.edu    for (int i = 0; i < system()->maxMasters(); i++) {
1753090Sstever@eecs.umich.edu        numOther.subname(i, system()->getMasterName(i));
1762523SN/A    }
1772523SN/A    bwRead
1782523SN/A        .name(name() + ".bw_read")
1793349Sbinkertn@umich.edu        .desc("Total read bandwidth from this memory (bytes/s)")
1802384SN/A        .precision(0)
1812489SN/A        .prereq(bytesRead)
1822523SN/A        .flags(total | nozero | nonan)
1832523SN/A        ;
1842523SN/A    for (int i = 0; i < system()->maxMasters(); i++) {
1852523SN/A        bwRead.subname(i, system()->getMasterName(i));
1863349Sbinkertn@umich.edu    }
187545SN/A
188545SN/A    bwInstRead
1893090Sstever@eecs.umich.edu        .name(name() + ".bw_inst_read")
1903090Sstever@eecs.umich.edu        .desc("Instruction read bandwidth from this memory (bytes/s)")
1913090Sstever@eecs.umich.edu        .precision(0)
1922512SN/A        .prereq(bytesInstRead)
1932512SN/A        .flags(total | nozero | nonan)
1942512SN/A        ;
1952512SN/A    for (int i = 0; i < system()->maxMasters(); i++) {
1962522SN/A        bwInstRead.subname(i, system()->getMasterName(i));
1972512SN/A    }
1982521SN/A    bwWrite
1992512SN/A        .name(name() + ".bw_write")
2002512SN/A        .desc("Write bandwidth from this memory (bytes/s)")
2012512SN/A        .precision(0)
2022512SN/A        .prereq(bytesWritten)
2032512SN/A        .flags(total | nozero | nonan)
2042512SN/A        ;
2052521SN/A    for (int i = 0; i < system()->maxMasters(); i++) {
2062901Ssaidi@eecs.umich.edu        bwWrite.subname(i, system()->getMasterName(i));
2072901Ssaidi@eecs.umich.edu    }
2082512SN/A    bwTotal
2092384SN/A        .name(name() + ".bw_total")
210545SN/A        .desc("Total bandwidth to/from this memory (bytes/s)")
2112384SN/A        .precision(0)
2122541SN/A        .prereq(bwTotal)
2132541SN/A        .flags(total | nozero | nonan)
2142901Ssaidi@eecs.umich.edu        ;
2152901Ssaidi@eecs.umich.edu    for (int i = 0; i < system()->maxMasters(); i++) {
2162738Sstever@eecs.umich.edu        bwTotal.subname(i, system()->getMasterName(i));
2172384SN/A    }
2182521SN/A    bwRead = bytesRead / simSeconds;
2192512SN/A    bwInstRead = bytesInstRead / simSeconds;
2202512SN/A    bwWrite = bytesWritten / simSeconds;
2212901Ssaidi@eecs.umich.edu    bwTotal = (bytesRead + bytesWritten) / simSeconds;
2222384SN/A}
2232521SN/A
2242384SN/ARange<Addr>
2252384SN/AAbstractMemory::getAddrRange()
2262489SN/A{
2272489SN/A    return range;
228545SN/A}
229545SN/A
2302512SN/A// Add load-locked to tracking list.  Should only be called if the
2312512SN/A// operation is a load and the LLSC flag is set.
2322512SN/Avoid
2332521SN/AAbstractMemory::trackLoadLocked(PacketPtr pkt)
2342512SN/A{
2352512SN/A    Request *req = pkt->req;
2362512SN/A    Addr paddr = LockedAddr::mask(req->getPaddr());
2372512SN/A
2382512SN/A    // first we check if we already have a locked addr for this
2392512SN/A    // xc.  Since each xc only gets one, we just update the
2402512SN/A    // existing record with the new address.
2412512SN/A    list<LockedAddr>::iterator i;
2422512SN/A
2432512SN/A    for (i = lockedAddrList.begin(); i != lockedAddrList.end(); ++i) {
2442521SN/A        if (i->matchesContext(req)) {
2452512SN/A            DPRINTF(LLSC, "Modifying lock record: context %d addr %#x\n",
2462512SN/A                    req->contextId(), paddr);
2472512SN/A            i->addr = paddr;
2482512SN/A            return;
2492512SN/A        }
2502521SN/A    }
2513090Sstever@eecs.umich.edu
2523090Sstever@eecs.umich.edu    // no record for this xc: need to allocate a new one
2532512SN/A    DPRINTF(LLSC, "Adding lock record: context %d addr %#x\n",
2542512SN/A            req->contextId(), paddr);
2552539SN/A    lockedAddrList.push_front(LockedAddr(req));
2562982Sstever@eecs.umich.edu}
2572539SN/A
2582542SN/A
2592539SN/A// Called on *writes* only... both regular stores and
2602512SN/A// store-conditional operations.  Check for conventional stores which
2612512SN/A// conflict with locked addresses, and for success/failure of store
262545SN/A// conditionals.
263545SN/Abool
2644435Ssaidi@eecs.umich.eduAbstractMemory::checkLockedAddrList(PacketPtr pkt)
2654435Ssaidi@eecs.umich.edu{
2664435Ssaidi@eecs.umich.edu    Request *req = pkt->req;
2674435Ssaidi@eecs.umich.edu    Addr paddr = LockedAddr::mask(req->getPaddr());
2684435Ssaidi@eecs.umich.edu    bool isLLSC = pkt->isLLSC();
2694435Ssaidi@eecs.umich.edu
2704435Ssaidi@eecs.umich.edu    // Initialize return value.  Non-conditional stores always
2714435Ssaidi@eecs.umich.edu    // succeed.  Assume conditional stores will fail until proven
2722384SN/A    // otherwise.
2734435Ssaidi@eecs.umich.edu    bool success = !isLLSC;
2744435Ssaidi@eecs.umich.edu
275545SN/A    // Iterate over list.  Note that there could be multiple matching
276545SN/A    // records, as more than one context could have done a load locked
2772521SN/A    // to this location.
278545SN/A    list<LockedAddr>::iterator i = lockedAddrList.begin();
2792384SN/A
2802565SN/A    while (i != lockedAddrList.end()) {
2814022Sstever@eecs.umich.edu
2824022Sstever@eecs.umich.edu        if (i->addr == paddr) {
2834022Sstever@eecs.umich.edu            // we have a matching address
2844022Sstever@eecs.umich.edu
2852565SN/A            if (isLLSC && i->matchesContext(req)) {
2864263Ssaidi@eecs.umich.edu                // it's a store conditional, and as far as the memory
2874263Ssaidi@eecs.umich.edu                // system can tell, the requesting context's lock is
2884263Ssaidi@eecs.umich.edu                // still valid.
2894263Ssaidi@eecs.umich.edu                DPRINTF(LLSC, "StCond success: context %d addr %#x\n",
2902565SN/A                        req->contextId(), paddr);
2912565SN/A                success = true;
2922565SN/A            }
2932901Ssaidi@eecs.umich.edu
2942901Ssaidi@eecs.umich.edu            // Get rid of our record of this lock and advance to next
2954263Ssaidi@eecs.umich.edu            DPRINTF(LLSC, "Erasing lock record: context %d addr %#x\n",
2964263Ssaidi@eecs.umich.edu                    i->contextId, paddr);
2972738Sstever@eecs.umich.edu            i = lockedAddrList.erase(i);
2982384SN/A        }
2992565SN/A        else {
3002565SN/A            // no match: advance to next record
3012565SN/A            ++i;
3022901Ssaidi@eecs.umich.edu        }
3032384SN/A    }
3042565SN/A
3052565SN/A    if (isLLSC) {
3062565SN/A        req->setExtraData(success ? 1 : 0);
3072901Ssaidi@eecs.umich.edu    }
3082384SN/A
3092565SN/A    return success;
3102384SN/A}
3112384SN/A
3122489SN/A
3132489SN/A#if TRACING_ON
314545SN/A
315545SN/A#define CASE(A, T)                                                      \
3162384SN/A  case sizeof(T):                                                       \
3171310SN/A    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