timing.cc revision 3297:f0855ab36ff5
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: Steve Reinhardt
29 */
30
31#include "arch/locked_mem.hh"
32#include "arch/utility.hh"
33#include "cpu/exetrace.hh"
34#include "cpu/simple/timing.hh"
35#include "mem/packet_impl.hh"
36#include "sim/builder.hh"
37#include "sim/system.hh"
38
39using namespace std;
40using namespace TheISA;
41
42Port *
43TimingSimpleCPU::getPort(const std::string &if_name, int idx)
44{
45    if (if_name == "dcache_port")
46        return &dcachePort;
47    else if (if_name == "icache_port")
48        return &icachePort;
49    else
50        panic("No Such Port\n");
51}
52
53void
54TimingSimpleCPU::init()
55{
56    BaseCPU::init();
57#if FULL_SYSTEM
58    for (int i = 0; i < threadContexts.size(); ++i) {
59        ThreadContext *tc = threadContexts[i];
60
61        // initialize CPU, including PC
62        TheISA::initCPU(tc, tc->readCpuId());
63    }
64#endif
65}
66
67Tick
68TimingSimpleCPU::CpuPort::recvAtomic(Packet *pkt)
69{
70    panic("TimingSimpleCPU doesn't expect recvAtomic callback!");
71    return curTick;
72}
73
74void
75TimingSimpleCPU::CpuPort::recvFunctional(Packet *pkt)
76{
77    //No internal storage to update, jusst return
78    return;
79}
80
81void
82TimingSimpleCPU::CpuPort::recvStatusChange(Status status)
83{
84    if (status == RangeChange)
85        return;
86
87    panic("TimingSimpleCPU doesn't expect recvStatusChange callback!");
88}
89
90
91void
92TimingSimpleCPU::CpuPort::TickEvent::schedule(Packet *_pkt, Tick t)
93{
94    pkt = _pkt;
95    Event::schedule(t);
96}
97
98TimingSimpleCPU::TimingSimpleCPU(Params *p)
99    : BaseSimpleCPU(p), icachePort(this, p->clock), dcachePort(this, p->clock),
100      cpu_id(p->cpu_id)
101{
102    _status = Idle;
103    ifetch_pkt = dcache_pkt = NULL;
104    drainEvent = NULL;
105    fetchEvent = NULL;
106    previousTick = 0;
107    changeState(SimObject::Running);
108}
109
110
111TimingSimpleCPU::~TimingSimpleCPU()
112{
113}
114
115void
116TimingSimpleCPU::serialize(ostream &os)
117{
118    SimObject::State so_state = SimObject::getState();
119    SERIALIZE_ENUM(so_state);
120    BaseSimpleCPU::serialize(os);
121}
122
123void
124TimingSimpleCPU::unserialize(Checkpoint *cp, const string &section)
125{
126    SimObject::State so_state;
127    UNSERIALIZE_ENUM(so_state);
128    BaseSimpleCPU::unserialize(cp, section);
129}
130
131unsigned int
132TimingSimpleCPU::drain(Event *drain_event)
133{
134    // TimingSimpleCPU is ready to drain if it's not waiting for
135    // an access to complete.
136    if (status() == Idle || status() == Running || status() == SwitchedOut) {
137        changeState(SimObject::Drained);
138        return 0;
139    } else {
140        changeState(SimObject::Draining);
141        drainEvent = drain_event;
142        return 1;
143    }
144}
145
146void
147TimingSimpleCPU::resume()
148{
149    if (_status != SwitchedOut && _status != Idle) {
150        assert(system->getMemoryMode() == System::Timing);
151
152        // Delete the old event if it existed.
153        if (fetchEvent) {
154            if (fetchEvent->scheduled())
155                fetchEvent->deschedule();
156
157            delete fetchEvent;
158        }
159
160        fetchEvent =
161            new EventWrapper<TimingSimpleCPU, &TimingSimpleCPU::fetch>(this, false);
162        fetchEvent->schedule(curTick);
163    }
164
165    changeState(SimObject::Running);
166    previousTick = curTick;
167}
168
169void
170TimingSimpleCPU::switchOut()
171{
172    assert(status() == Running || status() == Idle);
173    _status = SwitchedOut;
174    numCycles += curTick - previousTick;
175
176    // If we've been scheduled to resume but are then told to switch out,
177    // we'll need to cancel it.
178    if (fetchEvent && fetchEvent->scheduled())
179        fetchEvent->deschedule();
180}
181
182
183void
184TimingSimpleCPU::takeOverFrom(BaseCPU *oldCPU)
185{
186    BaseCPU::takeOverFrom(oldCPU);
187
188    // if any of this CPU's ThreadContexts are active, mark the CPU as
189    // running and schedule its tick event.
190    for (int i = 0; i < threadContexts.size(); ++i) {
191        ThreadContext *tc = threadContexts[i];
192        if (tc->status() == ThreadContext::Active && _status != Running) {
193            _status = Running;
194            break;
195        }
196    }
197
198    if (_status != Running) {
199        _status = Idle;
200    }
201
202    Port *peer;
203    if (icachePort.getPeer() == NULL) {
204        peer = oldCPU->getPort("icache_port")->getPeer();
205        icachePort.setPeer(peer);
206    } else {
207        peer = icachePort.getPeer();
208    }
209    peer->setPeer(&icachePort);
210
211    if (dcachePort.getPeer() == NULL) {
212        peer = oldCPU->getPort("dcache_port")->getPeer();
213        dcachePort.setPeer(peer);
214    } else {
215        peer = dcachePort.getPeer();
216    }
217    peer->setPeer(&dcachePort);
218}
219
220
221void
222TimingSimpleCPU::activateContext(int thread_num, int delay)
223{
224    assert(thread_num == 0);
225    assert(thread);
226
227    assert(_status == Idle);
228
229    notIdleFraction++;
230    _status = Running;
231    // kick things off by initiating the fetch of the next instruction
232    fetchEvent =
233        new EventWrapper<TimingSimpleCPU, &TimingSimpleCPU::fetch>(this, false);
234    fetchEvent->schedule(curTick + cycles(delay));
235}
236
237
238void
239TimingSimpleCPU::suspendContext(int thread_num)
240{
241    assert(thread_num == 0);
242    assert(thread);
243
244    assert(_status == Running);
245
246    // just change status to Idle... if status != Running,
247    // completeInst() will not initiate fetch of next instruction.
248
249    notIdleFraction--;
250    _status = Idle;
251}
252
253
254template <class T>
255Fault
256TimingSimpleCPU::read(Addr addr, T &data, unsigned flags)
257{
258    Request *req =
259        new Request(/* asid */ 0, addr, sizeof(T), flags, thread->readPC(),
260                    cpu_id, /* thread ID */ 0);
261
262    if (traceData) {
263        traceData->setAddr(req->getVaddr());
264    }
265
266   // translate to physical address
267    Fault fault = thread->translateDataReadReq(req);
268
269    // Now do the access.
270    if (fault == NoFault) {
271        Packet *pkt =
272            new Packet(req, Packet::ReadReq, Packet::Broadcast);
273        pkt->dataDynamic<T>(new T);
274
275        if (!dcachePort.sendTiming(pkt)) {
276            _status = DcacheRetry;
277            dcache_pkt = pkt;
278        } else {
279            _status = DcacheWaitResponse;
280            // memory system takes ownership of packet
281            dcache_pkt = NULL;
282        }
283    }
284
285    // This will need a new way to tell if it has a dcache attached.
286    if (req->isUncacheable())
287        recordEvent("Uncached Read");
288
289    return fault;
290}
291
292#ifndef DOXYGEN_SHOULD_SKIP_THIS
293
294template
295Fault
296TimingSimpleCPU::read(Addr addr, uint64_t &data, unsigned flags);
297
298template
299Fault
300TimingSimpleCPU::read(Addr addr, uint32_t &data, unsigned flags);
301
302template
303Fault
304TimingSimpleCPU::read(Addr addr, uint16_t &data, unsigned flags);
305
306template
307Fault
308TimingSimpleCPU::read(Addr addr, uint8_t &data, unsigned flags);
309
310#endif //DOXYGEN_SHOULD_SKIP_THIS
311
312template<>
313Fault
314TimingSimpleCPU::read(Addr addr, double &data, unsigned flags)
315{
316    return read(addr, *(uint64_t*)&data, flags);
317}
318
319template<>
320Fault
321TimingSimpleCPU::read(Addr addr, float &data, unsigned flags)
322{
323    return read(addr, *(uint32_t*)&data, flags);
324}
325
326
327template<>
328Fault
329TimingSimpleCPU::read(Addr addr, int32_t &data, unsigned flags)
330{
331    return read(addr, (uint32_t&)data, flags);
332}
333
334
335template <class T>
336Fault
337TimingSimpleCPU::write(T data, Addr addr, unsigned flags, uint64_t *res)
338{
339    Request *req =
340        new Request(/* asid */ 0, addr, sizeof(T), flags, thread->readPC(),
341                    cpu_id, /* thread ID */ 0);
342
343    // translate to physical address
344    Fault fault = thread->translateDataWriteReq(req);
345
346    // Now do the access.
347    if (fault == NoFault) {
348        assert(dcache_pkt == NULL);
349        dcache_pkt = new Packet(req, Packet::WriteReq, Packet::Broadcast);
350        dcache_pkt->allocate();
351        dcache_pkt->set(data);
352
353        bool do_access = true;  // flag to suppress cache access
354
355        if (req->isLocked()) {
356            do_access = TheISA::handleLockedWrite(thread, req);
357        }
358
359        if (do_access) {
360            if (!dcachePort.sendTiming(dcache_pkt)) {
361                _status = DcacheRetry;
362            } else {
363                _status = DcacheWaitResponse;
364                // memory system takes ownership of packet
365                dcache_pkt = NULL;
366            }
367        }
368    }
369
370    // This will need a new way to tell if it's hooked up to a cache or not.
371    if (req->isUncacheable())
372        recordEvent("Uncached Write");
373
374    // If the write needs to have a fault on the access, consider calling
375    // changeStatus() and changing it to "bad addr write" or something.
376    return fault;
377}
378
379
380#ifndef DOXYGEN_SHOULD_SKIP_THIS
381template
382Fault
383TimingSimpleCPU::write(uint64_t data, Addr addr,
384                       unsigned flags, uint64_t *res);
385
386template
387Fault
388TimingSimpleCPU::write(uint32_t data, Addr addr,
389                       unsigned flags, uint64_t *res);
390
391template
392Fault
393TimingSimpleCPU::write(uint16_t data, Addr addr,
394                       unsigned flags, uint64_t *res);
395
396template
397Fault
398TimingSimpleCPU::write(uint8_t data, Addr addr,
399                       unsigned flags, uint64_t *res);
400
401#endif //DOXYGEN_SHOULD_SKIP_THIS
402
403template<>
404Fault
405TimingSimpleCPU::write(double data, Addr addr, unsigned flags, uint64_t *res)
406{
407    return write(*(uint64_t*)&data, addr, flags, res);
408}
409
410template<>
411Fault
412TimingSimpleCPU::write(float data, Addr addr, unsigned flags, uint64_t *res)
413{
414    return write(*(uint32_t*)&data, addr, flags, res);
415}
416
417
418template<>
419Fault
420TimingSimpleCPU::write(int32_t data, Addr addr, unsigned flags, uint64_t *res)
421{
422    return write((uint32_t)data, addr, flags, res);
423}
424
425
426void
427TimingSimpleCPU::fetch()
428{
429    checkForInterrupts();
430
431    Request *ifetch_req = new Request();
432    ifetch_req->setThreadContext(cpu_id, /* thread ID */ 0);
433    Fault fault = setupFetchRequest(ifetch_req);
434
435    ifetch_pkt = new Packet(ifetch_req, Packet::ReadReq, Packet::Broadcast);
436    ifetch_pkt->dataStatic(&inst);
437
438    if (fault == NoFault) {
439        if (!icachePort.sendTiming(ifetch_pkt)) {
440            // Need to wait for retry
441            _status = IcacheRetry;
442        } else {
443            // Need to wait for cache to respond
444            _status = IcacheWaitResponse;
445            // ownership of packet transferred to memory system
446            ifetch_pkt = NULL;
447        }
448    } else {
449        // fetch fault: advance directly to next instruction (fault handler)
450        advanceInst(fault);
451    }
452
453    numCycles += curTick - previousTick;
454    previousTick = curTick;
455}
456
457
458void
459TimingSimpleCPU::advanceInst(Fault fault)
460{
461    advancePC(fault);
462
463    if (_status == Running) {
464        // kick off fetch of next instruction... callback from icache
465        // response will cause that instruction to be executed,
466        // keeping the CPU running.
467        fetch();
468    }
469}
470
471
472void
473TimingSimpleCPU::completeIfetch(Packet *pkt)
474{
475    // received a response from the icache: execute the received
476    // instruction
477    assert(pkt->result == Packet::Success);
478    assert(_status == IcacheWaitResponse);
479
480    _status = Running;
481
482    delete pkt->req;
483    delete pkt;
484
485    numCycles += curTick - previousTick;
486    previousTick = curTick;
487
488    if (getState() == SimObject::Draining) {
489        completeDrain();
490        return;
491    }
492
493    preExecute();
494    if (curStaticInst->isMemRef() && !curStaticInst->isDataPrefetch()) {
495        // load or store: just send to dcache
496        Fault fault = curStaticInst->initiateAcc(this, traceData);
497        if (_status != Running) {
498            // instruction will complete in dcache response callback
499            assert(_status == DcacheWaitResponse || _status == DcacheRetry);
500            assert(fault == NoFault);
501        } else {
502            if (fault == NoFault) {
503                // early fail on store conditional: complete now
504                assert(dcache_pkt != NULL);
505                fault = curStaticInst->completeAcc(dcache_pkt, this,
506                                                   traceData);
507                delete dcache_pkt->req;
508                delete dcache_pkt;
509                dcache_pkt = NULL;
510            }
511            postExecute();
512            advanceInst(fault);
513        }
514    } else {
515        // non-memory instruction: execute completely now
516        Fault fault = curStaticInst->execute(this, traceData);
517        postExecute();
518        advanceInst(fault);
519    }
520}
521
522void
523TimingSimpleCPU::IcachePort::ITickEvent::process()
524{
525    cpu->completeIfetch(pkt);
526}
527
528bool
529TimingSimpleCPU::IcachePort::recvTiming(Packet *pkt)
530{
531    // delay processing of returned data until next CPU clock edge
532    Tick time = pkt->req->getTime();
533    while (time < curTick)
534        time += lat;
535
536    if (time == curTick)
537        cpu->completeIfetch(pkt);
538    else
539        tickEvent.schedule(pkt, time);
540
541    return true;
542}
543
544void
545TimingSimpleCPU::IcachePort::recvRetry()
546{
547    // we shouldn't get a retry unless we have a packet that we're
548    // waiting to transmit
549    assert(cpu->ifetch_pkt != NULL);
550    assert(cpu->_status == IcacheRetry);
551    Packet *tmp = cpu->ifetch_pkt;
552    if (sendTiming(tmp)) {
553        cpu->_status = IcacheWaitResponse;
554        cpu->ifetch_pkt = NULL;
555    }
556}
557
558void
559TimingSimpleCPU::completeDataAccess(Packet *pkt)
560{
561    // received a response from the dcache: complete the load or store
562    // instruction
563    assert(pkt->result == Packet::Success);
564    assert(_status == DcacheWaitResponse);
565    _status = Running;
566
567    numCycles += curTick - previousTick;
568    previousTick = curTick;
569
570    Fault fault = curStaticInst->completeAcc(pkt, this, traceData);
571
572    if (pkt->isRead() && pkt->req->isLocked()) {
573        TheISA::handleLockedRead(thread, pkt->req);
574    }
575
576    delete pkt->req;
577    delete pkt;
578
579    postExecute();
580
581    if (getState() == SimObject::Draining) {
582        advancePC(fault);
583        completeDrain();
584
585        return;
586    }
587
588    advanceInst(fault);
589}
590
591
592void
593TimingSimpleCPU::completeDrain()
594{
595    DPRINTF(Config, "Done draining\n");
596    changeState(SimObject::Drained);
597    drainEvent->process();
598}
599
600bool
601TimingSimpleCPU::DcachePort::recvTiming(Packet *pkt)
602{
603    // delay processing of returned data until next CPU clock edge
604    Tick time = pkt->req->getTime();
605    while (time < curTick)
606        time += lat;
607
608    if (time == curTick)
609        cpu->completeDataAccess(pkt);
610    else
611        tickEvent.schedule(pkt, time);
612
613    return true;
614}
615
616void
617TimingSimpleCPU::DcachePort::DTickEvent::process()
618{
619    cpu->completeDataAccess(pkt);
620}
621
622void
623TimingSimpleCPU::DcachePort::recvRetry()
624{
625    // we shouldn't get a retry unless we have a packet that we're
626    // waiting to transmit
627    assert(cpu->dcache_pkt != NULL);
628    assert(cpu->_status == DcacheRetry);
629    Packet *tmp = cpu->dcache_pkt;
630    if (sendTiming(tmp)) {
631        cpu->_status = DcacheWaitResponse;
632        // memory system takes ownership of packet
633        cpu->dcache_pkt = NULL;
634    }
635}
636
637
638////////////////////////////////////////////////////////////////////////
639//
640//  TimingSimpleCPU Simulation Object
641//
642BEGIN_DECLARE_SIM_OBJECT_PARAMS(TimingSimpleCPU)
643
644    Param<Counter> max_insts_any_thread;
645    Param<Counter> max_insts_all_threads;
646    Param<Counter> max_loads_any_thread;
647    Param<Counter> max_loads_all_threads;
648    Param<Tick> progress_interval;
649    SimObjectParam<MemObject *> mem;
650    SimObjectParam<System *> system;
651    Param<int> cpu_id;
652
653#if FULL_SYSTEM
654    SimObjectParam<AlphaITB *> itb;
655    SimObjectParam<AlphaDTB *> dtb;
656    Param<Tick> profile;
657#else
658    SimObjectParam<Process *> workload;
659#endif // FULL_SYSTEM
660
661    Param<int> clock;
662
663    Param<bool> defer_registration;
664    Param<int> width;
665    Param<bool> function_trace;
666    Param<Tick> function_trace_start;
667    Param<bool> simulate_stalls;
668
669END_DECLARE_SIM_OBJECT_PARAMS(TimingSimpleCPU)
670
671BEGIN_INIT_SIM_OBJECT_PARAMS(TimingSimpleCPU)
672
673    INIT_PARAM(max_insts_any_thread,
674               "terminate when any thread reaches this inst count"),
675    INIT_PARAM(max_insts_all_threads,
676               "terminate when all threads have reached this inst count"),
677    INIT_PARAM(max_loads_any_thread,
678               "terminate when any thread reaches this load count"),
679    INIT_PARAM(max_loads_all_threads,
680               "terminate when all threads have reached this load count"),
681    INIT_PARAM(progress_interval, "Progress interval"),
682    INIT_PARAM(mem, "memory"),
683    INIT_PARAM(system, "system object"),
684    INIT_PARAM(cpu_id, "processor ID"),
685
686#if FULL_SYSTEM
687    INIT_PARAM(itb, "Instruction TLB"),
688    INIT_PARAM(dtb, "Data TLB"),
689    INIT_PARAM(profile, ""),
690#else
691    INIT_PARAM(workload, "processes to run"),
692#endif // FULL_SYSTEM
693
694    INIT_PARAM(clock, "clock speed"),
695    INIT_PARAM(defer_registration, "defer system registration (for sampling)"),
696    INIT_PARAM(width, "cpu width"),
697    INIT_PARAM(function_trace, "Enable function trace"),
698    INIT_PARAM(function_trace_start, "Cycle to start function trace"),
699    INIT_PARAM(simulate_stalls, "Simulate cache stall cycles")
700
701END_INIT_SIM_OBJECT_PARAMS(TimingSimpleCPU)
702
703
704CREATE_SIM_OBJECT(TimingSimpleCPU)
705{
706    TimingSimpleCPU::Params *params = new TimingSimpleCPU::Params();
707    params->name = getInstanceName();
708    params->numberOfThreads = 1;
709    params->max_insts_any_thread = max_insts_any_thread;
710    params->max_insts_all_threads = max_insts_all_threads;
711    params->max_loads_any_thread = max_loads_any_thread;
712    params->max_loads_all_threads = max_loads_all_threads;
713    params->progress_interval = progress_interval;
714    params->deferRegistration = defer_registration;
715    params->clock = clock;
716    params->functionTrace = function_trace;
717    params->functionTraceStart = function_trace_start;
718    params->mem = mem;
719    params->system = system;
720    params->cpu_id = cpu_id;
721
722#if FULL_SYSTEM
723    params->itb = itb;
724    params->dtb = dtb;
725    params->profile = profile;
726#else
727    params->process = workload;
728#endif
729
730    TimingSimpleCPU *cpu = new TimingSimpleCPU(params);
731    return cpu;
732}
733
734REGISTER_SIM_OBJECT("TimingSimpleCPU", TimingSimpleCPU)
735
736