atomic.cc revision 7518:917208416d2a
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 "config/the_isa.hh"
36#include "cpu/exetrace.hh"
37#include "cpu/simple/atomic.hh"
38#include "mem/packet.hh"
39#include "mem/packet_access.hh"
40#include "params/AtomicSimpleCPU.hh"
41#include "sim/system.hh"
42
43using namespace std;
44using namespace TheISA;
45
46AtomicSimpleCPU::TickEvent::TickEvent(AtomicSimpleCPU *c)
47    : Event(CPU_Tick_Pri), cpu(c)
48{
49}
50
51
52void
53AtomicSimpleCPU::TickEvent::process()
54{
55    cpu->tick();
56}
57
58const char *
59AtomicSimpleCPU::TickEvent::description() const
60{
61    return "AtomicSimpleCPU tick";
62}
63
64Port *
65AtomicSimpleCPU::getPort(const string &if_name, int idx)
66{
67    if (if_name == "dcache_port")
68        return &dcachePort;
69    else if (if_name == "icache_port")
70        return &icachePort;
71    else if (if_name == "physmem_port") {
72        hasPhysMemPort = true;
73        return &physmemPort;
74    }
75    else
76        panic("No Such Port\n");
77}
78
79void
80AtomicSimpleCPU::init()
81{
82    BaseCPU::init();
83#if FULL_SYSTEM
84    ThreadID size = threadContexts.size();
85    for (ThreadID i = 0; i < size; ++i) {
86        ThreadContext *tc = threadContexts[i];
87
88        // initialize CPU, including PC
89        TheISA::initCPU(tc, tc->contextId());
90    }
91#endif
92    if (hasPhysMemPort) {
93        bool snoop = false;
94        AddrRangeList pmAddrList;
95        physmemPort.getPeerAddressRanges(pmAddrList, snoop);
96        physMemAddr = *pmAddrList.begin();
97    }
98    // Atomic doesn't do MT right now, so contextId == threadId
99    ifetch_req.setThreadContext(_cpuId, 0); // Add thread ID if we add MT
100    data_read_req.setThreadContext(_cpuId, 0); // Add thread ID here too
101    data_write_req.setThreadContext(_cpuId, 0); // Add thread ID here too
102}
103
104bool
105AtomicSimpleCPU::CpuPort::recvTiming(PacketPtr pkt)
106{
107    panic("AtomicSimpleCPU doesn't expect recvTiming callback!");
108    return true;
109}
110
111Tick
112AtomicSimpleCPU::CpuPort::recvAtomic(PacketPtr pkt)
113{
114    //Snooping a coherence request, just return
115    return 0;
116}
117
118void
119AtomicSimpleCPU::CpuPort::recvFunctional(PacketPtr pkt)
120{
121    //No internal storage to update, just return
122    return;
123}
124
125void
126AtomicSimpleCPU::CpuPort::recvStatusChange(Status status)
127{
128    if (status == RangeChange) {
129        if (!snoopRangeSent) {
130            snoopRangeSent = true;
131            sendStatusChange(Port::RangeChange);
132        }
133        return;
134    }
135
136    panic("AtomicSimpleCPU doesn't expect recvStatusChange callback!");
137}
138
139void
140AtomicSimpleCPU::CpuPort::recvRetry()
141{
142    panic("AtomicSimpleCPU doesn't expect recvRetry callback!");
143}
144
145void
146AtomicSimpleCPU::DcachePort::setPeer(Port *port)
147{
148    Port::setPeer(port);
149
150#if FULL_SYSTEM
151    // Update the ThreadContext's memory ports (Functional/Virtual
152    // Ports)
153    cpu->tcBase()->connectMemPorts(cpu->tcBase());
154#endif
155}
156
157AtomicSimpleCPU::AtomicSimpleCPU(AtomicSimpleCPUParams *p)
158    : BaseSimpleCPU(p), tickEvent(this), width(p->width), locked(false),
159      simulate_data_stalls(p->simulate_data_stalls),
160      simulate_inst_stalls(p->simulate_inst_stalls),
161      icachePort(name() + "-iport", this), dcachePort(name() + "-iport", this),
162      physmemPort(name() + "-iport", this), hasPhysMemPort(false)
163{
164    _status = Idle;
165
166    icachePort.snoopRangeSent = false;
167    dcachePort.snoopRangeSent = false;
168
169}
170
171
172AtomicSimpleCPU::~AtomicSimpleCPU()
173{
174    if (tickEvent.scheduled()) {
175        deschedule(tickEvent);
176    }
177}
178
179void
180AtomicSimpleCPU::serialize(ostream &os)
181{
182    SimObject::State so_state = SimObject::getState();
183    SERIALIZE_ENUM(so_state);
184    SERIALIZE_SCALAR(locked);
185    BaseSimpleCPU::serialize(os);
186    nameOut(os, csprintf("%s.tickEvent", name()));
187    tickEvent.serialize(os);
188}
189
190void
191AtomicSimpleCPU::unserialize(Checkpoint *cp, const string &section)
192{
193    SimObject::State so_state;
194    UNSERIALIZE_ENUM(so_state);
195    UNSERIALIZE_SCALAR(locked);
196    BaseSimpleCPU::unserialize(cp, section);
197    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
198}
199
200void
201AtomicSimpleCPU::resume()
202{
203    if (_status == Idle || _status == SwitchedOut)
204        return;
205
206    DPRINTF(SimpleCPU, "Resume\n");
207    assert(system->getMemoryMode() == Enums::atomic);
208
209    changeState(SimObject::Running);
210    if (thread->status() == ThreadContext::Active) {
211        if (!tickEvent.scheduled())
212            schedule(tickEvent, nextCycle());
213    }
214}
215
216void
217AtomicSimpleCPU::switchOut()
218{
219    assert(_status == Running || _status == Idle);
220    _status = SwitchedOut;
221
222    tickEvent.squash();
223}
224
225
226void
227AtomicSimpleCPU::takeOverFrom(BaseCPU *oldCPU)
228{
229    BaseCPU::takeOverFrom(oldCPU, &icachePort, &dcachePort);
230
231    assert(!tickEvent.scheduled());
232
233    // if any of this CPU's ThreadContexts are active, mark the CPU as
234    // running and schedule its tick event.
235    ThreadID size = threadContexts.size();
236    for (ThreadID i = 0; i < size; ++i) {
237        ThreadContext *tc = threadContexts[i];
238        if (tc->status() == ThreadContext::Active && _status != Running) {
239            _status = Running;
240            schedule(tickEvent, nextCycle());
241            break;
242        }
243    }
244    if (_status != Running) {
245        _status = Idle;
246    }
247    assert(threadContexts.size() == 1);
248    ifetch_req.setThreadContext(_cpuId, 0); // Add thread ID if we add MT
249    data_read_req.setThreadContext(_cpuId, 0); // Add thread ID here too
250    data_write_req.setThreadContext(_cpuId, 0); // Add thread ID here too
251}
252
253
254void
255AtomicSimpleCPU::activateContext(int thread_num, int delay)
256{
257    DPRINTF(SimpleCPU, "ActivateContext %d (%d cycles)\n", thread_num, delay);
258
259    assert(thread_num == 0);
260    assert(thread);
261
262    assert(_status == Idle);
263    assert(!tickEvent.scheduled());
264
265    notIdleFraction++;
266    numCycles += tickToCycles(thread->lastActivate - thread->lastSuspend);
267
268    //Make sure ticks are still on multiples of cycles
269    schedule(tickEvent, nextCycle(curTick + ticks(delay)));
270    _status = Running;
271}
272
273
274void
275AtomicSimpleCPU::suspendContext(int thread_num)
276{
277    DPRINTF(SimpleCPU, "SuspendContext %d\n", thread_num);
278
279    assert(thread_num == 0);
280    assert(thread);
281
282    if (_status == Idle)
283        return;
284
285    assert(_status == Running);
286
287    // tick event may not be scheduled if this gets called from inside
288    // an instruction's execution, e.g. "quiesce"
289    if (tickEvent.scheduled())
290        deschedule(tickEvent);
291
292    notIdleFraction--;
293    _status = Idle;
294}
295
296
297template <class T>
298Fault
299AtomicSimpleCPU::read(Addr addr, T &data, 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 block size of our peer.
309    unsigned blockSize = dcachePort.peerBlockSize();
310    //The size of the data we're trying to read.
311    int dataSize = sizeof(T);
312
313    uint8_t * dataPtr = (uint8_t *)&data;
314
315    //The address of the second part of this access if it needs to be split
316    //across a cache line boundary.
317    Addr secondAddr = roundDown(addr + dataSize - 1, blockSize);
318
319    if(secondAddr > addr)
320        dataSize = secondAddr - addr;
321
322    dcache_latency = 0;
323
324    while(1) {
325        req->setVirt(0, addr, dataSize, flags, thread->readPC());
326
327        // translate to physical address
328        Fault fault = thread->dtb->translateAtomic(req, tc, BaseTLB::Read);
329
330        // Now do the access.
331        if (fault == NoFault && !req->getFlags().isSet(Request::NO_ACCESS)) {
332            Packet pkt = Packet(req,
333                    req->isLLSC() ? MemCmd::LoadLockedReq : MemCmd::ReadReq,
334                    Packet::Broadcast);
335            pkt.dataStatic(dataPtr);
336
337            if (req->isMmapedIpr())
338                dcache_latency += TheISA::handleIprRead(thread->getTC(), &pkt);
339            else {
340                if (hasPhysMemPort && pkt.getAddr() == physMemAddr)
341                    dcache_latency += physmemPort.sendAtomic(&pkt);
342                else
343                    dcache_latency += dcachePort.sendAtomic(&pkt);
344            }
345            dcache_access = true;
346
347            assert(!pkt.isError());
348
349            if (req->isLLSC()) {
350                TheISA::handleLockedRead(thread, req);
351            }
352        }
353
354        //If there's a fault, return it
355        if (fault != NoFault) {
356            if (req->isPrefetch()) {
357                return NoFault;
358            } else {
359                return fault;
360            }
361        }
362
363        //If we don't need to access a second cache line, stop now.
364        if (secondAddr <= addr)
365        {
366            data = gtoh(data);
367            if (traceData) {
368                traceData->setData(data);
369            }
370            if (req->isLocked() && fault == NoFault) {
371                assert(!locked);
372                locked = true;
373            }
374            return fault;
375        }
376
377        /*
378         * Set up for accessing the second cache line.
379         */
380
381        //Move the pointer we're reading into to the correct location.
382        dataPtr += dataSize;
383        //Adjust the size to get the remaining bytes.
384        dataSize = addr + sizeof(T) - secondAddr;
385        //And access the right address.
386        addr = secondAddr;
387    }
388}
389
390#ifndef DOXYGEN_SHOULD_SKIP_THIS
391
392template
393Fault
394AtomicSimpleCPU::read(Addr addr, Twin32_t &data, unsigned flags);
395
396template
397Fault
398AtomicSimpleCPU::read(Addr addr, Twin64_t &data, unsigned flags);
399
400template
401Fault
402AtomicSimpleCPU::read(Addr addr, uint64_t &data, unsigned flags);
403
404template
405Fault
406AtomicSimpleCPU::read(Addr addr, uint32_t &data, unsigned flags);
407
408template
409Fault
410AtomicSimpleCPU::read(Addr addr, uint16_t &data, unsigned flags);
411
412template
413Fault
414AtomicSimpleCPU::read(Addr addr, uint8_t &data, unsigned flags);
415
416#endif //DOXYGEN_SHOULD_SKIP_THIS
417
418template<>
419Fault
420AtomicSimpleCPU::read(Addr addr, double &data, unsigned flags)
421{
422    return read(addr, *(uint64_t*)&data, flags);
423}
424
425template<>
426Fault
427AtomicSimpleCPU::read(Addr addr, float &data, unsigned flags)
428{
429    return read(addr, *(uint32_t*)&data, flags);
430}
431
432
433template<>
434Fault
435AtomicSimpleCPU::read(Addr addr, int32_t &data, unsigned flags)
436{
437    return read(addr, (uint32_t&)data, flags);
438}
439
440
441template <class T>
442Fault
443AtomicSimpleCPU::write(T data, Addr addr, unsigned flags, uint64_t *res)
444{
445    // use the CPU's statically allocated write request and packet objects
446    Request *req = &data_write_req;
447
448    if (traceData) {
449        traceData->setAddr(addr);
450        traceData->setData(data);
451    }
452
453    data = htog(data);
454
455    //The block size of our peer.
456    unsigned blockSize = dcachePort.peerBlockSize();
457    //The size of the data we're trying to read.
458    int dataSize = sizeof(T);
459
460    uint8_t * dataPtr = (uint8_t *)&data;
461
462    //The address of the second part of this access if it needs to be split
463    //across a cache line boundary.
464    Addr secondAddr = roundDown(addr + dataSize - 1, blockSize);
465
466    if(secondAddr > addr)
467        dataSize = secondAddr - addr;
468
469    dcache_latency = 0;
470
471    while(1) {
472        req->setVirt(0, addr, dataSize, flags, thread->readPC());
473
474        // translate to physical address
475        Fault fault = thread->dtb->translateAtomic(req, tc, BaseTLB::Write);
476
477        // Now do the access.
478        if (fault == NoFault) {
479            MemCmd cmd = MemCmd::WriteReq; // default
480            bool do_access = true;  // flag to suppress cache access
481
482            if (req->isLLSC()) {
483                cmd = MemCmd::StoreCondReq;
484                do_access = TheISA::handleLockedWrite(thread, req);
485            } else if (req->isSwap()) {
486                cmd = MemCmd::SwapReq;
487                if (req->isCondSwap()) {
488                    assert(res);
489                    req->setExtraData(*res);
490                }
491            }
492
493            if (do_access && !req->getFlags().isSet(Request::NO_ACCESS)) {
494                Packet pkt = Packet(req, cmd, Packet::Broadcast);
495                pkt.dataStatic(dataPtr);
496
497                if (req->isMmapedIpr()) {
498                    dcache_latency +=
499                        TheISA::handleIprWrite(thread->getTC(), &pkt);
500                } else {
501                    if (hasPhysMemPort && pkt.getAddr() == physMemAddr)
502                        dcache_latency += physmemPort.sendAtomic(&pkt);
503                    else
504                        dcache_latency += dcachePort.sendAtomic(&pkt);
505                }
506                dcache_access = true;
507                assert(!pkt.isError());
508
509                if (req->isSwap()) {
510                    assert(res);
511                    *res = pkt.get<T>();
512                }
513            }
514
515            if (res && !req->isSwap()) {
516                *res = req->getExtraData();
517            }
518        }
519
520        //If there's a fault or we don't need to access a second cache line,
521        //stop now.
522        if (fault != NoFault || secondAddr <= addr)
523        {
524            if (req->isLocked() && fault == NoFault) {
525                assert(locked);
526                locked = false;
527            }
528            if (fault != NoFault && req->isPrefetch()) {
529                return NoFault;
530            } else {
531                return fault;
532            }
533        }
534
535        /*
536         * Set up for accessing the second cache line.
537         */
538
539        //Move the pointer we're reading into to the correct location.
540        dataPtr += dataSize;
541        //Adjust the size to get the remaining bytes.
542        dataSize = addr + sizeof(T) - secondAddr;
543        //And access the right address.
544        addr = secondAddr;
545    }
546}
547
548
549#ifndef DOXYGEN_SHOULD_SKIP_THIS
550
551template
552Fault
553AtomicSimpleCPU::write(Twin32_t data, Addr addr,
554                       unsigned flags, uint64_t *res);
555
556template
557Fault
558AtomicSimpleCPU::write(Twin64_t data, Addr addr,
559                       unsigned flags, uint64_t *res);
560
561template
562Fault
563AtomicSimpleCPU::write(uint64_t data, Addr addr,
564                       unsigned flags, uint64_t *res);
565
566template
567Fault
568AtomicSimpleCPU::write(uint32_t data, Addr addr,
569                       unsigned flags, uint64_t *res);
570
571template
572Fault
573AtomicSimpleCPU::write(uint16_t data, Addr addr,
574                       unsigned flags, uint64_t *res);
575
576template
577Fault
578AtomicSimpleCPU::write(uint8_t data, Addr addr,
579                       unsigned flags, uint64_t *res);
580
581#endif //DOXYGEN_SHOULD_SKIP_THIS
582
583template<>
584Fault
585AtomicSimpleCPU::write(double data, Addr addr, unsigned flags, uint64_t *res)
586{
587    return write(*(uint64_t*)&data, addr, flags, res);
588}
589
590template<>
591Fault
592AtomicSimpleCPU::write(float data, Addr addr, unsigned flags, uint64_t *res)
593{
594    return write(*(uint32_t*)&data, addr, flags, res);
595}
596
597
598template<>
599Fault
600AtomicSimpleCPU::write(int32_t data, Addr addr, unsigned flags, uint64_t *res)
601{
602    return write((uint32_t)data, addr, flags, res);
603}
604
605
606void
607AtomicSimpleCPU::tick()
608{
609    DPRINTF(SimpleCPU, "Tick\n");
610
611    Tick latency = 0;
612
613    for (int i = 0; i < width || locked; ++i) {
614        numCycles++;
615
616        if (!curStaticInst || !curStaticInst->isDelayedCommit())
617            checkForInterrupts();
618
619        checkPcEventQueue();
620
621        Fault fault = NoFault;
622
623        bool fromRom = isRomMicroPC(thread->readMicroPC());
624        if (!fromRom && !curMacroStaticInst) {
625            setupFetchRequest(&ifetch_req);
626            fault = thread->itb->translateAtomic(&ifetch_req, tc,
627                                                 BaseTLB::Execute);
628        }
629
630        if (fault == NoFault) {
631            Tick icache_latency = 0;
632            bool icache_access = false;
633            dcache_access = false; // assume no dcache access
634
635            if (!fromRom && !curMacroStaticInst) {
636                // This is commented out because the predecoder would act like
637                // a tiny cache otherwise. It wouldn't be flushed when needed
638                // like the I cache. It should be flushed, and when that works
639                // this code should be uncommented.
640                //Fetch more instruction memory if necessary
641                //if(predecoder.needMoreBytes())
642                //{
643                    icache_access = true;
644                    Packet ifetch_pkt = Packet(&ifetch_req, MemCmd::ReadReq,
645                                               Packet::Broadcast);
646                    ifetch_pkt.dataStatic(&inst);
647
648                    if (hasPhysMemPort && ifetch_pkt.getAddr() == physMemAddr)
649                        icache_latency = physmemPort.sendAtomic(&ifetch_pkt);
650                    else
651                        icache_latency = icachePort.sendAtomic(&ifetch_pkt);
652
653                    assert(!ifetch_pkt.isError());
654
655                    // ifetch_req is initialized to read the instruction directly
656                    // into the CPU object's inst field.
657                //}
658            }
659
660            preExecute();
661
662            if (curStaticInst) {
663                fault = curStaticInst->execute(this, traceData);
664
665                // keep an instruction count
666                if (fault == NoFault)
667                    countInst();
668                else if (traceData) {
669                    // If there was a fault, we should trace this instruction.
670                    delete traceData;
671                    traceData = NULL;
672                }
673
674                postExecute();
675            }
676
677            // @todo remove me after debugging with legion done
678            if (curStaticInst && (!curStaticInst->isMicroop() ||
679                        curStaticInst->isFirstMicroop()))
680                instCnt++;
681
682            Tick stall_ticks = 0;
683            if (simulate_inst_stalls && icache_access)
684                stall_ticks += icache_latency;
685
686            if (simulate_data_stalls && dcache_access)
687                stall_ticks += dcache_latency;
688
689            if (stall_ticks) {
690                Tick stall_cycles = stall_ticks / ticks(1);
691                Tick aligned_stall_ticks = ticks(stall_cycles);
692
693                if (aligned_stall_ticks < stall_ticks)
694                    aligned_stall_ticks += 1;
695
696                latency += aligned_stall_ticks;
697            }
698
699        }
700        if(fault != NoFault || !stayAtPC)
701            advancePC(fault);
702    }
703
704    // instruction takes at least one cycle
705    if (latency < ticks(1))
706        latency = ticks(1);
707
708    if (_status != Idle)
709        schedule(tickEvent, curTick + latency);
710}
711
712
713void
714AtomicSimpleCPU::printAddr(Addr a)
715{
716    dcachePort.printAddr(a);
717}
718
719
720////////////////////////////////////////////////////////////////////////
721//
722//  AtomicSimpleCPU Simulation Object
723//
724AtomicSimpleCPU *
725AtomicSimpleCPUParams::create()
726{
727    numThreads = 1;
728#if !FULL_SYSTEM
729    if (workload.size() != 1)
730        panic("only one workload allowed");
731#endif
732    return new AtomicSimpleCPU(this);
733}
734