openMSX
MSXDevice.cc
Go to the documentation of this file.
1 #include "MSXDevice.hh"
2 #include "XMLElement.hh"
3 #include "MSXMotherBoard.hh"
4 #include "HardwareConfig.hh"
6 #include "MSXCPUInterface.hh"
7 #include "MSXCPU.hh"
8 #include "CacheLine.hh"
9 #include "TclObject.hh"
10 #include "StringOp.hh"
11 #include "MSXException.hh"
12 #include "serialize.hh"
13 #include "stl.hh"
14 #include "unreachable.hh"
15 #include <algorithm>
16 #include <cassert>
17 #include <cstring>
18 #include <iterator> // for back_inserter
19 
20 using std::string;
21 using std::vector;
22 
23 namespace openmsx {
24 
27 
28 
29 MSXDevice::MSXDevice(const DeviceConfig& config, const string& name)
30  : deviceConfig(config)
31 {
32  initName(name);
33 }
34 
36  : deviceConfig(config)
37 {
38  initName(getDeviceConfig().getAttribute("id"));
39 }
40 
41 void MSXDevice::initName(const string& name)
42 {
43  deviceName = name;
44  if (getMotherBoard().findDevice(deviceName)) {
45  unsigned n = 0;
46  do {
47  deviceName = StringOp::Builder() << name << " (" << ++n << ')';
48  } while (getMotherBoard().findDevice(deviceName));
49  }
50 }
51 
53 {
54  staticInit();
55 
56  lockDevices();
57  registerSlots();
58  registerPorts();
59 }
60 
62 {
63  unregisterPorts();
64  unregisterSlots();
65  unlockDevices();
66  assert(referencedBy.empty());
67 }
68 
69 void MSXDevice::staticInit()
70 {
71  static bool alreadyInit = false;
72  if (alreadyInit) return;
73  alreadyInit = true;
74 
75  memset(unmappedRead, 0xFF, sizeof(unmappedRead));
76 }
77 
79 {
81 }
82 
83 void MSXDevice::testRemove(Devices removed) const
84 {
85  auto all = referencedBy;
86  sort(begin(all), end(all));
87  sort(begin(removed), end(removed));
88  Devices rest;
89  set_difference(begin(all), end(all), begin(removed), end(removed),
90  back_inserter(rest));
91  if (!rest.empty()) {
93  msg << "Still in use by ";
94  for (auto& d : rest) {
95  msg << d->getName() << ' ';
96  }
97  throw MSXException(msg);
98  }
99 }
100 
101 void MSXDevice::lockDevices()
102 {
103  // This code can only handle backward references: the thing that is
104  // referenced must already be instantiated, we don't try to change the
105  // instantiation order. For the moment this is good enough (only ADVRAM
106  // (an extension) uses it to refer to the VDP (inside a machine)). If
107  // needed we can implement something more sophisticated later without
108  // changing the format of the config files.
109  for (auto& c : getDeviceConfig().getChildren("device")) {
110  const auto& name = c->getAttribute("idref");
111  auto* dev = getMotherBoard().findDevice(name);
112  if (!dev) {
113  throw MSXException(
114  "Unsatisfied dependency: '" + getName() +
115  "' depends on unavailable device '" +
116  name + "'.");
117  }
118  references.push_back(dev);
119  dev->referencedBy.push_back(this);
120  }
121 }
122 
123 void MSXDevice::unlockDevices()
124 {
125  for (auto& r : references) {
126  r->referencedBy.erase(find_unguarded(r->referencedBy, this));
127  }
128 }
129 
131 {
132  // init() must already be called
133  return references;
134 }
135 
137 {
138  return getMotherBoard().getCurrentTime();
139 }
141 {
142  return getMotherBoard().getCPU();
143 }
145 {
146  return getMotherBoard().getCPUInterface();
147 }
149 {
150  return getMotherBoard().getScheduler();
151 }
153 {
154  return getMotherBoard().getMSXCliComm();
155 }
157 {
158  return getMotherBoard().getReactor();
159 }
161 {
163 }
165 {
166  return getMotherBoard().getLedStatus();
167 }
169 {
171 }
172 
173 void MSXDevice::registerSlots()
174 {
175  MemRegions tmpMemRegions;
176  for (auto& m : getDeviceConfig().getChildren("mem")) {
177  unsigned base = m->getAttributeAsInt("base");
178  unsigned size = m->getAttributeAsInt("size");
179  if ((base >= 0x10000) || (size > 0x10000)) {
180  throw MSXException(
181  "Invalid memory specification for device " +
182  getName() + " should be in range "
183  "[0x0000,0x10000).");
184  }
185  tmpMemRegions.emplace_back(base, size);
186  }
187  if (tmpMemRegions.empty()) {
188  return;
189  }
190 
191  // find primary and secondary slot specification
192  auto& slotManager = getMotherBoard().getSlotManager();
193  auto* primaryConfig = getDeviceConfig2().getPrimary();
194  auto* secondaryConfig = getDeviceConfig2().getSecondary();
195  if (primaryConfig) {
196  ps = slotManager.getSlotNum(primaryConfig->getAttribute("slot"));
197  } else {
198  throw MSXException("Invalid memory specification");
199  }
200  if (secondaryConfig) {
201  ss = slotManager.getSlotNum(secondaryConfig->getAttribute("slot"));
202  } else {
203  ss = 0;
204  }
205 
206  // This is only for backwards compatibility: in the past we added extra
207  // attributes "primary_slot" and "secondary_slot" (in each MSXDevice
208  // config) instead of changing the 'any' value of the slot attribute of
209  // the (possibly shared) <primary> and <secondary> tags. When loading
210  // an old savestate these tags can still occur, so keep this code. Also
211  // remove these attributes to convert to the new format.
212  const auto& config = getDeviceConfig();
213  if (config.hasAttribute("primary_slot")) {
214  auto& mutableConfig = const_cast<XMLElement&>(config);
215  const auto& primSlot = config.getAttribute("primary_slot");
216  ps = slotManager.getSlotNum(primSlot);
217  mutableConfig.removeAttribute("primary_slot");
218  if (config.hasAttribute("secondary_slot")) {
219  const auto& secondSlot = config.getAttribute("secondary_slot");
220  ss = slotManager.getSlotNum(secondSlot);
221  mutableConfig.removeAttribute("secondary_slot");
222  }
223  }
224 
225  // decode special values for 'ss'
226  if ((-128 <= ss) && (ss < 0)) {
227  if ((0 <= ps) && (ps < 4) &&
228  getCPUInterface().isExpanded(ps)) {
229  ss += 128;
230  } else {
231  ss = 0;
232  }
233  }
234 
235  // decode special values for 'ps'
236  if (ps == -256) {
237  slotManager.getAnyFreeSlot(ps, ss);
238  } else if (ps < 0) {
239  // specified slot by name (carta, cartb, ...)
240  slotManager.getSpecificSlot(-ps - 1, ps, ss);
241  } else {
242  // numerical specified slot (0, 1, 2, 3)
243  }
244  assert((0 <= ps) && (ps <= 3));
245 
246  if (!getCPUInterface().isExpanded(ps)) {
247  ss = -1;
248  }
249 
250  // Store actual slot in config. This has two purposes:
251  // - Make sure that devices that are grouped under the same
252  // <primary>/<secondary> tags actually use the same slot. (This
253  // matters when the value of some of the slot attributes is "any").
254  // - Fix the slot number so that it remains the same after a
255  // savestate/loadstate.
256  assert(primaryConfig);
257  primaryConfig->setAttribute("slot", StringOp::toString(ps));
258  if (secondaryConfig) {
259  string slot = (ss == -1) ? "X" : StringOp::toString(ss);
260  secondaryConfig->setAttribute("slot", slot);
261  } else {
262  if (ss != -1) {
263  throw MSXException(
264  "Missing <secondary> tag for device" +
265  getName());
266  }
267  }
268 
269  int logicalSS = (ss == -1) ? 0 : ss;
270  for (auto& r : tmpMemRegions) {
272  *this, ps, logicalSS, r.first, r.second);
273  memRegions.push_back(r);
274  }
275 
276  // Mark the slot as 'in-use' so that future searches for free external
277  // slots don't return this slot anymore. If the slot was not an
278  // external slot, this call has no effect. Multiple MSXDevices from the
279  // same extension (the same HardwareConfig) can all allocate the same
280  // slot (later they should also all free this slot).
281  slotManager.allocateSlot(ps, ss, getHardwareConfig());
282 }
283 
284 void MSXDevice::unregisterSlots()
285 {
286  if (memRegions.empty()) return;
287 
288  int logicalSS = (ss == -1) ? 0 : ss;
289  for (auto& r : memRegions) {
291  *this, ps, logicalSS, r.first, r.second);
292  }
293 
294  // See comments above about allocateSlot() for more details:
295  // - has no effect for non-external slots
296  // - can be called multiple times for the same slot
298 }
299 
300 void MSXDevice::getVisibleMemRegion(unsigned& base, unsigned& size) const
301 {
302  // init() must already be called
303  if (memRegions.empty()) {
304  base = 0;
305  size = 0;
306  return;
307  }
308  auto it = begin(memRegions);
309  unsigned lowest = it->first;
310  unsigned highest = it->first + it->second;
311  for (++it; it != end(memRegions); ++it) {
312  lowest = std::min(lowest, it->first);
313  highest = std::max(highest, it->first + it->second);
314  }
315  assert(lowest <= highest);
316  base = lowest;
317  size = highest - lowest;
318 }
319 
320 void MSXDevice::registerPorts()
321 {
322  for (auto& i : getDeviceConfig().getChildren("io")) {
323  unsigned base = i->getAttributeAsInt("base");
324  unsigned num = i->getAttributeAsInt("num");
325  const auto& type = i->getAttribute("type", "IO");
326  if (((base + num) > 256) || (num == 0) ||
327  ((type != "I") && (type != "O") && (type != "IO"))) {
328  throw MSXException("Invalid IO port specification");
329  }
330  for (unsigned port = base; port < base + num; ++port) {
331  if ((type == "I") || (type == "IO")) {
332  getCPUInterface().register_IO_In(port, this);
333  inPorts.push_back(port);
334  }
335  if ((type == "O") || (type == "IO")) {
336  getCPUInterface().register_IO_Out(port, this);
337  outPorts.push_back(port);
338  }
339  }
340  }
341 }
342 
343 void MSXDevice::unregisterPorts()
344 {
345  for (auto& p : inPorts) {
347  }
348  for (auto& p : outPorts) {
350  }
351 }
352 
353 
355 {
356  // nothing
357 }
358 
360 {
361  return 0xFF;
362 }
363 
365 {
366  // nothing
367 }
368 
370 {
371  reset(time);
372 }
373 
374 string MSXDevice::getName() const
375 {
376  return deviceName;
377 }
378 
380 {
381  result.addListElement(getName());
382 }
383 
385 {
387  getExtraDeviceInfo(result);
388 }
389 
391 {
392  // nothing
393 }
394 
395 
397 {
398  // read from unmapped IO
399  return 0xFF;
400 }
401 
402 void MSXDevice::writeIO(word /*port*/, byte /*value*/, EmuTime::param /*time*/)
403 {
404  // write to unmapped IO, do nothing
405 }
406 
407 byte MSXDevice::peekIO(word /*port*/, EmuTime::param /*time*/) const
408 {
409  return 0xFF;
410 }
411 
412 
414 {
415  // read from unmapped memory
416  return 0xFF;
417 }
418 
419 const byte* MSXDevice::getReadCacheLine(word /*start*/) const
420 {
421  return nullptr; // uncacheable
422 }
423 
424 void MSXDevice::writeMem(word /*address*/, byte /*value*/,
425  EmuTime::param /*time*/)
426 {
427  // write to unmapped memory, do nothing
428 }
429 
430 byte MSXDevice::peekMem(word address, EmuTime::param /*time*/) const
431 {
432  word base = address & CacheLine::HIGH;
433  if (const byte* cache = getReadCacheLine(base)) {
434  word offset = address & CacheLine::LOW;
435  return cache[offset];
436  } else {
437  // peek not supported for this device
438  return 0xFF;
439  }
440 }
441 
442 void MSXDevice::globalWrite(word /*address*/, byte /*value*/,
443  EmuTime::param /*time*/)
444 {
445  UNREACHABLE;
446 }
447 
449 {
450  return nullptr; // uncacheable
451 }
452 
453 void MSXDevice::invalidateMemCache(word start, unsigned size)
454 {
455  getCPU().invalidateMemCache(start, size);
456 }
457 
458 template<typename Archive>
459 void MSXDevice::serialize(Archive& ar, unsigned /*version*/)
460 {
461  // When this method is called, the method init() has already been
462  // called (thus also registerSlots() and registerPorts()).
463  ar.serialize("name", deviceName);
464 }
466 
467 } // namespace openmsx
virtual void init()
Definition: MSXDevice.cc:52
signed char offset
Definition: CPUCore.cc:252
void freeSlot(int ps, int ss, const HardwareConfig &hwConfig)
Contains the main loop of openMSX.
Definition: Reactor.hh:62
MSXCPUInterface & getCPUInterface() const
Definition: MSXDevice.cc:144
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:150
void registerMemDevice(MSXDevice &device, int primSl, int secSL, int base, int size)
Devices can register themself in the MSX slotstructure.
ITER find_unguarded(ITER first, ITER last, const VAL &val)
Faster alternative to 'find' when it's guaranteed that the value will be found (if not the behavior i...
Definition: stl.hh:114
PluggingController & getPluggingController()
MSXCPUInterface & getCPUInterface()
string toString(long long a)
Definition: StringOp.cc:156
EmuTime::param getCurrentTime() const
Definition: MSXDevice.cc:136
unsigned char byte
8 bit unsigned integer
Definition: openmsx.hh:27
const HardwareConfig & getHardwareConfig() const
Returns the hardwareconfig this device belongs to.
Definition: MSXDevice.hh:41
virtual byte readMem(word address, EmuTime::param time)
Read a byte from a location at a certain time from this device.
Definition: MSXDevice.cc:413
virtual void writeMem(word address, byte value, EmuTime::param time)
Write a given byte to a given location at a certain time to this device.
Definition: MSXDevice.cc:424
XMLElement * getPrimary() const
Definition: DeviceConfig.hh:58
virtual void globalWrite(word address, byte value, EmuTime::param time)
Global writes.
Definition: MSXDevice.cc:442
PluggingController & getPluggingController() const
Definition: MSXDevice.cc:168
virtual byte readIRQVector()
Gets IRQ vector used in IM2.
Definition: MSXDevice.cc:359
virtual byte readIO(word port, EmuTime::param time)
Read a byte from an IO port at a certain time from this device.
Definition: MSXDevice.cc:396
Central administration of Connectors and Pluggables.
void unregister_IO_In(byte port, MSXDevice *device)
void unregisterMemDevice(MSXDevice &device, int primSl, int secSL, int base, int size)
void getDeviceInfo(TclObject &result) const
Get device info.
Definition: MSXDevice.cc:384
LedStatus & getLedStatus() const
Definition: MSXDevice.cc:164
Reactor & getReactor() const
Definition: MSXDevice.cc:156
const DeviceConfig & getDeviceConfig2() const
Definition: MSXDevice.hh:213
CommandController & getCommandController() const
Definition: MSXDevice.cc:160
void invalidateMemCache(word start, unsigned size)
Invalidate the CPU its cache for the interval [start, start + size) For example MSXMemoryMapper and M...
Definition: MSXCPU.cc:187
void serialize(Archive &ar, unsigned version)
Definition: MSXDevice.cc:459
virtual void powerUp(EmuTime::param time)
This method is called when MSX is powered up.
Definition: MSXDevice.cc:369
MSXDevice * findDevice(string_ref name)
Find a MSXDevice by name.
virtual byte * getWriteCacheLine(word start) const
Test that the memory in the interval [start, start + CacheLine::SIZE) is cacheable for writing...
Definition: MSXDevice.cc:448
void register_IO_In(byte port, MSXDevice *device)
Devices can register their In ports.
MSXMotherBoard & getMotherBoard() const
Get the mother board this device belongs to.
Definition: MSXDevice.cc:78
virtual std::string getName() const
Returns a human-readable name for this device.
Definition: MSXDevice.cc:374
virtual const byte * getReadCacheLine(word start) const
Test that the memory in the interval [start, start + CacheLine::SIZE) is cacheable for reading...
Definition: MSXDevice.cc:419
void register_IO_Out(byte port, MSXDevice *device)
Devices can register their Out ports.
CliComm & getCliComm() const
Definition: MSXDevice.cc:152
CartridgeSlotManager & getSlotManager()
MSXDevice(const DeviceConfig &config, const std::string &name)
Every MSXDevice has a config entry; this constructor gets some device properties from that config ent...
Definition: MSXDevice.cc:29
const Devices & getReferences() const
Get the device references that are specified for this device.
Definition: MSXDevice.cc:130
void testRemove(Devices alreadyRemoved) const
Checks whether this device can be removed (no other device has a reference to it).
Definition: MSXDevice.cc:83
virtual void powerDown(EmuTime::param time)
This method is called when MSX is powered down.
Definition: MSXDevice.cc:364
void getVisibleMemRegion(unsigned &base, unsigned &size) const
Returns the range where this device is visible in memory.
Definition: MSXDevice.cc:300
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:7
An MSXDevice is an emulated hardware component connected to the bus of the emulated MSX...
Definition: MSXDevice.hh:32
unsigned short word
16 bit unsigned integer
Definition: openmsx.hh:32
virtual void writeIO(word port, byte value, EmuTime::param time)
Write a byte to a given IO port at a certain time to this device.
Definition: MSXDevice.cc:402
CommandController & getCommandController()
void unregister_IO_Out(byte port, MSXDevice *device)
virtual void getExtraDeviceInfo(TclObject &result) const
Definition: MSXDevice.cc:390
MSXCPU & getCPU() const
Definition: MSXDevice.cc:140
const XMLElement & getDeviceConfig() const
Get the configuration section for this device.
Definition: MSXDevice.hh:210
std::vector< MSXDevice * > Devices
Definition: MSXDevice.hh:35
static byte unmappedRead[0x10000]
Definition: MSXDevice.hh:266
void addListElement(string_ref element)
Definition: TclObject.cc:120
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
Definition: serialize.hh:802
static byte unmappedWrite[0x10000]
Definition: MSXDevice.hh:267
virtual byte peekMem(word address, EmuTime::param time) const
Read a byte from a given memory location.
Definition: MSXDevice.cc:430
virtual byte peekIO(word port, EmuTime::param time) const
Read a byte from a given IO port.
Definition: MSXDevice.cc:407
virtual void reset(EmuTime::param time)
This method is called on reset.
Definition: MSXDevice.cc:354
EmuTime::param getCurrentTime()
Convenience method: This is the same as getScheduler().getCurrentTime().
size_t size(string_ref utf8)
string_ref::const_iterator begin(const string_ref &x)
Definition: string_ref.hh:149
Scheduler & getScheduler() const
Definition: MSXDevice.cc:148
XMLElement * getSecondary() const
Definition: DeviceConfig.hh:62
virtual void getNameList(TclObject &result) const
Returns list of name(s) of this device.
Definition: MSXDevice.cc:379
void invalidateMemCache(word start, unsigned size)
Invalidate CPU memory-mapping cache.
Definition: MSXDevice.cc:453
virtual ~MSXDevice()=0
Definition: MSXDevice.cc:61
#define UNREACHABLE
Definition: unreachable.hh:35
MSXMotherBoard & getMotherBoard() const