atomic.cc revision 3387
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/utility.hh"
33#include "cpu/exetrace.hh"
34#include "cpu/simple/atomic.hh"
35#include "mem/packet.hh"
36#include "mem/packet_access.hh"
37#include "sim/builder.hh"
38#include "sim/system.hh"
39
40using namespace std;
41using namespace TheISA;
42
43AtomicSimpleCPU::TickEvent::TickEvent(AtomicSimpleCPU *c)
44    : Event(&mainEventQueue, CPU_Tick_Pri), cpu(c)
45{
46}
47
48
49void
50AtomicSimpleCPU::TickEvent::process()
51{
52    cpu->tick();
53}
54
55const char *
56AtomicSimpleCPU::TickEvent::description()
57{
58    return "AtomicSimpleCPU tick event";
59}
60
61Port *
62AtomicSimpleCPU::getPort(const std::string &if_name, int idx)
63{
64    if (if_name == "dcache_port")
65        return &dcachePort;
66    else if (if_name == "icache_port")
67        return &icachePort;
68    else
69        panic("No Such Port\n");
70}
71
72void
73AtomicSimpleCPU::init()
74{
75    //Create Memory Ports (conect them up)
76//    Port *mem_dport = mem->getPort("");
77//    dcachePort.setPeer(mem_dport);
78//    mem_dport->setPeer(&dcachePort);
79
80//    Port *mem_iport = mem->getPort("");
81//    icachePort.setPeer(mem_iport);
82//    mem_iport->setPeer(&icachePort);
83
84    BaseCPU::init();
85#if FULL_SYSTEM
86    for (int i = 0; i < threadContexts.size(); ++i) {
87        ThreadContext *tc = threadContexts[i];
88
89        // initialize CPU, including PC
90        TheISA::initCPU(tc, tc->readCpuId());
91    }
92#endif
93}
94
95bool
96AtomicSimpleCPU::CpuPort::recvTiming(PacketPtr pkt)
97{
98    panic("AtomicSimpleCPU doesn't expect recvTiming callback!");
99    return true;
100}
101
102Tick
103AtomicSimpleCPU::CpuPort::recvAtomic(PacketPtr pkt)
104{
105    //Snooping a coherence request, just return
106    return curTick;
107}
108
109void
110AtomicSimpleCPU::CpuPort::recvFunctional(PacketPtr pkt)
111{
112    //No internal storage to update, just return
113    return;
114}
115
116void
117AtomicSimpleCPU::CpuPort::recvStatusChange(Status status)
118{
119    if (status == RangeChange)
120        return;
121
122    panic("AtomicSimpleCPU doesn't expect recvStatusChange callback!");
123}
124
125void
126AtomicSimpleCPU::CpuPort::recvRetry()
127{
128    panic("AtomicSimpleCPU doesn't expect recvRetry callback!");
129}
130
131
132AtomicSimpleCPU::AtomicSimpleCPU(Params *p)
133    : BaseSimpleCPU(p), tickEvent(this),
134      width(p->width), simulate_stalls(p->simulate_stalls),
135      icachePort(name() + "-iport", this), dcachePort(name() + "-iport", this)
136{
137    _status = Idle;
138
139    ifetch_req = new Request();
140    ifetch_req->setThreadContext(p->cpu_id, 0); // Add thread ID if we add MT
141    ifetch_pkt = new Packet(ifetch_req, Packet::ReadReq, Packet::Broadcast);
142    ifetch_pkt->dataStatic(&inst);
143
144    data_read_req = new Request();
145    data_read_req->setThreadContext(p->cpu_id, 0); // Add thread ID here too
146    data_read_pkt = new Packet(data_read_req, Packet::ReadReq,
147                               Packet::Broadcast);
148    data_read_pkt->dataStatic(&dataReg);
149
150    data_write_req = new Request();
151    data_write_req->setThreadContext(p->cpu_id, 0); // Add thread ID here too
152    data_write_pkt = new Packet(data_write_req, Packet::WriteReq,
153                                Packet::Broadcast);
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    changeState(SimObject::Running);
187    if (thread->status() == ThreadContext::Active) {
188        assert(system->getMemoryMode() == System::Atomic);
189        if (!tickEvent.scheduled())
190            tickEvent.schedule(curTick);
191    }
192}
193
194void
195AtomicSimpleCPU::switchOut()
196{
197    assert(status() == Running || status() == Idle);
198    _status = SwitchedOut;
199
200    tickEvent.squash();
201}
202
203
204void
205AtomicSimpleCPU::takeOverFrom(BaseCPU *oldCPU)
206{
207    BaseCPU::takeOverFrom(oldCPU);
208
209    assert(!tickEvent.scheduled());
210
211    // if any of this CPU's ThreadContexts are active, mark the CPU as
212    // running and schedule its tick event.
213    for (int i = 0; i < threadContexts.size(); ++i) {
214        ThreadContext *tc = threadContexts[i];
215        if (tc->status() == ThreadContext::Active && _status != Running) {
216            _status = Running;
217            tickEvent.schedule(curTick);
218            break;
219        }
220    }
221}
222
223
224void
225AtomicSimpleCPU::activateContext(int thread_num, int delay)
226{
227    assert(thread_num == 0);
228    assert(thread);
229
230    assert(_status == Idle);
231    assert(!tickEvent.scheduled());
232
233    notIdleFraction++;
234    tickEvent.schedule(curTick + cycles(delay));
235    _status = Running;
236}
237
238
239void
240AtomicSimpleCPU::suspendContext(int thread_num)
241{
242    assert(thread_num == 0);
243    assert(thread);
244
245    assert(_status == Running);
246
247    // tick event may not be scheduled if this gets called from inside
248    // an instruction's execution, e.g. "quiesce"
249    if (tickEvent.scheduled())
250        tickEvent.deschedule();
251
252    notIdleFraction--;
253    _status = Idle;
254}
255
256
257template <class T>
258Fault
259AtomicSimpleCPU::read(Addr addr, T &data, unsigned flags)
260{
261    // use the CPU's statically allocated read request and packet objects
262    Request *req = data_read_req;
263    PacketPtr pkt = data_read_pkt;
264
265    req->setVirt(0, addr, sizeof(T), flags, thread->readPC());
266
267    if (traceData) {
268        traceData->setAddr(addr);
269    }
270
271    // translate to physical address
272    Fault fault = thread->translateDataReadReq(req);
273
274    // Now do the access.
275    if (fault == NoFault) {
276        pkt->reinitFromRequest();
277
278        dcache_latency = dcachePort.sendAtomic(pkt);
279        dcache_access = true;
280
281        assert(pkt->result == Packet::Success);
282        data = pkt->get<T>();
283
284        if (req->isLocked()) {
285            TheISA::handleLockedRead(thread, req);
286        }
287    }
288
289    // This will need a new way to tell if it has a dcache attached.
290    if (req->isUncacheable())
291        recordEvent("Uncached Read");
292
293    return fault;
294}
295
296#ifndef DOXYGEN_SHOULD_SKIP_THIS
297
298template
299Fault
300AtomicSimpleCPU::read(Addr addr, uint64_t &data, unsigned flags);
301
302template
303Fault
304AtomicSimpleCPU::read(Addr addr, uint32_t &data, unsigned flags);
305
306template
307Fault
308AtomicSimpleCPU::read(Addr addr, uint16_t &data, unsigned flags);
309
310template
311Fault
312AtomicSimpleCPU::read(Addr addr, uint8_t &data, unsigned flags);
313
314#endif //DOXYGEN_SHOULD_SKIP_THIS
315
316template<>
317Fault
318AtomicSimpleCPU::read(Addr addr, double &data, unsigned flags)
319{
320    return read(addr, *(uint64_t*)&data, flags);
321}
322
323template<>
324Fault
325AtomicSimpleCPU::read(Addr addr, float &data, unsigned flags)
326{
327    return read(addr, *(uint32_t*)&data, flags);
328}
329
330
331template<>
332Fault
333AtomicSimpleCPU::read(Addr addr, int32_t &data, unsigned flags)
334{
335    return read(addr, (uint32_t&)data, flags);
336}
337
338
339template <class T>
340Fault
341AtomicSimpleCPU::write(T data, Addr addr, unsigned flags, uint64_t *res)
342{
343    // use the CPU's statically allocated write request and packet objects
344    Request *req = data_write_req;
345    PacketPtr pkt = data_write_pkt;
346
347    req->setVirt(0, addr, sizeof(T), flags, thread->readPC());
348
349    if (traceData) {
350        traceData->setAddr(addr);
351    }
352
353    // translate to physical address
354    Fault fault = thread->translateDataWriteReq(req);
355
356    // Now do the access.
357    if (fault == NoFault) {
358        bool do_access = true;  // flag to suppress cache access
359
360        if (req->isLocked()) {
361            do_access = TheISA::handleLockedWrite(thread, req);
362        }
363
364        if (do_access) {
365            data = htog(data);
366            pkt->reinitFromRequest();
367            pkt->dataStatic(&data);
368
369            dcache_latency = dcachePort.sendAtomic(pkt);
370            dcache_access = true;
371
372            assert(pkt->result == Packet::Success);
373        }
374
375        if (req->isLocked()) {
376            uint64_t scResult = req->getScResult();
377            if (scResult != 0) {
378                // clear failure counter
379                thread->setStCondFailures(0);
380            }
381            if (res) {
382                *res = req->getScResult();
383            }
384        }
385    }
386
387    // This will need a new way to tell if it's hooked up to a cache or not.
388    if (req->isUncacheable())
389        recordEvent("Uncached Write");
390
391    // If the write needs to have a fault on the access, consider calling
392    // changeStatus() and changing it to "bad addr write" or something.
393    return fault;
394}
395
396
397#ifndef DOXYGEN_SHOULD_SKIP_THIS
398template
399Fault
400AtomicSimpleCPU::write(uint64_t data, Addr addr,
401                       unsigned flags, uint64_t *res);
402
403template
404Fault
405AtomicSimpleCPU::write(uint32_t data, Addr addr,
406                       unsigned flags, uint64_t *res);
407
408template
409Fault
410AtomicSimpleCPU::write(uint16_t data, Addr addr,
411                       unsigned flags, uint64_t *res);
412
413template
414Fault
415AtomicSimpleCPU::write(uint8_t data, Addr addr,
416                       unsigned flags, uint64_t *res);
417
418#endif //DOXYGEN_SHOULD_SKIP_THIS
419
420template<>
421Fault
422AtomicSimpleCPU::write(double data, Addr addr, unsigned flags, uint64_t *res)
423{
424    return write(*(uint64_t*)&data, addr, flags, res);
425}
426
427template<>
428Fault
429AtomicSimpleCPU::write(float data, Addr addr, unsigned flags, uint64_t *res)
430{
431    return write(*(uint32_t*)&data, addr, flags, res);
432}
433
434
435template<>
436Fault
437AtomicSimpleCPU::write(int32_t data, Addr addr, unsigned flags, uint64_t *res)
438{
439    return write((uint32_t)data, addr, flags, res);
440}
441
442
443void
444AtomicSimpleCPU::tick()
445{
446    Tick latency = cycles(1); // instruction takes one cycle by default
447
448    for (int i = 0; i < width; ++i) {
449        numCycles++;
450
451        if (!curStaticInst || !curStaticInst->isDelayedCommit())
452            checkForInterrupts();
453
454        Fault fault = setupFetchRequest(ifetch_req);
455
456        if (fault == NoFault) {
457            ifetch_pkt->reinitFromRequest();
458
459            Tick icache_latency = icachePort.sendAtomic(ifetch_pkt);
460            // ifetch_req is initialized to read the instruction directly
461            // into the CPU object's inst field.
462
463            dcache_access = false; // assume no dcache access
464            preExecute();
465            fault = curStaticInst->execute(this, traceData);
466            postExecute();
467
468            if (simulate_stalls) {
469                Tick icache_stall = icache_latency - cycles(1);
470                Tick dcache_stall =
471                    dcache_access ? dcache_latency - cycles(1) : 0;
472                Tick stall_cycles = (icache_stall + dcache_stall) / cycles(1);
473                if (cycles(stall_cycles) < (icache_stall + dcache_stall))
474                    latency += cycles(stall_cycles+1);
475                else
476                    latency += cycles(stall_cycles);
477            }
478
479        }
480
481        advancePC(fault);
482    }
483
484    if (_status != Idle)
485        tickEvent.schedule(curTick + latency);
486}
487
488
489////////////////////////////////////////////////////////////////////////
490//
491//  AtomicSimpleCPU Simulation Object
492//
493BEGIN_DECLARE_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
494
495    Param<Counter> max_insts_any_thread;
496    Param<Counter> max_insts_all_threads;
497    Param<Counter> max_loads_any_thread;
498    Param<Counter> max_loads_all_threads;
499    Param<Tick> progress_interval;
500    SimObjectParam<MemObject *> mem;
501    SimObjectParam<System *> system;
502    Param<int> cpu_id;
503
504#if FULL_SYSTEM
505    SimObjectParam<AlphaITB *> itb;
506    SimObjectParam<AlphaDTB *> dtb;
507    Param<Tick> profile;
508#else
509    SimObjectParam<Process *> workload;
510#endif // FULL_SYSTEM
511
512    Param<int> clock;
513
514    Param<bool> defer_registration;
515    Param<int> width;
516    Param<bool> function_trace;
517    Param<Tick> function_trace_start;
518    Param<bool> simulate_stalls;
519
520END_DECLARE_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
521
522BEGIN_INIT_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
523
524    INIT_PARAM(max_insts_any_thread,
525               "terminate when any thread reaches this inst count"),
526    INIT_PARAM(max_insts_all_threads,
527               "terminate when all threads have reached this inst count"),
528    INIT_PARAM(max_loads_any_thread,
529               "terminate when any thread reaches this load count"),
530    INIT_PARAM(max_loads_all_threads,
531               "terminate when all threads have reached this load count"),
532    INIT_PARAM(progress_interval, "Progress interval"),
533    INIT_PARAM(mem, "memory"),
534    INIT_PARAM(system, "system object"),
535    INIT_PARAM(cpu_id, "processor ID"),
536
537#if FULL_SYSTEM
538    INIT_PARAM(itb, "Instruction TLB"),
539    INIT_PARAM(dtb, "Data TLB"),
540    INIT_PARAM(profile, ""),
541#else
542    INIT_PARAM(workload, "processes to run"),
543#endif // FULL_SYSTEM
544
545    INIT_PARAM(clock, "clock speed"),
546    INIT_PARAM(defer_registration, "defer system registration (for sampling)"),
547    INIT_PARAM(width, "cpu width"),
548    INIT_PARAM(function_trace, "Enable function trace"),
549    INIT_PARAM(function_trace_start, "Cycle to start function trace"),
550    INIT_PARAM(simulate_stalls, "Simulate cache stall cycles")
551
552END_INIT_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
553
554
555CREATE_SIM_OBJECT(AtomicSimpleCPU)
556{
557    AtomicSimpleCPU::Params *params = new AtomicSimpleCPU::Params();
558    params->name = getInstanceName();
559    params->numberOfThreads = 1;
560    params->max_insts_any_thread = max_insts_any_thread;
561    params->max_insts_all_threads = max_insts_all_threads;
562    params->max_loads_any_thread = max_loads_any_thread;
563    params->max_loads_all_threads = max_loads_all_threads;
564    params->progress_interval = progress_interval;
565    params->deferRegistration = defer_registration;
566    params->clock = clock;
567    params->functionTrace = function_trace;
568    params->functionTraceStart = function_trace_start;
569    params->width = width;
570    params->simulate_stalls = simulate_stalls;
571    params->mem = mem;
572    params->system = system;
573    params->cpu_id = cpu_id;
574
575#if FULL_SYSTEM
576    params->itb = itb;
577    params->dtb = dtb;
578    params->profile = profile;
579#else
580    params->process = workload;
581#endif
582
583    AtomicSimpleCPU *cpu = new AtomicSimpleCPU(params);
584    return cpu;
585}
586
587REGISTER_SIM_OBJECT("AtomicSimpleCPU", AtomicSimpleCPU)
588
589