L4Re Operating System Framework
Interface and Usage Documentation
Loading...
Searching...
No Matches
virtio-net
1// vi:ft=cpp
2/* SPDX-License-Identifier: MIT */
3/*
4 * Copyright (C) 2022, 2024-2025 Kernkonzept GmbH.
5 * Author(s): Stephan Gerhold <stephan.gerhold@kernkonzept.com>
6 */
7#pragma once
8
9#include <cstring>
10#include <functional>
11
12#include <l4/cxx/exceptions>
13#include <l4/cxx/minmax>
14#include <l4/re/dataspace>
15#include <l4/re/env>
16#include <l4/re/error_helper>
17#include <l4/re/util/unique_cap>
18#include <l4/sys/consts.h>
19
20#include <l4/l4virtio/client/l4virtio>
21#include <l4/l4virtio/l4virtio>
22#include <l4/l4virtio/virtio_net.h>
23#include <l4/l4virtio/virtqueue>
24
25namespace L4virtio { namespace Driver {
26
31{
32public:
37 struct Packet
38 {
40 l4_uint8_t data[1500 + 14]; /* MTU + Ethernet header */
41 };
42
47 int rx_queue_size() const
48 { return max_queue_size(0); }
49
54 int tx_queue_size() const
55 { return max_queue_size(1); }
56
75 L4Re::Util::Dbg msg_dev = L4Re::Util::Dbg{2})
76
77 {
78 // Contact device.
79 driver_connect(srvcap, false);
80
81 if (_config->device != L4VIRTIO_ID_NET)
82 L4Re::chksys(-L4_ENODEV, "Device is not a network device.");
83
84 if (_config->num_queues < 2)
85 L4Re::chksys(-L4_EINVAL, "Invalid number of queues reported.");
86
87 auto rxqsz = rx_queue_size();
88 auto txqsz = tx_queue_size();
89
90 // Allocate memory for RX/TX queue and RX/TX packet buffers
91 auto rxqoff = 0;
92 auto txqoff = l4_round_size(rxqoff + rxqsz * _rxq.total_size(rxqsz),
93 L4virtio::Virtqueue::Desc_align);
94 auto rxpktoff = l4_round_size(txqoff + txqsz * _txq.total_size(txqsz),
95 L4virtio::Virtqueue::Desc_align);
96 auto txpktoff = rxpktoff + rxqsz * sizeof(Packet);
97 auto totalsz = txpktoff + txqsz * sizeof(Packet);
98
99 auto *e = L4Re::Env::env();
100
101 if (queue_ds)
102 _queue_ds = L4Re::Util::Unique_cap<L4Re::Dataspace>(queue_ds);
103 else
104 {
106 "Allocate queue dataspace capability");
107 L4Re::chksys(e->mem_alloc()->alloc(totalsz, _queue_ds.get(),
110 "Allocate memory for virtio structures");
111 }
112
113 L4Re::chksys(e->rm()->attach(&_queue_region, totalsz,
115 L4::Ipc::make_cap_rw(_queue_ds.get()), 0,
117 "Attach dataspace for virtio structures");
118
119 l4_uint64_t devaddr;
120 L4Re::chksys(register_ds(_queue_ds.get(), 0, totalsz, &devaddr),
121 "Register queue dataspace with device");
122
123 _rxq.init_queue(rxqsz, _queue_region.get() + rxqoff, msg_dev);
124 _txq.init_queue(txqsz, _queue_region.get() + txqoff, msg_dev);
125
126 config_queue(0, rxqsz, devaddr + rxqoff,
127 devaddr + rxqoff + _rxq.avail_offset(),
128 devaddr + rxqoff + _rxq.used_offset());
129 config_queue(1, txqsz, devaddr + txqoff,
130 devaddr + txqoff + _txq.avail_offset(),
131 devaddr + txqoff + _txq.used_offset());
132
133 _rxpkts = reinterpret_cast<Packet*>(_queue_region.get() + rxpktoff);
134 _txpkts = reinterpret_cast<Packet*>(_queue_region.get() + txpktoff);
135
136 // Prepare descriptors to save work later
137 for (l4_uint16_t descno = 0; descno < rxqsz; ++descno)
138 {
139 auto &desc = _rxq.desc(descno);
140 desc.addr = L4virtio::Ptr<void>(devaddr + rxpktoff +
141 descno * sizeof(Packet));
142 desc.len = sizeof(Packet);
143 desc.flags.write() = 1;
144 }
145 for (l4_uint16_t descno = 0; descno < txqsz; ++descno)
146 {
147 auto &desc = _txq.desc(descno);
148 desc.addr = L4virtio::Ptr<void>(devaddr + txpktoff +
149 descno * sizeof(Packet));
150 desc.len = sizeof(Packet);
151 }
152
153 // Setup notification IRQ
154 _driver_notification_irq =
156 "Allocate notification capability");
157
158 L4Re::chksys(l4_error(e->factory()->create(_driver_notification_irq.get())),
159 "Create irq for notifications from device");
160
161 L4Re::chksys(_device->bind(0, _driver_notification_irq.get()),
162 "Bind driver notification interrupt");
163
164 // Finish handshake with device
165 l4virtio_set_feature(_config->driver_features_map,
167 l4virtio_set_feature(_config->driver_features_map, L4VIRTIO_NET_F_MAC);
169 }
170
175 {
176 return *_config->device_config<l4virtio_net_config_t>();
177 }
178
186 {
187 return l4_error(_driver_notification_irq->bind_thread(thread, label));
188 }
189
194 { return _driver_notification_irq.get(); }
195
203 {
204 if (descno >= _rxq.num())
205 throw L4::Bounds_error("Invalid used descriptor number in RX queue");
206 return _rxpkts[descno];
207 }
208
222 {
223 l4_uint16_t descno = _rxq.find_next_used(len);
224
225 if (len && descno != Virtqueue::Eoq)
226 // Ensure that the length provided by the device in wait_for_next_used()
227 // is not larger than the buffer and subtract the length of the header.
228 *len = cxx::min(*len - sizeof(_rxpkts[0].hdr), sizeof(_rxpkts[0].data));
229 return descno;
230 }
231
248 {
249 l4_uint16_t descno;
250 // Wait until used descriptor becomes available.
251 for (;;)
252 {
253 descno = poll_rx(len);
254 if (descno != Virtqueue::Eoq)
255 break;
256
257 L4Re::chksys(_driver_notification_irq->receive(), "Wait for RX");
258 }
259
260 return descno;
261 }
262
272 {
273 _rxq.free_descriptor(descno, descno);
274 }
275
279 void queue_rx()
280 {
281 l4_uint16_t descno;
282 while ((descno = _rxq.alloc_descriptor()) != Virtqueue::Eoq)
283 _rxq.enqueue_descriptor(descno);
284 notify(_rxq);
285 }
286
301 bool tx(std::function<l4_uint32_t(Packet&)> prepare)
302 {
303 auto descno = _txq.alloc_descriptor();
304 if (descno == Virtqueue::Eoq)
305 {
306 // Try again after cleaning old descriptors that have already been used
307 free_used_tx_descriptors();
308 descno = _txq.alloc_descriptor();
309 if (descno == Virtqueue::Eoq)
310 return false;
311 }
312
313 auto &pkt = _txpkts[descno];
314 auto &desc = _txq.desc(descno);
315 desc.len = sizeof(pkt.hdr) + prepare(pkt);
316 send(_txq, descno);
317 return true;
318 }
319
320private:
321 void free_used_tx_descriptors()
322 {
323 l4_uint16_t used;
324 while ((used = _txq.find_next_used()) != Virtqueue::Eoq)
325 {
326 if (used >= _txq.num())
327 throw L4::Bounds_error("Invalid used descriptor number in TX queue");
328 _txq.free_descriptor(used, used);
329 }
330 }
331
332private:
335 L4Re::Util::Unique_cap<L4::Irq> _driver_notification_irq;
337 Packet *_rxpkts, *_txpkts;
338};
339
340} }
static Env const * env() noexcept
Returns the initial environment for the current task.
Definition env:96
@ Continuous
Allocate physically contiguous memory.
Definition mem_alloc:64
@ Pinned
Deprecated, use L4Re::Dma_space instead.
Definition mem_alloc:65
Unique region.
Definition rm:432
Access out of bounds.
Definition exceptions:279
@ Invalid
Invalid capability selector.
Definition capability.h:42
C++ interface for capabilities.
Definition capability.h:249
Client-side implementation for a general virtio device.
Definition l4virtio:32
int max_queue_size(int num) const
Maximum queue size allowed by the device.
Definition l4virtio:230
void driver_connect(L4::Cap< L4virtio::Device > srvcap, bool manage_notify=true)
Contacts the device and starts the initial handshake.
Definition l4virtio:56
void send(Virtqueue &queue, l4_uint16_t descno)
Send a request to the device.
Definition l4virtio:312
int register_ds(L4::Cap< L4Re::Dataspace > ds, l4_umword_t offset, l4_umword_t size, l4_uint64_t *devaddr)
Share a dataspace with the device.
Definition l4virtio:196
int config_queue(int num, unsigned size, l4_uint64_t desc_addr, l4_uint64_t avail_addr, l4_uint64_t used_addr)
Send the virtqueue configuration to the device.
Definition l4virtio:212
int driver_acknowledge()
Finalize handshake with the device.
Definition l4virtio:156
Simple class for accessing a virtio net device.
Definition virtio-net:31
L4::Cap< L4::Irq > get_rx_notification_irq() const
Get notification IRQ.
Definition virtio-net:193
void setup_device(L4::Cap< L4virtio::Device > srvcap, L4::Cap< L4Re::Dataspace > queue_ds=L4::Cap< L4Re::Dataspace >::Invalid, L4Re::Util::Dbg msg_dev=L4Re::Util::Dbg{2})
Establish a connection to the device and set up shared memory.
Definition virtio-net:72
int rx_queue_size() const
Return the maximum receive queue size allowed by the device.
Definition virtio-net:47
void finish_rx(l4_uint16_t descno)
Free an RX descriptor number to make it available for the RX queue again.
Definition virtio-net:271
l4_uint16_t poll_rx(l4_uint32_t *len=nullptr)
Poll if a network packet has been received from the device and return the descriptor number,...
Definition virtio-net:221
Packet & rx_pkt(l4_uint16_t descno)
Return a reference to the RX packet buffer of the specified descriptor, e.g.
Definition virtio-net:202
l4virtio_net_config_t const & device_config() const
Return a reference to the device configuration.
Definition virtio-net:174
int bind_rx_notification_irq(L4::Cap< L4::Thread > thread, l4_umword_t label)
Bind the rx notification IRQ to the specified thread.
Definition virtio-net:185
l4_uint16_t wait_rx(l4_uint32_t *len=nullptr)
Block until a network packet has been received from the device and return the descriptor number.
Definition virtio-net:247
int tx_queue_size() const
Return the maximum transmit queue size allowed by the device.
Definition virtio-net:54
bool tx(std::function< l4_uint32_t(Packet &)> prepare)
Attempt to allocate a descriptor in the TX queue and transmit the packet, after calling the prepare c...
Definition virtio-net:301
void queue_rx()
Queue new available descriptors in the RX queue.
Definition virtio-net:279
Driver-side implementation of a Virtqueue.
Definition virtqueue:490
void free_descriptor(l4_uint16_t head, l4_uint16_t tail)
Free a chained list of descriptors in the descriptor queue.
Definition virtqueue:665
l4_uint16_t find_next_used(l4_uint32_t *len=nullptr)
Return the next finished block.
Definition virtqueue:637
Desc & desc(l4_uint16_t descno)
Return a reference to a descriptor in the descriptor table.
Definition virtqueue:618
void init_queue(unsigned num, void *desc, void *avail, void *used, L4Re::Util::Dbg msg_dev=L4Re::Util::Dbg{2})
Initialize this virtqueue.
Definition virtqueue:543
Pointer used in virtio descriptors.
Definition virtqueue:54
Ptr< void > addr
Address stored in descriptor.
Definition virtqueue:114
unsigned long avail_offset() const
Get the offset of the available ring from the descriptor table.
Definition virtqueue:331
static unsigned long total_size(unsigned num)
Calculate the total size for a virtqueue of the given dimensions.
Definition virtqueue:253
unsigned long used_offset() const
Get the offset of the used ring from the descriptor table.
Definition virtqueue:337
unsigned num() const
Definition virtqueue:421
T get() const noexcept
Return the address.
Definition rm:505
Dataspace interface.
Environment interface.
Error helper.
Base exceptions.
unsigned long l4_umword_t
Unsigned machine word.
Definition l4int.h:40
unsigned char l4_uint8_t
Unsigned 8bit value.
Definition l4int.h:25
unsigned int l4_uint32_t
Unsigned 32bit value.
Definition l4int.h:29
unsigned short int l4_uint16_t
Unsigned 16bit value.
Definition l4int.h:27
unsigned long long l4_uint64_t
Unsigned 64bit value.
Definition l4int.h:31
@ L4_EINVAL
Invalid argument.
Definition err.h:47
@ L4_ENODEV
No such thing.
Definition err.h:45
l4_ret_t l4_error(l4_msgtag_t tag) L4_NOTHROW
Get IPC error code if any or message tag label otherwise for an IPC call.
Definition ipc.h:687
#define L4_PAGESHIFT
Size of a page, log2-based.
Definition consts.h:26
l4_addr_t l4_round_size(l4_addr_t value, unsigned char bits) L4_NOTHROW
Round value up to the next alignment with bits size.
Definition consts.h:495
void l4virtio_set_feature(l4_uint32_t *feature_map, unsigned feat)
Set the given feature bit in a feature map.
Definition virtio.h:275
@ L4VIRTIO_FEATURE_VERSION_1
Virtio protocol version 1 supported. Must be 1 for L4virtio.
Definition virtio.h:104
@ L4VIRTIO_ID_NET
Virtual ethernet card.
Definition virtio.h:64
Common constants.
Unique_cap< T > make_unique_cap()
Allocate a capability slot and wrap it in an Unique_cap.
Definition unique_cap:56
L4::Detail::Unique_cap_impl< T, L4Re::Util::Smart_cap_auto< L4_FP_ALL_SPACES > > Unique_cap
Unique capability that implements automatic free and unmap of the capability selector.
Definition unique_cap:43
T chkcap(T &&cap, char const *extra="", l4_ret_t err=-L4_ENOMEM)
Check for valid capability or raise C++ exception.
Definition error_helper:149
l4_ret_t chksys(l4_ret_t err, char const *extra="", l4_ret_t ret=0)
Generate C++ exception on error.
Definition error_helper:72
Cap< T > make_cap_rw(L4::Cap< T > cap) noexcept
Make an L4::Ipc::Cap<T> for the given capability with L4_CAP_FPAGE_RW rights.
Definition ipc_types:855
L4-VIRTIO Transport C++ API.
Definition l4virtio:26
@ RW
Readable and writable region.
Definition rm:141
@ Search_addr
Search for a suitable address range.
Definition rm:115
Structure for a network packet (header including data) with maximum size, assuming that no extra feat...
Definition virtio-net:38
l4_uint32_t device
device ID
Definition virtio.h:140
l4_uint32_t num_queues
number of virtqueues
Definition virtio.h:153
Device configuration for network devices.
Definition virtio_net.h:35
Header structure of a request for a network device.
Definition virtio_net.h:21
Unique_cap / Unique_del_cap.