Subversion Repositories Kolibri OS

Rev

Rev 3598 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3520 clevermous 1
; standard driver stuff
2
format MS COFF
3
 
4
DEBUG = 1
5
DUMP_PACKETS = 0
6
 
7
; this is for DEBUGF macro from 'fdo.inc'
8
__DEBUG__ = 1
9
__DEBUG_LEVEL__ = 1
10
 
11
include 'proc32.inc'
12
include 'imports.inc'
13
include 'fdo.inc'
14
 
15
public START
16
public version
17
 
18
; USB constants
19
DEVICE_DESCR_TYPE = 1
20
CONFIG_DESCR_TYPE = 2
21
STRING_DESCR_TYPE = 3
22
INTERFACE_DESCR_TYPE = 4
23
ENDPOINT_DESCR_TYPE = 5
24
DEVICE_QUALIFIER_DESCR_TYPE = 6
25
 
26
CONTROL_PIPE = 0
27
ISOCHRONOUS_PIPE = 1
28
BULK_PIPE = 2
29
INTERRUPT_PIPE = 3
30
 
31
; USB structures
32
virtual at 0
33
config_descr:
34
.bLength                db      ?
35
.bDescriptorType        db      ?
36
.wTotalLength           dw      ?
37
.bNumInterfaces         db      ?
38
.bConfigurationValue    db      ?
39
.iConfiguration         db      ?
40
.bmAttributes           db      ?
41
.bMaxPower              db      ?
42
.sizeof:
43
end virtual
44
 
45
virtual at 0
46
interface_descr:
47
.bLength                db      ?
48
.bDescriptorType        db      ?
49
.bInterfaceNumber       db      ?
50
.bAlternateSetting      db      ?
51
.bNumEndpoints          db      ?
52
.bInterfaceClass        db      ?
53
.bInterfaceSubClass     db      ?
54
.bInterfaceProtocol     db      ?
55
.iInterface             db      ?
56
.sizeof:
57
end virtual
58
 
59
virtual at 0
60
endpoint_descr:
61
.bLength                db      ?
62
.bDescriptorType        db      ?
63
.bEndpointAddress       db      ?
64
.bmAttributes           db      ?
65
.wMaxPacketSize         dw      ?
66
.bInterval              db      ?
67
.sizeof:
68
end virtual
69
 
70
; Mass storage protocol constants, USB layer
71
REQUEST_GETMAXLUN = 0xFE        ; get max lun
72
REQUEST_BORESET = 0xFF          ; bulk-only reset
73
 
74
; Mass storage protocol structures, USB layer
75
; Sent from host to device in the first stage of an operation.
76
struc command_block_wrapper
77
{
78
.Signature      dd      ?       ; the constant 'USBC'
79
.Tag            dd      ?       ; identifies response with request
80
.Length         dd      ?       ; length of data-transport phase
81
.Flags          db      ?       ; one of CBW_FLAG_*
82
CBW_FLAG_OUT = 0
83
CBW_FLAG_IN = 80h
84
.LUN            db      ?       ; addressed unit
85
.CommandLength  db      ?       ; the length of the following field
86
.Command        rb      16
87
.sizeof:
88
}
89
virtual at 0
90
command_block_wrapper   command_block_wrapper
91
end virtual
92
 
93
; Sent from device to host in the last stage of an operation.
94
struc command_status_wrapper
95
{
96
.Signature      dd      ?       ; the constant 'USBS'
97
.Tag            dd      ?       ; identifies response with request
98
.LengthRest     dd      ?       ; .Length - (size of data which were transferred)
99
.Status         db      ?       ; one of CSW_STATUS_*
100
CSW_STATUS_OK = 0
101
CSW_STATUS_FAIL = 1
102
CSW_STATUS_FATAL = 2
103
.sizeof:
104
}
105
virtual at 0
106
command_status_wrapper  command_status_wrapper
107
end virtual
108
 
109
; Constants of SCSI layer
110
SCSI_REQUEST_SENSE = 3
111
SCSI_INQUIRY = 12h
112
SCSI_READ_CAPACITY = 25h
113
SCSI_READ10 = 28h
114
SCSI_WRITE10 = 2Ah
115
 
116
; Result of SCSI REQUEST SENSE command.
117
SENSE_UNKNOWN = 0
118
SENSE_RECOVERED_ERROR = 1
119
SENSE_NOT_READY = 2
120
SENSE_MEDIUM_ERROR = 3
121
SENSE_HARDWARE_ERROR = 4
122
SENSE_ILLEGAL_REQUEST = 5
123
SENSE_UNIT_ATTENTION = 6
124
SENSE_DATA_PROTECT = 7
125
SENSE_BLANK_CHECK = 8
126
; 9 is vendor-specific
127
SENSE_COPY_ABORTED = 10
128
SENSE_ABORTED_COMMAND = 11
129
SENSE_EQUAL = 12
130
SENSE_VOLUME_OVERFLOW = 13
131
SENSE_MISCOMPARE = 14
132
; 15 is reserved
133
 
134
; Structures of SCSI layer
135
; Result of SCSI INQUIRY request.
136
struc inquiry_data
137
{
138
.PeripheralDevice       db      ?       ; lower 5 bits are PeripheralDeviceType
139
                                        ; upper 3 bits are PeripheralQualifier
140
.RemovableMedium        db      ?       ; upper bit is RemovableMedium
141
                                        ; other bits are for compatibility
142
.Version                db      ?       ; lower 3 bits are ANSI-Approved version
143
                                        ; next 3 bits are ECMA version
144
                                        ; upper 2 bits are ISO version
145
.ResponseDataFormat     db      ?       ; lower 4 bits are ResponseDataFormat
146
                                        ; bit 6 is TrmIOP
147
                                        ; bit 7 is AENC
148
.AdditionalLength       db      ?
149
                        dw      ?       ; reserved
150
.Flags                  db      ?
151
.VendorID               rb      8       ; vendor ID, big-endian
152
.ProductID              rb      16      ; product ID, big-endian
153
.ProductRevBE           dd      ?       ; product revision, big-endian
154
.sizeof:
155
}
156
virtual at 0
157
inquiry_data inquiry_data
158
end virtual
159
 
160
struc sense_data
161
{
162
.ErrorCode              db      ?       ; lower 7 bits are error code:
163
                                        ; 70h = current error,
164
                                        ; 71h = deferred error
165
                                        ; upper bit is InformationValid
166
.SegmentNumber          db      ?       ; number of segment descriptor
167
                                        ; for commands COPY [+VERIFY], COMPARE
168
.SenseKey               db      ?       ; bits 0-3 are one of SENSE_*
169
                                        ; bit 4 is reserved
170
                                        ; bit 5 is IncorrectLengthIndicator
171
                                        ; bits 6 and 7 are used by
172
                                        ; sequential-access devices
173
.Information            dd      ?       ; command-specific
174
.AdditionalLength       db      ?       ; length of data starting here
175
.CommandInformation     dd      ?       ; command-specific
176
.AdditionalSenseCode    db      ?       ; \ more detailed error code
177
.AdditionalSenseQual    db      ?       ; / standard has a large table of them
178
.FRUCode                db      ?       ; which part of device has failed
179
                                        ; (device-specific, not regulated)
180
.SenseKeySpecific       rb      3       ; depends on SenseKey
181
.sizeof:
182
}
183
virtual at 0
184
sense_data sense_data
185
end virtual
186
 
187
; Device data
188
; USB Mass storage device has one or more logical units, identified by LUN,
189
; logical unit number. The highest value of LUN, that is, number of units
190
; minus 1, can be obtained via control request Get Max LUN.
191
virtual at 0
192
usb_device_data:
193
.ConfigPipe             dd      ?       ; configuration pipe
194
.OutPipe                dd      ?       ; pipe for OUT bulk endpoint
195
.InPipe                 dd      ?       ; pipe for IN bulk endpoint
196
.MaxLUN                 dd      ?       ; maximum Logical Unit Number
197
.LogicalDevices         dd      ?       ; pointer to array of usb_unit_data
198
; 1 for a connected USB device, 1 for each disk device
199
; the structure can be freed when .NumReferences decreases to zero
200
.NumReferences          dd      ?       ; number of references
201
.ConfigRequest          rb      8       ; buffer for configuration requests
202
.LengthRest             dd      ?       ; Length - (size of data which were transferred)
203
; All requests to a given device are serialized,
204
; only one request to a given device can be processed at a time.
205
; The current request and all pending requests are organized in the following
206
; queue, the head being the current request.
207
; NB: the queue must be device-wide due to the protocol:
208
; data stage is not tagged (unlike command_*_wrapper), so the only way to know
209
; what request the data are associated with is to guarantee that only one
210
; request is processing at the time.
211
.RequestsQueue          rd      2
212
.QueueLock              rd      3       ; protects .RequestsQueue
213
.InquiryData            inquiry_data    ; information about device
214
; data for the current request
215
.Command                command_block_wrapper
216
.DeviceDisconnected     db      ?
217
.Status                 command_status_wrapper
218
.Sense                  sense_data
219
.sizeof:
220
end virtual
221
 
222
; Information about one logical device.
223
virtual at 0
224
usb_unit_data:
225
.Parent         dd      ?       ; pointer to parent usb_device_data
226
.LUN            db      ?       ; index in usb_device_data.LogicalDevices array
227
.DiskIndex      db      ?       ; for name "usbhd"
228
.MediaPresent   db      ?
229
                db      ?       ; alignment
230
.DiskDevice     dd      ?       ; handle of disk device or NULL
231
.SectorSize     dd      ?       ; sector size
232
; For some devices, the first request to the medium fails with 'unit not ready'.
233
; When the code sees this status, it retries the command several times.
234
; Two following variables track the retry count and total time for those;
235
; total time is currently used only for debug output.
236
.UnitReadyAttempts      dd      ?
237
.TimerTicks             dd      ?
238
.sizeof:
239
end virtual
240
 
241
; This is the structure for items in the queue usb_device_data.RequestsQueue.
242
virtual at 0
243
request_queue_item:
244
.Next           dd      ?       ; next item in the queue
245
.Prev           dd      ?       ; prev item in the queue
246
.ReqBuilder     dd      ?       ; procedure to fill command_block_wrapper
247
.Buffer         dd      ?       ; input or output data
248
                                ; (length is command_block_wrapper.Length)
249
.Callback       dd      ?       ; procedure to call in the end of transfer
250
.UserData       dd      ?       ; passed as-is to .Callback
251
; There are 3 possible stages of any request, one of them optional:
252
; command stage (host sends command_block_wrapper to device),
253
; optional data stage,
254
; status stage (device sends command_status_wrapper to host).
255
; Also, if a request fails, the code queues additional request
256
; SCSI_REQUEST_SENSE; sense_data from SCSI_REQUEST_SENSE
257
; contains some information about the error.
258
.Stage          db      ?
259
.sizeof:
260
end virtual
261
 
262
section '.flat' code readable align 16
263
; The start procedure.
264
proc START
265
virtual at esp
266
        dd      ?       ; return address
267
.reason dd      ?       ; DRV_ENTRY or DRV_EXIT
268
end virtual
269
; 1. Test whether the procedure is called with the argument DRV_ENTRY.
270
; If not, return 0.
271
        xor     eax, eax        ; initialize return value
272
        cmp     [.reason], 1    ; compare the argument
273
        jnz     .nothing
274
; 2. Initialize: we have one global mutex.
275
        mov     ecx, free_numbers_lock
276
        call    MutexInit
277
; 3. Register self as a USB driver.
278
; The name is my_driver = 'usbstor'; IOCTL interface is not supported;
279
; usb_functions is an offset of a structure with callback functions.
280
        stdcall RegUSBDriver, my_driver, 0, usb_functions
281
; 4. Return the returned value of RegUSBDriver.
282
.nothing:
283
        ret     4
284
endp
285
 
286
; Helper procedures to work with requests queue.
287
 
288
; Add a request to the queue. Stdcall with 5 arguments.
289
proc queue_request
290
        push    ebx esi
291
virtual at esp
292
                rd      2       ; saved registers
293
                dd      ?       ; return address
294
.device         dd      ?       ; pointer to usb_device_data
295
.ReqBuilder     dd      ?       ; request_queue_item.ReqBuilder
296
.Buffer         dd      ?       ; request_queue_item.Buffer
297
.Callback       dd      ?       ; request_queue_item.Callback
298
.UserData       dd      ?       ; request_queue_item.UserData
299
end virtual
300
; 1. Allocate the memory for the request description.
3598 clevermous 301
        movi    eax, request_queue_item.sizeof
3520 clevermous 302
        call    Kmalloc
303
        test    eax, eax
304
        jnz     @f
305
        mov     esi, nomemory
306
        call    SysMsgBoardStr
307
        pop     esi ebx
308
        ret     20
309
@@:
310
; 2. Fill user-provided parts of the request description.
311
        push    edi
312
        xchg    eax, ebx
313
        lea     esi, [.ReqBuilder+4]
314
        lea     edi, [ebx+request_queue_item.ReqBuilder]
315
        movsd   ; ReqBuilder
316
        movsd   ; Buffer
317
        movsd   ; Callback
318
        movsd   ; UserData
319
        pop     edi
320
; 3. Set stage to zero: not started.
321
        mov     [ebx+request_queue_item.Stage], 0
322
; 4. Lock the queue.
323
        mov     esi, [.device]
324
        lea     ecx, [esi+usb_device_data.QueueLock]
325
        call    MutexLock
326
; 5. Insert the request to the tail of the queue.
327
        add     esi, usb_device_data.RequestsQueue
328
        mov     edx, [esi+request_queue_item.Prev]
329
        mov     [ebx+request_queue_item.Next], esi
330
        mov     [ebx+request_queue_item.Prev], edx
331
        mov     [edx+request_queue_item.Next], ebx
332
        mov     [esi+request_queue_item.Prev], ebx
333
; 6. Test whether the queue was empty
334
; and the request should be started immediately.
335
        cmp     [esi+request_queue_item.Next], ebx
336
        jnz     .unlock
337
; 8. If the step 6 shows that the request is the first in the queue,
338
; start it.
339
        sub     esi, usb_device_data.RequestsQueue
340
        call    setup_request
341
        jmp     .nothing
342
.unlock:
343
        call    MutexUnlock
344
; 9. Return.
345
.nothing:
346
        pop     esi ebx
347
        ret     20
348
endp
349
 
350
; The current request is completed. Call the callback,
351
; remove the request from the queue, start the next
352
; request if there is one.
353
; esi points to usb_device_data
354
proc complete_request
355
; 1. Print common debug messages on fails.
356
if DEBUG
357
        cmp     [esi+usb_device_data.Status.Status], CSW_STATUS_FAIL
358
        jb      .normal
359
        jz      .fail
360
        DEBUGF 1, 'K : Fatal error during execution of command %x\n', [esi+usb_device_data.Command.Command]:2
361
        jmp     .normal
362
.fail:
363
        DEBUGF 1, 'K : Command %x failed\n', [esi+usb_device_data.Command.Command]:2
364
.normal:
365
end if
366
; 2. Get the current request.
367
        mov     ebx, [esi+usb_device_data.RequestsQueue+request_queue_item.Next]
368
; 3. Call the callback.
369
        stdcall [ebx+request_queue_item.Callback], esi, [ebx+request_queue_item.UserData]
370
; 4. Lock the queue.
371
        lea     ecx, [esi+usb_device_data.QueueLock]
372
        call    MutexLock
373
; 5. Remove the request.
374
        lea     edx, [esi+usb_device_data.RequestsQueue]
375
        mov     eax, [ebx+request_queue_item.Next]
376
        mov     [eax+request_queue_item.Prev], edx
377
        mov     [edx+request_queue_item.Next], eax
378
; 6. Free the request memory.
379
        push    eax edx
380
        xchg    eax, ebx
381
        call    Kfree
382
        pop     edx ebx
383
; 7. If there is a next request, start processing.
384
        cmp     ebx, edx
385
        jnz     setup_request
386
; 8. Unlock the queue and return.
387
        lea     ecx, [esi+usb_device_data.QueueLock]
388
        call    MutexUnlock
389
        ret
390
endp
391
 
392
; Start processing the request. Called either by queue_request
393
; or when the previous request has been processed.
394
; Do not call directly, use queue_request.
395
; Must be called when queue is locked; unlocks the queue when returns.
396
proc setup_request
397
        xor     eax, eax
398
; 1. If DeviceDisconnected has been run, then all handles of pipes
399
; are invalid, so we must fail immediately.
400
; (That is why this function needs the locked queue: this
401
; guarantee that either DeviceDisconnected has been already run, or
402
; DeviceDisconnected will not return before the queue is unlocked.)
403
        cmp     [esi+usb_device_data.DeviceDisconnected], al
404
        jnz     .fatal
405
; 2. If the previous command has encountered a fatal error,
406
; perform reset recovery.
407
        cmp     [esi+usb_device_data.Status.Status], CSW_STATUS_FATAL
408
        jb      .norecovery
409
; 2a. Send Bulk-Only Mass Storage Reset command to config pipe.
410
        lea     edx, [esi+usb_device_data.ConfigRequest]
411
        mov     word [edx], (REQUEST_BORESET shl 8) + 21h       ; class request
412
        mov     word [edx+6], ax        ; length = 0
413
        stdcall USBControlTransferAsync, [esi+usb_device_data.ConfigPipe], edx, eax, eax, recovery_callback1, esi, eax
414
; 2b. Fail here = fatal error.
415
        test    eax, eax
416
        jz      .fatal
417
; 2c. Otherwise, unlock the queue and return. recovery_callback1 will continue processing.
418
.unlock_return:
419
        lea     ecx, [esi+usb_device_data.QueueLock]
420
        call    MutexUnlock
421
        ret
422
.norecovery:
423
; 3. Send the command. Fail (no memory or device disconnected) = fatal error.
424
; Otherwise, go to 2c.
425
        call    request_stage1
426
        test    eax, eax
427
        jnz     .unlock_return
428
.fatal:
429
; 4. Fatal error. Set status = FATAL, unlock the queue, complete the request.
430
        mov     [esi+usb_device_data.Status.Status], CSW_STATUS_FATAL
431
        lea     ecx, [esi+usb_device_data.QueueLock]
432
        call    MutexUnlock
433
        jmp     complete_request
434
endp
435
 
436
; Initiate USB transfer for the first stage of a request (send command).
437
proc request_stage1
438
        mov     ebx, [esi+usb_device_data.RequestsQueue+request_queue_item.Next]
439
; 1. Set the stage to 1 = command stage.
440
        inc     [ebx+request_queue_item.Stage]
441
; 2. Generate the command. Zero-initialize and use the caller-provided proc.
442
        lea     edx, [esi+usb_device_data.Command]
443
        xor     eax, eax
444
        mov     [edx+command_block_wrapper.CommandLength], 12
445
        mov     dword [edx+command_block_wrapper.Command], eax
446
        mov     dword [edx+command_block_wrapper.Command+4], eax
447
        mov     dword [edx+command_block_wrapper.Command+8], eax
448
        mov     dword [edx+command_block_wrapper.Command+12], eax
449
        inc     [edx+command_block_wrapper.Tag]
450
        stdcall [ebx+request_queue_item.ReqBuilder], edx, [ebx+request_queue_item.UserData]
451
; 4. Initiate USB transfer.
452
        lea     edx, [esi+usb_device_data.Command]
453
if DUMP_PACKETS
454
        DEBUGF 1,'K : USBSTOR out:'
455
        mov     eax, edx
456
        mov     ecx, command_block_wrapper.sizeof
457
        call    debug_dump
458
        DEBUGF 1,'\n'
459
end if
460
        stdcall USBNormalTransferAsync, [esi+usb_device_data.OutPipe], edx, command_block_wrapper.sizeof, request_callback1, esi, 0
461
        ret
462
endp
463
 
464
if DUMP_PACKETS
465
proc debug_dump
466
        test    ecx, ecx
467
        jz      .done
468
.loop:
469
        test    ecx, 0Fh
470
        jnz     @f
471
        DEBUGF 1,'\nK :'
472
@@:
473
        DEBUGF 1,' %x',[eax]:2
474
        inc     eax
475
        dec     ecx
476
        jnz     .loop
477
.done:
478
        ret
479
endp
480
end if
481
 
482
; Called when the Reset command is completed,
483
; either successfully or not.
484
proc recovery_callback1
485
virtual at esp
486
                dd      ?       ; return address
487
.pipe           dd      ?
488
.status         dd      ?
489
.buffer         dd      ?
490
.length         dd      ?
491
.calldata       dd      ?
492
end virtual
493
        cmp     [.status], 0
494
        jnz     .error
495
; todo: reset pipes
496
        push    ebx esi
497
        mov     esi, [.calldata+8]
498
        call    request_stage1
499
        pop     esi ebx
500
        test    eax, eax
501
        jz      .error
502
        ret     20
503
.error:
504
        DEBUGF 1, 'K : error %d while resetting', [.status]
505
        jmp     request_callback1.common_error
506
endp
507
 
508
; Called when the first stage of request is completed,
509
; either successfully or not.
510
proc request_callback1
511
virtual at esp
512
                dd      ?       ; return address
513
.pipe           dd      ?
514
.status         dd      ?
515
.buffer         dd      ?
516
.length         dd      ?
517
.calldata       dd      ?
518
end virtual
519
; 1. Initialize.
520
        mov     ecx, [.calldata]
521
        mov     eax, [.status]
522
; 2. Test for error.
523
        test    eax, eax
524
        jnz     .error
525
; No error.
526
; 3. Increment the stage.
527
        mov     edx, [ecx+usb_device_data.RequestsQueue+request_queue_item.Next]
528
        inc     [edx+request_queue_item.Stage]
529
; 4. If there is no data, skip this stage.
530
        cmp     [ecx+usb_device_data.Command.Length], 0
531
        jz      ..request_get_status
532
; 5. Initiate USB transfer. If this fails, go to the error handler.
533
        mov     eax, [ecx+usb_device_data.InPipe]
534
        cmp     [ecx+usb_device_data.Command.Flags], 0
535
        js      @f
536
        mov     eax, [ecx+usb_device_data.OutPipe]
537
if DUMP_PACKETS
538
        DEBUGF 1,'K : USBSTOR out:'
539
        push    eax ecx
540
        mov     eax, [edx+request_queue_item.Buffer]
541
        mov     ecx, [ecx+usb_device_data.Command.Length]
542
        call    debug_dump
543
        pop     ecx eax
544
        DEBUGF 1,'\n'
545
end if
546
@@:
547
        stdcall USBNormalTransferAsync, eax, [edx+request_queue_item.Buffer], [ecx+usb_device_data.Command.Length], request_callback2, ecx, 0
548
        test    eax, eax
549
        jz      .error
550
; 6. Return.
551
        ret     20
552
.error:
553
; Error.
554
; 7. Print debug message and complete the request as failed.
555
        DEBUGF 1,'K : error %d after %d bytes in request stage\n',eax,[.length]
556
.common_error:
557
; TODO: add recovery after STALL
558
        mov     ecx, [.calldata]
559
        mov     [ecx+usb_device_data.Status.Status], CSW_STATUS_FATAL
560
        push    ebx esi
561
        mov     esi, ecx
562
        call    complete_request
563
        pop     esi ebx
564
        ret     20
565
endp
566
 
567
; Called when the second stage of request is completed,
568
; either successfully or not.
569
proc request_callback2
570
virtual at esp
571
                dd      ?       ; return address
572
.pipe           dd      ?
573
.status         dd      ?
574
.buffer         dd      ?
575
.length         dd      ?
576
.calldata       dd      ?
577
end virtual
578
if DUMP_PACKETS
579
        mov     eax, [.calldata]
580
        mov     eax, [eax+usb_device_data.InPipe]
581
        cmp     [.pipe], eax
582
        jnz     @f
583
        DEBUGF 1,'K : USBSTOR in:'
584
        push    eax ecx
585
        mov     eax, [.buffer+8]
586
        mov     ecx, [.length+8]
587
        call    debug_dump
588
        pop     ecx eax
589
        DEBUGF 1,'\n'
590
@@:
591
end if
592
; 1. Initialize.
593
        mov     ecx, [.calldata]
594
        mov     eax, [.status]
595
; 2. Test for error.
596
        test    eax, eax
597
        jnz     .error
598
; No error.
599
..request_get_status:
600
; 3. Increment the stage.
601
        mov     edx, [ecx+usb_device_data.RequestsQueue+request_queue_item.Next]
602
        inc     [edx+request_queue_item.Stage]
603
; 4. Initiate USB transfer. If this fails, go to the error handler.
604
        lea     edx, [ecx+usb_device_data.Status]
605
        stdcall USBNormalTransferAsync, [ecx+usb_device_data.InPipe], edx, command_status_wrapper.sizeof, request_callback3, ecx, 0
606
        test    eax, eax
607
        jz      .error
608
        ret     20
609
.error:
610
; Error.
611
; 7. Print debug message and complete the request as failed.
612
        DEBUGF 1,'K : error %d after %d bytes in data stage\n',eax,[.length]
613
        jmp     request_callback1.common_error
614
endp
615
 
616
; Called when the third stage of request is completed,
617
; either successfully or not.
618
proc request_callback3
619
virtual at esp
620
                dd      ?       ; return address
621
.pipe           dd      ?
622
.status         dd      ?
623
.buffer         dd      ?
624
.length         dd      ?
625
.calldata       dd      ?
626
end virtual
627
if DUMP_PACKETS
628
        DEBUGF 1,'K : USBSTOR in:'
629
        mov     eax, [.buffer]
630
        mov     ecx, [.length]
631
        call    debug_dump
632
        DEBUGF 1,'\n'
633
end if
634
; 1. Initialize.
635
        mov     eax, [.status]
636
; 2. Test for error.
637
        test    eax, eax
638
        jnz     .transfer_error
639
; Transfer is OK.
640
; 3. Validate the status. Invalid status = fatal error.
641
        push    ebx esi
642
        mov     esi, [.calldata+8]
643
        mov     ebx, [esi+usb_device_data.RequestsQueue+request_queue_item.Next]
644
        cmp     [esi+usb_device_data.Status.Signature], 'USBS'
645
        jnz     .invalid
646
        mov     eax, [esi+usb_device_data.Command.Tag]
647
        cmp     [esi+usb_device_data.Status.Tag], eax
648
        jnz     .invalid
649
        cmp     [esi+usb_device_data.Status.Status], CSW_STATUS_FATAL
650
        ja      .invalid
651
; 4. The status block is valid. Check the status code.
652
        jz      .complete
653
; 5. If this command was not REQUEST_SENSE, copy status data to safe place.
654
; Otherwise, the original command has failed, so restore the fail status.
655
        cmp     byte [esi+usb_device_data.Command.Command], SCSI_REQUEST_SENSE
656
        jz      .request_sense
657
        mov     eax, [esi+usb_device_data.Status.LengthRest]
658
        mov     [esi+usb_device_data.LengthRest], eax
659
        cmp     [esi+usb_device_data.Status.Status], CSW_STATUS_FAIL
660
        jz      .fail
661
.complete:
662
        call    complete_request
663
.nothing:
664
        pop     esi ebx
665
        ret     20
666
.request_sense:
667
        mov     [esi+usb_device_data.Status.Status], CSW_STATUS_FAIL
668
        jmp     .complete
669
.invalid:
670
; 6. Invalid status block. Say error, set status to fatal and complete request.
671
        push    esi
672
        mov     esi, invresponse
673
        call    SysMsgBoardStr
674
        pop     esi
675
        mov     [esi+usb_device_data.Status.Status], CSW_STATUS_FATAL
676
        jmp     .complete
677
.fail:
678
; 7. The command has failed.
679
; If this command was not REQUEST_SENSE, schedule the REQUEST_SENSE command
680
; to determine the reason of fail. Otherwise, assume that there is no error data.
681
        cmp     [esi+usb_device_data.Command.Command], SCSI_REQUEST_SENSE
682
        jz      .fail_request_sense
683
        mov     [ebx+request_queue_item.ReqBuilder], request_sense_req
684
        lea     eax, [esi+usb_device_data.Sense]
685
        mov     [ebx+request_queue_item.Buffer], eax
686
        call    request_stage1
687
        test    eax, eax
688
        jnz     .nothing
689
.fail_request_sense:
690
        DEBUGF 1,'K : fail during REQUEST SENSE\n'
691
        mov     byte [esi+usb_device_data.Sense], 0
692
        jmp     .complete
693
.transfer_error:
694
; TODO: add recovery after STALL
695
        DEBUGF 1,'K : error %d after %d bytes in status stage\n',eax,[.length]
696
        jmp     request_callback1.common_error
697
endp
698
 
699
; Builder for SCSI_REQUEST_SENSE request.
700
; edx = first argument = pointer to usb_device_data.Command,
701
; second argument = custom data given to queue_request (ignored).
702
proc request_sense_req
703
        mov     [edx+command_block_wrapper.Length], sense_data.sizeof
704
        mov     [edx+command_block_wrapper.Flags], CBW_FLAG_IN
705
        mov     byte [edx+command_block_wrapper.Command+0], SCSI_REQUEST_SENSE
706
        mov     byte [edx+command_block_wrapper.Command+4], sense_data.sizeof
707
        ret     8
708
endp
709
 
710
; This procedure is called when new mass-storage device is detected.
711
; It initializes the device.
712
; Technically, initialization implies sending several USB queries,
713
; so it is split in several procedures. The first is AddDevice,
714
; other are callbacks which will be called at some time in the future,
715
; when the device will respond.
716
; The general scheme:
717
; * AddDevice parses descriptors, opens pipes; if everything is ok,
718
;   AddDevice sends REQUEST_GETMAXLUN with callback known_lun_callback;
719
; * known_lun_callback allocates memory for LogicalDevices and sends
720
;   SCSI_TEST_UNIT_READY to all logical devices with test_unit_ready_callback;
721
; * test_unit_ready_callback checks whether the unit is ready;
722
;   if not, it repeats the same request several times;
723
;   if ok or there were too many attempts, it sends SCSI_INQUIRY with
724
;   callback inquiry_callback;
725
; * inquiry_callback checks that a logical device is a block device
726
;   and the unit was ready; if so, it notifies the kernel about new disk device.
727
proc AddDevice
728
        push    ebx esi
729
virtual at esp
730
                rd      2       ; saved registers ebx, esi
731
                dd      ?       ; return address
732
.pipe0          dd      ?       ; handle of the config pipe
733
.config         dd      ?       ; pointer to config_descr
734
.interface      dd      ?       ; pointer to interface_descr
735
end virtual
736
; 1. Check device type. Currently only SCSI-command-set Bulk-only devices
737
; are supported.
738
; 1a. Get the subclass and the protocol. Since bInterfaceSubClass and
739
; bInterfaceProtocol are subsequent in interface_descr, just one
740
; memory reference is used for both.
741
        mov     esi, [.interface]
742
        xor     ebx, ebx
743
        mov     cx, word [esi+interface_descr.bInterfaceSubClass]
744
; 1b. For Mass-storage SCSI-command-set Bulk-only devices subclass must be 6
745
; and protocol must be 50h. Check.
746
        cmp     cx, 0x5006
747
        jz      .known
748
; There are devices with subclass 5 which use the same protocol 50h.
749
; The difference is not important for the code except for this test,
750
; so allow them to proceed also.
751
        cmp     cx, 0x5005
752
        jz      .known
753
; 1c. If the device is unknown, print a message and go to 11c.
754
        mov     esi, unkdevice
755
        call    SysMsgBoardStr
756
        jmp     .nothing
757
; 1d. If the device uses known command set, print a message and continue
758
; configuring.
759
.known:
760
        push    esi
761
        mov     esi, okdevice
762
        call    SysMsgBoardStr
763
        pop     esi
764
; 2. Allocate memory for internal device data.
765
; 2a. Call the kernel.
766
        mov     eax, usb_device_data.sizeof
767
        call    Kmalloc
768
; 2b. Check return value.
769
        test    eax, eax
770
        jnz     @f
771
; 2c. If failed, say a message and go to 11c.
772
        mov     esi, nomemory
773
        call    SysMsgBoardStr
774
        jmp     .nothing
775
@@:
776
; 2d. If succeeded, zero the contents and continue configuring.
777
        xchg    ebx, eax        ; ebx will point to usb_device_data
778
        xor     eax, eax
779
        mov     [ebx+usb_device_data.OutPipe], eax
780
        mov     [ebx+usb_device_data.InPipe], eax
781
        mov     [ebx+usb_device_data.MaxLUN], eax
782
        mov     [ebx+usb_device_data.LogicalDevices], eax
783
        mov     dword [ebx+usb_device_data.ConfigRequest], eax
784
        mov     dword [ebx+usb_device_data.ConfigRequest+4], eax
785
        mov     [ebx+usb_device_data.Status.Status], al
786
        mov     [ebx+usb_device_data.DeviceDisconnected], al
787
; 2e. There is one reference: a connected USB device.
788
        inc     eax
789
        mov     [ebx+usb_device_data.NumReferences], eax
790
; 2f. Save handle of configuration pipe for reset recovery.
791
        mov     eax, [.pipe0]
792
        mov     [ebx+usb_device_data.ConfigPipe], eax
793
; 2g. Save the interface number for configuration requests.
794
        mov     al, [esi+interface_descr.bInterfaceNumber]
795
        mov     [ebx+usb_device_data.ConfigRequest+4], al
796
; 2h. Initialize common fields in command wrapper.
797
        mov     [ebx+usb_device_data.Command.Signature], 'USBC'
798
        mov     [ebx+usb_device_data.Command.Tag], 'xxxx'
799
; 2i. Initialize requests queue.
800
        lea     eax, [ebx+usb_device_data.RequestsQueue]
801
        mov     [eax+request_queue_item.Next], eax
802
        mov     [eax+request_queue_item.Prev], eax
803
        lea     ecx, [ebx+usb_device_data.QueueLock]
804
        call    MutexInit
805
; Bulk-only mass storage devices use one OUT bulk endpoint for sending
806
; command/data and one IN bulk endpoint for receiving data/status.
807
; Look for those endpoints.
808
; 3. Get the upper bound of all descriptors' data.
809
        mov     edx, [.config]  ; configuration descriptor
810
        movzx   ecx, [edx+config_descr.wTotalLength]
811
        add     edx, ecx
812
; 4. Loop over all descriptors until
813
; either end-of-data reached - this is fail
814
; or interface descriptor found - this is fail, all further data
815
;    correspond to that interface
816
; or both endpoint descriptors found.
817
; 4a. Loop start: esi points to the interface descriptor,
818
.lookep:
819
; 4b. Get next descriptor.
820
        movzx   ecx, byte [esi] ; the first byte of all descriptors is length
821
        add     esi, ecx
822
; 4c. Check that at least two bytes are readable. The opposite is an error.
823
        inc     esi
824
        cmp     esi, edx
825
        jae     .errorep
826
        dec     esi
827
; 4d. Check that this descriptor is not interface descriptor. The opposite is
828
; an error.
829
        cmp     byte [esi+endpoint_descr.bDescriptorType], INTERFACE_DESCR_TYPE
830
        jz      .errorep
831
; 4e. Test whether this descriptor is an endpoint descriptor. If not, continue
832
; the loop.
833
        cmp     byte [esi+endpoint_descr.bDescriptorType], ENDPOINT_DESCR_TYPE
834
        jnz     .lookep
835
; 5. Check that the descriptor contains all required data and all data are
836
; readable. The opposite is an error.
837
        cmp     byte [esi+endpoint_descr.bLength], endpoint_descr.sizeof
838
        jb      .errorep
839
        lea     ecx, [esi+endpoint_descr.sizeof]
840
        cmp     ecx, edx
841
        ja      .errorep
842
; 6. Check that the endpoint is bulk endpoint. The opposite is an error.
843
        mov     cl, [esi+endpoint_descr.bmAttributes]
844
        and     cl, 3
845
        cmp     cl, BULK_PIPE
846
        jnz     .errorep
847
; 7. Get the direction of this endpoint.
848
        movzx   ecx, [esi+endpoint_descr.bEndpointAddress]
849
        shr     ecx, 7
850
; 8. Test whether a pipe for this direction is already opened. If so, continue
851
; the loop.
852
        cmp     [ebx+usb_device_data.OutPipe+ecx*4], 0
853
        jnz     .lookep
854
; 9. Open pipe for this endpoint.
855
; 9a. Save registers.
856
        push    ecx edx
857
; 9b. Load parameters from the descriptor.
858
        movzx   ecx, [esi+endpoint_descr.bEndpointAddress]
859
        movzx   edx, [esi+endpoint_descr.wMaxPacketSize]
860
        movzx   eax, [esi+endpoint_descr.bInterval]     ; not used for USB1, may be important for USB2
861
; 9c. Call the kernel.
862
        stdcall USBOpenPipe, [ebx+usb_device_data.ConfigPipe], ecx, edx, BULK_PIPE, eax
863
; 9d. Restore registers.
864
        pop     edx ecx
865
; 9e. Check result. If failed, go to 11b.
866
        test    eax, eax
867
        jz      .free
868
; 9f. Save result.
869
        mov     [ebx+usb_device_data.OutPipe+ecx*4], eax
870
; 10. Test whether the second pipe is already opened. If not, continue loop.
871
        xor     ecx, 1
872
        cmp     [ebx+usb_device_data.OutPipe+ecx*4], 0
873
        jz      .lookep
874
        jmp     .created
875
; 11. An error occured during processing endpoint descriptor.
876
.errorep:
877
; 11a. Print a message.
878
        DEBUGF 1,'K : error: invalid endpoint descriptor\n'
879
.free:
880
; 11b. Free the allocated usb_device_data.
881
        xchg    eax, ebx
882
        call    Kfree
883
.nothing:
884
; 11c. Return an error.
885
        xor     eax, eax
886
        jmp     .return
887
.created:
888
; 12. Pipes are opened. Send GetMaxLUN control request.
889
        lea     eax, [ebx+usb_device_data.ConfigRequest]
890
        mov     byte [eax], 0A1h        ; class request from interface
891
        mov     byte [eax+1], REQUEST_GETMAXLUN
892
        mov     byte [eax+6], 1         ; transfer 1 byte
893
        lea     ecx, [ebx+usb_device_data.MaxLUN]
894
if DUMP_PACKETS
895
        DEBUGF 1,'K : GETMAXLUN: %x %x %x %x %x %x %x %x\n',[eax]:2,[eax+1]:2,[eax+2]:2,[eax+3]:2,[eax+4]:2,[eax+5]:2,[eax+6]:2,[eax+7]:2
896
end if
897
        stdcall USBControlTransferAsync, [ebx+usb_device_data.ConfigPipe], eax, ecx, 1, known_lun_callback, ebx, 0
898
; 13. Return with pointer to device data as returned value.
899
        xchg    eax, ebx
900
.return:
901
        pop     esi ebx
902
        ret     12
903
endp
904
 
905
; This function is called when REQUEST_GETMAXLUN is done,
906
; either successful or unsuccessful.
907
proc known_lun_callback
908
        push    ebx esi
909
virtual at esp
910
                rd      2       ; saved registers
911
                dd      ?       ; return address
912
.pipe           dd      ?
913
.status         dd      ?
914
.buffer         dd      ?
915
.length         dd      ?
916
.calldata       dd      ?
917
end virtual
918
; 1. Check the status. If the request failed, assume that MaxLUN is zero.
919
        mov     ebx, [.calldata]
920
        mov     eax, [.status]
921
        test    eax, eax
922
        jz      @f
923
        DEBUGF 1, 'K : GETMAXLUN failed with status %d, assuming zero\n', eax
924
        mov     [ebx+usb_device_data.MaxLUN], 0
925
@@:
926
; 2. Allocate the memory for logical devices.
927
        mov     eax, [ebx+usb_device_data.MaxLUN]
928
        inc     eax
929
        DEBUGF 1,'K : %d logical unit(s)\n',eax
930
        imul    eax, usb_unit_data.sizeof
931
        push    ebx
932
        call    Kmalloc
933
        pop     ebx
934
; If failed, print a message and do nothing.
935
        test    eax, eax
936
        jnz     @f
937
        mov     esi, nomemory
938
        call    SysMsgBoardStr
939
        pop     esi ebx
940
        ret     20
941
@@:
942
        mov     [ebx+usb_device_data.LogicalDevices], eax
943
; 3. Initialize logical devices and initiate TEST_UNIT_READY request.
944
        xchg    esi, eax
945
        xor     ecx, ecx
946
.looplun:
947
        mov     [esi+usb_unit_data.Parent], ebx
948
        mov     [esi+usb_unit_data.LUN], cl
949
        xor     eax, eax
950
        mov     [esi+usb_unit_data.MediaPresent], al
951
        mov     [esi+usb_unit_data.DiskDevice], eax
952
        mov     [esi+usb_unit_data.SectorSize], eax
953
        mov     [esi+usb_unit_data.UnitReadyAttempts], eax
954
        push    ecx
955
        call    GetTimerTicks
956
        mov     [esi+usb_unit_data.TimerTicks], eax
957
        stdcall queue_request, ebx, test_unit_ready_req, 0, test_unit_ready_callback, esi
958
        pop     ecx
959
        inc     ecx
960
        add     esi, usb_unit_data.sizeof
961
        cmp     ecx, [ebx+usb_device_data.MaxLUN]
962
        jbe     .looplun
963
; 4. Return.
964
        pop     esi ebx
965
        ret     20
966
endp
967
 
968
; Builder for SCSI INQUIRY request.
969
; edx = first argument = pointer to usb_device_data.Command,
970
; second argument = custom data given to queue_request.
971
proc inquiry_req
972
        mov     eax, [esp+8]
973
        mov     al, [eax+usb_unit_data.LUN]
974
        mov     [edx+command_block_wrapper.Length], inquiry_data.sizeof
975
        mov     [edx+command_block_wrapper.Flags], CBW_FLAG_IN
976
        mov     [edx+command_block_wrapper.LUN], al
977
        mov     byte [edx+command_block_wrapper.Command+0], SCSI_INQUIRY
978
        mov     byte [edx+command_block_wrapper.Command+4], inquiry_data.sizeof
979
        ret     8
980
endp
981
 
982
; Called when SCSI INQUIRY request is completed.
983
proc inquiry_callback
984
; 1. Check the status.
985
        mov     ecx, [esp+4]
986
        cmp     [ecx+usb_device_data.Status.Status], CSW_STATUS_OK
987
        jnz     .fail
988
; 2. The command has completed successfully.
989
; Print a message showing device type, ignore anything but block devices.
990
        mov     al, [ecx+usb_device_data.InquiryData.PeripheralDevice]
991
        and     al, 1Fh
992
        DEBUGF 1,'K : peripheral device type is %x\n',al
993
        test    al, al
994
        jnz     .nothing
995
        DEBUGF 1,'K : direct-access mass storage device detected\n'
996
; 3. We have found a new disk device. Increment number of references.
997
        lock inc [ecx+usb_device_data.NumReferences]
998
; Unfortunately, we are now in the context of the USB thread,
999
; so we can't notify the kernel immediately: it would try to do something
1000
; with a new disk, those actions would be synchronous and would require
1001
; waiting for results of USB requests, but we need to exit this callback
1002
; to allow the USB thread to continue working and handling those requests.
1003
; 4. Thus, create a temporary kernel thread which would do it.
1004
        mov     edx, [esp+8]
4127 clevermous 1005
        push    ebx ecx esi edi
3598 clevermous 1006
        movi    ebx, 1
3520 clevermous 1007
        mov     ecx, new_disk_thread
1008
        ; edx = parameter
4127 clevermous 1009
        call    CreateThread
1010
        pop     edi esi ecx ebx
3520 clevermous 1011
        cmp     eax, -1
1012
        jnz     .nothing
1013
; on error, reverse step 3
1014
        lock dec [ecx+usb_device_data.NumReferences]
1015
.nothing:
1016
        ret     8
1017
.fail:
1018
; 4. The command has failed. Print a message and do nothing.
1019
        push    esi
1020
        mov     esi, inquiry_fail
1021
        call    SysMsgBoardStr
1022
        pop     esi
1023
        ret     8
1024
endp
1025
 
1026
; Builder for SCSI TEST_UNIT_READY request.
1027
; edx = first argument = pointer to usb_device_data.Command,
1028
; second argument = custom data given to queue_request.
1029
proc test_unit_ready_req
1030
        mov     eax, [esp+8]
1031
        mov     al, [eax+usb_unit_data.LUN]
1032
        mov     [edx+command_block_wrapper.Length], 0
1033
        mov     [edx+command_block_wrapper.Flags], CBW_FLAG_IN
1034
        mov     [edx+command_block_wrapper.LUN], al
1035
        ret     8
1036
endp
1037
 
1038
; Called when SCSI TEST_UNIT_READY request is completed.
1039
proc test_unit_ready_callback
1040
virtual at esp
1041
                dd      ?       ; return address
1042
.device         dd      ?
1043
.calldata       dd      ?
1044
end virtual
1045
; 1. Check the status.
1046
        mov     ecx, [.device]
1047
        mov     edx, [.calldata]
1048
        cmp     [ecx+usb_device_data.Status.Status], CSW_STATUS_OK
1049
        jnz     .fail
1050
; 2. The command has completed successfully,
1051
; possibly after some repetitions. Print a debug message showing
1052
; number and time of those. Remember that media is ready and go to 4.
1053
        DEBUGF 1,'K : media is ready\n'
1054
        call    GetTimerTicks
1055
        sub     eax, [edx+usb_unit_data.TimerTicks]
1056
        DEBUGF 1,'K : %d attempts, %d ticks\n',[edx+usb_unit_data.UnitReadyAttempts],eax
1057
        inc     [edx+usb_unit_data.MediaPresent]
1058
        jmp     .inquiry
1059
.fail:
1060
; 3. The command has failed.
1061
; Retry the same request up to 3 times with 10ms delay;
1062
; if limit of retries is not reached, exit from the function.
1063
; Otherwise, go to 4.
1064
        inc     [edx+usb_unit_data.UnitReadyAttempts]
1065
        cmp     [edx+usb_unit_data.UnitReadyAttempts], 3
1066
        jz      @f
1067
        push    ecx edx esi
3598 clevermous 1068
        movi    esi, 10
3520 clevermous 1069
        call    Sleep
1070
        pop     esi edx ecx
1071
        stdcall queue_request, ecx, test_unit_ready_req, 0, test_unit_ready_callback, edx
1072
        ret     8
1073
@@:
1074
        DEBUGF 1,'K : media not ready\n'
1075
.inquiry:
1076
; 4. initiate INQUIRY request.
1077
        lea     eax, [ecx+usb_device_data.InquiryData]
1078
        stdcall queue_request, ecx, inquiry_req, eax, inquiry_callback, edx
1079
        ret     8
1080
endp
1081
 
1082
; Temporary thread for initial actions with a new disk device.
1083
proc new_disk_thread
1084
        sub     esp, 32
1085
virtual at esp
1086
.name   rb      32      ; device name
1087
.param  dd      ?       ; contents of edx at the moment of int 0x40/eax=51
1088
        dd      ?       ; stack segment
1089
end virtual
1090
; We are ready to notify the kernel about a new disk device.
1091
        mov     esi, [.param]
1092
; 1. Generate name.
1093
; 1a. Find a free index.
1094
        mov     ecx, free_numbers_lock
1095
        call    MutexLock
1096
        xor     eax, eax
1097
@@:
1098
        bsf     edx, [free_numbers+eax]
1099
        jnz     @f
1100
        add     eax, 4
1101
        cmp     eax, 4*4
1102
        jnz     @b
1103
        call    MutexUnlock
1104
        push    esi
1105
        mov     esi, noindex
1106
        call    SysMsgBoardStr
1107
        pop     esi
1108
        jmp     .drop_reference
1109
@@:
1110
; 1b. Mark the index as busy.
1111
        btr     [free_numbers+eax], edx
1112
        lea     eax, [eax*8+edx]
1113
        push    eax
1114
        call    MutexUnlock
1115
        pop     eax
1116
; 1c. Generate a name of the form "usbhd" in the stack.
1117
        mov     dword [esp], 'usbh'
1118
        lea     edi, [esp+5]
1119
        mov     byte [edi-1], 'd'
1120
        push    eax
1121
        push    -'0'
3598 clevermous 1122
        movi    ecx, 10
3520 clevermous 1123
@@:
1124
        cdq
1125
        div     ecx
1126
        push    edx
1127
        test    eax, eax
1128
        jnz     @b
1129
@@:
1130
        pop     eax
1131
        add     al, '0'
1132
        stosb
1133
        jnz     @b
1134
        pop     ecx
1135
        mov     edx, esp
1136
; 3d. Store the index in usb_unit_data to free it later.
1137
        mov     [esi+usb_unit_data.DiskIndex], cl
1138
; 4. Notify the kernel about a new disk.
1139
; 4a. Add a disk.
1140
;       stdcall queue_request, ecx, read_capacity_req, eax, read_capacity_callback, eax
1141
        stdcall DiskAdd, disk_functions, edx, esi, 0
1142
        mov     ebx, eax
1143
; 4b. If it failed, release the index and do nothing.
1144
        test    eax, eax
1145
        jz      .free_index
1146
; 4c. Notify the kernel that a media is present.
1147
        stdcall DiskMediaChanged, eax, 1
1148
; 5. Lock the requests queue, check that device is not disconnected,
1149
; store the disk handle, unlock the requests queue.
1150
        mov     ecx, [esi+usb_unit_data.Parent]
1151
        add     ecx, usb_device_data.QueueLock
1152
        call    MutexLock
1153
        cmp     byte [ecx+usb_device_data.DeviceDisconnected-usb_device_data.QueueLock], 0
1154
        jnz     .disconnected
1155
        mov     [esi+usb_unit_data.DiskDevice], ebx
1156
        call    MutexUnlock
1157
        jmp     .exit
1158
.disconnected:
1159
        call    MutexUnlock
1160
        stdcall disk_close, ebx
1161
        jmp     .exit
1162
.free_index:
1163
        mov     ecx, free_numbers_lock
1164
        call    MutexLock
1165
        movzx   eax, [esi+usb_unit_data.DiskIndex]
1166
        bts     [free_numbers], eax
1167
        call    MutexUnlock
1168
.drop_reference:
1169
        mov     esi, [esi+usb_unit_data.Parent]
1170
        lock dec [esi+usb_device_data.NumReferences]
1171
        jnz     .exit
1172
        mov     eax, [esi+usb_device_data.LogicalDevices]
1173
        call    Kfree
1174
        xchg    eax, esi
1175
        call    Kfree
1176
.exit:
1177
        or      eax, -1
1178
        int     0x40
1179
endp
1180
 
1181
; This function is called when the device is disconnected.
1182
proc DeviceDisconnected
1183
        push    ebx esi
1184
virtual at esp
1185
        rd      2       ; saved registers
1186
        dd      ?       ; return address
1187
.device dd      ?
1188
end virtual
1189
; 1. Say a message.
1190
        mov     esi, disconnectmsg
1191
        call    SysMsgBoardStr
1192
; 2. Lock the requests queue, set .DeviceDisconnected to 1,
1193
; unlock the requests queue.
1194
; Locking is required for synchronization with queue_request:
1195
; all USB callbacks are executed in the same thread and are
1196
; synchronized automatically, but queue_request can be running
1197
; from any thread which wants to do something with a filesystem.
1198
; Without locking, it would be possible that queue_request has
1199
; been started, has checked that device is not yet disconnected,
1200
; then DeviceDisconnected completes and all handles become invalid,
1201
; then queue_request tries to use them.
1202
        mov     esi, [.device]
1203
        lea     ecx, [esi+usb_device_data.QueueLock]
1204
        call    MutexLock
1205
        mov     [esi+usb_device_data.DeviceDisconnected], 1
1206
        call    MutexUnlock
1207
; 3. Drop one reference to the structure and check whether
1208
; that was the last reference.
1209
        lock dec [esi+usb_device_data.NumReferences]
1210
        jz      .free
1211
; 4. If not, there are some additional references due to disk devices;
1212
; notify the kernel that those disks are deleted.
1213
; Note that new disks cannot be added while we are looping here,
1214
; because new_disk_thread checks for .DeviceDisconnected.
1215
        mov     ebx, [esi+usb_device_data.MaxLUN]
1216
        mov     esi, [esi+usb_device_data.LogicalDevices]
1217
        inc     ebx
1218
.diskdel:
1219
        mov     eax, [esi+usb_unit_data.DiskDevice]
1220
        test    eax, eax
1221
        jz      @f
1222
        stdcall DiskDel, eax
1223
@@:
1224
        add     esi, usb_unit_data.sizeof
1225
        dec     ebx
1226
        jnz     .diskdel
1227
; In this case, some operations with those disks are still possible,
1228
; so we can't do anything more now. disk_close will take care of the rest.
1229
.return:
1230
        pop     esi ebx
1231
        ret     4
1232
; 5. If there are no disk devices, free all resources which were allocated.
1233
.free:
1234
        mov     eax, [esi+usb_device_data.LogicalDevices]
1235
        test    eax, eax
1236
        jz      @f
1237
        call    Kfree
1238
@@:
1239
        xchg    eax, esi
1240
        call    Kfree
1241
        jmp     .return
1242
endp
1243
 
1244
; Disk functions.
1245
DISK_STATUS_OK              = 0 ; success
1246
DISK_STATUS_GENERAL_ERROR   = -1; if no other code is suitable
1247
DISK_STATUS_INVALID_CALL    = 1 ; invalid input parameters
1248
DISK_STATUS_NO_MEDIA        = 2 ; no media present
1249
DISK_STATUS_END_OF_MEDIA    = 3 ; end of media while reading/writing data
1250
 
1251
; Called when all operations with the given disk are done.
1252
proc disk_close
1253
        push    ebx esi
1254
virtual at esp
1255
        rd      2       ; saved registers
1256
        dd      ?       ; return address
1257
.userdata       dd      ?
1258
end virtual
1259
        mov     esi, [.userdata]
1260
        mov     ecx, free_numbers_lock
1261
        call    MutexLock
1262
        movzx   eax, [esi+usb_unit_data.DiskIndex]
1263
        bts     [free_numbers], eax
1264
        call    MutexUnlock
1265
        mov     esi, [esi+usb_unit_data.Parent]
1266
        lock dec [esi+usb_device_data.NumReferences]
1267
        jnz     .nothing
1268
        mov     eax, [esi+usb_device_data.LogicalDevices]
1269
        call    Kfree
1270
        xchg    eax, esi
1271
        call    Kfree
1272
.nothing:
1273
        pop     esi ebx
1274
        ret     4
1275
endp
1276
 
1277
; Returns sector size, capacity and flags of the media.
1278
proc disk_querymedia stdcall uses ebx esi edi, \
1279
        userdata:dword, mediainfo:dword
1280
; 1. Create event for waiting.
1281
        xor     esi, esi
1282
        xor     ecx, ecx
1283
        call    CreateEvent
1284
        test    eax, eax
1285
        jz      .generic_fail
1286
        push    eax
1287
        push    edx
1288
        push    ecx
1289
        push    0
1290
        push    0
1291
virtual at ebp-.localsize
1292
.locals:
1293
; two following dwords are the output of READ_CAPACITY
1294
.LastLBABE      dd      ?
1295
.SectorSizeBE   dd      ?
1296
.Status         dd      ?
1297
; two following dwords identify an event
1298
.event_code     dd      ?
1299
.event          dd      ?
1300
                rd      3       ; saved registers
1301
.localsize = $ - .locals
1302
                dd      ?       ; saved ebp
1303
                dd      ?       ; return address
1304
.userdata       dd      ?
1305
.mediainfo      dd      ?
1306
end virtual
1307
; 2. Initiate SCSI READ_CAPACITY request.
1308
        mov     eax, [userdata]
1309
        mov     ecx, [eax+usb_unit_data.Parent]
1310
        mov     edx, esp
1311
        stdcall queue_request, ecx, read_capacity_req, edx, read_capacity_callback, edx
1312
; 3. Wait for event. This destroys it.
1313
        mov     eax, [.event]
1314
        mov     ebx, [.event_code]
1315
        call    WaitEvent
1316
; 4. Get the status and results.
1317
        pop     ecx
1318
        bswap   ecx     ; .LastLBA
1319
        pop     edx
1320
        bswap   edx     ; .SectorSize
1321
        pop     eax     ; .Status
1322
; 5. If the request has completed successfully, store results.
1323
        test    eax, eax
1324
        jnz     @f
1325
        DEBUGF 1,'K : sector size is %d, last sector is %d\n',edx,ecx
1326
        mov     ebx, [mediainfo]
1327
        mov     [ebx], eax      ; flags = 0
1328
        mov     [ebx+4], edx    ; sectorsize
1329
        add     ecx, 1
1330
        adc     eax, 0
1331
        mov     [ebx+8], ecx
1332
        mov     [ebx+12], eax   ; capacity
1333
        mov     eax, [userdata]
1334
        mov     [eax+usb_unit_data.SectorSize], edx
1335
        xor     eax, eax
1336
@@:
1337
; 6. Restore the stack and return.
1338
        pop     ecx
1339
        pop     ecx
1340
        ret
1341
.generic_fail:
1342
        or      eax, -1
1343
        ret
1344
endp
1345
 
1346
; Builder for SCSI READ_CAPACITY request.
1347
; edx = first argument = pointer to usb_device_data.Command,
1348
; second argument = custom data given to queue_request,
1349
; pointer to disk_querymedia.locals.
1350
proc read_capacity_req
1351
        mov     eax, [esp+8]
1352
        mov     eax, [eax+disk_querymedia.userdata-disk_querymedia.locals]
1353
        mov     al, [eax+usb_unit_data.LUN]
1354
        mov     [edx+command_block_wrapper.Length], 8
1355
        mov     [edx+command_block_wrapper.Flags], CBW_FLAG_IN
1356
        mov     [edx+command_block_wrapper.LUN], al
1357
        mov     byte [edx+command_block_wrapper.Command+0], SCSI_READ_CAPACITY
1358
        ret     8
1359
endp
1360
 
1361
; Called when SCSI READ_CAPACITY request is completed.
1362
proc read_capacity_callback
1363
; Transform the status to return value of disk_querymedia
1364
; and set the event.
1365
        mov     ecx, [esp+4]
1366
        xor     eax, eax
1367
        cmp     [ecx+usb_device_data.Status.Status], al
1368
        jz      @f
1369
        or      eax, -1
1370
@@:
1371
        mov     ecx, [esp+8]
1372
        mov     [ecx+disk_querymedia.Status-disk_querymedia.locals], eax
1373
        push    ebx esi edi
1374
        mov     eax, [ecx+disk_querymedia.event-disk_querymedia.locals]
1375
        mov     ebx, [ecx+disk_querymedia.event_code-disk_querymedia.locals]
1376
        xor     edx, edx
1377
        xor     esi, esi
1378
        call    RaiseEvent
1379
        pop     edi esi ebx
1380
        ret     8
1381
endp
1382
 
1383
disk_write:
1384
        mov     al, SCSI_WRITE10
1385
        jmp     disk_read_write
1386
 
1387
disk_read:
1388
        mov     al, SCSI_READ10
1389
 
1390
; Reads from the device or writes to the device.
1391
proc disk_read_write stdcall uses ebx esi edi, \
1392
        userdata:dword, buffer:dword, startsector:qword, numsectors:dword
1393
; 1. Initialize.
1394
        push    eax     ; .command
1395
        mov     eax, [userdata]
1396
        mov     eax, [eax+usb_unit_data.SectorSize]
1397
        push    eax     ; .SectorSize
1398
        push    0       ; .processed
1399
        mov     eax, [numsectors]
1400
        mov     eax, [eax]
1401
; 2. The transfer length for SCSI_{READ,WRITE}10 commands can not be greater
1402
; than 0xFFFF, so split the request to slices with <= 0xFFFF sectors.
1403
max_sectors_at_time = 0xFFFF
1404
.split:
1405
        push    eax     ; .length_rest
1406
        cmp     eax, max_sectors_at_time
1407
        jb      @f
1408
        mov     eax, max_sectors_at_time
1409
@@:
1410
        sub     [esp], eax
1411
        push    eax     ; .length_cur
1412
; 3. startsector must fit in 32 bits, otherwise abort the request.
1413
        cmp     dword [startsector+4], 0
1414
        jnz     .generic_fail
1415
; 4. Create event for waiting.
1416
        xor     esi, esi
1417
        xor     ecx, ecx
1418
        call    CreateEvent
1419
        test    eax, eax
1420
        jz      .generic_fail
1421
        push    eax     ; .event
1422
        push    edx     ; .event_code
1423
        push    ecx     ; .status
1424
virtual at ebp-.localsize
1425
.locals:
1426
.status         dd      ?
1427
.event_code     dd      ?
1428
.event          dd      ?
1429
.length_cur     dd      ?
1430
.length_rest    dd      ?
1431
.processed      dd      ?
1432
.SectorSize     dd      ?
1433
.command        db      ?
1434
                rb      3
1435
                rd      3       ; saved registers
1436
.localsize = $ - .locals
1437
                dd      ?       ; saved ebp
1438
                dd      ?       ; return address
1439
.userdata       dd      ?
1440
.buffer         dd      ?
1441
.startsector    dq      ?
1442
.numsectors     dd      ?
1443
end virtual
1444
; 5. Initiate SCSI READ10 or WRITE10 request.
1445
        mov     eax, [userdata]
1446
        mov     ecx, [eax+usb_unit_data.Parent]
1447
        stdcall queue_request, ecx, read_write_req, [buffer], read_write_callback, esp
1448
; 6. Wait for event. This destroys it.
1449
        mov     eax, [.event]
1450
        mov     ebx, [.event_code]
1451
        call    WaitEvent
1452
; 7. Get the status. If the operation has failed, abort.
1453
        pop     eax     ; .status
1454
        pop     ecx ecx ; cleanup .event_code, .event
1455
        pop     ecx     ; .length_cur
1456
        test    eax, eax
1457
        jnz     .return
1458
; 8. Otherwise, continue the loop started at step 2.
1459
        add     dword [startsector], ecx
1460
        adc     dword [startsector+4], eax
1461
        imul    ecx, [.SectorSize]
1462
        add     [buffer], ecx
1463
        pop     eax
1464
        test    eax, eax
1465
        jnz     .split
1466
        push    eax
1467
.return:
1468
; 9. Restore the stack, store .processed to [numsectors], return.
1469
        pop     ecx     ; .length_rest
1470
        pop     ecx     ; .processed
1471
        mov     edx, [numsectors]
1472
        mov     [edx], ecx
1473
        pop     ecx     ; .SectorSize
1474
        pop     ecx     ; .command
1475
        ret
1476
.generic_fail:
1477
        or      eax, -1
1478
        pop     ecx     ; .length_cur
1479
        jmp     .return
1480
endp
1481
 
1482
; Builder for SCSI READ10 or WRITE10 request.
1483
; edx = first argument = pointer to usb_device_data.Command,
1484
; second argument = custom data given to queue_request,
1485
; pointer to disk_read_write.locals.
1486
proc read_write_req
1487
        mov     eax, [esp+8]
1488
        mov     ecx, [eax+disk_read_write.userdata-disk_read_write.locals]
1489
        mov     cl, [ecx+usb_unit_data.LUN]
1490
        mov     [edx+command_block_wrapper.LUN], cl
1491
        mov     ecx, [eax+disk_read_write.length_cur-disk_read_write.locals]
1492
        imul    ecx, [eax+disk_read_write.SectorSize-disk_read_write.locals]
1493
        mov     [edx+command_block_wrapper.Length], ecx
1494
        mov     cl, [eax+disk_read_write.command-disk_read_write.locals]
1495
        mov     [edx+command_block_wrapper.Flags], CBW_FLAG_OUT
1496
        cmp     cl, SCSI_READ10
1497
        jnz     @f
1498
        mov     [edx+command_block_wrapper.Flags], CBW_FLAG_IN
1499
@@:
1500
        mov     byte [edx+command_block_wrapper.Command], cl
1501
        mov     ecx, dword [eax+disk_read_write.startsector-disk_read_write.locals]
1502
        bswap   ecx
1503
        mov     dword [edx+command_block_wrapper.Command+2], ecx
1504
        mov     ecx, [eax+disk_read_write.length_cur-disk_read_write.locals]
1505
        xchg    cl, ch
1506
        mov     word [edx+command_block_wrapper.Command+7], cx
1507
        ret     8
1508
endp
1509
 
1510
; Called when SCSI READ10 or WRITE10 request is completed.
1511
proc read_write_callback
1512
; 1. Initialize.
1513
        push    ebx esi edi
1514
virtual at esp
1515
        rd      3       ; saved registers
1516
        dd      ?       ; return address
1517
.device         dd      ?
1518
.calldata       dd      ?
1519
end virtual
1520
        mov     ecx, [.device]
1521
        mov     esi, [.calldata]
1522
; 2. Get the number of sectors which were read.
1523
; If the status is OK or FAIL, the field .LengthRest is valid.
1524
; Otherwise, it is invalid, so assume zero sectors.
1525
        xor     eax, eax
1526
        cmp     [ecx+usb_device_data.Status.Status], CSW_STATUS_FAIL
1527
        ja      .sectors_calculated
1528
        mov     eax, [ecx+usb_device_data.LengthRest]
1529
        xor     edx, edx
1530
        div     [esi+disk_read_write.SectorSize-disk_read_write.locals]
1531
        test    edx, edx
1532
        jz      @f
1533
        inc     eax
1534
@@:
1535
        mov     edx, eax
1536
        mov     eax, [esi+disk_read_write.length_cur-disk_read_write.locals]
1537
        sub     eax, edx
1538
        jae     .sectors_calculated
1539
        xor     eax, eax
1540
.sectors_calculated:
1541
; 3. Increase the total number of processed sectors.
1542
        add     [esi+disk_read_write.processed-disk_read_write.locals], eax
1543
; 4. Set status to OK if all sectors were read, to ERROR otherwise.
1544
        cmp     eax, [esi+disk_read_write.length_cur-disk_read_write.locals]
1545
        setz    al
1546
        movzx   eax, al
1547
        dec     eax
1548
        mov     [esi+disk_read_write.status-disk_read_write.locals], eax
1549
; 5. Set the event.
1550
        mov     eax, [esi+disk_read_write.event-disk_read_write.locals]
1551
        mov     ebx, [esi+disk_read_write.event_code-disk_read_write.locals]
1552
        xor     edx, edx
1553
        xor     esi, esi
1554
        call    RaiseEvent
1555
; 6. Return.
1556
        pop     edi esi ebx
1557
        ret     8
1558
endp
1559
 
1560
; strings
1561
my_driver       db      'usbstor',0
1562
disconnectmsg   db      'K : USB mass storage device disconnected',13,10,0
1563
nomemory        db      'K : no memory',13,10,0
1564
unkdevice       db      'K : unknown mass storage device',13,10,0
1565
okdevice        db      'K : USB mass storage device detected',13,10,0
1566
transfererror   db      'K : USB transfer error, disabling mass storage',13,10,0
1567
invresponse     db      'K : invalid response from mass storage device',13,10,0
1568
fatalerr        db      'K : mass storage device reports fatal error',13,10,0
1569
inquiry_fail    db      'K : INQUIRY command failed',13,10,0
1570
;read_capacity_fail db  'K : READ CAPACITY command failed',13,10,0
1571
;read_fail      db      'K : READ command failed',13,10,0
1572
noindex         db      'K : failed to generate disk name',13,10,0
1573
 
1574
; Exported variable: kernel API version.
1575
align 4
1576
version dd      50005h
1577
; Structure with callback functions.
1578
usb_functions:
1579
        dd      usb_functions_end - usb_functions
1580
        dd      AddDevice
1581
        dd      DeviceDisconnected
1582
usb_functions_end:
1583
 
1584
disk_functions:
1585
        dd      disk_functions_end - disk_functions
1586
        dd      disk_close
1587
        dd      0       ; closemedia
1588
        dd      disk_querymedia
1589
        dd      disk_read
1590
        dd      disk_write
1591
        dd      0       ; flush
1592
        dd      0       ; adjust_cache_size: use default cache
1593
disk_functions_end:
1594
 
1595
free_numbers_lock       rd      3
1596
; 128 devices should be enough for everybody
1597
free_numbers    dd      -1, -1, -1, -1
1598
 
1599
; for DEBUGF macro
1600
include_debug_strings
1601
 
1602
; for uninitialized data
1603
section '.data' data readable writable align 16