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