atomic.cc revision 7046:d21d575a6f99
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    //The block size of our peer.
454    unsigned blockSize = dcachePort.peerBlockSize();
455    //The size of the data we're trying to read.
456    int dataSize = sizeof(T);
457
458    uint8_t * dataPtr = (uint8_t *)&data;
459
460    //The address of the second part of this access if it needs to be split
461    //across a cache line boundary.
462    Addr secondAddr = roundDown(addr + dataSize - 1, blockSize);
463
464    if(secondAddr > addr)
465        dataSize = secondAddr - addr;
466
467    dcache_latency = 0;
468
469    while(1) {
470        req->setVirt(0, addr, dataSize, flags, thread->readPC());
471
472        // translate to physical address
473        Fault fault = thread->dtb->translateAtomic(req, tc, BaseTLB::Write);
474
475        // Now do the access.
476        if (fault == NoFault) {
477            MemCmd cmd = MemCmd::WriteReq; // default
478            bool do_access = true;  // flag to suppress cache access
479
480            if (req->isLLSC()) {
481                cmd = MemCmd::StoreCondReq;
482                do_access = TheISA::handleLockedWrite(thread, req);
483            } else if (req->isSwap()) {
484                cmd = MemCmd::SwapReq;
485                if (req->isCondSwap()) {
486                    assert(res);
487                    req->setExtraData(*res);
488                }
489            }
490
491            if (do_access && !req->getFlags().isSet(Request::NO_ACCESS)) {
492                Packet pkt = Packet(req, cmd, Packet::Broadcast);
493                pkt.dataStatic(dataPtr);
494
495                if (req->isMmapedIpr()) {
496                    dcache_latency +=
497                        TheISA::handleIprWrite(thread->getTC(), &pkt);
498                } else {
499                    //XXX This needs to be outside of the loop in order to
500                    //work properly for cache line boundary crossing
501                    //accesses in transendian simulations.
502                    data = htog(data);
503                    if (hasPhysMemPort && pkt.getAddr() == physMemAddr)
504                        dcache_latency += physmemPort.sendAtomic(&pkt);
505                    else
506                        dcache_latency += dcachePort.sendAtomic(&pkt);
507                }
508                dcache_access = true;
509                assert(!pkt.isError());
510
511                if (req->isSwap()) {
512                    assert(res);
513                    *res = pkt.get<T>();
514                }
515            }
516
517            if (res && !req->isSwap()) {
518                *res = req->getExtraData();
519            }
520        }
521
522        //If there's a fault or we don't need to access a second cache line,
523        //stop now.
524        if (fault != NoFault || secondAddr <= addr)
525        {
526            if (req->isLocked() && fault == NoFault) {
527                assert(locked);
528                locked = false;
529            }
530            if (fault != NoFault && req->isPrefetch()) {
531                return NoFault;
532            } else {
533                return fault;
534            }
535        }
536
537        /*
538         * Set up for accessing the second cache line.
539         */
540
541        //Move the pointer we're reading into to the correct location.
542        dataPtr += dataSize;
543        //Adjust the size to get the remaining bytes.
544        dataSize = addr + sizeof(T) - secondAddr;
545        //And access the right address.
546        addr = secondAddr;
547    }
548}
549
550
551#ifndef DOXYGEN_SHOULD_SKIP_THIS
552
553template
554Fault
555AtomicSimpleCPU::write(Twin32_t data, Addr addr,
556                       unsigned flags, uint64_t *res);
557
558template
559Fault
560AtomicSimpleCPU::write(Twin64_t data, Addr addr,
561                       unsigned flags, uint64_t *res);
562
563template
564Fault
565AtomicSimpleCPU::write(uint64_t data, Addr addr,
566                       unsigned flags, uint64_t *res);
567
568template
569Fault
570AtomicSimpleCPU::write(uint32_t data, Addr addr,
571                       unsigned flags, uint64_t *res);
572
573template
574Fault
575AtomicSimpleCPU::write(uint16_t data, Addr addr,
576                       unsigned flags, uint64_t *res);
577
578template
579Fault
580AtomicSimpleCPU::write(uint8_t data, Addr addr,
581                       unsigned flags, uint64_t *res);
582
583#endif //DOXYGEN_SHOULD_SKIP_THIS
584
585template<>
586Fault
587AtomicSimpleCPU::write(double data, Addr addr, unsigned flags, uint64_t *res)
588{
589    return write(*(uint64_t*)&data, addr, flags, res);
590}
591
592template<>
593Fault
594AtomicSimpleCPU::write(float data, Addr addr, unsigned flags, uint64_t *res)
595{
596    return write(*(uint32_t*)&data, addr, flags, res);
597}
598
599
600template<>
601Fault
602AtomicSimpleCPU::write(int32_t data, Addr addr, unsigned flags, uint64_t *res)
603{
604    return write((uint32_t)data, addr, flags, res);
605}
606
607
608void
609AtomicSimpleCPU::tick()
610{
611    DPRINTF(SimpleCPU, "Tick\n");
612
613    Tick latency = 0;
614
615    for (int i = 0; i < width || locked; ++i) {
616        numCycles++;
617
618        if (!curStaticInst || !curStaticInst->isDelayedCommit())
619            checkForInterrupts();
620
621        checkPcEventQueue();
622
623        Fault fault = NoFault;
624
625        bool fromRom = isRomMicroPC(thread->readMicroPC());
626        if (!fromRom && !curMacroStaticInst) {
627            setupFetchRequest(&ifetch_req);
628            fault = thread->itb->translateAtomic(&ifetch_req, tc,
629                                                 BaseTLB::Execute);
630        }
631
632        if (fault == NoFault) {
633            Tick icache_latency = 0;
634            bool icache_access = false;
635            dcache_access = false; // assume no dcache access
636
637            if (!fromRom && !curMacroStaticInst) {
638                // This is commented out because the predecoder would act like
639                // a tiny cache otherwise. It wouldn't be flushed when needed
640                // like the I cache. It should be flushed, and when that works
641                // this code should be uncommented.
642                //Fetch more instruction memory if necessary
643                //if(predecoder.needMoreBytes())
644                //{
645                    icache_access = true;
646                    Packet ifetch_pkt = Packet(&ifetch_req, MemCmd::ReadReq,
647                                               Packet::Broadcast);
648                    ifetch_pkt.dataStatic(&inst);
649
650                    if (hasPhysMemPort && ifetch_pkt.getAddr() == physMemAddr)
651                        icache_latency = physmemPort.sendAtomic(&ifetch_pkt);
652                    else
653                        icache_latency = icachePort.sendAtomic(&ifetch_pkt);
654
655                    assert(!ifetch_pkt.isError());
656
657                    // ifetch_req is initialized to read the instruction directly
658                    // into the CPU object's inst field.
659                //}
660            }
661
662            preExecute();
663
664            if (curStaticInst) {
665                fault = curStaticInst->execute(this, traceData);
666
667                // keep an instruction count
668                if (fault == NoFault)
669                    countInst();
670                else if (traceData) {
671                    // If there was a fault, we should trace this instruction.
672                    delete traceData;
673                    traceData = NULL;
674                }
675
676                postExecute();
677            }
678
679            // @todo remove me after debugging with legion done
680            if (curStaticInst && (!curStaticInst->isMicroop() ||
681                        curStaticInst->isFirstMicroop()))
682                instCnt++;
683
684            Tick stall_ticks = 0;
685            if (simulate_inst_stalls && icache_access)
686                stall_ticks += icache_latency;
687
688            if (simulate_data_stalls && dcache_access)
689                stall_ticks += dcache_latency;
690
691            if (stall_ticks) {
692                Tick stall_cycles = stall_ticks / ticks(1);
693                Tick aligned_stall_ticks = ticks(stall_cycles);
694
695                if (aligned_stall_ticks < stall_ticks)
696                    aligned_stall_ticks += 1;
697
698                latency += aligned_stall_ticks;
699            }
700
701        }
702        if(fault != NoFault || !stayAtPC)
703            advancePC(fault);
704    }
705
706    // instruction takes at least one cycle
707    if (latency < ticks(1))
708        latency = ticks(1);
709
710    if (_status != Idle)
711        schedule(tickEvent, curTick + latency);
712}
713
714
715void
716AtomicSimpleCPU::printAddr(Addr a)
717{
718    dcachePort.printAddr(a);
719}
720
721
722////////////////////////////////////////////////////////////////////////
723//
724//  AtomicSimpleCPU Simulation Object
725//
726AtomicSimpleCPU *
727AtomicSimpleCPUParams::create()
728{
729    numThreads = 1;
730#if !FULL_SYSTEM
731    if (workload.size() != 1)
732        panic("only one workload allowed");
733#endif
734    return new AtomicSimpleCPU(this);
735}
736