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