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