xref: /freebsd/sys/dev/netmap/if_vtnet_netmap.h (revision a3557ef0)
1 /*
2  * Copyright (C) 2014-2018 Vincenzo Maffione, Luigi Rizzo.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25 
26 /*
27  * $FreeBSD$
28  */
29 
30 #include <net/netmap.h>
31 #include <sys/selinfo.h>
32 #include <vm/vm.h>
33 #include <vm/pmap.h>    /* vtophys ? */
34 #include <dev/netmap/netmap_kern.h>
35 
36 /*
37  * Return 1 if the queue identified by 't' and 'idx' is in netmap mode.
38  */
39 static int
40 vtnet_netmap_queue_on(struct vtnet_softc *sc, enum txrx t, int idx)
41 {
42 	struct netmap_adapter *na = NA(sc->vtnet_ifp);
43 
44 	if (!nm_native_on(na))
45 		return 0;
46 
47 	if (t == NR_RX)
48 		return !!(idx < na->num_rx_rings &&
49 			na->rx_rings[idx]->nr_mode == NKR_NETMAP_ON);
50 
51 	return !!(idx < na->num_tx_rings &&
52 		na->tx_rings[idx]->nr_mode == NKR_NETMAP_ON);
53 }
54 
55 /* Register and unregister. */
56 static int
57 vtnet_netmap_reg(struct netmap_adapter *na, int state)
58 {
59 	struct ifnet *ifp = na->ifp;
60 	struct vtnet_softc *sc = ifp->if_softc;
61 	int success;
62 	int i;
63 
64 	/* Drain the taskqueues to make sure that there are no worker threads
65 	 * accessing the virtqueues. */
66 	vtnet_drain_taskqueues(sc);
67 
68 	VTNET_CORE_LOCK(sc);
69 
70 	/* We need nm_netmap_on() to return true when called by
71 	 * vtnet_init_locked() below. */
72 	if (state)
73 		nm_set_native_flags(na);
74 
75 	/* We need to trigger a device reset in order to unexpose guest buffers
76 	 * published to the host. */
77 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
78 	/* Get pending used buffers. The way they are freed depends on whether
79 	 * they are netmap buffer or they are mbufs. We can tell apart the two
80 	 * cases by looking at kring->nr_mode, before this is possibly updated
81 	 * in the loop below. */
82 	for (i = 0; i < sc->vtnet_act_vq_pairs; i++) {
83 		struct vtnet_txq *txq = &sc->vtnet_txqs[i];
84 		struct vtnet_rxq *rxq = &sc->vtnet_rxqs[i];
85 
86 		VTNET_TXQ_LOCK(txq);
87 		vtnet_txq_free_mbufs(txq);
88 		VTNET_TXQ_UNLOCK(txq);
89 
90 		VTNET_RXQ_LOCK(rxq);
91 		vtnet_rxq_free_mbufs(rxq);
92 		VTNET_RXQ_UNLOCK(rxq);
93 	}
94 	vtnet_init_locked(sc);
95 	success = (ifp->if_drv_flags & IFF_DRV_RUNNING) ? 0 : ENXIO;
96 
97 	if (state) {
98 		netmap_krings_mode_commit(na, state);
99 	} else {
100 		nm_clear_native_flags(na);
101 		netmap_krings_mode_commit(na, state);
102 	}
103 
104 	VTNET_CORE_UNLOCK(sc);
105 
106 	return success;
107 }
108 
109 
110 /* Reconcile kernel and user view of the transmit ring. */
111 static int
112 vtnet_netmap_txsync(struct netmap_kring *kring, int flags)
113 {
114 	struct netmap_adapter *na = kring->na;
115 	struct ifnet *ifp = na->ifp;
116 	struct netmap_ring *ring = kring->ring;
117 	u_int ring_nr = kring->ring_id;
118 	u_int nm_i;	/* index into the netmap ring */
119 	u_int const lim = kring->nkr_num_slots - 1;
120 	u_int const head = kring->rhead;
121 
122 	/* device-specific */
123 	struct vtnet_softc *sc = ifp->if_softc;
124 	struct vtnet_txq *txq = &sc->vtnet_txqs[ring_nr];
125 	struct virtqueue *vq = txq->vtntx_vq;
126 	int interrupts = !(kring->nr_kflags & NKR_NOINTR);
127 	u_int n;
128 
129 	/*
130 	 * First part: process new packets to send.
131 	 */
132 
133 	nm_i = kring->nr_hwcur;
134 	if (nm_i != head) {	/* we have new packets to send */
135 		struct sglist *sg = txq->vtntx_sg;
136 
137 		for (; nm_i != head; nm_i = nm_next(nm_i, lim)) {
138 			/* we use an empty header here */
139 			struct netmap_slot *slot = &ring->slot[nm_i];
140 			u_int len = slot->len;
141 			uint64_t paddr;
142 			void *addr = PNMB(na, slot, &paddr);
143 			int err;
144 
145 			NM_CHECK_ADDR_LEN(na, addr, len);
146 
147 			slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
148 			/* Initialize the scatterlist, expose it to the hypervisor,
149 			 * and kick the hypervisor (if necessary).
150 			 */
151 			sglist_reset(sg); // cheap
152 			err = sglist_append(sg, &txq->vtntx_shrhdr, sc->vtnet_hdr_size);
153 			err |= sglist_append_phys(sg, paddr, len);
154 			KASSERT(err == 0, ("%s: cannot append to sglist %d",
155 						__func__, err));
156 			err = virtqueue_enqueue(vq, /*cookie=*/txq, sg,
157 						/*readable=*/sg->sg_nseg,
158 						/*writeable=*/0);
159 			if (unlikely(err)) {
160 				if (err != ENOSPC)
161 					nm_prerr("virtqueue_enqueue(%s) failed: %d",
162 							kring->name, err);
163 				break;
164 			}
165 		}
166 
167 		virtqueue_notify(vq);
168 
169 		/* Update hwcur depending on where we stopped. */
170 		kring->nr_hwcur = nm_i; /* note we migth break early */
171 	}
172 
173 	/* Free used slots. We only consider our own used buffers, recognized
174 	 * by the token we passed to virtqueue_enqueue.
175 	 */
176 	n = 0;
177 	for (;;) {
178 		void *token = virtqueue_dequeue(vq, NULL);
179 		if (token == NULL)
180 			break;
181 		if (unlikely(token != (void *)txq))
182 			nm_prerr("BUG: TX token mismatch");
183 		else
184 			n++;
185 	}
186 	if (n > 0) {
187 		kring->nr_hwtail += n;
188 		if (kring->nr_hwtail > lim)
189 			kring->nr_hwtail -= lim + 1;
190 	}
191 
192 	if (interrupts && virtqueue_nfree(vq) < 32)
193 		virtqueue_postpone_intr(vq, VQ_POSTPONE_LONG);
194 
195 	return 0;
196 }
197 
198 /*
199  * Publish 'num 'netmap receive buffers to the host, starting
200  * from the next available one (rx->vtnrx_nm_refill).
201  * Return a positive error code on error, and 0 on success.
202  * If we could not publish all of the buffers that's an error,
203  * since the netmap ring and the virtqueue would go out of sync.
204  */
205 static int
206 vtnet_netmap_kring_refill(struct netmap_kring *kring, u_int num)
207 {
208 	struct netmap_adapter *na = kring->na;
209 	struct ifnet *ifp = na->ifp;
210 	struct netmap_ring *ring = kring->ring;
211 	u_int ring_nr = kring->ring_id;
212 	u_int const lim = kring->nkr_num_slots - 1;
213 	u_int nm_i;
214 
215 	/* device-specific */
216 	struct vtnet_softc *sc = ifp->if_softc;
217 	struct vtnet_rxq *rxq = &sc->vtnet_rxqs[ring_nr];
218 	struct virtqueue *vq = rxq->vtnrx_vq;
219 
220 	/* use a local sglist, default might be short */
221 	struct sglist_seg ss[2];
222 	struct sglist sg = { ss, 0, 0, 2 };
223 
224 	for (nm_i = rxq->vtnrx_nm_refill; num > 0;
225 	    nm_i = nm_next(nm_i, lim), num--) {
226 		struct netmap_slot *slot = &ring->slot[nm_i];
227 		uint64_t paddr;
228 		void *addr = PNMB(na, slot, &paddr);
229 		int err;
230 
231 		if (addr == NETMAP_BUF_BASE(na)) { /* bad buf */
232 			if (netmap_ring_reinit(kring))
233 				return EFAULT;
234 		}
235 
236 		slot->flags &= ~NS_BUF_CHANGED;
237 		sglist_reset(&sg);
238 		err = sglist_append(&sg, &rxq->vtnrx_shrhdr, sc->vtnet_hdr_size);
239 		err |= sglist_append_phys(&sg, paddr, NETMAP_BUF_SIZE(na));
240 		KASSERT(err == 0, ("%s: cannot append to sglist %d",
241 					__func__, err));
242 		/* writable for the host */
243 		err = virtqueue_enqueue(vq, /*cookie=*/rxq, &sg,
244 				/*readable=*/0, /*writeable=*/sg.sg_nseg);
245 		if (unlikely(err)) {
246 			nm_prerr("virtqueue_enqueue(%s) failed: %d",
247 				kring->name, err);
248 			break;
249 		}
250 	}
251 	rxq->vtnrx_nm_refill = nm_i;
252 
253 	return num == 0 ? 0 : ENOSPC;
254 }
255 
256 /*
257  * Publish netmap buffers on a RX virtqueue.
258  * Returns -1 if this virtqueue is not being opened in netmap mode.
259  * If the virtqueue is being opened in netmap mode, return 0 on success and
260  * a positive error code on failure.
261  */
262 static int
263 vtnet_netmap_rxq_populate(struct vtnet_rxq *rxq)
264 {
265 	struct netmap_adapter *na = NA(rxq->vtnrx_sc->vtnet_ifp);
266 	struct netmap_kring *kring;
267 	int error;
268 
269 	if (!nm_native_on(na) || rxq->vtnrx_id >= na->num_rx_rings)
270 		return -1;
271 
272 	kring = na->rx_rings[rxq->vtnrx_id];
273 	if (!(nm_kring_pending_on(kring) ||
274 			kring->nr_pending_mode == NKR_NETMAP_ON))
275 		return -1;
276 
277 	/* Expose all the RX netmap buffers we can. In case of no indirect
278 	 * buffers, the number of netmap slots in the RX ring matches the
279 	 * maximum number of 2-elements sglist that the RX virtqueue can
280 	 * accommodate. We need to start from kring->nr_hwcur, which is 0
281 	 * on netmap register and may be different from 0 if a virtio
282 	 * re-init happens while the device is in use by netmap. */
283 	rxq->vtnrx_nm_refill = kring->nr_hwcur;
284 	error = vtnet_netmap_kring_refill(kring, na->num_rx_desc - 1);
285 	virtqueue_notify(rxq->vtnrx_vq);
286 
287 	return error;
288 }
289 
290 /* Reconcile kernel and user view of the receive ring. */
291 static int
292 vtnet_netmap_rxsync(struct netmap_kring *kring, int flags)
293 {
294 	struct netmap_adapter *na = kring->na;
295 	struct ifnet *ifp = na->ifp;
296 	struct netmap_ring *ring = kring->ring;
297 	u_int ring_nr = kring->ring_id;
298 	u_int nm_i;	/* index into the netmap ring */
299 	u_int const lim = kring->nkr_num_slots - 1;
300 	u_int const head = kring->rhead;
301 	int force_update = (flags & NAF_FORCE_READ) ||
302 				(kring->nr_kflags & NKR_PENDINTR);
303 	int interrupts = !(kring->nr_kflags & NKR_NOINTR);
304 
305 	/* device-specific */
306 	struct vtnet_softc *sc = ifp->if_softc;
307 	struct vtnet_rxq *rxq = &sc->vtnet_rxqs[ring_nr];
308 	struct virtqueue *vq = rxq->vtnrx_vq;
309 
310 	/*
311 	 * First part: import newly received packets.
312 	 * Only accept our own buffers (matching the token). We should only get
313 	 * matching buffers. The hwtail should never overrun hwcur, because
314 	 * we publish only N-1 receive buffers (and non N).
315 	 * In any case we must not leave this routine with the interrupts
316 	 * disabled, pending packets in the VQ and hwtail == (hwcur - 1),
317 	 * otherwise the pending packets could stall.
318 	 */
319 	if (netmap_no_pendintr || force_update) {
320 		uint32_t hwtail_lim = nm_prev(kring->nr_hwcur, lim);
321 		void *token;
322 
323 		vtnet_rxq_disable_intr(rxq);
324 
325 		nm_i = kring->nr_hwtail;
326 		for (;;) {
327 			int len;
328 			token = virtqueue_dequeue(vq, &len);
329 			if (token == NULL) {
330 				/*
331 				 * Enable the interrupts again and double-check
332 				 * for more work. We can go on until we win the
333 				 * race condition, since we are not replenishing
334 				 * in the meanwhile, and thus we will process at
335 				 * most N-1 slots.
336 				 */
337 				if (interrupts && vtnet_rxq_enable_intr(rxq)) {
338 					vtnet_rxq_disable_intr(rxq);
339 					continue;
340 				}
341 				break;
342 			}
343 			if (unlikely(token != (void *)rxq)) {
344 				nm_prerr("BUG: RX token mismatch");
345 			} else {
346 				if (nm_i == hwtail_lim) {
347 					KASSERT(false, ("hwtail would "
348 					    "overrun hwcur"));
349 				}
350 
351 				/* Skip the virtio-net header. */
352 				len -= sc->vtnet_hdr_size;
353 				if (unlikely(len < 0)) {
354 					nm_prlim(1, "Truncated virtio-net-header, "
355 						"missing %d bytes", -len);
356 					len = 0;
357 				}
358 				ring->slot[nm_i].len = len;
359 				ring->slot[nm_i].flags = 0;
360 				nm_i = nm_next(nm_i, lim);
361 			}
362 		}
363 		kring->nr_hwtail = nm_i;
364 		kring->nr_kflags &= ~NKR_PENDINTR;
365 	}
366 
367 	/*
368 	 * Second part: skip past packets that userspace has released.
369 	 */
370 	nm_i = kring->nr_hwcur; /* netmap ring index */
371 	if (nm_i != head) {
372 		int released;
373 		int error;
374 
375 		released = head - nm_i;
376 		if (released < 0)
377 			released += kring->nkr_num_slots;
378 		error = vtnet_netmap_kring_refill(kring, released);
379 		if (error) {
380 			nm_prerr("Failed to replenish RX VQ with %u sgs",
381 			    released);
382 			return error;
383 		}
384 		kring->nr_hwcur = head;
385 		virtqueue_notify(vq);
386 	}
387 
388 	nm_prdis("h %d c %d t %d hwcur %d hwtail %d", kring->rhead,
389 	    kring->rcur, kring->rtail, kring->nr_hwcur, kring->nr_hwtail);
390 
391 	return 0;
392 }
393 
394 
395 /* Enable/disable interrupts on all virtqueues. */
396 static void
397 vtnet_netmap_intr(struct netmap_adapter *na, int state)
398 {
399 	struct vtnet_softc *sc = na->ifp->if_softc;
400 	int i;
401 
402 	for (i = 0; i < sc->vtnet_max_vq_pairs; i++) {
403 		struct vtnet_rxq *rxq = &sc->vtnet_rxqs[i];
404 		struct vtnet_txq *txq = &sc->vtnet_txqs[i];
405 		struct virtqueue *txvq = txq->vtntx_vq;
406 
407 		if (state) {
408 			vtnet_rxq_enable_intr(rxq);
409 			virtqueue_enable_intr(txvq);
410 		} else {
411 			vtnet_rxq_disable_intr(rxq);
412 			virtqueue_disable_intr(txvq);
413 		}
414 	}
415 }
416 
417 static int
418 vtnet_netmap_tx_slots(struct vtnet_softc *sc)
419 {
420 	int div;
421 
422 	/* We need to prepend a virtio-net header to each netmap buffer to be
423 	 * transmitted, therefore calling virtqueue_enqueue() passing sglist
424 	 * with 2 elements.
425 	 * TX virtqueues use indirect descriptors if the feature was negotiated
426 	 * with the host, and if sc->vtnet_tx_nsegs > 1. With indirect
427 	 * descriptors, a single virtio descriptor is sufficient to reference
428 	 * each TX sglist. Without them, we need two separate virtio descriptors
429 	 * for each TX sglist. We therefore compute the number of netmap TX
430 	 * slots according to these assumptions.
431 	 */
432 	if ((sc->vtnet_flags & VTNET_FLAG_INDIRECT) && sc->vtnet_tx_nsegs > 1)
433 		div = 1;
434 	else
435 		div = 2;
436 
437 	return virtqueue_size(sc->vtnet_txqs[0].vtntx_vq) / div;
438 }
439 
440 static int
441 vtnet_netmap_rx_slots(struct vtnet_softc *sc)
442 {
443 	int div;
444 
445 	/* We need to prepend a virtio-net header to each netmap buffer to be
446 	 * received, therefore calling virtqueue_enqueue() passing sglist
447 	 * with 2 elements.
448 	 * RX virtqueues use indirect descriptors if the feature was negotiated
449 	 * with the host, and if sc->vtnet_rx_nsegs > 1. With indirect
450 	 * descriptors, a single virtio descriptor is sufficient to reference
451 	 * each RX sglist. Without them, we need two separate virtio descriptors
452 	 * for each RX sglist. We therefore compute the number of netmap RX
453 	 * slots according to these assumptions.
454 	 */
455 	if ((sc->vtnet_flags & VTNET_FLAG_INDIRECT) && sc->vtnet_rx_nsegs > 1)
456 		div = 1;
457 	else
458 		div = 2;
459 
460 	return virtqueue_size(sc->vtnet_rxqs[0].vtnrx_vq) / div;
461 }
462 
463 static int
464 vtnet_netmap_config(struct netmap_adapter *na, struct nm_config_info *info)
465 {
466 	struct vtnet_softc *sc = na->ifp->if_softc;
467 
468 	info->num_tx_rings = sc->vtnet_act_vq_pairs;
469 	info->num_rx_rings = sc->vtnet_act_vq_pairs;
470 	info->num_tx_descs = vtnet_netmap_tx_slots(sc);
471 	info->num_rx_descs = vtnet_netmap_rx_slots(sc);
472 	info->rx_buf_maxsize = NETMAP_BUF_SIZE(na);
473 
474 	return 0;
475 }
476 
477 static void
478 vtnet_netmap_attach(struct vtnet_softc *sc)
479 {
480 	struct netmap_adapter na;
481 
482 	bzero(&na, sizeof(na));
483 
484 	na.ifp = sc->vtnet_ifp;
485 	na.na_flags = 0;
486 	na.num_tx_desc = vtnet_netmap_tx_slots(sc);
487 	na.num_rx_desc = vtnet_netmap_rx_slots(sc);
488 	na.num_tx_rings = na.num_rx_rings = sc->vtnet_max_vq_pairs;
489 	na.rx_buf_maxsize = 0;
490 	na.nm_register = vtnet_netmap_reg;
491 	na.nm_txsync = vtnet_netmap_txsync;
492 	na.nm_rxsync = vtnet_netmap_rxsync;
493 	na.nm_intr = vtnet_netmap_intr;
494 	na.nm_config = vtnet_netmap_config;
495 
496 	netmap_attach(&na);
497 
498 	nm_prinf("vtnet attached txq=%d, txd=%d rxq=%d, rxd=%d",
499 			na.num_tx_rings, na.num_tx_desc,
500 			na.num_tx_rings, na.num_rx_desc);
501 }
502 /* end of file */
503