edsk.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # greaseweazle/image/edsk.py
  2. #
  3. # Some of the code here is heavily inspired by Simon Owen's SAMdisk:
  4. # https://simonowen.com/samdisk/
  5. #
  6. # Written & released by Keir Fraser <keir.xen@gmail.com>
  7. #
  8. # This is free and unencumbered software released into the public domain.
  9. # See the file COPYING for more details, or visit <http://unlicense.org>.
  10. import binascii, math, struct
  11. import itertools as it
  12. from bitarray import bitarray
  13. from greaseweazle import error
  14. from greaseweazle.codec.ibm import mfm
  15. from greaseweazle.track import MasterTrack, RawTrack
  16. from .image import Image
  17. class SR1:
  18. SUCCESS = 0x00
  19. CANNOT_FIND_ID_ADDRESS = 0x01
  20. WRITE_PROTECT_DETECTED = 0x02
  21. CANNOT_FIND_SECTOR_ID = 0x04
  22. RESERVED1 = 0x08
  23. OVERRUN = 0x10
  24. CRC_ERROR = 0x20
  25. RESERVED2 = 0x40
  26. END_OF_CYLINDER = 0x80
  27. class SR2:
  28. SUCCESS = 0x00
  29. MISSING_ADDRESS_MARK = 0x01
  30. BAD_CYLINDER = 0x02
  31. SCAN_COMMAND_FAILED = 0x04
  32. SCAN_COMMAND_EQUAL = 0x08
  33. WRONG_CYLINDER_DETECTED = 0x10
  34. CRC_ERROR_IN_SECTOR_DATA = 0x20
  35. SECTOR_WITH_DELETED_DATA = 0x40
  36. RESERVED = 0x80
  37. class SectorErrors:
  38. def __init__(self, sr1, sr2):
  39. self.id_crc_error = (sr1 & SR1.CRC_ERROR) != 0
  40. self.data_not_found = (sr2 & SR2.MISSING_ADDRESS_MARK) != 0
  41. self.data_crc_error = (sr2 & SR2.CRC_ERROR_IN_SECTOR_DATA) != 0
  42. self.deleted_dam = (sr2 & SR2.SECTOR_WITH_DELETED_DATA) != 0
  43. if self.data_crc_error:
  44. # uPD765 sets both id and data flags for data CRC errors
  45. self.id_crc_error = False
  46. if (# normal data
  47. (sr1 == SR1.SUCCESS and sr2 == SR2.SUCCESS) or
  48. # deleted data
  49. (sr1 == SR1.SUCCESS and sr2 == SR2.SECTOR_WITH_DELETED_DATA) or
  50. # end of track
  51. (sr1 == SR1.END_OF_CYLINDER and sr2 == SR2.SUCCESS) or
  52. # id crc error
  53. (sr1 == SR1.CRC_ERROR and sr2 == SR2.SUCCESS) or
  54. # normal data crc error
  55. (sr1 == SR1.CRC_ERROR and sr2 == SR2.CRC_ERROR_IN_SECTOR_DATA) or
  56. # deleted data crc error
  57. (sr1 == SR1.CRC_ERROR and sr2 == (SR2.CRC_ERROR_IN_SECTOR_DATA |
  58. SR2.SECTOR_WITH_DELETED_DATA)) or
  59. # data field missing (some FDCs set AM in ST1)
  60. (sr1 == SR1.CANNOT_FIND_ID_ADDRESS
  61. and sr2 == SR2.MISSING_ADDRESS_MARK) or
  62. # data field missing (some FDCs don't)
  63. (sr1 == SR1.SUCCESS and sr2 == SR2.MISSING_ADDRESS_MARK) or
  64. # CHRN mismatch
  65. (sr1 == SR1.CANNOT_FIND_SECTOR_ID and sr2 == SR2.SUCCESS) or
  66. # CHRN mismatch, including wrong cylinder
  67. (sr1 == SR1.CANNOT_FIND_SECTOR_ID
  68. and sr2 == SR2.WRONG_CYLINDER_DETECTED)):
  69. pass
  70. else:
  71. print('Unusual status flags (ST1=%02X ST2=%02X)' % (sr1, sr2))
  72. class EDSKTrack:
  73. gap_presync = 12
  74. gap_4a = 80 # Post-Index
  75. gap_1 = 50 # Post-IAM
  76. gap_2 = 22 # Post-IDAM
  77. gapbyte = 0x4e
  78. def __init__(self):
  79. self.time_per_rev = 0.2
  80. self.clock = 2e-6
  81. self.bits, self.weak = [], []
  82. def raw_track(self):
  83. track = MasterTrack(
  84. bits = self.bits,
  85. time_per_rev = self.time_per_rev,
  86. weak = self.weak)
  87. track.verify = self
  88. track.verify_revs = 1
  89. return track
  90. def _find_sync(self, bits, sync, start):
  91. for offs in bits.itersearch(sync):
  92. if offs >= start:
  93. return offs
  94. return None
  95. def verify_track(self, flux):
  96. flux.cue_at_index()
  97. raw = RawTrack(clock = self.clock, data = flux)
  98. bits, _ = raw.get_all_data()
  99. weak_iter = it.chain(self.weak, [(self.verify_len+1,1)])
  100. weak = next(weak_iter)
  101. # Start checking from the IAM sync
  102. dump_start = self._find_sync(bits, mfm.iam_sync, 0)
  103. self_start = self._find_sync(self.bits, mfm.iam_sync, 0)
  104. # Include the IAM pre-sync header
  105. if dump_start is None:
  106. return False
  107. dump_start -= self.gap_presync * 16
  108. self_start -= self.gap_presync * 16
  109. while self_start is not None and dump_start is not None:
  110. # Find the weak areas immediately before and after the current
  111. # region to be checked.
  112. s,n = None,None
  113. while self_start > weak[0]:
  114. s,n = weak
  115. weak = next(weak_iter)
  116. # If there is a weak area preceding us, move the start point to
  117. # immediately follow the weak area.
  118. if s is not None:
  119. delta = self_start - (s + n + 16)
  120. self_start -= delta
  121. dump_start -= delta
  122. # Truncate the region at the next weak area, or the last sector.
  123. self_end = max(self_start, min(weak[0], self.verify_len+1))
  124. dump_end = dump_start + self_end - self_start
  125. # Extract the corresponding areas from the pristine track and
  126. # from the dump, and check that they match.
  127. if bits[dump_start:dump_end] != self.bits[self_start:self_end]:
  128. return False
  129. # Find the next A1A1A1 sync pattern
  130. dump_start = self._find_sync(bits, mfm.sync, dump_end)
  131. self_start = self._find_sync(self.bits, mfm.sync, self_end)
  132. # Did we verify all regions in the pristine track?
  133. return self_start is None
  134. class EDSK(Image):
  135. read_only = True
  136. default_format = 'ibm.mfm'
  137. def __init__(self):
  138. self.to_track = dict()
  139. # Currently only finds one weak range.
  140. @staticmethod
  141. def find_weak_ranges(dat, size):
  142. orig = dat[:size]
  143. s, e = size, 0
  144. for i in range(1, len(dat)//size):
  145. diff = [x^y for x, y in zip(orig, dat[size*i:size*(i+1)])]
  146. weak = [idx for idx, val in enumerate(diff) if val != 0]
  147. if weak:
  148. s, e = min(s, weak[0]), max(e, weak[-1])
  149. return [(s,e-s+1)] if s <= e else []
  150. @classmethod
  151. def from_file(cls, name):
  152. with open(name, "rb") as f:
  153. dat = f.read()
  154. edsk = cls()
  155. sig, creator, ncyls, nsides, track_sz = struct.unpack(
  156. '<34s14s2BH', dat[:52])
  157. if sig[:8] == b'MV - CPC':
  158. extended = False
  159. elif sig[:16] == b'EXTENDED CPC DSK':
  160. extended = True
  161. else:
  162. raise error.Fatal('Unrecognised CPC DSK file: bad signature')
  163. if extended:
  164. track_sizes = list(dat[52:52+ncyls*nsides])
  165. track_sizes = list(map(lambda x: x*256, track_sizes))
  166. else:
  167. track_sizes = [track_sz] * (ncyls * nsides)
  168. o = 256 # skip disk header and track-size table
  169. for track_size in track_sizes:
  170. if track_size == 0:
  171. continue
  172. sig, cyl, head, sec_sz, nsecs, gap_3, filler = struct.unpack(
  173. '<12s4x2B2x4B', dat[o:o+24])
  174. error.check(sig == b'Track-Info\r\n',
  175. 'EDSK: Missing track header')
  176. error.check((cyl, head) not in edsk.to_track,
  177. 'EDSK: Track specified twice')
  178. while True:
  179. track = EDSKTrack()
  180. t = bytes()
  181. # Post-index gap
  182. t += mfm.encode(bytes([track.gapbyte] * track.gap_4a))
  183. # IAM
  184. t += mfm.encode(bytes(track.gap_presync))
  185. t += mfm.iam_sync_bytes
  186. t += mfm.encode(bytes([mfm.IBM_MFM.IAM]))
  187. t += mfm.encode(bytes([track.gapbyte] * track.gap_1))
  188. secs = dat[o+24:o+24+8*nsecs]
  189. data_pos = o + 256 # skip track header and sector-info table
  190. while secs:
  191. c, h, r, n, stat1, stat2, data_size = struct.unpack(
  192. '<6BH', secs[:8])
  193. secs = secs[8:]
  194. native_size = mfm.sec_sz(n)
  195. weak = []
  196. errs = SectorErrors(stat1, stat2)
  197. num_copies = 0 if errs.data_not_found else 1
  198. if not extended:
  199. data_size = mfm.sec_sz(sec_sz)
  200. sec_data = dat[data_pos:data_pos+data_size]
  201. data_pos += data_size
  202. if (extended
  203. and data_size > native_size
  204. and errs.data_crc_error
  205. and (data_size % native_size == 0
  206. or data_size == 49152)):
  207. num_copies = (3 if data_size == 49152
  208. else data_size // native_size)
  209. data_size //= num_copies
  210. weak = cls().find_weak_ranges(sec_data, data_size)
  211. sec_data = sec_data[:data_size]
  212. if data_size < native_size:
  213. # Pad short data
  214. sec_data += bytes(native_size - data_size)
  215. # IDAM
  216. t += mfm.encode(bytes(track.gap_presync))
  217. t += mfm.sync_bytes
  218. am = bytes([0xa1, 0xa1, 0xa1, mfm.IBM_MFM.IDAM,
  219. c, h, r, n])
  220. crc = mfm.crc16.new(am).crcValue
  221. if errs.id_crc_error:
  222. crc ^= 0x5555
  223. am += struct.pack('>H', crc)
  224. t += mfm.encode(am[3:])
  225. t += mfm.encode(bytes([track.gapbyte] * track.gap_2))
  226. # DAM
  227. if errs.id_crc_error or errs.data_not_found:
  228. continue
  229. t += mfm.encode(bytes(track.gap_presync))
  230. t += mfm.sync_bytes
  231. track.weak += [((s+len(t)//2+4)*16, n*16) for s,n in weak]
  232. dmark = (mfm.IBM_MFM.DDAM if errs.deleted_dam
  233. else mfm.IBM_MFM.DAM)
  234. am = bytes([0xa1, 0xa1, 0xa1, dmark]) + sec_data
  235. if data_size > native_size:
  236. # Long data includes CRC and GAP
  237. if (sec_data[-13] != 0
  238. and all([v==0 for v in sec_data[-12:]])):
  239. # Includes next pre-sync: Clip it.
  240. am = am[:-12]
  241. t += mfm.encode(am[3:])
  242. continue
  243. crc = mfm.crc16.new(am).crcValue
  244. if errs.data_crc_error:
  245. crc ^= 0x5555
  246. am += struct.pack('>H', crc)
  247. t += mfm.encode(am[3:])
  248. t += mfm.encode(bytes([track.gapbyte] * gap_3))
  249. # Some EDSK images have bogus GAP3 values. If the track is too
  250. # long to comfortably fit in 300rpm at double density, shrink
  251. # GAP3 as far as necessary.
  252. tracklen = int((track.time_per_rev / track.clock) / 16)
  253. overhang = int(len(t)//2 - tracklen*0.99)
  254. if overhang <= 0:
  255. break
  256. new_gap_3 = gap_3 - math.ceil(overhang / nsecs)
  257. error.check(new_gap_3 >= 0,
  258. 'EDSK: Track %d.%d is too long '
  259. '(%d bits @ GAP3=%d; %d bits @ GAP3=0)'
  260. % (cyl, head, len(t)*8, gap_3,
  261. (len(t)//2-gap_3*nsecs)*16))
  262. #print('EDSK: GAP3 reduced (%d -> %d)' % (gap_3, new_gap_3))
  263. gap_3 = new_gap_3
  264. # Pre-index gap
  265. track.verify_len = len(t)*8
  266. gap = tracklen - len(t)//2
  267. t += mfm.encode(bytes([track.gapbyte] * gap))
  268. track.bits = bitarray(endian='big')
  269. track.bits.frombytes(mfm.mfm_encode(t))
  270. edsk.to_track[cyl,head] = track
  271. o += track_size
  272. return edsk
  273. def get_track(self, cyl, side):
  274. if (cyl,side) not in self.to_track:
  275. return None
  276. return self.to_track[cyl,side].raw_track()
  277. # Local variables:
  278. # python-indent: 4
  279. # End: