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