atomic.cc revision 4986:b7c82ad6b3ef
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/mmaped_ipr.hh"
33#include "arch/utility.hh"
34#include "base/bigint.hh"
35#include "cpu/exetrace.hh"
36#include "cpu/simple/atomic.hh"
37#include "mem/packet.hh"
38#include "mem/packet_access.hh"
39#include "params/AtomicSimpleCPU.hh"
40#include "sim/system.hh"
41
42using namespace std;
43using namespace TheISA;
44
45AtomicSimpleCPU::TickEvent::TickEvent(AtomicSimpleCPU *c)
46    : Event(&mainEventQueue, CPU_Tick_Pri), cpu(c)
47{
48}
49
50
51void
52AtomicSimpleCPU::TickEvent::process()
53{
54    cpu->tick();
55}
56
57const char *
58AtomicSimpleCPU::TickEvent::description()
59{
60    return "AtomicSimpleCPU tick";
61}
62
63Port *
64AtomicSimpleCPU::getPort(const std::string &if_name, int idx)
65{
66    if (if_name == "dcache_port")
67        return &dcachePort;
68    else if (if_name == "icache_port")
69        return &icachePort;
70    else if (if_name == "physmem_port") {
71        hasPhysMemPort = true;
72        return &physmemPort;
73    }
74    else
75        panic("No Such Port\n");
76}
77
78void
79AtomicSimpleCPU::init()
80{
81    BaseCPU::init();
82#if FULL_SYSTEM
83    for (int i = 0; i < threadContexts.size(); ++i) {
84        ThreadContext *tc = threadContexts[i];
85
86        // initialize CPU, including PC
87        TheISA::initCPU(tc, tc->readCpuId());
88    }
89#endif
90    if (hasPhysMemPort) {
91        bool snoop = false;
92        AddrRangeList pmAddrList;
93        physmemPort.getPeerAddressRanges(pmAddrList, snoop);
94        physMemAddr = *pmAddrList.begin();
95    }
96}
97
98bool
99AtomicSimpleCPU::CpuPort::recvTiming(PacketPtr pkt)
100{
101    panic("AtomicSimpleCPU doesn't expect recvTiming callback!");
102    return true;
103}
104
105Tick
106AtomicSimpleCPU::CpuPort::recvAtomic(PacketPtr pkt)
107{
108    //Snooping a coherence request, just return
109    return 0;
110}
111
112void
113AtomicSimpleCPU::CpuPort::recvFunctional(PacketPtr pkt)
114{
115    //No internal storage to update, just return
116    return;
117}
118
119void
120AtomicSimpleCPU::CpuPort::recvStatusChange(Status status)
121{
122    if (status == RangeChange) {
123        if (!snoopRangeSent) {
124            snoopRangeSent = true;
125            sendStatusChange(Port::RangeChange);
126        }
127        return;
128    }
129
130    panic("AtomicSimpleCPU doesn't expect recvStatusChange callback!");
131}
132
133void
134AtomicSimpleCPU::CpuPort::recvRetry()
135{
136    panic("AtomicSimpleCPU doesn't expect recvRetry callback!");
137}
138
139void
140AtomicSimpleCPU::DcachePort::setPeer(Port *port)
141{
142    Port::setPeer(port);
143
144#if FULL_SYSTEM
145    // Update the ThreadContext's memory ports (Functional/Virtual
146    // Ports)
147    cpu->tcBase()->connectMemPorts();
148#endif
149}
150
151AtomicSimpleCPU::AtomicSimpleCPU(Params *p)
152    : BaseSimpleCPU(p), tickEvent(this),
153      width(p->width), simulate_stalls(p->simulate_stalls),
154      icachePort(name() + "-iport", this), dcachePort(name() + "-iport", this),
155      physmemPort(name() + "-iport", this), hasPhysMemPort(false)
156{
157    _status = Idle;
158
159    icachePort.snoopRangeSent = false;
160    dcachePort.snoopRangeSent = false;
161
162    ifetch_req.setThreadContext(p->cpu_id, 0); // Add thread ID if we add MT
163    data_read_req.setThreadContext(p->cpu_id, 0); // Add thread ID here too
164    data_write_req.setThreadContext(p->cpu_id, 0); // Add thread ID here too
165}
166
167
168AtomicSimpleCPU::~AtomicSimpleCPU()
169{
170}
171
172void
173AtomicSimpleCPU::serialize(ostream &os)
174{
175    SimObject::State so_state = SimObject::getState();
176    SERIALIZE_ENUM(so_state);
177    Status _status = status();
178    SERIALIZE_ENUM(_status);
179    BaseSimpleCPU::serialize(os);
180    nameOut(os, csprintf("%s.tickEvent", name()));
181    tickEvent.serialize(os);
182}
183
184void
185AtomicSimpleCPU::unserialize(Checkpoint *cp, const string &section)
186{
187    SimObject::State so_state;
188    UNSERIALIZE_ENUM(so_state);
189    UNSERIALIZE_ENUM(_status);
190    BaseSimpleCPU::unserialize(cp, section);
191    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
192}
193
194void
195AtomicSimpleCPU::resume()
196{
197    DPRINTF(SimpleCPU, "Resume\n");
198    if (_status != SwitchedOut && _status != Idle) {
199        assert(system->getMemoryMode() == Enums::atomic);
200
201        changeState(SimObject::Running);
202        if (thread->status() == ThreadContext::Active) {
203            if (!tickEvent.scheduled()) {
204                tickEvent.schedule(nextCycle());
205            }
206        }
207    }
208}
209
210void
211AtomicSimpleCPU::switchOut()
212{
213    assert(status() == Running || status() == Idle);
214    _status = SwitchedOut;
215
216    tickEvent.squash();
217}
218
219
220void
221AtomicSimpleCPU::takeOverFrom(BaseCPU *oldCPU)
222{
223    BaseCPU::takeOverFrom(oldCPU, &icachePort, &dcachePort);
224
225    assert(!tickEvent.scheduled());
226
227    // if any of this CPU's ThreadContexts are active, mark the CPU as
228    // running and schedule its tick event.
229    for (int i = 0; i < threadContexts.size(); ++i) {
230        ThreadContext *tc = threadContexts[i];
231        if (tc->status() == ThreadContext::Active && _status != Running) {
232            _status = Running;
233            tickEvent.schedule(nextCycle());
234            break;
235        }
236    }
237    if (_status != Running) {
238        _status = Idle;
239    }
240}
241
242
243void
244AtomicSimpleCPU::activateContext(int thread_num, int delay)
245{
246    DPRINTF(SimpleCPU, "ActivateContext %d (%d cycles)\n", thread_num, delay);
247
248    assert(thread_num == 0);
249    assert(thread);
250
251    assert(_status == Idle);
252    assert(!tickEvent.scheduled());
253
254    notIdleFraction++;
255
256    //Make sure ticks are still on multiples of cycles
257    tickEvent.schedule(nextCycle(curTick + cycles(delay)));
258    _status = Running;
259}
260
261
262void
263AtomicSimpleCPU::suspendContext(int thread_num)
264{
265    DPRINTF(SimpleCPU, "SuspendContext %d\n", thread_num);
266
267    assert(thread_num == 0);
268    assert(thread);
269
270    assert(_status == Running);
271
272    // tick event may not be scheduled if this gets called from inside
273    // an instruction's execution, e.g. "quiesce"
274    if (tickEvent.scheduled())
275        tickEvent.deschedule();
276
277    notIdleFraction--;
278    _status = Idle;
279}
280
281
282template <class T>
283Fault
284AtomicSimpleCPU::read(Addr addr, T &data, unsigned flags)
285{
286    // use the CPU's statically allocated read request and packet objects
287    Request *req = &data_read_req;
288    req->setVirt(0, addr, sizeof(T), flags, thread->readPC());
289
290    if (traceData) {
291        traceData->setAddr(addr);
292    }
293
294    // translate to physical address
295    Fault fault = thread->translateDataReadReq(req);
296
297    // Now do the access.
298    if (fault == NoFault) {
299        Packet pkt =
300            Packet(req,
301                   req->isLocked() ? MemCmd::LoadLockedReq : MemCmd::ReadReq,
302                   Packet::Broadcast);
303        pkt.dataStatic(&data);
304
305        if (req->isMmapedIpr())
306            dcache_latency = TheISA::handleIprRead(thread->getTC(), &pkt);
307        else {
308            if (hasPhysMemPort && pkt.getAddr() == physMemAddr)
309                dcache_latency = physmemPort.sendAtomic(&pkt);
310            else
311                dcache_latency = dcachePort.sendAtomic(&pkt);
312        }
313        dcache_access = true;
314
315        assert(!pkt.isError());
316
317        data = gtoh(data);
318
319        if (req->isLocked()) {
320            TheISA::handleLockedRead(thread, req);
321        }
322    }
323
324    // This will need a new way to tell if it has a dcache attached.
325    if (req->isUncacheable())
326        recordEvent("Uncached Read");
327
328    return fault;
329}
330
331#ifndef DOXYGEN_SHOULD_SKIP_THIS
332
333template
334Fault
335AtomicSimpleCPU::read(Addr addr, Twin32_t &data, unsigned flags);
336
337template
338Fault
339AtomicSimpleCPU::read(Addr addr, Twin64_t &data, unsigned flags);
340
341template
342Fault
343AtomicSimpleCPU::read(Addr addr, uint64_t &data, unsigned flags);
344
345template
346Fault
347AtomicSimpleCPU::read(Addr addr, uint32_t &data, unsigned flags);
348
349template
350Fault
351AtomicSimpleCPU::read(Addr addr, uint16_t &data, unsigned flags);
352
353template
354Fault
355AtomicSimpleCPU::read(Addr addr, uint8_t &data, unsigned flags);
356
357#endif //DOXYGEN_SHOULD_SKIP_THIS
358
359template<>
360Fault
361AtomicSimpleCPU::read(Addr addr, double &data, unsigned flags)
362{
363    return read(addr, *(uint64_t*)&data, flags);
364}
365
366template<>
367Fault
368AtomicSimpleCPU::read(Addr addr, float &data, unsigned flags)
369{
370    return read(addr, *(uint32_t*)&data, flags);
371}
372
373
374template<>
375Fault
376AtomicSimpleCPU::read(Addr addr, int32_t &data, unsigned flags)
377{
378    return read(addr, (uint32_t&)data, flags);
379}
380
381
382template <class T>
383Fault
384AtomicSimpleCPU::write(T data, Addr addr, unsigned flags, uint64_t *res)
385{
386    // use the CPU's statically allocated write request and packet objects
387    Request *req = &data_write_req;
388    req->setVirt(0, addr, sizeof(T), flags, thread->readPC());
389
390    if (traceData) {
391        traceData->setAddr(addr);
392    }
393
394    // translate to physical address
395    Fault fault = thread->translateDataWriteReq(req);
396
397    // Now do the access.
398    if (fault == NoFault) {
399        MemCmd cmd = MemCmd::WriteReq; // default
400        bool do_access = true;  // flag to suppress cache access
401
402        if (req->isLocked()) {
403            cmd = MemCmd::StoreCondReq;
404            do_access = TheISA::handleLockedWrite(thread, req);
405        } else if (req->isSwap()) {
406            cmd = MemCmd::SwapReq;
407            if (req->isCondSwap()) {
408                assert(res);
409                req->setExtraData(*res);
410            }
411        }
412
413        if (do_access) {
414            Packet pkt = Packet(req, cmd, Packet::Broadcast);
415            pkt.dataStatic(&data);
416
417            if (req->isMmapedIpr()) {
418                dcache_latency = TheISA::handleIprWrite(thread->getTC(), &pkt);
419            } else {
420                data = htog(data);
421                if (hasPhysMemPort && pkt.getAddr() == physMemAddr)
422                    dcache_latency = physmemPort.sendAtomic(&pkt);
423                else
424                    dcache_latency = dcachePort.sendAtomic(&pkt);
425            }
426            dcache_access = true;
427            assert(!pkt.isError());
428
429            if (req->isSwap()) {
430                assert(res);
431                *res = pkt.get<T>();
432            }
433        }
434
435        if (res && !req->isSwap()) {
436            *res = req->getExtraData();
437        }
438    }
439
440    // This will need a new way to tell if it's hooked up to a cache or not.
441    if (req->isUncacheable())
442        recordEvent("Uncached Write");
443
444    // If the write needs to have a fault on the access, consider calling
445    // changeStatus() and changing it to "bad addr write" or something.
446    return fault;
447}
448
449
450#ifndef DOXYGEN_SHOULD_SKIP_THIS
451
452template
453Fault
454AtomicSimpleCPU::write(Twin32_t data, Addr addr,
455                       unsigned flags, uint64_t *res);
456
457template
458Fault
459AtomicSimpleCPU::write(Twin64_t data, Addr addr,
460                       unsigned flags, uint64_t *res);
461
462template
463Fault
464AtomicSimpleCPU::write(uint64_t data, Addr addr,
465                       unsigned flags, uint64_t *res);
466
467template
468Fault
469AtomicSimpleCPU::write(uint32_t data, Addr addr,
470                       unsigned flags, uint64_t *res);
471
472template
473Fault
474AtomicSimpleCPU::write(uint16_t data, Addr addr,
475                       unsigned flags, uint64_t *res);
476
477template
478Fault
479AtomicSimpleCPU::write(uint8_t data, Addr addr,
480                       unsigned flags, uint64_t *res);
481
482#endif //DOXYGEN_SHOULD_SKIP_THIS
483
484template<>
485Fault
486AtomicSimpleCPU::write(double data, Addr addr, unsigned flags, uint64_t *res)
487{
488    return write(*(uint64_t*)&data, addr, flags, res);
489}
490
491template<>
492Fault
493AtomicSimpleCPU::write(float data, Addr addr, unsigned flags, uint64_t *res)
494{
495    return write(*(uint32_t*)&data, addr, flags, res);
496}
497
498
499template<>
500Fault
501AtomicSimpleCPU::write(int32_t data, Addr addr, unsigned flags, uint64_t *res)
502{
503    return write((uint32_t)data, addr, flags, res);
504}
505
506
507void
508AtomicSimpleCPU::tick()
509{
510    DPRINTF(SimpleCPU, "Tick\n");
511
512    Tick latency = cycles(1); // instruction takes one cycle by default
513
514    for (int i = 0; i < width; ++i) {
515        numCycles++;
516
517        if (!curStaticInst || !curStaticInst->isDelayedCommit())
518            checkForInterrupts();
519
520        Fault fault = setupFetchRequest(&ifetch_req);
521
522        if (fault == NoFault) {
523            Tick icache_latency = 0;
524            bool icache_access = false;
525            dcache_access = false; // assume no dcache access
526
527            //Fetch more instruction memory if necessary
528            //if(predecoder.needMoreBytes())
529            //{
530                icache_access = true;
531                Packet ifetch_pkt = Packet(&ifetch_req, MemCmd::ReadReq,
532                                           Packet::Broadcast);
533                ifetch_pkt.dataStatic(&inst);
534
535                if (hasPhysMemPort && ifetch_pkt.getAddr() == physMemAddr)
536                    icache_latency = physmemPort.sendAtomic(&ifetch_pkt);
537                else
538                    icache_latency = icachePort.sendAtomic(&ifetch_pkt);
539
540                assert(!ifetch_pkt.isError());
541
542                // ifetch_req is initialized to read the instruction directly
543                // into the CPU object's inst field.
544            //}
545
546            preExecute();
547
548            if(curStaticInst)
549            {
550                fault = curStaticInst->execute(this, traceData);
551                postExecute();
552            }
553
554            // @todo remove me after debugging with legion done
555            if (curStaticInst && (!curStaticInst->isMicroop() ||
556                        curStaticInst->isFirstMicroop()))
557                instCnt++;
558
559            if (simulate_stalls) {
560                Tick icache_stall =
561                    icache_access ? icache_latency - cycles(1) : 0;
562                Tick dcache_stall =
563                    dcache_access ? dcache_latency - cycles(1) : 0;
564                Tick stall_cycles = (icache_stall + dcache_stall) / cycles(1);
565                if (cycles(stall_cycles) < (icache_stall + dcache_stall))
566                    latency += cycles(stall_cycles+1);
567                else
568                    latency += cycles(stall_cycles);
569            }
570
571        }
572        if(fault != NoFault || !stayAtPC)
573            advancePC(fault);
574    }
575
576    if (_status != Idle)
577        tickEvent.schedule(curTick + latency);
578}
579
580
581////////////////////////////////////////////////////////////////////////
582//
583//  AtomicSimpleCPU Simulation Object
584//
585AtomicSimpleCPU *
586AtomicSimpleCPUParams::create()
587{
588    AtomicSimpleCPU::Params *params = new AtomicSimpleCPU::Params();
589    params->name = name;
590    params->numberOfThreads = 1;
591    params->max_insts_any_thread = max_insts_any_thread;
592    params->max_insts_all_threads = max_insts_all_threads;
593    params->max_loads_any_thread = max_loads_any_thread;
594    params->max_loads_all_threads = max_loads_all_threads;
595    params->progress_interval = progress_interval;
596    params->deferRegistration = defer_registration;
597    params->phase = phase;
598    params->clock = clock;
599    params->functionTrace = function_trace;
600    params->functionTraceStart = function_trace_start;
601    params->width = width;
602    params->simulate_stalls = simulate_stalls;
603    params->system = system;
604    params->cpu_id = cpu_id;
605    params->tracer = tracer;
606
607#if FULL_SYSTEM
608    params->itb = itb;
609    params->dtb = dtb;
610    params->profile = profile;
611    params->do_quiesce = do_quiesce;
612    params->do_checkpoint_insts = do_checkpoint_insts;
613    params->do_statistics_insts = do_statistics_insts;
614#else
615    if (workload.size() != 1)
616        panic("only one workload allowed");
617    params->process = workload[0];
618#endif
619
620    AtomicSimpleCPU *cpu = new AtomicSimpleCPU(params);
621    return cpu;
622}
623