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