b8f6c88cd608e4b77746747695cf5a569c6f3821
[SCSI2SD.git] / software / SCSI2SD / src / disk.c
1 //      Copyright (C) 2013 Michael McMaster <michael@codesrc.com>\r
2 //      Copyright (C) 2014 Doug Brown <doug@downtowndougbrown.com>\r
3 //\r
4 //      This file is part of SCSI2SD.\r
5 //\r
6 //      SCSI2SD is free software: you can redistribute it and/or modify\r
7 //      it under the terms of the GNU General Public License as published by\r
8 //      the Free Software Foundation, either version 3 of the License, or\r
9 //      (at your option) any later version.\r
10 //\r
11 //      SCSI2SD is distributed in the hope that it will be useful,\r
12 //      but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 //      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 //      GNU General Public License for more details.\r
15 //\r
16 //      You should have received a copy of the GNU General Public License\r
17 //      along with SCSI2SD.  If not, see <http://www.gnu.org/licenses/>.\r
18 #include "device.h"\r
19 #include "scsi.h"\r
20 #include "scsiPhy.h"\r
21 #include "config.h"\r
22 #include "debug.h"\r
23 #include "debug.h"\r
24 #include "disk.h"\r
25 #include "sd.h"\r
26 #include "time.h"\r
27 \r
28 #include <string.h>\r
29 \r
30 // Global\r
31 BlockDevice blockDev;\r
32 Transfer transfer;\r
33 \r
34 static int doSdInit()\r
35 {\r
36         int result = 0;\r
37         if (blockDev.state & DISK_PRESENT)\r
38         {\r
39                 result = sdInit();\r
40 \r
41                 if (result)\r
42                 {\r
43                         blockDev.state = blockDev.state | DISK_INITIALISED;\r
44                 }\r
45         }\r
46         return result;\r
47 }\r
48 \r
49 // Callback once all data has been read in the data out phase.\r
50 static void doFormatUnitComplete(void)\r
51 {\r
52         // TODO start writing the initialisation pattern to the SD\r
53         // card\r
54         scsiDev.phase = STATUS;\r
55 }\r
56 \r
57 static void doFormatUnitSkipData(int bytes)\r
58 {\r
59         // We may not have enough memory to store the initialisation pattern and\r
60         // defect list data.  Since we're not making use of it yet anyway, just\r
61         // discard the bytes.\r
62         scsiEnterPhase(DATA_OUT);\r
63         int i;\r
64         for (i = 0; i < bytes; ++i)\r
65         {\r
66                 scsiReadByte();\r
67         }\r
68 }\r
69 \r
70 // Callback from the data out phase.\r
71 static void doFormatUnitPatternHeader(void)\r
72 {\r
73         int defectLength =\r
74                 ((((uint16_t)scsiDev.data[2])) << 8) +\r
75                         scsiDev.data[3];\r
76 \r
77         int patternLength =\r
78                 ((((uint16_t)scsiDev.data[4 + 2])) << 8) +\r
79                 scsiDev.data[4 + 3];\r
80 \r
81                 doFormatUnitSkipData(defectLength + patternLength);\r
82                 doFormatUnitComplete();\r
83 }\r
84 \r
85 // Callback from the data out phase.\r
86 static void doFormatUnitHeader(void)\r
87 {\r
88         int IP = (scsiDev.data[1] & 0x08) ? 1 : 0;\r
89         int DSP = (scsiDev.data[1] & 0x04) ? 1 : 0;\r
90 \r
91         if (! DSP) // disable save parameters\r
92         {\r
93                 // Save the "MODE SELECT savable parameters"\r
94                 configSave(\r
95                         scsiDev.target->targetId,\r
96                         scsiDev.target->liveCfg.bytesPerSector);\r
97         }\r
98 \r
99         if (IP)\r
100         {\r
101                 // We need to read the initialisation pattern header first.\r
102                 scsiDev.dataLen += 4;\r
103                 scsiDev.phase = DATA_OUT;\r
104                 scsiDev.postDataOutHook = doFormatUnitPatternHeader;\r
105         }\r
106         else\r
107         {\r
108                 // Read the defect list data\r
109                 int defectLength =\r
110                         ((((uint16_t)scsiDev.data[2])) << 8) +\r
111                         scsiDev.data[3];\r
112                 doFormatUnitSkipData(defectLength);\r
113                 doFormatUnitComplete();\r
114         }\r
115 }\r
116 \r
117 static void doReadCapacity()\r
118 {\r
119         uint32_t lba = (((uint32) scsiDev.cdb[2]) << 24) +\r
120                 (((uint32) scsiDev.cdb[3]) << 16) +\r
121                 (((uint32) scsiDev.cdb[4]) << 8) +\r
122                 scsiDev.cdb[5];\r
123         int pmi = scsiDev.cdb[8] & 1;\r
124 \r
125         uint32_t capacity = getScsiCapacity(\r
126                 scsiDev.target->cfg->sdSectorStart,\r
127                 scsiDev.target->liveCfg.bytesPerSector,\r
128                 scsiDev.target->cfg->scsiSectors);\r
129 \r
130         if (!pmi && lba)\r
131         {\r
132                 // error.\r
133                 // We don't do anything with the "partial medium indicator", and\r
134                 // assume that delays are constant across each block. But the spec\r
135                 // says we must return this error if pmi is specified incorrectly.\r
136                 scsiDev.status = CHECK_CONDITION;\r
137                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
138                 scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;\r
139                 scsiDev.phase = STATUS;\r
140         }\r
141         else if (capacity > 0)\r
142         {\r
143                 uint32_t highestBlock = capacity - 1;\r
144 \r
145                 scsiDev.data[0] = highestBlock >> 24;\r
146                 scsiDev.data[1] = highestBlock >> 16;\r
147                 scsiDev.data[2] = highestBlock >> 8;\r
148                 scsiDev.data[3] = highestBlock;\r
149 \r
150                 uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;\r
151                 scsiDev.data[4] = bytesPerSector >> 24;\r
152                 scsiDev.data[5] = bytesPerSector >> 16;\r
153                 scsiDev.data[6] = bytesPerSector >> 8;\r
154                 scsiDev.data[7] = bytesPerSector;\r
155                 scsiDev.dataLen = 8;\r
156                 scsiDev.phase = DATA_IN;\r
157         }\r
158         else\r
159         {\r
160                 scsiDev.status = CHECK_CONDITION;\r
161                 scsiDev.target->sense.code = NOT_READY;\r
162                 scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;\r
163                 scsiDev.phase = STATUS;\r
164         }\r
165 }\r
166 \r
167 static void doWrite(uint32 lba, uint32 blocks)\r
168 {\r
169         if (unlikely(scsiDev.target->cfg->deviceType == CONFIG_FLOPPY_14MB)) {\r
170                 // Floppies are supposed to be slow. Some systems can't handle a floppy\r
171                 // without an access time\r
172                 CyDelay(10);\r
173         }\r
174 \r
175         uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;\r
176 \r
177         if (unlikely(blockDev.state & DISK_WP) ||\r
178                 unlikely(scsiDev.target->cfg->deviceType == CONFIG_OPTICAL))\r
179 \r
180         {\r
181                 scsiDev.status = CHECK_CONDITION;\r
182                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
183                 scsiDev.target->sense.asc = WRITE_PROTECTED;\r
184                 scsiDev.phase = STATUS;\r
185         }\r
186         else if (unlikely(((uint64) lba) + blocks >\r
187                 getScsiCapacity(\r
188                         scsiDev.target->cfg->sdSectorStart,\r
189                         bytesPerSector,\r
190                         scsiDev.target->cfg->scsiSectors\r
191                         )\r
192                 ))\r
193         {\r
194                 scsiDev.status = CHECK_CONDITION;\r
195                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
196                 scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;\r
197                 scsiDev.phase = STATUS;\r
198         }\r
199         else\r
200         {\r
201                 transfer.lba = lba;\r
202                 transfer.blocks = blocks;\r
203                 transfer.currentBlock = 0;\r
204                 scsiDev.phase = DATA_OUT;\r
205                 scsiDev.dataLen = bytesPerSector;\r
206                 scsiDev.dataPtr = bytesPerSector;\r
207 \r
208                 // No need for single-block writes atm.  Overhead of the\r
209                 // multi-block write is minimal.\r
210                 transfer.multiBlock = 1;\r
211 \r
212 \r
213                 uint32_t sdLBA =\r
214                         SCSISector2SD(\r
215                                 scsiDev.target->cfg->sdSectorStart,\r
216                                 bytesPerSector,\r
217                                 lba);\r
218                 uint32_t sdBlocks = blocks * SDSectorsPerSCSISector(bytesPerSector);\r
219                 sdWriteMultiSectorPrep(sdLBA, sdBlocks);\r
220         }\r
221 }\r
222 \r
223 \r
224 static void doRead(uint32 lba, uint32 blocks)\r
225 {\r
226         if (unlikely(scsiDev.target->cfg->deviceType == CONFIG_FLOPPY_14MB)) {\r
227                 // Floppies are supposed to be slow. Some systems can't handle a floppy\r
228                 // without an access time\r
229                 CyDelay(10);\r
230         }\r
231 \r
232         uint32_t capacity = getScsiCapacity(\r
233                 scsiDev.target->cfg->sdSectorStart,\r
234                 scsiDev.target->liveCfg.bytesPerSector,\r
235                 scsiDev.target->cfg->scsiSectors);\r
236         if (unlikely(((uint64) lba) + blocks > capacity))\r
237         {\r
238                 scsiDev.status = CHECK_CONDITION;\r
239                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
240                 scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;\r
241                 scsiDev.phase = STATUS;\r
242         }\r
243         else\r
244         {\r
245                 transfer.lba = lba;\r
246                 transfer.blocks = blocks;\r
247                 transfer.currentBlock = 0;\r
248                 scsiDev.phase = DATA_IN;\r
249                 scsiDev.dataLen = 0; // No data yet\r
250 \r
251                 uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;\r
252                 uint32_t sdSectorPerSCSISector = SDSectorsPerSCSISector(bytesPerSector);\r
253                 uint32_t sdSectors =\r
254                         blocks * sdSectorPerSCSISector;\r
255 \r
256                 if ((\r
257                                 (sdSectors == 1) &&\r
258                                 !(scsiDev.boardCfg.flags & CONFIG_ENABLE_CACHE)\r
259                         ) ||\r
260                         unlikely(((uint64) lba) + blocks == capacity)\r
261                         )\r
262                 {\r
263                         // We get errors on reading the last sector using a multi-sector\r
264                         // read :-(\r
265                         transfer.multiBlock = 0;\r
266                 }\r
267                 else\r
268                 {\r
269                         transfer.multiBlock = 1;\r
270 \r
271                         uint32_t sdLBA =\r
272                                 SCSISector2SD(\r
273                                         scsiDev.target->cfg->sdSectorStart,\r
274                                         bytesPerSector,\r
275                                         lba);\r
276 \r
277                         sdReadMultiSectorPrep(sdLBA, sdSectors);\r
278                 }\r
279         }\r
280 }\r
281 \r
282 static void doSeek(uint32 lba)\r
283 {\r
284         if (lba >=\r
285                 getScsiCapacity(\r
286                         scsiDev.target->cfg->sdSectorStart,\r
287                         scsiDev.target->liveCfg.bytesPerSector,\r
288                         scsiDev.target->cfg->scsiSectors)\r
289                 )\r
290         {\r
291                 scsiDev.status = CHECK_CONDITION;\r
292                 scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
293                 scsiDev.target->sense.asc = LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;\r
294                 scsiDev.phase = STATUS;\r
295         }\r
296 }\r
297 \r
298 static int doTestUnitReady()\r
299 {\r
300         int ready = 1;\r
301         if (likely(blockDev.state == (DISK_STARTED | DISK_PRESENT | DISK_INITIALISED)))\r
302         {\r
303                 // nothing to do.\r
304         }\r
305         else if (unlikely(!(blockDev.state & DISK_STARTED)))\r
306         {\r
307                 ready = 0;\r
308                 scsiDev.status = CHECK_CONDITION;\r
309                 scsiDev.target->sense.code = NOT_READY;\r
310                 scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_INITIALIZING_COMMAND_REQUIRED;\r
311                 scsiDev.phase = STATUS;\r
312         }\r
313         else if (unlikely(!(blockDev.state & DISK_PRESENT)))\r
314         {\r
315                 ready = 0;\r
316                 scsiDev.status = CHECK_CONDITION;\r
317                 scsiDev.target->sense.code = NOT_READY;\r
318                 scsiDev.target->sense.asc = MEDIUM_NOT_PRESENT;\r
319                 scsiDev.phase = STATUS;\r
320         }\r
321         else if (unlikely(!(blockDev.state & DISK_INITIALISED)))\r
322         {\r
323                 ready = 0;\r
324                 scsiDev.status = CHECK_CONDITION;\r
325                 scsiDev.target->sense.code = NOT_READY;\r
326                 scsiDev.target->sense.asc = LOGICAL_UNIT_NOT_READY_CAUSE_NOT_REPORTABLE;\r
327                 scsiDev.phase = STATUS;\r
328         }\r
329         return ready;\r
330 }\r
331 \r
332 // Handle direct-access scsi device commands\r
333 int scsiDiskCommand()\r
334 {\r
335         int commandHandled = 1;\r
336 \r
337         uint8 command = scsiDev.cdb[0];\r
338         if (unlikely(command == 0x1B))\r
339         {\r
340                 // START STOP UNIT\r
341                 // Enable or disable media access operations.\r
342                 // Ignore load/eject requests. We can't do that.\r
343                 //int immed = scsiDev.cdb[1] & 1;\r
344                 int start = scsiDev.cdb[4] & 1;\r
345 \r
346                 if (start)\r
347                 {\r
348                         blockDev.state = blockDev.state | DISK_STARTED;\r
349                         if (!(blockDev.state & DISK_INITIALISED))\r
350                         {\r
351                                 doSdInit();\r
352                         }\r
353                 }\r
354                 else\r
355                 {\r
356                         blockDev.state &= ~DISK_STARTED;\r
357                 }\r
358         }\r
359         else if (unlikely(command == 0x00))\r
360         {\r
361                 // TEST UNIT READY\r
362                 doTestUnitReady();\r
363         }\r
364         else if (unlikely(!doTestUnitReady()))\r
365         {\r
366                 // Status and sense codes already set by doTestUnitReady\r
367         }\r
368         else if (likely(command == 0x08))\r
369         {\r
370                 // READ(6)\r
371                 uint32 lba =\r
372                         (((uint32) scsiDev.cdb[1] & 0x1F) << 16) +\r
373                         (((uint32) scsiDev.cdb[2]) << 8) +\r
374                         scsiDev.cdb[3];\r
375                 uint32 blocks = scsiDev.cdb[4];\r
376                 if (unlikely(blocks == 0)) blocks = 256;\r
377                 doRead(lba, blocks);\r
378         }\r
379         else if (likely(command == 0x28))\r
380         {\r
381                 // READ(10)\r
382                 // Ignore all cache control bits - we don't support a memory cache.\r
383 \r
384                 uint32 lba =\r
385                         (((uint32) scsiDev.cdb[2]) << 24) +\r
386                         (((uint32) scsiDev.cdb[3]) << 16) +\r
387                         (((uint32) scsiDev.cdb[4]) << 8) +\r
388                         scsiDev.cdb[5];\r
389                 uint32 blocks =\r
390                         (((uint32) scsiDev.cdb[7]) << 8) +\r
391                         scsiDev.cdb[8];\r
392 \r
393                 doRead(lba, blocks);\r
394         }\r
395         else if (likely(command == 0x0A))\r
396         {\r
397                 // WRITE(6)\r
398                 uint32 lba =\r
399                         (((uint32) scsiDev.cdb[1] & 0x1F) << 16) +\r
400                         (((uint32) scsiDev.cdb[2]) << 8) +\r
401                         scsiDev.cdb[3];\r
402                 uint32 blocks = scsiDev.cdb[4];\r
403                 if (unlikely(blocks == 0)) blocks = 256;\r
404                 doWrite(lba, blocks);\r
405         }\r
406         else if (likely(command == 0x2A) || // WRITE(10)\r
407                 unlikely(command == 0x2E)) // WRITE AND VERIFY\r
408         {\r
409                 // Ignore all cache control bits - we don't support a memory cache.\r
410                 // Don't bother verifying either. The SD card likely stores ECC\r
411                 // along with each flash row.\r
412 \r
413                 uint32 lba =\r
414                         (((uint32) scsiDev.cdb[2]) << 24) +\r
415                         (((uint32) scsiDev.cdb[3]) << 16) +\r
416                         (((uint32) scsiDev.cdb[4]) << 8) +\r
417                         scsiDev.cdb[5];\r
418                 uint32 blocks =\r
419                         (((uint32) scsiDev.cdb[7]) << 8) +\r
420                         scsiDev.cdb[8];\r
421 \r
422                 doWrite(lba, blocks);\r
423         }\r
424 \r
425         else if (unlikely(command == 0x04))\r
426         {\r
427                 // FORMAT UNIT\r
428                 // We don't really do any formatting, but we need to read the correct\r
429                 // number of bytes in the DATA_OUT phase to make the SCSI host happy.\r
430 \r
431                 int fmtData = (scsiDev.cdb[1] & 0x10) ? 1 : 0;\r
432                 if (fmtData)\r
433                 {\r
434                         // We need to read the parameter list, but we don't know how\r
435                         // big it is yet. Start with the header.\r
436                         scsiDev.dataLen = 4;\r
437                         scsiDev.phase = DATA_OUT;\r
438                         scsiDev.postDataOutHook = doFormatUnitHeader;\r
439                 }\r
440                 else\r
441                 {\r
442                         // No data to read, we're already finished!\r
443                 }\r
444         }\r
445         else if (unlikely(command == 0x25))\r
446         {\r
447                 // READ CAPACITY\r
448                 doReadCapacity();\r
449         }\r
450         else if (unlikely(command == 0x0B))\r
451         {\r
452                 // SEEK(6)\r
453                 uint32 lba =\r
454                         (((uint32) scsiDev.cdb[1] & 0x1F) << 16) +\r
455                         (((uint32) scsiDev.cdb[2]) << 8) +\r
456                         scsiDev.cdb[3];\r
457 \r
458                 doSeek(lba);\r
459         }\r
460 \r
461         else if (unlikely(command == 0x2B))\r
462         {\r
463                 // SEEK(10)\r
464                 uint32 lba =\r
465                         (((uint32) scsiDev.cdb[2]) << 24) +\r
466                         (((uint32) scsiDev.cdb[3]) << 16) +\r
467                         (((uint32) scsiDev.cdb[4]) << 8) +\r
468                         scsiDev.cdb[5];\r
469 \r
470                 doSeek(lba);\r
471         }\r
472         else if (unlikely(command == 0x36))\r
473         {\r
474                 // LOCK UNLOCK CACHE\r
475                 // We don't have a cache to lock data into. do nothing.\r
476         }\r
477         else if (unlikely(command == 0x34))\r
478         {\r
479                 // PRE-FETCH.\r
480                 // We don't have a cache to pre-fetch into. do nothing.\r
481         }\r
482         else if (unlikely(command == 0x1E))\r
483         {\r
484                 // PREVENT ALLOW MEDIUM REMOVAL\r
485                 // Not much we can do to prevent the user removing the SD card.\r
486                 // do nothing.\r
487         }\r
488         else if (unlikely(command == 0x01))\r
489         {\r
490                 // REZERO UNIT\r
491                 // Set the lun to a vendor-specific state. Ignore.\r
492         }\r
493         else if (unlikely(command == 0x35))\r
494         {\r
495                 // SYNCHRONIZE CACHE\r
496                 // We don't have a cache. do nothing.\r
497         }\r
498         else if (unlikely(command == 0x2F))\r
499         {\r
500                 // VERIFY\r
501                 // TODO: When they supply data to verify, we should read the data and\r
502                 // verify it. If they don't supply any data, just say success.\r
503                 if ((scsiDev.cdb[1] & 0x02) == 0)\r
504                 {\r
505                         // They are asking us to do a medium verification with no data\r
506                         // comparison. Assume success, do nothing.\r
507                 }\r
508                 else\r
509                 {\r
510                         // TODO. This means they are supplying data to verify against.\r
511                         // Technically we should probably grab the data and compare it.\r
512                         scsiDev.status = CHECK_CONDITION;\r
513                         scsiDev.target->sense.code = ILLEGAL_REQUEST;\r
514                         scsiDev.target->sense.asc = INVALID_FIELD_IN_CDB;\r
515                         scsiDev.phase = STATUS;\r
516                 }\r
517         }\r
518         else if (unlikely(command == 0x37))\r
519         {\r
520                 // READ DEFECT DATA\r
521                 scsiDev.status = CHECK_CONDITION;\r
522                 scsiDev.target->sense.code = NO_SENSE;\r
523                 scsiDev.target->sense.asc = DEFECT_LIST_NOT_FOUND;\r
524                 scsiDev.phase = STATUS;\r
525 \r
526         }\r
527         else\r
528         {\r
529                 commandHandled = 0;\r
530         }\r
531 \r
532         return commandHandled;\r
533 }\r
534 \r
535 void scsiDiskPoll()\r
536 {\r
537         uint32_t bytesPerSector = scsiDev.target->liveCfg.bytesPerSector;\r
538 \r
539         if (scsiDev.phase == DATA_IN &&\r
540                 transfer.currentBlock != transfer.blocks)\r
541         {\r
542                 scsiEnterPhase(DATA_IN);\r
543 \r
544                 int totalSDSectors =\r
545                         transfer.blocks * SDSectorsPerSCSISector(bytesPerSector);\r
546                 uint32_t sdLBA =\r
547                         SCSISector2SD(\r
548                                 scsiDev.target->cfg->sdSectorStart,\r
549                                 bytesPerSector,\r
550                                 transfer.lba);\r
551 \r
552                 const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);\r
553                 int buffers = sizeof(scsiDev.data) / SD_SECTOR_SIZE;\r
554                 int prep = 0;\r
555                 int i = 0;\r
556                 int scsiActive = 0;\r
557                 int sdActive = 0;\r
558                 while ((i < totalSDSectors) &&\r
559                         likely(scsiDev.phase == DATA_IN) &&\r
560                         likely(!scsiDev.resetFlag))\r
561                 {\r
562                         // Wait for the next DMA interrupt. It's beneficial to halt the\r
563                         // processor to give the DMA controller more memory bandwidth to\r
564                         // work with.\r
565                         int scsiBusy = 1;\r
566                         int sdBusy = 1;\r
567                         while (scsiBusy && sdBusy)\r
568                         {\r
569                                 uint8_t intr = CyEnterCriticalSection();\r
570                                 scsiBusy = scsiDMABusy();\r
571                                 sdBusy = sdDMABusy();\r
572                                 if (scsiBusy && sdBusy)\r
573                                 {\r
574                                         __WFI();\r
575                                 }\r
576                                 CyExitCriticalSection(intr);\r
577                         }\r
578 \r
579                         if (sdActive && !sdBusy && sdReadSectorDMAPoll())\r
580                         {\r
581                                 sdActive = 0;\r
582                                 prep++;\r
583                         }\r
584 \r
585                         // Usually SD is slower than the SCSI interface.\r
586                         // Prioritise starting the read of the next sector over starting a\r
587                         // SCSI transfer for the last sector\r
588                         // ie. NO "else" HERE.\r
589                         if (!sdActive &&\r
590                                 (prep - i < buffers) &&\r
591                                 (prep < totalSDSectors))\r
592                         {\r
593                                 // Start an SD transfer if we have space.\r
594                                 if (transfer.multiBlock)\r
595                                 {\r
596                                         sdReadMultiSectorDMA(&scsiDev.data[SD_SECTOR_SIZE * (prep % buffers)]);\r
597                                 }\r
598                                 else\r
599                                 {\r
600                                         sdReadSingleSectorDMA(sdLBA + prep, &scsiDev.data[SD_SECTOR_SIZE * (prep % buffers)]);\r
601                                 }\r
602                                 sdActive = 1;\r
603                         }\r
604 \r
605                         if (scsiActive && !scsiBusy && scsiWriteDMAPoll())\r
606                         {\r
607                                 scsiActive = 0;\r
608                                 ++i;\r
609                         }\r
610                         if (!scsiActive && ((prep - i) > 0))\r
611                         {\r
612                                 int dmaBytes = SD_SECTOR_SIZE;\r
613                                 if ((i % sdPerScsi) == (sdPerScsi - 1))\r
614                                 {\r
615                                         dmaBytes = bytesPerSector % SD_SECTOR_SIZE;\r
616                                         if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;\r
617                                 }\r
618                                 scsiWriteDMA(&scsiDev.data[SD_SECTOR_SIZE * (i % buffers)], dmaBytes);\r
619                                 scsiActive = 1;\r
620                         }\r
621                 }\r
622                 if (scsiDev.phase == DATA_IN)\r
623                 {\r
624                         scsiDev.phase = STATUS;\r
625                 }\r
626                 scsiDiskReset();\r
627         }\r
628         else if (scsiDev.phase == DATA_OUT &&\r
629                 transfer.currentBlock != transfer.blocks)\r
630         {\r
631                 scsiEnterPhase(DATA_OUT);\r
632 \r
633                 const int sdPerScsi = SDSectorsPerSCSISector(bytesPerSector);\r
634                 int totalSDSectors = transfer.blocks * sdPerScsi;\r
635                 int buffers = sizeof(scsiDev.data) / SD_SECTOR_SIZE;\r
636                 int prep = 0;\r
637                 int i = 0;\r
638                 int scsiDisconnected = 0;\r
639                 int scsiComplete = 0;\r
640                 int clearBSY = 0;\r
641                 uint32_t lastActivityTime = getTime_ms();\r
642                 int scsiActive = 0;\r
643                 int sdActive = 0;\r
644 \r
645                 while ((i < totalSDSectors) &&\r
646                         (likely(scsiDev.phase == DATA_OUT) || // scsiDisconnect keeps our phase.\r
647                                 scsiComplete) &&\r
648                         likely(!scsiDev.resetFlag))\r
649                 {\r
650                         // Wait for the next DMA interrupt. It's beneficial to halt the\r
651                         // processor to give the DMA controller more memory bandwidth to\r
652                         // work with.\r
653                         int scsiBusy = 1;\r
654                         int sdBusy = 1;\r
655                         while (scsiBusy && sdBusy)\r
656                         {\r
657                                 uint8_t intr = CyEnterCriticalSection();\r
658                                 scsiBusy = scsiDMABusy();\r
659                                 sdBusy = sdDMABusy();\r
660                                 if (scsiBusy && sdBusy)\r
661                                 {\r
662                                         __WFI();\r
663                                 }\r
664                                 CyExitCriticalSection(intr);\r
665                         }\r
666 \r
667                         if (sdActive && !sdBusy && sdWriteSectorDMAPoll())\r
668                         {\r
669                                 sdActive = 0;\r
670                                 i++;\r
671                         }\r
672                         if (!sdActive && ((prep - i) > 0))\r
673                         {\r
674                                 // Start an SD transfer if we have space.\r
675                                 sdWriteMultiSectorDMA(&scsiDev.data[SD_SECTOR_SIZE * (i % buffers)]);\r
676                                 sdActive = 1;\r
677                         }\r
678 \r
679                         uint32_t now = getTime_ms();\r
680 \r
681                         if (scsiActive && !scsiBusy && scsiReadDMAPoll())\r
682                         {\r
683                                 scsiActive = 0;\r
684                                 ++prep;\r
685                                 lastActivityTime = now;\r
686                         }\r
687                         if (!scsiActive &&\r
688                                 ((prep - i) < buffers) &&\r
689                                 (prep < totalSDSectors) &&\r
690                                 likely(!scsiDisconnected))\r
691                         {\r
692                                 int dmaBytes = SD_SECTOR_SIZE;\r
693                                 if ((prep % sdPerScsi) == (sdPerScsi - 1))\r
694                                 {\r
695                                         dmaBytes = bytesPerSector % SD_SECTOR_SIZE;\r
696                                         if (dmaBytes == 0) dmaBytes = SD_SECTOR_SIZE;\r
697                                 }\r
698                                 scsiReadDMA(&scsiDev.data[SD_SECTOR_SIZE * (prep % buffers)], dmaBytes);\r
699                                 scsiActive = 1;\r
700                         }\r
701                         else if (\r
702                                 (scsiDev.boardCfg.flags & CONFIG_ENABLE_DISCONNECT) &&\r
703                                 (scsiActive == 0) &&\r
704                                 likely(!scsiDisconnected) &&\r
705                                 unlikely(scsiDev.discPriv) &&\r
706                                 unlikely(diffTime_ms(lastActivityTime, now) >= 20) &&\r
707                                 likely(scsiDev.phase == DATA_OUT))\r
708                         {\r
709                                 // We're transferring over the SCSI bus faster than the SD card\r
710                                 // can write.  There is no more buffer space once we've finished\r
711                                 // this SCSI transfer.\r
712                                 // The NCR 53C700 interface chips have a 250ms "byte-to-byte"\r
713                                 // timeout buffer. SD card writes are supposed to complete\r
714                                 // within 200ms, but sometimes they don't.\r
715                                 // The NCR 53C700 series is used on HP 9000 workstations.\r
716                                 scsiDisconnect();\r
717                                 scsiDisconnected = 1;\r
718                                 lastActivityTime = getTime_ms();\r
719                         }\r
720                         else if (unlikely(scsiDisconnected) &&\r
721                                 (\r
722                                         (prep == i) || // Buffers empty.\r
723                                         // Send some messages every 100ms so we don't timeout.\r
724                                         // At a minimum, a reselection involves an IDENTIFY message.\r
725                                         unlikely(diffTime_ms(lastActivityTime, now) >= 100)\r
726                                 ))\r
727                         {\r
728                                 int reconnected = scsiReconnect();\r
729                                 if (reconnected)\r
730                                 {\r
731                                         scsiDisconnected = 0;\r
732                                         lastActivityTime = getTime_ms(); // Don't disconnect immediately.\r
733                                 }\r
734                                 else if (diffTime_ms(lastActivityTime, getTime_ms()) >= 10000)\r
735                                 {\r
736                                         // Give up after 10 seconds of trying to reconnect.\r
737                                         scsiDev.resetFlag = 1;\r
738                                 }\r
739                         }\r
740                         else if (\r
741                                 likely(!scsiComplete) &&\r
742                                 (sdActive == 1) &&\r
743                                 (prep == totalSDSectors) && // All scsi data read and buffered\r
744                                 likely(!scsiDev.discPriv) && // Prefer disconnect where possible.\r
745                                 unlikely(diffTime_ms(lastActivityTime, now) >= 150) &&\r
746 \r
747                                 likely(scsiDev.phase == DATA_OUT) &&\r
748                                 !(scsiDev.cdb[scsiDev.cdbLen - 1] & 0x01) // Not linked command\r
749                                 )\r
750                         {\r
751                                 // We're transferring over the SCSI bus faster than the SD card\r
752                                 // can write.  All data is buffered, and we're just waiting for\r
753                                 // the SD card to complete. The host won't let us disconnect.\r
754                                 // Some drivers set a 250ms timeout on transfers to complete.\r
755                                 // SD card writes are supposed to complete\r
756                                 // within 200ms, but sometimes they don'to.\r
757                                 // Just pretend we're finished.\r
758                                 scsiComplete = 1;\r
759 \r
760                                 process_Status();\r
761                                 clearBSY = process_MessageIn(0); // Will go to BUS_FREE state but keeps BSY asserted\r
762                         }\r
763                 }\r
764 \r
765                 if (clearBSY)\r
766                 {\r
767                         enter_BusFree();\r
768                 }\r
769                 while (\r
770                         !scsiDev.resetFlag &&\r
771                         unlikely(scsiDisconnected) &&\r
772                         (elapsedTime_ms(lastActivityTime) <= 10000))\r
773                 {\r
774                         scsiDisconnected = !scsiReconnect();\r
775                 }\r
776                 if (scsiDisconnected)\r
777                 {\r
778                         // Failed to reconnect\r
779                         scsiDev.resetFlag = 1;\r
780                 }\r
781 \r
782                 if (scsiDev.phase == DATA_OUT)\r
783                 {\r
784                         if (scsiDev.parityError &&\r
785                                 (scsiDev.boardCfg.flags & CONFIG_ENABLE_PARITY) &&\r
786                                 (scsiDev.compatMode >= COMPAT_SCSI2))\r
787                         {\r
788                                 scsiDev.target->sense.code = ABORTED_COMMAND;\r
789                                 scsiDev.target->sense.asc = SCSI_PARITY_ERROR;\r
790                                 scsiDev.status = CHECK_CONDITION;;\r
791                         }\r
792                         scsiDev.phase = STATUS;\r
793                 }\r
794                 scsiDiskReset();\r
795         }\r
796 }\r
797 \r
798 void scsiDiskReset()\r
799 {\r
800         scsiDev.dataPtr = 0;\r
801         scsiDev.savedDataPtr = 0;\r
802         scsiDev.dataLen = 0;\r
803         // transfer.lba = 0; // Needed in Request Sense to determine failure\r
804         transfer.blocks = 0;\r
805         transfer.currentBlock = 0;\r
806 \r
807         // Cancel long running commands!\r
808         if (\r
809                 ((scsiDev.boardCfg.flags & CONFIG_ENABLE_CACHE) == 0) ||\r
810                         (transfer.multiBlock == 0)\r
811                 )\r
812         {\r
813                 sdCompleteTransfer();\r
814         }\r
815 \r
816         transfer.multiBlock = 0;\r
817 }\r
818 \r
819 void scsiDiskInit()\r
820 {\r
821         scsiDiskReset();\r
822 \r
823         // Don't require the host to send us a START STOP UNIT command\r
824         blockDev.state = DISK_STARTED;\r
825         // WP pin not available for micro-sd\r
826         // TODO read card WP register\r
827         #if 0\r
828         if (SD_WP_Read())\r
829         {\r
830                 blockDev.state = blockDev.state | DISK_WP;\r
831         }\r
832         #endif\r
833 }\r
834 \r
835 \r