~ehmry/device_manager

ref: post-mortem device_manager/src/device_manager.nim -rw-r--r-- 12.6 KiB
0e438d77Emery Hemingway Cleanup notes 1 year, 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# SPDX-FileCopyrightText: 2021 Emery Hemingway
#
# SPDX-License-Identifier: GPL-3.0-or-later.txt

when defined(genode):
  import genode/reports, genode/roms

import std/options, std/strtabs, std/strutils, std/tables, std/xmlparser, std/xmltree

from std/os import sleep

# USB driver documentation:
# genode/repos/dde_linux/src/drivers/usb_host/*.cc

# part_block documentation:
# genode/repos/os/src/server/part_block/README
# /home/repo/genode/repos/os/src/server/part_block/gpt.h - _parse_gpt

const
  ahciPortsRomLabel = "ahci-ports.xml"
  usbDevicesRomLabel = "usb-devices.xml"

const massStorage = 8

type ManagerState = ref object
  when defined(genode):
    env: GenodeEnv
    initConfigReport: ReportClient
    partitionReports: Table[string, RomHandler]
    configRom: RomHandler
    ahciPortsRom, usbDevicesRom: Option[RomHandler]
  else:
    partitionReports: Table[string, XmlNode]
    configRomXml: XmlNode
    ahciPortsRomXml, usbDevicesRomXml: XmlNode
  verbose: bool

proc process(state: ManagerState) {.gcsafe.}

when defined(genode):
  proc connectRom(state: ManagerState; label: string): RomHandler =
    echo "request ROM \"", label, "\""
    newRomHandler(state.env, label) do (rom: RomClient):
      try:
        update(rom)
        let data = rom.xml()
        echo "process ", label, " ROM"
        if state.verbose:
          echo data
        process(state)
      except XmlError: discard
  proc configRomXml(state: ManagerState): XmlNode =
    state.configRom.xml()
  proc ahciPortsRomXml(state: ManagerState): XmlNode =
    if state.ahciPortsRom.isSome:
      try: return state.ahciPortsRom.get.xml()
      except XmlError:
        echo "AHCI ports ROM is invalid"
    result = newElement("ports")
  proc usbDevicesRomXml(state: ManagerState): XmlNode =
    if state.usbDevicesRom.isSome:
      try: return state.usbDevicesRom.get.xml()
      except XmlError:
        echo "USB devices ROM is invalid"
    result = newElement("devices")

proc childOrDefault(n: XmlNode; name: string): XmlNode =
  if n.isNil: return newElement(name)
  result = n.child(name)
  if result.isNil: return newElement(name)

proc defaultPolicy(n: XmlNode): XmlNode =
  result = newElement("default-policy")
  result.add(n)

proc process(state: ManagerState) =
  let
    cfg = state.configRomXml
    ahciPortsReport = state.ahciPortsRomXml
    usbDevicesReport = state.usbDevicesRomXml
    ahciDriverCfg = cfg.child("ahci_drv")
    usbDriverCfg = cfg.child("usb_host_drv")
    blockCfg = cfg.child("usb_block_drv")
    partCfg = cfg.child("part_block")
    reportRomCfg = cfg.child("report_rom")
  state.verbose = cfg.attrs.getOrDefault("verbose", "no") == "yes"
  when defined(genode):
    if not ahciDriverCfg.isNil and state.ahciPortsRom.isNone:
      state.ahciPortsRom = some connectRom(state, ahciPortsRomLabel)
    if not usbDriverCfg.isNil:
      if blockCfg.isNil:
        echo "missing <usb_block_drv/> node in configuration"
        quit(-1)
      if state.usbDevicesRom.isNone:
        state.usbDevicesRom = some connectRom(state, usbDevicesRomLabel)
  if partCfg.isNil:
    echo "missing <part_block/> node in configuration"
    quit(-1)
  if reportRomCfg.isNil:
    echo "missing <report_rom/> node in configuration"
    quit(-1)

  var
    routes = newElement("routes")
    pendingPolicy = defaultPolicy(<>child(name = "pending"))
    blockServicePolicies = <>service(name = "Block", pendingPolicy)
    romServicePolicies = <>service(name = "ROM", pendingPolicy)
    children = newSeq[XmlNode]()
    reportRomConfig = newElement("config")
    ahciDriverConfig = ahciDriverCfg.childOrDefault("config")
    usbDriverConfig = usbDriverCfg.childOrDefault("config")
    partitionReports = move state.partitionReports
    pendingPartitionReportLabels = newSeq[string]()

  when defined(genode):
    proc fillPartBlockConfig(partConfig: XmlNode; partRom: RomHandler; partBlockName: string) =
      try:
        let report = partRom.xml
        for part in report.findAll("partition"):
          try:
            let
              pUuid = part.attrs["guid"]
              pType = part.attrs["type"]
            partConfig.add(<>policy(
                label_suffix = pUuid, partition = part.attrs["number"], writeable = "yes"))
            partConfig.add(<>policy(
                label_suffix = pType, partition = part.attrs["number"], writeable = "yes"))
            blockServicePolicies.add(<>policy(
                label_suffix = pUuid, <>child(name = partBlockName)))
            blockServicePolicies.add(<>policy(
                label_suffix = pType, <>child(name = partBlockName)))
            # TODO: multiple partitions having the same type
          except KeyError: discard
      except XmlError: discard

  for p in ahciPortsReport.findAll("port"):
    try:
      let
        portNum = p.attrs["num"]
        baseLabel = "ahci-" & portNum
        partBlockName = "part_block-" & baseLabel
        partReportLabel = "partitions-" & baseLabel
      var partConfig = <>config(<>report(partitions = "yes"))
      when defined(genode):
        var report: RomHandler
        if partitionReports.pop(partReportLabel, report):
          state.partitionReports[partReportLabel] = report
          fillPartBlockConfig(partConfig, report, partBlockName)
        else:
          pendingPartitionReportLabels.add(partReportLabel)
      let partStart = <>start(
          name = partBlockName, caps = "128",
          <>binary(name = partCfg.attrs["binary"]),
          <>resource(name = "RAM", quantum = "8M"),
          <>provides(<>service(name = "Block")),
          partConfig)
      children.add(partStart)
      routes.add(<>service(
          name = "Block", label_prefix = partBlockName, <>child(name = "ahci", label = partBlockName)))
      reportRomConfig.add(<>policy(
          label_suffix = partReportLabel, report = partBlockName & " -> partitions"))
      romServicePolicies.add(<>policy(label_suffix = partReportLabel, <>child(name = "report_rom")))
      ahciDriverConfig.add(<>policy(
          label = partBlockName, device = portNum, writeable = "yes"))
    except XmlError:
      echo "failed to parse ", p

  for d in usbDevicesReport.findAll("device"):
    try:
      let
        attrs = d.attrs
        classStr = attrs.getOrDefault("class", "0")
        classNum = if classStr.startsWith("0x"):
          classStr.parseHexInt else: classStr.parseInt
      case classNum
      of massStorage:
        if blockCfg.isNil: continue
        let
          baseLabel = attrs["label"]
          blockDriverName = "block-" & baseLabel
          partBlockName = "part_block-" & baseLabel
          partReportLabel = "partitions-" & baseLabel

        let blockStart = <>start(
            name = blockDriverName, caps = "128",
            <>resource(name = "RAM", quantum = "4M"),
            <>provides(<>service(name = "Block")),
            <>binary(name = blockCfg.attrs["binary"]))
        children.add(blockStart)

        var partConfig = <>config(<>report(partitions = "yes"))
        when defined(genode):
          var report: RomHandler
          if partitionReports.pop(partReportLabel, report):
            state.partitionReports[partReportLabel] = report
            fillPartBlockConfig(partConfig, report, partBlockName)
          else:
            pendingPartitionReportLabels.add(partReportLabel)
        let partStart = <>start(
            name = partBlockName, caps = "128",
            <>resource(name = "RAM", quantum = "8M"),
            <>provides(<>service(name = "Block")),
            <>binary(name = partCfg.attrs["binary"]),
            partConfig)
        children.add(partStart)

        usbDriverConfig.add(<>policy(
            bus = attrs["bus"], dev = attrs["dev"], label_prefix = blockDriverName))
        routes.add(<>service(
            name = "Usb", label_prefix = blockDriverName, <>child(name = "usb")))
        routes.add(<>service(
            name = "Block", label_prefix = partBlockName, <>child(name = blockDriverName)))
        reportRomConfig.add(<>policy(
            label_suffix = partReportLabel, report = partBlockName & " -> partitions"))
        romServicePolicies.add(<>policy(label_suffix = partReportLabel, <>child(name = "report_rom")))
      else: discard
    except XmlError:
      echo "failed to parse ", d

  var initConfig = newElement("config")

  var reportRomStart = <>start(
      name = "report_rom", caps = "96",
      <>resource(name = "RAM", quantum = "2M"),
      <>provides(<>service(name = "ROM"),
      <>service(name = "Report")),
      <>binary(name = reportRomCfg.attrs["binary"]),
      reportRomConfig)
  initConfig.add(reportRomStart)

  if not usbDriverCfg.isNil:
    usbDriverConfig.add(<>report(devices = "yes"))
    let usbDriverStart = <>start(
        name = "usb", caps = "128",
        <>resource(name = "RAM", quantum = "12M"),
        <>provides(<>service(name = "Usb")),
        <>binary(name = usbDriverCfg.attrs["binary"]),
        usbDriverConfig)
    initConfig.add(usbDriverStart)
    if state.verbose:
      echo "USB host driver config:"
      echo usbDriverConfig

  if not ahciDriverCfg.isNil:
    ahciDriverConfig.add(<>report(ports = "yes"))
    let ahciDriverStart = <>start(
        name = "ahci", caps = "128",
        <>resource(name = "RAM", quantum = "10M"),
        <>provides(<>service(name = "Block")),
        <>binary(name = ahciDriverCfg.attrs["binary"]),
        ahciDriverConfig)
    initConfig.add(ahciDriverStart)

  for child in children:
    initConfig.add(child)
      # Add children last, init will starve the
      # last child if resources are depleted

  for name in ["CPU", "IO_MEM", "IO_PORT", "IRQ", "LOG", "PD", "RM",
      "ROM", "Platform", "Timer"]:
    routes.add(<>service(name = name, <>parent()))
  routes.add(<>service(
      name = "Report", label = "ahci -> ports", <>parent(label = ahciPortsRomLabel)))
  routes.add(<>service(
      name = "Report", label = "usb -> devices", <>parent(label = usbDevicesRomLabel)))
  routes.add(<>service(name = "Report", <>child(name = "report_rom")))
  routes.add(<>service(name = "ROM", label = "usb -> config", <>child(name = "report_rom")))
  initConfig.add(routes)

  initConfig.add(blockServicePolicies)
  initConfig.add(romServicePolicies)

  initConfig.add(<>service(name = "ROM", defaultPolicy(<>child(name = "report_rom"))))

  let genodeXml = replace($initConfig, "&gt;", ">")
    # the genode XML parser cannot parse
    # configurations with standard escaping applied
  when defined(genode):
    echo "submit drivers init config"
    state.initConfigReport.submit(genodeXml)
    for label, staleReport in partitionReports.pairs:
      echo "close ", label, " ROM"
      close(staleReport)
    sleep(1000) # handle the USB driver with care
    for label in pendingPartitionReportLabels:
      echo "requesting ", label, " ROM"
      state.partitionReports[label] = connectRom(state, label)
  else:
    echo(genodeXml)

when defined(genode):
  componentConstructHook = proc(env: GenodeEnv) =
    var state = ManagerState(
        env: env,
        initConfigReport: env.newReportClient("drivers.config.xml"),
        partitionReports: initTable[string, RomHandler]())
    state.configRom = connectRom(state, "config")
    process(state.configRom)


when defined(linux):
  import std/xmlparser
  var state = ManagerState(
      partitionReports: initTable[string, XmlNode](),
      configRomXml: parseXml """
      <config vebose="yes">
      <ahci_drv binary="ahci_drv"/>
      <usb_host_drv binary="x86_pc_usb_host_drv"><config uhci="yes" ohci="yes" ehci="yes" xhci="yes"/></usb_host_drv>
      <usb_block_drv binary="usb_block_drv_drv"/>
      <part_block binary="part_block"/>
      <report_rom binary="report_rom"/>
      </config>
      """,
      ahciPortsRomXml: parseXml """
      <ports>
        <port num="0" type="ATA" block_count="32768" block_size="512"
          model="QEMU HARDDISK" serial="QM00005"/>
        <port num="1" type="ATAPI"/>
        <port num="2" type="ATA" block_count="32768" block_size="512"
          model="QEMU HARDDISK" serial="QM00009"/>
      </ports>
      """,
      usbDevicesRomXml: parseXml """
      <devices>
        <device label="usb-1-2" vendor_id="0x46f4" product_id="0x0001" bus="0x0001" dev="0x0002" class="0x08"/>
        <device label="usb-1-1" vendor_id="0x1d6b" product_id="0x0002" bus="0x0001" dev="0x0001" class="0x09"/>
      </devices>
      """)
  state.partitionReports["part_block-usb-3-4"] = parseXml """
  <partitions type="gpt">
  <partition number="1" name="one" type="ebd0a0a2-b9e5-4433-87c0-68b6b72699c7" guid="5f4061cc-8d4a-4e6f-ad15-10b881b79aee" start="2048" length="2048"/>
  <partition number="2" name="two" type="ebd0a0a2-b9e5-4433-87c0-68b6b72699c7" guid="87199a83-d0f4-4a01-b9e3-6516a8579d61" start="4096" length="16351"/>
  </partitions>
  """
  process(state)