memtest.cc revision 4898
1/*
2 * Copyright (c) 2002-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Erik Hallnor
29 *          Steve Reinhardt
30 */
31
32// FIX ME: make trackBlkAddr use blocksize from actual cache, not hard coded
33
34#include <iomanip>
35#include <set>
36#include <string>
37#include <vector>
38
39#include "base/misc.hh"
40#include "base/statistics.hh"
41#include "cpu/memtest/memtest.hh"
42//#include "cpu/simple_thread.hh"
43//#include "mem/cache/base_cache.hh"
44#include "mem/mem_object.hh"
45#include "mem/port.hh"
46#include "mem/packet.hh"
47//#include "mem/physical.hh"
48#include "mem/request.hh"
49#include "sim/builder.hh"
50#include "sim/sim_events.hh"
51#include "sim/stats.hh"
52
53using namespace std;
54
55int TESTER_ALLOCATOR=0;
56
57bool
58MemTest::CpuPort::recvTiming(PacketPtr pkt)
59{
60    if (pkt->isResponse()) {
61        memtest->completeRequest(pkt);
62    } else {
63        // must be snoop upcall
64        assert(pkt->isRequest());
65        assert(pkt->getDest() == Packet::Broadcast);
66    }
67    return true;
68}
69
70Tick
71MemTest::CpuPort::recvAtomic(PacketPtr pkt)
72{
73    // must be snoop upcall
74    assert(pkt->isRequest());
75    assert(pkt->getDest() == Packet::Broadcast);
76    return curTick;
77}
78
79void
80MemTest::CpuPort::recvFunctional(PacketPtr pkt)
81{
82    //Do nothing if we see one come through
83//    if (curTick != 0)//Supress warning durring initialization
84//        warn("Functional Writes not implemented in MemTester\n");
85    //Need to find any response values that intersect and update
86    return;
87}
88
89void
90MemTest::CpuPort::recvStatusChange(Status status)
91{
92    if (status == RangeChange) {
93        if (!snoopRangeSent) {
94            snoopRangeSent = true;
95            sendStatusChange(Port::RangeChange);
96        }
97        return;
98    }
99
100    panic("MemTest doesn't expect recvStatusChange callback!");
101}
102
103void
104MemTest::CpuPort::recvRetry()
105{
106    memtest->doRetry();
107}
108
109void
110MemTest::sendPkt(PacketPtr pkt) {
111    if (atomic) {
112        cachePort.sendAtomic(pkt);
113        completeRequest(pkt);
114    }
115    else if (!cachePort.sendTiming(pkt)) {
116        accessRetry = true;
117        retryPkt = pkt;
118    }
119
120}
121
122MemTest::MemTest(const string &name,
123//		 MemInterface *_cache_interface,
124//		 PhysicalMemory *main_mem,
125//		 PhysicalMemory *check_mem,
126                 unsigned _memorySize,
127                 unsigned _percentReads,
128                 unsigned _percentFunctional,
129                 unsigned _percentUncacheable,
130                 unsigned _progressInterval,
131                 unsigned _percentSourceUnaligned,
132                 unsigned _percentDestUnaligned,
133                 Addr _traceAddr,
134                 Counter _max_loads,
135                 bool _atomic)
136    : MemObject(name),
137      tickEvent(this),
138      cachePort("test", this),
139      funcPort("functional", this),
140      retryPkt(NULL),
141//      mainMem(main_mem),
142//      checkMem(check_mem),
143      size(_memorySize),
144      percentReads(_percentReads),
145      percentFunctional(_percentFunctional),
146      percentUncacheable(_percentUncacheable),
147      progressInterval(_progressInterval),
148      nextProgressMessage(_progressInterval),
149      percentSourceUnaligned(_percentSourceUnaligned),
150      percentDestUnaligned(percentDestUnaligned),
151      maxLoads(_max_loads),
152      atomic(_atomic)
153{
154    vector<string> cmd;
155    cmd.push_back("/bin/ls");
156    vector<string> null_vec;
157    //  thread = new SimpleThread(NULL, 0, NULL, 0, mainMem);
158    curTick = 0;
159
160    cachePort.snoopRangeSent = false;
161    funcPort.snoopRangeSent = true;
162
163    // Needs to be masked off once we know the block size.
164    traceBlockAddr = _traceAddr;
165    baseAddr1 = 0x100000;
166    baseAddr2 = 0x400000;
167    uncacheAddr = 0x800000;
168
169    // set up counters
170    noResponseCycles = 0;
171    numReads = 0;
172    tickEvent.schedule(0);
173
174    id = TESTER_ALLOCATOR++;
175
176    accessRetry = false;
177}
178
179Port *
180MemTest::getPort(const std::string &if_name, int idx)
181{
182    if (if_name == "functional")
183        return &funcPort;
184    else if (if_name == "test")
185        return &cachePort;
186    else
187        panic("No Such Port\n");
188}
189
190void
191MemTest::init()
192{
193    // By the time init() is called, the ports should be hooked up.
194    blockSize = cachePort.peerBlockSize();
195    blockAddrMask = blockSize - 1;
196    traceBlockAddr = blockAddr(traceBlockAddr);
197
198    // initial memory contents for both physical memory and functional
199    // memory should be 0; no need to initialize them.
200}
201
202
203void
204MemTest::completeRequest(PacketPtr pkt)
205{
206    Request *req = pkt->req;
207
208    DPRINTF(MemTest, "completing %s at address %x (blk %x)\n",
209            pkt->isWrite() ? "write" : "read",
210            req->getPaddr(), blockAddr(req->getPaddr()));
211
212    MemTestSenderState *state =
213        dynamic_cast<MemTestSenderState *>(pkt->senderState);
214
215    uint8_t *data = state->data;
216    uint8_t *pkt_data = pkt->getPtr<uint8_t>();
217
218    //Remove the address from the list of outstanding
219    std::set<unsigned>::iterator removeAddr =
220        outstandingAddrs.find(req->getPaddr());
221    assert(removeAddr != outstandingAddrs.end());
222    outstandingAddrs.erase(removeAddr);
223
224    switch (pkt->cmd.toInt()) {
225      case MemCmd::ReadResp:
226
227        if (memcmp(pkt_data, data, pkt->getSize()) != 0) {
228            panic("%s: read of %x (blk %x) @ cycle %d "
229                  "returns %x, expected %x\n", name(),
230                  req->getPaddr(), blockAddr(req->getPaddr()), curTick,
231                  *pkt_data, *data);
232        }
233
234        numReads++;
235        numReadsStat++;
236
237        if (numReads == nextProgressMessage) {
238            ccprintf(cerr, "%s: completed %d read accesses @%d\n",
239                     name(), numReads, curTick);
240            nextProgressMessage += progressInterval;
241        }
242
243        if (maxLoads != 0 && numReads >= maxLoads)
244            exitSimLoop("maximum number of loads reached");
245        break;
246
247      case MemCmd::WriteResp:
248        numWritesStat++;
249        break;
250
251      default:
252        panic("invalid command %s (%d)", pkt->cmdString(), pkt->cmd.toInt());
253    }
254
255    noResponseCycles = 0;
256    delete state;
257    delete [] data;
258    delete pkt->req;
259    delete pkt;
260}
261
262void
263MemTest::regStats()
264{
265    using namespace Stats;
266
267    numReadsStat
268        .name(name() + ".num_reads")
269        .desc("number of read accesses completed")
270        ;
271
272    numWritesStat
273        .name(name() + ".num_writes")
274        .desc("number of write accesses completed")
275        ;
276
277    numCopiesStat
278        .name(name() + ".num_copies")
279        .desc("number of copy accesses completed")
280        ;
281}
282
283void
284MemTest::tick()
285{
286    if (!tickEvent.scheduled())
287        tickEvent.schedule(curTick + cycles(1));
288
289    if (++noResponseCycles >= 500000) {
290        cerr << name() << ": deadlocked at cycle " << curTick << endl;
291        fatal("");
292    }
293
294    if (accessRetry) {
295        return;
296    }
297
298    //make new request
299    unsigned cmd = random() % 100;
300    unsigned offset = random() % size;
301    unsigned base = random() % 2;
302    uint64_t data = random();
303    unsigned access_size = random() % 4;
304    unsigned cacheable = random() % 100;
305
306    //If we aren't doing copies, use id as offset, and do a false sharing
307    //mem tester
308    //We can eliminate the lower bits of the offset, and then use the id
309    //to offset within the blks
310    offset = blockAddr(offset);
311    offset += id;
312    access_size = 0;
313
314    Request *req = new Request();
315    uint32_t flags = 0;
316    Addr paddr;
317
318    if (cacheable < percentUncacheable) {
319        flags |= UNCACHEABLE;
320        paddr = uncacheAddr + offset;
321    } else {
322        paddr = ((base) ? baseAddr1 : baseAddr2) + offset;
323    }
324    bool probe = (random() % 100 < percentFunctional) && !(flags & UNCACHEABLE);
325    //bool probe = false;
326
327    paddr &= ~((1 << access_size) - 1);
328    req->setPhys(paddr, 1 << access_size, flags);
329    req->setThreadContext(id,0);
330
331    uint8_t *result = new uint8_t[8];
332
333    if (cmd < percentReads) {
334        // read
335
336        // For now we only allow one outstanding request per address
337        // per tester This means we assume CPU does write forwarding
338        // to reads that alias something in the cpu store buffer.
339        if (outstandingAddrs.find(paddr) != outstandingAddrs.end()) {
340            delete [] result;
341            delete req;
342            return;
343        }
344
345        outstandingAddrs.insert(paddr);
346
347        // ***** NOTE FOR RON: I'm not sure how to access checkMem. - Kevin
348        funcPort.readBlob(req->getPaddr(), result, req->getSize());
349
350        DPRINTF(MemTest,
351                "initiating read at address %x (blk %x) expecting %x\n",
352                req->getPaddr(), blockAddr(req->getPaddr()), *result);
353
354        PacketPtr pkt = new Packet(req, MemCmd::ReadReq, Packet::Broadcast);
355        pkt->setSrc(0);
356        pkt->dataDynamicArray(new uint8_t[req->getSize()]);
357        MemTestSenderState *state = new MemTestSenderState(result);
358        pkt->senderState = state;
359
360        if (probe) {
361            cachePort.sendFunctional(pkt);
362            pkt->makeAtomicResponse();
363            completeRequest(pkt);
364        } else {
365            sendPkt(pkt);
366        }
367    } else {
368        // write
369
370        // For now we only allow one outstanding request per addreess
371        // per tester.  This means we assume CPU does write forwarding
372        // to reads that alias something in the cpu store buffer.
373        if (outstandingAddrs.find(paddr) != outstandingAddrs.end()) {
374            delete [] result;
375            delete req;
376            return;
377        }
378
379        outstandingAddrs.insert(paddr);
380
381        DPRINTF(MemTest, "initiating write at address %x (blk %x) value %x\n",
382                req->getPaddr(), blockAddr(req->getPaddr()), data & 0xff);
383
384        PacketPtr pkt = new Packet(req, MemCmd::WriteReq, Packet::Broadcast);
385        pkt->setSrc(0);
386        uint8_t *pkt_data = new uint8_t[req->getSize()];
387        pkt->dataDynamicArray(pkt_data);
388        memcpy(pkt_data, &data, req->getSize());
389        MemTestSenderState *state = new MemTestSenderState(result);
390        pkt->senderState = state;
391
392        funcPort.writeBlob(req->getPaddr(), pkt_data, req->getSize());
393
394        if (probe) {
395            cachePort.sendFunctional(pkt);
396            pkt->makeAtomicResponse();
397            completeRequest(pkt);
398        } else {
399            sendPkt(pkt);
400        }
401    }
402}
403
404void
405MemTest::doRetry()
406{
407    if (cachePort.sendTiming(retryPkt)) {
408        accessRetry = false;
409        retryPkt = NULL;
410    }
411}
412
413BEGIN_DECLARE_SIM_OBJECT_PARAMS(MemTest)
414
415//    SimObjectParam<BaseCache *> cache;
416//    SimObjectParam<PhysicalMemory *> main_mem;
417//    SimObjectParam<PhysicalMemory *> check_mem;
418    Param<unsigned> memory_size;
419    Param<unsigned> percent_reads;
420    Param<unsigned> percent_functional;
421    Param<unsigned> percent_uncacheable;
422    Param<unsigned> progress_interval;
423    Param<unsigned> percent_source_unaligned;
424    Param<unsigned> percent_dest_unaligned;
425    Param<Addr> trace_addr;
426    Param<Counter> max_loads;
427    Param<bool> atomic;
428
429END_DECLARE_SIM_OBJECT_PARAMS(MemTest)
430
431
432BEGIN_INIT_SIM_OBJECT_PARAMS(MemTest)
433
434//    INIT_PARAM(cache, "L1 cache"),
435//    INIT_PARAM(main_mem, "hierarchical memory"),
436//    INIT_PARAM(check_mem, "check memory"),
437    INIT_PARAM(memory_size, "memory size"),
438    INIT_PARAM(percent_reads, "target read percentage"),
439    INIT_PARAM(percent_functional, "percentage of access that are functional"),
440    INIT_PARAM(percent_uncacheable, "target uncacheable percentage"),
441    INIT_PARAM(progress_interval, "progress report interval (in accesses)"),
442    INIT_PARAM(percent_source_unaligned,
443               "percent of copy source address that are unaligned"),
444    INIT_PARAM(percent_dest_unaligned,
445               "percent of copy dest address that are unaligned"),
446    INIT_PARAM(trace_addr, "address to trace"),
447                              INIT_PARAM(max_loads, "terminate when we have reached this load count"),
448    INIT_PARAM(atomic, "Is the tester testing atomic mode (or timing)")
449
450END_INIT_SIM_OBJECT_PARAMS(MemTest)
451
452
453CREATE_SIM_OBJECT(MemTest)
454{
455    return new MemTest(getInstanceName(), /*cache->getInterface(),*/ /*main_mem,*/
456                       /*check_mem,*/ memory_size, percent_reads, percent_functional,
457                       percent_uncacheable, progress_interval,
458                       percent_source_unaligned, percent_dest_unaligned,
459                       trace_addr, max_loads, atomic);
460}
461
462REGISTER_SIM_OBJECT("MemTest", MemTest)
463