summaryrefslogtreecommitdiff
path: root/nrf-softdevice/src/ble/l2cap.rs
blob: ab366e16dc705b738ff1bac0b16bac01bd9e2435 (plain)
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Link-Layer Control and Adaptation Protocol

use core::marker::PhantomData;
use core::ptr;
use core::ptr::NonNull;
use core::sync::atomic::{AtomicBool, Ordering};
use core::u16;

use crate::ble::*;
use crate::raw;
use crate::util::{get_union_field, Portal};
use crate::{RawError, Softdevice};

pub(crate) unsafe fn on_evt(ble_evt: *const raw::ble_evt_t) {
    let l2cap_evt = get_union_field(ble_evt, &(*ble_evt).evt.l2cap_evt);
    match (*ble_evt).header.evt_id as u32 {
        raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_CREDIT => {}
        raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_SDU_BUF_RELEASED => {
            let params = &l2cap_evt.params.ch_sdu_buf_released;
            let pkt = unwrap!(NonNull::new(params.sdu_buf.p_data));
            (unwrap!(PACKET_FREE))(pkt)
        }
        raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_TX => {
            let params = &l2cap_evt.params.tx;
            let pkt = unwrap!(NonNull::new(params.sdu_buf.p_data));
            portal(l2cap_evt.conn_handle).call(ble_evt);
            (unwrap!(PACKET_FREE))(pkt)
        }
        _ => {
            portal(l2cap_evt.conn_handle).call(ble_evt);
        }
    };
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum TxError<P: Packet> {
    Disconnected,
    TxQueueFull(P),
    Raw(RawError),
}

impl<P: Packet> From<DisconnectedError> for TxError<P> {
    fn from(_err: DisconnectedError) -> Self {
        TxError::Disconnected
    }
}

impl<P: Packet> From<RawError> for TxError<P> {
    fn from(err: RawError) -> Self {
        TxError::Raw(err)
    }
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RxError {
    Disconnected,
    AllocateFailed,
    Raw(RawError),
}

impl From<DisconnectedError> for RxError {
    fn from(_err: DisconnectedError) -> Self {
        RxError::Disconnected
    }
}

impl From<RawError> for RxError {
    fn from(err: RawError) -> Self {
        RxError::Raw(err)
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SetupError {
    Disconnected,
    Refused,
    Raw(RawError),
}

impl From<DisconnectedError> for SetupError {
    fn from(_err: DisconnectedError) -> Self {
        SetupError::Disconnected
    }
}

impl From<RawError> for SetupError {
    fn from(err: RawError) -> Self {
        SetupError::Raw(err)
    }
}

const PORTAL_NEW: Portal<*const raw::ble_evt_t> = Portal::new();
static PORTALS: [Portal<*const raw::ble_evt_t>; CONNS_MAX] = [PORTAL_NEW; CONNS_MAX];
pub(crate) fn portal(conn_handle: u16) -> &'static Portal<*const raw::ble_evt_t> {
    &PORTALS[conn_handle as usize]
}

pub trait Packet: Sized {
    const MTU: usize;
    fn allocate() -> Option<NonNull<u8>>;
    fn into_raw_parts(self) -> (NonNull<u8>, usize);
    unsafe fn from_raw_parts(ptr: NonNull<u8>, len: usize) -> Self;
}

pub struct L2cap<P: Packet> {
    _private: PhantomData<*mut P>,
}

static IS_INIT: AtomicBool = AtomicBool::new(false);
static mut PACKET_FREE: Option<unsafe fn(NonNull<u8>)> = None;

impl<P: Packet> L2cap<P> {
    pub fn init(_sd: &Softdevice) -> Self {
        if IS_INIT
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            panic!("L2cap::init() called multiple times.")
        }

        unsafe {
            PACKET_FREE = Some(|ptr| {
                P::from_raw_parts(ptr, 0);
                // create Packet from pointer, will be freed on drop
            })
        }

        Self {
            _private: PhantomData,
        }
    }

    pub async fn setup(
        &self,
        conn: &Connection,
        config: &Config,
        psm: u16,
    ) -> Result<Channel<P>, SetupError> {
        let sd = unsafe { Softdevice::steal() };

        let conn_handle = conn.with_state(|state| state.check_connected())?;
        let mut cid: u16 = raw::BLE_L2CAP_CID_INVALID as _;
        let params = raw::ble_l2cap_ch_setup_params_t {
            le_psm: psm,
            status: 0, // only used when responding
            rx_params: raw::ble_l2cap_ch_rx_params_t {
                rx_mps: sd.l2cap_rx_mps,
                rx_mtu: P::MTU as u16,
                sdu_buf: raw::ble_data_t {
                    len: 0,
                    p_data: ptr::null_mut(),
                },
            },
        };
        let ret = unsafe { raw::sd_ble_l2cap_ch_setup(conn_handle, &mut cid, &params) };
        if let Err(err) = RawError::convert(ret) {
            warn!("sd_ble_l2cap_ch_setup err {:?}", err);
            return Err(err.into());
        }
        info!("cid {:?}", cid);

        portal(conn_handle)
            .wait_once(|ble_evt| unsafe {
                match (*ble_evt).header.evt_id as u32 {
                    raw::BLE_GAP_EVTS_BLE_GAP_EVT_DISCONNECTED => {
                        return Err(SetupError::Disconnected)
                    }
                    raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_RELEASED => {
                        // It is possible to get L2CAP_EVT_CH_RELEASED for the
                        // "half-setup" channel if the conn gets disconnected while
                        // setting it up.
                        return Err(SetupError::Disconnected);
                    }
                    raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_SETUP => {
                        let l2cap_evt = get_union_field(ble_evt, &(*ble_evt).evt.l2cap_evt);
                        let _evt = &l2cap_evt.params.ch_setup;

                        // default is 1
                        if config.credits != 1 {
                            let ret = raw::sd_ble_l2cap_ch_flow_control(
                                conn_handle,
                                cid,
                                config.credits,
                                ptr::null_mut(),
                            );
                            if let Err(err) = RawError::convert(ret) {
                                warn!("sd_ble_l2cap_ch_flow_control err {:?}", err);
                                return Err(err.into());
                            }
                        }

                        Ok(Channel {
                            conn: conn.clone(),
                            cid,
                            _private: PhantomData,
                        })
                    }
                    raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_SETUP_REFUSED => {
                        let l2cap_evt = get_union_field(ble_evt, &(*ble_evt).evt.l2cap_evt);
                        let _evt = &l2cap_evt.params.ch_setup_refused;
                        Err(SetupError::Refused)
                    }
                    e => panic!("unexpected event {}", e),
                }
            })
            .await
    }

    pub async fn listen(
        &self,
        conn: &Connection,
        config: &Config,
        psm: u16,
    ) -> Result<Channel<P>, SetupError> {
        self.listen_with(conn, config, move |got_psm| got_psm == psm)
            .await
            .map(|(_, ch)| ch)
    }

    pub async fn listen_with(
        &self,
        conn: &Connection,
        config: &Config,
        mut accept_psm: impl FnMut(u16) -> bool,
    ) -> Result<(u16, Channel<P>), SetupError> {
        let sd = unsafe { Softdevice::steal() };
        let conn_handle = conn.with_state(|state| state.check_connected())?;

        portal(conn_handle)
            .wait_many(|ble_evt| unsafe {
                match (*ble_evt).header.evt_id as u32 {
                    raw::BLE_GAP_EVTS_BLE_GAP_EVT_DISCONNECTED => {
                        return Some(Err(SetupError::Disconnected))
                    }
                    raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_SETUP_REQUEST => {
                        let l2cap_evt = get_union_field(ble_evt, &(*ble_evt).evt.l2cap_evt);
                        let evt = &l2cap_evt.params.ch_setup_request;

                        let mut cid: u16 = l2cap_evt.local_cid;
                        if accept_psm(evt.le_psm) {
                            let params = raw::ble_l2cap_ch_setup_params_t {
                                le_psm: evt.le_psm,
                                status: raw::BLE_L2CAP_CH_STATUS_CODE_SUCCESS as _,
                                rx_params: raw::ble_l2cap_ch_rx_params_t {
                                    rx_mps: sd.l2cap_rx_mps,
                                    rx_mtu: P::MTU as u16,
                                    sdu_buf: raw::ble_data_t {
                                        len: 0,
                                        p_data: ptr::null_mut(),
                                    },
                                },
                            };

                            let ret = raw::sd_ble_l2cap_ch_setup(conn_handle, &mut cid, &params);
                            if let Err(err) = RawError::convert(ret) {
                                warn!("sd_ble_l2cap_ch_setup err {:?}", err);
                                return Some(Err(err.into()));
                            }

                            // default is 1
                            if config.credits != 1 {
                                let ret = raw::sd_ble_l2cap_ch_flow_control(
                                    conn_handle,
                                    cid,
                                    config.credits,
                                    ptr::null_mut(),
                                );
                                if let Err(err) = RawError::convert(ret) {
                                    warn!("sd_ble_l2cap_ch_flow_control err {:?}", err);
                                    return Some(Err(err.into()));
                                }
                            }

                            Some(Ok((
                                evt.le_psm,
                                Channel {
                                    _private: PhantomData,
                                    cid,
                                    conn: conn.clone(),
                                },
                            )))
                        } else {
                            let params = raw::ble_l2cap_ch_setup_params_t {
                                le_psm: evt.le_psm,
                                status: raw::BLE_L2CAP_CH_STATUS_CODE_LE_PSM_NOT_SUPPORTED as _,
                                rx_params: mem::zeroed(),
                            };

                            let ret = raw::sd_ble_l2cap_ch_setup(conn_handle, &mut cid, &params);
                            if let Err(_err) = RawError::convert(ret) {
                                warn!("sd_ble_l2cap_ch_setup err {:?}", _err);
                            }

                            None
                        }
                    }
                    e => panic!("unexpected event {}", e),
                }
            })
            .await
    }
}

pub struct Config {
    pub credits: u16,
}

pub struct Channel<P: Packet> {
    _private: PhantomData<*mut P>,
    conn: Connection,
    cid: u16,
}

impl<P: Packet> Clone for Channel<P> {
    fn clone(&self) -> Self {
        Self {
            _private: PhantomData,
            conn: self.conn.clone(),
            cid: self.cid,
        }
    }
}

impl<P: Packet> Channel<P> {
    pub fn connection(&self) -> &Connection {
        &self.conn
    }

    pub fn try_tx(&self, sdu: P) -> Result<(), TxError<P>> {
        let conn_handle = self.conn.with_state(|s| s.check_connected())?;

        let (ptr, len) = sdu.into_raw_parts();
        assert!(len <= P::MTU);
        let data = raw::ble_data_t {
            p_data: ptr.as_ptr(),
            len: len as u16,
        };

        let ret = unsafe { raw::sd_ble_l2cap_ch_tx(conn_handle, self.cid, &data) };
        match RawError::convert(ret) {
            Err(RawError::Resources) => {
                Err(TxError::TxQueueFull(unsafe { P::from_raw_parts(ptr, len) }))
            }
            Err(err) => {
                warn!("sd_ble_l2cap_ch_tx err {:?}", err);
                // The SD didn't take ownership of the buffer, so it's on us to free it.
                // Reconstruct the P and let it get dropped.
                unsafe { P::from_raw_parts(ptr, len) };

                Err(err.into())
            }
            Ok(()) => Ok(()),
        }
    }

    pub async fn tx(&self, mut sdu: P) -> Result<(), TxError<P>> {
        let conn_handle = self.conn.with_state(|s| s.check_connected())?;

        loop {
            match self.try_tx(sdu) {
                Ok(()) => {
                    return Ok(());
                }
                Err(TxError::TxQueueFull(ret_sdu)) => {
                    sdu = ret_sdu;
                    portal(conn_handle)
                        .wait_once(|ble_evt| unsafe {
                            match (*ble_evt).header.evt_id as u32 {
                                raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_TX => (),
                                _ => unreachable!("Invalid event"),
                            }
                        })
                        .await;
                    continue;
                }
                Err(e) => {
                    return Err(e);
                }
            }
        }
    }

    pub async fn rx(&self) -> Result<P, RxError> {
        let conn_handle = self.conn.with_state(|s| s.check_connected())?;

        let ptr = P::allocate().ok_or(RxError::AllocateFailed)?;
        let data = raw::ble_data_t {
            p_data: ptr.as_ptr(),
            len: P::MTU as u16,
        };

        let ret = unsafe { raw::sd_ble_l2cap_ch_rx(conn_handle, self.cid, &data) };
        if let Err(err) = RawError::convert(ret) {
            warn!("sd_ble_l2cap_ch_rx err {:?}", err);
            // The SD didn't take ownership of the buffer, so it's on us to free it.
            // Reconstruct the P and let it get dropped.
            unsafe { P::from_raw_parts(ptr, 0) };
            return Err(err.into());
        }

        portal(conn_handle)
            .wait_many(|ble_evt| unsafe {
                match (*ble_evt).header.evt_id as u32 {
                    raw::BLE_GAP_EVTS_BLE_GAP_EVT_DISCONNECTED => Some(Err(RxError::Disconnected)),
                    raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_RELEASED => {
                        Some(Err(RxError::Disconnected))
                    }
                    raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_RX => {
                        let l2cap_evt = get_union_field(ble_evt, &(*ble_evt).evt.l2cap_evt);
                        let evt = &l2cap_evt.params.rx;

                        let ptr = unwrap!(NonNull::new(evt.sdu_buf.p_data));
                        let len = evt.sdu_len;
                        let pkt = Packet::from_raw_parts(ptr, len as usize);
                        Some(Ok(pkt))
                    }
                    _ => None,
                }
            })
            .await
    }
}