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