system.cc revision 9172
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            // Load program sections into memory
270            kernel->loadSections(physProxy, loadAddrMask);
271
272            DPRINTF(Loader, "Kernel start = %#x\n", kernelStart);
273            DPRINTF(Loader, "Kernel end   = %#x\n", kernelEnd);
274            DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry);
275            DPRINTF(Loader, "Kernel loaded...\n");
276        }
277    }
278
279    activeCpus.clear();
280}
281
282void
283System::replaceThreadContext(ThreadContext *tc, int context_id)
284{
285    if (context_id >= threadContexts.size()) {
286        panic("replaceThreadContext: bad id, %d >= %d\n",
287              context_id, threadContexts.size());
288    }
289
290    threadContexts[context_id] = tc;
291    if (context_id < remoteGDB.size())
292        remoteGDB[context_id]->replaceThreadContext(tc);
293}
294
295Addr
296System::allocPhysPages(int npages)
297{
298    Addr return_addr = pagePtr << LogVMPageSize;
299    pagePtr += npages;
300    if ((pagePtr << LogVMPageSize) > physmem.totalSize())
301        fatal("Out of memory, please increase size of physical memory.");
302    return return_addr;
303}
304
305Addr
306System::memSize() const
307{
308    return physmem.totalSize();
309}
310
311Addr
312System::freeMemSize() const
313{
314   return physmem.totalSize() - (pagePtr << LogVMPageSize);
315}
316
317bool
318System::isMemAddr(Addr addr) const
319{
320    return physmem.isMemAddr(addr);
321}
322
323void
324System::resume()
325{
326    SimObject::resume();
327    totalNumInsts = 0;
328}
329
330void
331System::serialize(ostream &os)
332{
333    if (FullSystem)
334        kernelSymtab->serialize("kernel_symtab", os);
335    SERIALIZE_SCALAR(pagePtr);
336    SERIALIZE_SCALAR(nextPID);
337}
338
339
340void
341System::unserialize(Checkpoint *cp, const string &section)
342{
343    if (FullSystem)
344        kernelSymtab->unserialize("kernel_symtab", cp, section);
345    UNSERIALIZE_SCALAR(pagePtr);
346    UNSERIALIZE_SCALAR(nextPID);
347}
348
349void
350System::regStats()
351{
352    for (uint32_t j = 0; j < numWorkIds ; j++) {
353        workItemStats[j] = new Stats::Histogram();
354        stringstream namestr;
355        ccprintf(namestr, "work_item_type%d", j);
356        workItemStats[j]->init(20)
357                         .name(name() + "." + namestr.str())
358                         .desc("Run time stat for" + namestr.str())
359                         .prereq(*workItemStats[j]);
360    }
361}
362
363void
364System::workItemEnd(uint32_t tid, uint32_t workid)
365{
366    std::pair<uint32_t,uint32_t> p(tid, workid);
367    if (!lastWorkItemStarted.count(p))
368        return;
369
370    Tick samp = curTick() - lastWorkItemStarted[p];
371    DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
372
373    if (workid >= numWorkIds)
374        fatal("Got workid greater than specified in system configuration\n");
375
376    workItemStats[workid]->sample(samp);
377    lastWorkItemStarted.erase(p);
378}
379
380void
381System::printSystems()
382{
383    vector<System *>::iterator i = systemList.begin();
384    vector<System *>::iterator end = systemList.end();
385    for (; i != end; ++i) {
386        System *sys = *i;
387        cerr << "System " << sys->name() << ": " << hex << sys << endl;
388    }
389}
390
391void
392printSystems()
393{
394    System::printSystems();
395}
396
397MasterID
398System::getMasterId(std::string master_name)
399{
400    // strip off system name if the string starts with it
401    if (startswith(master_name, name()))
402        master_name = master_name.erase(0, name().size() + 1);
403
404    // CPUs in switch_cpus ask for ids again after switching
405    for (int i = 0; i < masterIds.size(); i++) {
406        if (masterIds[i] == master_name) {
407            return i;
408        }
409    }
410
411    // Verify that the statistics haven't been enabled yet
412    // Otherwise objects will have sized their stat buckets and
413    // they will be too small
414
415    if (Stats::enabled())
416        fatal("Can't request a masterId after regStats(). \
417                You must do so in init().\n");
418
419    masterIds.push_back(master_name);
420
421    return masterIds.size() - 1;
422}
423
424std::string
425System::getMasterName(MasterID master_id)
426{
427    if (master_id >= masterIds.size())
428        fatal("Invalid master_id passed to getMasterName()\n");
429
430    return masterIds[master_id];
431}
432
433const char *System::MemoryModeStrings[3] = {"invalid", "atomic",
434    "timing"};
435
436System *
437SystemParams::create()
438{
439    return new System(this);
440}
441