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