-
Notifications
You must be signed in to change notification settings - Fork 51
/
endpoint_handler.go
124 lines (98 loc) · 2.1 KB
/
endpoint_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// USB device mode support
// https://github.com/f-secure-foundry/tamago
//
// Copyright (c) F-Secure Corporation
// https://foundry.f-secure.com
//
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
package usb
import (
"log"
"runtime"
"sync"
"github.com/f-secure-foundry/tamago/internal/reg"
)
// Endpoint represents a USB 2.0 endpoint.
type Endpoint struct {
sync.Mutex
bus *USB
wg *sync.WaitGroup
desc *EndpointDescriptor
n int
dir int
}
// Init initializes an endpoint.
func (ep *Endpoint) Init() {
ep.n = ep.desc.Number()
ep.dir = ep.desc.Direction()
ep.bus.set(ep.n, ep.dir, int(ep.desc.MaxPacketSize), ep.desc.Zero, 0)
ep.bus.enable(ep.n, ep.dir, ep.desc.TransferType())
}
// Flush clears the endpoint receive and transmit buffers.
func (ep *Endpoint) Flush() {
reg.Set(ep.bus.flush, (ep.dir*16)+ep.n)
}
// Start initializes and runs an USB endpoint.
func (ep *Endpoint) Start() {
var err error
var buf []byte
var res []byte
if ep.desc.Function == nil {
return
}
ep.Lock()
defer func() {
ep.Flush()
ep.wg.Done()
ep.Unlock()
}()
ep.Init()
for {
runtime.Gosched()
if ep.dir == OUT {
buf, err = ep.bus.rx(ep.n, false, res)
if err == nil && len(buf) != 0 {
res, err = ep.desc.Function(buf, err)
}
} else {
res, err = ep.desc.Function(nil, err)
if err == nil && len(res) != 0 {
err = ep.bus.tx(ep.n, false, res)
}
}
if err != nil {
ep.Flush()
log.Printf("imx6_usb: EP%d.%d transfer error, %v", ep.n, ep.dir, err)
}
select {
case <-ep.bus.done:
return
default:
}
}
}
func (hw *USB) startEndpoints(wg *sync.WaitGroup, dev *Device, configurationValue uint8) {
if configurationValue == 0 {
return
}
hw.done = make(chan bool)
for _, conf := range dev.Configurations {
if configurationValue != conf.ConfigurationValue {
continue
}
for _, iface := range conf.Interfaces {
for _, desc := range iface.Endpoints {
ep := &Endpoint{
wg: wg,
bus: hw,
desc: desc,
}
wg.Add(1)
go func(ep *Endpoint) {
ep.Start()
}(ep)
}
}
}
}