Merge pull request #156 from p12nGH/noncontiguous_harts
[riscv-isa-sim.git] / riscv / devices.cc
index c7a63b0044b87e5a9a5dbd3df2958abd95699cd5..bcdd3a19ea89d05b978eb91162d38e9f3db8c66f 100644 (file)
@@ -2,21 +2,49 @@
 
 void bus_t::add_device(reg_t addr, abstract_device_t* dev)
 {
-  devices[-addr] = dev;
+  // Searching devices via lower_bound/upper_bound
+  // implicitly relies on the underlying std::map 
+  // container to sort the keys and provide ordered
+  // iteration over this sort, which it does. (python's
+  // SortedDict is a good analogy)
+  devices[addr] = dev;
 }
 
 bool bus_t::load(reg_t addr, size_t len, uint8_t* bytes)
 {
-  auto it = devices.lower_bound(-addr);
-  if (it == devices.end())
+  // Find the device with the base address closest to but
+  // less than addr (price-is-right search)
+  auto it = devices.upper_bound(addr);
+  if (devices.empty() || it == devices.begin()) {
+    // Either the bus is empty, or there weren't 
+    // any items with a base address <= addr
     return false;
-  return it->second->load(addr - -it->first, len, bytes);
+  }
+  // Found at least one item with base address <= addr
+  // The iterator points to the device after this, so
+  // go back by one item.
+  it--;
+  return it->second->load(addr - it->first, len, bytes);
 }
 
 bool bus_t::store(reg_t addr, size_t len, const uint8_t* bytes)
 {
-  auto it = devices.lower_bound(-addr);
-  if (it == devices.end())
+  // See comments in bus_t::load
+  auto it = devices.upper_bound(addr);
+  if (devices.empty() || it == devices.begin()) {
     return false;
-  return it->second->store(addr - -it->first, len, bytes);
+  }
+  it--;
+  return it->second->store(addr - it->first, len, bytes);
+}
+
+std::pair<reg_t, abstract_device_t*> bus_t::find_device(reg_t addr)
+{
+  // See comments in bus_t::load
+  auto it = devices.upper_bound(addr);
+  if (devices.empty() || it == devices.begin()) {
+    return std::make_pair((reg_t)0, (abstract_device_t*)NULL);
+  }
+  it--;
+  return std::make_pair(it->first, it->second);
 }