atomic.cc revision 3495:884bf1f0c0c9
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(nextCycle());
184            }
185        }
186    }
187}
188
189void
190AtomicSimpleCPU::switchOut()
191{
192    assert(status() == Running || status() == Idle);
193    _status = SwitchedOut;
194
195    tickEvent.squash();
196}
197
198
199void
200AtomicSimpleCPU::takeOverFrom(BaseCPU *oldCPU)
201{
202    BaseCPU::takeOverFrom(oldCPU);
203
204    assert(!tickEvent.scheduled());
205
206    // if any of this CPU's ThreadContexts are active, mark the CPU as
207    // running and schedule its tick event.
208    for (int i = 0; i < threadContexts.size(); ++i) {
209        ThreadContext *tc = threadContexts[i];
210        if (tc->status() == ThreadContext::Active && _status != Running) {
211            _status = Running;
212            tickEvent.schedule(nextCycle());
213            break;
214        }
215    }
216}
217
218
219void
220AtomicSimpleCPU::activateContext(int thread_num, int delay)
221{
222    assert(thread_num == 0);
223    assert(thread);
224
225    assert(_status == Idle);
226    assert(!tickEvent.scheduled());
227
228    notIdleFraction++;
229    //Make sure ticks are still on multiples of cycles
230    tickEvent.schedule(nextCycle(curTick + cycles(delay)));
231    _status = Running;
232}
233
234
235void
236AtomicSimpleCPU::suspendContext(int thread_num)
237{
238    assert(thread_num == 0);
239    assert(thread);
240
241    assert(_status == Running);
242
243    // tick event may not be scheduled if this gets called from inside
244    // an instruction's execution, e.g. "quiesce"
245    if (tickEvent.scheduled())
246        tickEvent.deschedule();
247
248    notIdleFraction--;
249    _status = Idle;
250}
251
252
253template <class T>
254Fault
255AtomicSimpleCPU::read(Addr addr, T &data, unsigned flags)
256{
257    // use the CPU's statically allocated read request and packet objects
258    Request *req = data_read_req;
259    PacketPtr pkt = data_read_pkt;
260
261    req->setVirt(0, addr, sizeof(T), flags, thread->readPC());
262
263    if (traceData) {
264        traceData->setAddr(addr);
265    }
266
267    // translate to physical address
268    Fault fault = thread->translateDataReadReq(req);
269
270    // Now do the access.
271    if (fault == NoFault) {
272        pkt->reinitFromRequest();
273
274        dcache_latency = dcachePort.sendAtomic(pkt);
275        dcache_access = true;
276
277        assert(pkt->result == Packet::Success);
278        data = pkt->get<T>();
279
280        if (req->isLocked()) {
281            TheISA::handleLockedRead(thread, req);
282        }
283    }
284
285    // This will need a new way to tell if it has a dcache attached.
286    if (req->isUncacheable())
287        recordEvent("Uncached Read");
288
289    return fault;
290}
291
292#ifndef DOXYGEN_SHOULD_SKIP_THIS
293
294template
295Fault
296AtomicSimpleCPU::read(Addr addr, uint64_t &data, unsigned flags);
297
298template
299Fault
300AtomicSimpleCPU::read(Addr addr, uint32_t &data, unsigned flags);
301
302template
303Fault
304AtomicSimpleCPU::read(Addr addr, uint16_t &data, unsigned flags);
305
306template
307Fault
308AtomicSimpleCPU::read(Addr addr, uint8_t &data, unsigned flags);
309
310#endif //DOXYGEN_SHOULD_SKIP_THIS
311
312template<>
313Fault
314AtomicSimpleCPU::read(Addr addr, double &data, unsigned flags)
315{
316    return read(addr, *(uint64_t*)&data, flags);
317}
318
319template<>
320Fault
321AtomicSimpleCPU::read(Addr addr, float &data, unsigned flags)
322{
323    return read(addr, *(uint32_t*)&data, flags);
324}
325
326
327template<>
328Fault
329AtomicSimpleCPU::read(Addr addr, int32_t &data, unsigned flags)
330{
331    return read(addr, (uint32_t&)data, flags);
332}
333
334
335template <class T>
336Fault
337AtomicSimpleCPU::write(T data, Addr addr, unsigned flags, uint64_t *res)
338{
339    // use the CPU's statically allocated write request and packet objects
340    Request *req = data_write_req;
341    PacketPtr pkt = data_write_pkt;
342
343    req->setVirt(0, addr, sizeof(T), flags, thread->readPC());
344
345    if (traceData) {
346        traceData->setAddr(addr);
347    }
348
349    // translate to physical address
350    Fault fault = thread->translateDataWriteReq(req);
351
352    // Now do the access.
353    if (fault == NoFault) {
354        bool do_access = true;  // flag to suppress cache access
355
356        if (req->isLocked()) {
357            do_access = TheISA::handleLockedWrite(thread, req);
358        }
359
360        if (do_access) {
361            data = htog(data);
362            pkt->reinitFromRequest();
363            pkt->dataStatic(&data);
364
365            dcache_latency = dcachePort.sendAtomic(pkt);
366            dcache_access = true;
367
368            assert(pkt->result == Packet::Success);
369        }
370
371        if (req->isLocked()) {
372            uint64_t scResult = req->getScResult();
373            if (scResult != 0) {
374                // clear failure counter
375                thread->setStCondFailures(0);
376            }
377            if (res) {
378                *res = req->getScResult();
379            }
380        }
381    }
382
383    // This will need a new way to tell if it's hooked up to a cache or not.
384    if (req->isUncacheable())
385        recordEvent("Uncached Write");
386
387    // If the write needs to have a fault on the access, consider calling
388    // changeStatus() and changing it to "bad addr write" or something.
389    return fault;
390}
391
392
393#ifndef DOXYGEN_SHOULD_SKIP_THIS
394template
395Fault
396AtomicSimpleCPU::write(uint64_t data, Addr addr,
397                       unsigned flags, uint64_t *res);
398
399template
400Fault
401AtomicSimpleCPU::write(uint32_t data, Addr addr,
402                       unsigned flags, uint64_t *res);
403
404template
405Fault
406AtomicSimpleCPU::write(uint16_t data, Addr addr,
407                       unsigned flags, uint64_t *res);
408
409template
410Fault
411AtomicSimpleCPU::write(uint8_t data, Addr addr,
412                       unsigned flags, uint64_t *res);
413
414#endif //DOXYGEN_SHOULD_SKIP_THIS
415
416template<>
417Fault
418AtomicSimpleCPU::write(double data, Addr addr, unsigned flags, uint64_t *res)
419{
420    return write(*(uint64_t*)&data, addr, flags, res);
421}
422
423template<>
424Fault
425AtomicSimpleCPU::write(float data, Addr addr, unsigned flags, uint64_t *res)
426{
427    return write(*(uint32_t*)&data, addr, flags, res);
428}
429
430
431template<>
432Fault
433AtomicSimpleCPU::write(int32_t data, Addr addr, unsigned flags, uint64_t *res)
434{
435    return write((uint32_t)data, addr, flags, res);
436}
437
438
439void
440AtomicSimpleCPU::tick()
441{
442    Tick latency = cycles(1); // instruction takes one cycle by default
443
444    for (int i = 0; i < width; ++i) {
445        numCycles++;
446
447        if (!curStaticInst || !curStaticInst->isDelayedCommit())
448            checkForInterrupts();
449
450        Fault fault = setupFetchRequest(ifetch_req);
451
452        if (fault == NoFault) {
453            ifetch_pkt->reinitFromRequest();
454
455            Tick icache_latency = icachePort.sendAtomic(ifetch_pkt);
456            // ifetch_req is initialized to read the instruction directly
457            // into the CPU object's inst field.
458
459            dcache_access = false; // assume no dcache access
460            preExecute();
461            fault = curStaticInst->execute(this, traceData);
462            postExecute();
463
464            if (simulate_stalls) {
465                Tick icache_stall = icache_latency - cycles(1);
466                Tick dcache_stall =
467                    dcache_access ? dcache_latency - cycles(1) : 0;
468                Tick stall_cycles = (icache_stall + dcache_stall) / cycles(1);
469                if (cycles(stall_cycles) < (icache_stall + dcache_stall))
470                    latency += cycles(stall_cycles+1);
471                else
472                    latency += cycles(stall_cycles);
473            }
474
475        }
476
477        advancePC(fault);
478    }
479
480    if (_status != Idle)
481        tickEvent.schedule(curTick + latency);
482}
483
484
485////////////////////////////////////////////////////////////////////////
486//
487//  AtomicSimpleCPU Simulation Object
488//
489BEGIN_DECLARE_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
490
491    Param<Counter> max_insts_any_thread;
492    Param<Counter> max_insts_all_threads;
493    Param<Counter> max_loads_any_thread;
494    Param<Counter> max_loads_all_threads;
495    Param<Tick> progress_interval;
496    SimObjectParam<System *> system;
497    Param<int> cpu_id;
498
499#if FULL_SYSTEM
500    SimObjectParam<TheISA::ITB *> itb;
501    SimObjectParam<TheISA::DTB *> dtb;
502    Param<Tick> profile;
503#else
504    SimObjectParam<Process *> workload;
505#endif // FULL_SYSTEM
506
507    Param<int> clock;
508
509    Param<bool> defer_registration;
510    Param<int> width;
511    Param<bool> function_trace;
512    Param<Tick> function_trace_start;
513    Param<bool> simulate_stalls;
514
515END_DECLARE_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
516
517BEGIN_INIT_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
518
519    INIT_PARAM(max_insts_any_thread,
520               "terminate when any thread reaches this inst count"),
521    INIT_PARAM(max_insts_all_threads,
522               "terminate when all threads have reached this inst count"),
523    INIT_PARAM(max_loads_any_thread,
524               "terminate when any thread reaches this load count"),
525    INIT_PARAM(max_loads_all_threads,
526               "terminate when all threads have reached this load count"),
527    INIT_PARAM(progress_interval, "Progress interval"),
528    INIT_PARAM(system, "system object"),
529    INIT_PARAM(cpu_id, "processor ID"),
530
531#if FULL_SYSTEM
532    INIT_PARAM(itb, "Instruction TLB"),
533    INIT_PARAM(dtb, "Data TLB"),
534    INIT_PARAM(profile, ""),
535#else
536    INIT_PARAM(workload, "processes to run"),
537#endif // FULL_SYSTEM
538
539    INIT_PARAM(clock, "clock speed"),
540    INIT_PARAM(defer_registration, "defer system registration (for sampling)"),
541    INIT_PARAM(width, "cpu width"),
542    INIT_PARAM(function_trace, "Enable function trace"),
543    INIT_PARAM(function_trace_start, "Cycle to start function trace"),
544    INIT_PARAM(simulate_stalls, "Simulate cache stall cycles")
545
546END_INIT_SIM_OBJECT_PARAMS(AtomicSimpleCPU)
547
548
549CREATE_SIM_OBJECT(AtomicSimpleCPU)
550{
551    AtomicSimpleCPU::Params *params = new AtomicSimpleCPU::Params();
552    params->name = getInstanceName();
553    params->numberOfThreads = 1;
554    params->max_insts_any_thread = max_insts_any_thread;
555    params->max_insts_all_threads = max_insts_all_threads;
556    params->max_loads_any_thread = max_loads_any_thread;
557    params->max_loads_all_threads = max_loads_all_threads;
558    params->progress_interval = progress_interval;
559    params->deferRegistration = defer_registration;
560    params->clock = clock;
561    params->functionTrace = function_trace;
562    params->functionTraceStart = function_trace_start;
563    params->width = width;
564    params->simulate_stalls = simulate_stalls;
565    params->system = system;
566    params->cpu_id = cpu_id;
567
568#if FULL_SYSTEM
569    params->itb = itb;
570    params->dtb = dtb;
571    params->profile = profile;
572#else
573    params->process = workload;
574#endif
575
576    AtomicSimpleCPU *cpu = new AtomicSimpleCPU(params);
577    return cpu;
578}
579
580REGISTER_SIM_OBJECT("AtomicSimpleCPU", AtomicSimpleCPU)
581
582