system.cc revision 10375:b1bc989611da
1/*
2 * Copyright (c) 2011-2014 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/str.hh"
54#include "base/trace.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 "kern/kernel_stats.hh"
60#include "mem/abstract_mem.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, p->cache_line_size),
81      kernelSymtab(nullptr),
82      kernel(nullptr),
83      loadAddrMask(p->load_addr_mask),
84      loadAddrOffset(p->load_offset),
85      nextPID(0),
86      physmem(name() + ".physmem", p->memories),
87      memoryMode(p->mem_mode),
88      _cacheLineSize(p->cache_line_size),
89      workItemsBegin(0),
90      workItemsEnd(0),
91      numWorkIds(p->num_work_ids),
92      _params(p),
93      totalNumInsts(0),
94      instEventQueue("system instruction-based event queue")
95{
96    // add self to global system list
97    systemList.push_back(this);
98
99    if (FullSystem) {
100        kernelSymtab = new SymbolTable;
101        if (!debugSymbolTable)
102            debugSymbolTable = new SymbolTable;
103    }
104
105    // check if the cache line size is a value known to work
106    if (!(_cacheLineSize == 16 || _cacheLineSize == 32 ||
107          _cacheLineSize == 64 || _cacheLineSize == 128))
108        warn_once("Cache line size is neither 16, 32, 64 nor 128 bytes.\n");
109
110    // Get the generic system master IDs
111    MasterID tmp_id M5_VAR_USED;
112    tmp_id = getMasterId("writebacks");
113    assert(tmp_id == Request::wbMasterId);
114    tmp_id = getMasterId("functional");
115    assert(tmp_id == Request::funcMasterId);
116    tmp_id = getMasterId("interrupt");
117    assert(tmp_id == Request::intMasterId);
118
119    if (FullSystem) {
120        if (params()->kernel == "") {
121            inform("No kernel set for full system simulation. "
122                   "Assuming you know what you're doing\n");
123        } else {
124            // Get the kernel code
125            kernel = createObjectFile(params()->kernel);
126            inform("kernel located at: %s", params()->kernel);
127
128            if (kernel == NULL)
129                fatal("Could not load kernel file %s", params()->kernel);
130
131            // setup entry points
132            kernelStart = kernel->textBase();
133            kernelEnd = kernel->bssBase() + kernel->bssSize();
134            kernelEntry = kernel->entryPoint();
135
136            // load symbols
137            if (!kernel->loadGlobalSymbols(kernelSymtab))
138                fatal("could not load kernel symbols\n");
139
140            if (!kernel->loadLocalSymbols(kernelSymtab))
141                fatal("could not load kernel local symbols\n");
142
143            if (!kernel->loadGlobalSymbols(debugSymbolTable))
144                fatal("could not load kernel symbols\n");
145
146            if (!kernel->loadLocalSymbols(debugSymbolTable))
147                fatal("could not load kernel local symbols\n");
148
149            // Loading only needs to happen once and after memory system is
150            // connected so it will happen in initState()
151        }
152    }
153
154    // increment the number of running systms
155    numSystemsRunning++;
156
157    // Set back pointers to the system in all memories
158    for (int x = 0; x < params()->memories.size(); x++)
159        params()->memories[x]->system(this);
160}
161
162System::~System()
163{
164    delete kernelSymtab;
165    delete kernel;
166
167    for (uint32_t j = 0; j < numWorkIds; j++)
168        delete workItemStats[j];
169}
170
171void
172System::init()
173{
174    // check that the system port is connected
175    if (!_systemPort.isConnected())
176        panic("System port on %s is not connected.\n", name());
177}
178
179BaseMasterPort&
180System::getMasterPort(const std::string &if_name, PortID idx)
181{
182    // no need to distinguish at the moment (besides checking)
183    return _systemPort;
184}
185
186void
187System::setMemoryMode(Enums::MemoryMode mode)
188{
189    assert(getDrainState() == Drainable::Drained);
190    memoryMode = mode;
191}
192
193bool System::breakpoint()
194{
195    if (remoteGDB.size())
196        return remoteGDB[0]->breakpoint();
197    return false;
198}
199
200/**
201 * Setting rgdb_wait to a positive integer waits for a remote debugger to
202 * connect to that context ID before continuing.  This should really
203   be a parameter on the CPU object or something...
204 */
205int rgdb_wait = -1;
206
207int
208System::registerThreadContext(ThreadContext *tc, int assigned)
209{
210    int id;
211    if (assigned == -1) {
212        for (id = 0; id < threadContexts.size(); id++) {
213            if (!threadContexts[id])
214                break;
215        }
216
217        if (threadContexts.size() <= id)
218            threadContexts.resize(id + 1);
219    } else {
220        if (threadContexts.size() <= assigned)
221            threadContexts.resize(assigned + 1);
222        id = assigned;
223    }
224
225    if (threadContexts[id])
226        fatal("Cannot have two CPUs with the same id (%d)\n", id);
227
228    threadContexts[id] = tc;
229    _numContexts++;
230
231#if THE_ISA != NULL_ISA
232    int port = getRemoteGDBPort();
233    if (port) {
234        RemoteGDB *rgdb = new RemoteGDB(this, tc);
235        GDBListener *gdbl = new GDBListener(rgdb, port + id);
236        gdbl->listen();
237
238        if (rgdb_wait != -1 && rgdb_wait == id)
239            gdbl->accept();
240
241        if (remoteGDB.size() <= id) {
242            remoteGDB.resize(id + 1);
243        }
244
245        remoteGDB[id] = rgdb;
246    }
247#endif
248
249    activeCpus.push_back(false);
250
251    return id;
252}
253
254int
255System::numRunningContexts()
256{
257    int running = 0;
258    for (int i = 0; i < _numContexts; ++i) {
259        if (threadContexts[i]->status() != ThreadContext::Halted)
260            ++running;
261    }
262    return running;
263}
264
265void
266System::initState()
267{
268    if (FullSystem) {
269        for (int i = 0; i < threadContexts.size(); i++)
270            TheISA::startupCPU(threadContexts[i], i);
271        // Moved from the constructor to here since it relies on the
272        // address map being resolved in the interconnect
273        /**
274         * Load the kernel code into memory
275         */
276        if (params()->kernel != "")  {
277            if (params()->kernel_addr_check) {
278                // Validate kernel mapping before loading binary
279                if (!(isMemAddr((kernelStart & loadAddrMask) +
280                                loadAddrOffset) &&
281                      isMemAddr((kernelEnd & loadAddrMask) +
282                                loadAddrOffset))) {
283                    fatal("Kernel is mapped to invalid location (not memory). "
284                          "kernelStart 0x(%x) - kernelEnd 0x(%x) %#x:%#x\n",
285                          kernelStart,
286                          kernelEnd, (kernelStart & loadAddrMask) +
287                          loadAddrOffset,
288                          (kernelEnd & loadAddrMask) + loadAddrOffset);
289                }
290            }
291            // Load program sections into memory
292            kernel->loadSections(physProxy, loadAddrMask, loadAddrOffset);
293
294            DPRINTF(Loader, "Kernel start = %#x\n", kernelStart);
295            DPRINTF(Loader, "Kernel end   = %#x\n", kernelEnd);
296            DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry);
297            DPRINTF(Loader, "Kernel loaded...\n");
298        }
299    }
300
301    activeCpus.clear();
302}
303
304void
305System::replaceThreadContext(ThreadContext *tc, int context_id)
306{
307    if (context_id >= threadContexts.size()) {
308        panic("replaceThreadContext: bad id, %d >= %d\n",
309              context_id, threadContexts.size());
310    }
311
312    threadContexts[context_id] = tc;
313    if (context_id < remoteGDB.size())
314        remoteGDB[context_id]->replaceThreadContext(tc);
315}
316
317Addr
318System::allocPhysPages(int npages)
319{
320    Addr return_addr = pagePtr << PageShift;
321    pagePtr += npages;
322    if ((pagePtr << PageShift) > physmem.totalSize())
323        fatal("Out of memory, please increase size of physical memory.");
324    return return_addr;
325}
326
327Addr
328System::memSize() const
329{
330    return physmem.totalSize();
331}
332
333Addr
334System::freeMemSize() const
335{
336   return physmem.totalSize() - (pagePtr << PageShift);
337}
338
339bool
340System::isMemAddr(Addr addr) const
341{
342    return physmem.isMemAddr(addr);
343}
344
345unsigned int
346System::drain(DrainManager *dm)
347{
348    setDrainState(Drainable::Drained);
349    return 0;
350}
351
352void
353System::drainResume()
354{
355    Drainable::drainResume();
356    totalNumInsts = 0;
357}
358
359void
360System::serialize(ostream &os)
361{
362    if (FullSystem)
363        kernelSymtab->serialize("kernel_symtab", os);
364    SERIALIZE_SCALAR(pagePtr);
365    SERIALIZE_SCALAR(nextPID);
366    serializeSymtab(os);
367
368    // also serialize the memories in the system
369    nameOut(os, csprintf("%s.physmem", name()));
370    physmem.serialize(os);
371}
372
373
374void
375System::unserialize(Checkpoint *cp, const string &section)
376{
377    if (FullSystem)
378        kernelSymtab->unserialize("kernel_symtab", cp, section);
379    UNSERIALIZE_SCALAR(pagePtr);
380    UNSERIALIZE_SCALAR(nextPID);
381    unserializeSymtab(cp, section);
382
383    // also unserialize the memories in the system
384    physmem.unserialize(cp, csprintf("%s.physmem", name()));
385}
386
387void
388System::regStats()
389{
390    for (uint32_t j = 0; j < numWorkIds ; j++) {
391        workItemStats[j] = new Stats::Histogram();
392        stringstream namestr;
393        ccprintf(namestr, "work_item_type%d", j);
394        workItemStats[j]->init(20)
395                         .name(name() + "." + namestr.str())
396                         .desc("Run time stat for" + namestr.str())
397                         .prereq(*workItemStats[j]);
398    }
399}
400
401void
402System::workItemEnd(uint32_t tid, uint32_t workid)
403{
404    std::pair<uint32_t,uint32_t> p(tid, workid);
405    if (!lastWorkItemStarted.count(p))
406        return;
407
408    Tick samp = curTick() - lastWorkItemStarted[p];
409    DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
410
411    if (workid >= numWorkIds)
412        fatal("Got workid greater than specified in system configuration\n");
413
414    workItemStats[workid]->sample(samp);
415    lastWorkItemStarted.erase(p);
416}
417
418void
419System::printSystems()
420{
421    ios::fmtflags flags(cerr.flags());
422
423    vector<System *>::iterator i = systemList.begin();
424    vector<System *>::iterator end = systemList.end();
425    for (; i != end; ++i) {
426        System *sys = *i;
427        cerr << "System " << sys->name() << ": " << hex << sys << endl;
428    }
429
430    cerr.flags(flags);
431}
432
433void
434printSystems()
435{
436    System::printSystems();
437}
438
439MasterID
440System::getMasterId(std::string master_name)
441{
442    // strip off system name if the string starts with it
443    if (startswith(master_name, name()))
444        master_name = master_name.erase(0, name().size() + 1);
445
446    // CPUs in switch_cpus ask for ids again after switching
447    for (int i = 0; i < masterIds.size(); i++) {
448        if (masterIds[i] == master_name) {
449            return i;
450        }
451    }
452
453    // Verify that the statistics haven't been enabled yet
454    // Otherwise objects will have sized their stat buckets and
455    // they will be too small
456
457    if (Stats::enabled()) {
458        fatal("Can't request a masterId after regStats(). "
459                "You must do so in init().\n");
460    }
461
462    masterIds.push_back(master_name);
463
464    return masterIds.size() - 1;
465}
466
467std::string
468System::getMasterName(MasterID master_id)
469{
470    if (master_id >= masterIds.size())
471        fatal("Invalid master_id passed to getMasterName()\n");
472
473    return masterIds[master_id];
474}
475
476System *
477SystemParams::create()
478{
479    return new System(this);
480}
481