system.cc revision 8706:b1838faf3bcc
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 "base/loader/object_file.hh"
52#include "base/loader/symtab.hh"
53#include "base/trace.hh"
54#include "config/full_system.hh"
55#include "config/the_isa.hh"
56#include "cpu/thread_context.hh"
57#include "debug/Loader.hh"
58#include "debug/WorkItems.hh"
59#include "mem/mem_object.hh"
60#include "mem/physical.hh"
61#include "sim/byteswap.hh"
62#include "sim/debug.hh"
63#include "sim/system.hh"
64
65#if FULL_SYSTEM
66#include "arch/vtophys.hh"
67#include "kern/kernel_stats.hh"
68#include "mem/fs_translating_port_proxy.hh"
69#else
70#include "params/System.hh"
71#endif
72
73using namespace std;
74using namespace TheISA;
75
76vector<System *> System::systemList;
77
78int System::numSystemsRunning = 0;
79
80System::System(Params *p)
81    : MemObject(p), _systemPort("system_port", this),
82      physmem(p->physmem),
83      _numContexts(0),
84#if FULL_SYSTEM
85      init_param(p->init_param),
86      loadAddrMask(p->load_addr_mask),
87#else
88      pagePtr(0),
89      nextPID(0),
90#endif
91      memoryMode(p->mem_mode),
92      workItemsBegin(0),
93      workItemsEnd(0),
94      numWorkIds(p->num_work_ids),
95      _params(p),
96      totalNumInsts(0),
97      instEventQueue("system instruction-based event queue")
98{
99    // add self to global system list
100    systemList.push_back(this);
101
102    /** Keep track of all memories we can execute code out of
103     * in our system
104     */
105    for (int x = 0; x < p->memories.size(); x++) {
106        if (!p->memories[x])
107            continue;
108        memRanges.push_back(RangeSize(p->memories[x]->start(),
109                                      p->memories[x]->size()));
110    }
111
112#if FULL_SYSTEM
113    kernelSymtab = new SymbolTable;
114    if (!debugSymbolTable)
115        debugSymbolTable = new SymbolTable;
116
117    /**
118     * Get a port proxy to memory
119     */
120    physProxy = new PortProxy(*getSystemPort());
121    virtProxy = new FSTranslatingPortProxy(*getSystemPort());
122#endif
123}
124
125System::~System()
126{
127#if FULL_SYSTEM
128    delete kernelSymtab;
129    delete kernel;
130#else
131    panic("System::fixFuncEventAddr needs to be rewritten "
132          "to work with syscall emulation");
133#endif // FULL_SYSTEM}
134
135    for (uint32_t j = 0; j < numWorkIds; j++)
136        delete workItemStats[j];
137}
138
139void
140System::init()
141{
142    // check that the system port is connected
143    if (!_systemPort.isConnected())
144        panic("System port on %s is not connected.\n", name());
145}
146
147Port*
148System::getPort(const std::string &if_name, int idx)
149{
150    // no need to distinguish at the moment (besides checking)
151    return &_systemPort;
152}
153
154void
155System::setMemoryMode(Enums::MemoryMode mode)
156{
157    assert(getState() == Drained);
158    memoryMode = mode;
159}
160
161bool System::breakpoint()
162{
163    if (remoteGDB.size())
164        return remoteGDB[0]->breakpoint();
165    return false;
166}
167
168/**
169 * Setting rgdb_wait to a positive integer waits for a remote debugger to
170 * connect to that context ID before continuing.  This should really
171   be a parameter on the CPU object or something...
172 */
173int rgdb_wait = -1;
174
175int
176System::registerThreadContext(ThreadContext *tc, int assigned)
177{
178    int id;
179    if (assigned == -1) {
180        for (id = 0; id < threadContexts.size(); id++) {
181            if (!threadContexts[id])
182                break;
183        }
184
185        if (threadContexts.size() <= id)
186            threadContexts.resize(id + 1);
187    } else {
188        if (threadContexts.size() <= assigned)
189            threadContexts.resize(assigned + 1);
190        id = assigned;
191    }
192
193    if (threadContexts[id])
194        fatal("Cannot have two CPUs with the same id (%d)\n", id);
195
196    threadContexts[id] = tc;
197    _numContexts++;
198
199    int port = getRemoteGDBPort();
200    if (port) {
201        RemoteGDB *rgdb = new RemoteGDB(this, tc);
202        GDBListener *gdbl = new GDBListener(rgdb, port + id);
203        gdbl->listen();
204
205        if (rgdb_wait != -1 && rgdb_wait == id)
206            gdbl->accept();
207
208        if (remoteGDB.size() <= id) {
209            remoteGDB.resize(id + 1);
210        }
211
212        remoteGDB[id] = rgdb;
213    }
214
215    activeCpus.push_back(false);
216
217    return id;
218}
219
220int
221System::numRunningContexts()
222{
223    int running = 0;
224    for (int i = 0; i < _numContexts; ++i) {
225        if (threadContexts[i]->status() != ThreadContext::Halted)
226            ++running;
227    }
228    return running;
229}
230
231void
232System::initState()
233{
234    // Moved from the constructor to here since it relies on the
235    // address map being resolved in the interconnect
236#if FULL_SYSTEM
237    /**
238     * Load the kernel code into memory
239     */
240    if (params()->kernel == "") {
241        inform("No kernel set for full system simulation. Assuming you know what"
242                " you're doing...\n");
243    } else {
244        // Load kernel code
245        kernel = createObjectFile(params()->kernel);
246        inform("kernel located at: %s", params()->kernel);
247
248        if (kernel == NULL)
249            fatal("Could not load kernel file %s", params()->kernel);
250
251        // Load program sections into memory
252        kernel->loadSections(physProxy, loadAddrMask);
253
254        // setup entry points
255        kernelStart = kernel->textBase();
256        kernelEnd = kernel->bssBase() + kernel->bssSize();
257        kernelEntry = kernel->entryPoint();
258
259        // load symbols
260        if (!kernel->loadGlobalSymbols(kernelSymtab))
261            fatal("could not load kernel symbols\n");
262
263        if (!kernel->loadLocalSymbols(kernelSymtab))
264            fatal("could not load kernel local symbols\n");
265
266        if (!kernel->loadGlobalSymbols(debugSymbolTable))
267            fatal("could not load kernel symbols\n");
268
269        if (!kernel->loadLocalSymbols(debugSymbolTable))
270            fatal("could not load kernel local symbols\n");
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#endif // FULL_SYSTEM
278
279    // increment the number of running systms
280    numSystemsRunning++;
281
282    activeCpus.clear();
283
284#if FULL_SYSTEM
285    int i;
286    for (i = 0; i < threadContexts.size(); i++)
287        TheISA::startupCPU(threadContexts[i], i);
288#endif
289}
290
291void
292System::replaceThreadContext(ThreadContext *tc, int context_id)
293{
294    if (context_id >= threadContexts.size()) {
295        panic("replaceThreadContext: bad id, %d >= %d\n",
296              context_id, threadContexts.size());
297    }
298
299    threadContexts[context_id] = tc;
300    if (context_id < remoteGDB.size())
301        remoteGDB[context_id]->replaceThreadContext(tc);
302}
303
304#if !FULL_SYSTEM
305Addr
306System::allocPhysPages(int npages)
307{
308    Addr return_addr = pagePtr << LogVMPageSize;
309    pagePtr += npages;
310    if (return_addr >= physmem->size())
311        fatal("Out of memory, please increase size of physical memory.");
312    return return_addr;
313}
314
315Addr
316System::memSize()
317{
318    return physmem->size();
319}
320
321Addr
322System::freeMemSize()
323{
324   return physmem->size() - (pagePtr << LogVMPageSize);
325}
326
327#endif
328
329bool
330System::isMemory(const Addr addr) const
331{
332    std::list<Range<Addr> >::const_iterator i;
333    for (i = memRanges.begin(); i != memRanges.end(); i++) {
334        if (*i == addr)
335            return true;
336    }
337    return false;
338}
339
340void
341System::resume()
342{
343    SimObject::resume();
344    totalNumInsts = 0;
345}
346
347void
348System::serialize(ostream &os)
349{
350#if FULL_SYSTEM
351    kernelSymtab->serialize("kernel_symtab", os);
352#else // !FULL_SYSTEM
353    SERIALIZE_SCALAR(pagePtr);
354    SERIALIZE_SCALAR(nextPID);
355#endif
356}
357
358
359void
360System::unserialize(Checkpoint *cp, const string &section)
361{
362#if FULL_SYSTEM
363    kernelSymtab->unserialize("kernel_symtab", cp, section);
364#else // !FULL_SYSTEM
365    UNSERIALIZE_SCALAR(pagePtr);
366    UNSERIALIZE_SCALAR(nextPID);
367#endif
368}
369
370void
371System::regStats()
372{
373    for (uint32_t j = 0; j < numWorkIds ; j++) {
374        workItemStats[j] = new Stats::Histogram();
375        stringstream namestr;
376        ccprintf(namestr, "work_item_type%d", j);
377        workItemStats[j]->init(20)
378                         .name(name() + "." + namestr.str())
379                         .desc("Run time stat for" + namestr.str())
380                         .prereq(*workItemStats[j]);
381    }
382}
383
384void
385System::workItemEnd(uint32_t tid, uint32_t workid)
386{
387    std::pair<uint32_t,uint32_t> p(tid, workid);
388    if (!lastWorkItemStarted.count(p))
389        return;
390
391    Tick samp = curTick() - lastWorkItemStarted[p];
392    DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
393
394    if (workid >= numWorkIds)
395        fatal("Got workid greater than specified in system configuration\n");
396
397    workItemStats[workid]->sample(samp);
398    lastWorkItemStarted.erase(p);
399}
400
401void
402System::printSystems()
403{
404    vector<System *>::iterator i = systemList.begin();
405    vector<System *>::iterator end = systemList.end();
406    for (; i != end; ++i) {
407        System *sys = *i;
408        cerr << "System " << sys->name() << ": " << hex << sys << endl;
409    }
410}
411
412void
413printSystems()
414{
415    System::printSystems();
416}
417
418const char *System::MemoryModeStrings[3] = {"invalid", "atomic",
419    "timing"};
420
421#if !FULL_SYSTEM
422
423System *
424SystemParams::create()
425{
426    return new System(this);
427}
428
429#endif
430