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