Subversion Repositories Kolibri OS

Rev

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

Rev Author Line No. Line
3555 Serge 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
84
;   (aligned on 0x1000 bytes), size of the structure must be divisible by 32.
85
; * The hardware also requires that the hardware part must not cross page
86
;   boundary; the allocator satisfies this automatically.
87
struct ehci_gtd ehci_hardware_td
88
Flags                   dd      ?
89
; Copy of flags from the call to usb_*_transfer_async.
90
SoftwarePart            rd      sizeof.usb_gtd/4
91
; Software part, common for all controllers.
92
                        rd      3       ; padding
93
ends
94
 
95
if sizeof.ehci_gtd mod 32
96
.err ehci_gtd must be 32-bytes aligned
97
end if
98
 
99
; EHCI-specific part of a pipe descriptor.
100
; * This structure corresponds to the Queue Head from the EHCI specification.
101
; * The hardware requires 32-bytes alignment of the hardware part.
102
;   Since the allocator (usb_allocate_common) allocates memory sequentially
103
;   from page start (aligned on 0x1000 bytes), size of the structure must be
104
;   divisible by 32.
105
; * The hardware requires also that the hardware part must not cross page
106
;   boundary; the allocator satisfies this automatically.
107
struct ehci_pipe
108
NextQH                  dd      ?
109
; 1. First bit (bit 0) is Terminate bit, 1 = there is no next QH.
110
; 2. Next two bits (bits 1-2) are Type field of the next QH,
111
;    one of EHCI_TYPE_* constants.
112
; 3. Next two bits (bits 3-4) are reserved, must be zero.
113
; 4. With masked 5 lower bits, this is the physical address of the next object
114
;    to be processed, usually next QH.
115
Token                   dd      ?
116
; 1. Lower 7 bits are DeviceAddress field. This is the address of the
117
;    target device on the USB bus.
118
; 2. Next bit (bit 7) is Inactivate-on-next-transaction bit. Can be nonzero
119
;    only for interrupt/isochronous USB1 endpoints.
120
; 3. Next 4 bits (bits 8-11) are Endpoint field. This is the target endpoint
121
;    number.
122
; 4. Next 2 bits (bits 12-13) are EndpointSpeed field, one of EHCI_SPEED_*.
123
; 5. Next bit (bit 14) is DataToggleControl bit,
124
;    0 = use DataToggle bit from QH, 1 = from TD.
125
; 6. Next bit (bit 15) is Head-of-reclamation-list. The head of Control list
126
;    has 1 here, all other QHs have zero.
127
; 7. Next 11 bits (bits 16-26) are MaximumPacketLength field for the target
128
;    endpoint.
129
; 8. Next bit (bit 27) is ControlEndpoint bit, must be 1 for USB1 control
130
;    endpoints and 0 for all others.
131
; 9. Upper 4 bits (bits 28-31) are NakCountReload field.
132
;    Zero for USB1 endpoints, zero for periodic endpoints.
133
;    For control/bulk USB2 endpoints, the code sets it to 4,
134
;    which is rather arbitrary.
135
Flags                   dd      ?
136
; 1. Lower byte is S-mask, each bit corresponds to one microframe per frame;
137
;    bit is set <=> enable transactions in this microframe.
138
; 2. Next byte is C-mask, each bit corresponds to one microframe per frame;
139
;    bit is set <=> enable complete-split transactions in this microframe.
140
;    Meaningful only for USB1 endpoints.
141
; 3. Next 14 bits give address of the target device as hub:port, bits 16-22
142
;    are the USB address of the hub, bits 23-29 are the port number.
143
;    Meaningful only for USB1 endpoints.
144
; 4. Upper 2 bits define number of consequetive transactions per micro-frame
145
;    which host is allowed to permit for this endpoint.
146
;    For control/bulk endpoints, it must be 1.
147
;    For periodic endpoints, the value is taken from the endpoint descriptor.
148
HeadTD                  dd      ?
149
; The physical address of the first TD for this pipe.
150
; Lower 5 bits must be zero.
151
Overlay                 ehci_hardware_td        ?
152
; Working area for the current TD, if there is any.
153
; When TD is retired, it is written to that TD and Overlay is loaded
154
; from the new TD, if any.
155
BaseList                dd      ?
156
; Pointer to head of the corresponding pipe list.
157
SoftwarePart            rd      sizeof.usb_pipe/4
158
; Software part, common for all controllers.
159
                        rd      2       ; padding
160
ends
161
 
162
if sizeof.ehci_pipe mod 32
163
.err ehci_pipe must be 32-bytes aligned
164
end if
165
 
166
; This structure describes the static head of every list of pipes.
167
; The hardware requires 32-bytes alignment of this structure.
168
; All instances of this structure are located sequentially in ehci_controller,
169
; ehci_controller is page-aligned, so it is sufficient to make this structure
170
; 32-bytes aligned and verify that the first instance is 32-bytes aligned
171
; inside ehci_controller.
172
; The hardware also requires that 44h bytes (size of 64-bit Queue Head
173
; Descriptor) starting at the beginning of this structure must not cross page
174
; boundary. If not, most hardware still behaves correctly (in fact, the last
175
; dword can have any value and this structure is never written), but on some
176
; hardware some things just break in mysterious ways.
177
struct ehci_static_ep
178
; Hardware fields are the same as in ehci_pipe.
179
; Only NextQH and Overlay.Token are actually used.
180
; NB: some emulators ignore Token.Halted bit (probably assuming that it is set
181
; only when device fails and emulation never fails) and always follow
182
; [Alternate]NextTD when they see that OverlayToken.Active bit is zero;
183
; so it is important to also set [Alternate]NextTD to 1.
184
NextQH          dd      ?
185
Token           dd      ?
186
Flags           dd      ?
187
HeadTD          dd      ?
188
NextTD          dd      ?
189
AlternateNextTD dd      ?
190
OverlayToken    dd      ?
191
NextList        dd      ?
192
SoftwarePart    rd      sizeof.usb_static_ep/4
193
Bandwidths      rw      8
194
                dd      ?
195
ends
196
 
197
if sizeof.ehci_static_ep mod 32
198
.err ehci_static_ep must be 32-bytes aligned
199
end if
200
 
201
if ehci_static_ep.OverlayToken <> ehci_pipe.Overlay.Token
202
.err ehci_static_ep.OverlayToken misplaced
203
end if
204
 
205
; EHCI-specific part of controller data.
206
; * The structure includes two parts, the hardware part and the software part.
207
; * The hardware part consists of first 4096 bytes and corresponds to
208
;   the Periodic Frame List from the EHCI specification.
209
; * The hardware requires page-alignment of the hardware part, so
210
;   the entire descriptor must be page-aligned.
211
;   This structure is allocated with kernel_alloc (see usb_init_controller),
212
;   this gives page-aligned data.
213
; * The controller is described by both ehci_controller and usb_controller
214
;   structures, for each controller there is one ehci_controller and one
215
;   usb_controller structure. These structures are located sequentially
216
;   in the memory: beginning from some page start, there is ehci_controller
217
;   structure - this enforces hardware alignment requirements - and then
218
;   usb_controller structure.
219
; * The code keeps pointer to usb_controller structure. The ehci_controller
220
;   structure is addressed as [ptr + ehci_controller.field - sizeof.ehci_controller].
221
struct ehci_controller
222
; ------------------------------ hardware fields ------------------------------
223
FrameList               rd      1024
224
; Entry n corresponds to the head of the frame list to be executed in
3589 Serge 225
; the frames n,n+1024,n+2048,n+3072,...
3555 Serge 226
; The first bit of each entry is Terminate bit, 1 = the frame is empty.
227
; Bits 1-2 are Type field, one of EHCI_TYPE_* constants.
228
; Bits 3-4 must be zero.
229
; With masked 5 lower bits, the entry is a physical address of the first QH/TD
230
; to be executed.
231
; ------------------------------ software fields ------------------------------
232
; Every list has the static head, which is an always halted QH.
233
; The following fields are static heads, one per list:
234
; 32+16+8+4+2+1 = 63 for Periodic lists, 1 for Control list and 1 for Bulk list.
235
IntEDs                  ehci_static_ep
236
                        rb      62 * sizeof.ehci_static_ep
237
; Beware.
238
; Two following strings ensure that 44h bytes at any static head
239
; do not cross page boundary. Without that, the code "works on my machine"...
240
; but fails on some hardware in seemingly unrelated ways.
241
; One hardware TD (without any software fields) fit in the rest of the page.
242
ehci_controller.ControlDelta = 2000h - (ehci_controller.IntEDs + 63 * sizeof.ehci_static_ep)
243
StopQueueTD             ehci_hardware_td
244
; Used as AlternateNextTD for transfers when short packet is considered
245
; as an error; short packet must stop the queue in this case, not advance
246
; to the next transfer.
247
                        rb      ehci_controller.ControlDelta - sizeof.ehci_hardware_td
248
; Padding for page-alignment.
249
ControlED               ehci_static_ep
250
BulkED                  ehci_static_ep
251
MMIOBase1               dd      ?
252
; Virtual address of memory-mapped area with part 1 of EHCI registers EhciXxxReg.
253
MMIOBase2               dd      ?
254
; Pointer inside memory-mapped area MMIOBase1; points to part 2 of EHCI registers.
255
StructuralParams        dd      ?
256
; Copy of EhciStructParamsReg value.
257
CapabilityParams        dd      ?
258
; Copy of EhciCapParamsReg value.
259
DeferredActions         dd      ?
260
; Bitmask of events from EhciStatusReg which were observed by the IRQ handler
261
; and needs to be processed in the IRQ thread.
262
ends
263
 
264
if ehci_controller.IntEDs mod 32
265
.err Static endpoint descriptors must be 32-bytes aligned inside ehci_controller
266
end if
267
 
268
; Description of #HCI-specific data and functions for
269
; controller-independent code.
270
; Implements the structure usb_hardware_func from hccommon.inc for EHCI.
271
iglobal
272
align 4
273
ehci_hardware_func:
274
        dd      'EHCI'
275
        dd      sizeof.ehci_controller
276
        dd      ehci_init
277
        dd      ehci_process_deferred
278
        dd      ehci_set_device_address
279
        dd      ehci_get_device_address
280
        dd      ehci_port_disable
281
        dd      ehci_new_port.reset
282
        dd      ehci_set_endpoint_packet_size
283
        dd      ehci_alloc_pipe
284
        dd      ehci_free_pipe
285
        dd      ehci_init_pipe
286
        dd      ehci_unlink_pipe
287
        dd      ehci_alloc_td
288
        dd      ehci_free_td
289
        dd      ehci_alloc_transfer
290
        dd      ehci_insert_transfer
291
        dd      ehci_new_device
292
endg
293
 
294
; =============================================================================
295
; =================================== Code ====================================
296
; =============================================================================
297
 
298
; Controller-specific initialization function.
299
; Called from usb_init_controller. Initializes the hardware and
300
; EHCI-specific parts of software structures.
301
; eax = pointer to ehci_controller to be initialized
302
; [ebp-4] = pcidevice
303
proc ehci_init
304
; inherit some variables from the parent (usb_init_controller)
305
.devfn   equ ebp - 4
306
.bus     equ ebp - 3
307
; 1. Store pointer to ehci_controller for further use.
308
        push    eax
309
        mov     edi, eax
310
        mov     esi, eax
311
; 2. Initialize ehci_controller.FrameList.
312
; Note that FrameList is located in the beginning of ehci_controller,
313
; so esi and edi now point to ehci_controller.FrameList.
314
; First 32 entries of FrameList contain physical addresses
315
; of first 32 Periodic static heads, further entries duplicate these.
316
; See the description of structures for full info.
317
; 2a. Get physical address of first static head.
318
; Note that 1) it is located in the beginning of a page
319
; and 2) first 32 static heads fit in the same page,
320
; so one call to get_phys_addr without correction of lower 12 bits
321
; is sufficient.
322
if (ehci_controller.IntEDs / 0x1000) <> ((ehci_controller.IntEDs + 32 * sizeof.ehci_static_ep) / 0x1000)
323
.err assertion failed
324
end if
325
if (ehci_controller.IntEDs mod 0x1000) <> 0
326
.err assertion failed
327
end if
328
        add     eax, ehci_controller.IntEDs
329
        call    get_phys_addr
330
; 2b. Fill first 32 entries.
331
        inc     eax
332
        inc     eax     ; set Type to EHCI_TYPE_QH
3626 Serge 333
        movi    ecx, 32
3555 Serge 334
        mov     edx, ecx
335
@@:
336
        stosd
337
        add     eax, sizeof.ehci_static_ep
338
        loop    @b
339
; 2c. Fill the rest entries.
340
        mov     ecx, 1024 - 32
341
        rep movsd
342
; 3. Initialize static heads ehci_controller.*ED.
343
; Use the loop over groups: first group consists of first 32 Periodic
344
; descriptors, next group consists of next 16 Periodic descriptors,
345
; ..., last group consists of the last Periodic descriptor.
346
; 3a. Prepare for the loop.
347
; make esi point to the second group, other registers are already set.
348
        add     esi, 32*4 + 32*sizeof.ehci_static_ep
349
; 3b. Loop over groups. On every iteration:
350
; edx = size of group, edi = pointer to the current group,
351
; esi = pointer to the next group.
352
.init_static_eds:
353
; 3c. Get the size of next group.
354
        shr     edx, 1
355
; 3d. Exit the loop if there is no next group.
356
        jz      .init_static_eds_done
357
; 3e. Initialize the first half of the current group.
358
; Advance edi to the second half.
359
        push    esi
360
        call    ehci_init_static_ep_group
361
        pop     esi
362
; 3f. Initialize the second half of the current group
363
; with the same values.
364
; Advance edi to the next group, esi/eax to the next of the next group.
365
        call    ehci_init_static_ep_group
366
        jmp     .init_static_eds
367
.init_static_eds_done:
368
; 3g. Initialize the last static head.
369
        xor     esi, esi
370
        call    ehci_init_static_endpoint
371
; While we are here, initialize StopQueueTD.
372
if (ehci_controller.StopQueueTD <> ehci_controller.IntEDs + 63 * sizeof.ehci_static_ep)
373
.err assertion failed
374
end if
375
        inc     [edi+ehci_hardware_td.NextTD]   ; 0 -> 1
376
        inc     [edi+ehci_hardware_td.AlternateNextTD]  ; 0 -> 1
377
; leave other fields as zero, including Active bit
378
; 3i. Initialize the head of Control list.
379
        add     edi, ehci_controller.ControlDelta
380
        lea     esi, [edi+sizeof.ehci_static_ep]
381
        call    ehci_init_static_endpoint
382
        or      byte [edi-sizeof.ehci_static_ep+ehci_static_ep.Token+1], 80h
383
; 3j. Initialize the head of Bulk list.
384
        sub     esi, sizeof.ehci_static_ep
385
        call    ehci_init_static_endpoint
386
; 4. Create a virtual memory area to talk with the controller.
387
; 4a. Enable memory & bus master access.
388
        mov     ch, [.bus]
389
        mov     cl, 1
390
        mov     eax, ecx
391
        mov     bh, [.devfn]
392
        mov     bl, 4
393
        call    pci_read_reg
394
        or      al, 6
395
        xchg    eax, ecx
396
        call    pci_write_reg
397
; 4b. Read memory base address.
398
        mov     ah, [.bus]
399
        mov     al, 2
400
        mov     bl, 10h
401
        call    pci_read_reg
402
;       DEBUGF 1,'K : phys MMIO %x\n',eax
403
        and     al, not 0Fh
404
; 4c. Create mapping for physical memory. 200h bytes are always sufficient.
405
        stdcall map_io_mem, eax, 200h, PG_SW+PG_NOCACHE
406
        test    eax, eax
407
        jz      .fail
408
;       DEBUGF 1,'K : MMIO %x\n',eax
409
if ehci_controller.MMIOBase1 <> ehci_controller.BulkED + sizeof.ehci_static_ep
410
.err assertion failed
411
end if
412
        stosd   ; fill ehci_controller.MMIOBase1
413
        movzx   ecx, byte [eax+EhciCapLengthReg]
414
        mov     edx, [eax+EhciCapParamsReg]
415
        mov     ebx, [eax+EhciStructParamsReg]
416
        add     eax, ecx
417
if ehci_controller.MMIOBase2 <> ehci_controller.MMIOBase1 + 4
418
.err assertion failed
419
end if
420
        stosd   ; fill ehci_controller.MMIOBase2
421
if ehci_controller.StructuralParams <> ehci_controller.MMIOBase2 + 4
422
.err assertion failed
423
end if
424
if ehci_controller.CapabilityParams <> ehci_controller.StructuralParams + 4
425
.err assertion failed
426
end if
427
        mov     [edi], ebx      ; fill ehci_controller.StructuralParams
428
        mov     [edi+4], edx    ; fill ehci_controller.CapabilityParams
429
        DEBUGF 1,'K : HCSPARAMS=%x, HCCPARAMS=%x\n',ebx,edx
430
        and     ebx, 15
431
        mov     [edi+usb_controller.NumPorts+sizeof.ehci_controller-ehci_controller.StructuralParams], ebx
432
        mov     edi, eax
433
; now edi = MMIOBase2
434
; 6. Transfer the controller to a known state.
435
; 6b. Stop the controller if it is running.
3626 Serge 436
        movi    ecx, 10
3555 Serge 437
        test    dword [edi+EhciStatusReg], 1 shl 12
438
        jnz     .stopped
439
        and     dword [edi+EhciCommandReg], not 1
440
@@:
3626 Serge 441
        movi    esi, 1
3555 Serge 442
        call    delay_ms
443
        test    dword [edi+EhciStatusReg], 1 shl 12
444
        jnz     .stopped
445
        loop    @b
446
        dbgstr 'Failed to stop EHCI controller'
447
        jmp     .fail_unmap
448
.stopped:
449
; 6c. Reset the controller. Wait up to 50 ms checking status every 1 ms.
450
        or      dword [edi+EhciCommandReg], 2
3626 Serge 451
        movi    ecx, 50
3555 Serge 452
@@:
3626 Serge 453
        movi    esi, 1
3555 Serge 454
        call    delay_ms
455
        test    dword [edi+EhciCommandReg], 2
456
        jz      .reset_ok
457
        loop    @b
458
        dbgstr 'Failed to reset EHCI controller'
459
        jmp     .fail_unmap
460
.reset_ok:
461
; 7. Configure the controller.
462
        pop     esi     ; restore the pointer saved at step 1
463
        add     esi, sizeof.ehci_controller
464
; 7a. If the controller is 64-bit, say to it that all structures are located
465
; in first 4G.
466
        test    byte [esi+ehci_controller.CapabilityParams-sizeof.ehci_controller], 1
467
        jz      @f
468
        mov     dword [edi+EhciCtrlDataSegReg], 0
469
@@:
470
; 7b. Hook interrupt and enable appropriate interrupt sources.
471
        mov     ah, [.bus]
472
        mov     al, 0
473
        mov     bh, [.devfn]
474
        mov     bl, 3Ch
475
        call    pci_read_reg
476
; al = IRQ
477
        DEBUGF 1,'K : attaching to IRQ %x\n',al
478
        movzx   eax, al
479
        stdcall attach_int_handler, eax, ehci_irq, esi
480
;       mov     dword [edi+EhciStatusReg], 111111b      ; clear status
481
; disable Frame List Rollover interrupt, enable all other sources
482
        mov     dword [edi+EhciInterruptReg], 110111b
483
; 7c. Inform the controller of the address of periodic lists head.
484
        lea     eax, [esi-sizeof.ehci_controller]
485
        call    get_phys_addr
486
        mov     dword [edi+EhciPeriodicListReg], eax
487
; 7d. Inform the controller of the address of asynchronous lists head.
488
        lea     eax, [esi+ehci_controller.ControlED-sizeof.ehci_controller]
489
        call    get_phys_addr
490
        mov     dword [edi+EhciAsyncListReg], eax
491
; 7e. Configure operational details and run the controller.
492
        mov     dword [edi+EhciCommandReg], \
493
                (1 shl 16) + \ ; interrupt threshold = 1 microframe = 0.125ms
494
                (0 shl 11) + \ ; disable Async Park Mode
495
                (0 shl 8) +  \ ; zero Async Park Mode Count
496
                (1 shl 5) +  \ ; Async Schedule Enable
497
                (1 shl 4) +  \ ; Periodic Schedule Enable
498
                (0 shl 2) +  \ ; 1024 elements in FrameList
499
                1              ; Run
500
; 7f. Route all ports to this controller, not companion controllers.
501
        mov     dword [edi+EhciConfigFlagReg], 1
502
        DEBUGF 1,'K : EHCI controller at %x:%x with %d ports initialized\n',[.bus]:2,[.devfn]:2,[esi+usb_controller.NumPorts]
503
; 8. Apply port power, if needed, and disable all ports.
504
        xor     ecx, ecx
505
@@:
506
        mov     dword [edi+EhciPortsReg+ecx*4], 1000h   ; Port Power enabled, all other bits disabled
507
        inc     ecx
508
        cmp     ecx, [esi+usb_controller.NumPorts]
509
        jb      @b
510
        test    byte [esi+ehci_controller.StructuralParams-sizeof.ehci_controller], 10h
511
        jz      @f
512
        push    esi
3626 Serge 513
        movi    esi, 20
3555 Serge 514
        call    delay_ms
515
        pop     esi
516
@@:
517
; 9. Return pointer to usb_controller.
518
        xchg    eax, esi
519
        ret
520
; On error, pop the pointer saved at step 1 and return zero.
521
; Note that the main code branch restores the stack at step 7 and never fails
522
; after step 7.
523
.fail_unmap:
524
        pop     eax
525
        push    eax
526
        stdcall free_kernel_space, [eax+ehci_controller.MMIOBase1]
527
.fail:
528
        pop     ecx
529
        xor     eax, eax
530
        ret
531
endp
532
 
533
; Helper procedure for step 3 of ehci_init, see comments there.
534
; Initializes the static head of one list.
535
; esi = pointer to the "next" list, edi = pointer to head to initialize.
536
; Advances edi to the next head, keeps esi.
537
proc ehci_init_static_endpoint
538
        xor     eax, eax
539
        inc     eax     ; set Terminate bit
540
        mov     [edi+ehci_static_ep.NextTD], eax
541
        mov     [edi+ehci_static_ep.AlternateNextTD], eax
542
        test    esi, esi
543
        jz      @f
544
        mov     eax, esi
545
        call    get_phys_addr
546
        inc     eax
547
        inc     eax     ; set Type to EHCI_TYPE_QH
548
@@:
549
        mov     [edi+ehci_static_ep.NextQH], eax
550
        mov     [edi+ehci_static_ep.NextList], esi
551
        mov     byte [edi+ehci_static_ep.OverlayToken], 1 shl 6 ; halted
552
        add     edi, ehci_static_ep.SoftwarePart
553
        call    usb_init_static_endpoint
554
        add     edi, sizeof.ehci_static_ep - ehci_static_ep.SoftwarePart
555
        ret
556
endp
557
 
558
; Helper procedure for step 3 of ehci_init, see comments there.
559
; Initializes one half of group of static heads.
560
; edx = size of the next group = half of size of the group,
561
; edi = pointer to the group, esi = pointer to the next group.
562
; Advances esi, edi to next group, keeps edx.
563
proc ehci_init_static_ep_group
564
        push    edx
565
@@:
566
        call    ehci_init_static_endpoint
567
        add     esi, sizeof.ehci_static_ep
568
        dec     edx
569
        jnz     @b
570
        pop     edx
571
        ret
572
endp
573
 
574
; Controller-specific pre-initialization function: take ownership from BIOS.
575
; Some BIOSes, although not all of them, use USB controllers themselves
576
; to support USB flash drives. In this case,
577
; we must notify the BIOS that we don't need that emulation and know how to
578
; deal with USB devices.
579
proc ehci_kickoff_bios
580
; 1. Get the physical address of MMIO registers.
581
        mov     ah, [esi+PCIDEV.bus]
582
        mov     bh, [esi+PCIDEV.devfn]
583
        mov     al, 2
584
        mov     bl, 10h
585
        call    pci_read_reg
586
        and     al, not 0Fh
587
; 2. Create mapping for physical memory. 200h bytes are always sufficient.
588
        stdcall map_io_mem, eax, 200h, PG_SW+PG_NOCACHE
589
        test    eax, eax
590
        jz      .nothing
591
        push    eax     ; push argument for step 8
592
; 3. Some BIOSes enable controller interrupts as a result of giving
593
; controller away. At this point the system knows nothing about how to serve
594
; EHCI interrupts, so such an interrupt will send the system into an infinite
595
; loop handling the same IRQ again and again. Thus, we need to block EHCI
596
; interrupts. We can't do this at the controller level until step 5,
597
; because the controller is currently owned by BIOS, so we block all hardware
598
; interrupts on this processor until step 5.
599
        pushf
600
        cli
601
; 4. Take the ownership over the controller.
602
; 4a. Locate take-ownership capability in the PCI configuration space.
603
; Limit the loop with 100h iterations; since the entire configuration space is
604
; 100h bytes long, hitting this number of iterations means that something is
605
; corrupted.
606
; Use a value from MMIO as a starting point.
607
        mov     edx, [eax+EhciCapParamsReg]
608
        DEBUGF 1,'K : edx=%x\n',edx
609
        movzx   edi, byte [eax+EhciCapLengthReg]
610
        add     edi, eax
611
        push    0
612
        mov     bl, dh          ; get Extended Capabilities Pointer
613
        test    bl, bl
614
        jz      .has_ownership2
615
        cmp     bl, 40h
616
        jb      .no_capability
617
.look_bios_handoff:
618
        test    bl, 3
619
        jnz     .no_capability
620
; In each iteration, read the current dword,
621
        mov     ah, [esi+PCIDEV.bus]
622
        mov     al, 2
623
        mov     bh, [esi+PCIDEV.devfn]
624
        call    pci_read_reg
625
; check, whether the capability ID is take-ownership ID = 1,
626
        cmp     al, 1
627
        jz      .found_bios_handoff
628
; if not, advance to next-capability link and continue loop.
629
        dec     byte [esp]
630
        jz      .no_capability
631
        mov     bl, ah
632
        cmp     bl, 40h
633
        jae     .look_bios_handoff
634
.no_capability:
635
        dbgstr 'warning: cannot locate take-ownership capability'
636
        jmp     .has_ownership2
637
.found_bios_handoff:
638
; 4b. Check whether BIOS has ownership.
639
; Some BIOSes release ownership before loading OS, but forget to unwatch for
640
; change-ownership requests; they cannot handle ownership request, so
641
; such a request sends the system into infinite loop of handling the same SMI
642
; over and over. Avoid this.
643
        inc     ebx
644
        inc     ebx
645
        test    eax, 0x10000
646
        jz      .has_ownership
647
; 4c. Request ownership.
648
        inc     ebx
649
        mov     cl, 1
650
        mov     ah, [esi+PCIDEV.bus]
651
        mov     al, 0
652
        call    pci_write_reg
653
; 4d. Some BIOSes set ownership flag, but forget to watch for change-ownership
654
; requests; if so, there is no sense in waiting.
655
        inc     ebx
656
        mov     ah, [esi+PCIDEV.bus]
657
        mov     al, 2
658
        call    pci_read_reg
659
        dec     ebx
660
        dec     ebx
661
        test    ah, 20h
662
        jz      .force_ownership
663
; 4e. Wait for result no more than 1 s, checking for status every 1 ms.
664
; If successful, go to 5.
665
        mov     dword [esp], 1000
666
@@:
667
        mov     ah, [esi+PCIDEV.bus]
668
        mov     al, 0
669
        call    pci_read_reg
670
        test    al, 1
671
        jz      .has_ownership
672
        push    esi
3626 Serge 673
        movi    esi, 1
3555 Serge 674
        call    delay_ms
675
        pop     esi
676
        dec     dword [esp]
677
        jnz     @b
678
        dbgstr  'warning: taking EHCI ownership from BIOS timeout'
679
.force_ownership:
680
; 4f. BIOS has not responded within the timeout.
681
; Let's just clear BIOS ownership flag and hope that everything will be ok.
682
        mov     ah, [esi+PCIDEV.bus]
683
        mov     al, 0
684
        mov     cl, 0
685
        call    pci_write_reg
686
.has_ownership:
687
; 5. Just in case clear all SMI event sources except change-ownership.
688
        dbgstr 'has_ownership'
689
        inc     ebx
690
        inc     ebx
691
        mov     ah, [esi+PCIDEV.bus]
692
        mov     al, 2
693
        mov     ecx, eax
694
        call    pci_read_reg
695
        and     ax, 2000h
696
        xchg    eax, ecx
697
        call    pci_write_reg
698
.has_ownership2:
699
        pop     ecx
700
; 6. Disable all controller interrupts until the system will be ready to
701
; process them.
702
        mov     dword [edi+EhciInterruptReg], 0
703
; 7. Now we can unblock interrupts in the processor.
704
        popf
705
; 8. Release memory mapping created in step 2 and return.
706
        call    free_kernel_space
707
.nothing:
708
        ret
709
endp
710
 
711
; IRQ handler for EHCI controllers.
712
ehci_irq.noint:
713
        spin_unlock_irqrestore [esi+usb_controller.WaitSpinlock]
714
; Not our interrupt: restore registers and return zero.
715
        xor     eax, eax
716
        pop     edi esi ebx
717
        ret
718
 
719
proc ehci_irq
720
        push    ebx esi edi     ; save registers to be cdecl
721
virtual at esp
722
        rd      3       ; saved registers
723
        dd      ?       ; return address
724
.controller     dd      ?
725
end virtual
726
; 1. ebx will hold whether some deferred processing is needed,
727
; that cannot be done from the interrupt handler. Initialize to zero.
728
        xor     ebx, ebx
729
; 2. Get the mask of events which should be processed.
730
        mov     esi, [.controller]
731
        mov     edi, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
732
        spin_lock_irqsave [esi+usb_controller.WaitSpinlock]
733
        mov     eax, [edi+EhciStatusReg]
734
;       DEBUGF 1,'K : [%d] EHCI status %x\n',[timer_ticks],eax
735
; 3. Check whether that interrupt has been generated by our controller.
736
; (One IRQ can be shared by several devices.)
737
        and     eax, [edi+EhciInterruptReg]
738
        jz      .noint
739
; 4. Clear the events we know of.
740
; Note that this should be done before processing of events:
741
; new events could arise while we are processing those, this way we won't lose
742
; them (the controller would generate another interrupt after completion
743
; of this one).
744
;       DEBUGF 1,'K : EHCI interrupt: status = %x\n',eax
745
        mov     [edi+EhciStatusReg], eax
746
; 5. Sanity check.
747
        test    al, 10h
748
        jz      @f
749
        DEBUGF 1,'K : something terrible happened with EHCI %x (%x)\n',esi,al
750
@@:
751
; We can't do too much from an interrupt handler. Inform the processing thread
752
; that it should perform appropriate actions.
753
        or      [esi+ehci_controller.DeferredActions-sizeof.ehci_controller], eax
754
        spin_unlock_irqrestore [esi+usb_controller.WaitSpinlock]
755
        inc     ebx
756
        call    usb_wakeup_if_needed
757
; 6. Interrupt processed; return non-zero.
758
        mov     al, 1
759
        pop     edi esi ebx     ; restore used registers to be cdecl
760
        ret
761
endp
762
 
763
; This procedure is called from usb_set_address_callback
764
; and stores USB device address in the ehci_pipe structure.
765
; in: esi -> usb_controller, ebx -> usb_pipe, cl = address
766
proc ehci_set_device_address
767
        mov     byte [ebx+ehci_pipe.Token-ehci_pipe.SoftwarePart], cl
768
        call    usb_subscribe_control
769
        ret
770
endp
771
 
772
; This procedure returns USB device address from the ehci_pipe structure.
773
; in: esi -> usb_controller, ebx -> usb_pipe
774
; out: eax = endpoint address
775
proc ehci_get_device_address
776
        mov     eax, [ebx+ehci_pipe.Token-ehci_pipe.SoftwarePart]
777
        and     eax, 7Fh
778
        ret
779
endp
780
 
781
; This procedure is called from usb_set_address_callback
782
; if the device does not accept SET_ADDRESS command and needs
783
; to be disabled at the port level.
784
; in: esi -> usb_controller, ecx = port (zero-based)
785
proc ehci_port_disable
786
        mov     eax, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
787
        and     dword [eax+EhciPortsReg+ecx*4], not (4 or 2Ah)
788
        ret
789
endp
790
 
791
; This procedure is called from usb_get_descr8_callback when
792
; the packet size for zero endpoint becomes known and
793
; stores the packet size in ehci_pipe structure.
794
; in: esi -> usb_controller, ebx -> usb_pipe, ecx = packet size
795
proc ehci_set_endpoint_packet_size
796
        mov     eax, [ebx+ehci_pipe.Token-ehci_pipe.SoftwarePart]
797
        and     eax, not (0x7FF shl 16)
798
        shl     ecx, 16
799
        or      eax, ecx
800
        mov     [ebx+ehci_pipe.Token-ehci_pipe.SoftwarePart], eax
801
; Wait until hardware cache is evicted.
802
        call    usb_subscribe_control
803
        ret
804
endp
805
 
806
uglobal
807
align 4
808
; Data for memory allocator, see memory.inc.
809
ehci_ep_first_page      dd      ?
810
ehci_ep_mutex           MUTEX
811
ehci_gtd_first_page     dd      ?
812
ehci_gtd_mutex          MUTEX
813
endg
814
 
815
; This procedure allocates memory for pipe.
816
; Both hardware+software parts must be allocated, returns pointer to usb_pipe
817
; (software part).
818
proc ehci_alloc_pipe
819
        push    ebx
820
        mov     ebx, ehci_ep_mutex
821
        stdcall usb_allocate_common, sizeof.ehci_pipe
822
        test    eax, eax
823
        jz      @f
824
        add     eax, ehci_pipe.SoftwarePart
825
@@:
826
        pop     ebx
827
        ret
828
endp
829
 
830
; This procedure frees memory for pipe allocated by ehci_alloc_pipe.
831
; void stdcall with one argument = pointer to usb_pipe.
832
proc ehci_free_pipe
833
virtual at esp
834
        dd      ?       ; return address
835
.ptr    dd      ?
836
end virtual
837
        sub     [.ptr], ehci_pipe.SoftwarePart
838
        jmp     usb_free_common
839
endp
840
 
841
; This procedure is called from API usb_open_pipe and processes
842
; the controller-specific part of this API. See docs.
843
; in: edi -> usb_pipe for target, ecx -> usb_pipe for config pipe,
844
; esi -> usb_controller, eax -> usb_gtd for the first TD,
845
; [ebp+12] = endpoint, [ebp+16] = maxpacket, [ebp+20] = type
846
proc ehci_init_pipe
847
virtual at ebp+8
848
.config_pipe    dd      ?
849
.endpoint       dd      ?
850
.maxpacket      dd      ?
851
.type           dd      ?
852
.interval       dd      ?
853
end virtual
854
; 1. Zero all fields in the hardware part.
855
        push    eax ecx
856
        sub     edi, ehci_pipe.SoftwarePart
857
        xor     eax, eax
3626 Serge 858
        movi    ecx, ehci_pipe.SoftwarePart/4
3555 Serge 859
        rep stosd
860
        pop     ecx eax
861
; 2. Setup PID in the first TD and make sure that the it is not active.
862
        xor     edx, edx
863
        test    byte [.endpoint], 80h
864
        setnz   dh
865
        mov     [eax+ehci_gtd.Token-ehci_gtd.SoftwarePart], edx
866
        mov     [eax+ehci_gtd.NextTD-ehci_gtd.SoftwarePart], 1
867
        mov     [eax+ehci_gtd.AlternateNextTD-ehci_gtd.SoftwarePart], 1
868
; 3. Store physical address of the first TD.
869
        sub     eax, ehci_gtd.SoftwarePart
870
        call    get_phys_addr
871
        mov     [edi+ehci_pipe.Overlay.NextTD-ehci_pipe.SoftwarePart], eax
872
; 4. Fill ehci_pipe.Flags except for S- and C-masks.
873
; Copy location from the config pipe.
874
        mov     eax, [ecx+ehci_pipe.Flags-ehci_pipe.SoftwarePart]
875
        and     eax, 3FFF0000h
876
; Use 1 requests per microframe for control/bulk endpoints,
877
; use value from the endpoint descriptor for periodic endpoints
3626 Serge 878
        movi    edx, 1
3555 Serge 879
        test    [.type], 1
880
        jz      @f
881
        mov     edx, [.maxpacket]
882
        shr     edx, 11
883
        inc     edx
884
@@:
885
        shl     edx, 30
886
        or      eax, edx
887
        mov     [edi+ehci_pipe.Flags-ehci_pipe.SoftwarePart], eax
888
; 5. Fill ehci_pipe.Token.
889
        mov     eax, [ecx+ehci_pipe.Token-ehci_pipe.SoftwarePart]
890
; copy following fields from the config pipe:
891
; DeviceAddress, EndpointSpeed, ControlEndpoint if new type is control
892
        mov     ecx, eax
893
        and     eax, 307Fh
894
        and     ecx, 8000000h
895
        or      ecx, 4000h
896
        mov     edx, [.endpoint]
897
        and     edx, 15
898
        shl     edx, 8
899
        or      eax, edx
900
        mov     edx, [.maxpacket]
901
        shl     edx, 16
902
        or      eax, edx
903
; for control endpoints, use DataToggle from TD, otherwise use DataToggle from QH
904
        cmp     [.type], CONTROL_PIPE
905
        jnz     @f
906
        or      eax, ecx
907
@@:
908
; for control/bulk USB2 endpoints, set NakCountReload to 4
909
        test    eax, USB_SPEED_HS shl 12
910
        jz      .nonak
911
        cmp     [.type], CONTROL_PIPE
912
        jz      @f
913
        cmp     [.type], BULK_PIPE
914
        jnz     .nonak
915
@@:
916
        or      eax, 40000000h
917
.nonak:
918
        mov     [edi+ehci_pipe.Token-ehci_pipe.SoftwarePart], eax
919
; 5. Select the corresponding list and insert to the list.
920
; 5a. Use Control list for control pipes, Bulk list for bulk pipes.
921
        lea     edx, [esi+ehci_controller.ControlED.SoftwarePart-sizeof.ehci_controller]
922
        cmp     [.type], BULK_PIPE
923
        jb      .insert ; control pipe
924
        lea     edx, [esi+ehci_controller.BulkED.SoftwarePart-sizeof.ehci_controller]
925
        jz      .insert ; bulk pipe
926
.interrupt_pipe:
927
; 5b. For interrupt pipes, let the scheduler select the appropriate list
928
; and the appropriate microframe(s) (which goes to S-mask and C-mask)
929
; based on the current bandwidth distribution and the requested bandwidth.
930
; There are two schedulers, one for high-speed devices,
931
; another for split transactions.
932
; This could fail if the requested bandwidth is not available;
933
; if so, return an error.
934
        test    word [edi+ehci_pipe.Flags-ehci_pipe.SoftwarePart+2], 3FFFh
935
        jnz     .interrupt_fs
936
        call    ehci_select_hs_interrupt_list
937
        jmp     .interrupt_common
938
.interrupt_fs:
939
        call    ehci_select_fs_interrupt_list
940
.interrupt_common:
941
        test    edx, edx
942
        jz      .return0
943
        mov     word [edi+ehci_pipe.Flags-ehci_pipe.SoftwarePart], ax
944
.insert:
945
        mov     [edi+ehci_pipe.BaseList-ehci_pipe.SoftwarePart], edx
946
; Insert to the head of the corresponding list.
947
; Note: inserting to the head guarantees that the list traverse in
948
; ehci_process_updated_schedule, once started, will not interact with new pipes.
949
; However, we still need to ensure that links in the new pipe (edi.NextVirt)
950
; are initialized before links to the new pipe (edx.NextVirt).
951
; 5c. Insert in the list of virtual addresses.
952
        mov     ecx, [edx+usb_pipe.NextVirt]
953
        mov     [edi+usb_pipe.NextVirt], ecx
954
        mov     [edi+usb_pipe.PrevVirt], edx
955
        mov     [ecx+usb_pipe.PrevVirt], edi
956
        mov     [edx+usb_pipe.NextVirt], edi
957
; 5d. Insert in the hardware list: copy previous NextQH to the new pipe,
958
; store the physical address of the new pipe to previous NextQH.
959
        mov     ecx, [edx+ehci_static_ep.NextQH-ehci_static_ep.SoftwarePart]
960
        mov     [edi+ehci_pipe.NextQH-ehci_pipe.SoftwarePart], ecx
961
        lea     eax, [edi-ehci_pipe.SoftwarePart]
962
        call    get_phys_addr
963
        inc     eax
964
        inc     eax
965
        mov     [edx+ehci_static_ep.NextQH-ehci_static_ep.SoftwarePart], eax
966
; 6. Return with nonzero eax.
967
        ret
968
.return0:
969
        xor     eax, eax
970
        ret
971
endp
972
 
973
; This function is called from ehci_process_deferred when
974
; a new device was connected at least USB_CONNECT_DELAY ticks
975
; and therefore is ready to be configured.
976
; ecx = port, esi -> ehci_controller, edi -> EHCI MMIO
977
proc ehci_new_port
978
; 1. If the device operates at low-speed, just release it to a companion.
979
        mov     eax, [edi+EhciPortsReg+ecx*4]
980
        DEBUGF 1,'K : [%d] EHCI %x port %d state is %x\n',[timer_ticks],esi,ecx,eax
981
        mov     edx, eax
982
        and     ah, 0Ch
983
        cmp     ah, 4
984
        jz      .low_speed
985
; 2. Devices operating at full-speed and high-speed must now have ah == 8.
986
; Some broken hardware asserts both D+ and D- even after initial decoupling;
987
; if so, stop initialization here, no sense in further actions.
988
        cmp     ah, 0Ch
989
        jz      .se1
990
; 3. If another port is resetting right now, mark this port as 'reset pending'
991
; and return.
992
        bts     [esi+usb_controller.PendingPorts], ecx
993
        cmp     [esi+usb_controller.ResettingPort], -1
994
        jnz     .nothing
995
        btr     [esi+usb_controller.PendingPorts], ecx
996
; Otherwise, fall through to ohci_new_port.reset.
997
 
998
; This function is called from ehci_new_port and usb_test_pending_port.
999
; It starts reset signalling for the port. Note that in USB first stages
1000
; of configuration can not be done for several ports in parallel.
1001
.reset:
1002
        push    edi
1003
        mov     edi, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
1004
        mov     eax, [edi+EhciPortsReg+ecx*4]
1005
; 1. Store information about resetting hub (roothub) and port.
1006
        and     [esi+usb_controller.ResettingHub], 0
1007
        mov     [esi+usb_controller.ResettingPort], cl
1008
; 2. Initiate reset signalling.
1009
        or      ah, 1
1010
        and     al, not (4 or 2Ah)
1011
        mov     [edi+EhciPortsReg+ecx*4], eax
1012
; 3. Store the current time and set status to 1 = reset signalling active.
1013
        mov     eax, [timer_ticks]
1014
        mov     [esi+usb_controller.ResetTime], eax
1015
        mov     [esi+usb_controller.ResettingStatus], 1
1016
;       dbgstr 'high-speed or full-speed device, resetting'
1017
        DEBUGF 1,'K : [%d] EHCI %x: port %d has HS or FS device, resetting\n',[timer_ticks],esi,ecx
1018
        pop     edi
1019
.nothing:
1020
        ret
1021
.low_speed:
1022
;       dbgstr 'low-speed device, releasing'
1023
        DEBUGF 1,'K : [%d] EHCI %x: port %d has LS device, releasing\n',[timer_ticks],esi,ecx
1024
        or      dh, 20h
1025
        and     dl, not 2Ah
1026
        mov     [edi+EhciPortsReg+ecx*4], edx
1027
        ret
1028
.se1:
1029
        dbgstr 'SE1 after connect debounce. Broken hardware?'
1030
        ret
1031
endp
1032
 
1033
; This procedure is called from several places in main USB code
1034
; and allocates required packets for the given transfer.
1035
; ebx = pipe, other parameters are passed through the stack:
1036
; buffer,size = data to transfer
1037
; flags = same as in usb_open_pipe: bit 0 = allow short transfer, other bits reserved
1038
; td = pointer to the current end-of-queue descriptor
1039
; direction =
1040
;   0000b for normal transfers,
1041
;   1000b for control SETUP transfer,
1042
;   1101b for control OUT transfer,
1043
;   1110b for control IN transfer
1044
; returns eax = pointer to the new end-of-queue descriptor
1045
; (not included in the queue itself) or 0 on error
1046
proc ehci_alloc_transfer stdcall uses edi, \
1047
        buffer:dword, size:dword, flags:dword, td:dword, direction:dword
1048
locals
1049
origTD          dd      ?
1050
packetSize      dd      ?       ; must be last variable, see usb_init_transfer
1051
endl
1052
; 1. Save original value of td:
1053
; it will be useful for rollback if something would fail.
1054
        mov     eax, [td]
1055
        mov     [origTD], eax
1056
; One transfer descriptor can describe up to 5 pages.
1057
; In the worst case (when the buffer is something*1000h+0FFFh)
1058
; this corresponds to 4001h bytes. If the requested size is
1059
; greater, we should split the transfer into several descriptors.
1060
; Boundaries to split must be multiples of endpoint transfer size
1061
; to avoid short packets except in the end of the transfer,
1062
; 4000h is always a good value.
1063
; 2. While the remaining data cannot fit in one descriptor,
1064
; allocate full descriptors (of maximal possible size).
1065
        mov     edi, 4000h
1066
        mov     [packetSize], edi
1067
.fullpackets:
1068
        cmp     [size], edi
1069
        jbe     .lastpacket
1070
        call    ehci_alloc_packet
1071
        test    eax, eax
1072
        jz      .fail
1073
        mov     [td], eax
1074
        add     [buffer], edi
1075
        sub     [size], edi
1076
        jmp     .fullpackets
1077
; 3. The remaining data can fit in one packet;
1078
; allocate the last descriptor with size = size of remaining data.
1079
.lastpacket:
1080
        mov     eax, [size]
1081
        mov     [packetSize], eax
1082
        call    ehci_alloc_packet
1083
        test    eax, eax
1084
        jz      .fail
1085
; 9. Update flags in the last packet.
1086
        mov     edx, [flags]
1087
        mov     [ecx+ehci_gtd.Flags-ehci_gtd.SoftwarePart], edx
1088
; 10. Fill AlternateNextTD field in all allocated TDs.
1089
; If the caller says that short transfer is ok, the queue must advance to
1090
; the next descriptor, which is in eax.
1091
; Otherwise, the queue should stop, so make AlternateNextTD point to
1092
; always-inactive descriptor StopQueueTD.
1093
        push    eax
1094
        test    dl, 1
1095
        jz      .disable_short
1096
        sub     eax, ehci_gtd.SoftwarePart
1097
        jmp     @f
1098
.disable_short:
1099
        mov     eax, [ebx+usb_pipe.Controller]
1100
        add     eax, ehci_controller.StopQueueTD - sizeof.ehci_controller
1101
@@:
1102
        call    get_phys_addr
1103
        mov     edx, [origTD]
1104
@@:
1105
        cmp     edx, [esp]
1106
        jz      @f
1107
        mov     [edx+ehci_gtd.AlternateNextTD-ehci_gtd.SoftwarePart], eax
1108
        mov     edx, [edx+usb_gtd.NextVirt]
1109
        jmp     @b
1110
@@:
1111
        pop     eax
1112
        ret
1113
.fail:
1114
        mov     edi, ehci_hardware_func
1115
        mov     eax, [td]
1116
        stdcall usb_undo_tds, [origTD]
1117
        xor     eax, eax
1118
        ret
1119
endp
1120
 
1121
; Helper procedure for ehci_alloc_transfer.
1122
; Allocates and initializes one transfer descriptor.
1123
; ebx = pipe, other parameters are passed through the stack;
1124
; fills the current last descriptor and
1125
; returns eax = next descriptor (not filled).
1126
proc ehci_alloc_packet
1127
; inherit some variables from the parent ehci_alloc_transfer
1128
virtual at ebp-8
1129
.origTD         dd      ?
1130
.packetSize     dd      ?
1131
                rd      2
1132
.buffer         dd      ?
1133
.transferSize   dd      ?
1134
.Flags          dd      ?
1135
.td             dd      ?
1136
.direction      dd      ?
1137
end virtual
1138
; 1. Allocate the next TD.
1139
        call    ehci_alloc_td
1140
        test    eax, eax
1141
        jz      .nothing
1142
; 2. Initialize controller-independent parts of both TDs.
1143
        push    eax
1144
        call    usb_init_transfer
1145
        pop     eax
1146
; 3. Copy PID to the new descriptor.
1147
        mov     edx, [ecx+ehci_gtd.Token-ehci_gtd.SoftwarePart]
1148
        mov     [eax+ehci_gtd.Token-ehci_gtd.SoftwarePart], edx
1149
        mov     [eax+ehci_gtd.NextTD-ehci_gtd.SoftwarePart], 1
1150
        mov     [eax+ehci_gtd.AlternateNextTD-ehci_gtd.SoftwarePart], 1
1151
; 4. Save the returned value (next descriptor).
1152
        push    eax
1153
; 5. Store the physical address of the next descriptor.
1154
        sub     eax, ehci_gtd.SoftwarePart
1155
        call    get_phys_addr
1156
        mov     [ecx+ehci_gtd.NextTD-ehci_gtd.SoftwarePart], eax
1157
; 6. For zero-length transfers, store zero in all fields for buffer addresses.
1158
; Otherwise, fill them with real values.
1159
        xor     eax, eax
1160
        mov     [ecx+ehci_gtd.Flags-ehci_gtd.SoftwarePart], eax
1161
repeat 10
1162
        mov     [ecx+ehci_gtd.BufferPointers-ehci_gtd.SoftwarePart+(%-1)*4], eax
1163
end repeat
1164
        cmp     [.packetSize], eax
1165
        jz      @f
1166
        mov     eax, [.buffer]
1167
        call    get_phys_addr
1168
        mov     [ecx+ehci_gtd.BufferPointers-ehci_gtd.SoftwarePart], eax
1169
        and     eax, 0xFFF
1170
        mov     edx, [.packetSize]
1171
        add     edx, eax
1172
        sub     edx, 0x1000
1173
        jbe     @f
1174
        mov     eax, [.buffer]
1175
        add     eax, 0x1000
1176
        call    get_pg_addr
1177
        mov     [ecx+ehci_gtd.BufferPointers+4-ehci_gtd.SoftwarePart], eax
1178
        sub     edx, 0x1000
1179
        jbe     @f
1180
        mov     eax, [.buffer]
1181
        add     eax, 0x2000
1182
        call    get_pg_addr
1183
        mov     [ecx+ehci_gtd.BufferPointers+8-ehci_gtd.SoftwarePart], eax
1184
        sub     edx, 0x1000
1185
        jbe     @f
1186
        mov     eax, [.buffer]
1187
        add     eax, 0x3000
1188
        call    get_pg_addr
1189
        mov     [ecx+ehci_gtd.BufferPointers+12-ehci_gtd.SoftwarePart], eax
1190
        sub     edx, 0x1000
1191
        jbe     @f
1192
        mov     eax, [.buffer]
1193
        add     eax, 0x4000
1194
        call    get_pg_addr
1195
        mov     [ecx+ehci_gtd.BufferPointers+16-ehci_gtd.SoftwarePart], eax
1196
@@:
1197
; 7. Fill Token field:
1198
; set Status = 0 (inactive, ehci_insert_transfer would mark everything active);
1199
; keep current PID if [.direction] is zero, use two lower bits of [.direction]
1200
; otherwise shifted as (0|1|2) -> (2|0|1);
1201
; set error counter to 3;
1202
; set current page to 0;
1203
; do not interrupt on complete (ehci_insert_transfer sets this bit where needed);
1204
; set DataToggle to bit 2 of [.direction].
1205
        mov     eax, [ecx+ehci_gtd.Token-ehci_gtd.SoftwarePart]
1206
        and     eax, 300h       ; keep PID code
1207
        mov     edx, [.direction]
1208
        test    edx, edx
1209
        jz      .haspid
1210
        and     edx, 3
1211
        dec     edx
1212
        jns     @f
1213
        add     edx, 3
1214
@@:
1215
        mov     ah, dl
1216
        mov     edx, [.direction]
1217
        and     edx, not 3
1218
        shl     edx, 29
1219
        or      eax, edx
1220
.haspid:
1221
        or      eax, 0C00h
1222
        mov     edx, [.packetSize]
1223
        shl     edx, 16
1224
        or      eax, edx
1225
        mov     [ecx+ehci_gtd.Token-ehci_gtd.SoftwarePart], eax
1226
; 4. Restore the returned value saved in step 2.
1227
        pop     eax
1228
.nothing:
1229
        ret
1230
endp
1231
 
1232
; This procedure is called from several places in main USB code
1233
; and activates the transfer which was previously allocated by
1234
; ehci_alloc_transfer.
1235
; ecx -> last descriptor for the transfer, ebx -> usb_pipe
1236
proc ehci_insert_transfer
1237
        or      byte [ecx+ehci_gtd.Token+1-ehci_gtd.SoftwarePart], 80h  ; set IOC bit
1238
        mov     eax, [esp+4]
1239
.activate:
1240
        or      byte [eax+ehci_gtd.Token-ehci_gtd.SoftwarePart], 80h    ; set Active bit
1241
        cmp     eax, ecx
1242
        mov     eax, [eax+usb_gtd.NextVirt]
1243
        jnz     .activate
1244
        ret
1245
endp
1246
 
1247
; This function is called from ehci_process_deferred when
1248
; reset signalling for a new device needs to be finished.
1249
proc ehci_port_reset_done
1250
        movzx   ecx, [esi+usb_controller.ResettingPort]
1251
        and     dword [edi+EhciPortsReg+ecx*4], not 12Ah
1252
        mov     eax, [timer_ticks]
1253
        mov     [esi+usb_controller.ResetTime], eax
1254
        mov     [esi+usb_controller.ResettingStatus], 2
1255
        DEBUGF 1,'K : [%d] EHCI %x: reset port %d done\n',[timer_ticks],esi,ecx
1256
        ret
1257
endp
1258
 
1259
; This function is called from ehci_process_deferred when
1260
; a new device has been reset, recovered after reset and needs to be configured.
1261
proc ehci_port_init
1262
; 1. Get the status and set it to zero.
1263
; If reset has been failed (device disconnected during reset),
1264
; continue to next device (if there is one).
1265
        xor     eax, eax
1266
        xchg    al, [esi+usb_controller.ResettingStatus]
1267
        test    al, al
1268
        js      usb_test_pending_port
1269
; 2. Get the port status. High-speed devices should be now enabled,
1270
; full-speed devices are left disabled;
1271
; if the port is disabled, release it to a companion and continue to
1272
; next device (if there is one).
1273
        movzx   ecx, [esi+usb_controller.ResettingPort]
1274
        mov     eax, [edi+EhciPortsReg+ecx*4]
1275
        DEBUGF 1,'K : [%d] EHCI %x status of port %d is %x\n',[timer_ticks],esi,ecx,eax
1276
        test    al, 4
1277
        jnz     @f
1278
;       DEBUGF 1,'K : USB port disabled after reset, status = %x\n',eax
1279
        dbgstr 'releasing to companion'
1280
        or      ah, 20h
1281
        mov     [edi+EhciPortsReg+ecx*4], eax
1282
        jmp     usb_test_pending_port
1283
@@:
1284
; 3. Call the worker procedure to notify the protocol layer
1285
; about new EHCI device. It is high-speed.
3626 Serge 1286
        movi    eax, USB_SPEED_HS
3555 Serge 1287
        call    ehci_new_device
1288
        test    eax, eax
1289
        jnz     .nothing
1290
; 4. If something at the protocol layer has failed
1291
; (no memory, no bus address), disable the port and stop the initialization.
1292
.disable_exit:
1293
        and     dword [edi+EhciPortsReg+ecx*4], not (4 or 2Ah)
1294
        jmp     usb_test_pending_port
1295
.nothing:
1296
        ret
1297
endp
1298
 
1299
; This procedure is called from ehci_port_init and from hub support code
1300
; when a new device is connected and has been reset.
1301
; It calls usb_new_device at the protocol layer with correct parameters.
1302
; in: esi -> usb_controller, eax = speed.
1303
proc ehci_new_device
1304
        push    ebx ecx ; save used registers (ecx is important for ehci_port_init)
1305
; 1. Store the speed for the protocol layer.
1306
        mov     [esi+usb_controller.ResettingSpeed], al
1307
; 2. Shift speed bits to the proper place in ehci_pipe.Token.
1308
        shl     eax, 12
1309
; 3. For high-speed devices, go to step 5 with edx = 0.
1310
        xor     edx, edx
1311
        cmp     ah, USB_SPEED_HS shl (12-8)
1312
        jz      .common
1313
; 4. For low-speed and full-speed devices, fill address:port
1314
; of the last high-speed hub (the closest to the device hub)
1315
; for split transactions, and set ControlEndpoint bit in eax;
1316
; ehci_init_pipe assumes that the parent pipe is a control pipe.
1317
        movzx   ecx, [esi+usb_controller.ResettingPort]
1318
        mov     edx, [esi+usb_controller.ResettingHub]
1319
        push    eax
1320
.find_hs_hub:
1321
        mov     eax, [edx+usb_hub.ConfigPipe]
1322
        mov     eax, [eax+usb_pipe.DeviceData]
1323
        cmp     [eax+usb_device_data.Speed], USB_SPEED_HS
1324
        jz      .found_hs_hub
1325
        movzx   ecx, [eax+usb_device_data.Port]
1326
        mov     edx, [eax+usb_device_data.Hub]
1327
        jmp     .find_hs_hub
1328
.found_hs_hub:
1329
        mov     edx, [edx+usb_hub.ConfigPipe]
1330
        inc     ecx
1331
        mov     edx, [edx+ehci_pipe.Token-ehci_pipe.SoftwarePart]
1332
        shl     ecx, 23
1333
        and     edx, 7Fh
1334
        shl     edx, 16
1335
        or      edx, ecx        ; ehci_pipe.Flags
1336
        pop     eax
1337
        or      eax, 1 shl 27   ; ehci_pipe.Token
1338
.common:
1339
; 5. Create pseudo-pipe in the stack.
1340
; See ehci_init_pipe: only .Controller, .Token, .Flags fields are used.
1341
        push    esi     ; ehci_pipe.SoftwarePart.Controller
1342
        mov     ecx, esp
1343
        sub     esp, ehci_pipe.SoftwarePart - ehci_pipe.Flags - 4
1344
        push    edx     ; ehci_pipe.Flags
1345
        push    eax     ; ehci_pipe.Token
1346
; 6. Notify the protocol layer.
1347
        call    usb_new_device
1348
; 7. Cleanup the stack after step 5 and return.
1349
        add     esp, ehci_pipe.SoftwarePart - ehci_pipe.Flags + 8
1350
        pop     ecx ebx ; restore used registers
1351
        ret
1352
endp
1353
 
1354
; This procedure is called in the USB thread from usb_thread_proc,
1355
; processes regular actions and those actions which can't be safely done
1356
; from interrupt handler.
1357
; Returns maximal time delta before the next call.
1358
proc ehci_process_deferred
1359
        push    ebx edi         ; save used registers to be stdcall
1360
        mov     edi, [esi+ehci_controller.MMIOBase2-sizeof.ehci_controller]
1361
; 1. Get the mask of events to process.
1362
        xor     eax, eax
1363
        xchg    eax, [esi+ehci_controller.DeferredActions-sizeof.ehci_controller]
1364
        push    eax
1365
; 2. Initialize the return value.
1366
        push    -1
1367
; Handle roothub events.
1368
; 3a. Test whether there are such events.
1369
        test    al, 4
1370
        jz      .skip_roothub
1371
; Status of some port has changed. Loop over all ports.
1372
; 3b. Prepare for the loop: start from port 0.
1373
        xor     ecx, ecx
1374
.portloop:
1375
; 3c. Get the port status and changes of it.
1376
; If there are no changes, just continue to the next port.
1377
        mov     eax, [edi+EhciPortsReg+ecx*4]
1378
        test    al, 2Ah
1379
        jz      .nextport
1380
; 3d. Clear change bits and read the status again.
1381
; (It is possible, although quite unlikely, that some event occurs between
1382
; the first read and the clearing, invalidating the old status. If an event
1383
; occurs after the clearing, we will not miss it, looking in the next scan.
1384
        mov     [edi+EhciPortsReg+ecx*4], eax
1385
        mov     ebx, eax
1386
        mov     eax, [edi+EhciPortsReg+ecx*4]
1387
        DEBUGF 1,'K : [%d] EHCI %x: status of port %d changed to %x\n',[timer_ticks],esi,ecx,ebx
1388
; 3e. Handle overcurrent.
1389
; Note: that needs work.
1390
        test    bl, 20h ; overcurrent change
1391
        jz      .noovercurrent
1392
        test    al, 10h ; overcurrent active
1393
        jz      .noovercurrent
1394
        DEBUGF 1,'K : overcurrent at port %d\n',ecx
1395
.noovercurrent:
1396
; 3f. Handle changing of connection status.
1397
        test    bl, 2
1398
        jz      .nocsc
1399
; There was a connect or disconnect event at this port.
1400
; 3g. Disconnect the old device on this port, if any.
1401
; If the port was resetting, indicate fail; later stages will process it.
1402
        cmp     [esi+usb_controller.ResettingHub], 0
1403
        jnz     @f
1404
        cmp     cl, [esi+usb_controller.ResettingPort]
1405
        jnz     @f
1406
        mov     [esi+usb_controller.ResettingStatus], -1
1407
@@:
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
1661
        cmp     byte [ebx+ehci_gtd.Token-ehci_gtd.SoftwarePart], 0
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
1693
;       lea     eax, [ebx-ehci_gtd.SoftwarePart]
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.
1700
        mov     eax, [ebx+ehci_gtd.Token-ehci_gtd.SoftwarePart]
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
1718
        test    byte [ebx+ehci_gtd.Flags-ehci_gtd.SoftwarePart], 1
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
1748
        sub     ebx, ehci_gtd.SoftwarePart
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]
1755
        sub     ecx, ehci_pipe.SoftwarePart
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
3626 Serge 1787
        movi    ecx, USB_STATUS_UNDERRUN
3555 Serge 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
1805
        test    byte [ebx+ehci_gtd.Flags-ehci_gtd.SoftwarePart], 1
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]
1835
        mov     eax, [ebx+ehci_gtd.NextTD-ehci_gtd.SoftwarePart]
1836
        or      al, 1
1837
        mov     [edx+ehci_pipe.Overlay.NextTD-ehci_pipe.SoftwarePart], eax
1838
        mov     [edx+ehci_pipe.Overlay.AlternateNextTD-ehci_pipe.SoftwarePart], eax
1839
        cmp     [edx+usb_pipe.Type], CONTROL_PIPE
1840
        jz      .control
1841
; Bulk/interrupt transfer; halt the queue.
1842
        mov     [edx+ehci_pipe.Overlay.Token-ehci_pipe.SoftwarePart], 40h
1843
        pop     edx
1844
        jmp     .notify
1845
; Control transfer.
1846
.control:
1847
        and     [edx+ehci_pipe.Overlay.Token-ehci_pipe.SoftwarePart], 0
1848
        dec     [edx+ehci_pipe.Overlay.NextTD-ehci_pipe.SoftwarePart]
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
1858
        test    word [ebx+ehci_pipe.Flags-ehci_pipe.SoftwarePart+2], 3FFFh
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
1873
        mov     edx, [ebx+ehci_pipe.NextQH-ehci_pipe.SoftwarePart]
1874
        jb      .prev_is_static
1875
        mov     [eax+ehci_pipe.NextQH-ehci_pipe.SoftwarePart], edx
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
1885
        stdcall usb_allocate_common, sizeof.ehci_gtd
1886
        test    eax, eax
1887
        jz      @f
1888
        add     eax, ehci_gtd.SoftwarePart
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
1898
        sub     dword [esp+4], ehci_gtd.SoftwarePart
1899
        jmp     usb_free_common
1900
endp