system.cc revision 9187:fd9a83e5178a
1/*
2 * Copyright (c) 2011-2012 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2003-2006 The Regents of The University of Michigan
15 * Copyright (c) 2011 Regents of the University of California
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Steve Reinhardt
42 *          Lisa Hsu
43 *          Nathan Binkert
44 *          Ali Saidi
45 *          Rick Strong
46 */
47
48#include "arch/isa_traits.hh"
49#include "arch/remote_gdb.hh"
50#include "arch/utility.hh"
51#include "arch/vtophys.hh"
52#include "base/loader/object_file.hh"
53#include "base/loader/symtab.hh"
54#include "base/str.hh"
55#include "base/trace.hh"
56#include "config/the_isa.hh"
57#include "cpu/thread_context.hh"
58#include "debug/Loader.hh"
59#include "debug/WorkItems.hh"
60#include "kern/kernel_stats.hh"
61#include "mem/physical.hh"
62#include "params/System.hh"
63#include "sim/byteswap.hh"
64#include "sim/debug.hh"
65#include "sim/full_system.hh"
66#include "sim/system.hh"
67
68using namespace std;
69using namespace TheISA;
70
71vector<System *> System::systemList;
72
73int System::numSystemsRunning = 0;
74
75System::System(Params *p)
76    : MemObject(p), _systemPort("system_port", this),
77      _numContexts(0),
78      pagePtr(0),
79      init_param(p->init_param),
80      physProxy(_systemPort),
81      virtProxy(_systemPort),
82      loadAddrMask(p->load_addr_mask),
83      nextPID(0),
84      physmem(p->memories),
85      memoryMode(p->mem_mode),
86      workItemsBegin(0),
87      workItemsEnd(0),
88      numWorkIds(p->num_work_ids),
89      _params(p),
90      totalNumInsts(0),
91      instEventQueue("system instruction-based event queue")
92{
93    // add self to global system list
94    systemList.push_back(this);
95
96    if (FullSystem) {
97        kernelSymtab = new SymbolTable;
98        if (!debugSymbolTable)
99            debugSymbolTable = new SymbolTable;
100    }
101
102    // Get the generic system master IDs
103    MasterID tmp_id M5_VAR_USED;
104    tmp_id = getMasterId("writebacks");
105    assert(tmp_id == Request::wbMasterId);
106    tmp_id = getMasterId("functional");
107    assert(tmp_id == Request::funcMasterId);
108    tmp_id = getMasterId("interrupt");
109    assert(tmp_id == Request::intMasterId);
110
111    if (FullSystem) {
112        if (params()->kernel == "") {
113            inform("No kernel set for full system simulation. "
114                   "Assuming you know what you're doing\n");
115
116            kernel = NULL;
117        } else {
118            // Get the kernel code
119            kernel = createObjectFile(params()->kernel);
120            inform("kernel located at: %s", params()->kernel);
121
122            if (kernel == NULL)
123                fatal("Could not load kernel file %s", params()->kernel);
124
125            // setup entry points
126            kernelStart = kernel->textBase();
127            kernelEnd = kernel->bssBase() + kernel->bssSize();
128            kernelEntry = kernel->entryPoint();
129
130            // load symbols
131            if (!kernel->loadGlobalSymbols(kernelSymtab))
132                fatal("could not load kernel symbols\n");
133
134            if (!kernel->loadLocalSymbols(kernelSymtab))
135                fatal("could not load kernel local symbols\n");
136
137            if (!kernel->loadGlobalSymbols(debugSymbolTable))
138                fatal("could not load kernel symbols\n");
139
140            if (!kernel->loadLocalSymbols(debugSymbolTable))
141                fatal("could not load kernel local symbols\n");
142
143            // Loading only needs to happen once and after memory system is
144            // connected so it will happen in initState()
145        }
146    }
147
148    // increment the number of running systms
149    numSystemsRunning++;
150
151    // Set back pointers to the system in all memories
152    for (int x = 0; x < params()->memories.size(); x++)
153        params()->memories[x]->system(this);
154}
155
156System::~System()
157{
158    delete kernelSymtab;
159    delete kernel;
160
161    for (uint32_t j = 0; j < numWorkIds; j++)
162        delete workItemStats[j];
163}
164
165void
166System::init()
167{
168    // check that the system port is connected
169    if (!_systemPort.isConnected())
170        panic("System port on %s is not connected.\n", name());
171}
172
173MasterPort&
174System::getMasterPort(const std::string &if_name, int idx)
175{
176    // no need to distinguish at the moment (besides checking)
177    return _systemPort;
178}
179
180void
181System::setMemoryMode(Enums::MemoryMode mode)
182{
183    assert(getState() == Drained);
184    memoryMode = mode;
185}
186
187bool System::breakpoint()
188{
189    if (remoteGDB.size())
190        return remoteGDB[0]->breakpoint();
191    return false;
192}
193
194/**
195 * Setting rgdb_wait to a positive integer waits for a remote debugger to
196 * connect to that context ID before continuing.  This should really
197   be a parameter on the CPU object or something...
198 */
199int rgdb_wait = -1;
200
201int
202System::registerThreadContext(ThreadContext *tc, int assigned)
203{
204    int id;
205    if (assigned == -1) {
206        for (id = 0; id < threadContexts.size(); id++) {
207            if (!threadContexts[id])
208                break;
209        }
210
211        if (threadContexts.size() <= id)
212            threadContexts.resize(id + 1);
213    } else {
214        if (threadContexts.size() <= assigned)
215            threadContexts.resize(assigned + 1);
216        id = assigned;
217    }
218
219    if (threadContexts[id])
220        fatal("Cannot have two CPUs with the same id (%d)\n", id);
221
222    threadContexts[id] = tc;
223    _numContexts++;
224
225    int port = getRemoteGDBPort();
226    if (port) {
227        RemoteGDB *rgdb = new RemoteGDB(this, tc);
228        GDBListener *gdbl = new GDBListener(rgdb, port + id);
229        gdbl->listen();
230
231        if (rgdb_wait != -1 && rgdb_wait == id)
232            gdbl->accept();
233
234        if (remoteGDB.size() <= id) {
235            remoteGDB.resize(id + 1);
236        }
237
238        remoteGDB[id] = rgdb;
239    }
240
241    activeCpus.push_back(false);
242
243    return id;
244}
245
246int
247System::numRunningContexts()
248{
249    int running = 0;
250    for (int i = 0; i < _numContexts; ++i) {
251        if (threadContexts[i]->status() != ThreadContext::Halted)
252            ++running;
253    }
254    return running;
255}
256
257void
258System::initState()
259{
260    if (FullSystem) {
261        for (int i = 0; i < threadContexts.size(); i++)
262            TheISA::startupCPU(threadContexts[i], i);
263        // Moved from the constructor to here since it relies on the
264        // address map being resolved in the interconnect
265        /**
266         * Load the kernel code into memory
267         */
268        if (params()->kernel != "")  {
269            // Validate kernel mapping before loading binary
270            if (!(isMemAddr(kernelStart & loadAddrMask) &&
271                            isMemAddr(kernelEnd & loadAddrMask))) {
272                fatal("Kernel is mapped to invalid location (not memory). "
273                      "kernelStart 0x(%x) - kernelEnd 0x(%x)\n", kernelStart,
274                      kernelEnd);
275            }
276            // Load program sections into memory
277            kernel->loadSections(physProxy, loadAddrMask);
278
279            DPRINTF(Loader, "Kernel start = %#x\n", kernelStart);
280            DPRINTF(Loader, "Kernel end   = %#x\n", kernelEnd);
281            DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry);
282            DPRINTF(Loader, "Kernel loaded...\n");
283        }
284    }
285
286    activeCpus.clear();
287}
288
289void
290System::replaceThreadContext(ThreadContext *tc, int context_id)
291{
292    if (context_id >= threadContexts.size()) {
293        panic("replaceThreadContext: bad id, %d >= %d\n",
294              context_id, threadContexts.size());
295    }
296
297    threadContexts[context_id] = tc;
298    if (context_id < remoteGDB.size())
299        remoteGDB[context_id]->replaceThreadContext(tc);
300}
301
302Addr
303System::allocPhysPages(int npages)
304{
305    Addr return_addr = pagePtr << LogVMPageSize;
306    pagePtr += npages;
307    if ((pagePtr << LogVMPageSize) > physmem.totalSize())
308        fatal("Out of memory, please increase size of physical memory.");
309    return return_addr;
310}
311
312Addr
313System::memSize() const
314{
315    return physmem.totalSize();
316}
317
318Addr
319System::freeMemSize() const
320{
321   return physmem.totalSize() - (pagePtr << LogVMPageSize);
322}
323
324bool
325System::isMemAddr(Addr addr) const
326{
327    return physmem.isMemAddr(addr);
328}
329
330void
331System::resume()
332{
333    SimObject::resume();
334    totalNumInsts = 0;
335}
336
337void
338System::serialize(ostream &os)
339{
340    if (FullSystem)
341        kernelSymtab->serialize("kernel_symtab", os);
342    SERIALIZE_SCALAR(pagePtr);
343    SERIALIZE_SCALAR(nextPID);
344}
345
346
347void
348System::unserialize(Checkpoint *cp, const string &section)
349{
350    if (FullSystem)
351        kernelSymtab->unserialize("kernel_symtab", cp, section);
352    UNSERIALIZE_SCALAR(pagePtr);
353    UNSERIALIZE_SCALAR(nextPID);
354}
355
356void
357System::regStats()
358{
359    for (uint32_t j = 0; j < numWorkIds ; j++) {
360        workItemStats[j] = new Stats::Histogram();
361        stringstream namestr;
362        ccprintf(namestr, "work_item_type%d", j);
363        workItemStats[j]->init(20)
364                         .name(name() + "." + namestr.str())
365                         .desc("Run time stat for" + namestr.str())
366                         .prereq(*workItemStats[j]);
367    }
368}
369
370void
371System::workItemEnd(uint32_t tid, uint32_t workid)
372{
373    std::pair<uint32_t,uint32_t> p(tid, workid);
374    if (!lastWorkItemStarted.count(p))
375        return;
376
377    Tick samp = curTick() - lastWorkItemStarted[p];
378    DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
379
380    if (workid >= numWorkIds)
381        fatal("Got workid greater than specified in system configuration\n");
382
383    workItemStats[workid]->sample(samp);
384    lastWorkItemStarted.erase(p);
385}
386
387void
388System::printSystems()
389{
390    vector<System *>::iterator i = systemList.begin();
391    vector<System *>::iterator end = systemList.end();
392    for (; i != end; ++i) {
393        System *sys = *i;
394        cerr << "System " << sys->name() << ": " << hex << sys << endl;
395    }
396}
397
398void
399printSystems()
400{
401    System::printSystems();
402}
403
404MasterID
405System::getMasterId(std::string master_name)
406{
407    // strip off system name if the string starts with it
408    if (startswith(master_name, name()))
409        master_name = master_name.erase(0, name().size() + 1);
410
411    // CPUs in switch_cpus ask for ids again after switching
412    for (int i = 0; i < masterIds.size(); i++) {
413        if (masterIds[i] == master_name) {
414            return i;
415        }
416    }
417
418    // Verify that the statistics haven't been enabled yet
419    // Otherwise objects will have sized their stat buckets and
420    // they will be too small
421
422    if (Stats::enabled())
423        fatal("Can't request a masterId after regStats(). \
424                You must do so in init().\n");
425
426    masterIds.push_back(master_name);
427
428    return masterIds.size() - 1;
429}
430
431std::string
432System::getMasterName(MasterID master_id)
433{
434    if (master_id >= masterIds.size())
435        fatal("Invalid master_id passed to getMasterName()\n");
436
437    return masterIds[master_id];
438}
439
440const char *System::MemoryModeStrings[3] = {"invalid", "atomic",
441    "timing"};
442
443System *
444SystemParams::create()
445{
446    return new System(this);
447}
448