Subversion Repositories Kolibri OS

Rev

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

Rev Author Line No. Line
3520 clevermous 1
; Code for OHCI controllers.
2
 
4418 clevermous 3
; Standard driver stuff
4
format PE DLL native
5
entry start
6
__DEBUG__ equ 1
7
__DEBUG_LEVEL__ equ 1
8
section '.reloc' data readable discardable fixups
9
section '.text' code readable executable
10
include '../proc32.inc'
11
include '../struct.inc'
12
include '../macros.inc'
13
include '../fdo.inc'
14
include '../../kernel/trunk/bus/usb/common.inc'
15
 
3520 clevermous 16
; =============================================================================
17
; ================================= Constants =================================
18
; =============================================================================
19
; OHCI register declarations
20
; All of the registers should be read and written as Dwords.
21
; Partition 1. Control and Status registers.
22
OhciRevisionReg         = 0
23
OhciControlReg          = 4
24
OhciCommandStatusReg    = 8
25
OhciInterruptStatusReg  = 0Ch
26
OhciInterruptEnableReg  = 10h
27
OhciInterruptDisableReg = 14h
28
; Partition 2. Memory Pointer registers.
29
OhciHCCAReg             = 18h
30
OhciPeriodCurrentEDReg  = 1Ch
31
OhciControlHeadEDReg    = 20h
32
OhciControlCurrentEDReg = 24h
33
OhciBulkHeadEDReg       = 28h
34
OhciBulkCurrentEDReg    = 2Ch
35
OhciDoneHeadReg         = 30h
36
; Partition 3. Frame Counter registers.
37
OhciFmIntervalReg       = 34h
38
OhciFmRemainingReg      = 38h
39
OhciFmNumberReg         = 3Ch
40
OhciPeriodicStartReg    = 40h
41
OhciLSThresholdReg      = 44h
42
; Partition 4. Root Hub registers.
43
OhciRhDescriptorAReg    = 48h
44
OhciRhDescriptorBReg    = 4Ch
45
OhciRhStatusReg         = 50h
46
OhciRhPortStatusReg     = 54h
47
 
48
; =============================================================================
49
; ================================ Structures =================================
50
; =============================================================================
51
 
52
; OHCI-specific part of a pipe descriptor.
53
; * This structure corresponds to the Endpoint Descriptor aka ED from the OHCI
54
;   specification.
55
; * The hardware requires 16-bytes alignment of the hardware part.
56
;   Since the allocator (usb_allocate_common) allocates memory sequentially
3653 clevermous 57
;   from page start (aligned on 0x1000 bytes), block size for the allocator
58
;   must be divisible by 16; usb1_allocate_endpoint ensures this.
3520 clevermous 59
struct ohci_pipe
60
; All addresses are physical.
61
Flags           dd      ?
62
; 1. Lower 7 bits (bits 0-6) are FunctionAddress. This is the USB address of
63
;    the function containing the endpoint that this ED controls.
64
; 2. Next 4 bits (bits 7-10) are EndpointNumber. This is the USB address of
65
;    the endpoint within the function.
66
; 3. Next 2 bits (bits 11-12) are Direction. This 2-bit field indicates the
67
;    direction of data flow: 1 = IN, 2 = OUT. If neither IN nor OUT is
68
;    specified, then the direction is determined from the PID field of the TD.
69
;    For CONTROL endpoints, the transfer direction is different
70
;    for different transfers, so the value of this field is 0
71
;    (3 would have the same effect) and the actual direction
72
;    of one transfer is encoded in the Transfer Descriptor.
73
; 4. Next bit (bit 13) is Speed bit. It indicates the speed of the endpoint:
74
;    full-speed (S = 0) or low-speed (S = 1).
75
; 5. Next bit (bit 14) is sKip bit. When this bit is set, the hardware
76
;    continues on to the next ED on the list without attempting access
77
;    to the TD queue or issuing any USB token for the endpoint.
78
;    Always cleared.
79
; 6. Next bit (bit 15) is Format bit. It must be 0 for Control, Bulk and
80
;    Interrupt endpoints and 1 for Isochronous endpoints.
81
; 7. Next 11 bits (bits 16-26) are MaximumPacketSize. This field indicates
82
;    the maximum number of bytes that can be sent to or received from the
83
;    endpoint in a single data packet.
84
TailP           dd      ?
85
; Physical address of the tail descriptor in the TD queue.
86
; The descriptor itself is not in the queue. See also HeadP.
87
HeadP           dd      ?
88
; 1. First bit (bit 0) is Halted bit. This bit is set by the hardware to
89
;    indicate that processing of the TD queue on the endpoint is halted.
90
; 2. Second bit (bit 1) is toggleCarry bit. Whenever a TD is retired, this
91
;    bit is written to contain the last data toggle value from the retired TD.
92
; 3. Next two bits (bits 2-3) are reserved and always zero.
93
; 4. With masked 4 lower bits, this is HeadP itself: physical address of the
94
;    head descriptor in the TD queue, that is, next TD to be processed for this
95
;    endpoint. Note that a TD must be 16-bytes aligned.
96
;    Empty queue is characterized by the condition HeadP == TailP.
97
NextED          dd      ?
98
; If nonzero, then this entry is a physical address of the next ED to be
99
; processed. See also the description before NextVirt field of the usb_pipe
100
; structure. Additionally to that description, the following is specific for
101
; the OHCI controller:
102
; * n=5, N=32, there are 32 "leaf" periodic lists.
103
; * The 1ms periodic list also serves Isochronous endpoints, which should be
104
;   in the end of the list.
105
; * There is no "next" list for Bulk and Control lists, they are processed
106
;   separately from others.
107
; * There is no "next" list for Periodic list for 1ms interval.
108
ends
109
 
110
; This structure describes the static head of every list of pipes.
111
; The hardware requires 16-bytes alignment of this structure.
112
; All instances of this structure are located sequentially in uhci_controller,
113
; uhci_controller is page-aligned, so it is sufficient to make this structure
114
; 16-bytes aligned and verify that the first instance is 16-bytes aligned
115
; inside uhci_controller.
116
struct ohci_static_ep
117
Flags           dd      ?
118
; Same as ohci_pipe.Flags.
119
; sKip bit is set, so the hardware ignores other fields except NextED.
120
                dd      ?
121
; Corresponds to ohci_pipe.TailP. Not used.
122
NextList        dd      ?
123
; Virtual address of the next list.
124
NextED          dd      ?
125
; Same as ohci_pipe.NextED.
126
SoftwarePart    rd      sizeof.usb_static_ep/4
127
; Software part, common for all controllers.
128
                dd      ?
129
; Padding for 16-bytes alignment.
130
ends
131
 
132
if sizeof.ohci_static_ep mod 16
133
.err ohci_static_ep must be 16-bytes aligned
134
end if
135
 
136
; OHCI-specific part of controller data.
137
; * The structure describes the memory area used for controller data,
138
;   additionally to the registers of the controller.
139
; * The structure includes two parts, the hardware part and the software part.
140
; * The hardware part consists of first 256 bytes and corresponds to
141
;   the HCCA from OHCI specification.
142
; * The hardware requires 256-bytes alignment of the hardware part, so
143
;   the entire descriptor must be 256-bytes aligned.
144
;   This structure is allocated with kernel_alloc (see usb_init_controller),
145
;   this gives page-aligned data.
146
; * The controller is described by both ohci_controller and usb_controller
147
;   structures, for each controller there is one ohci_controller and one
148
;   usb_controller structure. These structures are located sequentially
149
;   in the memory: beginning from some page start, there is ohci_controller
150
;   structure - this enforces hardware alignment requirements - and then
151
;   usb_controller structure.
152
; * The code keeps pointer to usb_controller structure. The ohci_controller
153
;   structure is addressed as [ptr + ohci_controller.field - sizeof.ohci_controller].
154
struct ohci_controller
155
; ------------------------------ hardware fields ------------------------------
156
InterruptTable  rd      32
157
; Pointers to interrupt EDs. The hardware starts processing of periodic lists
158
; within the frame N from the ED pointed to by [InterruptTable+(N and 31)*4].
159
; See also the description of periodic lists inside ohci_pipe structure.
160
FrameNumber     dw      ?
161
; The current frame number. This field is written by hardware only.
162
; This field is read by ohci_process_deferred and ohci_irq to
163
; communicate when control/bulk processing needs to be temporarily
164
; stopped/restarted.
165
                dw      ?
166
; Padding. Written as zero at every update of FrameNumber.
167
DoneHead        dd      ?
168
; Physical pointer to the start of Done Queue.
169
; When the hardware updates this field, it sets bit 0 to one if there is
170
; unmasked interrupt pending.
171
                rb      120
172
; Reserved for the hardware.
173
; ------------------------------ software fields ------------------------------
174
IntEDs          ohci_static_ep
175
                rb      62 * sizeof.ohci_static_ep
176
; Heads of 63 Periodic lists, see the description in usb_pipe.
177
ControlED       ohci_static_ep
178
; Head of Control list, see the description in usb_pipe.
179
BulkED          ohci_static_ep
180
; Head of Bulk list, see the description in usb_pipe.
181
MMIOBase        dd      ?
182
; Virtual address of memory-mapped area with OHCI registers OhciXxxReg.
183
PoweredUp       db      ?
184
; 1 in normal work, 0 during early phases of the initialization.
185
; This field is initialized to zero during memory allocation
186
; (see usb_init_controller), set to one by ohci_init when ports of the root hub
187
; are powered up, so connect/disconnect events can be handled.
188
                rb      3 ; alignment
189
DoneList        dd      ?
190
; List of descriptors which were processed by the controller and now need
191
; to be finalized.
192
DoneListEndPtr  dd      ?
193
; Pointer to dword which should receive a pointer to the next item in DoneList.
194
; If DoneList is empty, this is a pointer to DoneList itself;
195
; otherwise, this is a pointer to NextTD field of the last item in DoneList.
4418 clevermous 196
EhciCompanion   dd      ?
197
; Pointer to usb_controller for EHCI companion, if any, or NULL.
3520 clevermous 198
ends
199
 
200
if ohci_controller.IntEDs mod 16
201
.err Static endpoint descriptors must be 16-bytes aligned inside ohci_controller
202
end if
203
 
204
; OHCI general transfer descriptor.
205
; * The structure describes transfers to be performed on Control, Bulk or
206
;   Interrupt endpoints.
207
; * The structure includes two parts, the hardware part and the software part.
208
; * The hardware part consists of first 16 bytes and corresponds to
209
;   the General Transfer Descriptor aka general TD from OHCI specification.
210
; * The hardware requires 16-bytes alignment of the hardware part, so
211
;   the entire descriptor must be 16-bytes aligned. Since the allocator
212
;   (usb_allocate_common) allocates memory sequentially from page start
3653 clevermous 213
;   (aligned on 0x1000 bytes), block size for the allocator must be
214
;   divisible by 16; usb1_allocate_generic_td ensures this.
3520 clevermous 215
struct ohci_gtd
216
; ------------------------------ hardware fields ------------------------------
217
; All addresses in this part are physical.
218
Flags           dd      ?
219
; 1. Lower 18 bits (bits 0-17) are ignored and not modified by the hardware.
220
; 2. Next bit (bit 18) is bufferRounding bit. If this bit is 0, then the last
221
;    data packet must exactly fill the defined data buffer. If this bit is 1,
222
;    then the last data packet may be smaller than the defined buffer without
223
;    causing an error condition on the TD.
224
; 3. Next 2 bits (bits 19-20) are Direction field. This field indicates the
225
;    direction of data flow. If the Direction field in the ED is OUT or IN,
226
;    this field is ignored and the direction from the ED is used instead.
227
;    Otherwise, 0 = SETUP, 1 = OUT, 2 = IN, 3 is reserved.
228
; 4. Next 3 bits (bits 21-23) are DelayInterrupt field. This field contains
229
;    the interrupt delay count for this TD. When a TD is complete, the hardware
230
;    may wait up to DelayInterrupt frames before generating an interrupt.
231
;    If DelayInterrupt is 7 (maximum possible), then there is no interrupt
232
;    associated with completion of this TD.
233
; 5. Next 2 bits (bits 24-25) are DataToggle field. This field is used to
234
;    generate/compare the data PID value (DATA0 or DATA1). It is updated after
235
;    each successful transmission/reception of a data packet. The bit 25
236
;    is 0 when the data toggle value is acquired from the toggleCarry field in
237
;    the ED and 1 when the data toggle value is taken from the bit 24.
238
; 6. Next 2 bits (bits 26-27) are ErrorCount field. For each transmission
239
;    error, this value is incremented. If ErrorCount is 2 and another error
240
;    occurs, the TD is retired with error. When a transaction completes without
241
;    error, ErrorCount is reset to 0.
242
; 7. Upper 4 bits (bits 28-31) are ConditionCode field. This field contains
243
;    the status of the last attempted transaction, one of USB_STATUS_* values.
244
CurBufPtr       dd      ?
245
; Physical address of the next memory location that will be accessed for
246
; transfer to/from the endpoint. 0 means zero-length data packet or that all
247
; bytes have been transferred.
248
NextTD          dd      ?
249
; This field has different meanings depending on the status of the descriptor.
250
; When the descriptor is queued for processing, but not yet processed:
251
;   Physical address of the next TD for the endpoint.
252
; When the descriptor is processed by hardware, but not yet by software:
253
;   Physical address of the previous processed TD.
254
; When the descriptor is processed by the IRQ handler, but not yet completed:
255
;   Virtual pointer to the next processed TD.
256
BufEnd          dd      ?
257
; Physical address of the last byte in the buffer for this TD.
3711 clevermous 258
                dd      ?       ; padding to align with uhci_gtd
3520 clevermous 259
ends
260
 
261
; OHCI isochronous transfer descriptor.
262
; * The structure describes transfers to be performed on Isochronous endpoints.
263
; * The structure includes two parts, the hardware part and the software part.
264
; * The hardware part consists of first 32 bytes and corresponds to
265
;   the Isochronous Transfer Descriptor aka isochronous TD from OHCI
266
;   specification.
267
; * The hardware requires 32-bytes alignment of the hardware part, so
268
;   the entire descriptor must be 32-bytes aligned.
269
; * The isochronous endpoints are not supported yet, so only hardware part is
270
;   defined at the moment.
271
struct ohci_itd
272
StartingFrame   dw      ?
273
; This field contains the low order 16 bits of the frame number in which the
274
; first data packet of the Isochronous TD is to be sent.
275
Flags           dw      ?
276
; 1. Lower 5 bits (bits 0-4) are ignored and not modified by the hardware.
277
; 2. Next 3 bits (bits 5-7) are DelayInterrupt field.
278
; 3. Next 3 bits (bits 8-10) are FrameCount field. The TD describes
279
;    FrameCount+1 data packets.
280
; 4. Next bit (bit 11) is ignored and not modified by the hardware.
281
; 5. Upper 4 bits (bits 12-15) are ConditionCode field. This field contains
282
;    the completion code, one of USB_STATUS_* values, when the TD is moved to
283
;    the Done Queue.
284
BufPage0        dd      ?
285
; Lower 12 bits are ignored and not modified by the hardware.
286
; With masked 12 bits this field is the physical page containing all buffers.
287
NextTD          dd      ?
288
; Physical address of the next TD in the transfer queue.
289
BufEnd          dd      ?
290
; Physical address of the last byte in the buffer.
291
OffsetArray     rw      8
292
; Initialized by software, read by hardware: Offset for packet 0..7.
293
; Used to determine size and starting address of an isochronous data packet.
294
; Written by hardware, read by software: PacketStatusWord for packet 0..7.
295
; Contains completion code and, if applicable, size received for an isochronous
296
; data packet.
297
ends
298
 
299
; Description of OHCI-specific data and functions for
300
; controller-independent code.
301
; Implements the structure usb_hardware_func from hccommon.inc for OHCI.
302
iglobal
303
align 4
304
ohci_hardware_func:
4418 clevermous 305
        dd      USBHC_VERSION
3520 clevermous 306
        dd      'OHCI'
307
        dd      sizeof.ohci_controller
4418 clevermous 308
        dd      ohci_kickoff_bios
3520 clevermous 309
        dd      ohci_init
310
        dd      ohci_process_deferred
311
        dd      ohci_set_device_address
312
        dd      ohci_get_device_address
313
        dd      ohci_port_disable
314
        dd      ohci_new_port.reset
315
        dd      ohci_set_endpoint_packet_size
4418 clevermous 316
        dd      ohci_alloc_pipe
317
        dd      ohci_free_pipe
3520 clevermous 318
        dd      ohci_init_pipe
319
        dd      ohci_unlink_pipe
4418 clevermous 320
        dd      ohci_alloc_gtd
321
        dd      ohci_free_gtd
3520 clevermous 322
        dd      ohci_alloc_transfer
323
        dd      ohci_insert_transfer
324
        dd      ohci_new_device
4418 clevermous 325
ohci_name db    'OHCI',0
3520 clevermous 326
endg
327
 
328
; =============================================================================
329
; =================================== Code ====================================
330
; =============================================================================
331
 
4418 clevermous 332
; Called once when driver is loading and once at shutdown.
333
; When loading, must initialize itself, register itself in the system
334
; and return eax = value obtained when registering.
335
proc start
336
virtual at esp
337
                dd      ? ; return address
338
.reason         dd      ? ; DRV_ENTRY or DRV_EXIT
339
.cmdline        dd      ? ; normally NULL
340
end virtual
341
        cmp     [.reason], DRV_ENTRY
342
        jnz     .nothing
343
        mov     ecx, ohci_ep_mutex
344
        and     dword [ecx-4], 0
345
        invoke  MutexInit
346
        mov     ecx, ohci_gtd_mutex
347
        and     dword [ecx-4], 0
348
        invoke  MutexInit
349
        push    esi edi
350
        mov     esi, [USBHCFunc]
351
        mov     edi, usbhc_api
352
        movi    ecx, sizeof.usbhc_func/4
353
        rep movsd
354
        pop     edi esi
355
        invoke  RegUSBDriver, ohci_name, 0, ohci_hardware_func
356
.nothing:
357
        ret
358
endp
359
 
3520 clevermous 360
; Controller-specific initialization function.
361
; Called from usb_init_controller. Initializes the hardware and
362
; OHCI-specific parts of software structures.
363
; eax = pointer to ohci_controller to be initialized
364
; [ebp-4] = pcidevice
365
proc ohci_init
366
; inherit some variables from the parent (usb_init_controller)
367
.devfn   equ ebp - 4
368
.bus     equ ebp - 3
369
; 1. Store pointer to ohci_controller for further use.
370
        push    eax
371
        mov     edi, eax
372
; 2. Initialize hardware fields of ohci_controller.
373
; Namely, InterruptTable needs to be initialized with
374
; physical addresses of heads of first 32 Periodic lists.
375
; Note that all static heads fit in one page, so one call
376
; to get_pg_addr is sufficient.
377
if (ohci_controller.IntEDs / 0x1000) <> (ohci_controller.BulkED / 0x1000)
378
.err assertion failed
379
end if
380
if ohci_controller.IntEDs >= 0x1000
381
.err assertion failed
382
end if
383
        lea     esi, [eax+ohci_controller.IntEDs+32*sizeof.ohci_static_ep]
4418 clevermous 384
        invoke  GetPgAddr
3520 clevermous 385
        add     eax, ohci_controller.IntEDs
3598 clevermous 386
        movi    ecx, 32
3520 clevermous 387
        mov     edx, ecx
388
@@:
389
        stosd
390
        add     eax, sizeof.ohci_static_ep
391
        loop    @b
392
; 3. Initialize static heads ohci_controller.IntEDs, .ControlED, .BulkED.
393
; Use the loop over groups: first group consists of first 32 Periodic
394
; descriptors, next group consists of next 16 Periodic descriptors,
395
; ..., last group consists of the last Periodic descriptor.
396
; 3a. Prepare for the loop.
397
; make edi point to start of ohci_controller.IntEDs,
398
; other registers are already set.
399
; -128 fits in one byte, +128 does not fit.
400
        sub     edi, -128
401
; 3b. Loop over groups. On every iteration:
402
; edx = size of group, edi = pointer to the current group,
403
; esi = pointer to the next group, eax = physical address of the next group.
404
.init_static_eds:
405
; 3c. Get the size of the next group.
406
        shr     edx, 1
407
; 3d. Exit the loop if there is no next group.
408
        jz      .init_static_eds_done
409
; 3e. Initialize the first half of the current group.
410
; Advance edi to the second half.
411
        push    eax esi
412
        call    ohci_init_static_ep_group
413
        pop     esi eax
414
; 3f. Initialize the second half of the current group
415
; with the same values.
416
; Advance edi to the next group, esi/eax to the next of the next group.
417
        call    ohci_init_static_ep_group
418
        jmp     .init_static_eds
419
.init_static_eds_done:
420
; 3g. Initialize the head of the last Periodic list.
421
        xor     eax, eax
422
        xor     esi, esi
423
        call    ohci_init_static_endpoint
424
; 3i. Initialize the heads of Control and Bulk lists.
425
        call    ohci_init_static_endpoint
426
        call    ohci_init_static_endpoint
427
; 4. Create a virtual memory area to talk with the controller.
428
; 4a. Enable memory & bus master access.
4418 clevermous 429
        invoke  PciRead16, dword [.bus], dword [.devfn], 4
3520 clevermous 430
        or      al, 6
4418 clevermous 431
        invoke  PciWrite16, dword [.bus], dword [.devfn], 4, eax
3520 clevermous 432
; 4b. Read memory base address.
4418 clevermous 433
        invoke  PciRead32, dword [.bus], dword [.devfn], 10h
3520 clevermous 434
        and     al, not 0Fh
435
; 4c. Create mapping for physical memory. 256 bytes are sufficient.
4418 clevermous 436
        invoke  MapIoMem, eax, 100h, PG_SW+PG_NOCACHE
3520 clevermous 437
        test    eax, eax
438
        jz      .fail
439
        stosd   ; fill ohci_controller.MMIOBase
440
        xchg    eax, edi
441
; now edi = MMIOBase
442
; 5. Reset the controller if needed.
443
; 5a. Check operational state.
444
; 0 = reset, 1 = resume, 2 = operational, 3 = suspended
445
        mov     eax, [edi+OhciControlReg]
446
        and     al, 3 shl 6
447
        cmp     al, 2 shl 6
448
        jz      .operational
449
; 5b. State is not operational, reset is needed.
450
.reset:
451
; 5c. Save FmInterval register.
452
        pushd   [edi+OhciFmIntervalReg]
453
; 5d. Issue software reset and wait up to 10ms, checking status every 1 ms.
3598 clevermous 454
        movi    ecx, 1
455
        movi    edx, 10
3520 clevermous 456
        mov     [edi+OhciCommandStatusReg], ecx
457
@@:
458
        mov     esi, ecx
4418 clevermous 459
        invoke  Sleep
3520 clevermous 460
        test    [edi+OhciCommandStatusReg], ecx
461
        jz      .resetdone
462
        dec     edx
463
        jnz     @b
464
        pop     eax
465
        dbgstr 'controller reset timeout'
466
        jmp     .fail_unmap
467
.resetdone:
468
; 5e. Restore FmInterval register.
469
        pop     eax
470
        mov     edx, eax
471
        and     edx, 3FFFh
472
        jz      .setfminterval
473
        cmp     dx, 2EDFh       ; default value?
474
        jnz     @f              ; assume that BIOS has configured the value
475
.setfminterval:
476
        mov     eax, 27792EDFh  ; default value
477
@@:
478
        mov     [edi+OhciFmIntervalReg], eax
479
; 5f. Set PeriodicStart to 90% of FmInterval.
480
        movzx   eax, ax
481
; Two following lines are equivalent to eax = floor(eax * 0.9)
482
; for any 0 <= eax < 1C71C71Dh, which of course is far from maximum 0FFFFh.
483
        mov     edx, 0E6666667h
484
        mul     edx
485
        mov     [edi+OhciPeriodicStartReg], edx
486
.operational:
487
; 6. Setup controller registers.
488
        pop     esi     ; restore pointer to ohci_controller saved in step 1
489
; 6a. Physical address of HCCA.
490
        mov     eax, esi
4418 clevermous 491
        invoke  GetPgAddr
3520 clevermous 492
        mov     [edi+OhciHCCAReg], eax
493
; 6b. Transition to operational state and clear all Enable bits.
494
        mov     cl, 2 shl 6
495
        mov     [edi+OhciControlReg], ecx
496
; 6c. Physical addresses of head of Control and Bulk lists.
497
if ohci_controller.BulkED >= 0x1000
498
.err assertion failed
499
end if
500
        add     eax, ohci_controller.ControlED
501
        mov     [edi+OhciControlHeadEDReg], eax
502
        add     eax, ohci_controller.BulkED - ohci_controller.ControlED
503
        mov     [edi+OhciBulkHeadEDReg], eax
504
; 6d. Zero Head registers: there are no active Control and Bulk descriptors yet.
505
        xor     eax, eax
506
;       mov     [edi+OhciPeriodCurrentEDReg], eax
507
        mov     [edi+OhciControlCurrentEDReg], eax
508
        mov     [edi+OhciBulkCurrentEDReg], eax
509
;       mov     [edi+OhciDoneHeadReg], eax
510
; 6e. Enable processing of all lists with control:bulk ratio = 1:1.
511
        mov     dword [edi+OhciControlReg], 10111100b
4418 clevermous 512
; 7. Find the EHCI companion.
513
; Note: this assumes that EHCI is initialized before USB1 companions.
3520 clevermous 514
        add     esi, sizeof.ohci_controller
4418 clevermous 515
        mov     ebx, dword [.devfn]
516
        invoke  usbhc_api.usb_find_ehci_companion
517
        mov     [esi+ohci_controller.EhciCompanion-sizeof.ohci_controller], eax
518
; 8. Get number of ports.
3520 clevermous 519
        mov     eax, [edi+OhciRhDescriptorAReg]
520
        and     eax, 0xF
521
        mov     [esi+usb_controller.NumPorts], eax
4418 clevermous 522
; 9. Initialize DoneListEndPtr to point to DoneList.
3520 clevermous 523
        lea     eax, [esi+ohci_controller.DoneList-sizeof.ohci_controller]
524
        mov     [esi+ohci_controller.DoneListEndPtr-sizeof.ohci_controller], eax
4418 clevermous 525
; 10. Hook interrupt.
526
        invoke  PciRead8, dword [.bus], dword [.devfn], 3Ch
3520 clevermous 527
; al = IRQ
528
        movzx   eax, al
4418 clevermous 529
        invoke  AttachIntHandler, eax, ohci_irq, esi
530
; 11. Enable controller interrupt on HcDoneHead writeback and RootHubStatusChange.
3520 clevermous 531
        mov     dword [edi+OhciInterruptEnableReg], 80000042h
532
        DEBUGF 1,'K : OHCI controller at %x:%x with %d ports initialized\n',[.bus]:2,[.devfn]:2,[esi+usb_controller.NumPorts]
4418 clevermous 533
; 12. Initialize ports of the controller.
534
; 12a. Initiate power up, disable all ports, clear all "changed" bits.
3520 clevermous 535
        mov     dword [edi+OhciRhStatusReg], 10000h     ; SetGlobalPower
536
        xor     ecx, ecx
537
@@:
538
        mov     dword [edi+OhciRhPortStatusReg+ecx*4], 1F0101h  ; SetPortPower+ClearPortEnable+clear "changed" bits
539
        inc     ecx
540
        cmp     ecx, [esi+usb_controller.NumPorts]
541
        jb      @b
4418 clevermous 542
; 12b. Wait for power up.
3520 clevermous 543
; VirtualBox has AReg == 0, delay_ms doesn't like zero value; ignore zero delay
544
        push    esi
545
        mov     esi, [edi+OhciRhDescriptorAReg]
546
        shr     esi, 24
547
        add     esi, esi
548
        jz      @f
4418 clevermous 549
        invoke  Sleep
3520 clevermous 550
@@:
551
        pop     esi
4418 clevermous 552
; 12c. Ports are powered up; now it is ok to process connect/disconnect events.
3520 clevermous 553
        mov     [esi+ohci_controller.PoweredUp-sizeof.ohci_controller], 1
554
                ; IRQ handler doesn't accept connect/disconnect events before this point
4418 clevermous 555
; 12d. We could miss some events while waiting for powering up;
3520 clevermous 556
; scan all ports manually and check for connected devices.
557
        xor     ecx, ecx
558
.port_loop:
559
        test    dword [edi+OhciRhPortStatusReg+ecx*4], 1
560
        jz      .next_port
561
; There is a connected device; mark the port as 'connected'
562
; and save the connected time.
563
; Note that ConnectedTime must be set before 'connected' mark,
564
; otherwise the code in ohci_process_deferred could use incorrect time.
4418 clevermous 565
        invoke  GetTimerTicks
3520 clevermous 566
        mov     [esi+usb_controller.ConnectedTime+ecx*4], eax
567
        lock bts [esi+usb_controller.NewConnected], ecx
568
.next_port:
569
        inc     ecx
570
        cmp     ecx, [esi+usb_controller.NumPorts]
571
        jb      .port_loop
4418 clevermous 572
; 13. Return pointer to usb_controller.
3520 clevermous 573
        xchg    eax, esi
574
        ret
575
.fail_unmap:
4418 clevermous 576
; On error after step 5, release the virtual memory area.
577
        invoke  FreeKernelSpace, edi
3520 clevermous 578
.fail:
579
; On error, free the ohci_controller structure and return zero.
580
; Note that the pointer was placed in the stack at step 1.
4418 clevermous 581
; Note also that there can be no errors after step 6,
3520 clevermous 582
; where that pointer is popped from the stack.
583
        pop     ecx
584
.nothing:
585
        xor     eax, eax
586
        ret
587
endp
588
 
589
; Helper procedure for step 3 of ohci_init.
590
; Initializes the static head of one list.
591
; eax = physical address of the "next" list, esi = pointer to the "next" list,
592
; edi = pointer to head to initialize.
593
; Advances edi to the next head, keeps eax/esi.
594
proc ohci_init_static_endpoint
595
        mov     byte [edi+ohci_static_ep.Flags+1], 1 shl (14 - 8)       ; sKip this endpoint
596
        mov     [edi+ohci_static_ep.NextED], eax
597
        mov     [edi+ohci_static_ep.NextList], esi
598
        add     edi, ohci_static_ep.SoftwarePart
4418 clevermous 599
        invoke  usbhc_api.usb_init_static_endpoint
3520 clevermous 600
        add     edi, sizeof.ohci_static_ep - ohci_static_ep.SoftwarePart
601
        ret
602
endp
603
 
604
; Helper procedure for step 3 of ohci_init.
605
; Initializes one half of group of static heads.
606
; edx = size of the next group = half of size of the group,
607
; edi = pointer to the group, eax = physical address of the next group,
608
; esi = pointer to the next group.
609
; Advances eax, esi, edi to next group, keeps edx.
610
proc ohci_init_static_ep_group
611
        push    edx
612
@@:
613
        call    ohci_init_static_endpoint
614
        add     eax, sizeof.ohci_static_ep
615
        add     esi, sizeof.ohci_static_ep
616
        dec     edx
617
        jnz     @b
618
        pop     edx
619
        ret
620
endp
621
 
622
; Controller-specific pre-initialization function: take ownership from BIOS.
623
; Some BIOSes, although not all of them, provide legacy emulation
624
; for USB keyboard and/or mice as PS/2-devices. In this case,
625
; we must notify the BIOS that we don't need that emulation and know how to
626
; deal with USB devices.
627
proc ohci_kickoff_bios
628
; 1. Get the physical address of MMIO registers.
4418 clevermous 629
        invoke  PciRead32, dword [esi+PCIDEV.bus], dword [esi+PCIDEV.devfn], 10h
3520 clevermous 630
        and     al, not 0Fh
631
; 2. Create mapping for physical memory. 256 bytes are sufficient.
4418 clevermous 632
        invoke  MapIoMem, eax, 100h, PG_SW+PG_NOCACHE
3520 clevermous 633
        test    eax, eax
634
        jz      .nothing
635
; 3. Some BIOSes enable controller interrupts as a result of giving
636
; controller away. At this point the system knows nothing about how to serve
637
; OHCI interrupts, so such an interrupt will send the system into an infinite
638
; loop handling the same IRQ again and again. Thus, we need to block OHCI
639
; interrupts. We can't do this at the controller level until step 5,
640
; because the controller is currently owned by BIOS, so we block all hardware
641
; interrupts on this processor until step 5.
642
        pushf
643
        cli
644
; 4. Take the ownership over the controller.
645
; 4a. Check whether BIOS handles this controller at all.
646
        mov     edx, 100h
647
        test    dword [eax+OhciControlReg], edx
648
        jz      .has_ownership
649
; 4b. Send "take ownership" command to the BIOS.
650
; (This should generate SMI, BIOS should release its ownership in SMI handler.)
651
        mov     dword [eax+OhciCommandStatusReg], 8
652
; 4c. Wait for result no more than 50 ms, checking for status every 1 ms.
3598 clevermous 653
        movi    ecx, 50
3520 clevermous 654
@@:
655
        test    dword [eax+OhciControlReg], edx
656
        jz      .has_ownership
657
        push    esi
3598 clevermous 658
        movi    esi, 1
4418 clevermous 659
        invoke  Sleep
3520 clevermous 660
        pop     esi
661
        loop    @b
662
        dbgstr 'warning: taking OHCI ownership from BIOS timeout'
663
.has_ownership:
664
; 5. Disable all controller interrupts until the system will be ready to
665
; process them.
666
        mov     dword [eax+OhciInterruptDisableReg], 0C000007Fh
667
; 6. Now we can unblock interrupts in the processor.
668
        popf
669
; 7. Release memory mapping created in step 2 and return.
4418 clevermous 670
        invoke  FreeKernelSpace, eax
3520 clevermous 671
.nothing:
672
        ret
673
endp
674
 
675
; IRQ handler for OHCI controllers.
676
ohci_irq.noint:
677
; Not our interrupt: restore registers and return zero.
678
        xor     eax, eax
679
        pop     edi esi ebx
680
        ret
681
 
682
proc ohci_irq
683
        push    ebx esi edi     ; save used registers to be cdecl
684
virtual at esp
685
                rd      3       ; saved registers
686
                dd      ?       ; return address
687
.controller     dd      ?
688
end virtual
689
; 1. ebx will hold whether some deferred processing is needed,
690
; that cannot be done from the interrupt handler. Initialize to zero.
691
        xor     ebx, ebx
692
; 2. Get the mask of events which should be processed.
693
        mov     esi, [.controller]
694
        mov     edi, [esi+ohci_controller.MMIOBase-sizeof.ohci_controller]
695
        mov     eax, [edi+OhciInterruptStatusReg]
696
; 3. Check whether that interrupt has been generated by our controller.
697
; (One IRQ can be shared by several devices.)
698
        and     eax, [edi+OhciInterruptEnableReg]
699
        jz      .noint
700
; 4. Get the physical pointer to the last processed descriptor.
701
; All processed descriptors form single-linked list from last to first
702
; with the help of NextTD field. The list is restarted every time when
703
; the controller writes to DoneHead, so grab the pointer now (before the next
704
; step) or it could be lost (the controller could write new value to DoneHead
705
; any time after WorkDone bit is cleared in OhciInterruptStatusReg).
706
        mov     ecx, [esi+ohci_controller.DoneHead-sizeof.ohci_controller]
707
        and     ecx, not 1
708
; 5. Clear the events we know of.
709
; Note that this should be done before processing of events:
710
; new events could arise while we are processing those, this way we won't lose
711
; them (the controller would generate another interrupt
712
; after completion of this one).
713
        mov     [edi+OhciInterruptStatusReg], eax
714
; 6. Save the mask of events for further reference.
715
        push    eax
716
; 7. Handle 'transfer is done' events.
717
; 7a. Test whether there are such events.
718
        test    al, 2
719
        jz      .skip_donehead
720
; There are some 'transfer is done' events, processed descriptors are linked
721
; through physical addresses in the reverse order.
722
; We can't do much in an interrupt handler, since callbacks could require
723
; waiting for locks and that can't be done in an interrupt handler.
724
; However, we can't also just defer all work to the USB thread, since
725
; it is possible that previous lists are not yet processed and it is hard
726
; to store unlimited number of list heads. Thus, we reverse the current list,
727
; append it to end of the previous list (if there is one) and defer other
728
; processing to the USB thread; this way there always is no more than one list
729
; (possibly joined from several controller-reported lists).
730
; The list traversal requires converting physical addresses to virtual pointers,
731
; so we may as well store pointers instead of physical addresses.
732
; 7b. Prepare for the reversing loop.
733
        push    ebx
734
        xor     ebx, ebx
735
        test    ecx, ecx
736
        jz      .tddone
4418 clevermous 737
        mov     eax, [ohci_gtd_first_page]
738
        invoke  usbhc_api.usb_td_to_virt
3520 clevermous 739
        test    eax, eax
740
        jz      .tddone
741
        lea     edx, [eax+ohci_gtd.NextTD]
742
; 7c. Reverse the list, converting physical to virtual. On every iteration:
743
; ecx = physical address of the current item
744
; eax = virtual pointer to the current item
745
; edx = virtual pointer to the last item.NextTD (first in the reverse list)
746
; ebx = virtual pointer to the next item (previous in the reverse list)
747
.tdloop:
748
        mov     ecx, [eax+ohci_gtd.NextTD]
749
        mov     [eax+ohci_gtd.NextTD], ebx
3653 clevermous 750
        lea     ebx, [eax+sizeof.ohci_gtd]
3520 clevermous 751
        test    ecx, ecx
752
        jz      .tddone
4418 clevermous 753
        mov     eax, [ohci_gtd_first_page]
754
        invoke  usbhc_api.usb_td_to_virt
3520 clevermous 755
        test    eax, eax
756
        jnz     .tdloop
757
.tddone:
758
        mov     ecx, ebx
759
        pop     ebx
760
; 7d. The list is reversed,
761
; ecx = pointer to the first item, edx = pointer to the last item.NextTD.
762
; If the list is empty (unusual case), step 7 is done.
763
        test    ecx, ecx
764
        jz      .skip_donehead
765
; 7e. Otherwise, append this list to the end of previous one.
766
; Note that in theory the interrupt handler and the USB thread
767
; could execute in parallel.
768
.append_restart:
769
; Atomically get DoneListEndPtr in eax and set it to edx.
770
        mov     eax, [esi+ohci_controller.DoneListEndPtr-sizeof.ohci_controller]
771
        lock cmpxchg [esi+ohci_controller.DoneListEndPtr-sizeof.ohci_controller], edx
772
        jnz     .append_restart
773
; Store pointer to the new list.
774
; Note: we cannot perform any operations with [DoneListEndPtr]
775
; until we switch DoneListEndPtr to a new descriptor:
776
; it is possible that after first line of .append_restart loop
777
; ohci_process_deferred obtains the control, finishes processing
778
; of the old list, sets DoneListEndPtr to address of DoneList,
779
; frees all old descriptors, so eax would point to invalid location.
780
; This way, .append_restart loop would detect that DoneListEndPtr
781
; has changed, so eax needs to be re-read.
782
        mov     [eax], ecx
783
; 7f. Notify the USB thread that there is new work.
784
        inc     ebx
785
.skip_donehead:
786
; 8. Handle start-of-frame events.
787
; 8a. Test whether there are such events.
788
        test    byte [esp], 4
789
        jz      .skip_sof
790
; We enable SOF interrupt only when some pipes are waiting after changes.
791
        spin_lock_irqsave [esi+usb_controller.WaitSpinlock]
792
; 8b. Make sure that there was at least one frame update
793
; since the request. If not, wait for the next SOF.
794
        movzx   eax, [esi+ohci_controller.FrameNumber-sizeof.ohci_controller]
795
        cmp     eax, [esi+usb_controller.StartWaitFrame]
796
        jz      .sof_unlock
797
; 8c. Copy WaitPipeRequest* to ReadyPipeHead*.
798
        mov     eax, [esi+usb_controller.WaitPipeRequestAsync]
799
        mov     [esi+usb_controller.ReadyPipeHeadAsync], eax
800
        mov     eax, [esi+usb_controller.WaitPipeRequestPeriodic]
801
        mov     [esi+usb_controller.ReadyPipeHeadPeriodic], eax
802
; 8d. It is possible that pipe change is due to removal and
803
; Control/BulkCurrentED registers still point to one of pipes to be removed.
804
; The code responsible for disconnect events has temporarily stopped
805
; Control/Bulk processing, so it is safe to clear Control/BulkCurrentED.
806
; After that, restart processing.
807
        xor     edx, edx
808
        mov     [edi+OhciControlCurrentEDReg], edx
809
        mov     [edi+OhciBulkCurrentEDReg], edx
810
        mov     dword [edi+OhciCommandStatusReg], 6
811
        or      dword [edi+OhciControlReg], 30h
812
; 8e. Disable further interrupts on SOF.
813
; Note: OhciInterruptEnableReg/OhciInterruptDisableReg have unusual semantics.
814
        mov     dword [edi+OhciInterruptDisableReg], 4
815
; Notify the USB thread that there is new work (with pipes from ReadyPipeHead*).
816
        inc     ebx
817
.sof_unlock:
818
        spin_unlock_irqrestore [esi+usb_controller.RemoveSpinlock]
819
.skip_sof:
820
; Handle roothub events.
821
; 9. Test whether there are such events.
822
        test    byte [esp], 40h
823
        jz      .skip_roothub
824
; 10. Check the status of the roothub itself.
825
; 10a. Global overcurrent?
826
        test    dword [edi+OhciRhStatusReg], 2
827
        jz      @f
828
; Note: this needs work.
829
        dbgstr 'global overcurrent'
830
@@:
831
; 10b. Clear roothub events.
832
        mov     dword [edi+OhciRhStatusReg], 80020000h
833
; 11. Check the status of individual ports.
834
; Look for connect/disconnect and reset events.
835
; 11a. Prepare for the loop: start from port 0.
836
        xor     ecx, ecx
837
.portloop:
838
; 11b. Get the port status and changes of it.
839
; Accumulate change information.
840
; Look to "11.12.3 Port Change Information Processing" of the USB2 spec.
841
        xor     eax, eax
842
.accloop:
843
        mov     edx, [edi+OhciRhPortStatusReg+ecx*4]
844
        xor     ax, ax
845
        or      eax, edx
846
        test    edx, 1F0000h
847
        jz      .accdone
848
        mov     dword [edi+OhciRhPortStatusReg+ecx*4], 1F0000h
849
        jmp     .accloop
850
.accdone:
851
; debugging output, not needed for work
852
;       test    eax, 1F0000h
853
;       jz      @f
854
;       DEBUGF 1,'K : ohci irq [%d] status of port %d is %x\n',[timer_ticks],ecx,eax
855
;@@:
856
; 11c. Ignore any events until all ports are powered up.
857
; They will be processed by ohci_init.
858
        cmp     [esi+ohci_controller.PoweredUp-sizeof.ohci_controller], 0
859
        jz      .nextport
860
; Handle changing of connection status.
861
        test    eax, 10000h
862
        jz      .nocsc
863
; There was a connect or disconnect event at this port.
864
; 11d. Disconnect the old device on this port, if any.
865
; if the port was resetting, indicate fail and signal
866
        cmp     cl, [esi+usb_controller.ResettingPort]
867
        jnz     @f
868
        mov     [esi+usb_controller.ResettingStatus], -1
869
        inc     ebx
870
@@:
871
        lock bts [esi+usb_controller.NewDisconnected], ecx
872
; notify the USB thread that new work is waiting
873
        inc     ebx
874
; 11e. Change connected status. For the connection event, also
875
; store the connection time; any further processing is permitted only
876
; after USB_CONNECT_DELAY ticks.
877
        test    al, 1
878
        jz      .disconnect
879
; Note: ConnectedTime must be stored before setting the 'connected' bit,
880
; otherwise ohci_process_deferred could use an old time.
4418 clevermous 881
        invoke  GetTimerTicks
3520 clevermous 882
        mov     [esi+usb_controller.ConnectedTime+ecx*4], eax
883
        lock bts [esi+usb_controller.NewConnected], ecx
884
        jmp     .nextport
885
.disconnect:
886
        lock btr [esi+usb_controller.NewConnected], ecx
887
        jmp     .nextport
888
.nocsc:
889
; 11f. Process 'reset done' events.
890
        test    eax, 100000h
891
        jz      .nextport
892
        test    al, 10h
893
        jnz     .nextport
4418 clevermous 894
        invoke  GetTimerTicks
895
        mov     [esi+usb_controller.ResetTime], eax
3520 clevermous 896
        mov     [esi+usb_controller.ResettingStatus], 2
897
        inc     ebx
898
.nextport:
899
; 11g. Continue the loop for the next port.
900
        inc     ecx
901
        cmp     ecx, [esi+usb_controller.NumPorts]
902
        jb      .portloop
903
.skip_roothub:
904
; 12. Restore the stack after step 6.
905
        pop     eax
906
; 13. Notify the USB thread if some deferred processing is required.
4418 clevermous 907
        invoke  usbhc_api.usb_wakeup_if_needed
3520 clevermous 908
; 14. Interrupt processed; return something non-zero.
909
        mov     al, 1
910
        pop     edi esi ebx     ; restore used registers to be stdcall
911
        ret
912
endp
913
 
914
; This procedure is called from usb_set_address_callback
915
; and stores USB device address in the ohci_pipe structure.
916
; in: esi -> usb_controller, ebx -> usb_pipe, cl = address
917
proc ohci_set_device_address
3653 clevermous 918
        mov     byte [ebx+ohci_pipe.Flags-sizeof.ohci_pipe], cl
3520 clevermous 919
; Wait until the hardware will forget the old value.
4418 clevermous 920
        jmp     [usbhc_api.usb_subscribe_control]
3520 clevermous 921
endp
922
 
923
; This procedure returns USB device address from the usb_pipe structure.
924
; in: esi -> usb_controller, ebx -> usb_pipe
925
; out: eax = endpoint address
926
proc ohci_get_device_address
3653 clevermous 927
        mov     eax, [ebx+ohci_pipe.Flags-sizeof.ohci_pipe]
3520 clevermous 928
        and     eax, 7Fh
929
        ret
930
endp
931
 
932
; This procedure is called from usb_set_address_callback
933
; if the device does not accept SET_ADDRESS command and needs
934
; to be disabled at the port level.
935
; in: esi -> usb_controller, ecx = port
936
proc ohci_port_disable
937
        mov     edx, [esi+ohci_controller.MMIOBase-sizeof.ohci_controller]
938
        mov     dword [edx+OhciRhPortStatusReg+ecx*4], 1
939
        ret
940
endp
941
 
942
; This procedure is called from usb_get_descr8_callback when
943
; the packet size for zero endpoint becomes known and
944
; stores the packet size in ohci_pipe structure.
945
; in: esi -> usb_controller, ebx -> usb_pipe, ecx = packet size
946
proc ohci_set_endpoint_packet_size
3653 clevermous 947
        mov     byte [ebx+ohci_pipe.Flags+2-sizeof.ohci_pipe], cl
3520 clevermous 948
; Wait until the hardware will forget the old value.
4418 clevermous 949
        jmp     [usbhc_api.usb_subscribe_control]
3520 clevermous 950
endp
951
 
952
; This procedure is called from API usb_open_pipe and processes
953
; the controller-specific part of this API. See docs.
954
; in: edi -> usb_pipe for target, ecx -> usb_pipe for config pipe,
955
; esi -> usb_controller, eax -> usb_gtd for the first TD,
956
; [ebp+12] = endpoint, [ebp+16] = maxpacket, [ebp+20] = type
957
proc ohci_init_pipe
3816 clevermous 958
virtual at ebp-12
959
.speed          db      ?
960
                rb      3
961
.bandwidth      dd      ?
962
.target         dd      ?
963
                rd      2
3520 clevermous 964
.config_pipe    dd      ?
965
.endpoint       dd      ?
966
.maxpacket      dd      ?
967
.type           dd      ?
968
.interval       dd      ?
969
end virtual
970
; 1. Initialize the queue of transfer descriptors: empty.
3653 clevermous 971
        sub     eax, sizeof.ohci_gtd
4418 clevermous 972
        invoke  GetPhysAddr
3653 clevermous 973
        mov     [edi+ohci_pipe.TailP-sizeof.ohci_pipe], eax
974
        mov     [edi+ohci_pipe.HeadP-sizeof.ohci_pipe], eax
3520 clevermous 975
; 2. Generate ohci_pipe.Flags, see the description in ohci_pipe.
3653 clevermous 976
        mov     eax, [ecx+ohci_pipe.Flags-sizeof.ohci_pipe]
3520 clevermous 977
        and     eax, 0x207F     ; keep Speed bit and FunctionAddress
978
        mov     edx, [.endpoint]
979
        and     edx, 15
980
        shl     edx, 7
981
        or      eax, edx
3653 clevermous 982
        mov     [edi+ohci_pipe.Flags-sizeof.ohci_pipe], eax
3816 clevermous 983
        bt      eax, 13
984
        setc    [.speed]
3520 clevermous 985
        mov     eax, [.maxpacket]
3653 clevermous 986
        mov     word [edi+ohci_pipe.Flags+2-sizeof.ohci_pipe], ax
3520 clevermous 987
        cmp     [.type], CONTROL_PIPE
988
        jz      @f
989
        test    byte [.endpoint], 80h
990
        setnz   al
991
        inc     eax
992
        shl     al, 3
3653 clevermous 993
        or      byte [edi+ohci_pipe.Flags+1-sizeof.ohci_pipe], al
3520 clevermous 994
@@:
995
; 3. Insert the new pipe to the corresponding list of endpoints.
996
; 3a. Use Control list for control pipes, Bulk list for bulk pipes.
997
        lea     edx, [esi+ohci_controller.ControlED.SoftwarePart-sizeof.ohci_controller]
998
        cmp     [.type], BULK_PIPE
999
        jb      .insert ; control pipe
1000
        lea     edx, [esi+ohci_controller.BulkED.SoftwarePart-sizeof.ohci_controller]
1001
        jz      .insert ; bulk pipe
1002
.interrupt_pipe:
1003
; 3b. For interrupt pipes, let the scheduler select the appropriate list
1004
; based on the current bandwidth distribution and the requested bandwidth.
1005
; This could fail if the requested bandwidth is not available;
1006
; if so, return an error.
1007
        lea     edx, [esi + ohci_controller.IntEDs - sizeof.ohci_controller]
1008
        lea     eax, [esi + ohci_controller.IntEDs + 32*sizeof.ohci_static_ep - sizeof.ohci_controller]
3598 clevermous 1009
        movi    ecx, 64
3520 clevermous 1010
        call    usb1_select_interrupt_list
1011
        test    edx, edx
1012
        jz      .return0
1013
; 3c. Insert endpoint at edi to the head of list in edx.
1014
; Inserting to tail would work as well,
1015
; but let's be consistent with other controllers.
1016
.insert:
1017
        mov     ecx, [edx+usb_pipe.NextVirt]
1018
        mov     [edi+usb_pipe.NextVirt], ecx
1019
        mov     [edi+usb_pipe.PrevVirt], edx
1020
        mov     [ecx+usb_pipe.PrevVirt], edi
1021
        mov     [edx+usb_pipe.NextVirt], edi
3653 clevermous 1022
        mov     ecx, [edx+ohci_pipe.NextED-sizeof.ohci_pipe]
1023
        mov     [edi+ohci_pipe.NextED-sizeof.ohci_pipe], ecx
1024
        lea     eax, [edi-sizeof.ohci_pipe]
4418 clevermous 1025
        invoke  GetPhysAddr
3653 clevermous 1026
        mov     [edx+ohci_pipe.NextED-sizeof.ohci_pipe], eax
3520 clevermous 1027
; 4. Return something non-zero.
1028
        ret
1029
.return0:
1030
        xor     eax, eax
1031
        ret
1032
endp
1033
 
1034
; This function is called from ohci_process_deferred when
1035
; a new device was connected at least USB_CONNECT_DELAY ticks
1036
; and therefore is ready to be configured.
1037
; ecx = port, esi -> usb_controller
1038
proc ohci_new_port
1039
; test whether we are configuring another port
1040
; if so, postpone configuring and return
1041
        bts     [esi+usb_controller.PendingPorts], ecx
1042
        cmp     [esi+usb_controller.ResettingPort], -1
1043
        jnz     .nothing
1044
        btr     [esi+usb_controller.PendingPorts], ecx
1045
; fall through to ohci_new_port.reset
1046
 
1047
; This function is called from usb_test_pending_port.
1048
; It starts reset signalling for the port. Note that in USB first stages
1049
; of configuration can not be done for several ports in parallel.
1050
.reset:
1051
; reset port
1052
        and     [esi+usb_controller.ResettingHub], 0
1053
        mov     [esi+usb_controller.ResettingPort], cl
1054
; Note: setting status must be the last action:
1055
; it is possible that the device has been disconnected
1056
; after timeout of USB_CONNECT_DELAY but before call to ohci_new_port.
1057
; In this case, ohci_irq would not set reset status to 'failed',
1058
; because ohci_irq would not know that this port is to be reset.
1059
; However, the hardware would generate another interrupt
1060
; in a response to reset a disconnected port, and this time
1061
; ohci_irq knows that it needs to generate 'reset failed' event
1062
; (because ResettingPort is now filled).
1063
        push    edi
1064
        mov     edi, [esi+ohci_controller.MMIOBase-sizeof.ohci_controller]
1065
        mov     dword [edi+OhciRhPortStatusReg+ecx*4], 10h
1066
        pop     edi
1067
.nothing:
1068
        ret
1069
endp
1070
 
1071
; This procedure is called from the several places in main USB code
1072
; and allocates required packets for the given transfer.
1073
; ebx = pipe, other parameters are passed through the stack:
1074
; buffer,size = data to transfer
1075
; flags = same as in usb_open_pipe: bit 0 = allow short transfer, other bits reserved
1076
; td = pointer to the current end-of-queue descriptor
1077
; direction =
1078
;   0000b for normal transfers,
1079
;   1000b for control SETUP transfer,
1080
;   1101b for control OUT transfer,
1081
;   1110b for control IN transfer
1082
; returns eax = pointer to the new end-of-queue descriptor
1083
; (not included in the queue itself) or 0 on error
1084
proc ohci_alloc_transfer stdcall uses edi, \
1085
        buffer:dword, size:dword, flags:dword, td:dword, direction:dword
1086
locals
1087
origTD          dd      ?
1088
packetSize      dd      ?       ; must be the last variable, see usb_init_transfer
1089
endl
1090
; 1. Save original value of td:
1091
; it will be useful for rollback if something would fail.
1092
        mov     eax, [td]
1093
        mov     [origTD], eax
1094
; One transfer descriptor can describe up to two pages.
1095
; In the worst case (when the buffer is something*1000h+0FFFh)
1096
; this corresponds to 1001h bytes. If the requested size is
1097
; greater, we should split the transfer into several descriptors.
1098
; Boundaries to split must be multiples of endpoint transfer size
3656 clevermous 1099
; to avoid short packets except in the end of the transfer.
1100
        cmp     [size], 1001h
1101
        jbe     .lastpacket
3520 clevermous 1102
; 2. While the remaining data cannot fit in one packet,
3656 clevermous 1103
; allocate full-sized descriptors.
1104
; 2a. Calculate size of one descriptor: must be a multiple of transfer size
1105
; and must be not greater than 1001h.
1106
        movzx   ecx, word [ebx+ohci_pipe.Flags+2-sizeof.ohci_pipe]
1107
        mov     eax, 1001h
1108
        xor     edx, edx
1109
        mov     edi, eax
1110
        div     ecx
1111
        sub     edi, edx
1112
; 2b. Allocate in loop.
3520 clevermous 1113
        mov     [packetSize], edi
1114
.fullpackets:
1115
        call    ohci_alloc_packet
1116
        test    eax, eax
1117
        jz      .fail
1118
        mov     [td], eax
1119
        add     [buffer], edi
1120
        sub     [size], edi
3656 clevermous 1121
        cmp     [size], 1001h
1122
        ja      .fullpackets
3520 clevermous 1123
; 3. The remaining data can fit in one descriptor;
1124
; allocate the last descriptor with size = size of remaining data.
1125
.lastpacket:
1126
        mov     eax, [size]
1127
        mov     [packetSize], eax
1128
        call    ohci_alloc_packet
1129
        test    eax, eax
1130
        jz      .fail
1131
; 4. Enable an immediate interrupt on completion of the last packet.
3653 clevermous 1132
        and     byte [ecx+ohci_gtd.Flags+2-sizeof.ohci_gtd], not (7 shl (21-16))
3520 clevermous 1133
; 5. If a short transfer is ok for a caller, set the corresponding bit in
1134
; the last descriptor, but not in others.
1135
; Note: even if the caller says that short transfers are ok,
1136
; all packets except the last one are marked as 'must be complete':
1137
; if one of them will be short, the software intervention is needed
1138
; to skip remaining packets; ohci_process_finalized_td will handle this
1139
; transparently to the caller.
1140
        test    [flags], 1
1141
        jz      @f
3653 clevermous 1142
        or      byte [ecx+ohci_gtd.Flags+2-sizeof.ohci_gtd], 1 shl (18-16)
3520 clevermous 1143
@@:
1144
        ret
1145
.fail:
1146
        mov     edi, ohci_hardware_func
1147
        mov     eax, [td]
4418 clevermous 1148
        invoke  usbhc_api.usb_undo_tds, [origTD]
3520 clevermous 1149
        xor     eax, eax
1150
        ret
1151
endp
1152
 
1153
; Helper procedure for ohci_alloc_transfer.
1154
; Allocates and initializes one transfer descriptor.
1155
; ebx = pipe, other parameters are passed through the stack;
1156
; fills the current last descriptor and
1157
; returns eax = next descriptor (not filled).
1158
proc ohci_alloc_packet
1159
; inherit some variables from the parent ohci_alloc_transfer
1160
virtual at ebp-8
1161
.origTD         dd      ?
1162
.packetSize     dd      ?
1163
                rd      2
1164
.buffer         dd      ?
1165
.transferSize   dd      ?
1166
.Flags          dd      ?
1167
.td             dd      ?
1168
.direction      dd      ?
1169
end virtual
1170
; 1. Allocate the next TD.
4418 clevermous 1171
        call    ohci_alloc_gtd
3520 clevermous 1172
        test    eax, eax
1173
        jz      .nothing
1174
; 2. Initialize controller-independent parts of both TDs.
1175
        push    eax
4418 clevermous 1176
        invoke  usbhc_api.usb_init_transfer
3520 clevermous 1177
        pop     eax
1178
; 3. Save the returned value (next descriptor).
1179
        push    eax
1180
; 4. Store the physical address of the next descriptor.
3653 clevermous 1181
        sub     eax, sizeof.ohci_gtd
4418 clevermous 1182
        invoke  GetPhysAddr
3653 clevermous 1183
        mov     [ecx+ohci_gtd.NextTD-sizeof.ohci_gtd], eax
3520 clevermous 1184
; 5. For zero-length transfers, store zero in both fields for buffer addresses.
1185
; Otherwise, fill them with real values.
1186
        xor     eax, eax
3653 clevermous 1187
        mov     [ecx+ohci_gtd.CurBufPtr-sizeof.ohci_gtd], eax
1188
        mov     [ecx+ohci_gtd.BufEnd-sizeof.ohci_gtd], eax
3520 clevermous 1189
        cmp     [.packetSize], eax
1190
        jz      @f
1191
        mov     eax, [.buffer]
4418 clevermous 1192
        invoke  GetPhysAddr
3653 clevermous 1193
        mov     [ecx+ohci_gtd.CurBufPtr-sizeof.ohci_gtd], eax
3520 clevermous 1194
        mov     eax, [.buffer]
1195
        add     eax, [.packetSize]
1196
        dec     eax
4418 clevermous 1197
        invoke  GetPhysAddr
3653 clevermous 1198
        mov     [ecx+ohci_gtd.BufEnd-sizeof.ohci_gtd], eax
3520 clevermous 1199
@@:
1200
; 6. Generate Flags field:
1201
; - set bufferRounding (bit 18) to zero = disallow short transfers;
1202
;   for the last transfer in a row, ohci_alloc_transfer would set the real value;
1203
; - set Direction (bits 19-20) to lower 2 bits of [.direction];
1204
; - set DelayInterrupt (bits 21-23) to 7 = do not generate interrupt;
1205
;   for the last transfer in a row, ohci_alloc_transfer would set the real value;
1206
; - set DataToggle (bits 24-25) to next 2 bits of [.direction];
1207
; - set ConditionCode (bits 28-31) to 1111b as a indicator that there was no
1208
;   attempts to perform this transfer yet;
1209
; - zero all other bits.
1210
        mov     eax, [.direction]
1211
        mov     edx, eax
1212
        and     eax, 3
1213
        shl     eax, 19
1214
        and     edx, (3 shl 2)
1215
        shl     edx, 24 - 2
1216
        lea     eax, [eax + edx + (7 shl 21) + (15 shl 28)]
3653 clevermous 1217
        mov     [ecx+ohci_gtd.Flags-sizeof.ohci_gtd], eax
3520 clevermous 1218
; 7. Restore the returned value saved in step 3.
1219
        pop     eax
1220
.nothing:
1221
        ret
1222
endp
1223
 
1224
; This procedure is called from the several places in main USB code
1225
; and activates the transfer which was previously allocated by
1226
; ohci_alloc_transfer.
1227
; ecx -> last descriptor for the transfer, ebx -> usb_pipe
1228
proc ohci_insert_transfer
1229
; 1. Advance the queue of transfer descriptors.
3653 clevermous 1230
        mov     eax, [ecx+ohci_gtd.NextTD-sizeof.ohci_gtd]
1231
        mov     [ebx+ohci_pipe.TailP-sizeof.ohci_pipe], eax
3520 clevermous 1232
; 2. For control and bulk pipes, notify the controller that
1233
; there is new work in control/bulk queue respectively.
1234
ohci_notify_new_work:
1235
        mov     edx, [ebx+usb_pipe.Controller]
1236
        mov     edx, [edx+ohci_controller.MMIOBase-sizeof.ohci_controller]
1237
        cmp     [ebx+usb_pipe.Type], CONTROL_PIPE
1238
        jz      .control
1239
        cmp     [ebx+usb_pipe.Type], BULK_PIPE
1240
        jnz     .nothing
1241
.bulk:
1242
        mov     dword [edx+OhciCommandStatusReg], 4
1243
        jmp     .nothing
1244
.control:
1245
        mov     dword [edx+OhciCommandStatusReg], 2
1246
.nothing:
1247
        ret
1248
endp
1249
 
1250
; This function is called from ohci_process_deferred when
1251
; a new device has been reset and needs to be configured.
1252
proc ohci_port_after_reset
1253
; 1. Get the status.
1254
; If reset has been failed (device disconnected during reset),
1255
; continue to next device (if there is one).
1256
        xor     eax, eax
1257
        xchg    al, [esi+usb_controller.ResettingStatus]
1258
        test    al, al
4418 clevermous 1259
        jns     @f
1260
        jmp     [usbhc_api.usb_test_pending_port]
1261
@@:
3520 clevermous 1262
; If the controller has disabled the port (e.g. overcurrent),
1263
; continue to next device (if there is one).
1264
        movzx   ecx, [esi+usb_controller.ResettingPort]
1265
        mov     eax, [edi+OhciRhPortStatusReg+ecx*4]
1266
        test    al, 2
1267
        jnz     @f
1268
        DEBUGF 1,'K : USB port disabled after reset, status=%x\n',eax
4418 clevermous 1269
        jmp     [usbhc_api.usb_test_pending_port]
3520 clevermous 1270
@@:
1271
        push    ecx
1272
; 2. Get LowSpeed bit to bit 0 of eax and call the worker procedure
1273
; to notify the protocol layer about new OHCI device.
1274
        mov     eax, [edi+OhciRhPortStatusReg+ecx*4]
4418 clevermous 1275
        DEBUGF 1,'K : port_after_reset, status of port %d is %x\n',ecx,eax
3520 clevermous 1276
        shr     eax, 9
1277
        call    ohci_new_device
1278
        pop     ecx
1279
; 3. If something at the protocol layer has failed
1280
; (no memory, no bus address), disable the port and stop the initialization.
1281
        test    eax, eax
1282
        jnz     .nothing
1283
.disable_exit:
1284
        mov     dword [edi+OhciRhPortStatusReg+ecx*4], 1
4418 clevermous 1285
        jmp     [usbhc_api.usb_test_pending_port]
3520 clevermous 1286
.nothing:
1287
        ret
1288
endp
1289
 
1290
; This procedure is called from uhci_port_init and from hub support code
1291
; when a new device is connected and has been reset.
1292
; It calls usb_new_device at the protocol layer with correct parameters.
1293
; in: esi -> usb_controller, eax = speed;
1294
; OHCI is USB1 device, so only low bit of eax (LowSpeed) is used.
1295
proc ohci_new_device
1296
; 1. Clear all bits of speed except bit 0.
1297
        and     eax, 1
1298
; 2. Store the speed for the protocol layer.
1299
        mov     [esi+usb_controller.ResettingSpeed], al
1300
; 3. Create pseudo-pipe in the stack.
1301
; See ohci_init_pipe: only .Controller and .Flags fields are used.
1302
        shl     eax, 13
1303
        push    esi     ; .Controller
1304
        mov     ecx, esp
1305
        sub     esp, 12 ; ignored fields
1306
        push    eax     ; .Flags
1307
; 4. Notify the protocol layer.
4418 clevermous 1308
        invoke  usbhc_api.usb_new_device
3520 clevermous 1309
; 5. Cleanup the stack after step 3 and return.
1310
        add     esp, 20
1311
        ret
1312
endp
1313
 
1314
; This procedure is called in the USB thread from usb_thread_proc,
1315
; processes regular actions and those actions which can't be safely done
1316
; from interrupt handler.
1317
; Returns maximal time delta before the next call.
1318
proc ohci_process_deferred
1319
        push    ebx edi         ; save used registers to be stdcall
1320
; 1. Initialize the return value.
1321
        push    -1
1322
; 2. Process disconnect events.
4418 clevermous 1323
        invoke  usbhc_api.usb_disconnect_stage2
3520 clevermous 1324
; 3. Check for connected devices.
1325
; If there is a connected device which was connected less than
1326
; USB_CONNECT_DELAY ticks ago, plan to wake up when the delay will be over.
1327
; Otherwise, call ohci_new_port.
1328
        mov     edi, [esi+ohci_controller.MMIOBase-sizeof.ohci_controller]
1329
        xor     ecx, ecx
1330
        cmp     [esi+usb_controller.NewConnected], ecx
1331
        jz      .skip_newconnected
1332
.portloop:
1333
        bt      [esi+usb_controller.NewConnected], ecx
1334
        jnc     .noconnect
4418 clevermous 1335
; If this port is shared with the EHCI companion and we see the connect event,
1336
; then the device is USB1 dropped by EHCI,
1337
; so EHCI has already waited for debounce delay, we can proceed immediately.
1338
        cmp     [esi+ohci_controller.EhciCompanion-sizeof.ohci_controller], 0
1339
        jz      .portloop.test_time
1340
        dbgstr 'port is shared with EHCI, skipping initial debounce'
1341
        jmp     .connected
1342
.portloop.test_time:
1343
        invoke  GetTimerTicks
3520 clevermous 1344
        sub     eax, [esi+usb_controller.ConnectedTime+ecx*4]
1345
        sub     eax, USB_CONNECT_DELAY
1346
        jge     .connected
1347
        neg     eax
1348
        cmp     [esp], eax
1349
        jb      .nextport
1350
        mov     [esp], eax
1351
        jmp     .nextport
1352
.connected:
1353
        lock btr [esi+usb_controller.NewConnected], ecx
1354
        jnc     .nextport
1355
        call    ohci_new_port
1356
.noconnect:
1357
.nextport:
1358
        inc     ecx
1359
        cmp     ecx, [esi+usb_controller.NumPorts]
1360
        jb      .portloop
1361
.skip_newconnected:
1362
; 4. Check for end of reset signalling. If so, call ohci_port_after_reset.
1363
        cmp     [esi+usb_controller.ResettingStatus], 2
1364
        jnz     .no_reset_recovery
4418 clevermous 1365
        invoke  GetTimerTicks
3520 clevermous 1366
        sub     eax, [esi+usb_controller.ResetTime]
1367
        sub     eax, USB_RESET_RECOVERY_TIME
1368
        jge     .reset_done
1369
        neg     eax
1370
        cmp     [esp], eax
1371
        jb      .skip_roothub
1372
        mov     [esp], eax
1373
        jmp     .skip_roothub
1374
.no_reset_recovery:
1375
        cmp     [esi+usb_controller.ResettingStatus], 0
1376
        jz      .skip_roothub
1377
.reset_done:
1378
        call    ohci_port_after_reset
1379
.skip_roothub:
1380
; 5. Finalize transfers processed by hardware.
1381
; It is better to perform this step after processing disconnect events,
1382
; although not strictly obligatory. This way, an active transfer aborted
1383
; due to disconnect would be handled with more specific USB_STATUS_CLOSED,
1384
; not USB_STATUS_NORESPONSE.
1385
; Loop over all items in DoneList, call ohci_process_finalized_td for each.
1386
        xor     ebx, ebx
1387
        xchg    ebx, [esi+ohci_controller.DoneList-sizeof.ohci_controller]
1388
.tdloop:
1389
        test    ebx, ebx
1390
        jz      .tddone
1391
        call    ohci_process_finalized_td
1392
        jmp     .tdloop
1393
.tddone:
1394
; 6. Process wait-done notifications, test for new wait requests.
1395
; Note: that must be done after steps 2 and 5 which could create new requests.
1396
; 6a. Call the worker function from main USB code.
4418 clevermous 1397
        invoke  usbhc_api.usb_process_wait_lists
3520 clevermous 1398
; 6b. If no new requests, skip the rest of this step.
1399
        test    eax, eax
1400
        jz      @f
1401
; 6c. OHCI is not allowed to cache anything; we don't know what is
1402
; processed right now, but we can be sure that the controller will not
1403
; use any removed structure starting from the next frame.
1404
; Schedule SOF event.
1405
        spin_lock_irq [esi+usb_controller.RemoveSpinlock]
1406
        mov     eax, [esi+usb_controller.WaitPipeListAsync]
1407
        mov     [esi+usb_controller.WaitPipeRequestAsync], eax
1408
        mov     eax, [esi+usb_controller.WaitPipeListPeriodic]
1409
        mov     [esi+usb_controller.WaitPipeRequestPeriodic], eax
1410
; temporarily stop bulk and interrupt processing;
1411
; this is required for handler of SOF event
1412
        and     dword [edi+OhciControlReg], not 30h
1413
; remember the frame number when processing has been stopped
1414
; (needs to be done after stopping)
1415
        movzx   eax, [esi+ohci_controller.FrameNumber-sizeof.ohci_controller]
1416
        mov     [esi+usb_controller.StartWaitFrame], eax
1417
; make sure that the next SOF will happen after the request
1418
        mov     dword [edi+OhciInterruptStatusReg], 4
1419
; enable interrupt on SOF
1420
; Note: OhciInterruptEnableReg/OhciInterruptDisableReg have unusual semantics,
1421
; so there should be 'mov' here, not 'or'
1422
        mov     dword [edi+OhciInterruptEnableReg], 4
1423
        spin_unlock_irq [esi+usb_controller.RemoveSpinlock]
1424
@@:
1425
; 7. Restore the return value and return.
1426
        pop     eax
1427
        pop     edi ebx         ; restore used registers to be stdcall
1428
        ret
1429
endp
1430
 
1431
; Helper procedure for ohci_process_deferred. Processes one completed TD.
1432
; in: esi -> usb_controller, ebx -> usb_gtd, out: ebx -> next usb_gtd.
1433
proc ohci_process_finalized_td
1434
;       DEBUGF 1,'K : processing %x\n',ebx
1435
; 1. Check whether the pipe has been closed, either due to API call or due to
1436
; disconnect; if so, the callback will be called by usb_pipe_closed with
1437
; correct status, so go to step 6 with ebx = 0 (do not free the TD).
1438
        mov     edx, [ebx+usb_gtd.Pipe]
1439
        test    [edx+usb_pipe.Flags], USB_FLAG_CLOSED
1440
        jz      @f
3653 clevermous 1441
        lea     eax, [ebx+ohci_gtd.NextTD-sizeof.ohci_gtd]
3520 clevermous 1442
        xor     ebx, ebx
1443
        jmp     .next_td2
1444
@@:
1445
; 2. Remove the descriptor from the descriptors queue.
4418 clevermous 1446
        invoke  usbhc_api.usb_unlink_td
3520 clevermous 1447
; 3. Get number of bytes that remain to be transferred.
1448
; If CurBufPtr is zero, everything was transferred.
1449
        xor     edx, edx
3653 clevermous 1450
        cmp     [ebx+ohci_gtd.CurBufPtr-sizeof.ohci_gtd], edx
3520 clevermous 1451
        jz      .gotlen
1452
; Otherwise, the remaining length is
1453
; (BufEnd and 0xFFF) - (CurBufPtr and 0xFFF) + 1,
1454
; plus 0x1000 if BufEnd and CurBufPtr are in different pages.
3653 clevermous 1455
        mov     edx, [ebx+ohci_gtd.BufEnd-sizeof.ohci_gtd]
1456
        mov     eax, [ebx+ohci_gtd.CurBufPtr-sizeof.ohci_gtd]
3520 clevermous 1457
        mov     ecx, edx
1458
        and     edx, 0xFFF
1459
        inc     edx
1460
        xor     ecx, eax
1461
        and     ecx, -0x1000
1462
        jz      @f
1463
        add     edx, 0x1000
1464
@@:
1465
        and     eax, 0xFFF
1466
        sub     edx, eax
1467
.gotlen:
1468
; The actual length is Length - (remaining length).
1469
        sub     edx, [ebx+usb_gtd.Length]
1470
        neg     edx
1471
; 4. Check for error. If so, go to 7.
1472
        push    ebx
4418 clevermous 1473
        mov     ecx, [ebx+ohci_gtd.Flags-sizeof.ohci_gtd]
1474
        shr     ecx, 28
3520 clevermous 1475
        jnz     .error
1476
.notify:
1477
; 5. Successful completion.
4418 clevermous 1478
        invoke  usbhc_api.usb_process_gtd
3520 clevermous 1479
.next_td:
1480
; 6. Free the current descriptor and advance to the next item.
1481
; If the current item is the last in the list,
1482
; set DoneListEndPtr to pointer to DoneList.
1483
        cmp     ebx, [esp]
1484
        jz      @f
4418 clevermous 1485
        stdcall ohci_free_gtd, ebx
3520 clevermous 1486
@@:
1487
        pop     ebx
3653 clevermous 1488
        lea     eax, [ebx+ohci_gtd.NextTD-sizeof.ohci_gtd]
3520 clevermous 1489
.next_td2:
1490
        push    ebx
1491
        mov     ebx, eax
1492
        lea     edx, [esi+ohci_controller.DoneList-sizeof.ohci_controller]
1493
        xor     ecx, ecx        ; no next item
1494
        lock cmpxchg [esi+ohci_controller.DoneListEndPtr-sizeof.ohci_controller], edx
1495
        jz      .last
1496
; The current item is not the last.
1497
; It is possible, although very rare, that ohci_irq has already advanced
1498
; DoneListEndPtr, but not yet written NextTD. Wait until NextTD is nonzero.
1499
@@:
1500
        mov     ecx, [ebx]
1501
        test    ecx, ecx
1502
        jz      @b
1503
.last:
1504
        pop     ebx
1505
; ecx = the next item
1506
        push    ecx
1507
; Free the current item, set ebx to the next item, continue to 5a.
1508
        test    ebx, ebx
1509
        jz      @f
4418 clevermous 1510
        stdcall ohci_free_gtd, ebx
3520 clevermous 1511
@@:
1512
        pop     ebx
1513
        ret
1514
.error:
1515
; 7. There was an error while processing this descriptor.
1516
; The hardware has stopped processing the queue.
1517
; 7a. Save status and length.
4418 clevermous 1518
        push    ecx
3520 clevermous 1519
        push    edx
1520
;       DEBUGF 1,'K : TD failed:\n'
3653 clevermous 1521
;       DEBUGF 1,'K : %x %x %x %x\n',[ebx-sizeof.ohci_gtd],[ebx-sizeof.ohci_gtd+4],[ebx-sizeof.ohci_gtd+8],[ebx-sizeof.ohci_gtd+12]
1522
;       DEBUGF 1,'K : %x %x %x %x\n',[ebx-sizeof.ohci_gtd+16],[ebx-sizeof.ohci_gtd+20],[ebx-sizeof.ohci_gtd+24],[ebx-sizeof.ohci_gtd+28]
3520 clevermous 1523
;       mov     eax, [ebx+usb_gtd.Pipe]
3653 clevermous 1524
;       DEBUGF 1,'K : pipe: %x %x %x %x\n',[eax-sizeof.ohci_pipe],[eax-sizeof.ohci_pipe+4],[eax-sizeof.ohci_pipe+8],[eax-sizeof.ohci_pipe+12]
3520 clevermous 1525
; 7b. Traverse the list of descriptors looking for the final packet
1526
; for this transfer.
1527
; Free and unlink non-final descriptors, except the current one.
1528
; Final descriptor will be freed in step 6.
4418 clevermous 1529
        invoke  usbhc_api.usb_is_final_packet
3520 clevermous 1530
        jnc     .found_final
1531
        mov     ebx, [ebx+usb_gtd.NextVirt]
1532
virtual at esp
1533
.length         dd      ?
1534
.error_code     dd      ?
1535
.current_item   dd      ?
1536
end virtual
1537
.look_final:
4418 clevermous 1538
        invoke  usbhc_api.usb_unlink_td
1539
        invoke  usbhc_api.usb_is_final_packet
3520 clevermous 1540
        jnc     .found_final
1541
        push    [ebx+usb_gtd.NextVirt]
4418 clevermous 1542
        stdcall ohci_free_gtd, ebx
3520 clevermous 1543
        pop     ebx
1544
        jmp     .look_final
1545
.found_final:
1546
; 7c. If error code is USB_STATUS_UNDERRUN and the last TD allows short packets,
1547
; it is not an error.
1548
; Note: all TDs except the last one in any transfer stage are marked
1549
; as short-packet-is-error to stop controller from further processing
1550
; of that stage; we need to restart processing from a TD following the last.
1551
; After that, go to step 5 with eax = 0 (no error).
1552
        cmp     dword [.error_code], USB_STATUS_UNDERRUN
1553
        jnz     .no_underrun
3653 clevermous 1554
        test    byte [ebx+ohci_gtd.Flags+2-sizeof.ohci_gtd], 1 shl (18-16)
3520 clevermous 1555
        jz      .no_underrun
1556
        and     dword [.error_code], 0
1557
        mov     ecx, [ebx+usb_gtd.Pipe]
3653 clevermous 1558
        mov     edx, [ecx+ohci_pipe.HeadP-sizeof.ohci_pipe]
3520 clevermous 1559
        and     edx, 2
1560
.advance_queue:
1561
        mov     eax, [ebx+usb_gtd.NextVirt]
3653 clevermous 1562
        sub     eax, sizeof.ohci_gtd
4418 clevermous 1563
        invoke  GetPhysAddr
3520 clevermous 1564
        or      eax, edx
3653 clevermous 1565
        mov     [ecx+ohci_pipe.HeadP-sizeof.ohci_pipe], eax
3520 clevermous 1566
        push    ebx
1567
        mov     ebx, ecx
1568
        call    ohci_notify_new_work
1569
        pop     ebx
4418 clevermous 1570
        pop     edx ecx
3520 clevermous 1571
        jmp     .notify
1572
; 7d. Abort the entire transfer.
1573
; There are two cases: either there is only one transfer stage
1574
; (everything except control transfers), then ebx points to the last TD and
1575
; all previous TD were unlinked and dismissed (if possible),
1576
; or there are several stages (a control transfer) and ebx points to the last
1577
; TD of Data or Status stage (usb_is_final_packet does not stop in Setup stage,
1578
; because Setup stage can not produce short packets); for Data stage, we need
1579
; to unlink and free (if possible) one more TD and advance ebx to the next one.
1580
.no_underrun:
1581
        cmp     [ebx+usb_gtd.Callback], 0
1582
        jnz     .halted
1583
        cmp     ebx, [.current_item]
1584
        push    [ebx+usb_gtd.NextVirt]
1585
        jz      @f
4418 clevermous 1586
        stdcall ohci_free_gtd, ebx
3520 clevermous 1587
@@:
1588
        pop     ebx
4418 clevermous 1589
        invoke  usbhc_api.usb_unlink_td
3520 clevermous 1590
.halted:
1591
; 7e. For bulk/interrupt transfers we have no choice but halt the queue,
1592
; the driver should intercede (through some API which is not written yet).
1593
; Control pipes normally recover at the next SETUP transaction (first stage
1594
; of any control transfer), so we hope on the best and just advance the queue
1595
; to the next transfer. (According to the standard, "A control pipe may also
1596
; support functional stall as well, but this is not recommended.").
1597
; Advance the transfer queue to the next descriptor.
1598
        mov     ecx, [ebx+usb_gtd.Pipe]
3653 clevermous 1599
        mov     edx, [ecx+ohci_pipe.HeadP-sizeof.ohci_pipe]
3520 clevermous 1600
        and     edx, 2  ; keep toggleCarry bit
1601
        cmp     [ecx+usb_pipe.Type], CONTROL_PIPE
3707 clevermous 1602
        jz      @f
3520 clevermous 1603
        inc     edx     ; set Halted bit
1604
@@:
1605
        jmp     .advance_queue
1606
endp
1607
 
1608
; This procedure is called when a pipe is closing (either due to API call
1609
; or due to disconnect); it unlinks the pipe from the corresponding list.
1610
; esi -> usb_controller, ebx -> usb_pipe
1611
proc ohci_unlink_pipe
1612
        cmp     [ebx+usb_pipe.Type], INTERRUPT_PIPE
1613
        jnz     @f
3653 clevermous 1614
        mov     eax, [ebx+ohci_pipe.Flags-sizeof.ohci_pipe]
3520 clevermous 1615
        bt      eax, 13
1616
        setc    cl
1617
        bt      eax, 11
1618
        setc    ch
1619
        shr     eax, 16
1620
        stdcall usb1_interrupt_list_unlink, eax, ecx
1621
@@:
1622
        mov     edx, [ebx+usb_pipe.NextVirt]
1623
        mov     eax, [ebx+usb_pipe.PrevVirt]
1624
        mov     [edx+usb_pipe.PrevVirt], eax
1625
        mov     [eax+usb_pipe.NextVirt], edx
3653 clevermous 1626
        mov     edx, [ebx+ohci_pipe.NextED-sizeof.ohci_pipe]
1627
        mov     [eax+ohci_pipe.NextED-sizeof.ohci_pipe], edx
3520 clevermous 1628
        ret
1629
endp
4418 clevermous 1630
 
1631
; Allocates one endpoint structure for OHCI.
1632
; Returns pointer to software part (usb_pipe) in eax.
1633
proc ohci_alloc_pipe
1634
        push    ebx
1635
        mov     ebx, ohci_ep_mutex
1636
        invoke  usbhc_api.usb_allocate_common, (sizeof.ohci_pipe + sizeof.usb_pipe + 0Fh) and not 0Fh
1637
        test    eax, eax
1638
        jz      @f
1639
        add     eax, sizeof.ohci_pipe
1640
@@:
1641
        pop     ebx
1642
        ret
1643
endp
1644
 
1645
; Free one endpoint structure for OHCI.
1646
; Stdcall with one argument, pointer to software part (usb_pipe).
1647
proc ohci_free_pipe
1648
        sub     dword [esp+4], sizeof.ohci_pipe
1649
        jmp     [usbhc_api.usb_free_common]
1650
endp
1651
 
1652
; Allocates one general transfer descriptor structure for OHCI.
1653
; Returns pointer to software part (usb_gtd) in eax.
1654
proc ohci_alloc_gtd
1655
        push    ebx
1656
        mov     ebx, ohci_gtd_mutex
1657
        invoke  usbhc_api.usb_allocate_common, (sizeof.ohci_gtd + sizeof.usb_gtd + 0Fh) and not 0Fh
1658
        test    eax, eax
1659
        jz      @f
1660
        add     eax, sizeof.ohci_gtd
1661
@@:
1662
        pop     ebx
1663
        ret
1664
endp
1665
 
1666
; Free one general transfer descriptor structure for OHCI.
1667
; Stdcall with one argument, pointer to software part (usb_gtd).
1668
proc ohci_free_gtd
1669
        sub     dword [esp+4], sizeof.ohci_gtd
1670
        jmp     [usbhc_api.usb_free_common]
1671
endp
1672
 
1673
include 'usb1_scheduler.inc'
1674
define_controller_name ohci
1675
 
1676
section '.data' readable writable
1677
include '../peimport.inc'
1678
include_debug_strings
1679
IncludeIGlobals
1680
IncludeUGlobals
1681
align 4
1682
usbhc_api usbhc_func
1683
ohci_ep_first_page      dd      ?
1684
ohci_ep_mutex           MUTEX
1685
ohci_gtd_first_page     dd      ?
1686
ohci_gtd_mutex          MUTEX