Subversion Repositories Kolibri OS

Rev

Rev 3826 | 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 EHCI controllers.
2
; Note: it should be moved to an external driver,
3
; it was convenient to have this code compiled into the kernel during initial
4
; development, but there are no reasons to keep it here.
5
 
6
; =============================================================================
7
; ================================= Constants =================================
8
; =============================================================================
9
; EHCI register declarations.
10
; Part 1. Capability registers.
11
; Base is MMIO from the PCI space.
12
EhciCapLengthReg    = 0
13
EhciVersionReg      = 2
14
EhciStructParamsReg = 4
15
EhciCapParamsReg    = 8
16
EhciPortRouteReg    = 0Ch
17
; Part 2. Operational registers.
18
; Base is (base for part 1) + (value of EhciCapLengthReg).
19
EhciCommandReg      = 0
20
EhciStatusReg       = 4
21
EhciInterruptReg    = 8
22
EhciFrameIndexReg   = 0Ch
23
EhciCtrlDataSegReg  = 10h
24
EhciPeriodicListReg = 14h
25
EhciAsyncListReg    = 18h
26
EhciConfigFlagReg   = 40h
27
EhciPortsReg        = 44h
28
 
29
; Possible values of ehci_pipe.NextQH.Type bitfield.
30
EHCI_TYPE_ITD  = 0 ; isochronous transfer descriptor
31
EHCI_TYPE_QH   = 1 ; queue head
32
EHCI_TYPE_SITD = 2 ; split-transaction isochronous TD
33
EHCI_TYPE_FSTN = 3 ; frame span traversal node
34
 
35
; =============================================================================
36
; ================================ Structures =================================
37
; =============================================================================
38
 
39
; Hardware part of EHCI general transfer descriptor.
40
struct ehci_hardware_td
41
NextTD          dd      ?
42
; Bit 0 is Terminate bit, 1 = there is no next TD.
43
; Bits 1-4 must be zero.
44
; With masked 5 lower bits, this is the physical address of the next TD, if any.
45
AlternateNextTD dd      ?
46
; Similar to NextTD, used if the transfer terminates with a short packet.
47
Token           dd      ?
48
; 1. Lower byte is Status field:
49
; bit 0 = ping state for USB2 endpoints, ERR handshake signal for USB1 endpoints
50
; bit 1 = split transaction state, meaningless for USB2 endpoints
51
; bit 2 = missed micro-frame
52
; bit 3 = transaction error
53
; bit 4 = babble detected
54
; bit 5 = data buffer error
55
; bit 6 = halted
56
; bit 7 = active
57
; 2. Next two bits (bits 8-9) are PID code, 0 = OUT, 1 = IN, 2 = SETUP.
58
; 3. Next two bits (bits 10-11) is ErrorCounter. Initialized as 3, decremented
59
;    on each error; if it goes to zero, transaction is stopped.
60
; 4. Next 3 bits (bits 12-14) are CurrentPage field.
61
; 5. Next bit (bit 15) is InterruptOnComplete bit.
62
; 6. Next 15 bits (bits 16-30) are TransferLength field,
63
;    number of bytes to transfer.
64
; 7. Upper bit (bit 31) is DataToggle bit.
65
BufferPointers  rd      5
66
; The buffer to be transferred can be spanned on up to 5 physical pages.
67
; The first item of this array is the physical address of the first byte in
68
; the buffer, other items are physical addresses of next pages. Lower 12 bits
69
; in other items must be set to zero; ehci_pipe.Overlay reuses some of them.
70
BufferPointersHigh      rd      5
71
; Upper dwords of BufferPointers for controllers with 64-bit memory access.
72
; Always zero.
73
ends
74
 
75
; EHCI general transfer descriptor.
76
; * The structure describes transfers to be performed on Control, Bulk or
77
;   Interrupt endpoints.
78
; * The structure includes two parts, the hardware part and the software part.
79
; * The hardware part consists of first 52 bytes and corresponds to
80
;   the Queue Element Transfer Descriptor from EHCI specification.
81
; * The hardware requires 32-bytes alignment of the hardware part, so
82
;   the entire descriptor must be 32-bytes aligned. Since the allocator
83
;   (usb_allocate_common) allocates memory sequentially from page start
3653 clevermous 84
;   (aligned on 0x1000 bytes), block size for the allocator must be divisible
85
;   by 32; ehci_alloc_td ensures this.
3520 clevermous 86
; * The hardware also requires that the hardware part must not cross page
87
;   boundary; the allocator satisfies this automatically.
88
struct ehci_gtd ehci_hardware_td
89
Flags                   dd      ?
90
; Copy of flags from the call to usb_*_transfer_async.
91
ends
92
 
93
; EHCI-specific part of a pipe descriptor.
94
; * This structure corresponds to the Queue Head from the EHCI specification.
95
; * The hardware requires 32-bytes alignment of the hardware part.
96
;   Since the allocator (usb_allocate_common) allocates memory sequentially
3653 clevermous 97
;   from page start (aligned on 0x1000 bytes), block size for the allocator
98
;   must be divisible by 32; ehci_alloc_pipe ensures this.
3520 clevermous 99
; * The hardware requires also that the hardware part must not cross page
100
;   boundary; the allocator satisfies this automatically.
101
struct ehci_pipe
102
NextQH                  dd      ?
103
; 1. First bit (bit 0) is Terminate bit, 1 = there is no next QH.
104
; 2. Next two bits (bits 1-2) are Type field of the next QH,
105
;    one of EHCI_TYPE_* constants.
106
; 3. Next two bits (bits 3-4) are reserved, must be zero.
107
; 4. With masked 5 lower bits, this is the physical address of the next object
108
;    to be processed, usually next QH.
109
Token                   dd      ?
110
; 1. Lower 7 bits are DeviceAddress field. This is the address of the
111
;    target device on the USB bus.
112
; 2. Next bit (bit 7) is Inactivate-on-next-transaction bit. Can be nonzero
113
;    only for interrupt/isochronous USB1 endpoints.
114
; 3. Next 4 bits (bits 8-11) are Endpoint field. This is the target endpoint
115
;    number.
116
; 4. Next 2 bits (bits 12-13) are EndpointSpeed field, one of EHCI_SPEED_*.
117
; 5. Next bit (bit 14) is DataToggleControl bit,
118
;    0 = use DataToggle bit from QH, 1 = from TD.
119
; 6. Next bit (bit 15) is Head-of-reclamation-list. The head of Control list
120
;    has 1 here, all other QHs have zero.
121
; 7. Next 11 bits (bits 16-26) are MaximumPacketLength field for the target
122
;    endpoint.
123
; 8. Next bit (bit 27) is ControlEndpoint bit, must be 1 for USB1 control
124
;    endpoints and 0 for all others.
125
; 9. Upper 4 bits (bits 28-31) are NakCountReload field.
126
;    Zero for USB1 endpoints, zero for periodic endpoints.
127
;    For control/bulk USB2 endpoints, the code sets it to 4,
128
;    which is rather arbitrary.
129
Flags                   dd      ?
130
; 1. Lower byte is S-mask, each bit corresponds to one microframe per frame;
131
;    bit is set <=> enable transactions in this microframe.
132
; 2. Next byte is C-mask, each bit corresponds to one microframe per frame;
133
;    bit is set <=> enable complete-split transactions in this microframe.
134
;    Meaningful only for USB1 endpoints.
135
; 3. Next 14 bits give address of the target device as hub:port, bits 16-22
136
;    are the USB address of the hub, bits 23-29 are the port number.
137
;    Meaningful only for USB1 endpoints.
138
; 4. Upper 2 bits define number of consequetive transactions per micro-frame
139
;    which host is allowed to permit for this endpoint.
140
;    For control/bulk endpoints, it must be 1.
141
;    For periodic endpoints, the value is taken from the endpoint descriptor.
142
HeadTD                  dd      ?
143
; The physical address of the first TD for this pipe.
144
; Lower 5 bits must be zero.
145
Overlay                 ehci_hardware_td        ?
146
; Working area for the current TD, if there is any.
147
; When TD is retired, it is written to that TD and Overlay is loaded
148
; from the new TD, if any.
149
BaseList                dd      ?
150
; Pointer to head of the corresponding pipe list.
151
ends
152
 
153
; This structure describes the static head of every list of pipes.
154
; The hardware requires 32-bytes alignment of this structure.
155
; All instances of this structure are located sequentially in ehci_controller,
156
; ehci_controller is page-aligned, so it is sufficient to make this structure
157
; 32-bytes aligned and verify that the first instance is 32-bytes aligned
158
; inside ehci_controller.
159
; The hardware also requires that 44h bytes (size of 64-bit Queue Head
160
; Descriptor) starting at the beginning of this structure must not cross page
161
; boundary. If not, most hardware still behaves correctly (in fact, the last
162
; dword can have any value and this structure is never written), but on some
163
; hardware some things just break in mysterious ways.
164
struct ehci_static_ep
165
; Hardware fields are the same as in ehci_pipe.
166
; Only NextQH and Overlay.Token are actually used.
167
; NB: some emulators ignore Token.Halted bit (probably assuming that it is set
168
; only when device fails and emulation never fails) and always follow
169
; [Alternate]NextTD when they see that OverlayToken.Active bit is zero;
170
; so it is important to also set [Alternate]NextTD to 1.
171
NextQH          dd      ?
172
Token           dd      ?
173
Flags           dd      ?
174
HeadTD          dd      ?
175
NextTD          dd      ?
176
AlternateNextTD dd      ?
177
OverlayToken    dd      ?
178
NextList        dd      ?
179
SoftwarePart    rd      sizeof.usb_static_ep/4
180
Bandwidths      rw      8
181
                dd      ?
182
ends
183
 
184
if sizeof.ehci_static_ep mod 32
185
.err ehci_static_ep must be 32-bytes aligned
186
end if
187
 
188
if ehci_static_ep.OverlayToken <> ehci_pipe.Overlay.Token
189
.err ehci_static_ep.OverlayToken misplaced
190
end if
191
 
192
; EHCI-specific part of controller data.
193
; * The structure includes two parts, the hardware part and the software part.
194
; * The hardware part consists of first 4096 bytes and corresponds to
195
;   the Periodic Frame List from the EHCI specification.
196
; * The hardware requires page-alignment of the hardware part, so
197
;   the entire descriptor must be page-aligned.
198
;   This structure is allocated with kernel_alloc (see usb_init_controller),
199
;   this gives page-aligned data.
200
; * The controller is described by both ehci_controller and usb_controller
201
;   structures, for each controller there is one ehci_controller and one
202
;   usb_controller structure. These structures are located sequentially
203
;   in the memory: beginning from some page start, there is ehci_controller
204
;   structure - this enforces hardware alignment requirements - and then
205
;   usb_controller structure.
206
; * The code keeps pointer to usb_controller structure. The ehci_controller
207
;   structure is addressed as [ptr + ehci_controller.field - sizeof.ehci_controller].
208
struct ehci_controller
209
; ------------------------------ hardware fields ------------------------------
210
FrameList               rd      1024
211
; Entry n corresponds to the head of the frame list to be executed in
3578 clevermous 212
; the frames n,n+1024,n+2048,n+3072,...
3520 clevermous 213
; The first bit of each entry is Terminate bit, 1 = the frame is empty.
214
; Bits 1-2 are Type field, one of EHCI_TYPE_* constants.
215
; Bits 3-4 must be zero.
216
; With masked 5 lower bits, the entry is a physical address of the first QH/TD
217
; to be executed.
218
; ------------------------------ software fields ------------------------------
219
; Every list has the static head, which is an always halted QH.
220
; The following fields are static heads, one per list:
221
; 32+16+8+4+2+1 = 63 for Periodic lists, 1 for Control list and 1 for Bulk list.
222
IntEDs                  ehci_static_ep
223
                        rb      62 * sizeof.ehci_static_ep
224
; Beware.
225
; Two following strings ensure that 44h bytes at any static head
226
; do not cross page boundary. Without that, the code "works on my machine"...
227
; but fails on some hardware in seemingly unrelated ways.
228
; One hardware TD (without any software fields) fit in the rest of the page.
229
ehci_controller.ControlDelta = 2000h - (ehci_controller.IntEDs + 63 * sizeof.ehci_static_ep)
230
StopQueueTD             ehci_hardware_td
231
; Used as AlternateNextTD for transfers when short packet is considered
232
; as an error; short packet must stop the queue in this case, not advance
233
; to the next transfer.
234
                        rb      ehci_controller.ControlDelta - sizeof.ehci_hardware_td
235
; Padding for page-alignment.
236
ControlED               ehci_static_ep
237
BulkED                  ehci_static_ep
238
MMIOBase1               dd      ?
239
; Virtual address of memory-mapped area with part 1 of EHCI registers EhciXxxReg.
240
MMIOBase2               dd      ?
241
; Pointer inside memory-mapped area MMIOBase1; points to part 2 of EHCI registers.
242
StructuralParams        dd      ?
243
; Copy of EhciStructParamsReg value.
244
CapabilityParams        dd      ?
245
; Copy of EhciCapParamsReg value.
246
DeferredActions         dd      ?
247
; Bitmask of events from EhciStatusReg which were observed by the IRQ handler
248
; and needs to be processed in the IRQ thread.
249
ends
250
 
251
if ehci_controller.IntEDs mod 32
252
.err Static endpoint descriptors must be 32-bytes aligned inside ehci_controller
253
end if
254
 
255
; Description of #HCI-specific data and functions for
256
; controller-independent code.
257
; Implements the structure usb_hardware_func from hccommon.inc for EHCI.
258
iglobal
259
align 4
260
ehci_hardware_func:
261
        dd      'EHCI'
262
        dd      sizeof.ehci_controller
263
        dd      ehci_init
264
        dd      ehci_process_deferred
265
        dd      ehci_set_device_address
266
        dd      ehci_get_device_address
267
        dd      ehci_port_disable
268
        dd      ehci_new_port.reset
269
        dd      ehci_set_endpoint_packet_size
270
        dd      ehci_alloc_pipe
271
        dd      ehci_free_pipe
272
        dd      ehci_init_pipe
273
        dd      ehci_unlink_pipe
274
        dd      ehci_alloc_td
275
        dd      ehci_free_td
276
        dd      ehci_alloc_transfer
277
        dd      ehci_insert_transfer
278
        dd      ehci_new_device
279
endg
280
 
281
; =============================================================================
282
; =================================== Code ====================================
283
; =============================================================================
284
 
285
; Controller-specific initialization function.
286
; Called from usb_init_controller. Initializes the hardware and
287
; EHCI-specific parts of software structures.
288
; eax = pointer to ehci_controller to be initialized
289
; [ebp-4] = pcidevice
290
proc ehci_init
291
; inherit some variables from the parent (usb_init_controller)
292
.devfn   equ ebp - 4
293
.bus     equ ebp - 3
294
; 1. Store pointer to ehci_controller for further use.
295
        push    eax
296
        mov     edi, eax
297
        mov     esi, eax
298
; 2. Initialize ehci_controller.FrameList.
299
; Note that FrameList is located in the beginning of ehci_controller,
300
; so esi and edi now point to ehci_controller.FrameList.
301
; First 32 entries of FrameList contain physical addresses
302
; of first 32 Periodic static heads, further entries duplicate these.
303
; See the description of structures for full info.
304
; 2a. Get physical address of first static head.
305
; Note that 1) it is located in the beginning of a page
306
; and 2) first 32 static heads fit in the same page,
307
; so one call to get_phys_addr without correction of lower 12 bits
308
; is sufficient.
309
if (ehci_controller.IntEDs / 0x1000) <> ((ehci_controller.IntEDs + 32 * sizeof.ehci_static_ep) / 0x1000)
310
.err assertion failed
311
end if
312
if (ehci_controller.IntEDs mod 0x1000) <> 0
313
.err assertion failed
314
end if
315
        add     eax, ehci_controller.IntEDs
316
        call    get_phys_addr
317
; 2b. Fill first 32 entries.
318
        inc     eax
319
        inc     eax     ; set Type to EHCI_TYPE_QH
3598 clevermous 320
        movi    ecx, 32
3520 clevermous 321
        mov     edx, ecx
322
@@:
323
        stosd
324
        add     eax, sizeof.ehci_static_ep
325
        loop    @b
326
; 2c. Fill the rest entries.
327
        mov     ecx, 1024 - 32
328
        rep movsd
329
; 3. Initialize static heads ehci_controller.*ED.
330
; Use the loop over groups: first group consists of first 32 Periodic
331
; descriptors, next group consists of next 16 Periodic descriptors,
332
; ..., last group consists of the last Periodic descriptor.
333
; 3a. Prepare for the loop.
334
; make esi point to the second group, other registers are already set.
335
        add     esi, 32*4 + 32*sizeof.ehci_static_ep
336
; 3b. Loop over groups. On every iteration:
337
; edx = size of group, edi = pointer to the current group,
338
; esi = pointer to the next group.
339
.init_static_eds:
340
; 3c. Get the size of next group.
341
        shr     edx, 1
342
; 3d. Exit the loop if there is no next group.
343
        jz      .init_static_eds_done
344
; 3e. Initialize the first half of the current group.
345
; Advance edi to the second half.
346
        push    esi
347
        call    ehci_init_static_ep_group
348
        pop     esi
349
; 3f. Initialize the second half of the current group
350
; with the same values.
351
; Advance edi to the next group, esi/eax to the next of the next group.
352
        call    ehci_init_static_ep_group
353
        jmp     .init_static_eds
354
.init_static_eds_done:
355
; 3g. Initialize the last static head.
356
        xor     esi, esi
357
        call    ehci_init_static_endpoint
358
; While we are here, initialize StopQueueTD.
359
if (ehci_controller.StopQueueTD <> ehci_controller.IntEDs + 63 * sizeof.ehci_static_ep)
360
.err assertion failed
361
end if
362
        inc     [edi+ehci_hardware_td.NextTD]   ; 0 -> 1
363
        inc     [edi+ehci_hardware_td.AlternateNextTD]  ; 0 -> 1
364
; leave other fields as zero, including Active bit
365
; 3i. Initialize the head of Control list.
366
        add     edi, ehci_controller.ControlDelta
367
        lea     esi, [edi+sizeof.ehci_static_ep]
368
        call    ehci_init_static_endpoint
369
        or      byte [edi-sizeof.ehci_static_ep+ehci_static_ep.Token+1], 80h
370
; 3j. Initialize the head of Bulk list.
371
        sub     esi, sizeof.ehci_static_ep
372
        call    ehci_init_static_endpoint
373
; 4. Create a virtual memory area to talk with the controller.
374
; 4a. Enable memory & bus master access.
375
        mov     ch, [.bus]
376
        mov     cl, 1
377
        mov     eax, ecx
378
        mov     bh, [.devfn]
379
        mov     bl, 4
380
        call    pci_read_reg
381
        or      al, 6
382
        xchg    eax, ecx
383
        call    pci_write_reg
384
; 4b. Read memory base address.
385
        mov     ah, [.bus]
386
        mov     al, 2
387
        mov     bl, 10h
388
        call    pci_read_reg
389
;       DEBUGF 1,'K : phys MMIO %x\n',eax
390
        and     al, not 0Fh
391
; 4c. Create mapping for physical memory. 200h bytes are always sufficient.
392
        stdcall map_io_mem, eax, 200h, PG_SW+PG_NOCACHE
393
        test    eax, eax
394
        jz      .fail
395
;       DEBUGF 1,'K : MMIO %x\n',eax
396
if ehci_controller.MMIOBase1 <> ehci_controller.BulkED + sizeof.ehci_static_ep
397
.err assertion failed
398
end if
399
        stosd   ; fill ehci_controller.MMIOBase1
400
        movzx   ecx, byte [eax+EhciCapLengthReg]
401
        mov     edx, [eax+EhciCapParamsReg]
402
        mov     ebx, [eax+EhciStructParamsReg]
403
        add     eax, ecx
404
if ehci_controller.MMIOBase2 <> ehci_controller.MMIOBase1 + 4
405
.err assertion failed
406
end if
407
        stosd   ; fill ehci_controller.MMIOBase2
408
if ehci_controller.StructuralParams <> ehci_controller.MMIOBase2 + 4
409
.err assertion failed
410
end if
411
if ehci_controller.CapabilityParams <> ehci_controller.StructuralParams + 4
412
.err assertion failed
413
end if
414
        mov     [edi], ebx      ; fill ehci_controller.StructuralParams
415
        mov     [edi+4], edx    ; fill ehci_controller.CapabilityParams
416
        DEBUGF 1,'K : HCSPARAMS=%x, HCCPARAMS=%x\n',ebx,edx
417
        and     ebx, 15
418
        mov     [edi+usb_controller.NumPorts+sizeof.ehci_controller-ehci_controller.StructuralParams], ebx
419
        mov     edi, eax
420
; now edi = MMIOBase2
421
; 6. Transfer the controller to a known state.
422
; 6b. Stop the controller if it is running.
3598 clevermous 423
        movi    ecx, 10
3520 clevermous 424
        test    dword [edi+EhciStatusReg], 1 shl 12
425
        jnz     .stopped
426
        and     dword [edi+EhciCommandReg], not 1
427
@@:
3598 clevermous 428
        movi    esi, 1
3520 clevermous 429
        call    delay_ms
430
        test    dword [edi+EhciStatusReg], 1 shl 12
431
        jnz     .stopped
432
        loop    @b
433
        dbgstr 'Failed to stop EHCI controller'
434
        jmp     .fail_unmap
435
.stopped:
436
; 6c. Reset the controller. Wait up to 50 ms checking status every 1 ms.
437
        or      dword [edi+EhciCommandReg], 2
3598 clevermous 438
        movi    ecx, 50
3520 clevermous 439
@@:
3598 clevermous 440
        movi    esi, 1
3520 clevermous 441
        call    delay_ms
442
        test    dword [edi+EhciCommandReg], 2
443
        jz      .reset_ok
444
        loop    @b
445
        dbgstr 'Failed to reset EHCI controller'
446
        jmp     .fail_unmap
447
.reset_ok:
448
; 7. Configure the controller.
449
        pop     esi     ; restore the pointer saved at step 1
450
        add     esi, sizeof.ehci_controller
451
; 7a. If the controller is 64-bit, say to it that all structures are located
452
; in first 4G.
453
        test    byte [esi+ehci_controller.CapabilityParams-sizeof.ehci_controller], 1
454
        jz      @f
455
        mov     dword [edi+EhciCtrlDataSegReg], 0
456
@@:
457
; 7b. Hook interrupt and enable appropriate interrupt sources.
458
        mov     ah, [.bus]
459
        mov     al, 0
460
        mov     bh, [.devfn]
461
        mov     bl, 3Ch
462
        call    pci_read_reg
463
; al = IRQ
464
        DEBUGF 1,'K : attaching to IRQ %x\n',al
465
        movzx   eax, al
466
        stdcall attach_int_handler, eax, ehci_irq, esi
467
;       mov     dword [edi+EhciStatusReg], 111111b      ; clear status
468
; disable Frame List Rollover interrupt, enable all other sources
469
        mov     dword [edi+EhciInterruptReg], 110111b
470
; 7c. Inform the controller of the address of periodic lists head.
471
        lea     eax, [esi-sizeof.ehci_controller]
472
        call    get_phys_addr
473
        mov     dword [edi+EhciPeriodicListReg], eax
474
; 7d. Inform the controller of the address of asynchronous lists head.
475
        lea     eax, [esi+ehci_controller.ControlED-sizeof.ehci_controller]
476
        call    get_phys_addr
477
        mov     dword [edi+EhciAsyncListReg], eax
478
; 7e. Configure operational details and run the controller.
479
        mov     dword [edi+EhciCommandReg], \
480
                (1 shl 16) + \ ; interrupt threshold = 1 microframe = 0.125ms
481
                (0 shl 11) + \ ; disable Async Park Mode
482
                (0 shl 8) +  \ ; zero Async Park Mode Count
483
                (1 shl 5) +  \ ; Async Schedule Enable
484
                (1 shl 4) +  \ ; Periodic Schedule Enable
485
                (0 shl 2) +  \ ; 1024 elements in FrameList
486
                1              ; Run
487
; 7f. Route all ports to this controller, not companion controllers.
488
        mov     dword [edi+EhciConfigFlagReg], 1
489
        DEBUGF 1,'K : EHCI controller at %x:%x with %d ports initialized\n',[.bus]:2,[.devfn]:2,[esi+usb_controller.NumPorts]
490
; 8. Apply port power, if needed, and disable all ports.
491
        xor     ecx, ecx
492
@@:
493
        mov     dword [edi+EhciPortsReg+ecx*4], 1000h   ; Port Power enabled, all other bits disabled
494
        inc     ecx
495
        cmp     ecx, [esi+usb_controller.NumPorts]
496
        jb      @b
497
        test    byte [esi+ehci_controller.StructuralParams-sizeof.ehci_controller], 10h
498
        jz      @f
499
        push    esi
3598 clevermous 500
        movi    esi, 20
3520 clevermous 501
        call    delay_ms
502
        pop     esi
503
@@:
504
; 9. Return pointer to usb_controller.
505
        xchg    eax, esi
506
        ret
507
; On error, pop the pointer saved at step 1 and return zero.
508
; Note that the main code branch restores the stack at step 7 and never fails
509
; after step 7.
510
.fail_unmap:
511
        pop     eax
512
        push    eax
513
        stdcall free_kernel_space, [eax+ehci_controller.MMIOBase1]
514
.fail:
515
        pop     ecx
516
        xor     eax, eax
517
        ret
518
endp
519
 
520
; Helper procedure for step 3 of ehci_init, see comments there.
521
; Initializes the static head of one list.
522
; esi = pointer to the "next" list, edi = pointer to head to initialize.
523
; Advances edi to the next head, keeps esi.
524
proc ehci_init_static_endpoint
525
        xor     eax, eax
526
        inc     eax     ; set Terminate bit
527
        mov     [edi+ehci_static_ep.NextTD], eax
528
        mov     [edi+ehci_static_ep.AlternateNextTD], eax
529
        test    esi, esi
530
        jz      @f
531
        mov     eax, esi
532
        call    get_phys_addr
533
        inc     eax
534
        inc     eax     ; set Type to EHCI_TYPE_QH
535
@@:
536
        mov     [edi+ehci_static_ep.NextQH], eax
537
        mov     [edi+ehci_static_ep.NextList], esi
538
        mov     byte [edi+ehci_static_ep.OverlayToken], 1 shl 6 ; halted
539
        add     edi, ehci_static_ep.SoftwarePart
540
        call    usb_init_static_endpoint
541
        add     edi, sizeof.ehci_static_ep - ehci_static_ep.SoftwarePart
542
        ret
543
endp
544
 
545
; Helper procedure for step 3 of ehci_init, see comments there.
546
; Initializes one half of group of static heads.
547
; edx = size of the next group = half of size of the group,
548
; edi = pointer to the group, esi = pointer to the next group.
549
; Advances esi, edi to next group, keeps edx.
550
proc ehci_init_static_ep_group
551
        push    edx
552
@@:
553
        call    ehci_init_static_endpoint
554
        add     esi, sizeof.ehci_static_ep
555
        dec     edx
556
        jnz     @b
557
        pop     edx
558
        ret
559
endp
560
 
561
; Controller-specific pre-initialization function: take ownership from BIOS.
562
; Some BIOSes, although not all of them, use USB controllers themselves
563
; to support USB flash drives. In this case,
564
; we must notify the BIOS that we don't need that emulation and know how to
565
; deal with USB devices.
566
proc ehci_kickoff_bios
567
; 1. Get the physical address of MMIO registers.
568
        mov     ah, [esi+PCIDEV.bus]
569
        mov     bh, [esi+PCIDEV.devfn]
570
        mov     al, 2
571
        mov     bl, 10h
572
        call    pci_read_reg
573
        and     al, not 0Fh
574
; 2. Create mapping for physical memory. 200h bytes are always sufficient.
575
        stdcall map_io_mem, eax, 200h, PG_SW+PG_NOCACHE
576
        test    eax, eax
577
        jz      .nothing
578
        push    eax     ; push argument for step 8
579
; 3. Some BIOSes enable controller interrupts as a result of giving
580
; controller away. At this point the system knows nothing about how to serve
581
; EHCI interrupts, so such an interrupt will send the system into an infinite
582
; loop handling the same IRQ again and again. Thus, we need to block EHCI
583
; interrupts. We can't do this at the controller level until step 5,
584
; because the controller is currently owned by BIOS, so we block all hardware
585
; interrupts on this processor until step 5.
586
        pushf
587
        cli
588
; 4. Take the ownership over the controller.
589
; 4a. Locate take-ownership capability in the PCI configuration space.
590
; Limit the loop with 100h iterations; since the entire configuration space is
591
; 100h bytes long, hitting this number of iterations means that something is
592
; corrupted.
593
; Use a value from MMIO as a starting point.
594
        mov     edx, [eax+EhciCapParamsReg]
595
        movzx   edi, byte [eax+EhciCapLengthReg]
596
        add     edi, eax
597
        push    0
598
        mov     bl, dh          ; get Extended Capabilities Pointer
599
        test    bl, bl
600
        jz      .has_ownership2
601
        cmp     bl, 40h
602
        jb      .no_capability
603
.look_bios_handoff:
604
        test    bl, 3
605
        jnz     .no_capability
606
; In each iteration, read the current dword,
607
        mov     ah, [esi+PCIDEV.bus]
608
        mov     al, 2
609
        mov     bh, [esi+PCIDEV.devfn]
610
        call    pci_read_reg
611
; check, whether the capability ID is take-ownership ID = 1,
612
        cmp     al, 1
613
        jz      .found_bios_handoff
614
; if not, advance to next-capability link and continue loop.
615
        dec     byte [esp]
616
        jz      .no_capability
617
        mov     bl, ah
618
        cmp     bl, 40h
619
        jae     .look_bios_handoff
620
.no_capability:
621
        dbgstr 'warning: cannot locate take-ownership capability'
622
        jmp     .has_ownership2
623
.found_bios_handoff:
624
; 4b. Check whether BIOS has ownership.
625
; Some BIOSes release ownership before loading OS, but forget to unwatch for
626
; change-ownership requests; they cannot handle ownership request, so
627
; such a request sends the system into infinite loop of handling the same SMI
628
; over and over. Avoid this.
629
        inc     ebx
630
        inc     ebx
631
        test    eax, 0x10000
632
        jz      .has_ownership
633
; 4c. Request ownership.
634
        inc     ebx
635
        mov     cl, 1
636
        mov     ah, [esi+PCIDEV.bus]
637
        mov     al, 0
638
        call    pci_write_reg
639
; 4d. Some BIOSes set ownership flag, but forget to watch for change-ownership
640
; requests; if so, there is no sense in waiting.
641
        inc     ebx
642
        mov     ah, [esi+PCIDEV.bus]
643
        mov     al, 2
644
        call    pci_read_reg
645
        dec     ebx
646
        dec     ebx
647
        test    ah, 20h
648
        jz      .force_ownership
649
; 4e. Wait for result no more than 1 s, checking for status every 1 ms.
650
; If successful, go to 5.
651
        mov     dword [esp], 1000
652
@@:
653
        mov     ah, [esi+PCIDEV.bus]
654
        mov     al, 0
655
        call    pci_read_reg
656
        test    al, 1
657
        jz      .has_ownership
658
        push    esi
3598 clevermous 659
        movi    esi, 1
3520 clevermous 660
        call    delay_ms
661
        pop     esi
662
        dec     dword [esp]
663
        jnz     @b
664
        dbgstr  'warning: taking EHCI ownership from BIOS timeout'
665
.force_ownership:
666
; 4f. BIOS has not responded within the timeout.
667
; Let's just clear BIOS ownership flag and hope that everything will be ok.
668
        mov     ah, [esi+PCIDEV.bus]
669
        mov     al, 0
670
        mov     cl, 0
671
        call    pci_write_reg
672
.has_ownership:
673
; 5. Just in case clear all SMI event sources except change-ownership.
674
        dbgstr 'has_ownership'
675
        inc     ebx
676
        inc     ebx
677
        mov     ah, [esi+PCIDEV.bus]
678
        mov     al, 2
679
        mov     ecx, eax
680
        call    pci_read_reg
681
        and     ax, 2000h
682
        xchg    eax, ecx
683
        call    pci_write_reg
684
.has_ownership2:
685
        pop     ecx
686
; 6. Disable all controller interrupts until the system will be ready to
687
; process them.
688
        mov     dword [edi+EhciInterruptReg], 0
689
; 7. Now we can unblock interrupts in the processor.
690
        popf
691
; 8. Release memory mapping created in step 2 and return.
692
        call    free_kernel_space
693
.nothing:
694
        ret
695
endp
696
 
697
; IRQ handler for EHCI controllers.
698
ehci_irq.noint:
699
        spin_unlock_irqrestore [esi+usb_controller.WaitSpinlock]
700
; Not our interrupt: restore registers and return zero.
701
        xor     eax, eax
702
        pop     edi esi ebx
703
        ret
704
 
705
proc ehci_irq
706
        push    ebx esi edi     ; save registers to be cdecl
707
virtual at esp
708
        rd      3       ; saved registers
709
        dd      ?       ; return address
710
.controller     dd      ?
711
end virtual
712
; 1. ebx will hold whether some deferred processing is needed,
713
; that cannot be done from the interrupt handler. Initialize to zero.
714
        xor     ebx, ebx
715
; 2. Get the mask of events which should be processed.
716
        mov     esi, [.controller]
717
        mov     edi, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
718
        spin_lock_irqsave [esi+usb_controller.WaitSpinlock]
719
        mov     eax, [edi+EhciStatusReg]
720
;       DEBUGF 1,'K : [%d] EHCI status %x\n',[timer_ticks],eax
721
; 3. Check whether that interrupt has been generated by our controller.
722
; (One IRQ can be shared by several devices.)
723
        and     eax, [edi+EhciInterruptReg]
724
        jz      .noint
725
; 4. Clear the events we know of.
726
; Note that this should be done before processing of events:
727
; new events could arise while we are processing those, this way we won't lose
728
; them (the controller would generate another interrupt after completion
729
; of this one).
730
;       DEBUGF 1,'K : EHCI interrupt: status = %x\n',eax
731
        mov     [edi+EhciStatusReg], eax
732
; 5. Sanity check.
733
        test    al, 10h
734
        jz      @f
735
        DEBUGF 1,'K : something terrible happened with EHCI %x (%x)\n',esi,al
736
@@:
737
; We can't do too much from an interrupt handler. Inform the processing thread
738
; that it should perform appropriate actions.
739
        or      [esi+ehci_controller.DeferredActions-sizeof.ehci_controller], eax
740
        spin_unlock_irqrestore [esi+usb_controller.WaitSpinlock]
741
        inc     ebx
742
        call    usb_wakeup_if_needed
743
; 6. Interrupt processed; return non-zero.
744
        mov     al, 1
745
        pop     edi esi ebx     ; restore used registers to be cdecl
746
        ret
747
endp
748
 
749
; This procedure is called from usb_set_address_callback
750
; and stores USB device address in the ehci_pipe structure.
751
; in: esi -> usb_controller, ebx -> usb_pipe, cl = address
752
proc ehci_set_device_address
3653 clevermous 753
        mov     byte [ebx+ehci_pipe.Token-sizeof.ehci_pipe], cl
3520 clevermous 754
        call    usb_subscribe_control
755
        ret
756
endp
757
 
758
; This procedure returns USB device address from the ehci_pipe structure.
759
; in: esi -> usb_controller, ebx -> usb_pipe
760
; out: eax = endpoint address
761
proc ehci_get_device_address
3653 clevermous 762
        mov     eax, [ebx+ehci_pipe.Token-sizeof.ehci_pipe]
3520 clevermous 763
        and     eax, 7Fh
764
        ret
765
endp
766
 
767
; This procedure is called from usb_set_address_callback
768
; if the device does not accept SET_ADDRESS command and needs
769
; to be disabled at the port level.
770
; in: esi -> usb_controller, ecx = port (zero-based)
771
proc ehci_port_disable
772
        mov     eax, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
773
        and     dword [eax+EhciPortsReg+ecx*4], not (4 or 2Ah)
774
        ret
775
endp
776
 
777
; This procedure is called from usb_get_descr8_callback when
778
; the packet size for zero endpoint becomes known and
779
; stores the packet size in ehci_pipe structure.
780
; in: esi -> usb_controller, ebx -> usb_pipe, ecx = packet size
781
proc ehci_set_endpoint_packet_size
3653 clevermous 782
        mov     eax, [ebx+ehci_pipe.Token-sizeof.ehci_pipe]
3520 clevermous 783
        and     eax, not (0x7FF shl 16)
784
        shl     ecx, 16
785
        or      eax, ecx
3653 clevermous 786
        mov     [ebx+ehci_pipe.Token-sizeof.ehci_pipe], eax
3520 clevermous 787
; Wait until hardware cache is evicted.
788
        call    usb_subscribe_control
789
        ret
790
endp
791
 
792
uglobal
793
align 4
794
; Data for memory allocator, see memory.inc.
795
ehci_ep_first_page      dd      ?
796
ehci_ep_mutex           MUTEX
797
ehci_gtd_first_page     dd      ?
798
ehci_gtd_mutex          MUTEX
799
endg
800
 
801
; This procedure allocates memory for pipe.
802
; Both hardware+software parts must be allocated, returns pointer to usb_pipe
803
; (software part).
804
proc ehci_alloc_pipe
805
        push    ebx
806
        mov     ebx, ehci_ep_mutex
3653 clevermous 807
        stdcall usb_allocate_common, (sizeof.ehci_pipe + sizeof.usb_pipe + 1Fh) and not 1Fh
3520 clevermous 808
        test    eax, eax
809
        jz      @f
3653 clevermous 810
        add     eax, sizeof.ehci_pipe
3520 clevermous 811
@@:
812
        pop     ebx
813
        ret
814
endp
815
 
816
; This procedure frees memory for pipe allocated by ehci_alloc_pipe.
817
; void stdcall with one argument = pointer to usb_pipe.
818
proc ehci_free_pipe
819
virtual at esp
820
        dd      ?       ; return address
821
.ptr    dd      ?
822
end virtual
3653 clevermous 823
        sub     [.ptr], sizeof.ehci_pipe
3520 clevermous 824
        jmp     usb_free_common
825
endp
826
 
827
; This procedure is called from API usb_open_pipe and processes
828
; the controller-specific part of this API. See docs.
829
; in: edi -> usb_pipe for target, ecx -> usb_pipe for config pipe,
830
; esi -> usb_controller, eax -> usb_gtd for the first TD,
831
; [ebp+12] = endpoint, [ebp+16] = maxpacket, [ebp+20] = type
832
proc ehci_init_pipe
833
virtual at ebp+8
834
.config_pipe    dd      ?
835
.endpoint       dd      ?
836
.maxpacket      dd      ?
837
.type           dd      ?
838
.interval       dd      ?
839
end virtual
840
; 1. Zero all fields in the hardware part.
841
        push    eax ecx
3653 clevermous 842
        sub     edi, sizeof.ehci_pipe
3520 clevermous 843
        xor     eax, eax
3653 clevermous 844
        movi    ecx, sizeof.ehci_pipe/4
3520 clevermous 845
        rep stosd
846
        pop     ecx eax
847
; 2. Setup PID in the first TD and make sure that the it is not active.
848
        xor     edx, edx
849
        test    byte [.endpoint], 80h
850
        setnz   dh
3653 clevermous 851
        mov     [eax+ehci_gtd.Token-sizeof.ehci_gtd], edx
852
        mov     [eax+ehci_gtd.NextTD-sizeof.ehci_gtd], 1
853
        mov     [eax+ehci_gtd.AlternateNextTD-sizeof.ehci_gtd], 1
3520 clevermous 854
; 3. Store physical address of the first TD.
3653 clevermous 855
        sub     eax, sizeof.ehci_gtd
3520 clevermous 856
        call    get_phys_addr
3653 clevermous 857
        mov     [edi+ehci_pipe.Overlay.NextTD-sizeof.ehci_pipe], eax
3520 clevermous 858
; 4. Fill ehci_pipe.Flags except for S- and C-masks.
859
; Copy location from the config pipe.
3653 clevermous 860
        mov     eax, [ecx+ehci_pipe.Flags-sizeof.ehci_pipe]
3520 clevermous 861
        and     eax, 3FFF0000h
862
; Use 1 requests per microframe for control/bulk endpoints,
863
; use value from the endpoint descriptor for periodic endpoints
3598 clevermous 864
        movi    edx, 1
3520 clevermous 865
        test    [.type], 1
866
        jz      @f
867
        mov     edx, [.maxpacket]
868
        shr     edx, 11
869
        inc     edx
870
@@:
871
        shl     edx, 30
872
        or      eax, edx
3653 clevermous 873
        mov     [edi+ehci_pipe.Flags-sizeof.ehci_pipe], eax
3520 clevermous 874
; 5. Fill ehci_pipe.Token.
3653 clevermous 875
        mov     eax, [ecx+ehci_pipe.Token-sizeof.ehci_pipe]
3520 clevermous 876
; copy following fields from the config pipe:
877
; DeviceAddress, EndpointSpeed, ControlEndpoint if new type is control
878
        mov     ecx, eax
879
        and     eax, 307Fh
880
        and     ecx, 8000000h
881
        or      ecx, 4000h
882
        mov     edx, [.endpoint]
883
        and     edx, 15
884
        shl     edx, 8
885
        or      eax, edx
886
        mov     edx, [.maxpacket]
887
        shl     edx, 16
888
        or      eax, edx
889
; for control endpoints, use DataToggle from TD, otherwise use DataToggle from QH
890
        cmp     [.type], CONTROL_PIPE
891
        jnz     @f
892
        or      eax, ecx
893
@@:
894
; for control/bulk USB2 endpoints, set NakCountReload to 4
895
        test    eax, USB_SPEED_HS shl 12
896
        jz      .nonak
897
        cmp     [.type], CONTROL_PIPE
898
        jz      @f
899
        cmp     [.type], BULK_PIPE
900
        jnz     .nonak
901
@@:
902
        or      eax, 40000000h
903
.nonak:
3653 clevermous 904
        mov     [edi+ehci_pipe.Token-sizeof.ehci_pipe], eax
3520 clevermous 905
; 5. Select the corresponding list and insert to the list.
906
; 5a. Use Control list for control pipes, Bulk list for bulk pipes.
907
        lea     edx, [esi+ehci_controller.ControlED.SoftwarePart-sizeof.ehci_controller]
908
        cmp     [.type], BULK_PIPE
909
        jb      .insert ; control pipe
910
        lea     edx, [esi+ehci_controller.BulkED.SoftwarePart-sizeof.ehci_controller]
911
        jz      .insert ; bulk pipe
912
.interrupt_pipe:
913
; 5b. For interrupt pipes, let the scheduler select the appropriate list
914
; and the appropriate microframe(s) (which goes to S-mask and C-mask)
915
; based on the current bandwidth distribution and the requested bandwidth.
916
; There are two schedulers, one for high-speed devices,
917
; another for split transactions.
918
; This could fail if the requested bandwidth is not available;
919
; if so, return an error.
3653 clevermous 920
        test    word [edi+ehci_pipe.Flags-sizeof.ehci_pipe+2], 3FFFh
3826 clevermous 921
        jnz     .interrupt_tt
3520 clevermous 922
        call    ehci_select_hs_interrupt_list
923
        jmp     .interrupt_common
3826 clevermous 924
.interrupt_tt:
925
        call    ehci_select_tt_interrupt_list
3520 clevermous 926
.interrupt_common:
927
        test    edx, edx
928
        jz      .return0
3653 clevermous 929
        mov     word [edi+ehci_pipe.Flags-sizeof.ehci_pipe], ax
3520 clevermous 930
.insert:
3653 clevermous 931
        mov     [edi+ehci_pipe.BaseList-sizeof.ehci_pipe], edx
3520 clevermous 932
; Insert to the head of the corresponding list.
933
; Note: inserting to the head guarantees that the list traverse in
934
; ehci_process_updated_schedule, once started, will not interact with new pipes.
935
; However, we still need to ensure that links in the new pipe (edi.NextVirt)
936
; are initialized before links to the new pipe (edx.NextVirt).
937
; 5c. Insert in the list of virtual addresses.
938
        mov     ecx, [edx+usb_pipe.NextVirt]
939
        mov     [edi+usb_pipe.NextVirt], ecx
940
        mov     [edi+usb_pipe.PrevVirt], edx
941
        mov     [ecx+usb_pipe.PrevVirt], edi
942
        mov     [edx+usb_pipe.NextVirt], edi
943
; 5d. Insert in the hardware list: copy previous NextQH to the new pipe,
944
; store the physical address of the new pipe to previous NextQH.
945
        mov     ecx, [edx+ehci_static_ep.NextQH-ehci_static_ep.SoftwarePart]
3653 clevermous 946
        mov     [edi+ehci_pipe.NextQH-sizeof.ehci_pipe], ecx
947
        lea     eax, [edi-sizeof.ehci_pipe]
3520 clevermous 948
        call    get_phys_addr
949
        inc     eax
950
        inc     eax
951
        mov     [edx+ehci_static_ep.NextQH-ehci_static_ep.SoftwarePart], eax
952
; 6. Return with nonzero eax.
953
        ret
954
.return0:
955
        xor     eax, eax
956
        ret
957
endp
958
 
959
; This function is called from ehci_process_deferred when
960
; a new device was connected at least USB_CONNECT_DELAY ticks
961
; and therefore is ready to be configured.
962
; ecx = port, esi -> ehci_controller, edi -> EHCI MMIO
963
proc ehci_new_port
964
; 1. If the device operates at low-speed, just release it to a companion.
965
        mov     eax, [edi+EhciPortsReg+ecx*4]
966
        DEBUGF 1,'K : [%d] EHCI %x port %d state is %x\n',[timer_ticks],esi,ecx,eax
967
        mov     edx, eax
968
        and     ah, 0Ch
969
        cmp     ah, 4
970
        jz      .low_speed
971
; 2. Devices operating at full-speed and high-speed must now have ah == 8.
972
; Some broken hardware asserts both D+ and D- even after initial decoupling;
973
; if so, stop initialization here, no sense in further actions.
974
        cmp     ah, 0Ch
975
        jz      .se1
976
; 3. If another port is resetting right now, mark this port as 'reset pending'
977
; and return.
978
        bts     [esi+usb_controller.PendingPorts], ecx
979
        cmp     [esi+usb_controller.ResettingPort], -1
980
        jnz     .nothing
981
        btr     [esi+usb_controller.PendingPorts], ecx
982
; Otherwise, fall through to ohci_new_port.reset.
983
 
984
; This function is called from ehci_new_port and usb_test_pending_port.
985
; It starts reset signalling for the port. Note that in USB first stages
986
; of configuration can not be done for several ports in parallel.
987
.reset:
988
        push    edi
989
        mov     edi, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
990
        mov     eax, [edi+EhciPortsReg+ecx*4]
991
; 1. Store information about resetting hub (roothub) and port.
992
        and     [esi+usb_controller.ResettingHub], 0
993
        mov     [esi+usb_controller.ResettingPort], cl
994
; 2. Initiate reset signalling.
995
        or      ah, 1
996
        and     al, not (4 or 2Ah)
997
        mov     [edi+EhciPortsReg+ecx*4], eax
998
; 3. Store the current time and set status to 1 = reset signalling active.
999
        mov     eax, [timer_ticks]
1000
        mov     [esi+usb_controller.ResetTime], eax
1001
        mov     [esi+usb_controller.ResettingStatus], 1
1002
;       dbgstr 'high-speed or full-speed device, resetting'
1003
        DEBUGF 1,'K : [%d] EHCI %x: port %d has HS or FS device, resetting\n',[timer_ticks],esi,ecx
1004
        pop     edi
1005
.nothing:
1006
        ret
1007
.low_speed:
1008
;       dbgstr 'low-speed device, releasing'
1009
        DEBUGF 1,'K : [%d] EHCI %x: port %d has LS device, releasing\n',[timer_ticks],esi,ecx
1010
        or      dh, 20h
1011
        and     dl, not 2Ah
1012
        mov     [edi+EhciPortsReg+ecx*4], edx
1013
        ret
1014
.se1:
1015
        dbgstr 'SE1 after connect debounce. Broken hardware?'
1016
        ret
1017
endp
1018
 
1019
; This procedure is called from several places in main USB code
1020
; and allocates required packets for the given transfer.
1021
; ebx = pipe, other parameters are passed through the stack:
1022
; buffer,size = data to transfer
1023
; flags = same as in usb_open_pipe: bit 0 = allow short transfer, other bits reserved
1024
; td = pointer to the current end-of-queue descriptor
1025
; direction =
1026
;   0000b for normal transfers,
1027
;   1000b for control SETUP transfer,
1028
;   1101b for control OUT transfer,
1029
;   1110b for control IN transfer
1030
; returns eax = pointer to the new end-of-queue descriptor
1031
; (not included in the queue itself) or 0 on error
1032
proc ehci_alloc_transfer stdcall uses edi, \
1033
        buffer:dword, size:dword, flags:dword, td:dword, direction:dword
1034
locals
1035
origTD          dd      ?
1036
packetSize      dd      ?       ; must be last variable, see usb_init_transfer
1037
endl
1038
; 1. Save original value of td:
1039
; it will be useful for rollback if something would fail.
1040
        mov     eax, [td]
1041
        mov     [origTD], eax
1042
; One transfer descriptor can describe up to 5 pages.
1043
; In the worst case (when the buffer is something*1000h+0FFFh)
1044
; this corresponds to 4001h bytes. If the requested size is
1045
; greater, we should split the transfer into several descriptors.
1046
; Boundaries to split must be multiples of endpoint transfer size
3656 clevermous 1047
; to avoid short packets except in the end of the transfer.
1048
        cmp     [size], 4001h
1049
        jbe     .lastpacket
3520 clevermous 1050
; 2. While the remaining data cannot fit in one descriptor,
1051
; allocate full descriptors (of maximal possible size).
3656 clevermous 1052
; 2a. Calculate size of one descriptor: must be a multiple of transfer size
1053
; and must be not greater than 4001h.
1054
        movzx   ecx, word [ebx+ohci_pipe.Flags+2-sizeof.ohci_pipe]
1055
        mov     eax, 4001h
1056
        xor     edx, edx
1057
        mov     edi, eax
1058
        div     ecx
1059
        sub     edi, edx
3520 clevermous 1060
        mov     [packetSize], edi
1061
.fullpackets:
1062
        call    ehci_alloc_packet
1063
        test    eax, eax
1064
        jz      .fail
1065
        mov     [td], eax
1066
        add     [buffer], edi
1067
        sub     [size], edi
3656 clevermous 1068
        cmp     [size], 4001h
1069
        ja      .fullpackets
3520 clevermous 1070
; 3. The remaining data can fit in one packet;
1071
; allocate the last descriptor with size = size of remaining data.
1072
.lastpacket:
1073
        mov     eax, [size]
1074
        mov     [packetSize], eax
1075
        call    ehci_alloc_packet
1076
        test    eax, eax
1077
        jz      .fail
1078
; 9. Update flags in the last packet.
1079
        mov     edx, [flags]
3653 clevermous 1080
        mov     [ecx+ehci_gtd.Flags-sizeof.ehci_gtd], edx
3520 clevermous 1081
; 10. Fill AlternateNextTD field in all allocated TDs.
1082
; If the caller says that short transfer is ok, the queue must advance to
1083
; the next descriptor, which is in eax.
1084
; Otherwise, the queue should stop, so make AlternateNextTD point to
1085
; always-inactive descriptor StopQueueTD.
1086
        push    eax
1087
        test    dl, 1
1088
        jz      .disable_short
3653 clevermous 1089
        sub     eax, sizeof.ehci_gtd
3520 clevermous 1090
        jmp     @f
1091
.disable_short:
1092
        mov     eax, [ebx+usb_pipe.Controller]
1093
        add     eax, ehci_controller.StopQueueTD - sizeof.ehci_controller
1094
@@:
1095
        call    get_phys_addr
1096
        mov     edx, [origTD]
1097
@@:
1098
        cmp     edx, [esp]
1099
        jz      @f
3653 clevermous 1100
        mov     [edx+ehci_gtd.AlternateNextTD-sizeof.ehci_gtd], eax
3520 clevermous 1101
        mov     edx, [edx+usb_gtd.NextVirt]
1102
        jmp     @b
1103
@@:
1104
        pop     eax
1105
        ret
1106
.fail:
1107
        mov     edi, ehci_hardware_func
1108
        mov     eax, [td]
1109
        stdcall usb_undo_tds, [origTD]
1110
        xor     eax, eax
1111
        ret
1112
endp
1113
 
1114
; Helper procedure for ehci_alloc_transfer.
1115
; Allocates and initializes one transfer descriptor.
1116
; ebx = pipe, other parameters are passed through the stack;
1117
; fills the current last descriptor and
1118
; returns eax = next descriptor (not filled).
1119
proc ehci_alloc_packet
1120
; inherit some variables from the parent ehci_alloc_transfer
1121
virtual at ebp-8
1122
.origTD         dd      ?
1123
.packetSize     dd      ?
1124
                rd      2
1125
.buffer         dd      ?
1126
.transferSize   dd      ?
1127
.Flags          dd      ?
1128
.td             dd      ?
1129
.direction      dd      ?
1130
end virtual
1131
; 1. Allocate the next TD.
1132
        call    ehci_alloc_td
1133
        test    eax, eax
1134
        jz      .nothing
1135
; 2. Initialize controller-independent parts of both TDs.
1136
        push    eax
1137
        call    usb_init_transfer
1138
        pop     eax
1139
; 3. Copy PID to the new descriptor.
3653 clevermous 1140
        mov     edx, [ecx+ehci_gtd.Token-sizeof.ehci_gtd]
1141
        mov     [eax+ehci_gtd.Token-sizeof.ehci_gtd], edx
1142
        mov     [eax+ehci_gtd.NextTD-sizeof.ehci_gtd], 1
1143
        mov     [eax+ehci_gtd.AlternateNextTD-sizeof.ehci_gtd], 1
3520 clevermous 1144
; 4. Save the returned value (next descriptor).
1145
        push    eax
1146
; 5. Store the physical address of the next descriptor.
3653 clevermous 1147
        sub     eax, sizeof.ehci_gtd
3520 clevermous 1148
        call    get_phys_addr
3653 clevermous 1149
        mov     [ecx+ehci_gtd.NextTD-sizeof.ehci_gtd], eax
3520 clevermous 1150
; 6. For zero-length transfers, store zero in all fields for buffer addresses.
1151
; Otherwise, fill them with real values.
1152
        xor     eax, eax
3653 clevermous 1153
        mov     [ecx+ehci_gtd.Flags-sizeof.ehci_gtd], eax
3520 clevermous 1154
repeat 10
3653 clevermous 1155
        mov     [ecx+ehci_gtd.BufferPointers-sizeof.ehci_gtd+(%-1)*4], eax
3520 clevermous 1156
end repeat
1157
        cmp     [.packetSize], eax
1158
        jz      @f
1159
        mov     eax, [.buffer]
1160
        call    get_phys_addr
3653 clevermous 1161
        mov     [ecx+ehci_gtd.BufferPointers-sizeof.ehci_gtd], eax
3520 clevermous 1162
        and     eax, 0xFFF
1163
        mov     edx, [.packetSize]
1164
        add     edx, eax
1165
        sub     edx, 0x1000
1166
        jbe     @f
1167
        mov     eax, [.buffer]
1168
        add     eax, 0x1000
1169
        call    get_pg_addr
3653 clevermous 1170
        mov     [ecx+ehci_gtd.BufferPointers+4-sizeof.ehci_gtd], eax
3520 clevermous 1171
        sub     edx, 0x1000
1172
        jbe     @f
1173
        mov     eax, [.buffer]
1174
        add     eax, 0x2000
1175
        call    get_pg_addr
3653 clevermous 1176
        mov     [ecx+ehci_gtd.BufferPointers+8-sizeof.ehci_gtd], eax
3520 clevermous 1177
        sub     edx, 0x1000
1178
        jbe     @f
1179
        mov     eax, [.buffer]
1180
        add     eax, 0x3000
1181
        call    get_pg_addr
3653 clevermous 1182
        mov     [ecx+ehci_gtd.BufferPointers+12-sizeof.ehci_gtd], eax
3520 clevermous 1183
        sub     edx, 0x1000
1184
        jbe     @f
1185
        mov     eax, [.buffer]
1186
        add     eax, 0x4000
1187
        call    get_pg_addr
3653 clevermous 1188
        mov     [ecx+ehci_gtd.BufferPointers+16-sizeof.ehci_gtd], eax
3520 clevermous 1189
@@:
1190
; 7. Fill Token field:
1191
; set Status = 0 (inactive, ehci_insert_transfer would mark everything active);
1192
; keep current PID if [.direction] is zero, use two lower bits of [.direction]
1193
; otherwise shifted as (0|1|2) -> (2|0|1);
1194
; set error counter to 3;
1195
; set current page to 0;
1196
; do not interrupt on complete (ehci_insert_transfer sets this bit where needed);
1197
; set DataToggle to bit 2 of [.direction].
3653 clevermous 1198
        mov     eax, [ecx+ehci_gtd.Token-sizeof.ehci_gtd]
3520 clevermous 1199
        and     eax, 300h       ; keep PID code
1200
        mov     edx, [.direction]
1201
        test    edx, edx
1202
        jz      .haspid
1203
        and     edx, 3
1204
        dec     edx
1205
        jns     @f
1206
        add     edx, 3
1207
@@:
1208
        mov     ah, dl
1209
        mov     edx, [.direction]
1210
        and     edx, not 3
1211
        shl     edx, 29
1212
        or      eax, edx
1213
.haspid:
1214
        or      eax, 0C00h
1215
        mov     edx, [.packetSize]
1216
        shl     edx, 16
1217
        or      eax, edx
3653 clevermous 1218
        mov     [ecx+ehci_gtd.Token-sizeof.ehci_gtd], eax
3520 clevermous 1219
; 4. Restore the returned value saved in step 2.
1220
        pop     eax
1221
.nothing:
1222
        ret
1223
endp
1224
 
1225
; This procedure is called from several places in main USB code
1226
; and activates the transfer which was previously allocated by
1227
; ehci_alloc_transfer.
1228
; ecx -> last descriptor for the transfer, ebx -> usb_pipe
1229
proc ehci_insert_transfer
3653 clevermous 1230
        or      byte [ecx+ehci_gtd.Token+1-sizeof.ehci_gtd], 80h  ; set IOC bit
3520 clevermous 1231
        mov     eax, [esp+4]
1232
.activate:
3653 clevermous 1233
        or      byte [eax+ehci_gtd.Token-sizeof.ehci_gtd], 80h    ; set Active bit
3520 clevermous 1234
        cmp     eax, ecx
1235
        mov     eax, [eax+usb_gtd.NextVirt]
1236
        jnz     .activate
1237
        ret
1238
endp
1239
 
1240
; This function is called from ehci_process_deferred when
1241
; reset signalling for a new device needs to be finished.
1242
proc ehci_port_reset_done
1243
        movzx   ecx, [esi+usb_controller.ResettingPort]
1244
        and     dword [edi+EhciPortsReg+ecx*4], not 12Ah
1245
        mov     eax, [timer_ticks]
1246
        mov     [esi+usb_controller.ResetTime], eax
1247
        mov     [esi+usb_controller.ResettingStatus], 2
1248
        DEBUGF 1,'K : [%d] EHCI %x: reset port %d done\n',[timer_ticks],esi,ecx
1249
        ret
1250
endp
1251
 
1252
; This function is called from ehci_process_deferred when
1253
; a new device has been reset, recovered after reset and needs to be configured.
1254
proc ehci_port_init
1255
; 1. Get the status and set it to zero.
1256
; If reset has been failed (device disconnected during reset),
1257
; continue to next device (if there is one).
1258
        xor     eax, eax
1259
        xchg    al, [esi+usb_controller.ResettingStatus]
1260
        test    al, al
1261
        js      usb_test_pending_port
1262
; 2. Get the port status. High-speed devices should be now enabled,
1263
; full-speed devices are left disabled;
1264
; if the port is disabled, release it to a companion and continue to
1265
; next device (if there is one).
1266
        movzx   ecx, [esi+usb_controller.ResettingPort]
1267
        mov     eax, [edi+EhciPortsReg+ecx*4]
1268
        DEBUGF 1,'K : [%d] EHCI %x status of port %d is %x\n',[timer_ticks],esi,ecx,eax
1269
        test    al, 4
1270
        jnz     @f
1271
;       DEBUGF 1,'K : USB port disabled after reset, status = %x\n',eax
1272
        dbgstr 'releasing to companion'
1273
        or      ah, 20h
1274
        mov     [edi+EhciPortsReg+ecx*4], eax
1275
        jmp     usb_test_pending_port
1276
@@:
1277
; 3. Call the worker procedure to notify the protocol layer
1278
; about new EHCI device. It is high-speed.
3598 clevermous 1279
        movi    eax, USB_SPEED_HS
3520 clevermous 1280
        call    ehci_new_device
1281
        test    eax, eax
1282
        jnz     .nothing
1283
; 4. If something at the protocol layer has failed
1284
; (no memory, no bus address), disable the port and stop the initialization.
1285
.disable_exit:
1286
        and     dword [edi+EhciPortsReg+ecx*4], not (4 or 2Ah)
1287
        jmp     usb_test_pending_port
1288
.nothing:
1289
        ret
1290
endp
1291
 
1292
; This procedure is called from ehci_port_init and from hub support code
1293
; when a new device is connected and has been reset.
1294
; It calls usb_new_device at the protocol layer with correct parameters.
1295
; in: esi -> usb_controller, eax = speed.
1296
proc ehci_new_device
1297
        push    ebx ecx ; save used registers (ecx is important for ehci_port_init)
1298
; 1. Store the speed for the protocol layer.
1299
        mov     [esi+usb_controller.ResettingSpeed], al
1300
; 2. Shift speed bits to the proper place in ehci_pipe.Token.
1301
        shl     eax, 12
1302
; 3. For high-speed devices, go to step 5 with edx = 0.
1303
        xor     edx, edx
1304
        cmp     ah, USB_SPEED_HS shl (12-8)
1305
        jz      .common
1306
; 4. For low-speed and full-speed devices, fill address:port
1307
; of the last high-speed hub (the closest to the device hub)
1308
; for split transactions, and set ControlEndpoint bit in eax;
1309
; ehci_init_pipe assumes that the parent pipe is a control pipe.
1310
        movzx   ecx, [esi+usb_controller.ResettingPort]
1311
        mov     edx, [esi+usb_controller.ResettingHub]
3826 clevermous 1312
; If the parent hub is high-speed, it is TT for the device.
1313
; Otherwise, the parent hub itself is behind TT, and the device
1314
; has the same TT hub+port as the parent hub.
3520 clevermous 1315
        push    eax
1316
        mov     eax, [edx+usb_hub.ConfigPipe]
1317
        mov     eax, [eax+usb_pipe.DeviceData]
1318
        cmp     [eax+usb_device_data.Speed], USB_SPEED_HS
3826 clevermous 1319
        jz      @f
1320
        movzx   ecx, [eax+usb_device_data.TTPort]
1321
        mov     edx, [eax+usb_device_data.TTHub]
1322
@@:
3520 clevermous 1323
        mov     edx, [edx+usb_hub.ConfigPipe]
1324
        inc     ecx
3653 clevermous 1325
        mov     edx, [edx+ehci_pipe.Token-sizeof.ehci_pipe]
3520 clevermous 1326
        shl     ecx, 23
1327
        and     edx, 7Fh
1328
        shl     edx, 16
1329
        or      edx, ecx        ; ehci_pipe.Flags
1330
        pop     eax
1331
        or      eax, 1 shl 27   ; ehci_pipe.Token
1332
.common:
1333
; 5. Create pseudo-pipe in the stack.
1334
; See ehci_init_pipe: only .Controller, .Token, .Flags fields are used.
3653 clevermous 1335
        push    esi     ; usb_pipe.Controller
3520 clevermous 1336
        mov     ecx, esp
3653 clevermous 1337
        sub     esp, sizeof.ehci_pipe - ehci_pipe.Flags - 4
3520 clevermous 1338
        push    edx     ; ehci_pipe.Flags
1339
        push    eax     ; ehci_pipe.Token
1340
; 6. Notify the protocol layer.
1341
        call    usb_new_device
1342
; 7. Cleanup the stack after step 5 and return.
3653 clevermous 1343
        add     esp, sizeof.ehci_pipe - ehci_pipe.Flags + 8
3520 clevermous 1344
        pop     ecx ebx ; restore used registers
1345
        ret
1346
endp
1347
 
1348
; This procedure is called in the USB thread from usb_thread_proc,
1349
; processes regular actions and those actions which can't be safely done
1350
; from interrupt handler.
1351
; Returns maximal time delta before the next call.
1352
proc ehci_process_deferred
1353
        push    ebx edi         ; save used registers to be stdcall
1354
        mov     edi, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
1355
; 1. Get the mask of events to process.
1356
        xor     eax, eax
1357
        xchg    eax, [esi+ehci_controller.DeferredActions-sizeof.ehci_controller]
1358
        push    eax
1359
; 2. Initialize the return value.
1360
        push    -1
1361
; Handle roothub events.
1362
; 3a. Test whether there are such events.
1363
        test    al, 4
1364
        jz      .skip_roothub
1365
; Status of some port has changed. Loop over all ports.
1366
; 3b. Prepare for the loop: start from port 0.
1367
        xor     ecx, ecx
1368
.portloop:
1369
; 3c. Get the port status and changes of it.
1370
; If there are no changes, just continue to the next port.
1371
        mov     eax, [edi+EhciPortsReg+ecx*4]
1372
        test    al, 2Ah
1373
        jz      .nextport
1374
; 3d. Clear change bits and read the status again.
1375
; (It is possible, although quite unlikely, that some event occurs between
1376
; the first read and the clearing, invalidating the old status. If an event
1377
; occurs after the clearing, we will not miss it, looking in the next scan.
1378
        mov     [edi+EhciPortsReg+ecx*4], eax
1379
        mov     ebx, eax
1380
        mov     eax, [edi+EhciPortsReg+ecx*4]
1381
        DEBUGF 1,'K : [%d] EHCI %x: status of port %d changed to %x\n',[timer_ticks],esi,ecx,ebx
1382
; 3e. Handle overcurrent.
1383
; Note: that needs work.
1384
        test    bl, 20h ; overcurrent change
1385
        jz      .noovercurrent
1386
        test    al, 10h ; overcurrent active
1387
        jz      .noovercurrent
1388
        DEBUGF 1,'K : overcurrent at port %d\n',ecx
1389
.noovercurrent:
1390
; 3f. Handle changing of connection status.
1391
        test    bl, 2
1392
        jz      .nocsc
1393
; There was a connect or disconnect event at this port.
1394
; 3g. Disconnect the old device on this port, if any.
1395
; If the port was resetting, indicate fail; later stages will process it.
4300 clevermous 1396
; Ignore connect event immediately after resetting.
3520 clevermous 1397
        cmp     [esi+usb_controller.ResettingHub], 0
4300 clevermous 1398
        jnz     .csc.noreset
3520 clevermous 1399
        cmp     cl, [esi+usb_controller.ResettingPort]
4300 clevermous 1400
        jnz     .csc.noreset
1401
        cmp     [esi+usb_controller.ResettingStatus], 2
3520 clevermous 1402
        jnz     @f
4300 clevermous 1403
        test    al, 1
1404
        jnz     .nextport
1405
@@:
3520 clevermous 1406
        mov     [esi+usb_controller.ResettingStatus], -1
4300 clevermous 1407
.csc.noreset:
3520 clevermous 1408
        bts     [esi+usb_controller.NewDisconnected], ecx
1409
; 3h. Change connected status. For the connection event, also store
1410
; the connection time; any further processing is permitted only after
1411
; USB_CONNECT_DELAY ticks.
1412
        test    al, 1
1413
        jz      .disconnect
1414
        mov     eax, [timer_ticks]
1415
        mov     [esi+usb_controller.ConnectedTime+ecx*4], eax
1416
        bts     [esi+usb_controller.NewConnected], ecx
1417
        jmp     .nextport
1418
.disconnect:
1419
        btr     [esi+usb_controller.NewConnected], ecx
1420
        jmp     .nextport
1421
.nocsc:
1422
; 3i. Handle port disabling.
1423
; Note: that needs work.
1424
        test    al, 8
1425
        jz      @f
1426
        test    al, 4
1427
        jz      @f
1428
        DEBUGF 1,'K : port %d disabled\n',ecx
1429
@@:
1430
; 3j. Continue the loop for the next port.
1431
.nextport:
1432
        inc     ecx
1433
        cmp     ecx, [esi+usb_controller.NumPorts]
1434
        jb      .portloop
1435
.skip_roothub:
1436
; 4. Process disconnect events. This should be done after step 3
1437
; (which includes the first stage of disconnect processing).
1438
        call    usb_disconnect_stage2
1439
; 5. Check for previously connected devices.
1440
; If there is a connected device which was connected less than
1441
; USB_CONNECT_DELAY ticks ago, plan to wake up when the delay will be over.
1442
; Otherwise, call ehci_new_port.
1443
; This should be done after step 3.
1444
        xor     ecx, ecx
1445
        cmp     [esi+usb_controller.NewConnected], ecx
1446
        jz      .skip_newconnected
1447
.portloop2:
1448
        bt      [esi+usb_controller.NewConnected], ecx
1449
        jnc     .noconnect
1450
        mov     eax, [timer_ticks]
1451
        sub     eax, [esi+usb_controller.ConnectedTime+ecx*4]
1452
        sub     eax, USB_CONNECT_DELAY
1453
        jge     .connected
1454
        neg     eax
1455
        cmp     [esp], eax
1456
        jb      .nextport2
1457
        mov     [esp], eax
1458
        jmp     .nextport2
1459
.connected:
1460
        btr     [esi+usb_controller.NewConnected], ecx
1461
        call    ehci_new_port
1462
        jmp     .portloop2
1463
.noconnect:
1464
.nextport2:
1465
        inc     ecx
1466
        cmp     ecx, [esi+usb_controller.NumPorts]
1467
        jb      .portloop2
1468
.skip_newconnected:
1469
; 6. Process wait lists.
1470
; 6a. Periodic endpoints.
1471
; If a request is pending >8 microframes, satisfy it.
1472
; If a request is pending <=8 microframes, schedule next wakeup in 0.01s.
1473
        mov     eax, [esi+usb_controller.WaitPipeRequestPeriodic]
1474
        cmp     eax, [esi+usb_controller.ReadyPipeHeadPeriodic]
1475
        jz      .noperiodic
1476
        mov     edx, [edi+EhciFrameIndexReg]
1477
        sub     edx, [esi+usb_controller.StartWaitFrame]
1478
        and     edx, 0x3FFF
1479
        cmp     edx, 8
1480
        jbe     @f
1481
        mov     [esi+usb_controller.ReadyPipeHeadPeriodic], eax
1482
        jmp     .noperiodic
1483
@@:
1484
        pop     eax
1485
        push    1               ; wakeup in 0.01 sec for next test
1486
.noperiodic:
1487
; 6b. Asynchronous endpoints.
1488
; Satisfy a request when InterruptOnAsyncAdvance fired.
1489
        test    byte [esp+4], 20h
1490
        jz      @f
1491
        dbgstr 'async advance int'
1492
        mov     eax, [esi+usb_controller.WaitPipeRequestAsync]
1493
        mov     [esi+usb_controller.ReadyPipeHeadAsync], eax
1494
@@:
1495
; Some hardware in some (rarely) conditions set the status bit,
1496
; but just does not generate the corresponding interrupt.
1497
; Force checking the status here.
1498
        mov     eax, [esi+usb_controller.WaitPipeRequestAsync]
1499
        cmp     [esi+usb_controller.ReadyPipeHeadAsync], eax
1500
        jz      .noasync
1501
        spin_lock_irq [esi+usb_controller.WaitSpinlock]
1502
        mov     edx, [edi+EhciStatusReg]
1503
        test    dl, 20h
1504
        jz      @f
1505
        mov     dword [edi+EhciStatusReg], 20h
1506
        and     dword [esi+ehci_controller.DeferredActions-sizeof.ehci_controller], not 20h
1507
        dbgstr 'warning: async advance int missed'
1508
        mov     [esi+usb_controller.ReadyPipeHeadAsync], eax
1509
        jmp     .async_unlock
1510
@@:
1511
        cmp     dword [esp], 100
1512
        jb      .async_unlock
1513
        mov     dword [esp], 100
1514
.async_unlock:
1515
        spin_unlock_irq [esi+usb_controller.WaitSpinlock]
1516
.noasync:
1517
; 7. Finalize transfers processed by hardware.
1518
; It is better to perform this step after step 4 (disconnect events),
1519
; although not strictly obligatory. This way, an active transfer aborted
1520
; due to disconnect would be handled with more specific USB_STATUS_CLOSED,
1521
; not USB_STATUS_NORESPONSE.
1522
        test    byte [esp+4], 3
1523
        jz      @f
1524
        call    ehci_process_updated_schedule
1525
@@:
1526
; 8. Test whether reset signalling has been started and should be stopped now.
1527
; This must be done after step 7, because completion of some transfer could
1528
; result in resetting a new port.
1529
.test_reset:
1530
; 8a. Test whether reset signalling is active.
1531
        cmp     [esi+usb_controller.ResettingStatus], 1
1532
        jnz     .no_reset_in_progress
1533
; 8b. Yep. Test whether it should be stopped.
1534
        mov     eax, [timer_ticks]
1535
        sub     eax, [esi+usb_controller.ResetTime]
1536
        sub     eax, USB_RESET_TIME
1537
        jge     .reset_done
1538
; 8c. Not yet, but initiate wakeup in -eax ticks and exit this step.
1539
        neg     eax
1540
        cmp     [esp], eax
1541
        jb      .skip_reset
1542
        mov     [esp], eax
1543
        jmp     .skip_reset
1544
.reset_done:
1545
; 8d. Yep, call the worker function and proceed to 8e.
1546
        call    ehci_port_reset_done
1547
.no_reset_in_progress:
1548
; 8e. Test whether reset process is done, either successful or failed.
1549
        cmp     [esi+usb_controller.ResettingStatus], 0
1550
        jz      .skip_reset
1551
; 8f. Yep. Test whether it should be stopped.
1552
        mov     eax, [timer_ticks]
1553
        sub     eax, [esi+usb_controller.ResetTime]
1554
        sub     eax, USB_RESET_RECOVERY_TIME
1555
        jge     .reset_recovery_done
1556
; 8g. Not yet, but initiate wakeup in -eax ticks and exit this step.
1557
        neg     eax
1558
        cmp     [esp], eax
1559
        jb      .skip_reset
1560
        mov     [esp], eax
1561
        jmp     .skip_reset
1562
.reset_recovery_done:
1563
; 8h. Yep, call the worker function. This could initiate another reset,
1564
; so return to the beginning of this step.
1565
        call    ehci_port_init
1566
        jmp     .test_reset
1567
.skip_reset:
1568
; 9. Process wait-done notifications, test for new wait requests.
1569
; Note: that must be done after steps 4 and 7 which could create new requests.
1570
; 9a. Call the worker function.
1571
        call    usb_process_wait_lists
1572
; 9b. If it reports that an asynchronous endpoint should be removed,
1573
; doorbell InterruptOnAsyncAdvance and schedule wakeup in 1s
1574
; (sometimes it just does not fire).
1575
        test    al, 1 shl CONTROL_PIPE
1576
        jz      @f
1577
        mov     edx, [esi+usb_controller.WaitPipeListAsync]
1578
        mov     [esi+usb_controller.WaitPipeRequestAsync], edx
1579
        or      dword [edi+EhciCommandReg], 1 shl 6
1580
        dbgstr 'async advance doorbell'
1581
        cmp     dword [esp], 100
1582
        jb      @f
1583
        mov     dword [esp], 100
1584
@@:
1585
; 9c. If it reports that a periodic endpoint should be removed,
1586
; save the current frame and schedule wakeup in 0.01 sec.
1587
        test    al, 1 shl INTERRUPT_PIPE
1588
        jz      @f
1589
        mov     eax, [esi+usb_controller.WaitPipeListPeriodic]
1590
        mov     [esi+usb_controller.WaitPipeRequestPeriodic], eax
1591
        mov     edx, [edi+EhciFrameIndexReg]
1592
        mov     [esi+usb_controller.StartWaitFrame], edx
1593
        mov     dword [esp], 1  ; wakeup in 0.01 sec for next test
1594
@@:
1595
; 10. Pop the return value, restore the stack after step 1 and return.
1596
        pop     eax
1597
        pop     ecx
1598
        pop     edi ebx ; restore used registers to be stdcall
1599
        ret
1600
endp
1601
 
1602
; This procedure is called in the USB thread from ehci_process_deferred
1603
; when EHCI IRQ handler has signalled that new IOC-packet was processed.
1604
; It scans all lists for completed packets and calls ehci_process_finalized_td
1605
; for those packets.
1606
proc ehci_process_updated_schedule
1607
; Important note: we cannot hold the list lock during callbacks,
1608
; because callbacks sometimes open and/or close pipes and thus acquire/release
1609
; the corresponding lock itself.
1610
; Fortunately, pipes can be finally freed only by another step of
1611
; ehci_process_deferred, so all pipes existing at the start of this function
1612
; will be valid while this function is running. Some pipes can be removed
1613
; from the corresponding list, some pipes can be inserted; insert/remove
1614
; functions guarantee that traversing one list yields all pipes that were in
1615
; that list at the beginning of the traversing (possibly with some new pipes,
1616
; possibly without some new pipes, that doesn't matter).
1617
        push    edi
1618
; 1. Process all Periodic lists.
1619
        lea     edi, [esi+ehci_controller.IntEDs-sizeof.ehci_controller+ehci_static_ep.SoftwarePart]
1620
        lea     ebx, [esi+ehci_controller.IntEDs+63*sizeof.ehci_static_ep-sizeof.ehci_controller+ehci_static_ep.SoftwarePart]
1621
@@:
1622
        call    ehci_process_updated_list
1623
        cmp     edi, ebx
1624
        jnz     @b
1625
; 2. Process the Control list.
1626
        add     edi, ehci_controller.ControlDelta
1627
        call    ehci_process_updated_list
1628
; 3. Process the Bulk list.
1629
        call    ehci_process_updated_list
1630
; 4. Return.
1631
        pop     edi
1632
        ret
1633
endp
1634
 
1635
; This procedure is called from ehci_process_updated_schedule, see comments there.
1636
; It processes one list, esi -> usb_controller, edi -> usb_static_ep,
1637
; and advances edi to next head.
1638
proc ehci_process_updated_list
1639
        push    ebx
1640
; 1. Perform the external loop over all pipes.
1641
        mov     ebx, [edi+usb_static_ep.NextVirt]
1642
.loop:
1643
        cmp     ebx, edi
1644
        jz      .done
1645
; store pointer to the next pipe in the stack
1646
        push    [ebx+usb_static_ep.NextVirt]
1647
; 2. For every pipe, perform the internal loop over all descriptors.
1648
; All descriptors are organized in the queue; we process items from the start
1649
; of the queue until a) the last descriptor (not the part of the queue itself)
1650
; or b) an active (not yet processed by the hardware) descriptor is reached.
1651
        lea     ecx, [ebx+usb_pipe.Lock]
1652
        call    mutex_lock
1653
        mov     ebx, [ebx+usb_pipe.LastTD]
1654
        push    ebx
1655
        mov     ebx, [ebx+usb_gtd.NextVirt]
1656
.tdloop:
1657
; 3. For every descriptor, test active flag and check for end-of-queue;
1658
; if either of conditions holds, exit from the internal loop.
1659
        cmp     ebx, [esp]
1660
        jz      .tddone
3653 clevermous 1661
        cmp     byte [ebx+ehci_gtd.Token-sizeof.ehci_gtd], 0
3520 clevermous 1662
        js      .tddone
1663
; Release the queue lock while processing one descriptor:
1664
; callback function could (and often would) schedule another transfer.
1665
        push    ecx
1666
        call    mutex_unlock
1667
        call    ehci_process_updated_td
1668
        pop     ecx
1669
        call    mutex_lock
1670
        jmp     .tdloop
1671
.tddone:
1672
        call    mutex_unlock
1673
        pop     ebx
1674
; End of internal loop, restore pointer to the next pipe
1675
; and continue the external loop.
1676
        pop     ebx
1677
        jmp     .loop
1678
.done:
1679
        pop     ebx
1680
        add     edi, sizeof.ehci_static_ep
1681
        ret
1682
endp
1683
 
1684
; This procedure is called from ehci_process_updated_list, which is itself
1685
; called from ehci_process_updated_schedule, see comments there.
1686
; It processes one completed descriptor.
1687
; in: ebx -> usb_gtd, out: ebx -> next usb_gtd.
1688
proc ehci_process_updated_td
1689
;       mov     eax, [ebx+usb_gtd.Pipe]
1690
;       cmp     [eax+usb_pipe.Type], INTERRUPT_PIPE
1691
;       jnz     @f
1692
;       DEBUGF 1,'K : finalized TD for pipe %x:\n',eax
3653 clevermous 1693
;       lea     eax, [ebx-sizeof.ehci_gtd]
3520 clevermous 1694
;       DEBUGF 1,'K : %x %x %x %x\n',[eax],[eax+4],[eax+8],[eax+12]
1695
;       DEBUGF 1,'K : %x %x %x %x\n',[eax+16],[eax+20],[eax+24],[eax+28]
1696
;@@:
1697
; 1. Remove this descriptor from the list of descriptors for this pipe.
1698
        call    usb_unlink_td
1699
; 2. Calculate actual number of bytes transferred.
3653 clevermous 1700
        mov     eax, [ebx+ehci_gtd.Token-sizeof.ehci_gtd]
3520 clevermous 1701
        lea     edx, [eax+eax]
1702
        shr     edx, 17
1703
        sub     edx, [ebx+usb_gtd.Length]
1704
        neg     edx
1705
; 3. Check whether we need some special processing beyond notifying the driver.
1706
; Transfer errors require special processing.
1707
; Short packets require special processing if
1708
; a) this is not the last descriptor for transfer stage
1709
; (in this case we need to process subsequent descriptors for the stage too)
1710
; or b) the caller considers short transfers to be an error.
1711
; ehci_alloc_transfer sets bit 0 of ehci_gtd.Flags to 0 if short packet
1712
; in this descriptor requires special processing and to 1 otherwise.
1713
; If special processing is not needed, advance to 4 with ecx = 0.
1714
; Otherwise, go to 6.
1715
        xor     ecx, ecx
1716
        test    al, 40h
1717
        jnz     .error
3653 clevermous 1718
        test    byte [ebx+ehci_gtd.Flags-sizeof.ehci_gtd], 1
3520 clevermous 1719
        jnz     .notify
1720
        cmp     edx, [ebx+usb_gtd.Length]
1721
        jnz     .special
1722
.notify:
1723
; 4. Either the descriptor in ebx was processed without errors,
1724
; or all necessary error actions were taken and ebx points to the last
1725
; related descriptor.
1726
; 4a. Test whether it is the last descriptor in the transfer
1727
; <=> it has an associated callback.
1728
        mov     eax, [ebx+usb_gtd.Callback]
1729
        test    eax, eax
1730
        jz      .nocallback
1731
; 4b. It has an associated callback; call it with corresponding parameters.
1732
        stdcall_verify eax, [ebx+usb_gtd.Pipe], ecx, \
1733
                [ebx+usb_gtd.Buffer], edx, [ebx+usb_gtd.UserData]
1734
        jmp     .callback
1735
.nocallback:
1736
; 4c. It is an intermediate descriptor. Add its length to the length
1737
; in the following descriptor.
1738
        mov     eax, [ebx+usb_gtd.NextVirt]
1739
        add     [eax+usb_gtd.Length], edx
1740
.callback:
1741
; 5. Free the current descriptor and return the next one.
1742
        push    [ebx+usb_gtd.NextVirt]
1743
        stdcall ehci_free_td, ebx
1744
        pop     ebx
1745
        ret
1746
.error:
1747
        push    ebx
3653 clevermous 1748
        sub     ebx, sizeof.ehci_gtd
3520 clevermous 1749
        DEBUGF 1,'K : TD failed:\n'
1750
        DEBUGF 1,'K : %x %x %x %x\n',[ebx],[ebx+4],[ebx+8],[ebx+12]
1751
        DEBUGF 1,'K : %x %x %x %x\n',[ebx+16],[ebx+20],[ebx+24],[ebx+28]
1752
        pop     ebx
1753
        DEBUGF 1,'K : pipe now:\n'
1754
        mov     ecx, [ebx+usb_gtd.Pipe]
3653 clevermous 1755
        sub     ecx, sizeof.ehci_pipe
3520 clevermous 1756
        DEBUGF 1,'K : %x %x %x %x\n',[ecx],[ecx+4],[ecx+8],[ecx+12]
1757
        DEBUGF 1,'K : %x %x %x %x\n',[ecx+16],[ecx+20],[ecx+24],[ecx+28]
1758
        DEBUGF 1,'K : %x %x %x %x\n',[ecx+32],[ecx+36],[ecx+40],[ecx+44]
1759
.special:
1760
; 6. Special processing is needed.
1761
; 6a. Save the status and length.
1762
        push    edx
1763
        push    eax
1764
; 6b. Traverse the list of descriptors looking for the final descriptor
1765
; for this transfer. Free and unlink non-final descriptors.
1766
; Final descriptor will be freed in step 5.
1767
.look_final:
1768
        call    usb_is_final_packet
1769
        jnc     .found_final
1770
        push    [ebx+usb_gtd.NextVirt]
1771
        stdcall ehci_free_td, ebx
1772
        pop     ebx
1773
        call    usb_unlink_td
1774
        jmp     .look_final
1775
.found_final:
1776
; 6c. Restore the status saved in 6a and transform it to the error code.
1777
; Notes:
1778
; * any USB transaction error results in Halted bit; if it is not set,
1779
;   but we are here, it must be due to short packet;
1780
; * babble is considered a fatal USB transaction error,
1781
;   other errors just lead to retrying the transaction;
1782
;   if babble is detected, return the corresponding error;
1783
; * if several non-fatal errors have occured during transaction retries,
1784
;   all corresponding bits are set. In this case, return some error code,
1785
;   the order is quite arbitrary.
1786
        pop     eax     ; status
3598 clevermous 1787
        movi    ecx, USB_STATUS_UNDERRUN
3520 clevermous 1788
        test    al, 40h         ; not Halted?
1789
        jz      .know_error
1790
        mov     cl, USB_STATUS_OVERRUN
1791
        test    al, 10h         ; Babble detected?
1792
        jnz     .know_error
1793
        mov     cl, USB_STATUS_BUFOVERRUN
1794
        test    al, 20h         ; Data Buffer error?
1795
        jnz     .know_error
1796
        mov     cl, USB_STATUS_NORESPONSE
1797
        test    al, 8           ; Transaction Error?
1798
        jnz     .know_error
1799
        mov     cl, USB_STATUS_STALL
1800
.know_error:
1801
; 6d. If error code is USB_STATUS_UNDERRUN and the last TD allows short packets,
1802
; it is not an error; in this case, go to 4 with ecx = 0.
1803
        cmp     ecx, USB_STATUS_UNDERRUN
1804
        jnz     @f
3653 clevermous 1805
        test    byte [ebx+ehci_gtd.Flags-sizeof.ehci_gtd], 1
3520 clevermous 1806
        jz      @f
1807
        xor     ecx, ecx
1808
        pop     edx     ; length
1809
        jmp     .notify
1810
@@:
1811
; 6e. Abort the entire transfer.
1812
; There are two cases: either there is only one transfer stage
1813
; (everything except control transfers), then ebx points to the last TD and
1814
; all previous TD were unlinked and dismissed (if possible),
1815
; or there are several stages (a control transfer) and ebx points to the last
1816
; TD of Data or Status stage (usb_is_final_packet does not stop in Setup stage,
1817
; because Setup stage can not produce short packets); for Data stage, we need
1818
; to unlink and free (if possible) one more TD and advance ebx to the next one.
1819
        cmp     [ebx+usb_gtd.Callback], 0
1820
        jnz     .normal
1821
        push    ecx
1822
        push    [ebx+usb_gtd.NextVirt]
1823
        stdcall ehci_free_td, ebx
1824
        pop     ebx
1825
        call    usb_unlink_td
1826
        pop     ecx
1827
.normal:
1828
; 6f. For bulk/interrupt transfers we have no choice but halt the queue,
1829
; the driver should intercede (through some API which is not written yet).
1830
; Control pipes normally recover at the next SETUP transaction (first stage
1831
; of any control transfer), so we hope on the best and just advance the queue
1832
; to the next transfer. (According to the standard, "A control pipe may also
1833
; support functional stall as well, but this is not recommended.").
1834
        mov     edx, [ebx+usb_gtd.Pipe]
3653 clevermous 1835
        mov     eax, [ebx+ehci_gtd.NextTD-sizeof.ehci_gtd]
3520 clevermous 1836
        or      al, 1
3653 clevermous 1837
        mov     [edx+ehci_pipe.Overlay.NextTD-sizeof.ehci_pipe], eax
1838
        mov     [edx+ehci_pipe.Overlay.AlternateNextTD-sizeof.ehci_pipe], eax
3520 clevermous 1839
        cmp     [edx+usb_pipe.Type], CONTROL_PIPE
1840
        jz      .control
1841
; Bulk/interrupt transfer; halt the queue.
3653 clevermous 1842
        mov     [edx+ehci_pipe.Overlay.Token-sizeof.ehci_pipe], 40h
3520 clevermous 1843
        pop     edx
1844
        jmp     .notify
1845
; Control transfer.
1846
.control:
3653 clevermous 1847
        and     [edx+ehci_pipe.Overlay.Token-sizeof.ehci_pipe], 0
1848
        dec     [edx+ehci_pipe.Overlay.NextTD-sizeof.ehci_pipe]
3520 clevermous 1849
        pop     edx
1850
        jmp     .notify
1851
endp
1852
 
1853
; This procedure unlinks the pipe from the corresponding pipe list.
1854
; esi -> usb_controller, ebx -> usb_pipe
1855
proc ehci_unlink_pipe
1856
        cmp     [ebx+usb_pipe.Type], INTERRUPT_PIPE
1857
        jnz     @f
3653 clevermous 1858
        test    word [ebx+ehci_pipe.Flags-sizeof.ehci_pipe+2], 3FFFh
3520 clevermous 1859
        jnz     .interrupt_fs
1860
        call    ehci_hs_interrupt_list_unlink
1861
        jmp     .interrupt_common
1862
.interrupt_fs:
1863
        call    ehci_fs_interrupt_list_unlink
1864
.interrupt_common:
1865
@@:
1866
        mov     edx, [ebx+usb_pipe.NextVirt]
1867
        mov     eax, [ebx+usb_pipe.PrevVirt]
1868
        mov     [edx+usb_pipe.PrevVirt], eax
1869
        mov     [eax+usb_pipe.NextVirt], edx
1870
        mov     edx, esi
1871
        sub     edx, eax
1872
        cmp     edx, sizeof.ehci_controller
3653 clevermous 1873
        mov     edx, [ebx+ehci_pipe.NextQH-sizeof.ehci_pipe]
3520 clevermous 1874
        jb      .prev_is_static
3653 clevermous 1875
        mov     [eax+ehci_pipe.NextQH-sizeof.ehci_pipe], edx
3520 clevermous 1876
        ret
1877
.prev_is_static:
1878
        mov     [eax+ehci_static_ep.NextQH-ehci_static_ep.SoftwarePart], edx
1879
        ret
1880
endp
1881
 
1882
proc ehci_alloc_td
1883
        push    ebx
1884
        mov     ebx, ehci_gtd_mutex
3653 clevermous 1885
        stdcall usb_allocate_common, (sizeof.ehci_gtd + sizeof.usb_gtd + 1Fh) and not 1Fh
3520 clevermous 1886
        test    eax, eax
1887
        jz      @f
3653 clevermous 1888
        add     eax, sizeof.ehci_gtd
3520 clevermous 1889
@@:
1890
        pop     ebx
1891
        ret
1892
endp
1893
 
1894
; This procedure is called from several places from main USB code and
1895
; frees all additional data associated with the transfer descriptor.
1896
; EHCI has no additional data, so just free ehci_gtd structure.
1897
proc ehci_free_td
3653 clevermous 1898
        sub     dword [esp+4], sizeof.ehci_gtd
3520 clevermous 1899
        jmp     usb_free_common
1900
endp