Merge branch 'master' of ssh://webhost.codesrc.com/home/michael/projects/SCSI2SD
[SCSI2SD.git] / software / SCSI2SD / src / scsi.c
1 //      Copyright (C) 2014 Michael McMaster <michael@codesrc.com>\r
2 //\r
3 //      This file is part of SCSI2SD.\r
4 //\r
5 //      SCSI2SD is free software: you can redistribute it and/or modify\r
6 //      it under the terms of the GNU General Public License as published by\r
7 //      the Free Software Foundation, either version 3 of the License, or\r
8 //      (at your option) any later version.\r
9 //\r
10 //      SCSI2SD is distributed in the hope that it will be useful,\r
11 //      but WITHOUT ANY WARRANTY; without even the implied warranty of\r
12 //      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
13 //      GNU General Public License for more details.\r
14 //\r
15 //      You should have received a copy of the GNU General Public License\r
16 //      along with SCSI2SD.  If not, see <http://www.gnu.org/licenses/>.\r
17 #pragma GCC push_options\r
18 #pragma GCC optimize("-flto")\r
19 \r
20 #include "device.h"\r
21 #include "scsi.h"\r
22 #include "scsiPhy.h"\r
23 #include "config.h"\r
24 #include "bits.h"\r
25 #include "diagnostic.h"\r
26 #include "disk.h"\r
27 #include "inquiry.h"\r
28 #include "led.h"\r
29 #include "mode.h"\r
30 #include "disk.h"\r
31 #include "time.h"\r
32 #include "cdrom.h"\r
33 #include "debug.h"\r
34 \r
35 #include <string.h>\r
36 \r
37 // Global SCSI device state.\r
38 ScsiDevice scsiDev;\r
39 \r
40 static void enter_SelectionPhase(void);\r
41 static void process_SelectionPhase(void);\r
42 static void enter_BusFree(void);\r
43 static void enter_MessageIn(uint8 message);\r
44 static void enter_Status(uint8 status);\r
45 static void enter_DataIn(int len);\r
46 static void process_DataIn(void);\r
47 static void process_DataOut(void);\r
48 static void process_Command(void);\r
49 \r
50 static void doReserveRelease(void);\r
51 \r
52 static void enter_BusFree()\r
53 {\r
54         // This delay probably isn't needed for most SCSI hosts, but it won't\r
55         // hurt either. It's possible some of the samplers needed this delay.\r
56         if (scsiDev.compatMode < COMPAT_SCSI2)\r
57         {\r
58                 CyDelayUs(2);\r
59         }\r
60 \r
61         if (scsiDev.status != GOOD && isDebugEnabled())\r
62         {\r
63                 // We want to capture debug information for failure cases.\r
64                 CyDelay(64);\r
65         }\r
66 \r
67         SCSI_ClearPin(SCSI_Out_BSY);\r
68         // We now have a Bus Clear Delay of 800ns to release remaining signals.\r
69         SCSI_CTL_PHASE_Write(0);\r
70 \r
71         // Wait for the initiator to cease driving signals\r
72         // Bus settle delay + bus clear delay = 1200ns\r
73         CyDelayUs(2);\r
74 \r
75         ledOff();\r
76         scsiDev.phase = BUS_FREE;\r
77 }\r
78 \r
79 static void enter_MessageIn(uint8 message)\r
80 {\r
81         scsiDev.msgIn = message;\r
82         scsiDev.phase = MESSAGE_IN;\r
83 }\r
84 \r
85 void process_MessageIn()\r
86 {\r
87         scsiEnterPhase(MESSAGE_IN);\r
88         scsiWriteByte(scsiDev.msgIn);\r
89 \r
90         if (unlikely(scsiDev.atnFlag))\r
91         {\r
92                 // If there was a parity error, we go\r
93                 // back to MESSAGE_OUT first, get out parity error message, then come\r
94                 // back here.\r
95         }\r
96         else if ((scsiDev.msgIn == MSG_LINKED_COMMAND_COMPLETE) ||\r
97                 (scsiDev.msgIn == MSG_LINKED_COMMAND_COMPLETE_WITH_FLAG))\r
98         {\r
99                 // Go back to the command phase and start again.\r
100                 scsiDev.phase = COMMAND;\r
101                 scsiDev.parityError = 0;\r
102                 scsiDev.dataPtr = 0;\r
103                 scsiDev.savedDataPtr = 0;\r
104                 scsiDev.dataLen = 0;\r
105                 scsiDev.status = GOOD;\r
106                 transfer.blocks = 0;\r
107                 transfer.currentBlock = 0;\r
108         }\r
109         else /*if (scsiDev.msgIn == MSG_COMMAND_COMPLETE)*/\r
110         {\r
111                 enter_BusFree();\r
112         }\r
113 }\r
114 \r
115 static void messageReject()\r
116 {\r
117         scsiEnterPhase(MESSAGE_IN);\r
118         scsiWriteByte(MSG_REJECT);\r
119 }\r
120 \r
121 static void enter_Status(uint8 status)\r
122 {\r
123         scsiDev.status = status;\r
124         scsiDev.phase = STATUS;\r
125 \r
126         scsiDev.lastStatus = scsiDev.status;\r
127         scsiDev.lastSense = scsiDev.target->sense.code;\r
128         scsiDev.lastSenseASC = scsiDev.target->sense.asc;\r
129 }\r
130 \r
131 void process_Status()\r
132 {\r
133         scsiEnterPhase(STATUS);\r
134 \r
135         uint8 message;\r
136 \r
137         uint8 control = scsiDev.cdb[scsiDev.cdbLen - 1];\r
138         if ((scsiDev.status == GOOD) && (control & 0x01))\r
139         {\r
140                 // Linked command.\r
141                 scsiDev.status = INTERMEDIATE;\r
142                 if (control & 0x02)\r
143                 {\r
144                         message = MSG_LINKED_COMMAND_COMPLETE_WITH_FLAG;\r
145                 }\r
146                 else\r
147                 {\r
148                         message = MSG_LINKED_COMMAND_COMPLETE;\r
149                 }\r
150         }\r
151         else\r
152         {\r
153                 message = MSG_COMMAND_COMPLETE;\r
154         }\r
155         scsiWriteByte(scsiDev.status);\r
156 \r
157         scsiDev.lastStatus = scsiDev.status;\r
158         scsiDev.lastSense = scsiDev.target->sense.code;\r
159         scsiDev.lastSenseASC = scsiDev.target->sense.asc;\r
160 \r
161 \r
162         // Command Complete occurs AFTER a valid status has been\r
163         // sent. then we go bus-free.\r
164         enter_MessageIn(message);\r
165 }\r
166 \r
167 static void enter_DataIn(int len)\r
168 {\r
169         scsiDev.dataLen = len;\r
170         scsiDev.phase = DATA_IN;\r
171 }\r
172 \r
173 static void process_DataIn()\r
174 {\r
175         uint32 len;\r
176 \r
177         if (scsiDev.dataLen > sizeof(scsiDev.data))\r
178         {\r
179                 scsiDev.dataLen = sizeof(scsiDev.data);\r
180         }\r
181 \r
182         len = scsiDev.dataLen - scsiDev.dataPtr;\r
183         if (len > 0)\r
184         {\r
185                 scsiEnterPhase(DATA_IN);\r
186                 scsiWrite(scsiDev.data + scsiDev.dataPtr, len);\r
187                 scsiDev.dataPtr += len;\r
188         }\r
189 \r
190         if ((scsiDev.dataPtr >= scsiDev.dataLen) &&\r
191                 (transfer.currentBlock == transfer.blocks))\r
192         {\r
193                 enter_Status(GOOD);\r
194         }\r
195 }\r
196 \r
197 static void process_DataOut()\r
198 {\r
199         uint32 len;\r
200 \r
201         if (scsiDev.dataLen > sizeof(scsiDev.data))\r
202         {\r
203                 scsiDev.dataLen = sizeof(scsiDev.data);\r
204         }\r
205 \r
206         scsiDev.parityError = 0;\r
207         len = scsiDev.dataLen - scsiDev.dataPtr;\r
208         if (len > 0)\r
209         {\r
210                 scsiEnterPhase(DATA_OUT);\r
211 \r
212                 scsiRead(scsiDev.data + scsiDev.dataPtr, len);\r
213                 scsiDev.dataPtr += len;\r
214 \r
215                 if (scsiDev.parityError &&\r
216                         (scsiDev.target->cfg->flags & CONFIG_ENABLE_PARITY) &&\r
217                         (scsiDev.compatMode >= COMPAT_SCSI2))\r
218                 {\r
219                         scsiDev.target->sense.code = ABORTED_COMMAND;\r
220                         scsiDev.target->sense.asc = SCSI_PARITY_ERROR;\r
221                         enter_Status(CHECK_CONDITION);\r
222                 }\r
223         }\r
224 \r
225         if ((scsiDev.dataPtr >= scsiDev.dataLen) &&\r
226                 (transfer.currentBlock == transfer.blocks))\r
227         {\r
228                 if (scsiDev.postDataOutHook != NULL)\r
229                 {\r
230                         scsiDev.postDataOutHook();\r
231                 }\r
232                 else\r
233                 {\r
234                         enter_Status(GOOD);\r
235                 }\r
236         }\r
237 }\r
238 \r
239 static const uint8 CmdGroupBytes[8] = {6, 10, 10, 6, 6, 12, 6, 6};\r
240 static void process_Command()\r
241 {\r
242         int group;\r
243         uint8 command;\r
244         uint8 control;\r
245 \r
246         scsiEnterPhase(COMMAND);\r
247         scsiDev.parityError = 0;\r
248 \r
249         memset(scsiDev.cdb, 0, sizeof(scsiDev.cdb));\r
250         scsiDev.cdb[0] = scsiReadByte();\r
251 \r
252         group = scsiDev.cdb[0] >> 5;\r
253         scsiDev.cdbLen = CmdGroupBytes[group];\r
254         scsiRead(scsiDev.cdb + 1, scsiDev.cdbLen - 1);\r
255 \r
256         command = scsiDev.cdb[0];\r
257 \r
258         // Prefer LUN's set by IDENTIFY messages for newer hosts.\r
259         if (scsiDev.lun < 0)\r
260         {\r
261                 scsiDev.lun = scsiDev.cdb[1] >> 5;\r
262         }\r
263 \r
264         control = scsiDev.cdb[scsiDev.cdbLen - 1];\r
265 \r
266         scsiDev.cmdCount++;\r
267         TargetConfig* cfg = scsiDev.target->cfg;\r
268 \r
269         if (unlikely(scsiDev.resetFlag))\r
270         {\r
271                 // Don't log bogus commands\r
272                 scsiDev.cmdCount--;\r
273                 memset(scsiDev.cdb, 0xff, sizeof(scsiDev.cdb));\r
274                 return;\r
275         }\r
276         else if (scsiDev.parityError &&\r
277                 (cfg->flags & CONFIG_ENABLE_PARITY) &&\r
278                 (scsiDev.compatMode >= COMPAT_SCSI2))\r
279         {\r
280                 scsiDev.target->sense.code = ABORTED_COMMAND;\r
281                 scsiDev.target->sense.asc = SCSI_PARITY_ERROR;\r
282                 enter_Status(CHECK_CONDITION);\r
283         }\r
284         else if ((control & 0x02) && ((control & 0x01) == 0))\r
285         {\r
286                 // FLAG set without LINK flag.\r
287                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
288                 scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;\r
289                 enter_Status(CHECK_CONDITION);\r
290         }\r
291         else if (command == 0x12)\r
292         {\r
293                 scsiInquiry();\r
294         }\r
295         else if (command == 0x03)\r
296         {\r
297                 // REQUEST SENSE\r
298                 uint32 allocLength = scsiDev.cdb[4];\r
299 \r
300                 // As specified by the SASI and SCSI1 standard.\r
301                 // Newer initiators won't be specifying 0 anyway.\r
302                 if (allocLength == 0) allocLength = 4;\r
303 \r
304                 memset(scsiDev.data, 0, 256); // Max possible alloc length\r
305                 scsiDev.data[0] = 0xF0;\r
306                 scsiDev.data[2] = scsiDev.target->sense.code & 0x0F;\r
307 \r
308                 scsiDev.data[3] = transfer.lba >> 24;\r
309                 scsiDev.data[4] = transfer.lba >> 16;\r
310                 scsiDev.data[5] = transfer.lba >> 8;\r
311                 scsiDev.data[6] = transfer.lba;\r
312 \r
313                 // Additional bytes if there are errors to report\r
314                 scsiDev.data[7] = 10; // additional length\r
315                 scsiDev.data[12] = scsiDev.target->sense.asc >> 8;\r
316                 scsiDev.data[13] = scsiDev.target->sense.asc;\r
317 \r
318                 // Silently truncate results. SCSI-2 spec 8.2.14.\r
319                 enter_DataIn(allocLength);\r
320 \r
321                 // This is a good time to clear out old sense information.\r
322                 scsiDev.target->sense.code = NO_SENSE;\r
323                 scsiDev.target->sense.asc = NO_ADDITIONAL_SENSE_INFORMATION;\r
324         }\r
325         // Some old SCSI drivers do NOT properly support\r
326         // unitAttention. eg. the Mac Plus would trigger a SCSI reset\r
327         // on receiving the unit attention response on boot, thus\r
328         // triggering another unit attention condition.\r
329         else if (scsiDev.target->unitAttention &&\r
330                 (cfg->flags & CONFIG_ENABLE_UNIT_ATTENTION))\r
331         {\r
332                 scsiDev.target->sense.code = UNIT_ATTENTION;\r
333                 scsiDev.target->sense.asc = scsiDev.target->unitAttention;\r
334 \r
335                 // If initiator doesn't do REQUEST SENSE for the next command, then\r
336                 // data is lost.\r
337                 scsiDev.target->unitAttention = 0;\r
338 \r
339                 enter_Status(CHECK_CONDITION);\r
340         }\r
341         else if (scsiDev.lun)\r
342         {\r
343                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
344                 scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_SUPPORTED;\r
345                 enter_Status(CHECK_CONDITION);\r
346         }\r
347         else if (command == 0x17 || command == 0x16)\r
348         {\r
349                 doReserveRelease();\r
350         }\r
351         else if ((scsiDev.target->reservedId >= 0) &&\r
352                 (scsiDev.target->reservedId != scsiDev.initiatorId))\r
353         {\r
354                 enter_Status(CONFLICT);\r
355         }\r
356         // Handle odd device types first that may override basic read and\r
357         // write commands. Will fall-through to generic disk handling.\r
358         else if (((cfg->deviceType == CONFIG_OPTICAL) && scsiCDRomCommand()) ||\r
359                 ((cfg->deviceType == CONFIG_SEQUENTIAL) && scsiTapeCommand()) ||\r
360                 ((cfg->deviceType == CONFIG_MO) && scsiMOCommand()))\r
361         {\r
362                 // Already handled.\r
363         }\r
364         else if (scsiDiskCommand())\r
365         {\r
366                 // Already handled.\r
367                 // check for the performance-critical read/write\r
368                 // commands ASAP.\r
369         }\r
370         else if (command == 0x1C)\r
371         {\r
372                 scsiReceiveDiagnostic();\r
373         }\r
374         else if (command == 0x1D)\r
375         {\r
376                 scsiSendDiagnostic();\r
377         }\r
378         else if (command == 0x3B)\r
379         {\r
380                 scsiWriteBuffer();\r
381         }\r
382         else if (command == 0x3C)\r
383         {\r
384                 scsiReadBuffer();\r
385         }\r
386         else if (!scsiModeCommand())\r
387         {\r
388                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
389                 scsiDev.target->sense.asc = INVALID_COMMAND_OPERATION_CODE;\r
390                 enter_Status(CHECK_CONDITION);\r
391         }\r
392 \r
393         // Successful\r
394         if (scsiDev.phase == COMMAND) // No status set, and not in DATA_IN\r
395         {\r
396                 enter_Status(GOOD);\r
397         }\r
398 \r
399 }\r
400 \r
401 static void doReserveRelease()\r
402 {\r
403         int extentReservation = scsiDev.cdb[1] & 1;\r
404         int thirdPty = scsiDev.cdb[1] & 0x10;\r
405         int thirdPtyId = (scsiDev.cdb[1] >> 1) & 0x7;\r
406         uint8 command = scsiDev.cdb[0];\r
407 \r
408         int canRelease =\r
409                 (!thirdPty && (scsiDev.initiatorId == scsiDev.target->reservedId)) ||\r
410                         (thirdPty &&\r
411                                 (scsiDev.target->reserverId == scsiDev.initiatorId) &&\r
412                                 (scsiDev.target->reservedId == thirdPtyId)\r
413                         );\r
414 \r
415         if (extentReservation)\r
416         {\r
417                 // Not supported.\r
418                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
419                 scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;\r
420                 enter_Status(CHECK_CONDITION);\r
421         }\r
422         else if (command == 0x17) // release\r
423         {\r
424                 if ((scsiDev.target->reservedId < 0) || canRelease)\r
425                 {\r
426                         scsiDev.target->reservedId = -1;\r
427                         scsiDev.target->reserverId = -1;\r
428                 }\r
429                 else\r
430                 {\r
431                         enter_Status(CONFLICT);\r
432                 }\r
433         }\r
434         else // assume reserve.\r
435         {\r
436                 if ((scsiDev.target->reservedId < 0) || canRelease)\r
437                 {\r
438                         scsiDev.target->reserverId = scsiDev.initiatorId;\r
439                         if (thirdPty)\r
440                         {\r
441                                 scsiDev.target->reservedId = thirdPtyId;\r
442                         }\r
443                         else\r
444                         {\r
445                                 scsiDev.target->reservedId = scsiDev.initiatorId;\r
446                         }\r
447                 }\r
448                 else\r
449                 {\r
450                         // Already reserved by someone else!\r
451                         enter_Status(CONFLICT);\r
452                 }\r
453         }\r
454 }\r
455 \r
456 static void scsiReset()\r
457 {\r
458         scsiDev.rstCount++;\r
459         ledOff();\r
460 \r
461         scsiPhyReset();\r
462         SCSI_Out_Ctl_Write(0);\r
463 \r
464         scsiDev.parityError = 0;\r
465         scsiDev.phase = BUS_FREE;\r
466         scsiDev.atnFlag = 0;\r
467         scsiDev.resetFlag = 0;\r
468         scsiDev.lun = -1;\r
469         scsiDev.compatMode = COMPAT_UNKNOWN;\r
470 \r
471         if (scsiDev.target)\r
472         {\r
473                 if (scsiDev.target->unitAttention != POWER_ON_RESET)\r
474                 {\r
475                         scsiDev.target->unitAttention = SCSI_BUS_RESET;\r
476                 }\r
477                 scsiDev.target->reservedId = -1;\r
478                 scsiDev.target->reserverId = -1;\r
479                 scsiDev.target->sense.code = NO_SENSE;\r
480                 scsiDev.target->sense.asc = NO_ADDITIONAL_SENSE_INFORMATION;\r
481         }\r
482         scsiDev.target = NULL;\r
483         scsiDiskReset();\r
484 \r
485         scsiDev.postDataOutHook = NULL;\r
486 \r
487         // Sleep to allow the bus to settle down a bit.\r
488         // We must be ready again within the "Reset to selection time" of\r
489         // 250ms.\r
490         // There is no guarantee that the RST line will be negated by then.\r
491         // NOTE: We could be connected and powered by USB for configuration,\r
492         // in which case TERMPWR cannot be supplied, and reset will ALWAYS\r
493         // be true. Therefore, the sleep here must be slow to avoid slowing\r
494         // USB comms\r
495         CyDelay(1); // 1ms.\r
496 }\r
497 \r
498 static void enter_SelectionPhase()\r
499 {\r
500         // Ignore stale versions of this flag, but ensure we know the\r
501         // current value if the flag is still set.\r
502         scsiDev.atnFlag = 0;\r
503         scsiDev.parityError = 0;\r
504         scsiDev.dataPtr = 0;\r
505         scsiDev.savedDataPtr = 0;\r
506         scsiDev.dataLen = 0;\r
507         scsiDev.status = GOOD;\r
508         scsiDev.phase = SELECTION;\r
509         scsiDev.lun = -1;\r
510         scsiDev.discPriv = 0;\r
511 \r
512         scsiDev.initiatorId = -1;\r
513         scsiDev.target = NULL;\r
514 \r
515         transfer.blocks = 0;\r
516         transfer.currentBlock = 0;\r
517 \r
518         scsiDev.postDataOutHook = NULL;\r
519 }\r
520 \r
521 static void process_SelectionPhase()\r
522 {\r
523         if (scsiDev.compatMode < COMPAT_SCSI2)\r
524         {\r
525                 // Required for some older SCSI1 devices using a 5380 chip.\r
526                 CyDelay(1);\r
527         }\r
528 \r
529         int sel = SCSI_ReadFilt(SCSI_Filt_SEL);\r
530         int bsy = SCSI_ReadFilt(SCSI_Filt_BSY);\r
531 \r
532         // Only read these pins AFTER SEL and BSY - we don't want to catch them\r
533         // during a transition period.\r
534         uint8 mask = scsiReadDBxPins();\r
535         int maskBitCount = countBits(mask);\r
536         int goodParity = (Lookup_OddParity[mask] == SCSI_ReadPin(SCSI_In_DBP));\r
537         int atnFlag = SCSI_ReadFilt(SCSI_Filt_ATN);\r
538 \r
539         int tgtIndex;\r
540         TargetState* target = NULL;\r
541         for (tgtIndex = 0; tgtIndex < MAX_SCSI_TARGETS; ++tgtIndex)\r
542         {\r
543                 if (mask & (1 << scsiDev.targets[tgtIndex].targetId))\r
544                 {\r
545                         target = &scsiDev.targets[tgtIndex];\r
546                         break;\r
547                 }\r
548         }\r
549         if (!bsy && sel &&\r
550                 target &&\r
551                 (goodParity || !(target->cfg->flags & CONFIG_ENABLE_PARITY) || !atnFlag) &&\r
552                 likely(maskBitCount <= 2))\r
553         {\r
554                 scsiDev.target = target;\r
555 \r
556                 // Do we enter MESSAGE OUT immediately ? SCSI 1 and 2 standards says\r
557                 // move to MESSAGE OUT if ATN is true before we assert BSY.\r
558                 // The initiator should assert ATN with SEL.\r
559                 scsiDev.atnFlag = atnFlag;\r
560 \r
561                 // Unit attention breaks many older SCSI hosts. Disable it completely\r
562                 // for SCSI-1 (and older) hosts, regardless of our configured setting.\r
563                 // Enable the compatability mode also as many SASI and SCSI1\r
564                 // controllers don't generate parity bits.\r
565                 if (!scsiDev.atnFlag)\r
566                 {\r
567                         target->unitAttention = 0;\r
568                         scsiDev.compatMode = COMPAT_SCSI1;\r
569                 }\r
570                 else if (!(target->cfg->flags & CONFIG_ENABLE_SCSI2))\r
571                 {\r
572                         scsiDev.compatMode = COMPAT_SCSI1;\r
573                 }\r
574                 else if (scsiDev.compatMode == COMPAT_UNKNOWN)\r
575                 {\r
576                         scsiDev.compatMode = COMPAT_SCSI2;\r
577                 }\r
578 \r
579                 // We've been selected!\r
580                 // Assert BSY - Selection success!\r
581                 // must happen within 200us (Selection abort time) of seeing our\r
582                 // ID + SEL.\r
583                 // (Note: the initiator will be waiting the "Selection time-out delay"\r
584                 // for our BSY response, which is actually a very generous 250ms)\r
585                 SCSI_SetPin(SCSI_Out_BSY);\r
586                 ledOn();\r
587 \r
588                 scsiDev.selCount++;\r
589 \r
590                 // Wait until the end of the selection phase.\r
591                 while (likely(!scsiDev.resetFlag))\r
592                 {\r
593                         if (!SCSI_ReadFilt(SCSI_Filt_SEL))\r
594                         {\r
595                                 break;\r
596                         }\r
597                 }\r
598 \r
599                 // Save our initiator now that we're no longer in a time-critical\r
600                 // section.\r
601                 // SCSI1/SASI initiators may not set their own ID.\r
602                 {\r
603                         int i;\r
604                         uint8_t initiatorMask = mask ^ (1 << target->targetId);\r
605                         scsiDev.initiatorId = -1;\r
606                         for (i = 0; i < 8; ++i)\r
607                         {\r
608                                 if (initiatorMask & (1 << i))\r
609                                 {\r
610                                         scsiDev.initiatorId = i;\r
611                                         break;\r
612                                 }\r
613                         }\r
614                 }\r
615 \r
616                 scsiDev.phase = COMMAND;\r
617         }\r
618         else if (!sel)\r
619         {\r
620                 scsiDev.phase = BUS_BUSY;\r
621         }\r
622 }\r
623 \r
624 static void process_MessageOut()\r
625 {\r
626         scsiEnterPhase(MESSAGE_OUT);\r
627 \r
628         scsiDev.atnFlag = 0;\r
629         scsiDev.parityError = 0;\r
630         scsiDev.msgOut = scsiReadByte();\r
631         scsiDev.msgCount++;\r
632 \r
633         if (scsiDev.parityError &&\r
634                 (scsiDev.target->cfg->flags & CONFIG_ENABLE_PARITY) &&\r
635                 (scsiDev.compatMode >= COMPAT_SCSI2))\r
636         {\r
637                 // Skip the remaining message bytes, and then start the MESSAGE_OUT\r
638                 // phase again from the start. The initiator will re-send the\r
639                 // same set of messages.\r
640                 while (SCSI_ReadFilt(SCSI_Filt_ATN) && !scsiDev.resetFlag)\r
641                 {\r
642                         scsiReadByte();\r
643                 }\r
644 \r
645                 // Go-back and try the message again.\r
646                 scsiDev.atnFlag = 1;\r
647                 scsiDev.parityError = 0;\r
648         }\r
649         else if (scsiDev.msgOut == 0x00)\r
650         {\r
651                 // COMMAND COMPLETE. but why would the target be receiving this ? nfi.\r
652                 enter_BusFree();\r
653         }\r
654         else if (scsiDev.msgOut == 0x06)\r
655         {\r
656                 // ABORT\r
657                 scsiDiskReset();\r
658                 enter_BusFree();\r
659         }\r
660         else if (scsiDev.msgOut == 0x0C)\r
661         {\r
662                 // BUS DEVICE RESET\r
663 \r
664                 scsiDiskReset();\r
665 \r
666                 scsiDev.target->unitAttention = SCSI_BUS_RESET;\r
667 \r
668                 // ANY initiator can reset the reservation state via this message.\r
669                 scsiDev.target->reservedId = -1;\r
670                 scsiDev.target->reserverId = -1;\r
671                 enter_BusFree();\r
672         }\r
673         else if (scsiDev.msgOut == 0x05)\r
674         {\r
675                 // Initiate Detected Error\r
676                 // Ignore for now\r
677         }\r
678         else if (scsiDev.msgOut == 0x0F)\r
679         {\r
680                 // INITIATE RECOVERY\r
681                 // Ignore for now\r
682         }\r
683         else if (scsiDev.msgOut == 0x10)\r
684         {\r
685                 // RELEASE RECOVERY\r
686                 // Ignore for now\r
687                 enter_BusFree();\r
688         }\r
689         else if (scsiDev.msgOut == MSG_REJECT)\r
690         {\r
691                 // Message Reject\r
692                 // Oh well.\r
693                 scsiDev.resetFlag = 1;\r
694         }\r
695         else if (scsiDev.msgOut == 0x08)\r
696         {\r
697                 // NOP\r
698         }\r
699         else if (scsiDev.msgOut == 0x09)\r
700         {\r
701                 // Message Parity Error\r
702                 // Go back and re-send the last message.\r
703                 scsiDev.phase = MESSAGE_IN;\r
704         }\r
705         else if (scsiDev.msgOut & 0x80) // 0x80 -> 0xFF\r
706         {\r
707                 // IDENTIFY\r
708                 if ((scsiDev.msgOut & 0x18) || // Reserved bits set.\r
709                         (scsiDev.msgOut & 0x20))  // We don't have any target routines!\r
710                 {\r
711                         messageReject();\r
712                 }\r
713 \r
714                 scsiDev.lun = scsiDev.msgOut & 0x7;\r
715                 scsiDev.discPriv = \r
716                         ((scsiDev.msgOut & 0x40) && (scsiDev.initiatorId >= 0))\r
717                                 ? 1 : 0;\r
718         }\r
719         else if (scsiDev.msgOut >= 0x20 && scsiDev.msgOut <= 0x2F)\r
720         {\r
721                 // Two byte message. We don't support these. read and discard.\r
722                 scsiReadByte();\r
723         }\r
724         else if (scsiDev.msgOut == 0x01)\r
725         {\r
726                 int i;\r
727 \r
728                 // Extended message.\r
729                 int msgLen = scsiReadByte();\r
730                 if (msgLen == 0) msgLen = 256;\r
731                 uint8_t extmsg[256];\r
732                 for (i = 0; i < msgLen && !scsiDev.resetFlag; ++i)\r
733                 {\r
734                         // Discard bytes.\r
735                         extmsg[i] = scsiReadByte();\r
736                 }\r
737 \r
738                 if (extmsg[0] == 3 && msgLen == 2) // Wide Data Request\r
739                 {\r
740                         // Negotiate down to 8bit\r
741                         scsiEnterPhase(MESSAGE_IN);\r
742                         static const uint8_t WDTR[] = {0x01, 0x02, 0x03, 0x00};\r
743                         scsiWrite(WDTR, sizeof(WDTR));\r
744                 }\r
745                 else if (extmsg[0] == 1 && msgLen == 3) // Synchronous data request\r
746                 {\r
747                         // Negotiate back to async\r
748                         scsiEnterPhase(MESSAGE_IN);\r
749                         static const uint8_t SDTR[] = {0x01, 0x03, 0x01, 0x00, 0x00};\r
750                         scsiWrite(SDTR, sizeof(SDTR));\r
751                 }\r
752                 else\r
753                 {\r
754                         // Not supported\r
755                         messageReject();\r
756                 }\r
757         }\r
758         else\r
759         {\r
760                 messageReject();\r
761         }\r
762 \r
763         // Re-check the ATN flag in case it stays asserted.\r
764         scsiDev.atnFlag |= SCSI_ReadFilt(SCSI_Filt_ATN);\r
765 }\r
766 \r
767 void scsiPoll(void)\r
768 {\r
769         if (unlikely(scsiDev.resetFlag))\r
770         {\r
771                 scsiReset();\r
772                 if ((scsiDev.resetFlag = SCSI_ReadFilt(SCSI_Filt_RST)))\r
773                 {\r
774                         // Still in reset phase. Do not try and process any commands.\r
775                         return;\r
776                 }\r
777         }\r
778 \r
779         switch (scsiDev.phase)\r
780         {\r
781         case BUS_FREE:\r
782                 if (SCSI_ReadFilt(SCSI_Filt_BSY))\r
783                 {\r
784                         scsiDev.phase = BUS_BUSY;\r
785                 }\r
786                 // The Arbitration phase is optional for SCSI1/SASI hosts if there is only\r
787                 // one initiator in the chain. Support this by moving\r
788                 // straight to selection if SEL is asserted.\r
789                 // ie. the initiator won't assert BSY and it's own ID before moving to selection.\r
790                 else if (SCSI_ReadFilt(SCSI_Filt_SEL))\r
791                 {\r
792                         enter_SelectionPhase();\r
793                 }\r
794         break;\r
795 \r
796         case BUS_BUSY:\r
797                 // Someone is using the bus. Perhaps they are trying to\r
798                 // select us.\r
799                 if (SCSI_ReadFilt(SCSI_Filt_SEL))\r
800                 {\r
801                         enter_SelectionPhase();\r
802                 }\r
803                 else if (!SCSI_ReadFilt(SCSI_Filt_BSY))\r
804                 {\r
805                         scsiDev.phase = BUS_FREE;\r
806                 }\r
807         break;\r
808 \r
809         case ARBITRATION:\r
810                 // TODO Support reselection.\r
811                 break;\r
812 \r
813         case SELECTION:\r
814                 process_SelectionPhase();\r
815         break;\r
816 \r
817         case RESELECTION:\r
818                 // Not currently supported!\r
819         break;\r
820 \r
821         case COMMAND:\r
822                 // Do not check ATN here. SCSI 1 & 2 initiators must set ATN\r
823                 // and SEL together upon entering the selection phase if they\r
824                 // want to send a message (IDENTIFY) immediately.\r
825                 if (scsiDev.atnFlag)\r
826                 {\r
827                         process_MessageOut();\r
828                 }\r
829                 else\r
830                 {\r
831                         process_Command();\r
832                 }\r
833         break;\r
834 \r
835         case DATA_IN:\r
836                 scsiDev.atnFlag |= SCSI_ReadFilt(SCSI_Filt_ATN);\r
837                 if (scsiDev.atnFlag)\r
838                 {\r
839                         process_MessageOut();\r
840                 }\r
841                 else\r
842                 {\r
843                         process_DataIn();\r
844                 }\r
845         break;\r
846 \r
847         case DATA_OUT:\r
848                 scsiDev.atnFlag |= SCSI_ReadFilt(SCSI_Filt_ATN);\r
849                 if (scsiDev.atnFlag)\r
850                 {\r
851                         process_MessageOut();\r
852                 }\r
853                 else\r
854                 {\r
855                         process_DataOut();\r
856                 }\r
857         break;\r
858 \r
859         case STATUS:\r
860                 scsiDev.atnFlag |= SCSI_ReadFilt(SCSI_Filt_ATN);\r
861                 if (scsiDev.atnFlag)\r
862                 {\r
863                         process_MessageOut();\r
864                 }\r
865                 else\r
866                 {\r
867                         process_Status();\r
868                 }\r
869         break;\r
870 \r
871         case MESSAGE_IN:\r
872                 scsiDev.atnFlag |= SCSI_ReadFilt(SCSI_Filt_ATN);\r
873                 if (scsiDev.atnFlag)\r
874                 {\r
875                         process_MessageOut();\r
876                 }\r
877                 else\r
878                 {\r
879                         process_MessageIn();\r
880                 }\r
881 \r
882         break;\r
883 \r
884         case MESSAGE_OUT:\r
885                 process_MessageOut();\r
886         break;\r
887         }\r
888 }\r
889 \r
890 void scsiInit()\r
891 {\r
892         scsiDev.atnFlag = 0;\r
893         scsiDev.resetFlag = 1;\r
894         scsiDev.phase = BUS_FREE;\r
895         scsiDev.target = NULL;\r
896         scsiDev.compatMode = COMPAT_UNKNOWN;\r
897 \r
898         int i;\r
899         for (i = 0; i < MAX_SCSI_TARGETS; ++i)\r
900         {\r
901                 const TargetConfig* cfg = getConfigByIndex(i);\r
902                 if (cfg && (cfg->scsiId & CONFIG_TARGET_ENABLED))\r
903                 {\r
904                         scsiDev.targets[i].targetId = cfg->scsiId & CONFIG_TARGET_ID_BITS;\r
905                         scsiDev.targets[i].cfg = cfg;\r
906 \r
907                         scsiDev.targets[i].liveCfg.bytesPerSector = cfg->bytesPerSector;\r
908                 }\r
909                 else\r
910                 {\r
911                         scsiDev.targets[i].targetId = 0xff;\r
912                         scsiDev.targets[i].cfg = NULL;\r
913                 }\r
914                 scsiDev.targets[i].reservedId = -1;\r
915                 scsiDev.targets[i].reserverId = -1;\r
916                 scsiDev.targets[i].unitAttention = POWER_ON_RESET;\r
917                 scsiDev.targets[i].sense.code = NO_SENSE;\r
918                 scsiDev.targets[i].sense.asc = NO_ADDITIONAL_SENSE_INFORMATION;\r
919         }\r
920 }\r
921 \r
922 void scsiDisconnect()\r
923 {\r
924         scsiEnterPhase(MESSAGE_IN);\r
925         scsiWriteByte(0x02); // save data pointer\r
926         scsiWriteByte(0x04); // disconnect msg.\r
927 \r
928         // For now, the caller is responsible for tracking the disconnected\r
929         // state, and calling scsiReconnect.\r
930         // Ideally the client would exit their loop and we'd implement this\r
931         // as part of scsiPoll\r
932         int phase = scsiDev.phase;\r
933         enter_BusFree();\r
934         scsiDev.phase = phase;\r
935 }\r
936 \r
937 int scsiReconnect()\r
938 {\r
939         int reconnected = 0;\r
940 \r
941         int sel = SCSI_ReadFilt(SCSI_Filt_SEL);\r
942         int bsy = SCSI_ReadFilt(SCSI_Filt_BSY);\r
943         if (!sel && !bsy)\r
944         {\r
945                 CyDelayUs(1);\r
946                 sel = SCSI_ReadFilt(SCSI_Filt_SEL);\r
947                 bsy = SCSI_ReadFilt(SCSI_Filt_BSY);\r
948         }\r
949 \r
950         if (!sel && !bsy)\r
951         {\r
952                 // Arbitrate.\r
953                 ledOn();\r
954                 uint8_t scsiIdMask = 1 << scsiDev.target->targetId;\r
955                 SCSI_Out_Bits_Write(scsiIdMask);\r
956                 SCSI_Out_Ctl_Write(1); // Write bits manually.\r
957                 SCSI_SetPin(SCSI_Out_BSY);\r
958 \r
959                 CyDelayUs(3); // arbitrate delay. 2.4us.\r
960 \r
961                 uint8_t dbx = scsiReadDBxPins();\r
962                 sel = SCSI_ReadFilt(SCSI_Filt_SEL);\r
963                 if (sel || ((dbx ^ scsiIdMask) > scsiIdMask))\r
964                 {\r
965                         // Lost arbitration.\r
966                         SCSI_Out_Ctl_Write(0);\r
967                         SCSI_ClearPin(SCSI_Out_BSY);\r
968                         ledOff();\r
969                 }\r
970                 else\r
971                 {\r
972                         // Won arbitration\r
973                         SCSI_SetPin(SCSI_Out_SEL);\r
974                         CyDelayUs(1); // Bus clear + Bus settle.\r
975 \r
976                         // Reselection phase\r
977                         SCSI_CTL_PHASE_Write(__scsiphase_io);\r
978                         SCSI_Out_Bits_Write(scsiIdMask | (1 << scsiDev.initiatorId));\r
979                         scsiDeskewDelay(); // 2 deskew delays\r
980                         scsiDeskewDelay(); // 2 deskew delays\r
981                         SCSI_ClearPin(SCSI_Out_BSY);\r
982                         CyDelayUs(1);  // Bus Settle Delay\r
983 \r
984                         uint32_t waitStart_ms = getTime_ms();\r
985                         bsy = SCSI_ReadFilt(SCSI_Filt_BSY);\r
986                         // Wait for initiator.\r
987                         while (\r
988                                 !bsy &&\r
989                                 !scsiDev.resetFlag &&\r
990                                 (elapsedTime_ms(waitStart_ms) < 250))\r
991                         {\r
992                                 bsy = SCSI_ReadFilt(SCSI_Filt_BSY);\r
993                         }\r
994 \r
995                         if (bsy)\r
996                         {\r
997                                 SCSI_SetPin(SCSI_Out_BSY);\r
998                                 scsiDeskewDelay(); // 2 deskew delays\r
999                                 scsiDeskewDelay(); // 2 deskew delays\r
1000                                 SCSI_ClearPin(SCSI_Out_SEL);\r
1001 \r
1002                                 // Prepare for the initial IDENTIFY message.\r
1003                                 SCSI_Out_Ctl_Write(0);\r
1004                                 scsiEnterPhase(MESSAGE_IN);\r
1005 \r
1006                                 // Send identify command\r
1007                                 scsiWriteByte(0x80);\r
1008 \r
1009                                 scsiEnterPhase(scsiDev.phase);\r
1010                                 reconnected = 1;\r
1011                         }\r
1012                         else\r
1013                         {\r
1014                                 // reselect timeout.\r
1015                                 SCSI_Out_Ctl_Write(0);\r
1016                                 SCSI_ClearPin(SCSI_Out_SEL);\r
1017                                 SCSI_CTL_PHASE_Write(0);\r
1018                                 ledOff();\r
1019                         }\r
1020                 }\r
1021         }\r
1022         return reconnected;\r
1023 }\r
1024 \r
1025 #pragma GCC pop_options\r