capsules_extra/net/udp/driver.rs
1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! UDP userspace interface for transmit and receive.
6//!
7//! Implements a userspace interface for sending and receiving UDP messages.
8//! Processes use this driver to send UDP packets from a common interface and
9//! bind to UDP ports for receiving packets. Also exposes a list of interface
10//! addresses to the application (currently hard-coded).
11
12use crate::net::ipv6::ip_utils::IPAddr;
13use crate::net::network_capabilities::NetworkCapability;
14use crate::net::stream::SResult;
15use crate::net::stream::encode_u8;
16use crate::net::stream::encode_u16;
17use crate::net::udp::udp_port_table::{PortQuery, UdpPortManager};
18use crate::net::udp::udp_recv::UDPRecvClient;
19use crate::net::udp::udp_send::{UDPSendClient, UDPSender};
20use crate::net::util::host_slice_to_u16;
21
22use core::cell::Cell;
23use core::mem::size_of;
24use core::{cmp, mem};
25
26use kernel::capabilities::UdpDriverCapability;
27use kernel::debug;
28use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
29use kernel::processbuffer::{ReadableProcessBuffer, WriteableProcessBuffer};
30use kernel::syscall::{CommandReturn, SyscallDriver};
31use kernel::utilities::cells::MapCell;
32use kernel::utilities::leasable_buffer::SubSliceMut;
33use kernel::{ErrorCode, ProcessId};
34
35use capsules_core::driver;
36pub const DRIVER_NUM: usize = driver::NUM::Udp as usize;
37
38/// IDs for subscribed upcalls.
39mod upcall {
40 /// Callback for when packet is received. If no port has been bound, return
41 /// `RESERVE` to indicate that port binding is is a prerequisite to
42 /// reception.
43 pub const PACKET_RECEIVED: usize = 0;
44 /// Callback for when packet is transmitted.
45 ///
46 /// Notably, this callback receives the result of the send_done callback
47 /// from udp_send.rs, which does not currently pass information regarding
48 /// whether packets were acked at the link layer.
49 pub const PACKET_TRANSMITTED: usize = 1;
50 /// Number of upcalls.
51 pub const COUNT: u8 = 2;
52}
53
54/// Ids for read-only allow buffers
55mod ro_allow {
56 /// Write buffer. Contains the UDP payload to be transmitted. Returns SIZE
57 /// if the passed buffer is too long, and NOSUPPORT if an invalid
58 /// `allow_num` is passed.
59 pub const WRITE: usize = 0;
60 /// The number of allow buffers the kernel stores for this grant
61 pub const COUNT: u8 = 1;
62}
63
64/// Ids for read-write allow buffers
65mod rw_allow {
66 /// Read buffer. Will contain the received payload.
67 pub const READ: usize = 0;
68 /// Config buffer. Used to contain miscellaneous data associated with some
69 /// commands, namely source/destination addresses and ports.
70 pub const CFG: usize = 1;
71 /// Rx config buffer. Used to contain source/destination addresses and ports
72 /// for receives (separate from `2` because receives may be waiting for an
73 /// incoming packet asynchronously).
74 pub const RX_CFG: usize = 2;
75 /// The number of allow buffers the kernel stores for this grant
76 pub const COUNT: u8 = 3;
77}
78
79#[derive(Debug, Copy, Clone, Eq, PartialEq)]
80pub struct UDPEndpoint {
81 addr: IPAddr,
82 port: u16,
83}
84
85impl UDPEndpoint {
86 /// This function serializes the `UDPEndpoint` into the provided buffer.
87 ///
88 /// # Arguments
89 ///
90 /// - `buf` - A mutable buffer to serialize the `UDPEndpoint` into
91 /// - `offset` - The current offset into the provided buffer
92 ///
93 /// # Return Value
94 ///
95 /// This function returns the new offset into the buffer wrapped in an
96 /// SResult.
97 pub fn encode(&self, buf: &mut [u8], offset: usize) -> SResult<usize> {
98 stream_len_cond!(buf, size_of::<UDPEndpoint>() + offset);
99
100 let mut off = offset;
101 for i in 0..16 {
102 off = enc_consume!(buf, off; encode_u8, self.addr.0[i]);
103 }
104 off = enc_consume!(buf, off; encode_u16, self.port);
105 stream_done!(off, off);
106 }
107
108 /// This function checks if the UDPEndpoint specified is the 0 address + 0 port.
109 pub fn is_zero(&self) -> bool {
110 self.addr.is_unspecified() && self.port == 0
111 }
112}
113
114#[derive(Default)]
115pub struct App {
116 pending_tx: Option<[UDPEndpoint; 2]>,
117 bound_port: Option<UDPEndpoint>,
118}
119
120#[allow(dead_code)]
121pub struct UDPDriver<'a> {
122 /// UDP sender
123 sender: &'a dyn UDPSender<'a>,
124
125 /// Grant of apps that use this radio driver.
126 apps: Grant<
127 App,
128 UpcallCount<{ upcall::COUNT }>,
129 AllowRoCount<{ ro_allow::COUNT }>,
130 AllowRwCount<{ rw_allow::COUNT }>,
131 >,
132 /// ID of app whose transmission request is being processed.
133 current_app: Cell<Option<ProcessId>>,
134
135 /// List of IP Addresses of the interfaces on the device
136 interface_list: &'static [IPAddr],
137
138 /// Maximum length payload that an app can transmit via this driver
139 max_tx_pyld_len: usize,
140
141 /// UDP bound port table (manages kernel bindings)
142 port_table: &'static UdpPortManager,
143
144 kernel_buffer: MapCell<SubSliceMut<'static, u8>>,
145
146 driver_send_cap: &'static dyn UdpDriverCapability,
147
148 net_cap: &'static NetworkCapability,
149}
150
151impl<'a> UDPDriver<'a> {
152 pub fn new(
153 sender: &'a dyn UDPSender<'a>,
154 grant: Grant<
155 App,
156 UpcallCount<{ upcall::COUNT }>,
157 AllowRoCount<{ ro_allow::COUNT }>,
158 AllowRwCount<{ rw_allow::COUNT }>,
159 >,
160 interface_list: &'static [IPAddr],
161 max_tx_pyld_len: usize,
162 port_table: &'static UdpPortManager,
163 kernel_buffer: SubSliceMut<'static, u8>,
164 driver_send_cap: &'static dyn UdpDriverCapability,
165 net_cap: &'static NetworkCapability,
166 ) -> UDPDriver<'a> {
167 UDPDriver {
168 sender,
169 apps: grant,
170 current_app: Cell::new(None),
171 interface_list,
172 max_tx_pyld_len,
173 port_table,
174 kernel_buffer: MapCell::new(kernel_buffer),
175 driver_send_cap,
176 net_cap,
177 }
178 }
179
180 /// If the driver is currently idle and there are pending transmissions,
181 /// pick an app with a pending transmission and return its `ProcessId`.
182 fn get_next_tx_if_idle(&self) -> Option<ProcessId> {
183 if self.current_app.get().is_some() {
184 // Tx already in progress
185 return None;
186 }
187 let mut pending_app = None;
188 for app in self.apps.iter() {
189 let processid = app.processid();
190 app.enter(|app, _| {
191 if app.pending_tx.is_some() {
192 pending_app = Some(processid);
193 }
194 });
195 if pending_app.is_some() {
196 break;
197 }
198 }
199 pending_app
200 }
201
202 /// Performs `processid`'s pending transmission asynchronously. If the
203 /// transmission is not successful, the error is returned to the app via its
204 /// `tx_callback`. Assumes that the driver is currently idle and the app has
205 /// a pending transmission.
206 #[inline]
207 fn perform_tx_async(&self, processid: ProcessId) {
208 let result = self.perform_tx_sync(processid);
209 if result != Ok(()) {
210 let _ = self.apps.enter(processid, |_app, upcalls| {
211 let _ = upcalls.schedule_upcall(
212 upcall::PACKET_TRANSMITTED,
213 (kernel::errorcode::into_statuscode(result), 0, 0),
214 );
215 });
216 }
217 }
218
219 /// Performs `processid`'s pending transmission synchronously. The result is
220 /// returned immediately to the app. Assumes that the driver is currently
221 /// idle and the app has a pending transmission.
222 #[inline]
223 fn perform_tx_sync(&self, processid: ProcessId) -> Result<(), ErrorCode> {
224 self.apps.enter(processid, |app, kernel_data| {
225 let addr_ports = match app.pending_tx.take() {
226 Some(pending_tx) => pending_tx,
227 None => {
228 return Ok(());
229 }
230 };
231 let dst_addr = addr_ports[1].addr;
232 let dst_port = addr_ports[1].port;
233 let src_port = addr_ports[0].port;
234
235 // Send UDP payload. Copy payload into packet buffer held by this driver, then queue
236 // it on the udp_mux.
237 let result = kernel_data
238 .get_readonly_processbuffer(ro_allow::WRITE)
239 .and_then(|write| {
240 write.enter(|payload| {
241 self.kernel_buffer.take().map_or(
242 Err(ErrorCode::NOMEM),
243 |mut kernel_buffer| {
244 if payload.len() > kernel_buffer.len() {
245 self.kernel_buffer.replace(kernel_buffer);
246 return Err(ErrorCode::SIZE);
247 }
248 payload.copy_to_slice(&mut kernel_buffer[0..payload.len()]);
249 kernel_buffer.slice(0..payload.len());
250 match self.sender.driver_send_to(
251 dst_addr,
252 dst_port,
253 src_port,
254 kernel_buffer,
255 self.driver_send_cap,
256 self.net_cap,
257 ) {
258 Ok(()) => Ok(()),
259 Err(mut buf) => {
260 buf.reset();
261 self.kernel_buffer.replace(buf);
262 Err(ErrorCode::FAIL)
263 }
264 }
265 },
266 )
267 })
268 })
269 .unwrap_or(Err(ErrorCode::NOMEM));
270 if result == Ok(()) {
271 self.current_app.set(Some(processid));
272 }
273 result
274 })?
275 }
276
277 /// Schedule the next transmission if there is one pending. Performs the
278 /// transmission eventually, returning any errors via asynchronous callbacks.
279 #[inline]
280 #[allow(dead_code)]
281 fn do_next_tx_queued(&self) {
282 self.get_next_tx_if_idle()
283 .map(|processid| self.perform_tx_async(processid));
284 }
285
286 /// Schedule the next transmission if there is one pending. If the next
287 /// transmission happens to be the one that was just queued, then the
288 /// transmission is immediate. Hence, errors must be returned immediately.
289 /// On the other hand, if it is some other app, then return any errors via
290 /// callbacks.
291 #[inline]
292 fn do_next_tx_immediate(&self, new_processid: ProcessId) -> Result<u32, ErrorCode> {
293 self.get_next_tx_if_idle().map_or(Ok(0), |processid| {
294 if processid == new_processid {
295 let sync_result = self.perform_tx_sync(processid);
296 if sync_result == Ok(()) {
297 Ok(1) //Indicates packet passed to radio
298 } else {
299 Err(ErrorCode::try_from(sync_result).unwrap())
300 }
301 } else {
302 self.perform_tx_async(processid);
303 Ok(0) //indicates async transmission
304 }
305 })
306 }
307
308 #[inline]
309 fn parse_ip_port_pair(&self, buf: &[u8]) -> Option<UDPEndpoint> {
310 if buf.len() != size_of::<UDPEndpoint>() {
311 debug!(
312 "[parse] len is {:?}, not {:?} as expected",
313 buf.len(),
314 size_of::<UDPEndpoint>()
315 );
316 None
317 } else {
318 let (a, p) = buf.split_at(size_of::<IPAddr>());
319 let mut addr = IPAddr::new();
320 addr.0.copy_from_slice(a);
321
322 let pair = UDPEndpoint {
323 addr,
324 port: host_slice_to_u16(p),
325 };
326 Some(pair)
327 }
328 }
329}
330
331impl SyscallDriver for UDPDriver<'_> {
332 /// UDP control
333 ///
334 /// ### `command_num`
335 ///
336 /// - `0`: Driver existence check.
337 /// - `1`: Get the interface list app_cfg (out): 16 * `n` bytes: the list of
338 /// interface IPv6 addresses, length limited by `app_cfg` length. Returns
339 /// INVAL if the cfg buffer is the wrong size, or not available.
340 /// - `2`: Transmit payload.
341 /// - Returns BUSY is this process already has a pending tx.
342 /// - Returns INVAL if no valid buffer has been loaded into the write
343 /// buffer, or if the config buffer is the wrong length, or if the
344 /// destination and source port/address pairs cannot be parsed.
345 /// - Otherwise, returns the result of do_next_tx_immediate(). Notably, a
346 /// successful transmit can produce two different success values. If
347 /// success is returned, this simply means that the packet was queued.
348 /// In this case, the app still still needs to wait for a callback to
349 /// check if any errors occurred before the packet was passed to the
350 /// radio. However, if Success_U32 is returned with value 1, this means
351 /// the the packet was successfully passed the radio without any errors,
352 /// which tells the userland application that it does not need to wait
353 /// for a callback to check if any errors occurred while the packet was
354 /// being passed down to the radio. Any successful return value
355 /// indicates that the app should wait for a send_done() callback before
356 /// attempting to queue another packet. Currently, only will transmit if
357 /// the app has bound to the port passed in the tx_cfg buf as the source
358 /// address.
359 /// - If no port is bound, returns RESERVE,
360 /// - if it tries to send on a port other than the port which is bound,
361 /// returns INVALID. Notably, the currently transmit implementation
362 /// allows for starvation: an an app with a lower app id can send
363 /// constantly and starve an app with a later ID.
364 /// - `3`: Bind to the address in rx_cfg. Returns Ok(()) if that addr/port
365 /// combo is free, returns INVAL if the address requested is not a local
366 /// interface, or if the port requested is 0. Returns BUSY if that port is
367 /// already bound to by another app. This command should be called after
368 /// allow() is called on the rx_cfg buffer, and before subscribe() is used
369 /// to set up the recv callback. Additionally, apps can only send on ports
370 /// after they have bound to said port. If this command is called and the
371 /// address in rx_cfg is 0::0 : 0, this command will reset the option
372 /// containing the bound port to None. Notably, the current implementation
373 /// of this only allows for each app to bind to a single port at a time,
374 /// as such an implementation conserves memory (and is similar to the
375 /// approach applied by TinyOS and Riot).
376 /// - `4`: Returns the maximum payload that can be transmitted by apps using
377 /// this driver. This represents the size of the payload buffer in the
378 /// kernel. Apps can use this syscall to ensure they do not attempt to
379 /// send too-large messages.
380 fn command(
381 &self,
382 command_num: usize,
383 arg1: usize,
384 _: usize,
385 processid: ProcessId,
386 ) -> CommandReturn {
387 match command_num {
388 0 => CommandReturn::success(),
389
390 // Writes the requested number of network interface addresses
391 // `arg1`: number of interfaces requested that will fit into the buffer
392 1 => {
393 self.apps
394 .enter(processid, |_, kernel_data| {
395 kernel_data
396 .get_readwrite_processbuffer(rw_allow::CFG)
397 .and_then(|cfg| {
398 cfg.mut_enter(|cfg| {
399 if cfg.len() != arg1 * size_of::<IPAddr>() {
400 return CommandReturn::failure(ErrorCode::INVAL);
401 }
402 let n_ifaces_to_copy =
403 cmp::min(arg1, self.interface_list.len());
404 let iface_size = size_of::<IPAddr>();
405 for i in 0..n_ifaces_to_copy {
406 cfg[i * iface_size..(i + 1) * iface_size]
407 .copy_from_slice(&self.interface_list[i].0);
408 }
409 // Returns total number of interfaces
410 CommandReturn::success_u32(self.interface_list.len() as u32)
411 })
412 })
413 .unwrap_or(CommandReturn::failure(ErrorCode::INVAL))
414 })
415 .unwrap_or_else(|err| CommandReturn::failure(err.into()))
416 }
417
418 // Transmits UDP packet stored in tx_buf
419 2 => {
420 let res = self
421 .apps
422 .enter(processid, |app, kernel_data| {
423 if app.pending_tx.is_some() {
424 // Cannot support more than one pending tx per process.
425 return Err(ErrorCode::BUSY);
426 }
427 if app.bound_port.is_none() {
428 // Currently, apps need to bind to a port before they can send from said port
429 return Err(ErrorCode::RESERVE);
430 }
431 let next_tx = kernel_data
432 .get_readwrite_processbuffer(rw_allow::CFG)
433 .and_then(|cfg| {
434 cfg.enter(|cfg| {
435 if cfg.len() != 2 * size_of::<UDPEndpoint>() {
436 return None;
437 }
438
439 let mut tmp_cfg_buffer: [u8; size_of::<UDPEndpoint>() * 2] =
440 [0; size_of::<UDPEndpoint>() * 2];
441 cfg.copy_to_slice(&mut tmp_cfg_buffer);
442
443 if let (Some(dst), Some(src)) = (
444 self.parse_ip_port_pair(
445 &tmp_cfg_buffer[size_of::<UDPEndpoint>()..],
446 ),
447 self.parse_ip_port_pair(
448 &tmp_cfg_buffer[..size_of::<UDPEndpoint>()],
449 ),
450 ) {
451 if Some(src) == app.bound_port {
452 Some([src, dst])
453 } else {
454 None
455 }
456 } else {
457 None
458 }
459 })
460 })
461 .unwrap_or(None);
462 if next_tx.is_none() {
463 return Err(ErrorCode::INVAL);
464 }
465 app.pending_tx = next_tx;
466 Ok(())
467 })
468 .unwrap_or_else(|err| Err(err.into()));
469 match res {
470 Ok(()) => self
471 .do_next_tx_immediate(processid)
472 .map_or_else(CommandReturn::failure, CommandReturn::success_u32),
473 Err(e) => CommandReturn::failure(e),
474 }
475 }
476 3 => {
477 let err = self
478 .apps
479 .enter(processid, |app, kernel_data| {
480 // Move UDPEndpoint into udp.rs?
481 let requested_addr_opt = kernel_data
482 .get_readwrite_processbuffer(rw_allow::RX_CFG)
483 .and_then(|rx_cfg| {
484 rx_cfg.enter(|cfg| {
485 if cfg.len() != 2 * mem::size_of::<UDPEndpoint>() {
486 None
487 } else {
488 let mut tmp_endpoint: [u8; mem::size_of::<UDPEndpoint>()] =
489 [0; mem::size_of::<UDPEndpoint>()];
490 cfg[mem::size_of::<UDPEndpoint>()..]
491 .copy_to_slice(&mut tmp_endpoint);
492
493 self.parse_ip_port_pair(&tmp_endpoint)
494 }
495 })
496 })
497 .unwrap_or(None);
498 requested_addr_opt.map_or(Err(Err(ErrorCode::INVAL)), |requested_addr| {
499 // If zero address, close any already bound socket
500 if requested_addr.is_zero() {
501 app.bound_port = None;
502 return Ok(None);
503 }
504 // Check that requested addr is a local interface
505 let mut requested_is_local = false;
506 for i in 0..self.interface_list.len() {
507 if requested_addr.addr == self.interface_list[i] {
508 requested_is_local = true;
509 }
510 }
511 if !requested_is_local {
512 return Err(Err(ErrorCode::INVAL));
513 }
514 Ok(Some(requested_addr))
515 })
516 })
517 .unwrap_or_else(|err| Err(err.into()));
518 match err {
519 Ok(requested_addr_opt) => {
520 requested_addr_opt.map_or(CommandReturn::success(), |requested_addr| {
521 // Check bound ports in the kernel.
522 match self.port_table.is_bound(requested_addr.port) {
523 Ok(bound) => {
524 if bound {
525 CommandReturn::failure(ErrorCode::BUSY)
526 } else {
527 self.apps
528 .enter(processid, |app, _| {
529 // The requested addr is free and valid
530 app.bound_port = Some(requested_addr);
531 CommandReturn::success()
532 })
533 .unwrap_or_else(|err| {
534 CommandReturn::failure(err.into())
535 })
536 }
537 }
538 Err(()) => CommandReturn::failure(ErrorCode::FAIL), //error in port table
539 }
540 })
541 }
542 Err(retcode) => CommandReturn::failure(retcode.try_into().unwrap()),
543 }
544 }
545 4 => CommandReturn::success_u32(self.max_tx_pyld_len as u32),
546 _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
547 }
548 }
549
550 fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
551 self.apps.enter(processid, |_, _| {})
552 }
553}
554
555impl UDPSendClient for UDPDriver<'_> {
556 fn send_done(&self, result: Result<(), ErrorCode>, mut dgram: SubSliceMut<'static, u8>) {
557 // Replace the returned kernel buffer. Now we can send the next msg.
558 dgram.reset();
559 self.kernel_buffer.replace(dgram);
560 self.current_app.get().map(|processid| {
561 let _ = self.apps.enter(processid, |_app, upcalls| {
562 let _ = upcalls.schedule_upcall(
563 upcall::PACKET_TRANSMITTED,
564 (kernel::errorcode::into_statuscode(result), 0, 0),
565 );
566 });
567 });
568 self.current_app.set(None);
569 self.do_next_tx_queued();
570 }
571}
572
573impl UDPRecvClient for UDPDriver<'_> {
574 fn receive(
575 &self,
576 src_addr: IPAddr,
577 dst_addr: IPAddr,
578 src_port: u16,
579 dst_port: u16,
580 payload: &[u8],
581 ) {
582 self.apps.each(|_, app, kernel_data| {
583 if app.bound_port.is_some() {
584 let mut for_me = false;
585 app.bound_port.as_ref().map(|requested_addr| {
586 if requested_addr.addr == dst_addr && requested_addr.port == dst_port {
587 for_me = true;
588 }
589 });
590 if for_me {
591 let len = payload.len();
592 let res = kernel_data
593 .get_readwrite_processbuffer(rw_allow::READ)
594 .and_then(|read| {
595 read.mut_enter(|rbuf| {
596 if rbuf.len() >= len {
597 rbuf[..len].copy_from_slice(&payload[..len]);
598 Ok(())
599 } else {
600 Err(ErrorCode::SIZE) //packet does not fit
601 }
602 })
603 })
604 .unwrap_or(Ok(()));
605 if res.is_ok() {
606 // Write address of sender into rx_cfg so it can be read by client
607 let sender_addr = UDPEndpoint {
608 addr: src_addr,
609 port: src_port,
610 };
611 let _ = kernel_data.schedule_upcall(upcall::PACKET_RECEIVED, (len, 0, 0));
612 const CFG_LEN: usize = 2 * size_of::<UDPEndpoint>();
613 let _ = kernel_data
614 .get_readwrite_processbuffer(rw_allow::RX_CFG)
615 .and_then(|rx_cfg| {
616 rx_cfg.mut_enter(|cfg| {
617 if cfg.len() != CFG_LEN {
618 return Err(ErrorCode::INVAL);
619 }
620 let mut tmp_cfg_buffer: [u8; CFG_LEN] = [0; CFG_LEN];
621 sender_addr.encode(&mut tmp_cfg_buffer, 0);
622 cfg.copy_from_slice(&tmp_cfg_buffer);
623 Ok(())
624 })
625 })
626 .unwrap_or(Err(ErrorCode::INVAL));
627 }
628 }
629 }
630 });
631 }
632}
633
634impl PortQuery for UDPDriver<'_> {
635 // Returns true if |port| is bound (on any iface), false otherwise.
636 fn is_bound(&self, port: u16) -> bool {
637 let mut port_bound = false;
638 for app in self.apps.iter() {
639 app.enter(|other_app, _| {
640 if other_app.bound_port.is_some() {
641 let other_addr_opt = other_app.bound_port;
642 let other_addr = other_addr_opt.unwrap(); // Unwrap fail = Missing other_addr
643 if other_addr.port == port {
644 port_bound = true;
645 }
646 }
647 });
648 }
649 port_bound
650 }
651}