Guest User

hw/isp.py

a guest
Sep 19th, 2023
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.47 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: MIT
  3. import sys, pathlib, time
  4.  
  5. import struct
  6. from enum import IntEnum
  7. from ..utils import *
  8. from m1n1.fw.isp.isp_opcodes import *
  9.  
  10. class ISPCommandDirection(IntEnum):
  11. RX = 0
  12. TX = 1
  13.  
  14. class ISPCommand:
  15. """ Represents a command in any IPC channel """
  16.  
  17. def __init__(self, channel, message, direction):
  18. self.arg0, self.arg1, self.arg2, self.arg3, self.arg4, self.arg5, self.arg6, self.arg7 = struct.unpack("<8q", message.data)
  19. self.iova = self.arg0 & ~3
  20. # value, u0, u1 = struct.unpack('<3q40x', message.data)
  21. self.message = message
  22. self.channel = channel
  23. self.direction = direction
  24. self.tracer = channel.tracer
  25.  
  26. value, u0, u1 = struct.unpack('<3q40x', message.data)
  27. self.value = value & 0xFFFFFFFFFFFFFFFC
  28.  
  29. def dump(self):
  30. self.log(f"[CMD arg0: {hex(self.arg0)}, arg1: {hex(self.arg1)}, arg2: {hex(self.arg2)}]")
  31.  
  32. def read_iova(self, address, length):
  33. return self.tracer.dart.ioread(0, address, length)
  34.  
  35. def valid(self):
  36. return True
  37.  
  38. def log(self, message):
  39. if self.direction is ISPCommandDirection.RX:
  40. self.tracer.log(f"<== [{self.channel.name}]({self.message.index}): {message}")
  41. else:
  42. self.tracer.log(f"==> [{self.channel.name}]({self.message.index}): {message}")
  43.  
  44. class ISPTerminalCommand(ISPCommand):
  45. """ Represents a command in TERMINAL channel
  46.  
  47. A command arguments include a pointer to a buffer that contains log line
  48. and the length of the buffer. Buffers are 0x80 bytes wide.
  49. """
  50. # ISP sends buffer address at beginning
  51. BUFFER_ADDRESS = None
  52. # It seems messages are capped to 100 bytes
  53. MAX_BUFFER_SIZE = 0x80
  54.  
  55. @staticmethod
  56. def set_address(address):
  57. if address != 0:
  58. ISPTerminalCommand.BUFFER_ADDRESS = address
  59.  
  60. @staticmethod
  61. def move_cursor():
  62. if ISPTerminalCommand.BUFFER_ADDRESS:
  63. ISPTerminalCommand.BUFFER_ADDRESS += ISPTerminalCommand.MAX_BUFFER_SIZE
  64. else:
  65. return None
  66.  
  67. def __init__(self, channel, message, direction):
  68. super().__init__(channel, message, direction)
  69.  
  70. ## Set buffer address
  71. ISPTerminalCommand.set_address(self.value)
  72.  
  73. ## Read contents
  74. self.buffer_message = self.read_iova(ISPTerminalCommand.BUFFER_ADDRESS, self.arg1)
  75.  
  76. ## Move cursor
  77. ISPTerminalCommand.move_cursor()
  78.  
  79. def dump(self):
  80. if self.buffer_message:
  81. s = self.buffer_message.decode().strip().replace('\n', '').replace('\r', '')
  82. if (s):
  83. print("(%d): ISPASC: %s" % (self.message.index, s))
  84.  
  85. class ISPIOCommand(ISPCommand):
  86. """ Represents a command in IO channel
  87.  
  88. An IO command is used to request ISP to perform some operations. The command
  89. contains a pointer to a command struct which contains a OPCODE. The OPCODE
  90. is used to differentate commands.
  91. """
  92.  
  93. def __init__(self, channel, message, direction):
  94. super().__init__(channel, message, direction)
  95.  
  96. if self.iova != 0:
  97. # Dumping first 0x80 bytes bc structs all differ TODO get size
  98. self.contents = self.read_iova(self.iova, 0x120)
  99. else:
  100. self.contents = None
  101.  
  102. def dump(self):
  103. if self.iova != 0:
  104. self.contents = self.read_iova(self.iova, 0x120)
  105. opcode = struct.unpack("<l", self.contents[0x4:0x8])[0]
  106. self.log(f"[IO iova: {hex(self.iova)}, insize: {hex(self.arg1)}, outsize: {hex(self.arg2)} -> opcode: {hex(opcode)}]")
  107. chexdump32(self.message.data)
  108. self.log("IO struct: ")
  109. chexdump32(self.contents)
  110.  
  111. class ISPT2HBufferCommand(ISPCommand):
  112. """ Represents a command in BUF_T2H channel """
  113. def __init__(self, channel, message, direction):
  114. super().__init__(channel, message, direction)
  115.  
  116. def dump(self):
  117. super().dump()
  118. if self.iova != 0:
  119. self.contents = self.read_iova(0x1813140, 0x4000)
  120. print("BufT2H struct:")
  121. chexdump32(self.contents)
  122.  
  123. class ISPH2TBufferCommand(ISPCommand):
  124. """ Represents a command in BUF_H2T channel """
  125. def __init__(self, channel, message, direction):
  126. super().__init__(channel, message, direction)
  127.  
  128. def dump(self):
  129. super().dump()
  130. if self.iova != 0:
  131. self.contents = self.read_iova(0x1813140, 0x4000)
  132. print("BufT2H struct:")
  133. chexdump32(self.contents)
  134.  
  135. class ISPT2HIOCommand(ISPCommand):
  136. """ Represents a command in IO_T2H channel """
  137. def __init__(self, channel, message, direction):
  138. super().__init__(channel, message, direction)
  139.  
  140. def dump(self):
  141. super().dump()
  142.  
  143. class ISPSharedMallocCommand(ISPCommand):
  144. """ Represents a command in SHAREDMALLOC channel
  145.  
  146. A command of this type can either request memory allocation or memory free
  147. depending the arguments. When ISP needs to allocate memory, it puts a
  148. message in the SHAREDMALLOC channel, message arguments are length of buffer
  149. and type of allocation.
  150.  
  151. CPU detects the new message, perform memory allocation and mutate the
  152. original message to indicate the address of the allocated memory block.
  153. """
  154.  
  155. def __init__(self, channel, message, direction):
  156. super().__init__(channel, message, direction)
  157.  
  158. def dump(self):
  159. if self.direction == ISPCommandDirection.RX:
  160. if self.iova is 0:
  161. size = self.arg1
  162. name = struct.pack(">q", self.arg2).decode()
  163. else:
  164. self.log(f"[FW Free, iova: {hex(self.arg0)}, size: {hex(self.arg1)}, index: {hex(self.arg2)})]")
  165. else:
  166. pass # should never get here
  167.  
  168. class ISPChannelTable:
  169. """ A class used to present IPC table.
  170.  
  171. The Channel Table describes the IPC channels available to communicate with
  172. the ISP.
  173.  
  174. In the M1 processor (tonga), the list of channels exposed by ISP are:
  175. [CH - TERMINAL] (src = 0, type = 2, entries = 768, iova = 0x1804700)
  176. [CH - IO] (src = 1, type = 0, entries = 8, iova = 0x1810700)
  177. [CH - BUF_H2T] (src = 2, type = 0, entries = 64, iova = 0x1810b00)
  178. [CH - BUF_T2H] (src = 3, type = 1, entries = 64, iova = 0x1811b00)
  179. [CH - SHAREDMALLOC] (src = 3, type = 1, entries = 8, iova = 0x1812b00)
  180. [CH - IO_T2H] (src = 3, type = 1, entries = 8, iova = 0x1812d00)
  181.  
  182. Each entry in the table is 256 bytes wide. Here is the layout of each entry:
  183. 0x00 - 0x1F = Name (NULL terminated string)
  184. 0x20 - 0x3F = Padding
  185. 0x40 - 0x43 = Type (DWORD)
  186. 0x44 - 0x47 = Source (DWORD)
  187. 0x48 - 0x4F = Entries (QWORD)
  188. 0x50 - 0x58 = Address (QWORD)
  189. """
  190.  
  191. ENTRY_LENGTH = 256
  192.  
  193. def __init__(self, tracer, number_of_channels, table_address):
  194. self.tracer = tracer
  195. self.address = table_address
  196. self.count = number_of_channels
  197. self.size = number_of_channels * self.ENTRY_LENGTH
  198. self.channels = []
  199.  
  200. _table = self.ioread(self.address & 0xFFFFFFFF, self.size)
  201. for offset in range(0, self.size, self.ENTRY_LENGTH):
  202. _entry = _table[offset: offset + self.ENTRY_LENGTH]
  203. _name, _type, _source, _entries, _address = struct.unpack('<32s32x2I2q168x', _entry)
  204. _channel = ISPChannel(self, _name, _type, _source, _entries, _address)
  205. # We want to process terminal logs as fast as possible before they are processed by CPU
  206. # So we use a special implementation for TERMINAL channel that fetches all logs
  207. if _channel.name == "TERMINAL":
  208. _channel = ISPTerminalChannel(self, _name, _type, _source, _entries, _address)
  209. self.channels.append(_channel)
  210.  
  211. def get_last_write_command(self, doorbell_value):
  212. """ Gets last written message given a Doorbell value """
  213. if self.channels and len(self.channels) > 0:
  214. names = []
  215. channel_cmds = []
  216. for channel in self.channels:
  217. if (channel.name == "TERMINAL"): continue
  218. # We want to process terminal logs as fast as possible before they are processed by CPU
  219. if (channel.doorbell == doorbell_value) and channel.name == "TERMINAL":
  220. names.append(channel.name)
  221. for cmd in channel.get_commands(ISPCommandDirection.TX):
  222. channel_cmds.append(cmd)
  223.  
  224. self.log(f"CHs: [{(','.join(names))}]")
  225. for cmd in channel_cmds:
  226. cmd.dump()
  227.  
  228. def get_last_read_command(self, pending_irq):
  229. """ Gets last read message given a IRQ value """
  230. cmds = []
  231. scanned_channels = []
  232. if self.channels and len(self.channels) > 0:
  233. cidx = 0
  234. for channel in self.channels:
  235. if (channel.name == "TERMINAL"): continue
  236. if (pending_irq >> channel.source & 1) != 0:
  237. scanned_channels.append(channel.name)
  238. for cmd in channel.get_commands(ISPCommandDirection.RX):
  239. cmds.append(cmd)
  240. cidx = cidx + 1
  241.  
  242. if len(scanned_channels) > 0:
  243. self.log(f"CHs: [{(','.join(scanned_channels))}]")
  244. for cmd in cmds:
  245. cmd.dump()
  246.  
  247. def dump(self):
  248. """ Dumps the content of each channel """
  249. if self.channels and len(self.channels) > 0:
  250. for channel in self.channels:
  251. if (channel.name != "SHAREDMALLOC") and (channel.name != "IO_T2H") and (channel.name != "TERMINAL") and (channel.name != "DEBUG"):
  252. channel.dump()
  253.  
  254. def ioread(self, address, size):
  255. return self.tracer.ioread(address, size)
  256.  
  257. def log(self, message):
  258. self.tracer.log(message)
  259.  
  260. def __str__(self):
  261. s = "======== CHANNEL TABLE ========\n"
  262. for channel in self.channels:
  263. s += f"\t{str(channel)}\n"
  264. return s
  265.  
  266. class ISPChannel:
  267. """ A class used to represent IPC channel
  268.  
  269. ISP channels are ring buffers used by communication between CPU and ISP.
  270. channel length is measured in number of entries, each entry is 64 bytes,
  271. so channel size is '(entries * 64)' bytes.
  272.  
  273. Channel Source is used to filter out channels when processing interrupts
  274. and doorbell. Each time CPU wants to notify ISP about a new message it
  275. writes doorbell register. In the other hand, when ISP wants to notify CPU
  276. about a new message it triggers a hardware interrupt.
  277.  
  278. Channel Type is a mistery, but it seems to have a connection with cmd bit
  279. mask.
  280. """
  281.  
  282. ENTRY_LENGTH = 64
  283.  
  284. def __init__(self, table, name, _type, source, number_of_entries, address):
  285. self.table = table
  286. self.tracer = table.tracer
  287. self.name = str(name, "ascii").rstrip('\x00')
  288. self.source = source
  289. self.type = _type
  290. self.number_of_entries = number_of_entries
  291. self.num = self.number_of_entries
  292. self.entry_size = self.ENTRY_LENGTH
  293. self.size = self.number_of_entries * self.entry_size
  294. self.address = address
  295. self.doorbell = 1 << source
  296. self.last_message_sent = None
  297. self.last_message_received = None
  298.  
  299. def get_commands(self, direction):
  300. """ Gets a command from the channel"""
  301. commands = []
  302. message = self.get_message(direction)
  303. if message:
  304. command = self.__convert2command__(message, direction)
  305. if command:
  306. commands.append(command)
  307. return commands
  308.  
  309. def get_message(self, direction):
  310. """ Gets a message from the channel and increase the associated index """
  311. last_message = self.last_message_sent if direction is ISPCommandDirection.TX else self.last_message_received
  312. index = (last_message.index + 1) if last_message else 0
  313. new_index, message = self.__read_message__(index)
  314. if message:
  315. if last_message and last_message == message:
  316. return
  317.  
  318. last_message = message
  319. if direction is ISPCommandDirection.TX:
  320. self.last_message_sent = last_message
  321. else:
  322. self.last_message_received = last_message
  323. return message
  324.  
  325. def dump(self):
  326. """ Dumps the content of the channel """
  327. s = f"[{self.name}] Channel messages: \n"
  328. for index in range(self.number_of_entries):
  329. _, message = self.__read_message__(index)
  330. if (message):
  331. # if (message.arg0 == 0x1813140):
  332. if ((message.arg0 & 0xffff0ff) == 0x1813040):
  333. # BUF H2T COMMAND: [0x1813140, 0x280, 0x30000000]
  334. if (message.arg2 >= 0x10000000):
  335. pass
  336. #contents = self.tracer.dart.ioread(0, message.arg0, 0x200)
  337. #chexdu
  338. #print("BUF H2T COMMAND:" + str(message) + "\n")
  339. # 00000001 00000000 00000010 00000000 056a8000 00000000 00000000 00000000
  340. #iova = self.tracer.dart.ioread(0, message.arg0 + 0x10, 0x4)
  341. #iova = struct.unpack("<l", iova)[0]
  342. #d = self.tracer.dart.ioread(0, iova & ~3, 0x200)
  343. #chexdump32(d)
  344. else: # IO COMMAND
  345. contents = self.tracer.dart.ioread(0, message.arg0, 0x10)
  346. opcode = struct.unpack("<l", contents[0x4:0x8])[0]
  347. t = "IO COMMAND: [0x%x, 0x%x, 0x%x] OPCODE: 0x%04x" % (message.arg0, message.arg1, message.arg2, opcode)
  348. if (opcode in opcode_dict):
  349. name = opcode_dict[opcode]
  350. else:
  351. name = "UNKNOWN"
  352. t += " [%s]" % (name)
  353. print(t)
  354. elif (message.arg0 == 0x1813141):
  355. pass
  356. else:
  357. s = s + "\t" + str(message) + "\n"
  358. self.table.log(s)
  359.  
  360. def __convert2command__(self, message, direction):
  361. """ Converts a channel message into a command """
  362. if self.name == "TERMINAL":
  363. return ISPTerminalCommand(self, message, direction)
  364. elif self.name == "IO" or self.name == "DEBUG":
  365. return ISPIOCommand(self, message, direction)
  366. elif self.name == "SHAREDMALLOC":
  367. return ISPSharedMallocCommand(self, message, direction)
  368. elif self.name == "BUF_T2H":
  369. return ISPT2HBufferCommand(self, message, direction)
  370. elif self.name == "BUF_H2T":
  371. return ISPH2TBufferCommand(self, message, direction)
  372. elif self.name == "IO_T2H":
  373. return ISPT2HIOCommand(self, message, direction)
  374. else:
  375. return ISPCommand(self, message, direction)
  376.  
  377. def __read_message__(self, index):
  378. message_data = self.__read_by_index__(index)
  379. message = ISPChannelMessage(index, message_data)
  380. if message.valid():
  381. index += 1
  382. if index >= self.number_of_entries:
  383. index = 0
  384. return index, message
  385. return 0, None
  386.  
  387. def __read_by_index__(self, index):
  388. return self.table.ioread(self.address + (self.entry_size * index), self.entry_size)
  389.  
  390. def __str__(self):
  391. return f"[CH - {str(self.name)}] (src = {self.source!s}, type = {self.type!s}, size = {self.number_of_entries!s}, iova = {hex(self.address)!s})"
  392.  
  393. class ISPTerminalChannel(ISPChannel):
  394. """ Special channel implementation for TERMINAL channel
  395. Addresses of log buffers are removed from memory after MacOS processes them,
  396. hence we want to be a little bit ahead of MacOS and fetch all entries if
  397. possible.
  398. """
  399. def __init__(self, table, name, _type, source, number_of_entries, address):
  400. super().__init__(table, name, _type, source, number_of_entries, address)
  401. self.last_index = 0
  402.  
  403. def get_commands(self, direction):
  404. """ Gets a command from the channel"""
  405. commands = []
  406. for i in range(self.number_of_entries):
  407. index = (self.last_index + i) % self.number_of_entries
  408. _, message = self.__read_message__(index)
  409. if message and message.valid():
  410. command = self.__convert2command__(message, ISPCommandDirection.RX)
  411. if command:
  412. commands.append(command)
  413. else:
  414. self.last_index = index
  415. break
  416. return commands
  417.  
  418. class ISPChannelMessage:
  419. """ A class used to represent IPC channel message or entry
  420.  
  421. Each entry is 64 bytes, however only 24 bytes seems to be used. These 24
  422. bytes are divided in three qwords (8-bytes).
  423. """
  424.  
  425. def __init__(self, index, data):
  426. self.index = index
  427. self.data = data
  428. idx = 0
  429. for arg in struct.unpack('<8q', self.data):
  430. setattr(self, f"arg{idx}", arg)
  431. idx += 1
  432.  
  433. def valid(self):
  434. """ Checks if a message seems to be valid
  435.  
  436. So far I have observed that invalid messages or empty slots
  437. are usually marked as 0x1 (or 0x3 in case of TERMINAL msgs)
  438. """
  439. return (self.arg0 is not 0x1) and (self.arg0 is not 0x3)
  440.  
  441. def __str__(self):
  442. s = "ISP Message: {"
  443. idx = 0
  444. for arg in struct.unpack('<8q', self.data):
  445. s = s + f"Arg{idx}: {hex(arg)}, "
  446. idx = idx + 1
  447. s = s + "}"
  448. return s
  449.  
  450. def __eq__(self, other):
  451. return self.data == other.data
  452.  
  453. class ISP_REVISION(Register32):
  454. REVISION = 15, 0
  455.  
  456. class ISP_PMU(Register32):
  457. STATUS = 7, 0
  458. OTHER = 63, 8
  459.  
  460. class ISP_PMU_SPECIAL_STATUS(Register32):
  461. STATUS = 7, 0
  462. OTHER = 63, 8
  463.  
  464. class ISPRegs(RegMap):
  465. ISP_CPU_CONTROL = 0x0000, Register32
  466. ISP_CPU_STATUS = 0x0004, Register32
  467. ISP_REVISION = 0x1800000, ISP_REVISION
  468. ISP_POWER_UNKNOWN = 0x20e0080, Register32
  469. ISP_IRQ_INTERRUPT = 0x2104000, Register32
  470. ISP_IRQ_ENABLE = 0x2104004, Register32
  471. ISP_SENSOR_REF_CLOCK = irange(0x2104190, 3, 4), Register32
  472. ISP_GPR0 = 0x2104170, Register32
  473. ISP_GPR1 = 0x2104174, Register32
  474. ISP_GPR2 = 0x2104178, Register32
  475. ISP_GPR3 = 0x210417c, Register32
  476. ISP_GPR4 = 0x2104180, Register32
  477. ISP_GPR5 = 0x2104184, Register32
  478. ISP_GPR6 = 0x2104188, Register32
  479. ISP_GPR7 = 0x210418c, Register32
  480.  
  481. ISP_IRQ_DOORBELL = 0x21043f0, Register32
  482. ISP_IRQ_ACK = 0x21043fc, Register32
  483.  
  484. ISP_SMBUS_REG_MTXFIFO = irange(0x2110000, 4, 0x1000), Register32
  485. ISP_SMBUS_REG_MRXFIFO = irange(0x2110004, 4, 0x1000), Register32
  486. ISP_SMBUS_REG_UNK_1 = irange(0x2110008, 4, 0x1000), Register32
  487. ISP_SMBUS_REG_UNK_2 = irange(0x211000c, 4, 0x1000), Register32
  488. ISP_SMBUS_REG_UNK_3 = irange(0x2110010, 4, 0x1000), Register32
  489. ISP_SMBUS_REG_SMSTA = irange(0x2110014, 4, 0x1000), Register32
  490. ISP_SMBUS_REG_UNK_4 = irange(0x2110018, 4, 0x1000), Register32
  491. ISP_SMBUS_REG_CTL = irange(0x211001c, 4, 0x1000), Register32
  492. ISP_SMBUS_REG_UNK_5 = irange(0x2110020, 4, 0x1000), Register32
  493. ISP_SMBUS_REG_UNK_6 = irange(0x2110024, 4, 0x1000), Register32
  494. ISP_SMBUS_REG_REV = irange(0x2110028, 4, 0x1000), Register32
  495. ISP_SMBUS_REG_UNK_7 = irange(0x211002c, 4, 0x1000), Register32
  496. ISP_SMBUS_REG_UNK_8 = irange(0x2110030, 4, 0x1000), Register32
  497. ISP_SMBUS_REG_UNK_9 = irange(0x2110034, 4, 0x1000), Register32
  498. ISP_SMBUS_REG_UNK_A = irange(0x2110038, 4, 0x1000), Register32
  499. ISP_SMBUS_REG_UNK_B = irange(0x211003c, 4, 0x1000), Register32
  500.  
  501. ISP_DPE_REG_UNK1 = 0x2504000, Register32
  502. ISP_DPE_REG_UNK2 = 0x2508000, Register32
  503.  
  504. ISP_CPU_BUFFER = 0x1050000, Register32
  505.  
  506. ISP_SPMI0_REGISTER_BASE = 0x2900000, Register32
  507. ISP_SPMI1_REGISTER_BASE = 0x2920000, Register32
  508. ISP_SPMI2_REGISTER_BASE = 0x2940000, Register32
  509.  
  510. class PSReg(RegMap):
  511. PMU_UNKNOWN0 = 0x4000, ISP_PMU
  512. PMU_UNKNOWN1 = 0x4008, ISP_PMU
  513. PMU_UNKNOWN2 = 0x4010, ISP_PMU
  514. PMU_UNKNOWN3 = 0x4018, ISP_PMU
  515. PMU_UNKNOWN4 = 0x4020, ISP_PMU
  516. PMU_UNKNOWN5 = 0x4028, ISP_PMU
  517. PMU_UNKNOWN6 = 0x4030, ISP_PMU
  518. PMU_UNKNOWN7 = 0x4038, ISP_PMU
  519. PMU_UNKNOWN8 = 0x4040, ISP_PMU
  520. PMU_UNKNOWN9 = 0x4048, ISP_PMU
  521. PMU_UNKNOWNA = 0x4050, ISP_PMU
  522. PMU_UNKNOWNB = 0x4058, ISP_PMU
  523. PMU_SPECIAL_STATUS = 0x4060, ISP_PMU_SPECIAL_STATUS
  524. CLOCK_TICK_LOW = 0x34004, Register32
  525. CLOCK_TICK_HIGH = 0x34008, Register32
  526. RT_BANDWIDTH_SCRATCH1 = 0x38014, Register32
  527. RT_BANDWIDTH_SCRATCH2 = 0x38018, Register32
  528.  
  529. class SPMIReg(RegMap):
  530. SPMI_UNKNOWN0 = 0x28, Register32
  531. SPMI_UNKNOWN1 = 0x40, Register32
  532. SPMI_UNKNOWN2 = 0x90, Register32
  533. SPMI_UNKNOWN3 = 0x80a0, Register32
  534. SPMI_UNKNOWN4 = 0x80a4, Register32
  535.  
Add Comment
Please, Sign In to add comment