atomic.cc revision 10381
1/*
2 * Copyright (c) 2012-2013 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) 2002-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: Steve Reinhardt
41 */
42
43#include "arch/locked_mem.hh"
44#include "arch/mmapped_ipr.hh"
45#include "arch/utility.hh"
46#include "base/bigint.hh"
47#include "base/output.hh"
48#include "config/the_isa.hh"
49#include "cpu/simple/atomic.hh"
50#include "cpu/exetrace.hh"
51#include "debug/Drain.hh"
52#include "debug/ExecFaulting.hh"
53#include "debug/SimpleCPU.hh"
54#include "mem/packet.hh"
55#include "mem/packet_access.hh"
56#include "mem/physical.hh"
57#include "params/AtomicSimpleCPU.hh"
58#include "sim/faults.hh"
59#include "sim/system.hh"
60#include "sim/full_system.hh"
61
62using namespace std;
63using namespace TheISA;
64
65AtomicSimpleCPU::TickEvent::TickEvent(AtomicSimpleCPU *c)
66    : Event(CPU_Tick_Pri), cpu(c)
67{
68}
69
70
71void
72AtomicSimpleCPU::TickEvent::process()
73{
74    cpu->tick();
75}
76
77const char *
78AtomicSimpleCPU::TickEvent::description() const
79{
80    return "AtomicSimpleCPU tick";
81}
82
83void
84AtomicSimpleCPU::init()
85{
86    BaseCPU::init();
87
88    // Initialise the ThreadContext's memory proxies
89    tcBase()->initMemProxies(tcBase());
90
91    if (FullSystem && !params()->switched_out) {
92        ThreadID size = threadContexts.size();
93        for (ThreadID i = 0; i < size; ++i) {
94            ThreadContext *tc = threadContexts[i];
95            // initialize CPU, including PC
96            TheISA::initCPU(tc, tc->contextId());
97        }
98    }
99
100    // Atomic doesn't do MT right now, so contextId == threadId
101    ifetch_req.setThreadContext(_cpuId, 0); // Add thread ID if we add MT
102    data_read_req.setThreadContext(_cpuId, 0); // Add thread ID here too
103    data_write_req.setThreadContext(_cpuId, 0); // Add thread ID here too
104}
105
106AtomicSimpleCPU::AtomicSimpleCPU(AtomicSimpleCPUParams *p)
107    : BaseSimpleCPU(p), tickEvent(this), width(p->width), locked(false),
108      simulate_data_stalls(p->simulate_data_stalls),
109      simulate_inst_stalls(p->simulate_inst_stalls),
110      drain_manager(NULL),
111      icachePort(name() + ".icache_port", this),
112      dcachePort(name() + ".dcache_port", this),
113      fastmem(p->fastmem)
114{
115    _status = Idle;
116}
117
118
119AtomicSimpleCPU::~AtomicSimpleCPU()
120{
121    if (tickEvent.scheduled()) {
122        deschedule(tickEvent);
123    }
124}
125
126unsigned int
127AtomicSimpleCPU::drain(DrainManager *dm)
128{
129    assert(!drain_manager);
130    if (switchedOut())
131        return 0;
132
133    if (!isDrained()) {
134        DPRINTF(Drain, "Requesting drain: %s\n", pcState());
135        drain_manager = dm;
136        return 1;
137    } else {
138        if (tickEvent.scheduled())
139            deschedule(tickEvent);
140
141        DPRINTF(Drain, "Not executing microcode, no need to drain.\n");
142        return 0;
143    }
144}
145
146void
147AtomicSimpleCPU::drainResume()
148{
149    assert(!tickEvent.scheduled());
150    assert(!drain_manager);
151    if (switchedOut())
152        return;
153
154    DPRINTF(SimpleCPU, "Resume\n");
155    verifyMemoryMode();
156
157    assert(!threadContexts.empty());
158    if (threadContexts.size() > 1)
159        fatal("The atomic CPU only supports one thread.\n");
160
161    if (thread->status() == ThreadContext::Active) {
162        schedule(tickEvent, nextCycle());
163        _status = BaseSimpleCPU::Running;
164        notIdleFraction = 1;
165    } else {
166        _status = BaseSimpleCPU::Idle;
167        notIdleFraction = 0;
168    }
169
170    system->totalNumInsts = 0;
171}
172
173bool
174AtomicSimpleCPU::tryCompleteDrain()
175{
176    if (!drain_manager)
177        return false;
178
179    DPRINTF(Drain, "tryCompleteDrain: %s\n", pcState());
180    if (!isDrained())
181        return false;
182
183    DPRINTF(Drain, "CPU done draining, processing drain event\n");
184    drain_manager->signalDrainDone();
185    drain_manager = NULL;
186
187    return true;
188}
189
190
191void
192AtomicSimpleCPU::switchOut()
193{
194    BaseSimpleCPU::switchOut();
195
196    assert(!tickEvent.scheduled());
197    assert(_status == BaseSimpleCPU::Running || _status == Idle);
198    assert(isDrained());
199}
200
201
202void
203AtomicSimpleCPU::takeOverFrom(BaseCPU *oldCPU)
204{
205    BaseSimpleCPU::takeOverFrom(oldCPU);
206
207    // The tick event should have been descheduled by drain()
208    assert(!tickEvent.scheduled());
209
210    ifetch_req.setThreadContext(_cpuId, 0); // Add thread ID if we add MT
211    data_read_req.setThreadContext(_cpuId, 0); // Add thread ID here too
212    data_write_req.setThreadContext(_cpuId, 0); // Add thread ID here too
213}
214
215void
216AtomicSimpleCPU::verifyMemoryMode() const
217{
218    if (!system->isAtomicMode()) {
219        fatal("The atomic CPU requires the memory system to be in "
220              "'atomic' mode.\n");
221    }
222}
223
224void
225AtomicSimpleCPU::activateContext(ThreadID thread_num, Cycles delay)
226{
227    DPRINTF(SimpleCPU, "ActivateContext %d (%d cycles)\n", thread_num, delay);
228
229    assert(thread_num == 0);
230    assert(thread);
231
232    assert(_status == Idle);
233    assert(!tickEvent.scheduled());
234
235    notIdleFraction = 1;
236    numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend);
237
238    //Make sure ticks are still on multiples of cycles
239    schedule(tickEvent, clockEdge(delay));
240    _status = BaseSimpleCPU::Running;
241}
242
243
244void
245AtomicSimpleCPU::suspendContext(ThreadID thread_num)
246{
247    DPRINTF(SimpleCPU, "SuspendContext %d\n", thread_num);
248
249    assert(thread_num == 0);
250    assert(thread);
251
252    if (_status == Idle)
253        return;
254
255    assert(_status == BaseSimpleCPU::Running);
256
257    // tick event may not be scheduled if this gets called from inside
258    // an instruction's execution, e.g. "quiesce"
259    if (tickEvent.scheduled())
260        deschedule(tickEvent);
261
262    notIdleFraction = 0;
263    _status = Idle;
264}
265
266
267Tick
268AtomicSimpleCPU::AtomicCPUDPort::recvAtomicSnoop(PacketPtr pkt)
269{
270    DPRINTF(SimpleCPU, "received snoop pkt for addr:%#x %s\n", pkt->getAddr(),
271            pkt->cmdString());
272
273    // if snoop invalidates, release any associated locks
274    if (pkt->isInvalidate()) {
275        DPRINTF(SimpleCPU, "received invalidation for addr:%#x\n",
276                pkt->getAddr());
277        TheISA::handleLockedSnoop(cpu->thread, pkt, cacheBlockMask);
278    }
279
280    return 0;
281}
282
283void
284AtomicSimpleCPU::AtomicCPUDPort::recvFunctionalSnoop(PacketPtr pkt)
285{
286    DPRINTF(SimpleCPU, "received snoop pkt for addr:%#x %s\n", pkt->getAddr(),
287            pkt->cmdString());
288
289    // if snoop invalidates, release any associated locks
290    if (pkt->isInvalidate()) {
291        DPRINTF(SimpleCPU, "received invalidation for addr:%#x\n",
292                pkt->getAddr());
293        TheISA::handleLockedSnoop(cpu->thread, pkt, cacheBlockMask);
294    }
295}
296
297Fault
298AtomicSimpleCPU::readMem(Addr addr, uint8_t * data,
299                         unsigned size, unsigned flags)
300{
301    // use the CPU's statically allocated read request and packet objects
302    Request *req = &data_read_req;
303
304    if (traceData) {
305        traceData->setAddr(addr);
306    }
307
308    //The size of the data we're trying to read.
309    int fullSize = size;
310
311    //The address of the second part of this access if it needs to be split
312    //across a cache line boundary.
313    Addr secondAddr = roundDown(addr + size - 1, cacheLineSize());
314
315    if (secondAddr > addr)
316        size = secondAddr - addr;
317
318    dcache_latency = 0;
319
320    req->taskId(taskId());
321    while (1) {
322        req->setVirt(0, addr, size, flags, dataMasterId(), thread->pcState().instAddr());
323
324        // translate to physical address
325        Fault fault = thread->dtb->translateAtomic(req, tc, BaseTLB::Read);
326
327        // Now do the access.
328        if (fault == NoFault && !req->getFlags().isSet(Request::NO_ACCESS)) {
329            Packet pkt(req, MemCmd::ReadReq);
330            pkt.refineCommand();
331            pkt.dataStatic(data);
332
333            if (req->isMmappedIpr())
334                dcache_latency += TheISA::handleIprRead(thread->getTC(), &pkt);
335            else {
336                if (fastmem && system->isMemAddr(pkt.getAddr()))
337                    system->getPhysMem().access(&pkt);
338                else
339                    dcache_latency += dcachePort.sendAtomic(&pkt);
340            }
341            dcache_access = true;
342
343            assert(!pkt.isError());
344
345            if (req->isLLSC()) {
346                TheISA::handleLockedRead(thread, req);
347            }
348        }
349
350        //If there's a fault, return it
351        if (fault != NoFault) {
352            if (req->isPrefetch()) {
353                return NoFault;
354            } else {
355                return fault;
356            }
357        }
358
359        //If we don't need to access a second cache line, stop now.
360        if (secondAddr <= addr)
361        {
362            if (req->isLocked() && fault == NoFault) {
363                assert(!locked);
364                locked = true;
365            }
366            return fault;
367        }
368
369        /*
370         * Set up for accessing the second cache line.
371         */
372
373        //Move the pointer we're reading into to the correct location.
374        data += size;
375        //Adjust the size to get the remaining bytes.
376        size = addr + fullSize - secondAddr;
377        //And access the right address.
378        addr = secondAddr;
379    }
380}
381
382
383Fault
384AtomicSimpleCPU::writeMem(uint8_t *data, unsigned size,
385                          Addr addr, unsigned flags, uint64_t *res)
386{
387
388    static uint8_t zero_array[64] = {};
389
390    if (data == NULL) {
391        assert(size <= 64);
392        assert(flags & Request::CACHE_BLOCK_ZERO);
393        // This must be a cache block cleaning request
394        data = zero_array;
395    }
396
397    // use the CPU's statically allocated write request and packet objects
398    Request *req = &data_write_req;
399
400    if (traceData) {
401        traceData->setAddr(addr);
402    }
403
404    //The size of the data we're trying to read.
405    int fullSize = size;
406
407    //The address of the second part of this access if it needs to be split
408    //across a cache line boundary.
409    Addr secondAddr = roundDown(addr + size - 1, cacheLineSize());
410
411    if(secondAddr > addr)
412        size = secondAddr - addr;
413
414    dcache_latency = 0;
415
416    req->taskId(taskId());
417    while(1) {
418        req->setVirt(0, addr, size, flags, dataMasterId(), thread->pcState().instAddr());
419
420        // translate to physical address
421        Fault fault = thread->dtb->translateAtomic(req, tc, BaseTLB::Write);
422
423        // Now do the access.
424        if (fault == NoFault) {
425            MemCmd cmd = MemCmd::WriteReq; // default
426            bool do_access = true;  // flag to suppress cache access
427
428            if (req->isLLSC()) {
429                cmd = MemCmd::StoreCondReq;
430                do_access = TheISA::handleLockedWrite(thread, req, dcachePort.cacheBlockMask);
431            } else if (req->isSwap()) {
432                cmd = MemCmd::SwapReq;
433                if (req->isCondSwap()) {
434                    assert(res);
435                    req->setExtraData(*res);
436                }
437            }
438
439            if (do_access && !req->getFlags().isSet(Request::NO_ACCESS)) {
440                Packet pkt = Packet(req, cmd);
441                pkt.dataStatic(data);
442
443                if (req->isMmappedIpr()) {
444                    dcache_latency +=
445                        TheISA::handleIprWrite(thread->getTC(), &pkt);
446                } else {
447                    if (fastmem && system->isMemAddr(pkt.getAddr()))
448                        system->getPhysMem().access(&pkt);
449                    else
450                        dcache_latency += dcachePort.sendAtomic(&pkt);
451                }
452                dcache_access = true;
453                assert(!pkt.isError());
454
455                if (req->isSwap()) {
456                    assert(res);
457                    memcpy(res, pkt.getPtr<uint8_t>(), fullSize);
458                }
459            }
460
461            if (res && !req->isSwap()) {
462                *res = req->getExtraData();
463            }
464        }
465
466        //If there's a fault or we don't need to access a second cache line,
467        //stop now.
468        if (fault != NoFault || secondAddr <= addr)
469        {
470            if (req->isLocked() && fault == NoFault) {
471                assert(locked);
472                locked = false;
473            }
474            if (fault != NoFault && req->isPrefetch()) {
475                return NoFault;
476            } else {
477                return fault;
478            }
479        }
480
481        /*
482         * Set up for accessing the second cache line.
483         */
484
485        //Move the pointer we're reading into to the correct location.
486        data += size;
487        //Adjust the size to get the remaining bytes.
488        size = addr + fullSize - secondAddr;
489        //And access the right address.
490        addr = secondAddr;
491    }
492}
493
494
495void
496AtomicSimpleCPU::tick()
497{
498    DPRINTF(SimpleCPU, "Tick\n");
499
500    Tick latency = 0;
501
502    for (int i = 0; i < width || locked; ++i) {
503        numCycles++;
504
505        if (!curStaticInst || !curStaticInst->isDelayedCommit())
506            checkForInterrupts();
507
508        checkPcEventQueue();
509        // We must have just got suspended by a PC event
510        if (_status == Idle) {
511            tryCompleteDrain();
512            return;
513        }
514
515        Fault fault = NoFault;
516
517        TheISA::PCState pcState = thread->pcState();
518
519        bool needToFetch = !isRomMicroPC(pcState.microPC()) &&
520                           !curMacroStaticInst;
521        if (needToFetch) {
522            ifetch_req.taskId(taskId());
523            setupFetchRequest(&ifetch_req);
524            fault = thread->itb->translateAtomic(&ifetch_req, tc,
525                                                 BaseTLB::Execute);
526        }
527
528        if (fault == NoFault) {
529            Tick icache_latency = 0;
530            bool icache_access = false;
531            dcache_access = false; // assume no dcache access
532
533            if (needToFetch) {
534                // This is commented out because the decoder would act like
535                // a tiny cache otherwise. It wouldn't be flushed when needed
536                // like the I cache. It should be flushed, and when that works
537                // this code should be uncommented.
538                //Fetch more instruction memory if necessary
539                //if(decoder.needMoreBytes())
540                //{
541                    icache_access = true;
542                    Packet ifetch_pkt = Packet(&ifetch_req, MemCmd::ReadReq);
543                    ifetch_pkt.dataStatic(&inst);
544
545                    if (fastmem && system->isMemAddr(ifetch_pkt.getAddr()))
546                        system->getPhysMem().access(&ifetch_pkt);
547                    else
548                        icache_latency = icachePort.sendAtomic(&ifetch_pkt);
549
550                    assert(!ifetch_pkt.isError());
551
552                    // ifetch_req is initialized to read the instruction directly
553                    // into the CPU object's inst field.
554                //}
555            }
556
557            preExecute();
558
559            if (curStaticInst) {
560                fault = curStaticInst->execute(this, traceData);
561
562                // keep an instruction count
563                if (fault == NoFault) {
564                    countInst();
565                    if (!curStaticInst->isMicroop() ||
566                         curStaticInst->isLastMicroop()) {
567                        ppCommit->notify(std::make_pair(thread, curStaticInst));
568                    }
569                }
570                else if (traceData && !DTRACE(ExecFaulting)) {
571                    delete traceData;
572                    traceData = NULL;
573                }
574
575                postExecute();
576            }
577
578            // @todo remove me after debugging with legion done
579            if (curStaticInst && (!curStaticInst->isMicroop() ||
580                        curStaticInst->isFirstMicroop()))
581                instCnt++;
582
583            Tick stall_ticks = 0;
584            if (simulate_inst_stalls && icache_access)
585                stall_ticks += icache_latency;
586
587            if (simulate_data_stalls && dcache_access)
588                stall_ticks += dcache_latency;
589
590            if (stall_ticks) {
591                // the atomic cpu does its accounting in ticks, so
592                // keep counting in ticks but round to the clock
593                // period
594                latency += divCeil(stall_ticks, clockPeriod()) *
595                    clockPeriod();
596            }
597
598        }
599        if(fault != NoFault || !stayAtPC)
600            advancePC(fault);
601    }
602
603    if (tryCompleteDrain())
604        return;
605
606    // instruction takes at least one cycle
607    if (latency < clockPeriod())
608        latency = clockPeriod();
609
610    if (_status != Idle)
611        schedule(tickEvent, curTick() + latency);
612}
613
614void
615AtomicSimpleCPU::regProbePoints()
616{
617    ppCommit = new ProbePointArg<pair<SimpleThread*, const StaticInstPtr>>
618                                (getProbeManager(), "Commit");
619}
620
621void
622AtomicSimpleCPU::printAddr(Addr a)
623{
624    dcachePort.printAddr(a);
625}
626
627////////////////////////////////////////////////////////////////////////
628//
629//  AtomicSimpleCPU Simulation Object
630//
631AtomicSimpleCPU *
632AtomicSimpleCPUParams::create()
633{
634    numThreads = 1;
635    if (!FullSystem && workload.size() != 1)
636        panic("only one workload allowed");
637    return new AtomicSimpleCPU(this);
638}
639