system.cc revision 9142
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 if not SPARC ISA\n");
115        } else {
116            // Get the kernel code
117            kernel = createObjectFile(params()->kernel);
118            inform("kernel located at: %s", params()->kernel);
119
120            if (kernel == NULL)
121                fatal("Could not load kernel file %s", params()->kernel);
122
123            // setup entry points
124            kernelStart = kernel->textBase();
125            kernelEnd = kernel->bssBase() + kernel->bssSize();
126            kernelEntry = kernel->entryPoint();
127
128            // load symbols
129            if (!kernel->loadGlobalSymbols(kernelSymtab))
130                fatal("could not load kernel symbols\n");
131
132            if (!kernel->loadLocalSymbols(kernelSymtab))
133                fatal("could not load kernel local symbols\n");
134
135            if (!kernel->loadGlobalSymbols(debugSymbolTable))
136                fatal("could not load kernel symbols\n");
137
138            if (!kernel->loadLocalSymbols(debugSymbolTable))
139                fatal("could not load kernel local symbols\n");
140
141            // Loading only needs to happen once and after memory system is
142            // connected so it will happen in initState()
143        }
144    }
145
146    // increment the number of running systms
147    numSystemsRunning++;
148
149    // Set back pointers to the system in all memories
150    for (int x = 0; x < params()->memories.size(); x++)
151        params()->memories[x]->system(this);
152}
153
154System::~System()
155{
156    delete kernelSymtab;
157    delete kernel;
158
159    for (uint32_t j = 0; j < numWorkIds; j++)
160        delete workItemStats[j];
161}
162
163void
164System::init()
165{
166    // check that the system port is connected
167    if (!_systemPort.isConnected())
168        panic("System port on %s is not connected.\n", name());
169}
170
171MasterPort&
172System::getMasterPort(const std::string &if_name, int idx)
173{
174    // no need to distinguish at the moment (besides checking)
175    return _systemPort;
176}
177
178void
179System::setMemoryMode(Enums::MemoryMode mode)
180{
181    assert(getState() == Drained);
182    memoryMode = mode;
183}
184
185bool System::breakpoint()
186{
187    if (remoteGDB.size())
188        return remoteGDB[0]->breakpoint();
189    return false;
190}
191
192/**
193 * Setting rgdb_wait to a positive integer waits for a remote debugger to
194 * connect to that context ID before continuing.  This should really
195   be a parameter on the CPU object or something...
196 */
197int rgdb_wait = -1;
198
199int
200System::registerThreadContext(ThreadContext *tc, int assigned)
201{
202    int id;
203    if (assigned == -1) {
204        for (id = 0; id < threadContexts.size(); id++) {
205            if (!threadContexts[id])
206                break;
207        }
208
209        if (threadContexts.size() <= id)
210            threadContexts.resize(id + 1);
211    } else {
212        if (threadContexts.size() <= assigned)
213            threadContexts.resize(assigned + 1);
214        id = assigned;
215    }
216
217    if (threadContexts[id])
218        fatal("Cannot have two CPUs with the same id (%d)\n", id);
219
220    threadContexts[id] = tc;
221    _numContexts++;
222
223    int port = getRemoteGDBPort();
224    if (port) {
225        RemoteGDB *rgdb = new RemoteGDB(this, tc);
226        GDBListener *gdbl = new GDBListener(rgdb, port + id);
227        gdbl->listen();
228
229        if (rgdb_wait != -1 && rgdb_wait == id)
230            gdbl->accept();
231
232        if (remoteGDB.size() <= id) {
233            remoteGDB.resize(id + 1);
234        }
235
236        remoteGDB[id] = rgdb;
237    }
238
239    activeCpus.push_back(false);
240
241    return id;
242}
243
244int
245System::numRunningContexts()
246{
247    int running = 0;
248    for (int i = 0; i < _numContexts; ++i) {
249        if (threadContexts[i]->status() != ThreadContext::Halted)
250            ++running;
251    }
252    return running;
253}
254
255void
256System::initState()
257{
258    int i;
259    if (FullSystem) {
260        for (i = 0; i < threadContexts.size(); i++)
261            TheISA::startupCPU(threadContexts[i], i);
262        // Moved from the constructor to here since it relies on the
263        // address map being resolved in the interconnect
264        /**
265         * Load the kernel code into memory
266         */
267        if (params()->kernel != "")  {
268            // Load program sections into memory
269            kernel->loadSections(physProxy, loadAddrMask);
270
271            DPRINTF(Loader, "Kernel start = %#x\n", kernelStart);
272            DPRINTF(Loader, "Kernel end   = %#x\n", kernelEnd);
273            DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry);
274            DPRINTF(Loader, "Kernel loaded...\n");
275        }
276    }
277
278    activeCpus.clear();
279
280    if (!FullSystem)
281        return;
282
283    for (i = 0; i < threadContexts.size(); i++)
284        TheISA::startupCPU(threadContexts[i], i);
285}
286
287void
288System::replaceThreadContext(ThreadContext *tc, int context_id)
289{
290    if (context_id >= threadContexts.size()) {
291        panic("replaceThreadContext: bad id, %d >= %d\n",
292              context_id, threadContexts.size());
293    }
294
295    threadContexts[context_id] = tc;
296    if (context_id < remoteGDB.size())
297        remoteGDB[context_id]->replaceThreadContext(tc);
298}
299
300Addr
301System::allocPhysPages(int npages)
302{
303    Addr return_addr = pagePtr << LogVMPageSize;
304    pagePtr += npages;
305    if ((pagePtr << LogVMPageSize) > physmem.totalSize())
306        fatal("Out of memory, please increase size of physical memory.");
307    return return_addr;
308}
309
310Addr
311System::memSize() const
312{
313    return physmem.totalSize();
314}
315
316Addr
317System::freeMemSize() const
318{
319   return physmem.totalSize() - (pagePtr << LogVMPageSize);
320}
321
322bool
323System::isMemAddr(Addr addr) const
324{
325    return physmem.isMemAddr(addr);
326}
327
328void
329System::resume()
330{
331    SimObject::resume();
332    totalNumInsts = 0;
333}
334
335void
336System::serialize(ostream &os)
337{
338    if (FullSystem)
339        kernelSymtab->serialize("kernel_symtab", os);
340    SERIALIZE_SCALAR(pagePtr);
341    SERIALIZE_SCALAR(nextPID);
342}
343
344
345void
346System::unserialize(Checkpoint *cp, const string &section)
347{
348    if (FullSystem)
349        kernelSymtab->unserialize("kernel_symtab", cp, section);
350    UNSERIALIZE_SCALAR(pagePtr);
351    UNSERIALIZE_SCALAR(nextPID);
352}
353
354void
355System::regStats()
356{
357    for (uint32_t j = 0; j < numWorkIds ; j++) {
358        workItemStats[j] = new Stats::Histogram();
359        stringstream namestr;
360        ccprintf(namestr, "work_item_type%d", j);
361        workItemStats[j]->init(20)
362                         .name(name() + "." + namestr.str())
363                         .desc("Run time stat for" + namestr.str())
364                         .prereq(*workItemStats[j]);
365    }
366}
367
368void
369System::workItemEnd(uint32_t tid, uint32_t workid)
370{
371    std::pair<uint32_t,uint32_t> p(tid, workid);
372    if (!lastWorkItemStarted.count(p))
373        return;
374
375    Tick samp = curTick() - lastWorkItemStarted[p];
376    DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
377
378    if (workid >= numWorkIds)
379        fatal("Got workid greater than specified in system configuration\n");
380
381    workItemStats[workid]->sample(samp);
382    lastWorkItemStarted.erase(p);
383}
384
385void
386System::printSystems()
387{
388    vector<System *>::iterator i = systemList.begin();
389    vector<System *>::iterator end = systemList.end();
390    for (; i != end; ++i) {
391        System *sys = *i;
392        cerr << "System " << sys->name() << ": " << hex << sys << endl;
393    }
394}
395
396void
397printSystems()
398{
399    System::printSystems();
400}
401
402MasterID
403System::getMasterId(std::string master_name)
404{
405    // strip off system name if the string starts with it
406    if (startswith(master_name, name()))
407        master_name = master_name.erase(0, name().size() + 1);
408
409    // CPUs in switch_cpus ask for ids again after switching
410    for (int i = 0; i < masterIds.size(); i++) {
411        if (masterIds[i] == master_name) {
412            return i;
413        }
414    }
415
416    // Verify that the statistics haven't been enabled yet
417    // Otherwise objects will have sized their stat buckets and
418    // they will be too small
419
420    if (Stats::enabled())
421        fatal("Can't request a masterId after regStats(). \
422                You must do so in init().\n");
423
424    masterIds.push_back(master_name);
425
426    return masterIds.size() - 1;
427}
428
429std::string
430System::getMasterName(MasterID master_id)
431{
432    if (master_id >= masterIds.size())
433        fatal("Invalid master_id passed to getMasterName()\n");
434
435    return masterIds[master_id];
436}
437
438const char *System::MemoryModeStrings[3] = {"invalid", "atomic",
439    "timing"};
440
441System *
442SystemParams::create()
443{
444    return new System(this);
445}
446