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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//! Transmit side of the Resource Manager.
use structbuf::Pack;
use tracing::{trace, warn};
use super::*;
/// Outbound PDU transfer state.
#[derive(Debug)]
pub(super) struct State {
alloc: Arc<Alloc>,
sched: SyncMutex<Scheduler>,
}
impl State {
/// Creates a new outbound transfer state.
#[must_use]
#[inline]
pub fn new(t: &Arc<dyn host::Transport>, max_pkts: u16, acl_data_len: u16) -> Arc<Self> {
Arc::new(Self {
alloc: Alloc::new(Arc::clone(t), host::Direction::Out, acl_data_len),
sched: SyncMutex::new(Scheduler::new(max_pkts)),
})
}
/// Returns the maximum frame length that avoids fragmentation.
#[inline]
pub fn preferred_frame_len(&self) -> u16 {
self.alloc.acl_data_len
}
/// Allocates an outbound frame with a zero-filled basic L2CAP header.
#[inline]
pub fn new_frame(&self, max_frame_len: usize) -> Frame {
self.alloc.frame(max_frame_len)
}
/// Sends the PDU, returning as soon as the last fragment is submitted to
/// the controller.
#[inline]
pub async fn send(self: &Arc<Self>, ch: &Arc<RawChan>, pdu: Frame) -> Result<()> {
let (tx, ch) = (Arc::clone(self), Arc::clone(ch));
let guard = self.sched.lock().schedule(tx, ch)?;
guard.send(pdu).await
}
/// Registers a new LE-U logical link.
pub fn register_link(&self, link: LeU) {
self.sched.lock().register_link(link);
}
/// Removes LE-U logical link registration.
pub fn handle_disconnect(&self, evt: hci::DisconnectionComplete) {
self.sched.lock().disconnect_link(LeU::new(evt.handle));
}
/// Updates controller's buffer status.
pub fn handle_num_completed(&self, evt: &hci::NumberOfCompletedPackets) {
let pkts = (evt.as_ref().iter()).map(|&(cn, complete)| (LeU::new(cn), complete));
self.sched.lock().ack(pkts);
}
// TODO: Handle Data Buffer Overflow event?
}
/// Outbound PDU scheduler. Ensures that the controller's transmit buffer is
/// shared fairly between all logical links. Within each logical link, PDUs are
/// transmitted in FIFO order.
#[derive(Debug)]
struct Scheduler {
/// Channels that are blocked from sending because another channel on the
/// same logical link is sending a PDU ([Vol 3] Part A, Section 7.2.1).
blocked: HashMap<LeU, VecDeque<Arc<RawChan>>>,
/// Channels from distinct logical links that are ready to send PDU
/// fragments as soon as controller buffer space is available.
ready: VecDeque<Arc<RawChan>>,
/// Current channel with permission to send.
active: Option<Arc<RawChan>>,
/// Number of PDU fragments sent to the controller for each logical link,
/// but not yet acknowledged by `HCI_Number_Of_Completed_Packets` event.
sent: HashMap<LeU, u16>,
/// Number of new PDU fragments that the controller can accept immediately.
quota: u16,
}
impl Scheduler {
/// Creates a new outbound PDU scheduler. This assumes that the controller
/// is ready to accept `max_pkts` data packets.
#[inline]
#[must_use]
fn new(max_pkts: u16) -> Self {
Self {
blocked: HashMap::new(),
ready: VecDeque::new(),
active: None,
sent: HashMap::new(),
quota: max_pkts,
}
}
/// Registers a new LE-U logical link, allowing it to send data.
#[inline]
fn register_link(&mut self, link: LeU) {
trace!("Adding logical link: {link}");
self.blocked.entry(link).or_default();
self.sent.entry(link).or_default();
}
/// Removes an LE-U logical link after an `HCI_Disconnection_Complete`
/// event. This does not change the status of any affected channels, so
/// [`SchedulerGuard`]s will block indefinitely until the channels are
/// closed.
#[inline]
fn disconnect_link(&mut self, link: LeU) {
self.remove_link(link);
if let Some(sent) = self.sent.remove(&link) {
self.quota += sent; // [Vol 4] Part E, Section 4.3
self.reschedule();
}
}
/// Removes an LE-U logical link without assuming that any unacknowledged
/// packets were flushed from the controller's buffer.
#[inline]
fn remove_link(&mut self, link: LeU) {
trace!("Removing logical link: {link}");
let Some(blocked) = self.blocked.remove(&link) else { return };
for ch in blocked {
ch.state.lock().set_scheduled(false);
}
let mut is_active = false;
if let Some(ch) = self.active.as_ref() {
if ch.cid.link == link {
// The channel may be in the process of sending a fragment, and
// we don't want another channel to start a new transfer before
// the current one is finished. We stop this channel from
// sending any more fragments, but keep it active until it is
// closed and its SchedulerGuard is dropped.
// TODO: Use an explicit SENDING Status?
ch.deny_send();
is_active = true;
}
}
if !is_active {
if let Some(i) = self.ready.iter().position(|other| other.cid.link == link) {
(self.ready.remove(i).unwrap().state.lock()).set_scheduled(false);
}
}
if let Entry::Occupied(sent) = self.sent.entry(link) {
if *sent.get() == 0 {
sent.remove();
}
}
}
/// Updates controller's buffer status.
#[inline]
fn ack(&mut self, pkts: impl Iterator<Item = (LeU, u16)>) {
for (link, mut complete) in pkts {
let Entry::Occupied(mut sent) = self.sent.entry(link) else {
warn!("ACL data packet completion for an unknown {link} ({complete})");
continue;
};
let rem = sent.get().checked_sub(complete).unwrap_or_else(|| {
let sent = *sent.get();
warn!("ACL data packet completion mismatch for {link} (sent={sent}, acked={complete})");
complete = sent;
0
});
self.quota += complete;
if self.blocked.contains_key(&link) || rem > 0 {
sent.insert(rem);
} else {
sent.remove(); // remove_link was called
}
}
self.reschedule();
}
/// Allows the next ready channel to send its PDU fragment. The caller must
/// not be holding a lock on any channel.
fn reschedule(&mut self) {
if self.quota == 0 || self.active.is_some() {
return;
}
self.active = match self.ready.len() {
0 => return,
1 => self.ready.pop_front(),
// Pick the logical link with the fewest unacknowledged packets to
// maximize physical link utilization and prevent a stalled link
// from filling up the controller's buffer. Channels are removed
// from the front and pushed to the back after sending, resulting in
// round-robin scheduling when the number of unacknowledged packets
// is equal.
_ => self.ready.remove(
(self.ready.iter().map(|ch| self.sent[&ch.cid.link]))
.enumerate()
.reduce(|min, cur| if min.1 <= cur.1 { min } else { cur })
.map_or(0, |min| min.0),
),
};
self.active.as_ref().unwrap().allow_send();
}
/// Returns whether channel `ch` is the current sender. This is done by
/// comparing pointers because connection handles can be reused before the
/// channel is removed from the scheduler ([Vol 4] Part E, Section 5.3).
#[inline]
fn is_active(&self, ch: &Arc<RawChan>) -> bool {
(self.active.as_ref()).map_or(false, |act| Arc::ptr_eq(act, ch))
}
/// Schedules channel `ch` for sending a PDU.
fn schedule(&mut self, tx: Arc<State>, ch: Arc<RawChan>) -> Result<SchedulerGuard> {
let Some(blocked) = self.blocked.get_mut(&ch.cid.link) else {
return Err(Error::InvalidConn(ch.cid.link.into()));
};
let mut cs = ch.state.lock();
assert!(
!cs.is_scheduled(),
"A channel may not send two PDUs concurrently"
);
cs.err(ch.cid)?;
if self.quota > 0 && self.active.is_none() {
// Fast path for the only sender, no notification needed
cs.set_scheduled_active();
drop(cs);
self.active = Some(Arc::clone(&ch));
} else {
cs.set_scheduled(true);
drop(cs);
if blocked.is_empty()
&& (self.active.iter().chain(self.ready.iter()))
.all(|other| other.cid.link != ch.cid.link)
{
// First sender for this logical link
self.ready.push_back(Arc::clone(&ch));
} else {
// Multiple senders for this logical link
blocked.push_back(Arc::clone(&ch));
}
}
Ok(SchedulerGuard { tx, ch })
}
/// Updates scheduler state after a PDU fragment is sent to the controller.
fn sent(&mut self, ch: &Arc<RawChan>, more: bool) {
debug_assert!(self.is_active(ch));
if !self.blocked.contains_key(&ch.cid.link) {
// remove_link was called. The channel already can't send, but keep
// it active until it is closed and removed by SchedulerGuard.
// Testing shows that at least one controller does not report
// invalid connection handles in HCI_Number_Of_Completed_Packets
// events, so we do not change self.quota or self.sent.
return;
}
self.quota -= 1; // [Vol 4] Part E, Section 4.1.1
*self.sent.get_mut(&ch.cid.link).unwrap() += 1;
if !more {
// Keep the channel active so that remove() takes the fast path
ch.deny_send();
} else if self.quota == 0 || !self.ready.is_empty() {
ch.deny_send();
self.ready.push_back(self.active.take().unwrap());
self.reschedule();
} else {
// Channel is the only sender and can send another PDU fragment
}
}
/// Removes channel `ch` from the scheduler.
fn remove(&mut self, ch: &Arc<RawChan>) {
#[inline]
fn position<V>(q: &VecDeque<Arc<V>>, v: &Arc<V>) -> Option<usize> {
q.iter().position(|other| Arc::ptr_eq(other, v))
}
if self.is_active(ch) {
// Fast path for the active channel
self.active = None;
ch.state.lock().set_scheduled(false);
if let Some(next) = (self.blocked.get_mut(&ch.cid.link)).and_then(VecDeque::pop_front) {
self.ready.push_back(next);
}
self.reschedule();
return;
}
let Some(blocked) = self.blocked.get_mut(&ch.cid.link) else { return };
let mut cs = ch.state.lock();
if !cs.is_scheduled() {
// The channel was already removed by remove_link() and a new link
// was created with the same connection handle.
return;
}
cs.set_scheduled(false);
let Some(i) = position(&self.ready, ch) else {
blocked.remove(position(blocked, ch).unwrap());
return;
};
match blocked.pop_front() {
Some(next) => self.ready[i] = next,
None => {
self.ready.remove(i);
}
}
}
}
/// Scheduled PDU send task. Ensures that the channel is removed from the
/// Scheduler when the send operation is done (or dropped).
#[derive(Debug)]
#[must_use]
struct SchedulerGuard {
tx: Arc<State>,
ch: Arc<RawChan>,
}
impl SchedulerGuard {
/// Performs PDU fragmentation and submits each fragment to the controller.
async fn send(self, mut pdu: Frame) -> Result<()> {
// Update basic L2CAP header ([Vol 3] Part A, Section 3.1)
let mut hdr = pdu.at(0);
let pdu_len = u16::try_from(hdr.as_ref().len() - L2CAP_HDR).unwrap();
hdr.u16(pdu_len).u16(self.ch.cid.chan);
if let Some(xfer) = pdu.take_xfer() {
// Fast path for a single-fragment PDU
debug_assert_eq!(xfer.dir(), host::Direction::Out);
return self.send_frag(xfer, false, false).await.map(|_xfer| ());
}
let mut xfer = self.tx.alloc.xfer();
let frags = pdu.as_ref().chunks(self.tx.alloc.acl_data_len as _);
let last = frags.len() - 1;
for (i, frag) in frags.enumerate() {
xfer.at(ACL_HDR).put(frag);
xfer = self.send_frag(xfer, i != 0, i != last).await?;
if i != last {
xfer.reset();
}
}
Ok(())
}
/// Sends a single PDU fragment.
async fn send_frag(
&self,
mut xfer: AclTransfer,
is_cont: bool,
more: bool,
) -> Result<AclTransfer> {
// Update ACL data packet header ([Vol 4] Part E, Section 5.4.2)
let data_len = u16::try_from(xfer.as_ref().len() - ACL_HDR).unwrap();
xfer.at(0)
.u16(u16::from(is_cont) << hci::ConnHandle::BITS | u16::from(self.ch.cid.link))
.u16(data_len);
self.ch.may_send().await?;
trace!(
"{}{}: {:02X?}",
if is_cont { "Cont. " } else { "" },
self.ch.cid,
&xfer.as_ref()[4 + 4..] // Skip ACL and L2CAP headers
);
match xfer.submit().await {
Ok(xfer) => {
self.tx.sched.lock().sent(&self.ch, more);
Ok(xfer)
}
Err(e) => {
self.ch.set_error();
Err(e.into())
}
}
}
}
impl Drop for SchedulerGuard {
#[inline]
fn drop(&mut self) {
// TODO: Mark the channel as broken if the entire PDU was not sent?
self.tx.sched.lock().remove(&self.ch);
}
}