VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/DevVirtioNet_1_0.cpp@ 96407

Last change on this file since 96407 was 96407, checked in by vboxsync, 22 months ago

scm copyright and license note update

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 162.3 KB
Line 
1/* $Id: DevVirtioNet_1_0.cpp 96407 2022-08-22 17:43:14Z vboxsync $ $Revision: 96407 $ $Date: 2022-08-22 17:43:14 +0000 (Mon, 22 Aug 2022) $ $Author: vboxsync $ */
2
3/** @file
4 * VBox storage devices - Virtio NET Driver
5 *
6 * Log-levels used:
7 * - Level 1: The most important (but usually rare) things to note
8 * - Level 2: NET command logging
9 * - Level 3: Vector and I/O transfer summary (shows what client sent an expects and fulfillment)
10 * - Level 6: Device <-> Guest Driver negotation, traffic, notifications and state handling
11 * - Level 12: Brief formatted hex dumps of I/O data
12 */
13
14/*
15 * Copyright (C) 2006-2022 Oracle and/or its affiliates.
16 *
17 * This file is part of VirtualBox base platform packages, as
18 * available from https://www.virtualbox.org.
19 *
20 * This program is free software; you can redistribute it and/or
21 * modify it under the terms of the GNU General Public License
22 * as published by the Free Software Foundation, in version 3 of the
23 * License.
24 *
25 * This program is distributed in the hope that it will be useful, but
26 * WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28 * General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, see <https://www.gnu.org/licenses>.
32 *
33 * SPDX-License-Identifier: GPL-3.0-only
34 */
35
36/*******************************************************************************************************************************
37* Header Files *
38***************************************************************************************************************************** **/
39#define LOG_GROUP LOG_GROUP_DEV_VIRTIO
40#define VIRTIONET_WITH_GSO
41
42#include <iprt/types.h>
43#include <iprt/errcore.h>
44#include <iprt/assert.h>
45#include <iprt/string.h>
46
47#include <VBox/sup.h>
48#include <VBox/vmm/pdmdev.h>
49#include <VBox/vmm/stam.h>
50#include <VBox/vmm/pdmcritsect.h>
51#include <VBox/vmm/pdmnetifs.h>
52#include <VBox/msi.h>
53#include <VBox/version.h>
54#include <VBox/log.h>
55
56
57#ifdef IN_RING3
58# include <VBox/VBoxPktDmp.h>
59# include <iprt/alloc.h>
60# include <iprt/memcache.h>
61# include <iprt/semaphore.h>
62# include <iprt/sg.h>
63# include <iprt/param.h>
64# include <iprt/uuid.h>
65#endif
66#include "../VirtIO/VirtioCore.h"
67
68#include "VBoxDD.h"
69
70#define VIRTIONET_TRANSITIONAL_ENABLE_FLAG 1 /** < If set behave as VirtIO "transitional" device */
71
72/** The current saved state version for the virtio core. */
73#define VIRTIONET_SAVEDSTATE_VERSION UINT32_C(1)
74#define VIRTIONET_SAVEDSTATE_VERSION_3_1_BETA1_LEGACY UINT32_C(1) /**< Grandfathered in from DevVirtioNet.cpp */
75#define VIRTIONET_SAVEDSTATE_VERSION_LEGACY UINT32_C(2) /**< Grandfathered in from DevVirtioNet.cpp */
76#define VIRTIONET_VERSION_MARKER_MAC_ADDR { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } /** SSM handling */
77
78/*
79 * Glossary of networking acronyms used in feature names below:
80 *
81 * GSO = Generic Segmentation Offload
82 * TSO = TCP Segmentation Offload
83 * UFO = UDP Fragmentation Offload
84 * ECN = Explicit Congestion Notification
85 */
86
87/** @name VirtIO 1.0 NET Host feature bits (See VirtIO 1.0 specification, Section 5.6.3)
88 * @{ */
89#define VIRTIONET_F_CSUM RT_BIT_64(0) /**< Handle packets with partial checksum */
90#define VIRTIONET_F_GUEST_CSUM RT_BIT_64(1) /**< Handles packets with partial checksum */
91#define VIRTIONET_F_CTRL_GUEST_OFFLOADS RT_BIT_64(2) /**< Control channel offloads reconfig support */
92#define VIRTIONET_F_MAC RT_BIT_64(5) /**< Device has given MAC address */
93#define VIRTIONET_F_GUEST_TSO4 RT_BIT_64(7) /**< Driver can receive TSOv4 */
94#define VIRTIONET_F_GUEST_TSO6 RT_BIT_64(8) /**< Driver can receive TSOv6 */
95#define VIRTIONET_F_GUEST_ECN RT_BIT_64(9) /**< Driver can receive TSO with ECN */
96#define VIRTIONET_F_GUEST_UFO RT_BIT_64(10) /**< Driver can receive UFO */
97#define VIRTIONET_F_HOST_TSO4 RT_BIT_64(11) /**< Device can receive TSOv4 */
98#define VIRTIONET_F_HOST_TSO6 RT_BIT_64(12) /**< Device can receive TSOv6 */
99#define VIRTIONET_F_HOST_ECN RT_BIT_64(13) /**< Device can receive TSO with ECN */
100#define VIRTIONET_F_HOST_UFO RT_BIT_64(14) /**< Device can receive UFO */
101#define VIRTIONET_F_MRG_RXBUF RT_BIT_64(15) /**< Driver can merge receive buffers */
102#define VIRTIONET_F_STATUS RT_BIT_64(16) /**< Config status field is available */
103#define VIRTIONET_F_CTRL_VQ RT_BIT_64(17) /**< Control channel is available */
104#define VIRTIONET_F_CTRL_RX RT_BIT_64(18) /**< Control channel RX mode + MAC addr filtering */
105#define VIRTIONET_F_CTRL_VLAN RT_BIT_64(19) /**< Control channel VLAN filtering */
106#define VIRTIONET_F_CTRL_RX_EXTRA RT_BIT_64(20) /**< Control channel RX mode extra functions */
107#define VIRTIONET_F_GUEST_ANNOUNCE RT_BIT_64(21) /**< Driver can send gratuitous packets */
108#define VIRTIONET_F_MQ RT_BIT_64(22) /**< Support ultiqueue with auto receive steering */
109#define VIRTIONET_F_CTRL_MAC_ADDR RT_BIT_64(23) /**< Set MAC address through control channel */
110/** @} */
111
112#ifdef IN_RING3
113static const VIRTIO_FEATURES_LIST s_aDevSpecificFeatures[] =
114{
115 { VIRTIONET_F_STATUS, " STATUS Configuration status field is available.\n" },
116 { VIRTIONET_F_MAC, " MAC Host has given MAC address.\n" },
117 { VIRTIONET_F_CTRL_VQ, " CTRL_VQ Control channel is available.\n" },
118 { VIRTIONET_F_CTRL_MAC_ADDR, " CTRL_MAC_ADDR Set MAC address through control channel.\n" },
119 { VIRTIONET_F_CTRL_RX, " CTRL_RX Control channel RX mode support.\n" },
120 { VIRTIONET_F_CTRL_VLAN, " CTRL_VLAN Control channel VLAN filtering.\n" },
121 { VIRTIONET_F_CTRL_GUEST_OFFLOADS, " CTRL_GUEST_OFFLOADS Control channel offloads reconfiguration support.\n" },
122 { VIRTIONET_F_GUEST_CSUM, " GUEST_CSUM Guest handles packets with partial checksum.\n" },
123 { VIRTIONET_F_GUEST_ANNOUNCE, " GUEST_ANNOUNCE Guest can send gratuitous packets.\n" },
124 { VIRTIONET_F_GUEST_TSO4, " GUEST_TSO4 Guest can receive TSOv4.\n" },
125 { VIRTIONET_F_GUEST_TSO6, " GUEST_TSO6 Guest can receive TSOv6.\n" },
126 { VIRTIONET_F_GUEST_ECN, " GUEST_ECN Guest can receive TSO with ECN.\n" },
127 { VIRTIONET_F_GUEST_UFO, " GUEST_UFO Guest can receive UFO.\n" },
128 { VIRTIONET_F_HOST_TSO4, " HOST_TSO4 Host can receive TSOv4.\n" },
129 { VIRTIONET_F_HOST_TSO6, " HOST_TSO6 Host can receive TSOv6.\n" },
130 { VIRTIONET_F_HOST_ECN, " HOST_ECN Host can receive TSO with ECN.\n" },
131 { VIRTIONET_F_HOST_UFO, " HOST_UFO Host can receive UFO.\n" },
132 { VIRTIONET_F_MQ, " MQ Host supports multiqueue with automatic receive steering.\n" },
133 { VIRTIONET_F_CSUM, " CSUM Host handles packets with partial checksum.\n" },
134 { VIRTIONET_F_MRG_RXBUF, " MRG_RXBUF Guest can merge receive buffers.\n" },
135};
136#endif
137
138#ifdef VIRTIONET_WITH_GSO
139# define VIRTIONET_HOST_FEATURES_GSO \
140 VIRTIONET_F_CSUM \
141 | VIRTIONET_F_HOST_TSO4 \
142 | VIRTIONET_F_HOST_TSO6 \
143 | VIRTIONET_F_HOST_UFO \
144 | VIRTIONET_F_GUEST_TSO4 \
145 | VIRTIONET_F_GUEST_TSO6 \
146 | VIRTIONET_F_GUEST_UFO \
147 | VIRTIONET_F_GUEST_CSUM /* @bugref(4796) Guest must handle partial chksums */
148#else
149# define VIRTIONET_HOST_FEATURES_GSO
150#endif
151
152#define VIRTIONET_HOST_FEATURES_OFFERED \
153 VIRTIONET_F_STATUS \
154 | VIRTIONET_F_GUEST_ANNOUNCE \
155 | VIRTIONET_F_MAC \
156 | VIRTIONET_F_CTRL_VQ \
157 | VIRTIONET_F_CTRL_RX \
158 | VIRTIONET_F_CTRL_VLAN \
159 | VIRTIONET_HOST_FEATURES_GSO \
160 | VIRTIONET_F_MRG_RXBUF
161
162#define FEATURE_ENABLED(feature) RT_BOOL(!!(pThis->fNegotiatedFeatures & VIRTIONET_F_##feature))
163#define FEATURE_DISABLED(feature) (!FEATURE_ENABLED(feature))
164#define FEATURE_OFFERED(feature) VIRTIONET_HOST_FEATURES_OFFERED & VIRTIONET_F_##feature
165
166#if FEATURE_OFFERED(MQ)
167/* Instance data doesn't allow an array large enough to contain VIRTIONET_CTRL_MQ_VQ_PAIRS_MAX entries */
168# define VIRTIONET_MAX_QPAIRS 1 /* This should be increased at some point and made to work */
169#else
170# define VIRTIONET_MAX_QPAIRS VIRTIONET_CTRL_MQ_VQ_PAIRS_MIN /* default, VirtIO 1.0, 5.1.6.5.5 */
171#endif
172
173#define VIRTIONET_CTRL_MQ_VQ_PAIRS 64
174#define VIRTIONET_MAX_WORKERS VIRTIONET_MAX_QPAIRS + 1
175#define VIRTIONET_MAX_VIRTQS (VIRTIONET_MAX_QPAIRS * 2 + 1)
176#define VIRTIONET_MAX_FRAME_SIZE 65535 + 18 /**< Max IP pkt size + Eth. header w/VLAN tag */
177#define VIRTIONET_MAC_FILTER_LEN 64
178#define VIRTIONET_MAX_VLAN_ID 4096
179#define VIRTIONET_RX_SEG_COUNT 32
180
181#define VIRTQNAME(uVirtqNbr) (pThis->aVirtqs[uVirtqNbr]->szName)
182#define CBVIRTQNAME(uVirtqNbr) RTStrNLen(VIRTQNAME(uVirtqNbr), sizeof(VIRTQNAME(uVirtqNbr)))
183
184#define IS_TX_VIRTQ(n) ((n) != CTRLQIDX && ((n) & 1))
185#define IS_RX_VIRTQ(n) ((n) != CTRLQIDX && !IS_TX_VIRTQ(n))
186#define IS_CTRL_VIRTQ(n) ((n) == CTRLQIDX)
187
188/*
189 * Macros to calculate queue type-pecific index number regardless of scale. VirtIO 1.0, 5.1.2
190 */
191#define RXQIDX(qPairIdx) (qPairIdx * 2)
192#define TXQIDX(qPairIdx) (RXQIDX(qPairIdx) + 1)
193#define CTRLQIDX (FEATURE_ENABLED(MQ) ? ((VIRTIONET_MAX_QPAIRS - 1) * 2 + 2) : 2)
194
195#define IS_LINK_UP(pState) !!(pState->virtioNetConfig.uStatus & VIRTIONET_F_LINK_UP)
196#define IS_LINK_DOWN(pState) !IS_LINK_UP(pState)
197
198#define SET_LINK_UP(pState) \
199 LogFunc(("SET_LINK_UP\n")); \
200 pState->virtioNetConfig.uStatus |= VIRTIONET_F_LINK_UP; \
201 virtioCoreNotifyConfigChanged(&pThis->Virtio)
202
203#define SET_LINK_DOWN(pState) \
204 LogFunc(("SET_LINK_DOWN\n")); \
205 pState->virtioNetConfig.uStatus &= ~VIRTIONET_F_LINK_UP; \
206 virtioCoreNotifyConfigChanged(&pThis->Virtio)
207
208#define IS_VIRTQ_EMPTY(pDevIns, pVirtio, uVirtqNbr) \
209 (virtioCoreVirtqAvailBufCount(pDevIns, pVirtio, uVirtqNbr) == 0)
210
211#define PCI_DEVICE_ID_VIRTIONET_HOST 0x1000 /**< VirtIO transitional device ID for network card */
212#define PCI_CLASS_BASE_NETWORK_CONTROLLER 0x0200 /**< PCI Network device class */
213#define PCI_CLASS_SUB_NET_ETHERNET_CONTROLLER 0x00 /**< PCI NET Controller subclass */
214#define PCI_CLASS_PROG_UNSPECIFIED 0x00 /**< Programming interface. N/A. */
215#define VIRTIONET_PCI_CLASS 0x01 /**< Base class Mass Storage? */
216
217/**
218 * VirtIO Network (virtio-net) device-specific configuration subregion (VirtIO 1.0, 5.1.4)
219 * Guest MMIO is processed through callback to VirtIO core which forwards references to network configuration
220 * fields to this device-specific code through a callback.
221 */
222#pragma pack(1)
223
224 typedef struct virtio_net_config
225 {
226 RTMAC uMacAddress; /**< mac */
227
228#if FEATURE_OFFERED(STATUS)
229 uint16_t uStatus; /**< status */
230#endif
231
232#if FEATURE_OFFERED(MQ)
233 uint16_t uMaxVirtqPairs; /**< max_virtq_pairs */
234#endif
235
236 } VIRTIONET_CONFIG_T, PVIRTIONET_CONFIG_T;
237
238#pragma pack()
239
240#define VIRTIONET_F_LINK_UP 1 /**< config status: Link is up */
241#define VIRTIONET_F_ANNOUNCE 2 /**< config status: Announce */
242
243/** @name VirtIO 1.0 NET Host Device device specific control types
244 * @{ */
245#define VIRTIONET_HDR_F_NEEDS_CSUM 1 /**< flags: Packet needs checksum */
246#define VIRTIONET_HDR_GSO_NONE 0 /**< gso_type: No Global Segmentation Offset */
247#define VIRTIONET_HDR_GSO_TCPV4 1 /**< gso_type: Global Segment Offset for TCPV4 */
248#define VIRTIONET_HDR_GSO_UDP 3 /**< gso_type: Global Segment Offset for UDP */
249#define VIRTIONET_HDR_GSO_TCPV6 4 /**< gso_type: Global Segment Offset for TCPV6 */
250#define VIRTIONET_HDR_GSO_ECN 0x80 /**< gso_type: Explicit Congestion Notification */
251/** @} */
252
253/* Device operation: Net header packet (VirtIO 1.0, 5.1.6) */
254#pragma pack(1)
255struct virtio_net_pkt_hdr {
256 uint8_t uFlags; /**< flags */
257 uint8_t uGsoType; /**< gso_type */
258 uint16_t uHdrLen; /**< hdr_len */
259 uint16_t uGsoSize; /**< gso_size */
260 uint16_t uChksumStart; /**< Chksum_start */
261 uint16_t uChksumOffset; /**< Chksum_offset */
262 uint16_t uNumBuffers; /**< num_buffers */
263};
264#pragma pack()
265typedef virtio_net_pkt_hdr VIRTIONETPKTHDR, *PVIRTIONETPKTHDR;
266AssertCompileSize(VIRTIONETPKTHDR, 12);
267
268/* Control virtq: Command entry (VirtIO 1.0, 5.1.6.5) */
269#pragma pack(1)
270struct virtio_net_ctrl_hdr {
271 uint8_t uClass; /**< class */
272 uint8_t uCmd; /**< command */
273};
274#pragma pack()
275typedef virtio_net_ctrl_hdr VIRTIONET_CTRL_HDR_T, *PVIRTIONET_CTRL_HDR_T;
276
277typedef uint8_t VIRTIONET_CTRL_HDR_T_ACK;
278
279/* Command entry fAck values */
280#define VIRTIONET_OK 0 /**< Internal success status */
281#define VIRTIONET_ERROR 1 /**< Internal failure status */
282
283/** @name Control virtq: Receive filtering flags (VirtIO 1.0, 5.1.6.5.1)
284 * @{ */
285#define VIRTIONET_CTRL_RX 0 /**< Control class: Receive filtering */
286#define VIRTIONET_CTRL_RX_PROMISC 0 /**< Promiscuous mode */
287#define VIRTIONET_CTRL_RX_ALLMULTI 1 /**< All-multicast receive */
288#define VIRTIONET_CTRL_RX_ALLUNI 2 /**< All-unicast receive */
289#define VIRTIONET_CTRL_RX_NOMULTI 3 /**< No multicast receive */
290#define VIRTIONET_CTRL_RX_NOUNI 4 /**< No unicast receive */
291#define VIRTIONET_CTRL_RX_NOBCAST 5 /**< No broadcast receive */
292/** @} */
293
294typedef uint8_t VIRTIONET_MAC_ADDRESS[6];
295typedef uint32_t VIRTIONET_CTRL_MAC_TABLE_LEN;
296typedef uint8_t VIRTIONET_CTRL_MAC_ENTRIES[][6];
297
298/** @name Control virtq: MAC address filtering flags (VirtIO 1.0, 5.1.6.5.2)
299 * @{ */
300#define VIRTIONET_CTRL_MAC 1 /**< Control class: MAC address filtering */
301#define VIRTIONET_CTRL_MAC_TABLE_SET 0 /**< Set MAC table */
302#define VIRTIONET_CTRL_MAC_ADDR_SET 1 /**< Set default MAC address */
303/** @} */
304
305/** @name Control virtq: MAC address filtering flags (VirtIO 1.0, 5.1.6.5.3)
306 * @{ */
307#define VIRTIONET_CTRL_VLAN 2 /**< Control class: VLAN filtering */
308#define VIRTIONET_CTRL_VLAN_ADD 0 /**< Add VLAN to filter table */
309#define VIRTIONET_CTRL_VLAN_DEL 1 /**< Delete VLAN from filter table */
310/** @} */
311
312/** @name Control virtq: Gratuitous packet sending (VirtIO 1.0, 5.1.6.5.4)
313 * @{ */
314#define VIRTIONET_CTRL_ANNOUNCE 3 /**< Control class: Gratuitous Packet Sending */
315#define VIRTIONET_CTRL_ANNOUNCE_ACK 0 /**< Gratuitous Packet Sending ACK */
316/** @} */
317
318struct virtio_net_ctrl_mq {
319 uint16_t uVirtqueuePairs; /**< virtqueue_pairs */
320};
321
322/** @name Control virtq: Receive steering in multiqueue mode (VirtIO 1.0, 5.1.6.5.5)
323 * @{ */
324#define VIRTIONET_CTRL_MQ 4 /**< Control class: Receive steering */
325#define VIRTIONET_CTRL_MQ_VQ_PAIRS_SET 0 /**< Set number of TX/RX queues */
326#define VIRTIONET_CTRL_MQ_VQ_PAIRS_MIN 1 /**< Minimum number of TX/RX queues */
327#define VIRTIONET_CTRL_MQ_VQ_PAIRS_MAX 0x8000 /**< Maximum number of TX/RX queues */
328/** @} */
329
330uint64_t uOffloads; /**< offloads */
331
332/** @name Control virtq: Setting Offloads State (VirtIO 1.0, 5.1.6.5.6.1)
333 * @{ */
334#define VIRTIONET_CTRL_GUEST_OFFLOADS 5 /**< Control class: Offloads state configuration */
335#define VIRTIONET_CTRL_GUEST_OFFLOADS_SET 0 /**< Apply new offloads configuration */
336/** @} */
337
338typedef enum VIRTIONETPKTHDRTYPE
339{
340 kVirtioNetUninitializedPktHdrType = 0, /**< Uninitialized (default) packet header type */
341 kVirtioNetModernPktHdrWithoutMrgRx = 1, /**< Packets should not be merged (modern driver) */
342 kVirtioNetModernPktHdrWithMrgRx = 2, /**< Packets should be merged (modern driver) */
343 kVirtioNetLegacyPktHdrWithoutMrgRx = 3, /**< Packets should not be merged (legacy driver) */
344 kVirtioNetLegacyPktHdrWithMrgRx = 4, /**< Packets should be merged (legacy driver) */
345 kVirtioNetFor32BitHack = 0x7fffffff
346} VIRTIONETPKTHDRTYPE;
347
348/**
349 * device-specific queue info
350 */
351struct VIRTIONETWORKER;
352struct VIRTIONETWORKERR3;
353
354typedef struct VIRTIONETVIRTQ
355{
356 uint16_t uIdx; /**< Index of this queue */
357 uint16_t align;
358 bool fCtlVirtq; /**< If set this queue is the control queue */
359 bool fHasWorker; /**< If set this queue has an associated worker */
360 bool fAttachedToVirtioCore; /**< Set if queue attached to virtio core */
361 char szName[VIRTIO_MAX_VIRTQ_NAME_SIZE]; /**< Virtq name */
362} VIRTIONETVIRTQ, *PVIRTIONETVIRTQ;
363
364/**
365 * Worker thread context, shared state.
366 */
367typedef struct VIRTIONETWORKER
368{
369 SUPSEMEVENT hEvtProcess; /**< handle of associated sleep/wake-up semaphore */
370 uint16_t uIdx; /**< Index of this worker */
371 bool volatile fSleeping; /**< Flags whether worker thread is sleeping or not */
372 bool volatile fNotified; /**< Flags whether worker thread notified */
373 bool fAssigned; /**< Flags whether worker thread has been set up */
374 uint8_t pad;
375} VIRTIONETWORKER;
376/** Pointer to a virtio net worker. */
377typedef VIRTIONETWORKER *PVIRTIONETWORKER;
378
379/**
380 * Worker thread context, ring-3 state.
381 */
382typedef struct VIRTIONETWORKERR3
383{
384 R3PTRTYPE(PPDMTHREAD) pThread; /**< pointer to worker thread's handle */
385 uint16_t uIdx; /**< Index of this worker */
386 uint16_t pad;
387} VIRTIONETWORKERR3;
388/** Pointer to a virtio net worker. */
389typedef VIRTIONETWORKERR3 *PVIRTIONETWORKERR3;
390
391/**
392 * VirtIO Host NET device state, shared edition.
393 *
394 * @extends VIRTIOCORE
395 */
396typedef struct VIRTIONET
397{
398 /** The core virtio state. */
399 VIRTIOCORE Virtio;
400
401 /** Virtio device-specific configuration */
402 VIRTIONET_CONFIG_T virtioNetConfig;
403
404 /** Per device-bound virtq worker-thread contexts (eventq slot unused) */
405 VIRTIONETWORKER aWorkers[VIRTIONET_MAX_VIRTQS];
406
407 /** Track which VirtIO queues we've attached to */
408 VIRTIONETVIRTQ aVirtqs[VIRTIONET_MAX_VIRTQS];
409
410 /** PDM device Instance name */
411 char szInst[16];
412
413 /** VirtIO features negotiated with the guest, including generic core and device specific */
414 uint64_t fNegotiatedFeatures;
415
416 /** Number of Rx/Tx queue pairs (only one if MQ feature not negotiated */
417 uint16_t cVirtqPairs;
418
419 /** Number of Rx/Tx queue pairs that have already been initialized */
420 uint16_t cInitializedVirtqPairs;
421
422 /** Number of virtqueues total (which includes each queue of each pair plus one control queue */
423 uint16_t cVirtqs;
424
425 /** Number of worker threads (one for the control queue and one for each Tx queue) */
426 uint16_t cWorkers;
427
428 /** Alignment */
429 uint16_t alignment;
430
431 /** Indicates transmission in progress -- only one thread is allowed. */
432 uint32_t uIsTransmitting;
433
434 /** Link up delay (in milliseconds). */
435 uint32_t cMsLinkUpDelay;
436
437 /** The number of actually used slots in aMacMulticastFilter. */
438 uint32_t cMulticastFilterMacs;
439
440 /** The number of actually used slots in aMacUniicastFilter. */
441 uint32_t cUnicastFilterMacs;
442
443 /** Semaphore leaf device's thread waits on until guest driver sends empty Rx bufs */
444 SUPSEMEVENT hEventRxDescAvail;
445
446 /** Array of MAC multicast addresses accepted by RX filter. */
447 RTMAC aMacMulticastFilter[VIRTIONET_MAC_FILTER_LEN];
448
449 /** Array of MAC unicast addresses accepted by RX filter. */
450 RTMAC aMacUnicastFilter[VIRTIONET_MAC_FILTER_LEN];
451
452 /** Default MAC address which rx filtering accepts */
453 RTMAC rxFilterMacDefault;
454
455 /** MAC address obtained from the configuration. */
456 RTMAC macConfigured;
457
458 /** Bit array of VLAN filter, one bit per VLAN ID. */
459 uint8_t aVlanFilter[VIRTIONET_MAX_VLAN_ID / sizeof(uint8_t)];
460
461 /** Set if PDM leaf device at the network interface is starved for Rx buffers */
462 bool volatile fLeafWantsEmptyRxBufs;
463
464 /** Number of packet being sent/received to show in debug log. */
465 uint32_t uPktNo;
466
467 /** Flags whether VirtIO core is in ready state */
468 uint8_t fVirtioReady;
469
470 /** Resetting flag */
471 uint8_t fResetting;
472
473 /** Promiscuous mode -- RX filter accepts all packets. */
474 uint8_t fPromiscuous;
475
476 /** All multicast mode -- RX filter accepts all multicast packets. */
477 uint8_t fAllMulticast;
478
479 /** All unicast mode -- RX filter accepts all unicast packets. */
480 uint8_t fAllUnicast;
481
482 /** No multicast mode - Supresses multicast receive */
483 uint8_t fNoMulticast;
484
485 /** No unicast mode - Suppresses unicast receive */
486 uint8_t fNoUnicast;
487
488 /** No broadcast mode - Supresses broadcast receive */
489 uint8_t fNoBroadcast;
490
491 /** Type of network pkt header based on guest driver version/features */
492 VIRTIONETPKTHDRTYPE ePktHdrType;
493
494 /** Size of network pkt header based on guest driver version/features */
495 uint16_t cbPktHdr;
496
497 /** True if physical cable is attached in configuration. */
498 bool fCableConnected;
499
500 /** True if this device should offer legacy virtio support to the guest */
501 bool fOfferLegacy;
502
503 /** @name Statistic
504 * @{ */
505 STAMCOUNTER StatReceiveBytes;
506 STAMCOUNTER StatTransmitBytes;
507 STAMCOUNTER StatReceiveGSO;
508 STAMCOUNTER StatTransmitPackets;
509 STAMCOUNTER StatTransmitGSO;
510 STAMCOUNTER StatTransmitCSum;
511#ifdef VBOX_WITH_STATISTICS
512 STAMPROFILE StatReceive;
513 STAMPROFILE StatReceiveStore;
514 STAMPROFILEADV StatTransmit;
515 STAMPROFILE StatTransmitSend;
516 STAMPROFILE StatRxOverflow;
517 STAMCOUNTER StatRxOverflowWakeup;
518 STAMCOUNTER StatTransmitByNetwork;
519 STAMCOUNTER StatTransmitByThread;
520 /** @} */
521#endif
522} VIRTIONET;
523/** Pointer to the shared state of the VirtIO Host NET device. */
524typedef VIRTIONET *PVIRTIONET;
525
526/**
527 * VirtIO Host NET device state, ring-3 edition.
528 *
529 * @extends VIRTIOCORER3
530 */
531typedef struct VIRTIONETR3
532{
533 /** The core virtio ring-3 state. */
534 VIRTIOCORER3 Virtio;
535
536 /** Per device-bound virtq worker-thread contexts (eventq slot unused) */
537 VIRTIONETWORKERR3 aWorkers[VIRTIONET_MAX_VIRTQS];
538
539 /** The device instance.
540 * @note This is _only_ for use whxen dealing with interface callbacks. */
541 PPDMDEVINSR3 pDevIns;
542
543 /** Status LUN: Base interface. */
544 PDMIBASE IBase;
545
546 /** Status LUN: LED port interface. */
547 PDMILEDPORTS ILeds;
548
549 /** Status LUN: LED connector (peer). */
550 R3PTRTYPE(PPDMILEDCONNECTORS) pLedsConnector;
551
552 /** Status: LED */
553 PDMLED led;
554
555 /** Attached network driver. */
556 R3PTRTYPE(PPDMIBASE) pDrvBase;
557
558 /** Network port interface (down) */
559 PDMINETWORKDOWN INetworkDown;
560
561 /** Network config port interface (main). */
562 PDMINETWORKCONFIG INetworkConfig;
563
564 /** Connector of attached network driver. */
565 R3PTRTYPE(PPDMINETWORKUP) pDrv;
566
567 /** Link Up(/Restore) Timer. */
568 TMTIMERHANDLE hLinkUpTimer;
569
570} VIRTIONETR3;
571
572/** Pointer to the ring-3 state of the VirtIO Host NET device. */
573typedef VIRTIONETR3 *PVIRTIONETR3;
574
575/**
576 * VirtIO Host NET device state, ring-0 edition.
577 */
578typedef struct VIRTIONETR0
579{
580 /** The core virtio ring-0 state. */
581 VIRTIOCORER0 Virtio;
582} VIRTIONETR0;
583/** Pointer to the ring-0 state of the VirtIO Host NET device. */
584typedef VIRTIONETR0 *PVIRTIONETR0;
585
586/**
587 * VirtIO Host NET device state, raw-mode edition.
588 */
589typedef struct VIRTIONETRC
590{
591 /** The core virtio raw-mode state. */
592 VIRTIOCORERC Virtio;
593} VIRTIONETRC;
594/** Pointer to the ring-0 state of the VirtIO Host NET device. */
595typedef VIRTIONETRC *PVIRTIONETRC;
596
597/** @typedef VIRTIONETCC
598 * The instance data for the current context. */
599typedef CTX_SUFF(VIRTIONET) VIRTIONETCC;
600
601/** @typedef PVIRTIONETCC
602 * Pointer to the instance data for the current context. */
603typedef CTX_SUFF(PVIRTIONET) PVIRTIONETCC;
604
605#ifdef IN_RING3
606static DECLCALLBACK(int) virtioNetR3WorkerThread(PPDMDEVINS pDevIns, PPDMTHREAD pThread);
607static int virtioNetR3CreateWorkerThreads(PPDMDEVINS, PVIRTIONET, PVIRTIONETCC);
608
609/**
610 * Helper function used when logging state of a VM thread.
611 *
612 * @param Thread
613 *
614 * @return Associated name of thread as a pointer to a zero-terminated string.
615 */
616DECLINLINE(const char *) virtioNetThreadStateName(PPDMTHREAD pThread)
617{
618 if (!pThread)
619 return "<null>";
620
621 switch(pThread->enmState)
622 {
623 case PDMTHREADSTATE_INVALID:
624 return "invalid state";
625 case PDMTHREADSTATE_INITIALIZING:
626 return "initializing";
627 case PDMTHREADSTATE_SUSPENDING:
628 return "suspending";
629 case PDMTHREADSTATE_SUSPENDED:
630 return "suspended";
631 case PDMTHREADSTATE_RESUMING:
632 return "resuming";
633 case PDMTHREADSTATE_RUNNING:
634 return "running";
635 case PDMTHREADSTATE_TERMINATING:
636 return "terminating";
637 case PDMTHREADSTATE_TERMINATED:
638 return "terminated";
639 default:
640 return "unknown state";
641 }
642}
643#endif
644
645/**
646 * Wakeup PDM managed downstream (e.g. hierarchically inferior device's) RX thread
647 */
648static DECLCALLBACK(void) virtioNetWakeupRxBufWaiter(PPDMDEVINS pDevIns)
649{
650 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
651
652 AssertReturnVoid(pThis->hEventRxDescAvail != NIL_SUPSEMEVENT);
653
654 STAM_COUNTER_INC(&pThis->StatRxOverflowWakeup);
655 if (pThis->hEventRxDescAvail != NIL_SUPSEMEVENT)
656 {
657 Log10Func(("[%s] Waking downstream device's Rx buf waiter thread\n", pThis->szInst));
658 int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->hEventRxDescAvail);
659 AssertRC(rc);
660 }
661}
662
663/**
664 * Guest notifying us of its activity with a queue. Figure out which queue and respond accordingly.
665 *
666 * @callback_method_impl{VIRTIOCORER0,pfnVirtqNotified}
667 */
668static DECLCALLBACK(void) virtioNetVirtqNotified(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr)
669{
670 RT_NOREF(pVirtio);
671 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
672
673 PVIRTIONETVIRTQ pVirtq = &pThis->aVirtqs[uVirtqNbr];
674 PVIRTIONETWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
675
676#if defined (IN_RING3) && defined (LOG_ENABLED)
677 RTLogFlush(NULL);
678#endif
679 if (IS_RX_VIRTQ(uVirtqNbr))
680 {
681 uint16_t cBufsAvailable = virtioCoreVirtqAvailBufCount(pDevIns, pVirtio, uVirtqNbr);
682
683 if (cBufsAvailable)
684 {
685 Log10Func(("%s %u empty bufs added to %s by guest (notifying leaf device)\n",
686 pThis->szInst, cBufsAvailable, pVirtq->szName));
687 virtioNetWakeupRxBufWaiter(pDevIns);
688 }
689 else
690 Log10Func(("%s \n\n***WARNING: %s notified but no empty bufs added by guest! (skip leaf dev. notification)\n\n",
691 pThis->szInst, pVirtq->szName));
692 }
693 else if (IS_TX_VIRTQ(uVirtqNbr) || IS_CTRL_VIRTQ(uVirtqNbr))
694 {
695 /* Wake queue's worker thread up if sleeping (e.g. a Tx queue, or the control queue */
696 if (!ASMAtomicXchgBool(&pWorker->fNotified, true))
697 {
698 if (ASMAtomicReadBool(&pWorker->fSleeping))
699 {
700 Log10Func(("[%s] %s has available buffers - waking worker.\n", pThis->szInst, pVirtq->szName));
701
702 int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pWorker->hEvtProcess);
703 AssertRC(rc);
704 }
705 else
706 Log10Func(("[%s] %s has available buffers - worker already awake\n", pThis->szInst, pVirtq->szName));
707 }
708 else
709 Log10Func(("[%s] %s has available buffers - waking worker.\n", pThis->szInst, pVirtq->szName));
710 }
711 else
712 LogRelFunc(("[%s] unrecognized queue %s (idx=%d) notified\n", pThis->szInst, pVirtq->szName, uVirtqNbr));
713}
714
715#ifdef IN_RING3 /* spans most of the file, at the moment. */
716
717/**
718 * @callback_method_impl{FNPDMTHREADWAKEUPDEV}
719 */
720static DECLCALLBACK(int) virtioNetR3WakeupWorker(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
721{
722 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
723 PVIRTIONETWORKER pWorker = (PVIRTIONETWORKER)pThread->pvUser;
724
725 Log10Func(("[%s]\n", pThis->szInst));
726 RT_NOREF(pThis);
727 return PDMDevHlpSUPSemEventSignal(pDevIns, pWorker->hEvtProcess);
728}
729
730/**
731 * Set queue names, distinguishing between modern or legacy mode.
732 *
733 * @note This makes it obvious during logging which mode this transitional device is
734 * operating in, legacy or modern.
735 *
736 * @param pThis Device specific device state
737 * @param fLegacy (input) true if running in legacy mode
738 * false if running in modern mode
739 */
740DECLINLINE(void) virtioNetR3SetVirtqNames(PVIRTIONET pThis, uint32_t fLegacy)
741{
742 RTStrCopy(pThis->aVirtqs[CTRLQIDX].szName, VIRTIO_MAX_VIRTQ_NAME_SIZE, fLegacy ? "legacy-ctrlq" : " modern-ctrlq");
743 for (uint16_t qPairIdx = 0; qPairIdx < pThis->cVirtqPairs; qPairIdx++)
744 {
745 RTStrPrintf(pThis->aVirtqs[RXQIDX(qPairIdx)].szName, VIRTIO_MAX_VIRTQ_NAME_SIZE, "%s-recvq<%d>", fLegacy ? "legacy" : "modern", qPairIdx);
746 RTStrPrintf(pThis->aVirtqs[TXQIDX(qPairIdx)].szName, VIRTIO_MAX_VIRTQ_NAME_SIZE, "%s-xmitq<%d>", fLegacy ? "legacy" : "modern", qPairIdx);
747 }
748}
749
750/**
751 * Dump a packet to debug log.
752 *
753 * @param pThis The virtio-net shared instance data.
754 * @param pbPacket The packet.
755 * @param cb The size of the packet.
756 * @param pszText A string denoting direction of packet transfer.
757 */
758DECLINLINE(void) virtioNetR3PacketDump(PVIRTIONET pThis, const uint8_t *pbPacket, size_t cb, const char *pszText)
759{
760#ifdef LOG_ENABLED
761 if (!LogIs12Enabled())
762 return;
763#endif
764 vboxEthPacketDump(pThis->szInst, pszText, pbPacket, (uint32_t)cb);
765}
766
767#ifdef LOG_ENABLED
768void virtioNetDumpGcPhysRxBuf(PPDMDEVINS pDevIns, PVIRTIONETPKTHDR pRxPktHdr,
769 uint16_t cVirtqBufs, uint8_t *pvBuf, uint16_t cb, RTGCPHYS GCPhysRxBuf, uint8_t cbRxBuf)
770{
771 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
772 pRxPktHdr->uNumBuffers = cVirtqBufs;
773 if (pRxPktHdr)
774 {
775 LogFunc(("%*c\nrxPktHdr\n"
776 " uFlags ......... %2.2x\n uGsoType ....... %2.2x\n uHdrLen ........ %4.4x\n"
777 " uGsoSize ....... %4.4x\n uChksumStart ... %4.4x\n uChksumOffset .. %4.4x\n",
778 60, ' ', pRxPktHdr->uFlags, pRxPktHdr->uGsoType, pRxPktHdr->uHdrLen, pRxPktHdr->uGsoSize,
779 pRxPktHdr->uChksumStart, pRxPktHdr->uChksumOffset));
780 if (!virtioCoreIsLegacyMode(&pThis->Virtio) || FEATURE_ENABLED(MRG_RXBUF))
781 LogFunc((" uNumBuffers .... %4.4x\n", pRxPktHdr->uNumBuffers));
782 virtioCoreHexDump((uint8_t *)pRxPktHdr, sizeof(VIRTIONETPKTHDR), 0, "Dump of virtual rPktHdr");
783 }
784 virtioNetR3PacketDump(pThis, (const uint8_t *)pvBuf, cb, "<-- Incoming");
785 LogFunc((". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n"));
786 virtioCoreGCPhysHexDump(pDevIns, GCPhysRxBuf, cbRxBuf, 0, "Phys Mem Dump of Rx pkt");
787 LogFunc(("%*c", 60, '-'));
788}
789
790#endif /* LOG_ENABLED */
791
792/**
793 * @callback_method_impl{FNDBGFHANDLERDEV, virtio-net debugger info callback.}
794 */
795static DECLCALLBACK(void) virtioNetR3Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
796{
797 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
798 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
799
800 bool fNone = pszArgs && *pszArgs == '\0';
801 bool fAll = pszArgs && (*pszArgs == 'a' || *pszArgs == 'A'); /* "all" */
802 bool fNetwork = pszArgs && (*pszArgs == 'n' || *pszArgs == 'N'); /* "network" */
803 bool fFeatures = pszArgs && (*pszArgs == 'f' || *pszArgs == 'F'); /* "features" */
804 bool fState = pszArgs && (*pszArgs == 's' || *pszArgs == 'S'); /* "state" */
805 bool fPointers = pszArgs && (*pszArgs == 'p' || *pszArgs == 'P'); /* "pointers" */
806 bool fVirtqs = pszArgs && (*pszArgs == 'q' || *pszArgs == 'Q'); /* "queues */
807
808 /* Show basic information. */
809 pHlp->pfnPrintf(pHlp,
810 "\n"
811 "---------------------------------------------------------------------------\n"
812 "Debug Info: %s\n"
813 " (options: [a]ll, [n]et, [f]eatures, [s]tate, [p]ointers, [q]ueues)\n"
814 "---------------------------------------------------------------------------\n\n",
815 pThis->szInst);
816
817 if (fNone)
818 return;
819
820 /* Show offered/unoffered, accepted/rejected features */
821 if (fAll || fFeatures)
822 {
823 virtioCorePrintDeviceFeatures(&pThis->Virtio, pHlp, s_aDevSpecificFeatures,
824 RT_ELEMENTS(s_aDevSpecificFeatures));
825 pHlp->pfnPrintf(pHlp, "\n");
826 }
827
828 /* Show queues (and associate worker info if applicable) */
829 if (fAll || fVirtqs)
830 {
831 pHlp->pfnPrintf(pHlp, "Virtq information:\n\n");
832 for (int uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
833 {
834 PVIRTIONETVIRTQ pVirtq = &pThis->aVirtqs[uVirtqNbr];
835
836 if (pVirtq->fHasWorker)
837 {
838 PVIRTIONETWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
839 PVIRTIONETWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
840
841 Assert((pWorker->uIdx == pVirtq->uIdx));
842 Assert((pWorkerR3->uIdx == pVirtq->uIdx));
843
844 if (pWorker->fAssigned)
845 {
846 pHlp->pfnPrintf(pHlp, " %-15s (pThread: %p %s) ",
847 pVirtq->szName,
848 pWorkerR3->pThread,
849 virtioNetThreadStateName(pWorkerR3->pThread));
850 if (pVirtq->fAttachedToVirtioCore)
851 {
852 pHlp->pfnPrintf(pHlp, "worker: ");
853 pHlp->pfnPrintf(pHlp, "%s", pWorker->fSleeping ? "blocking" : "unblocked");
854 pHlp->pfnPrintf(pHlp, "%s", pWorker->fNotified ? ", notified" : "");
855 }
856 else
857 if (pWorker->fNotified)
858 pHlp->pfnPrintf(pHlp, "not attached to virtio core");
859 }
860 }
861 else
862 {
863 pHlp->pfnPrintf(pHlp, " %-15s (INetworkDown's thread) %s", pVirtq->szName,
864 pVirtq->fAttachedToVirtioCore ? "" : "not attached to virtio core");
865 }
866 pHlp->pfnPrintf(pHlp, "\n");
867 virtioCoreR3VirtqInfo(pDevIns, pHlp, pszArgs, uVirtqNbr);
868 pHlp->pfnPrintf(pHlp, " ---------------------------------------------------------------------\n");
869 pHlp->pfnPrintf(pHlp, "\n");
870 }
871 pHlp->pfnPrintf(pHlp, "\n");
872 }
873
874 /* Show various pointers */
875 if (fAll || fPointers)
876 {
877 pHlp->pfnPrintf(pHlp, "Internal Pointers (for instance \"%s\"):\n\n", pThis->szInst);
878 pHlp->pfnPrintf(pHlp, " pDevIns ................... %p\n", pDevIns);
879 pHlp->pfnPrintf(pHlp, " PVIRTIOCORE ............... %p\n", &pThis->Virtio);
880 pHlp->pfnPrintf(pHlp, " PVIRTIONET ................ %p\n", pThis);
881 pHlp->pfnPrintf(pHlp, " PVIRTIONETCC .............. %p\n", pThisCC);
882 pHlp->pfnPrintf(pHlp, " VIRTIONETVIRTQ[] .......... %p\n", pThis->aVirtqs);
883 pHlp->pfnPrintf(pHlp, " pDrvBase .................. %p\n", pThisCC->pDrvBase);
884 pHlp->pfnPrintf(pHlp, " pDrv ...................... %p\n", pThisCC->pDrv);
885 pHlp->pfnPrintf(pHlp, " pDrv ...................... %p\n", pThisCC->pDrv);
886 pHlp->pfnPrintf(pHlp, "\n");
887 }
888
889 /* Show device state info */
890 if (fAll || fState)
891 {
892 pHlp->pfnPrintf(pHlp, "Device state:\n\n");
893 uint32_t fTransmitting = ASMAtomicReadU32(&pThis->uIsTransmitting);
894
895 pHlp->pfnPrintf(pHlp, " Transmitting: ............. %s\n", fTransmitting ? "true" : "false");
896 pHlp->pfnPrintf(pHlp, "\n");
897 pHlp->pfnPrintf(pHlp, "Misc state\n");
898 pHlp->pfnPrintf(pHlp, "\n");
899 pHlp->pfnPrintf(pHlp, " fOfferLegacy .............. %d\n", pThis->fOfferLegacy);
900 pHlp->pfnPrintf(pHlp, " fVirtioReady .............. %d\n", pThis->fVirtioReady);
901 pHlp->pfnPrintf(pHlp, " fResetting ................ %d\n", pThis->fResetting);
902 pHlp->pfnPrintf(pHlp, " fGenUpdatePending ......... %d\n", pThis->Virtio.fGenUpdatePending);
903 pHlp->pfnPrintf(pHlp, " fMsiSupport ............... %d\n", pThis->Virtio.fMsiSupport);
904 pHlp->pfnPrintf(pHlp, " uConfigGeneration ......... %d\n", pThis->Virtio.uConfigGeneration);
905 pHlp->pfnPrintf(pHlp, " uDeviceStatus ............. 0x%x\n", pThis->Virtio.fDeviceStatus);
906 pHlp->pfnPrintf(pHlp, " cVirtqPairs .,............. %d\n", pThis->cVirtqPairs);
907 pHlp->pfnPrintf(pHlp, " cVirtqs .,................. %d\n", pThis->cVirtqs);
908 pHlp->pfnPrintf(pHlp, " cWorkers .................. %d\n", pThis->cWorkers);
909 pHlp->pfnPrintf(pHlp, " MMIO mapping name ......... %d\n", pThisCC->Virtio.szMmioName);
910 pHlp->pfnPrintf(pHlp, "\n");
911 }
912
913 /* Show network related information */
914 if (fAll || fNetwork)
915 {
916 pHlp->pfnPrintf(pHlp, "Network configuration:\n\n");
917 pHlp->pfnPrintf(pHlp, " MAC: ...................... %RTmac\n", &pThis->macConfigured);
918 pHlp->pfnPrintf(pHlp, "\n");
919 pHlp->pfnPrintf(pHlp, " Cable: .................... %s\n", pThis->fCableConnected ? "connected" : "disconnected");
920 pHlp->pfnPrintf(pHlp, " Link-up delay: ............ %d ms\n", pThis->cMsLinkUpDelay);
921 pHlp->pfnPrintf(pHlp, "\n");
922 pHlp->pfnPrintf(pHlp, " Accept all multicast: ..... %s\n", pThis->fAllMulticast ? "true" : "false");
923 pHlp->pfnPrintf(pHlp, " Suppress broadcast: ....... %s\n", pThis->fNoBroadcast ? "true" : "false");
924 pHlp->pfnPrintf(pHlp, " Suppress unicast: ......... %s\n", pThis->fNoUnicast ? "true" : "false");
925 pHlp->pfnPrintf(pHlp, " Suppress multicast: ....... %s\n", pThis->fNoMulticast ? "true" : "false");
926 pHlp->pfnPrintf(pHlp, " Promiscuous: .............. %s\n", pThis->fPromiscuous ? "true" : "false");
927 pHlp->pfnPrintf(pHlp, "\n");
928 pHlp->pfnPrintf(pHlp, " Default Rx MAC filter: .... %RTmac\n", pThis->rxFilterMacDefault);
929 pHlp->pfnPrintf(pHlp, "\n");
930
931 pHlp->pfnPrintf(pHlp, " Unicast filter MACs:\n");
932
933 if (!pThis->cUnicastFilterMacs)
934 pHlp->pfnPrintf(pHlp, " <none>\n");
935
936 for (uint32_t i = 0; i < pThis->cUnicastFilterMacs; i++)
937 pHlp->pfnPrintf(pHlp, " %RTmac\n", &pThis->aMacUnicastFilter[i]);
938
939 pHlp->pfnPrintf(pHlp, "\n Multicast filter MACs:\n");
940
941 if (!pThis->cMulticastFilterMacs)
942 pHlp->pfnPrintf(pHlp, " <none>\n");
943
944 for (uint32_t i = 0; i < pThis->cMulticastFilterMacs; i++)
945 pHlp->pfnPrintf(pHlp, " %RTmac\n", &pThis->aMacMulticastFilter[i]);
946
947 pHlp->pfnPrintf(pHlp, "\n\n");
948 pHlp->pfnPrintf(pHlp, " Leaf starved: ............. %s\n", pThis->fLeafWantsEmptyRxBufs ? "true" : "false");
949 pHlp->pfnPrintf(pHlp, "\n");
950 }
951 /** @todo implement this
952 * pHlp->pfnPrintf(pHlp, "\n");
953 * virtioCoreR3Info(pDevIns, pHlp, pszArgs);
954 */
955 pHlp->pfnPrintf(pHlp, "\n");
956}
957
958/**
959 * Checks whether certain mutually dependent negotiated features are clustered in required combinations.
960 *
961 * @note See VirtIO 1.0 spec, Section 5.1.3.1
962 *
963 * @param fFeatures Bitmask of negotiated features to evaluate
964 *
965 * @returns true if valid feature combination(s) found.
966 * false if non-valid feature set.
967 */
968DECLINLINE(bool) virtioNetValidateRequiredFeatures(uint32_t fFeatures)
969{
970 uint32_t fGuestChksumRequired = fFeatures & VIRTIONET_F_GUEST_TSO4
971 || fFeatures & VIRTIONET_F_GUEST_TSO6
972 || fFeatures & VIRTIONET_F_GUEST_UFO;
973
974 uint32_t fHostChksumRequired = fFeatures & VIRTIONET_F_HOST_TSO4
975 || fFeatures & VIRTIONET_F_HOST_TSO6
976 || fFeatures & VIRTIONET_F_HOST_UFO;
977
978 uint32_t fCtrlVqRequired = fFeatures & VIRTIONET_F_CTRL_RX
979 || fFeatures & VIRTIONET_F_CTRL_VLAN
980 || fFeatures & VIRTIONET_F_GUEST_ANNOUNCE
981 || fFeatures & VIRTIONET_F_MQ
982 || fFeatures & VIRTIONET_F_CTRL_MAC_ADDR;
983
984 if (fGuestChksumRequired && !(fFeatures & VIRTIONET_F_GUEST_CSUM))
985 return false;
986
987 if (fHostChksumRequired && !(fFeatures & VIRTIONET_F_CSUM))
988 return false;
989
990 if (fCtrlVqRequired && !(fFeatures & VIRTIONET_F_CTRL_VQ))
991 return false;
992
993 if ( fFeatures & VIRTIONET_F_GUEST_ECN
994 && !( fFeatures & VIRTIONET_F_GUEST_TSO4
995 || fFeatures & VIRTIONET_F_GUEST_TSO6))
996 return false;
997
998 if ( fFeatures & VIRTIONET_F_HOST_ECN
999 && !( fFeatures & VIRTIONET_F_HOST_TSO4
1000 || fFeatures & VIRTIONET_F_HOST_TSO6))
1001 return false;
1002 return true;
1003}
1004
1005/**
1006 * Read or write device-specific configuration parameters.
1007 * This is called by VirtIO core code a guest-initiated MMIO access is made to access device-specific
1008 * configuration
1009 *
1010 * @note See VirtIO 1.0 spec, 2.3 Device Configuration Space
1011 *
1012 * @param pThis Pointer to device-specific state
1013 * @param uOffsetOfAccess Offset (within VIRTIONET_CONFIG_T)
1014 * @param pv Pointer to data to read or write
1015 * @param cb Number of bytes to read or write
1016 * @param fWrite True if writing, false if reading
1017 *
1018 * @returns VINF_SUCCESS if successful, or VINF_IOM_MMIO_UNUSED if fails (bad offset or size)
1019 */
1020static int virtioNetR3DevCfgAccess(PVIRTIONET pThis, uint32_t uOffsetOfAccess, void *pv, uint32_t cb, bool fWrite)
1021{
1022 AssertReturn(pv && cb <= sizeof(uint32_t), fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00);
1023
1024 if (VIRTIO_DEV_CONFIG_SUBMATCH_MEMBER( uMacAddress, VIRTIONET_CONFIG_T, uOffsetOfAccess))
1025 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMacAddress, VIRTIONET_CONFIG_T, uOffsetOfAccess, &pThis->virtioNetConfig);
1026#if FEATURE_OFFERED(STATUS)
1027 else
1028 if (VIRTIO_DEV_CONFIG_SUBMATCH_MEMBER( uStatus, VIRTIONET_CONFIG_T, uOffsetOfAccess))
1029 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uStatus, VIRTIONET_CONFIG_T, uOffsetOfAccess, &pThis->virtioNetConfig);
1030#endif
1031#if FEATURE_OFFERED(MQ)
1032 else
1033 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxVirtqPairs, VIRTIONET_CONFIG_T, uOffsetOfAccess))
1034 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxVirtqPairs, VIRTIONET_CONFIG_T, uOffsetOfAccess, &pThis->virtioNetConfig);
1035#endif
1036 else
1037 {
1038 LogFunc(("%s Bad access by guest to virtio_net_config: off=%u (%#x), cb=%u\n",
1039 pThis->szInst, uOffsetOfAccess, uOffsetOfAccess, cb));
1040 return fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00;
1041 }
1042 return VINF_SUCCESS;
1043}
1044
1045/**
1046 * @callback_method_impl{VIRTIOCORER3,pfnDevCapRead}
1047 */
1048static DECLCALLBACK(int) virtioNetR3DevCapRead(PPDMDEVINS pDevIns, uint32_t uOffset, void *pv, uint32_t cb)
1049{
1050 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
1051
1052 RT_NOREF(pThis);
1053 return virtioNetR3DevCfgAccess(PDMDEVINS_2_DATA(pDevIns, PVIRTIONET), uOffset, pv, cb, false /*fRead*/);
1054}
1055
1056/**
1057 * @callback_method_impl{VIRTIOCORER3,pfnDevCapWrite}
1058 */
1059static DECLCALLBACK(int) virtioNetR3DevCapWrite(PPDMDEVINS pDevIns, uint32_t uOffset, const void *pv, uint32_t cb)
1060{
1061 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
1062
1063 Log10Func(("[%s] uOffset: %d, cb: %d: %.*Rhxs\n", pThis->szInst, uOffset, cb, RT_MAX(cb, 8) , pv));
1064 RT_NOREF(pThis);
1065 return virtioNetR3DevCfgAccess(PDMDEVINS_2_DATA(pDevIns, PVIRTIONET), uOffset, (void *)pv, cb, true /*fWrite*/);
1066}
1067
1068static int virtioNetR3VirtqDestroy(PVIRTIOCORE pVirtio, PVIRTIONETVIRTQ pVirtq)
1069{
1070 PVIRTIONET pThis = RT_FROM_MEMBER(pVirtio, VIRTIONET, Virtio);
1071 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pVirtio->pDevInsR3, PVIRTIONETCC);
1072 PVIRTIONETWORKER pWorker = &pThis->aWorkers[pVirtq->uIdx];
1073 PVIRTIONETWORKERR3 pWorkerR3 = &pThisCC->aWorkers[pVirtq->uIdx];
1074
1075 int rc = VINF_SUCCESS, rcThread;
1076 Log10Func(("[%s] Destroying \"%s\"", pThis->szInst, pVirtq->szName));
1077 if (pVirtq->fHasWorker)
1078 {
1079 Log10((" and its worker"));
1080 rc = PDMDevHlpSUPSemEventClose(pVirtio->pDevInsR3, pWorker->hEvtProcess);
1081 AssertRCReturn(rc, rc);
1082 pWorker->hEvtProcess = 0;
1083 rc = PDMDevHlpThreadDestroy(pVirtio->pDevInsR3, pWorkerR3->pThread, &rcThread);
1084 AssertRCReturn(rc, rc);
1085 pWorkerR3->pThread = 0;
1086 pVirtq->fHasWorker = false;
1087 }
1088 pWorker->fAssigned = false;
1089 pVirtq->fCtlVirtq = false;
1090 Log10(("\n"));
1091 return rc;
1092}
1093
1094
1095/*********************************************************************************************************************************
1096* Saved state *
1097*********************************************************************************************************************************/
1098
1099/**
1100 * @callback_method_impl{FNSSMDEVLOADEXEC}
1101 *
1102 * @note: This is included to accept and migrate VMs that had used the original VirtualBox legacy-only virtio-net (network card)
1103 * controller device emulator ("DevVirtioNet.cpp") to work with this superset of VirtIO compatibility known
1104 * as a transitional device (see PDM-invoked device constructor comments for more information)
1105 */
1106static DECLCALLBACK(int) virtioNetR3LegacyDeviceLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass,
1107 RTMAC uMacLoaded)
1108{
1109 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
1110 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
1111 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
1112 int rc;
1113
1114 Log7Func(("[%s] LOAD EXEC (LEGACY)!!\n", pThis->szInst));
1115
1116 if ( memcmp(&uMacLoaded.au8, &pThis->macConfigured.au8, sizeof(uMacLoaded))
1117 && ( uPass == 0
1118 || !PDMDevHlpVMTeleportedAndNotFullyResumedYet(pDevIns)))
1119 LogRelFunc(("[%s]: The mac address differs: config=%RTmac saved=%RTmac\n",
1120 pThis->szInst, &pThis->macConfigured, &uMacLoaded));
1121
1122 if (uPass == SSM_PASS_FINAL)
1123 {
1124 /* Call the virtio core to have it load legacy device state */
1125 rc = virtioCoreR3LegacyDeviceLoadExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM, uVersion, VIRTIONET_SAVEDSTATE_VERSION_3_1_BETA1_LEGACY);
1126 AssertRCReturn(rc, rc);
1127 /*
1128 * Scan constructor-determined virtqs to determine if they are all valid-as-restored.
1129 * If so, nudge them with a signal, otherwise destroy the unusable queue(s)
1130 * to avoid tripping up the other queue processing logic.
1131 */
1132 int cVirtqsToRemove = 0;
1133 for (int uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
1134 {
1135 PVIRTIONETVIRTQ pVirtq = &pThis->aVirtqs[uVirtqNbr];
1136 if (pVirtq->fHasWorker)
1137 {
1138 if (!virtioCoreR3VirtqIsEnabled(&pThis->Virtio, uVirtqNbr))
1139 {
1140 virtioNetR3VirtqDestroy(&pThis->Virtio, pVirtq);
1141 ++cVirtqsToRemove;
1142 }
1143 else
1144 {
1145 if (virtioCoreR3VirtqIsAttached(&pThis->Virtio, uVirtqNbr))
1146 {
1147 Log7Func(("[%s] Waking %s worker.\n", pThis->szInst, pVirtq->szName));
1148 rc = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[pVirtq->uIdx].hEvtProcess);
1149 AssertRCReturn(rc, rc);
1150 }
1151 }
1152 }
1153 }
1154 AssertMsg(cVirtqsToRemove < 2, ("Multiple unusable queues in saved state unexpected\n"));
1155 pThis->cVirtqs -= cVirtqsToRemove;
1156
1157 pThis->virtioNetConfig.uStatus = pThis->Virtio.fDeviceStatus;
1158 pThis->fVirtioReady = pThis->Virtio.fDeviceStatus & VIRTIO_STATUS_DRIVER_OK;
1159
1160 rc = pHlp->pfnSSMGetMem(pSSM, pThis->virtioNetConfig.uMacAddress.au8, sizeof(pThis->virtioNetConfig.uMacAddress));
1161 AssertRCReturn(rc, rc);
1162
1163 if (uVersion > VIRTIONET_SAVEDSTATE_VERSION_3_1_BETA1_LEGACY)
1164 {
1165 /* Zero-out the the Unicast/Multicast filter table */
1166 memset(&pThis->aMacUnicastFilter[0], 0, VIRTIONET_MAC_FILTER_LEN * sizeof(RTMAC));
1167
1168 rc = pHlp->pfnSSMGetU8( pSSM, &pThis->fPromiscuous);
1169 AssertRCReturn(rc, rc);
1170 rc = pHlp->pfnSSMGetU8( pSSM, &pThis->fAllMulticast);
1171 AssertRCReturn(rc, rc);
1172 /*
1173 * The 0.95 legacy virtio spec defines a control queue command VIRTIO_NET_CTRL_MAC_TABLE_SET,
1174 * wherein guest driver configures two variable length mac filter tables: A unicast filter,
1175 * and a multicast filter. However original VBox virtio-net saved both sets of filter entries
1176 * in a single table, abandoning the distinction between unicast and multicast filters. It preserved
1177 * only *one* filter's table length, leaving no way to separate table back out into respective unicast
1178 * and multicast tables this device implementation preserves. Deduced from legacy code, the original
1179 * assumption was that the both MAC filters are whitelists that can be processed identically
1180 * (from the standpoint of a *single* host receiver), such that the distinction between unicast and
1181 * multicast doesn't matter in any one VM's context. Little choice here but to save the undifferentiated
1182 * unicast & multicast MACs to the unicast filter table and leave multicast table empty/unused.
1183 */
1184 uint32_t cCombinedUnicastMulticastEntries;
1185 rc = pHlp->pfnSSMGetU32(pSSM, &cCombinedUnicastMulticastEntries);
1186 AssertRCReturn(rc, rc);
1187 AssertReturn(cCombinedUnicastMulticastEntries <= VIRTIONET_MAC_FILTER_LEN, VERR_OUT_OF_RANGE);
1188 pThis->cUnicastFilterMacs = cCombinedUnicastMulticastEntries;
1189 rc = pHlp->pfnSSMGetMem(pSSM, pThis->aMacUnicastFilter, cCombinedUnicastMulticastEntries * sizeof(RTMAC));
1190 AssertRCReturn(rc, rc);
1191 rc = pHlp->pfnSSMGetMem(pSSM, pThis->aVlanFilter, sizeof(pThis->aVlanFilter));
1192 AssertRCReturn(rc, rc);
1193 }
1194 else
1195 {
1196 pThis->fAllMulticast = false;
1197 pThis->cUnicastFilterMacs = 0;
1198 memset(&pThis->aMacUnicastFilter, 0, VIRTIONET_MAC_FILTER_LEN * sizeof(RTMAC));
1199
1200 memset(pThis->aVlanFilter, 0, sizeof(pThis->aVlanFilter));
1201
1202 pThis->fPromiscuous = true;
1203 if (pThisCC->pDrv)
1204 pThisCC->pDrv->pfnSetPromiscuousMode(pThisCC->pDrv, true);
1205 }
1206
1207 /*
1208 * Log the restored VirtIO feature selection.
1209 */
1210 pThis->fNegotiatedFeatures = virtioCoreGetNegotiatedFeatures(&pThis->Virtio);
1211 /** @todo shouldn't we update the virtio header size here? it depends on the negotiated features. */
1212 virtioCorePrintDeviceFeatures(&pThis->Virtio, NULL, s_aDevSpecificFeatures, RT_ELEMENTS(s_aDevSpecificFeatures));
1213
1214 /*
1215 * Configure remaining transitional device parameters presumably or deductively
1216 * as these weren't part of the legacy device code thus it didn't save them to SSM
1217 */
1218 pThis->fCableConnected = 1;
1219 pThis->fAllUnicast = 0;
1220 pThis->fNoMulticast = 0;
1221 pThis->fNoUnicast = 0;
1222 pThis->fNoBroadcast = 0;
1223
1224 /* Zero out the multicast table and count, all MAC filters, if any, are in the unicast filter table */
1225 pThis->cMulticastFilterMacs = 0;
1226 memset(&pThis->aMacMulticastFilter, 0, VIRTIONET_MAC_FILTER_LEN * sizeof(RTMAC));
1227 }
1228 return VINF_SUCCESS;
1229}
1230
1231/**
1232 * @callback_method_impl{FNSSMDEVLOADEXEC}
1233 *
1234 * @note: This loads state saved by a Modern (VirtIO 1.0+) device, of which this transitional device is one,
1235 * and thus supports both legacy and modern guest virtio drivers.
1236 */
1237static DECLCALLBACK(int) virtioNetR3ModernDeviceLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1238{
1239 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
1240 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
1241 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
1242 int rc;
1243
1244 RT_NOREF(pThisCC);
1245
1246 RTMAC uMacLoaded, uVersionMarkerMac = { VIRTIONET_VERSION_MARKER_MAC_ADDR };
1247 rc = pHlp->pfnSSMGetMem(pSSM, &uMacLoaded.au8, sizeof(uMacLoaded.au8));
1248 AssertRCReturn(rc, rc);
1249 if (memcmp(&uMacLoaded.au8, uVersionMarkerMac.au8, sizeof(uVersionMarkerMac.au8)))
1250 {
1251 rc = virtioNetR3LegacyDeviceLoadExec(pDevIns, pSSM, uVersion, uPass, uMacLoaded);
1252 return rc;
1253 }
1254
1255 Log7Func(("[%s] LOAD EXEC!!\n", pThis->szInst));
1256
1257 AssertReturn(uPass == SSM_PASS_FINAL, VERR_SSM_UNEXPECTED_PASS);
1258 AssertLogRelMsgReturn(uVersion == VIRTIONET_SAVEDSTATE_VERSION,
1259 ("uVersion=%u\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
1260
1261 virtioNetR3SetVirtqNames(pThis, false /* fLegacy */);
1262
1263 pHlp->pfnSSMGetU64( pSSM, &pThis->fNegotiatedFeatures);
1264
1265 pHlp->pfnSSMGetU16( pSSM, &pThis->cVirtqs);
1266 AssertReturn(pThis->cVirtqs <= (VIRTIONET_MAX_QPAIRS * 2) + 1, VERR_OUT_OF_RANGE);
1267 pHlp->pfnSSMGetU16( pSSM, &pThis->cWorkers);
1268 AssertReturn(pThis->cWorkers <= VIRTIONET_MAX_WORKERS , VERR_OUT_OF_RANGE);
1269
1270 for (int uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
1271 pHlp->pfnSSMGetBool(pSSM, &pThis->aVirtqs[uVirtqNbr].fAttachedToVirtioCore);
1272
1273 /* Config checks */
1274 RTMAC macConfigured;
1275 rc = pHlp->pfnSSMGetMem(pSSM, &macConfigured.au8, sizeof(macConfigured.au8));
1276 AssertRCReturn(rc, rc);
1277 if (memcmp(&macConfigured.au8, &pThis->macConfigured.au8, sizeof(macConfigured.au8))
1278 && (uPass == 0 || !PDMDevHlpVMTeleportedAndNotFullyResumedYet(pDevIns)))
1279 LogRel(("%s: The mac address differs: config=%RTmac saved=%RTmac\n",
1280 pThis->szInst, &pThis->macConfigured, &macConfigured));
1281 memcpy(pThis->virtioNetConfig.uMacAddress.au8, macConfigured.au8, sizeof(macConfigured.au8));
1282
1283#if FEATURE_OFFERED(STATUS)
1284 uint16_t fChkStatus;
1285 pHlp->pfnSSMGetU16( pSSM, &fChkStatus);
1286 if (fChkStatus == 0xffff)
1287 {
1288 /* Dummy value in saved state because status feature wasn't enabled at the time */
1289 pThis->virtioNetConfig.uStatus = 0; /* VIRTIO_NET_S_ANNOUNCE disabled */
1290 pThis->virtioNetConfig.uStatus = !!IS_LINK_UP(pThis); /* VIRTIO_NET_IS_LINK_UP (bit 0) */
1291 }
1292 else
1293 pThis->virtioNetConfig.uStatus = fChkStatus;
1294#else
1295 uint16_t fDiscard;
1296 pHlp->pfnSSMGetU16( pSSM, &fDiscard);
1297#endif
1298
1299#if FEATURE_OFFERED(MQ)
1300 uint16_t uCheckMaxVirtqPairs;
1301 pHlp->pfnSSMGetU16( pSSM, &uCheckMaxVirtqPairs);
1302 if (uCheckMaxVirtqPairs)
1303 pThis->virtioNetConfig.uMaxVirtqPairs = uCheckMaxVirtqPairs;
1304 else
1305 pThis->virtioNetConfig.uMaxVirtqPairs = VIRTIONET_CTRL_MQ_VQ_PAIRS;
1306#else
1307 uint16_t fDiscard;
1308 pHlp->pfnSSMGetU16( pSSM, &fDiscard);
1309#endif
1310
1311 /* Save device-specific part */
1312 pHlp->pfnSSMGetBool( pSSM, &pThis->fCableConnected);
1313 pHlp->pfnSSMGetU8( pSSM, &pThis->fPromiscuous);
1314 pHlp->pfnSSMGetU8( pSSM, &pThis->fAllMulticast);
1315 pHlp->pfnSSMGetU8( pSSM, &pThis->fAllUnicast);
1316 pHlp->pfnSSMGetU8( pSSM, &pThis->fNoMulticast);
1317 pHlp->pfnSSMGetU8( pSSM, &pThis->fNoUnicast);
1318 pHlp->pfnSSMGetU8( pSSM, &pThis->fNoBroadcast);
1319
1320 pHlp->pfnSSMGetU32( pSSM, &pThis->cMulticastFilterMacs);
1321 AssertReturn(pThis->cMulticastFilterMacs <= VIRTIONET_MAC_FILTER_LEN, VERR_OUT_OF_RANGE);
1322 pHlp->pfnSSMGetMem( pSSM, pThis->aMacMulticastFilter, pThis->cMulticastFilterMacs * sizeof(RTMAC));
1323
1324 if (pThis->cMulticastFilterMacs < VIRTIONET_MAC_FILTER_LEN)
1325 memset(&pThis->aMacMulticastFilter[pThis->cMulticastFilterMacs], 0,
1326 (VIRTIONET_MAC_FILTER_LEN - pThis->cMulticastFilterMacs) * sizeof(RTMAC));
1327
1328 pHlp->pfnSSMGetU32( pSSM, &pThis->cUnicastFilterMacs);
1329 AssertReturn(pThis->cUnicastFilterMacs <= VIRTIONET_MAC_FILTER_LEN, VERR_OUT_OF_RANGE);
1330 pHlp->pfnSSMGetMem( pSSM, pThis->aMacUnicastFilter, pThis->cUnicastFilterMacs * sizeof(RTMAC));
1331
1332 if (pThis->cUnicastFilterMacs < VIRTIONET_MAC_FILTER_LEN)
1333 memset(&pThis->aMacUnicastFilter[pThis->cUnicastFilterMacs], 0,
1334 (VIRTIONET_MAC_FILTER_LEN - pThis->cUnicastFilterMacs) * sizeof(RTMAC));
1335
1336 rc = pHlp->pfnSSMGetMem(pSSM, pThis->aVlanFilter, sizeof(pThis->aVlanFilter));
1337 AssertRCReturn(rc, rc);
1338 /*
1339 * Call the virtio core to let it load its state.
1340 */
1341 rc = virtioCoreR3ModernDeviceLoadExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM, uVersion,
1342 VIRTIONET_SAVEDSTATE_VERSION, pThis->cVirtqs);
1343 AssertRCReturn(rc, rc);
1344 /*
1345 * Since the control queue is created proactively in the constructor to accomodate worst-case
1346 * legacy guests, even though the queue may have been deducted from queue count while saving state,
1347 * we must explicitly remove queue and associated worker thread and context at this point,
1348 * or presence of bogus control queue will confuse operations.
1349 */
1350 PVIRTIONETVIRTQ pVirtq = &pThis->aVirtqs[CTRLQIDX];
1351 if (FEATURE_DISABLED(CTRL_VQ) || !virtioCoreIsVirtqEnabled(&pThis->Virtio, CTRLQIDX))
1352 {
1353 virtioCoreR3VirtqDetach(&pThis->Virtio, CTRLQIDX);
1354 virtioNetR3VirtqDestroy(&pThis->Virtio, pVirtq);
1355 pVirtq->fAttachedToVirtioCore = false;
1356 --pThis->cWorkers;
1357 }
1358 /*
1359 * Nudge queue workers
1360 */
1361 for (int uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
1362 {
1363 pVirtq = &pThis->aVirtqs[uVirtqNbr];
1364 if (pVirtq->fAttachedToVirtioCore)
1365 {
1366 if (pVirtq->fHasWorker)
1367 {
1368 PVIRTIONETWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
1369 Log7Func(("[%s] Waking %s worker.\n", pThis->szInst, pVirtq->szName));
1370 rc = PDMDevHlpSUPSemEventSignal(pDevIns, pWorker->hEvtProcess);
1371 AssertRCReturn(rc, rc);
1372 }
1373 }
1374 }
1375 pThis->virtioNetConfig.uStatus = pThis->Virtio.fDeviceStatus; /* reflects state to guest driver */
1376 pThis->fVirtioReady = pThis->Virtio.fDeviceStatus & VIRTIO_STATUS_DRIVER_OK;
1377
1378 return rc;
1379}
1380
1381/**
1382 * @callback_method_impl{FNSSMDEVSAVEEXEC}
1383 */
1384static DECLCALLBACK(int) virtioNetR3ModernSaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
1385{
1386 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
1387 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
1388 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
1389
1390 RT_NOREF(pThisCC);
1391 Log7Func(("[%s] SAVE EXEC!!\n", pThis->szInst));
1392
1393 /* Store a dummy MAC address that would never be actually assigned to a NIC
1394 * so that when load exec handler is called it can be easily determined
1395 * whether saved state is modern or legacy. This works because original
1396 * legacy code stored assigned NIC address as the first item of SSM state
1397 */
1398 RTMAC uVersionMarkerMac = { VIRTIONET_VERSION_MARKER_MAC_ADDR };
1399 pHlp->pfnSSMPutMem(pSSM, &uVersionMarkerMac.au8, sizeof(uVersionMarkerMac.au8));
1400
1401 pHlp->pfnSSMPutU64( pSSM, pThis->fNegotiatedFeatures);
1402
1403 pHlp->pfnSSMPutU16( pSSM, pThis->cVirtqs);
1404 pHlp->pfnSSMPutU16( pSSM, pThis->cWorkers);
1405
1406 for (int uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
1407 pHlp->pfnSSMPutBool(pSSM, pThis->aVirtqs[uVirtqNbr].fAttachedToVirtioCore);
1408 /*
1409
1410 * Save device config area (accessed via MMIO)
1411 */
1412 pHlp->pfnSSMPutMem( pSSM, pThis->virtioNetConfig.uMacAddress.au8,
1413 sizeof(pThis->virtioNetConfig.uMacAddress.au8));
1414#if FEATURE_OFFERED(STATUS)
1415 pHlp->pfnSSMPutU16( pSSM, pThis->virtioNetConfig.uStatus);
1416#else
1417 /*
1418 * Relevant values are lower bits. Forcing this to 0xffff let's loadExec know this
1419 * feature was not enabled in saved state. VirtIO 1.0, 5.1.4
1420 */
1421 pHlp->pfnSSMPutU16( pSSM, 0xffff);
1422
1423#endif
1424#if FEATURE_OFFERED(MQ)
1425 pHlp->pfnSSMPutU16( pSSM, pThis->virtioNetConfig.uMaxVirtqPairs);
1426#else
1427 /*
1428 * Legal values for max_virtqueue_pairs are 0x1 -> 0x8000 *. Forcing zero let's loadExec know this
1429 * feature was not enabled in saved state. VirtIO 1.0, 5.1.4.1
1430 */
1431 pHlp->pfnSSMPutU16( pSSM, 0);
1432#endif
1433
1434 /* Save device-specific part */
1435 pHlp->pfnSSMPutBool( pSSM, pThis->fCableConnected);
1436 pHlp->pfnSSMPutU8( pSSM, pThis->fPromiscuous);
1437 pHlp->pfnSSMPutU8( pSSM, pThis->fAllMulticast);
1438 pHlp->pfnSSMPutU8( pSSM, pThis->fAllUnicast);
1439 pHlp->pfnSSMPutU8( pSSM, pThis->fNoMulticast);
1440 pHlp->pfnSSMPutU8( pSSM, pThis->fNoUnicast);
1441 pHlp->pfnSSMPutU8( pSSM, pThis->fNoBroadcast);
1442
1443 pHlp->pfnSSMPutU32( pSSM, pThis->cMulticastFilterMacs);
1444 pHlp->pfnSSMPutMem( pSSM, pThis->aMacMulticastFilter, pThis->cMulticastFilterMacs * sizeof(RTMAC));
1445
1446 pHlp->pfnSSMPutU32( pSSM, pThis->cUnicastFilterMacs);
1447 pHlp->pfnSSMPutMem( pSSM, pThis->aMacUnicastFilter, pThis->cUnicastFilterMacs * sizeof(RTMAC));
1448
1449 int rc = pHlp->pfnSSMPutMem(pSSM, pThis->aVlanFilter, sizeof(pThis->aVlanFilter));
1450 AssertRCReturn(rc, rc);
1451
1452 /*
1453 * Call the virtio core to let it save its state.
1454 */
1455 return virtioCoreR3SaveExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM, VIRTIONET_SAVEDSTATE_VERSION, pThis->cVirtqs);
1456}
1457
1458
1459/*********************************************************************************************************************************
1460* Device interface. *
1461*********************************************************************************************************************************/
1462
1463#ifdef IN_RING3
1464
1465/**
1466 * Perform 16-bit 1's compliment checksum on provided packet in accordance with VirtIO specification,
1467 * pertinent to VIRTIO_NET_F_CSUM feature, which 'offloads' the Checksum feature from the driver
1468 * to save processor cycles, which is ironic in our case, where the controller device ('network card')
1469 * is emulated on the virtualization host.
1470 *
1471 * @note See VirtIO 1.0 spec, 5.1.6.2 Packet Transmission
1472 *
1473 * @param pBuf Pointer to r/w buffer with any portion to calculate checksum for
1474 * @param cbSize Number of bytes to checksum
1475 * @param uStart Where to start the checksum within the buffer
1476 * @param uOffset Offset past uStart point in the buffer to store checksum result
1477 *
1478 */
1479DECLINLINE(void) virtioNetR3Calc16BitChecksum(uint8_t *pBuf, size_t cb, uint16_t uStart, uint16_t uOffset)
1480{
1481 AssertReturnVoid(uStart < cb);
1482 AssertReturnVoid(uStart + uOffset + sizeof(uint16_t) <= cb);
1483
1484 uint32_t chksum = 0;
1485 uint16_t *pu = (uint16_t *)(pBuf + uStart);
1486
1487 cb -= uStart;
1488 while (cb > 1)
1489 {
1490 chksum += *pu++;
1491 cb -= 2;
1492 }
1493 if (cb)
1494 chksum += *(uint8_t *)pu;
1495 while (chksum >> 16)
1496 chksum = (chksum >> 16) + (chksum & 0xFFFF);
1497
1498 /* Store 1's compliment of calculated sum */
1499 *(uint16_t *)(pBuf + uStart + uOffset) = ~chksum;
1500}
1501
1502/**
1503 * Turns on/off the read status LED.
1504 *
1505 * @returns VBox status code.
1506 * @param pThis Pointer to the device state structure.
1507 * @param fOn New LED state.
1508 */
1509void virtioNetR3SetReadLed(PVIRTIONETR3 pThisR3, bool fOn)
1510{
1511 if (fOn)
1512 pThisR3->led.Asserted.s.fReading = pThisR3->led.Actual.s.fReading = 1;
1513 else
1514 pThisR3->led.Actual.s.fReading = fOn;
1515}
1516
1517/**
1518 * Turns on/off the write status LED.
1519 *
1520 * @returns VBox status code.
1521 * @param pThis Pointer to the device state structure.
1522 * @param fOn New LED state.
1523 */
1524void virtioNetR3SetWriteLed(PVIRTIONETR3 pThisR3, bool fOn)
1525{
1526 if (fOn)
1527 pThisR3->led.Asserted.s.fWriting = pThisR3->led.Actual.s.fWriting = 1;
1528 else
1529 pThisR3->led.Actual.s.fWriting = fOn;
1530}
1531
1532/**
1533 * Check that the core is setup and ready and co-configured with guest virtio driver,
1534 * and verifies that the VM is running.
1535 *
1536 * @returns true if VirtIO core and device are in a running and operational state
1537 */
1538DECLINLINE(bool) virtioNetIsOperational(PVIRTIONET pThis, PPDMDEVINS pDevIns)
1539{
1540 if (RT_LIKELY(pThis->fVirtioReady))
1541 {
1542 VMSTATE enmVMState = PDMDevHlpVMState(pDevIns);
1543 if (RT_LIKELY(enmVMState == VMSTATE_RUNNING || enmVMState == VMSTATE_RUNNING_LS))
1544 return true;
1545 }
1546 return false;
1547}
1548
1549/**
1550 * Check whether specific queue is ready and has Rx buffers (virtqueue descriptors)
1551 * available. This must be called before the pfnRecieve() method is called.
1552 *
1553 * @remarks As a side effect this function enables queue notification
1554 * if it cannot receive because the queue is empty.
1555 * It disables notification if it can receive.
1556 *
1557 * @returns VERR_NET_NO_BUFFER_SPACE if it cannot.
1558 * @thread RX
1559 */
1560static int virtioNetR3CheckRxBufsAvail(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETVIRTQ pRxVirtq)
1561{
1562 int rc = VERR_INVALID_STATE;
1563 Log8Func(("[%s] ", pThis->szInst));
1564 if (!virtioNetIsOperational(pThis, pDevIns))
1565 Log8(("No Rx bufs available. (VirtIO core not ready)\n"));
1566
1567 else if (!virtioCoreIsVirtqEnabled(&pThis->Virtio, pRxVirtq->uIdx))
1568 Log8(("[No Rx bufs available. (%s not enabled)\n", pRxVirtq->szName));
1569
1570 else if (IS_VIRTQ_EMPTY(pDevIns, &pThis->Virtio, pRxVirtq->uIdx))
1571 Log8(("No Rx bufs available. (%s empty)\n", pRxVirtq->szName));
1572
1573 else
1574 {
1575 Log8(("%s has %d empty guest bufs in avail ring\n", pRxVirtq->szName,
1576 virtioCoreVirtqAvailBufCount(pDevIns, &pThis->Virtio, pRxVirtq->uIdx)));
1577 rc = VINF_SUCCESS;
1578 }
1579 virtioCoreVirtqEnableNotify(&pThis->Virtio, pRxVirtq->uIdx, rc == VERR_INVALID_STATE /* fEnable */);
1580 return rc;
1581}
1582
1583/**
1584 * Find an Rx queue that has Rx packets in it, if *any* do.
1585 *
1586 * @todo When multiqueue (MQ) mode is fully supported and tested, some kind of round-robin
1587 * or randomization scheme should probably be incorporated here.
1588 *
1589 * @returns true if Rx pkts avail on queue and sets pRxVirtq to point to queue w/pkts found
1590 * @thread RX
1591 *
1592 */
1593static bool virtioNetR3AreRxBufsAvail(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETVIRTQ *pRxVirtq)
1594{
1595 for (int uVirtqPair = 0; uVirtqPair < pThis->cVirtqPairs; uVirtqPair++)
1596 {
1597 PVIRTIONETVIRTQ pThisRxVirtq = &pThis->aVirtqs[RXQIDX(uVirtqPair)];
1598 if (RT_SUCCESS(virtioNetR3CheckRxBufsAvail(pDevIns, pThis, pThisRxVirtq)))
1599 {
1600 if (pRxVirtq)
1601 *pRxVirtq = pThisRxVirtq;
1602 return true;
1603 }
1604 }
1605 return false;
1606}
1607
1608/**
1609 * @interface_method_impl{PDMINETWORKDOWN,pfnWaitReceiveAvail}
1610 */
1611static DECLCALLBACK(int) virtioNetR3NetworkDown_WaitReceiveAvail(PPDMINETWORKDOWN pInterface, RTMSINTERVAL timeoutMs)
1612{
1613 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, INetworkDown);
1614 PPDMDEVINS pDevIns = pThisCC->pDevIns;
1615 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
1616
1617 if (!virtioNetIsOperational(pThis, pDevIns))
1618 return VERR_INTERRUPTED;
1619
1620 if (virtioNetR3AreRxBufsAvail(pDevIns, pThis, NULL /* pRxVirtq */))
1621 {
1622 Log10Func(("[%s] Rx bufs available, releasing waiter...\n", pThis->szInst));
1623 return VINF_SUCCESS;
1624 }
1625 if (!timeoutMs)
1626 return VERR_NET_NO_BUFFER_SPACE;
1627
1628 LogFunc(("[%s] %s\n", pThis->szInst, timeoutMs == RT_INDEFINITE_WAIT ? "<indefinite wait>" : ""));
1629
1630 ASMAtomicXchgBool(&pThis->fLeafWantsEmptyRxBufs, true);
1631 STAM_PROFILE_START(&pThis->StatRxOverflow, a);
1632
1633 do {
1634 if (virtioNetR3AreRxBufsAvail(pDevIns, pThis, NULL /* pRxVirtq */))
1635 {
1636 Log10Func(("[%s] Rx bufs now available, releasing waiter...\n", pThis->szInst));
1637 ASMAtomicXchgBool(&pThis->fLeafWantsEmptyRxBufs, false);
1638 return VINF_SUCCESS;
1639 }
1640 Log9Func(("[%s] Starved for empty guest Rx bufs. Waiting...\n", pThis->szInst));
1641
1642 int rc = PDMDevHlpSUPSemEventWaitNoResume(pDevIns, pThis->hEventRxDescAvail, timeoutMs);
1643
1644 if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED)
1645 {
1646 LogFunc(("Woken due to %s\n", rc == VERR_TIMEOUT ? "timeout" : "getting interrupted"));
1647
1648 if (!virtioNetIsOperational(pThis, pDevIns))
1649 break;
1650
1651 continue;
1652 }
1653 if (RT_FAILURE(rc)) {
1654 LogFunc(("Waken due to failure %Rrc\n", rc));
1655 RTThreadSleep(1);
1656 }
1657 } while (virtioNetIsOperational(pThis, pDevIns));
1658
1659 STAM_PROFILE_STOP(&pThis->StatRxOverflow, a);
1660 ASMAtomicXchgBool(&pThis->fLeafWantsEmptyRxBufs, false);
1661
1662 Log7Func(("[%s] Wait for Rx buffers available was interrupted\n", pThis->szInst));
1663 return VERR_INTERRUPTED;
1664}
1665
1666/**
1667 * Sets up the GSO context according to the Virtio header.
1668 *
1669 * @param pGso The GSO context to setup.
1670 * @param pCtx The context descriptor.
1671 */
1672DECLINLINE(PPDMNETWORKGSO) virtioNetR3SetupGsoCtx(PPDMNETWORKGSO pGso, VIRTIONETPKTHDR const *pPktHdr)
1673{
1674 pGso->u8Type = PDMNETWORKGSOTYPE_INVALID;
1675
1676 if (pPktHdr->uGsoType & VIRTIONET_HDR_GSO_ECN)
1677 {
1678 AssertMsgFailed(("Unsupported flag in virtio header: ECN\n"));
1679 return NULL;
1680 }
1681 switch (pPktHdr->uGsoType & ~VIRTIONET_HDR_GSO_ECN)
1682 {
1683 case VIRTIONET_HDR_GSO_TCPV4:
1684 pGso->u8Type = PDMNETWORKGSOTYPE_IPV4_TCP;
1685 pGso->cbHdrsSeg = pPktHdr->uHdrLen;
1686 break;
1687 case VIRTIONET_HDR_GSO_TCPV6:
1688 pGso->u8Type = PDMNETWORKGSOTYPE_IPV6_TCP;
1689 pGso->cbHdrsSeg = pPktHdr->uHdrLen;
1690 break;
1691 case VIRTIONET_HDR_GSO_UDP:
1692 pGso->u8Type = PDMNETWORKGSOTYPE_IPV4_UDP;
1693 pGso->cbHdrsSeg = pPktHdr->uChksumStart;
1694 break;
1695 default:
1696 return NULL;
1697 }
1698 if (pPktHdr->uFlags & VIRTIONET_HDR_F_NEEDS_CSUM)
1699 pGso->offHdr2 = pPktHdr->uChksumStart;
1700 else
1701 {
1702 AssertMsgFailed(("GSO without checksum offloading!\n"));
1703 return NULL;
1704 }
1705 pGso->offHdr1 = sizeof(RTNETETHERHDR);
1706 pGso->cbHdrsTotal = pPktHdr->uHdrLen;
1707 pGso->cbMaxSeg = pPktHdr->uGsoSize;
1708 /* Mark GSO frames with zero MSS as PDMNETWORKGSOTYPE_INVALID, so they will be ignored by send. */
1709 if (pPktHdr->uGsoType != VIRTIONET_HDR_GSO_NONE && pPktHdr->uGsoSize == 0)
1710 pGso->u8Type = PDMNETWORKGSOTYPE_INVALID;
1711 return pGso;
1712}
1713
1714/**
1715 * @interface_method_impl{PDMINETWORKCONFIG,pfnGetMac}
1716 */
1717static DECLCALLBACK(int) virtioNetR3NetworkConfig_GetMac(PPDMINETWORKCONFIG pInterface, PRTMAC pMac)
1718{
1719 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, INetworkConfig);
1720 PVIRTIONET pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVIRTIONET);
1721 memcpy(pMac, pThis->virtioNetConfig.uMacAddress.au8, sizeof(RTMAC));
1722 return VINF_SUCCESS;
1723}
1724
1725/**
1726 * Returns true if it is a broadcast packet.
1727 *
1728 * @returns true if destination address indicates broadcast.
1729 * @param pvBuf The ethernet packet.
1730 */
1731DECLINLINE(bool) virtioNetR3IsBroadcast(const void *pvBuf)
1732{
1733 static const uint8_t s_abBcastAddr[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
1734 return memcmp(pvBuf, s_abBcastAddr, sizeof(s_abBcastAddr)) == 0;
1735}
1736
1737/**
1738 * Returns true if it is a multicast packet.
1739 *
1740 * @remarks returns true for broadcast packets as well.
1741 * @returns true if destination address indicates multicast.
1742 * @param pvBuf The ethernet packet.
1743 */
1744DECLINLINE(bool) virtioNetR3IsMulticast(const void *pvBuf)
1745{
1746 return (*(char*)pvBuf) & 1;
1747}
1748
1749/**
1750 * Determines if the packet is to be delivered to upper layer.
1751 *
1752 * @returns true if packet is intended for this node.
1753 * @param pThis Pointer to the state structure.
1754 * @param pvBuf The ethernet packet.
1755 * @param cb Number of bytes available in the packet.
1756 */
1757static bool virtioNetR3AddressFilter(PVIRTIONET pThis, const void *pvBuf, size_t cb)
1758{
1759
1760RT_NOREF(cb);
1761
1762#ifdef LOG_ENABLED
1763 if (LogIs11Enabled())
1764 {
1765 char *pszType;
1766 if (virtioNetR3IsMulticast(pvBuf))
1767 pszType = (char *)"mcast";
1768 else if (virtioNetR3IsBroadcast(pvBuf))
1769 pszType = (char *)"bcast";
1770 else
1771 pszType = (char *)"ucast";
1772
1773 LogFunc(("node(%RTmac%s%s), pkt(%RTmac, %s) ",
1774 pThis->virtioNetConfig.uMacAddress.au8,
1775 pThis->fPromiscuous ? " promisc" : "",
1776 pThis->fAllMulticast ? " all-mcast" : "",
1777 pvBuf, pszType));
1778 }
1779#endif
1780
1781 if (pThis->fPromiscuous) {
1782 Log11(("\n"));
1783 return true;
1784 }
1785
1786 /* Ignore everything outside of our VLANs */
1787 uint16_t *uPtr = (uint16_t *)pvBuf;
1788
1789 /* Compare TPID with VLAN Ether Type */
1790 if ( uPtr[6] == RT_H2BE_U16(0x8100)
1791 && !ASMBitTest(pThis->aVlanFilter, RT_BE2H_U16(uPtr[7]) & 0xFFF))
1792 {
1793 Log11Func(("\n[%s] not our VLAN, returning false\n", pThis->szInst));
1794 return false;
1795 }
1796
1797 if (virtioNetR3IsBroadcast(pvBuf))
1798 {
1799 Log11(("acpt (bcast)\n"));
1800#ifdef LOG_ENABLED
1801 if (LogIs12Enabled())
1802 virtioNetR3PacketDump(pThis, (const uint8_t *)pvBuf, cb, "<-- Incoming");
1803#endif
1804 return true;
1805 }
1806 if (pThis->fAllMulticast && virtioNetR3IsMulticast(pvBuf))
1807 {
1808 Log11(("acpt (all-mcast)\n"));
1809#ifdef LOG_ENABLED
1810 if (LogIs12Enabled())
1811 virtioNetR3PacketDump(pThis, (const uint8_t *)pvBuf, cb, "<-- Incoming");
1812#endif
1813 return true;
1814 }
1815
1816 if (!memcmp(pThis->virtioNetConfig.uMacAddress.au8, pvBuf, sizeof(RTMAC)))
1817 {
1818 Log11(("acpt (to-node)\n"));
1819#ifdef LOG_ENABLED
1820 if (LogIs12Enabled())
1821 virtioNetR3PacketDump(pThis, (const uint8_t *)pvBuf, cb, "<-- Incoming");
1822#endif
1823 return true;
1824 }
1825
1826 for (uint16_t i = 0; i < pThis->cMulticastFilterMacs; i++)
1827 {
1828 if (!memcmp(&pThis->aMacMulticastFilter[i], pvBuf, sizeof(RTMAC)))
1829 {
1830 Log11(("acpt (mcast whitelist)\n"));
1831#ifdef LOG_ENABLED
1832 if (LogIs12Enabled())
1833 virtioNetR3PacketDump(pThis, (const uint8_t *)pvBuf, cb, "<-- Incoming");
1834#endif
1835 return true;
1836 }
1837 }
1838
1839 for (uint16_t i = 0; i < pThis->cUnicastFilterMacs; i++)
1840 if (!memcmp(&pThis->aMacUnicastFilter[i], pvBuf, sizeof(RTMAC)))
1841 {
1842 Log11(("acpt (ucast whitelist)\n"));
1843 return true;
1844 }
1845#ifdef LOG_ENABLED
1846 if (LogIs11Enabled())
1847 Log(("... reject\n"));
1848#endif
1849
1850 return false;
1851}
1852
1853
1854/**
1855 * This handles the case where Rx packet must be transfered to guest driver via multiple buffers using
1856 * copy tactics slower than preferred method using a single virtq buf. Yet this is an available option
1857 * for guests. Although cited in the spec it's to accomodate guest that perhaps have memory constraints
1858 * wherein guest may benefit from smaller buffers (see MRG_RXBUF feature), in practice it is seen
1859 * that without MRG_RXBUF the linux guest enqueues 'huge' multi-segment buffers so that the largest
1860 * conceivable Rx packet can be contained in a single buffer, where for most transactions most of that
1861 * memory will be unfilled, so it is typically both wasteful and *slower* to avoid MRG_RXBUF.
1862 *
1863 * As an optimization, this multi-buffer copy is only used when:
1864 *
1865 * A. Guest has negotiated MRG_RXBUF
1866 * B. Next packet in the Rx avail queue isn't big enough to contain Rx pkt hdr+data.
1867 *
1868 * Architecture is defined in VirtIO 1.1 5.1.6 (Device Operations), which has improved
1869 * wording over the VirtIO 1.0 specification, but, as an implementation note, there is one
1870 * ambiguity that needs clarification:
1871 *
1872 * The VirtIO 1.1, 5.1.6.4 explains something in a potentially misleading way. And note,
1873 * the VirtIO spec makes a document-wide assertion that the distinction between
1874 * "SHOULD" and "MUST" is to be taken quite literally.
1875 *
1876 * The confusion is that VirtIO 1.1, 5.1.6.3.1 essentially says guest driver "SHOULD" populate
1877 * Rx queue with buffers large enough to accomodate full pkt hdr + data. That's a grammatical
1878 * error (dangling participle).
1879 *
1880 * In practice we MUST assume "SHOULD" strictly applies to the word *populate*, -not- to buffer
1881 * size, because ultimately buffer minimum size is predicated on configuration parameters,
1882 * specifically, when MRG_RXBUF feature is disabled, the driver *MUST* provide Rx bufs
1883 * (if and when it can provide them), that are *large enough* to hold pkt hdr + payload.
1884 *
1885 * Therefore, proper interpretation of 5.1.6.3.1 is, the guest *should* (ideally) keep Rx virtq
1886 * populated with appropriately sized buffers to *prevent starvation* (i.e. starvation may be
1887 * unavoidable thus can't be prohibited). As it would be a ludicrous to presume 5.1.6.3.1 is
1888 * giving guests leeway to violate MRG_RXBUF feature buf size constraints.
1889 *
1890 * @param pDevIns PDM instance
1891 * @param pThis Device instance
1892 * @param pvBuf Pointer to incoming GSO Rx data from downstream device
1893 * @param cb Amount of data given
1894 * @param rxPktHdr Rx pkt Header that's been massaged into VirtIO semantics
1895 * @param pRxVirtq Pointer to Rx virtq
1896 * @param pVirtqBuf Initial virtq buffer to start copying Rx hdr/pkt to guest into
1897 *
1898 */
1899static int virtioNetR3RxPktMultibufXfer(PPDMDEVINS pDevIns, PVIRTIONET pThis, uint8_t *pvPktBuf, size_t cb,
1900 PVIRTIONETPKTHDR pRxPktHdr, PVIRTIONETVIRTQ pRxVirtq, PVIRTQBUF pVirtqBuf)
1901{
1902
1903 size_t cbBufRemaining = pVirtqBuf->cbPhysReturn;
1904 size_t cbPktHdr = pThis->cbPktHdr;
1905
1906 AssertMsgReturn(cbBufRemaining >= pThis->cbPktHdr,
1907 ("guest-provided Rx buf not large enough to store pkt hdr"), VERR_INTERNAL_ERROR);
1908
1909 Log7Func((" Sending packet header to guest...\n"));
1910
1911 /* Copy packet header to rx buf provided by caller. */
1912 size_t cbHdrEnqueued = pVirtqBuf->cbPhysReturn == cbPktHdr ? cbPktHdr : 0;
1913 virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, cbPktHdr, pRxPktHdr, pVirtqBuf, cbHdrEnqueued);
1914
1915 /* Cache address of uNumBuffers field of pkthdr to update ex post facto */
1916 RTGCPHYS GCPhysNumBuffers = pVirtqBuf->pSgPhysReturn->paSegs[0].GCPhys + RT_UOFFSETOF(VIRTIONETPKTHDR, uNumBuffers);
1917 uint16_t cVirtqBufsUsed = 0;
1918 cbBufRemaining -= cbPktHdr;
1919 /*
1920 * Copy packet to guest using as many buffers as necessary, tracking and handling whether
1921 * the buf containing the packet header was already written to the Rx queue's used buffer ring.
1922 */
1923 uint64_t uPktOffset = 0;
1924 while(uPktOffset < cb)
1925 {
1926 Log7Func((" Sending packet data (in buffer #%d) to guest...\n", cVirtqBufsUsed));
1927 size_t cbBounded = RT_MIN(cbBufRemaining, cb - uPktOffset);
1928 (void) virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, cbBounded,
1929 pvPktBuf + uPktOffset, pVirtqBuf, cbBounded + (cbPktHdr - cbHdrEnqueued) /* cbEnqueue */);
1930 ++cVirtqBufsUsed;
1931 cbBufRemaining -= cbBounded;
1932 uPktOffset += cbBounded;
1933 if (uPktOffset < cb)
1934 {
1935 cbHdrEnqueued = cbPktHdr;
1936#ifdef VIRTIO_VBUF_ON_STACK
1937 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, pVirtqBuf, true);
1938#else /* !VIRTIO_VBUF_ON_STACK */
1939 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
1940 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, &pVirtqBuf, true);
1941#endif /* !VIRTIO_VBUF_ON_STACK */
1942
1943 AssertMsgReturn(rc == VINF_SUCCESS || rc == VERR_NOT_AVAILABLE, ("%Rrc\n", rc), rc);
1944
1945#ifdef VIRTIO_VBUF_ON_STACK
1946 AssertMsgReturn(rc == VINF_SUCCESS && pVirtqBuf->cbPhysReturn,
1947 ("Not enough Rx buffers in queue to accomodate ethernet packet\n"),
1948 VERR_INTERNAL_ERROR);
1949#else /* !VIRTIO_VBUF_ON_STACK */
1950 AssertMsgReturnStmt(rc == VINF_SUCCESS && pVirtqBuf->cbPhysReturn,
1951 ("Not enough Rx buffers in queue to accomodate ethernet packet\n"),
1952 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf),
1953 VERR_INTERNAL_ERROR);
1954#endif /* !VIRTIO_VBUF_ON_STACK */
1955 cbBufRemaining = pVirtqBuf->cbPhysReturn;
1956 }
1957 }
1958
1959 /* Fix-up pkthdr (in guest phys. memory) with number of buffers (descriptors) that were processed */
1960 int rc = virtioCoreGCPhysWrite(&pThis->Virtio, pDevIns, GCPhysNumBuffers, &cVirtqBufsUsed, sizeof(cVirtqBufsUsed));
1961 AssertMsgRCReturn(rc, ("Failure updating descriptor count in pkt hdr in guest physical memory\n"), rc);
1962
1963#ifndef VIRTIO_VBUF_ON_STACK
1964 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
1965#endif /* !VIRTIO_VBUF_ON_STACK */
1966 virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, pRxVirtq->uIdx);
1967 Log7(("\n"));
1968 return rc;
1969}
1970
1971/**
1972 * Pad and store received packet.
1973 *
1974 * @remarks Make sure that the packet appears to upper layer as one coming
1975 * from real Ethernet: pad it and insert FCS.
1976 *
1977 * @returns VBox status code.
1978 * @param pDevIns The device instance.
1979 * @param pThis The virtio-net shared instance data.
1980 * @param pvBuf The available data.
1981 * @param cb Number of bytes available in the buffer.
1982 * @param pGso Pointer to Global Segmentation Offload structure
1983 * @param pRxVirtq Pointer to Rx virtqueue
1984 * @thread RX
1985 */
1986
1987static int virtioNetR3CopyRxPktToGuest(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETCC pThisCC, const void *pvBuf, size_t cb,
1988 PVIRTIONETPKTHDR pRxPktHdr, uint8_t cbPktHdr, PVIRTIONETVIRTQ pRxVirtq)
1989{
1990 RT_NOREF(pThisCC);
1991#ifdef VIRTIO_VBUF_ON_STACK
1992 VIRTQBUF_T VirtqBuf;
1993 PVIRTQBUF pVirtqBuf = &VirtqBuf;
1994 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, pVirtqBuf, true);
1995#else /* !VIRTIO_VBUF_ON_STACK */
1996 PVIRTQBUF pVirtqBuf;
1997 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, &pVirtqBuf, true);
1998#endif /* !VIRTIO_VBUF_ON_STACK */
1999
2000 AssertMsgReturn(rc == VINF_SUCCESS || rc == VERR_NOT_AVAILABLE, ("%Rrc\n", rc), rc);
2001
2002#ifdef VIRTIO_VBUF_ON_STACK
2003 AssertMsgReturn(rc == VINF_SUCCESS && pVirtqBuf->cbPhysReturn,
2004 ("Not enough Rx buffers or capacity to accommodate ethernet packet\n"),
2005 VERR_INTERNAL_ERROR);
2006#else /* !VIRTIO_VBUF_ON_STACK */
2007 AssertMsgReturnStmt(rc == VINF_SUCCESS && pVirtqBuf->cbPhysReturn,
2008 ("Not enough Rx buffers or capacity to accommodate ethernet packet\n"),
2009 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf),
2010 VERR_INTERNAL_ERROR);
2011#endif /* !VIRTIO_VBUF_ON_STACK */
2012 /*
2013 * Try to do fast (e.g. single-buffer) copy to guest, even if MRG_RXBUF feature is enabled
2014 */
2015 STAM_PROFILE_START(&pThis->StatReceiveStore, a);
2016 if (RT_LIKELY(FEATURE_DISABLED(MRG_RXBUF))
2017 || RT_LIKELY(pVirtqBuf->cbPhysReturn > cb + cbPktHdr))
2018 {
2019 Log7Func(("Send Rx packet header and data to guest (single-buffer copy)...\n"));
2020 pRxPktHdr->uNumBuffers = 1;
2021 rc = virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, cbPktHdr, pRxPktHdr, pVirtqBuf, 0 /* cbEnqueue */);
2022 if (rc == VINF_SUCCESS)
2023 rc = virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, pRxVirtq->uIdx, cb, pvBuf, pVirtqBuf, cbPktHdr + cb /* cbEnqueue */);
2024#ifndef VIRTIO_VBUF_ON_STACK
2025 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
2026#endif /* !VIRTIO_VBUF_ON_STACK */
2027 virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, pRxVirtq->uIdx);
2028 AssertMsgReturn(rc == VINF_SUCCESS, ("%Rrc\n", rc), rc);
2029 }
2030 else
2031 {
2032 Log7Func(("Send Rx pkt to guest (merged-buffer copy [MRG_RXBUF feature])...\n"));
2033 rc = virtioNetR3RxPktMultibufXfer(pDevIns, pThis, (uint8_t *)pvBuf, cb, pRxPktHdr, pRxVirtq, pVirtqBuf);
2034 return rc;
2035 }
2036 STAM_PROFILE_STOP(&pThis->StatReceiveStore, a);
2037 return VINF_SUCCESS;
2038}
2039
2040/**
2041 * @interface_method_impl{PDMINETWORKDOWN,pfnReceiveGso}
2042 */
2043static DECLCALLBACK(int) virtioNetR3NetworkDown_ReceiveGso(
2044 PPDMINETWORKDOWN pInterface, const void *pvBuf, size_t cb, PCPDMNETWORKGSO pGso)
2045{
2046 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, INetworkDown);
2047 PPDMDEVINS pDevIns = pThisCC->pDevIns;
2048 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
2049 VIRTIONETPKTHDR rxPktHdr = { 0, VIRTIONET_HDR_GSO_NONE, 0, 0, 0, 0, 0 };
2050
2051 if (!pThis->fVirtioReady)
2052 {
2053 LogRelFunc(("VirtIO not ready, aborting downstream receive\n"));
2054 return VERR_INTERRUPTED;
2055 }
2056 /*
2057 * If GSO (Global Segment Offloading) was received from downstream PDM network device, massage the
2058 * PDM-provided GSO parameters into VirtIO semantics, which get passed to guest virtio-net via
2059 * Rx pkt header. See VirtIO 1.1, 5.1.6 Device Operation for more information.
2060 */
2061 if (pGso)
2062 {
2063 LogFunc(("[%s] (%RTmac) \n", pThis->szInst, pvBuf));
2064
2065 rxPktHdr.uFlags = VIRTIONET_HDR_F_NEEDS_CSUM;
2066 rxPktHdr.uHdrLen = pGso->cbHdrsTotal;
2067 rxPktHdr.uGsoSize = pGso->cbMaxSeg;
2068 rxPktHdr.uChksumStart = pGso->offHdr2;
2069
2070 switch (pGso->u8Type)
2071 {
2072 case PDMNETWORKGSOTYPE_IPV4_TCP:
2073 rxPktHdr.uGsoType = VIRTIONET_HDR_GSO_TCPV4;
2074 rxPktHdr.uChksumOffset = RT_OFFSETOF(RTNETTCP, th_sum);
2075 break;
2076 case PDMNETWORKGSOTYPE_IPV6_TCP:
2077 rxPktHdr.uGsoType = VIRTIONET_HDR_GSO_TCPV6;
2078 rxPktHdr.uChksumOffset = RT_OFFSETOF(RTNETTCP, th_sum);
2079 break;
2080 case PDMNETWORKGSOTYPE_IPV4_UDP:
2081 rxPktHdr.uGsoType = VIRTIONET_HDR_GSO_UDP;
2082 rxPktHdr.uChksumOffset = RT_OFFSETOF(RTNETUDP, uh_sum);
2083 break;
2084 default:
2085 LogFunc(("[%s] GSO type (0x%x) not supported\n", pThis->szInst, pGso->u8Type));
2086 return VERR_NOT_SUPPORTED;
2087 }
2088 STAM_REL_COUNTER_INC(&pThis->StatReceiveGSO);
2089 Log2Func(("[%s] gso type=%#x, cbHdrsTotal=%u cbHdrsSeg=%u mss=%u offHdr1=%#x offHdr2=%#x\n",
2090 pThis->szInst, pGso->u8Type, pGso->cbHdrsTotal, pGso->cbHdrsSeg,
2091 pGso->cbMaxSeg, pGso->offHdr1, pGso->offHdr2));
2092 }
2093
2094 /*
2095 * Find a virtq with Rx bufs on avail ring, if any, and copy the packet to the guest's Rx buffer.
2096 * @todo pk: PROBABLY NOT A SOPHISTICATED ENOUGH QUEUE SELECTION ALGORTITH FOR OPTIMAL MQ (FEATURE) SUPPORT
2097 */
2098 for (int uVirtqPair = 0; uVirtqPair < pThis->cVirtqPairs; uVirtqPair++)
2099 {
2100 PVIRTIONETVIRTQ pRxVirtq = &pThis->aVirtqs[RXQIDX(uVirtqPair)];
2101 if (RT_SUCCESS(virtioNetR3CheckRxBufsAvail(pDevIns, pThis, pRxVirtq)))
2102 {
2103 int rc = VINF_SUCCESS;
2104 STAM_PROFILE_START(&pThis->StatReceive, a);
2105 virtioNetR3SetReadLed(pThisCC, true);
2106 if (virtioNetR3AddressFilter(pThis, pvBuf, cb))
2107 {
2108 /* rxPktHdr is local stack variable that should not go out of scope in this use */
2109 rc = virtioNetR3CopyRxPktToGuest(pDevIns, pThis, pThisCC, pvBuf, cb, &rxPktHdr, pThis->cbPktHdr, pRxVirtq);
2110 STAM_REL_COUNTER_ADD(&pThis->StatReceiveBytes, cb);
2111 }
2112 virtioNetR3SetReadLed(pThisCC, false);
2113 STAM_PROFILE_STOP(&pThis->StatReceive, a);
2114 return rc;
2115 }
2116 }
2117 return VERR_INTERRUPTED;
2118}
2119
2120/**
2121 * @interface_method_impl{PDMINETWORKDOWN,pfnReceive}
2122 */
2123static DECLCALLBACK(int) virtioNetR3NetworkDown_Receive(PPDMINETWORKDOWN pInterface, const void *pvBuf, size_t cb)
2124{
2125
2126#ifdef LOG_ENABLED
2127 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, INetworkDown);
2128 PPDMDEVINS pDevIns = pThisCC->pDevIns;
2129 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
2130 LogFunc(("[%s] (%RTmac)\n", pThis->szInst, pvBuf));
2131#endif
2132
2133 return virtioNetR3NetworkDown_ReceiveGso(pInterface, pvBuf, cb, NULL);
2134}
2135
2136/*
2137 * Dispatched to here from virtioNetR3Ctrl() to configure this virtio-net device's Rx packet receive filtering.
2138 * See VirtIO 1.0, 5.1.6.5.1
2139 *
2140 * @param pThis virtio-net instance
2141 * @param pCtrlPktHdr Control packet header (which includes command parameters)
2142 * @param pVirtqBuf Buffer from ctrlq buffer (contains command data)
2143 */
2144static uint8_t virtioNetR3CtrlRx(PVIRTIONET pThis, PVIRTIONETCC pThisCC,
2145 PVIRTIONET_CTRL_HDR_T pCtrlPktHdr, PVIRTQBUF pVirtqBuf)
2146{
2147
2148#define LOG_VIRTIONET_FLAG(fld) LogFunc(("[%s] Setting %s=%d\n", pThis->szInst, #fld, pThis->fld))
2149
2150 LogFunc(("[%s] Processing CTRL Rx command\n", pThis->szInst));
2151 switch(pCtrlPktHdr->uCmd)
2152 {
2153 case VIRTIONET_CTRL_RX_PROMISC:
2154 break;
2155 case VIRTIONET_CTRL_RX_ALLMULTI:
2156 break;
2157 case VIRTIONET_CTRL_RX_ALLUNI:
2158 /* fallthrough */
2159 case VIRTIONET_CTRL_RX_NOMULTI:
2160 /* fallthrough */
2161 case VIRTIONET_CTRL_RX_NOUNI:
2162 /* fallthrough */
2163 case VIRTIONET_CTRL_RX_NOBCAST:
2164 AssertMsgReturn(FEATURE_ENABLED(CTRL_RX_EXTRA),
2165 ("CTRL 'extra' cmd w/o VIRTIONET_F_CTRL_RX_EXTRA feature negotiated - skipping\n"),
2166 VIRTIONET_ERROR);
2167 /* fall out */
2168 }
2169
2170 uint8_t fOn, fPromiscChanged = false;
2171 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &fOn, (size_t)RT_MIN(pVirtqBuf->cbPhysSend, sizeof(fOn)));
2172
2173 switch(pCtrlPktHdr->uCmd)
2174 {
2175 case VIRTIONET_CTRL_RX_PROMISC:
2176 pThis->fPromiscuous = RT_BOOL(fOn);
2177 fPromiscChanged = true;
2178 LOG_VIRTIONET_FLAG(fPromiscuous);
2179 break;
2180 case VIRTIONET_CTRL_RX_ALLMULTI:
2181 pThis->fAllMulticast = RT_BOOL(fOn);
2182 fPromiscChanged = true;
2183 LOG_VIRTIONET_FLAG(fAllMulticast);
2184 break;
2185 case VIRTIONET_CTRL_RX_ALLUNI:
2186 pThis->fAllUnicast = RT_BOOL(fOn);
2187 LOG_VIRTIONET_FLAG(fAllUnicast);
2188 break;
2189 case VIRTIONET_CTRL_RX_NOMULTI:
2190 pThis->fNoMulticast = RT_BOOL(fOn);
2191 LOG_VIRTIONET_FLAG(fNoMulticast);
2192 break;
2193 case VIRTIONET_CTRL_RX_NOUNI:
2194 pThis->fNoUnicast = RT_BOOL(fOn);
2195 LOG_VIRTIONET_FLAG(fNoUnicast);
2196 break;
2197 case VIRTIONET_CTRL_RX_NOBCAST:
2198 pThis->fNoBroadcast = RT_BOOL(fOn);
2199 LOG_VIRTIONET_FLAG(fNoBroadcast);
2200 break;
2201 }
2202
2203 if (pThisCC->pDrv && fPromiscChanged)
2204 pThisCC->pDrv->pfnSetPromiscuousMode(pThisCC->pDrv, (pThis->fPromiscuous || pThis->fAllMulticast));
2205
2206 return VIRTIONET_OK;
2207}
2208
2209/*
2210 * Dispatched to here from virtioNetR3Ctrl() to configure this virtio-net device's MAC filter tables
2211 * See VirtIO 1.0, 5.1.6.5.2
2212 *
2213 * @param pThis virtio-net instance
2214 * @param pCtrlPktHdr Control packet header (which includes command parameters)
2215 * @param pVirtqBuf Buffer from ctrlq buffer (contains command data)
2216 */
2217static uint8_t virtioNetR3CtrlMac(PVIRTIONET pThis, PVIRTIONET_CTRL_HDR_T pCtrlPktHdr, PVIRTQBUF pVirtqBuf)
2218{
2219 LogFunc(("[%s] Processing CTRL MAC command\n", pThis->szInst));
2220
2221
2222 AssertMsgReturn(pVirtqBuf->cbPhysSend >= sizeof(*pCtrlPktHdr),
2223 ("insufficient descriptor space for ctrl pkt hdr"),
2224 VIRTIONET_ERROR);
2225
2226 size_t cbRemaining = pVirtqBuf->cbPhysSend;
2227 switch(pCtrlPktHdr->uCmd)
2228 {
2229 case VIRTIONET_CTRL_MAC_ADDR_SET:
2230 {
2231 /* Set default Rx filter MAC */
2232 AssertMsgReturn(cbRemaining >= sizeof(pThis->rxFilterMacDefault),
2233 ("DESC chain too small to process CTRL_MAC_ADDR_SET cmd\n"), VIRTIONET_ERROR);
2234
2235 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &pThis->rxFilterMacDefault, sizeof(RTMAC));
2236 break;
2237 }
2238 case VIRTIONET_CTRL_MAC_TABLE_SET:
2239 {
2240 VIRTIONET_CTRL_MAC_TABLE_LEN cMacs;
2241
2242 /* Load unicast MAC filter table */
2243 AssertMsgReturn(cbRemaining >= sizeof(cMacs),
2244 ("DESC chain too small to process CTRL_MAC_TABLE_SET cmd\n"), VIRTIONET_ERROR);
2245
2246 /* Fetch count of unicast filter MACs from guest buffer */
2247 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &cMacs, sizeof(cMacs));
2248 cbRemaining -= sizeof(cMacs);
2249
2250 Log7Func(("[%s] Guest provided %d unicast MAC Table entries\n", pThis->szInst, cMacs));
2251
2252 if (cMacs)
2253 {
2254 uint32_t cbMacs = cMacs * sizeof(RTMAC);
2255
2256 AssertMsgReturn(cbMacs <= sizeof(pThis->aMacUnicastFilter) / sizeof(RTMAC),
2257 ("Guest provided Unicast MAC filter table exceeds hardcoded table size"), VIRTIONET_ERROR);
2258
2259 AssertMsgReturn(cbRemaining >= cbMacs,
2260 ("Virtq buffer too small to process CTRL_MAC_TABLE_SET cmd\n"), VIRTIONET_ERROR);
2261
2262
2263 /* Fetch unicast table contents from guest buffer */
2264 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &pThis->aMacUnicastFilter, cbMacs);
2265 cbRemaining -= cbMacs;
2266 }
2267 pThis->cUnicastFilterMacs = cMacs;
2268
2269 /* Load multicast MAC filter table */
2270 AssertMsgReturn(cbRemaining >= sizeof(cMacs),
2271 ("Virtq buffer too small to process CTRL_MAC_TABLE_SET cmd\n"), VIRTIONET_ERROR);
2272
2273 /* Fetch count of multicast filter MACs from guest buffer */
2274 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &cMacs, sizeof(cMacs));
2275 cbRemaining -= sizeof(cMacs);
2276
2277 Log10Func(("[%s] Guest provided %d multicast MAC Table entries\n", pThis->szInst, cMacs));
2278
2279 if (cMacs)
2280 {
2281 uint32_t cbMacs = cMacs * sizeof(RTMAC);
2282
2283 AssertMsgReturn(cbMacs <= sizeof(pThis->aMacMulticastFilter) / sizeof(RTMAC),
2284 ("Guest provided Unicast MAC filter table exceeds hardcoded table size"), VIRTIONET_ERROR);
2285
2286 AssertMsgReturn(cbRemaining >= cbMacs,
2287 ("Virtq buffer too small to process CTRL_MAC_TABLE_SET cmd\n"), VIRTIONET_ERROR);
2288
2289 /* Fetch multicast table contents from guest buffer */
2290 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &pThis->aMacMulticastFilter, cbMacs);
2291 cbRemaining -= cbMacs;
2292 }
2293 pThis->cMulticastFilterMacs = cMacs;
2294
2295#ifdef LOG_ENABLED
2296 LogFunc(("[%s] unicast MACs:\n", pThis->szInst));
2297 for(unsigned i = 0; i < pThis->cUnicastFilterMacs; i++)
2298 LogFunc((" %RTmac\n", &pThis->aMacUnicastFilter[i]));
2299
2300 LogFunc(("[%s] multicast MACs:\n", pThis->szInst));
2301 for(unsigned i = 0; i < pThis->cMulticastFilterMacs; i++)
2302 LogFunc((" %RTmac\n", &pThis->aMacMulticastFilter[i]));
2303#endif
2304 break;
2305 }
2306 default:
2307 LogRelFunc(("Unrecognized MAC subcommand in CTRL pkt from guest\n"));
2308 return VIRTIONET_ERROR;
2309 }
2310 return VIRTIONET_OK;
2311}
2312
2313/*
2314 * Dispatched to here from virtioNetR3Ctrl() to configure this virtio-net device's MQ (multiqueue) operations.
2315 * See VirtIO 1.0, 5.1.6.5.5
2316 *
2317 * @param pThis virtio-net instance
2318 * @param pCtrlPktHdr Control packet header (which includes command parameters)
2319 * @param pVirtqBuf Buffer from ctrlq buffer (contains command data)
2320 */
2321static uint8_t virtioNetR3CtrlMultiQueue(PVIRTIONET pThis, PVIRTIONETCC pThisCC, PPDMDEVINS pDevIns, PVIRTIONET_CTRL_HDR_T pCtrlPktHdr, PVIRTQBUF pVirtqBuf)
2322{
2323 LogFunc(("[%s] Processing CTRL MQ command\n", pThis->szInst));
2324
2325 uint16_t cVirtqPairs;
2326 switch(pCtrlPktHdr->uCmd)
2327 {
2328 case VIRTIONET_CTRL_MQ_VQ_PAIRS_SET:
2329 {
2330 size_t cbRemaining = pVirtqBuf->cbPhysSend - sizeof(*pCtrlPktHdr);
2331
2332 AssertMsgReturn(cbRemaining > sizeof(cVirtqPairs),
2333 ("DESC chain too small for VIRTIONET_CTRL_MQ cmd processing"), VIRTIONET_ERROR);
2334
2335 /* Fetch number of virtq pairs from guest buffer */
2336 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &cVirtqPairs, sizeof(cVirtqPairs));
2337
2338 AssertMsgReturn(cVirtqPairs > VIRTIONET_MAX_QPAIRS,
2339 ("[%s] Guest CTRL MQ virtq pair count out of range [%d])\n", pThis->szInst, cVirtqPairs), VIRTIONET_ERROR);
2340
2341 LogFunc(("[%s] Guest specifies %d VQ pairs in use\n", pThis->szInst, cVirtqPairs));
2342 pThis->cVirtqPairs = cVirtqPairs;
2343 break;
2344 }
2345 default:
2346 LogRelFunc(("Unrecognized multiqueue subcommand in CTRL pkt from guest\n"));
2347 return VIRTIONET_ERROR;
2348 }
2349
2350 /*
2351 * The MQ control function is invoked by the guest in an RPC like manner to change
2352 * the Rx/Tx queue pair count. If the new value exceeds the number of queues
2353 * (and associated workers) already initialized initialize only the new queues and
2354 * respective workers.
2355 */
2356 if (pThis->cVirtqPairs > pThis->cInitializedVirtqPairs)
2357 {
2358 virtioNetR3SetVirtqNames(pThis, virtioCoreIsLegacyMode(&pThis->Virtio));
2359 int rc = virtioNetR3CreateWorkerThreads(pDevIns, pThis, pThisCC);
2360 if (RT_FAILURE(rc))
2361 {
2362 LogRelFunc(("Failed to create worker threads\n"));
2363 return VIRTIONET_ERROR;
2364 }
2365 }
2366 return VIRTIONET_OK;
2367}
2368
2369/*
2370 * Dispatched to here from virtioNetR3Ctrl() to configure this virtio-net device's VLAN filtering.
2371 * See VirtIO 1.0, 5.1.6.5.3
2372 *
2373 * @param pThis virtio-net instance
2374 * @param pCtrlPktHdr Control packet header (which includes command parameters)
2375 * @param pVirtqBuf Buffer from ctrlq buffer (contains command data)
2376 */
2377static uint8_t virtioNetR3CtrlVlan(PVIRTIONET pThis, PVIRTIONET_CTRL_HDR_T pCtrlPktHdr, PVIRTQBUF pVirtqBuf)
2378{
2379 LogFunc(("[%s] Processing CTRL VLAN command\n", pThis->szInst));
2380
2381 uint16_t uVlanId;
2382 size_t cbRemaining = pVirtqBuf->cbPhysSend - sizeof(*pCtrlPktHdr);
2383
2384 AssertMsgReturn(cbRemaining > sizeof(uVlanId),
2385 ("DESC chain too small for VIRTIONET_CTRL_VLAN cmd processing"), VIRTIONET_ERROR);
2386
2387 /* Fetch VLAN ID from guest buffer */
2388 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, &uVlanId, sizeof(uVlanId));
2389
2390 AssertMsgReturn(uVlanId > VIRTIONET_MAX_VLAN_ID,
2391 ("%s VLAN ID out of range (VLAN ID=%u)\n", pThis->szInst, uVlanId), VIRTIONET_ERROR);
2392
2393 LogFunc(("[%s] uCommand=%u VLAN ID=%u\n", pThis->szInst, pCtrlPktHdr->uCmd, uVlanId));
2394
2395 switch (pCtrlPktHdr->uCmd)
2396 {
2397 case VIRTIONET_CTRL_VLAN_ADD:
2398 ASMBitSet(pThis->aVlanFilter, uVlanId);
2399 break;
2400 case VIRTIONET_CTRL_VLAN_DEL:
2401 ASMBitClear(pThis->aVlanFilter, uVlanId);
2402 break;
2403 default:
2404 LogRelFunc(("Unrecognized VLAN subcommand in CTRL pkt from guest\n"));
2405 return VIRTIONET_ERROR;
2406 }
2407 return VIRTIONET_OK;
2408}
2409
2410/**
2411 * Processes control command from guest.
2412 * See VirtIO 1.0 spec, 5.1.6 "Device Operation" and 5.1.6.5 "Control Virtqueue".
2413 *
2414 * The control command is contained in a virtio buffer pulled from the virtio-net defined control queue (ctrlq).
2415 * Command type is parsed is dispatched to a command-specific device-configuration handler function (e.g. RX, MAC, VLAN, MQ
2416 * and ANNOUNCE).
2417 *
2418 * This function handles all parts of the host-side of the ctrlq round-trip buffer processing.
2419 *
2420 * Invoked by worker for virtio-net control queue to process a queued control command buffer.
2421 *
2422 * @param pDevIns PDM device instance
2423 * @param pThis virtio-net device instance
2424 * @param pThisCC virtio-net device instance
2425 * @param pVirtqBuf pointer to buffer pulled from virtq (input to this function)
2426 */
2427static void virtioNetR3Ctrl(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETCC pThisCC,
2428 PVIRTQBUF pVirtqBuf)
2429{
2430 if (!(pThis->fNegotiatedFeatures & VIRTIONET_F_CTRL_VQ))
2431 LogFunc(("[%s] WARNING: Guest using CTRL queue w/o negotiating VIRTIONET_F_CTRL_VQ feature\n", pThis->szInst));
2432
2433 LogFunc(("[%s] Received CTRL packet from guest\n", pThis->szInst));
2434
2435 if (pVirtqBuf->cbPhysSend < 2)
2436 {
2437 LogFunc(("[%s] CTRL packet from guest driver incomplete. Skipping ctrl cmd\n", pThis->szInst));
2438 return;
2439 }
2440 else if (pVirtqBuf->cbPhysReturn < sizeof(VIRTIONET_CTRL_HDR_T_ACK))
2441 {
2442 LogFunc(("[%s] Guest driver didn't allocate memory to receive ctrl pkt ACK. Skipping ctrl cmd\n", pThis->szInst));
2443 return;
2444 }
2445
2446 /*
2447 * Allocate buffer and read in the control command
2448 */
2449 PVIRTIONET_CTRL_HDR_T pCtrlPktHdr = (PVIRTIONET_CTRL_HDR_T)RTMemAllocZ(sizeof(VIRTIONET_CTRL_HDR_T));
2450
2451 AssertPtrReturnVoid(pCtrlPktHdr);
2452
2453 AssertMsgReturnVoid(pVirtqBuf->cbPhysSend >= sizeof(VIRTIONET_CTRL_HDR_T),
2454 ("DESC chain too small for CTRL pkt header"));
2455
2456 virtioCoreR3VirtqBufDrain(&pThis->Virtio, pVirtqBuf, pCtrlPktHdr,
2457 RT_MIN(pVirtqBuf->cbPhysSend, sizeof(VIRTIONET_CTRL_HDR_T)));
2458
2459 Log7Func(("[%s] CTRL COMMAND: class=%d command=%d\n", pThis->szInst, pCtrlPktHdr->uClass, pCtrlPktHdr->uCmd));
2460
2461 uint8_t uAck;
2462 switch (pCtrlPktHdr->uClass)
2463 {
2464 case VIRTIONET_CTRL_RX:
2465 uAck = virtioNetR3CtrlRx(pThis, pThisCC, pCtrlPktHdr, pVirtqBuf);
2466 break;
2467 case VIRTIONET_CTRL_MAC:
2468 uAck = virtioNetR3CtrlMac(pThis, pCtrlPktHdr, pVirtqBuf);
2469 break;
2470 case VIRTIONET_CTRL_VLAN:
2471 uAck = virtioNetR3CtrlVlan(pThis, pCtrlPktHdr, pVirtqBuf);
2472 break;
2473 case VIRTIONET_CTRL_MQ:
2474 uAck = virtioNetR3CtrlMultiQueue(pThis, pThisCC, pDevIns, pCtrlPktHdr, pVirtqBuf);
2475 break;
2476 case VIRTIONET_CTRL_ANNOUNCE:
2477 uAck = VIRTIONET_OK;
2478 if (FEATURE_DISABLED(STATUS) || FEATURE_DISABLED(GUEST_ANNOUNCE))
2479 {
2480 LogFunc(("%s Ignoring CTRL class VIRTIONET_CTRL_ANNOUNCE.\n"
2481 "VIRTIO_F_STATUS or VIRTIO_F_GUEST_ANNOUNCE feature not enabled\n", pThis->szInst));
2482 break;
2483 }
2484 if (pCtrlPktHdr->uCmd != VIRTIONET_CTRL_ANNOUNCE_ACK)
2485 {
2486 LogFunc(("[%s] Ignoring CTRL class VIRTIONET_CTRL_ANNOUNCE. Unrecognized uCmd\n", pThis->szInst));
2487 break;
2488 }
2489#if FEATURE_OFFERED(STATUS)
2490 pThis->virtioNetConfig.uStatus &= ~VIRTIONET_F_ANNOUNCE;
2491#endif
2492 Log7Func(("[%s] Clearing VIRTIONET_F_ANNOUNCE in config status\n", pThis->szInst));
2493 break;
2494 default:
2495 LogRelFunc(("Unrecognized CTRL pkt hdr class (%d)\n", pCtrlPktHdr->uClass));
2496 uAck = VIRTIONET_ERROR;
2497 }
2498
2499 /* Currently CTRL pkt header just returns ack, but keeping segment logic generic/flexible
2500 * in case that changes to make adapting more straightforward
2501 */
2502 int cSegs = 1;
2503
2504 /* Return CTRL packet Ack byte (result code) to guest driver */
2505 PRTSGSEG paReturnSegs = (PRTSGSEG)RTMemAllocZ(sizeof(RTSGSEG));
2506 AssertMsgReturnVoid(paReturnSegs, ("Out of memory"));
2507
2508 RTSGSEG aStaticSegs[] = { { &uAck, sizeof(uAck) } };
2509 memcpy(paReturnSegs, aStaticSegs, sizeof(RTSGSEG));
2510
2511 PRTSGBUF pReturnSegBuf = (PRTSGBUF)RTMemAllocZ(sizeof(RTSGBUF));
2512 AssertMsgReturnVoid(pReturnSegBuf, ("Out of memory"));
2513
2514 /* Copy segment data to malloc'd memory to avoid stack out-of-scope errors sanitizer doesn't detect */
2515 for (int i = 0; i < cSegs; i++)
2516 {
2517 void *pv = paReturnSegs[i].pvSeg;
2518 paReturnSegs[i].pvSeg = RTMemAlloc(aStaticSegs[i].cbSeg);
2519 AssertMsgReturnVoid(paReturnSegs[i].pvSeg, ("Out of memory"));
2520 memcpy(paReturnSegs[i].pvSeg, pv, aStaticSegs[i].cbSeg);
2521 }
2522
2523 RTSgBufInit(pReturnSegBuf, paReturnSegs, cSegs);
2524
2525 virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, CTRLQIDX, pReturnSegBuf, pVirtqBuf, true /* fFence */);
2526 virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, CTRLQIDX);
2527
2528 for (int i = 0; i < cSegs; i++)
2529 RTMemFree(paReturnSegs[i].pvSeg);
2530
2531 RTMemFree(paReturnSegs);
2532 RTMemFree(pReturnSegBuf);
2533
2534 LogFunc(("%s Finished processing CTRL command with status %s\n",
2535 pThis->szInst, uAck == VIRTIONET_OK ? "VIRTIONET_OK" : "VIRTIONET_ERROR"));
2536}
2537
2538/**
2539 * Reads virtio-net pkt header from provided Phy. addr of virtio descriptor chain
2540 * (e.g. S/G segment from guest-driver provided buffer pulled from Tx virtq)
2541 * Verifies state and supported modes, sets TCP header size.
2542 *
2543 * @param pVirtio VirtIO core instance data
2544 * @param pThis virtio-net instance
2545 * @param pDevIns PDM device instance
2546 * @param GCPhys Phys. Address from where to read virtio-net pkt header
2547 * @param pPktHdr Where to store read Tx pkt hdr (virtio pkt hdr size is determined from instance configuration)
2548 * @param cbFrame Total pkt frame size to inform bounds check
2549 */
2550static int virtioNetR3ReadVirtioTxPktHdr(PVIRTIOCORE pVirtio, PVIRTIONET pThis, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, PVIRTIONETPKTHDR pPktHdr, size_t cbFrame)
2551{
2552 int rc = virtioCoreGCPhysRead(pVirtio, pDevIns, GCPhys, pPktHdr, pThis->cbPktHdr);
2553 if (RT_FAILURE(rc))
2554 return rc;
2555
2556 LogFunc(("pktHdr (flags=%x gso-type=%x len=%x gso-size=%x Chksum-start=%x Chksum-offset=%x) cbFrame=%d\n",
2557 pPktHdr->uFlags, pPktHdr->uGsoType, pPktHdr->uHdrLen,
2558 pPktHdr->uGsoSize, pPktHdr->uChksumStart, pPktHdr->uChksumOffset, cbFrame));
2559
2560 if (pPktHdr->uGsoType)
2561 {
2562 /* Segmentation offloading cannot be done without checksumming, and we do not support ECN */
2563 AssertMsgReturn( RT_LIKELY(pPktHdr->uFlags & VIRTIONET_HDR_F_NEEDS_CSUM)
2564 && !(RT_UNLIKELY(pPktHdr->uGsoType & VIRTIONET_HDR_GSO_ECN)),
2565 ("Unsupported ECN request in pkt header\n"), VERR_NOT_SUPPORTED);
2566
2567 uint32_t uTcpHdrSize;
2568 switch (pPktHdr->uGsoType)
2569 {
2570 case VIRTIONET_HDR_GSO_TCPV4:
2571 case VIRTIONET_HDR_GSO_TCPV6:
2572 uTcpHdrSize = sizeof(RTNETTCP);
2573 break;
2574 case VIRTIONET_HDR_GSO_UDP:
2575 uTcpHdrSize = 0;
2576 break;
2577 default:
2578 LogFunc(("Bad GSO type in packet header\n"));
2579 return VERR_INVALID_PARAMETER;
2580 }
2581 /* Header + MSS must not exceed the packet size. */
2582 AssertMsgReturn(RT_LIKELY(uTcpHdrSize + pPktHdr->uChksumStart + pPktHdr->uGsoSize <= cbFrame),
2583 ("Header plus message exceeds packet size"), VERR_BUFFER_OVERFLOW);
2584 }
2585
2586 AssertMsgReturn( !(pPktHdr->uFlags & VIRTIONET_HDR_F_NEEDS_CSUM)
2587 || sizeof(uint16_t) + pPktHdr->uChksumStart + pPktHdr->uChksumOffset <= cbFrame,
2588 ("Checksum (%d bytes) doesn't fit into pkt header (%d bytes)\n",
2589 sizeof(uint16_t) + pPktHdr->uChksumStart + pPktHdr->uChksumOffset, cbFrame),
2590 VERR_BUFFER_OVERFLOW);
2591
2592 return VINF_SUCCESS;
2593}
2594
2595/**
2596 * Transmits single GSO frame via PDM framework to downstream PDM device, to emit from virtual NIC.
2597 *
2598 * This does final prep of GSO parameters including checksum calculation if configured
2599 * (e.g. if VIRTIONET_HDR_F_NEEDS_CSUM flag is set).
2600 *
2601 * @param pThis virtio-net instance
2602 * @param pThisCC virtio-net instance
2603 * @param pSgBuf PDM S/G buffer containing pkt and hdr to transmit
2604 * @param pGso GSO parameters used for the packet
2605 * @param pPktHdr virtio-net pkt header to adapt to PDM semantics
2606 */
2607static int virtioNetR3TransmitFrame(PVIRTIONET pThis, PVIRTIONETCC pThisCC, PPDMSCATTERGATHER pSgBuf,
2608 PPDMNETWORKGSO pGso, PVIRTIONETPKTHDR pPktHdr)
2609{
2610
2611 virtioNetR3PacketDump(pThis, (uint8_t *)pSgBuf->aSegs[0].pvSeg, pSgBuf->cbUsed, "--> Outgoing");
2612 if (pGso)
2613 {
2614 /* Some guests (RHEL) may report HdrLen excluding transport layer header!
2615 * Thus cannot use cdHdrs provided by the guest because of different ways
2616 * it gets filled out by different versions of kernels. */
2617 Log4Func(("%s HdrLen before adjustment %d.\n", pThis->szInst, pGso->cbHdrsTotal));
2618 switch (pGso->u8Type)
2619 {
2620 case PDMNETWORKGSOTYPE_IPV4_TCP:
2621 case PDMNETWORKGSOTYPE_IPV6_TCP:
2622 pGso->cbHdrsTotal = pPktHdr->uChksumStart +
2623 ((PRTNETTCP)(((uint8_t*)pSgBuf->aSegs[0].pvSeg) + pPktHdr->uChksumStart))->th_off * 4;
2624 AssertMsgReturn(pSgBuf->cbUsed > pGso->cbHdrsTotal,
2625 ("cbHdrsTotal exceeds size of frame"), VERR_BUFFER_OVERFLOW);
2626 pGso->cbHdrsSeg = pGso->cbHdrsTotal;
2627 break;
2628 case PDMNETWORKGSOTYPE_IPV4_UDP:
2629 pGso->cbHdrsTotal = (uint8_t)(pPktHdr->uChksumStart + sizeof(RTNETUDP));
2630 pGso->cbHdrsSeg = pPktHdr->uChksumStart;
2631 break;
2632 case PDMNETWORKGSOTYPE_INVALID:
2633 LogFunc(("%s ignoring invalid GSO frame\n", pThis->szInst));
2634 return VERR_INVALID_PARAMETER;
2635 }
2636 /* Update GSO structure embedded into the frame */
2637 ((PPDMNETWORKGSO)pSgBuf->pvUser)->cbHdrsTotal = pGso->cbHdrsTotal;
2638 ((PPDMNETWORKGSO)pSgBuf->pvUser)->cbHdrsSeg = pGso->cbHdrsSeg;
2639 Log4Func(("%s adjusted HdrLen to %d.\n",
2640 pThis->szInst, pGso->cbHdrsTotal));
2641 Log2Func(("%s gso type=%x cbHdrsTotal=%u cbHdrsSeg=%u mss=%u off1=0x%x off2=0x%x\n",
2642 pThis->szInst, pGso->u8Type, pGso->cbHdrsTotal, pGso->cbHdrsSeg,
2643 pGso->cbMaxSeg, pGso->offHdr1, pGso->offHdr2));
2644 STAM_REL_COUNTER_INC(&pThis->StatTransmitGSO);
2645 }
2646 else if (pPktHdr->uFlags & VIRTIONET_HDR_F_NEEDS_CSUM)
2647 {
2648 STAM_REL_COUNTER_INC(&pThis->StatTransmitCSum);
2649 /*
2650 * This is not GSO frame but checksum offloading is requested.
2651 */
2652 virtioNetR3Calc16BitChecksum((uint8_t*)pSgBuf->aSegs[0].pvSeg, pSgBuf->cbUsed,
2653 pPktHdr->uChksumStart, pPktHdr->uChksumOffset);
2654 }
2655
2656 return pThisCC->pDrv->pfnSendBuf(pThisCC->pDrv, pSgBuf, true /* fOnWorkerThread */);
2657}
2658
2659/**
2660 * Non-reentrant function transmits all available packets from specified Tx virtq to downstream
2661 * PDM device (if cable is connected). For each Tx pkt, virtio-net pkt header is converted
2662 * to required GSO information (VBox host network stack semantics)
2663 *
2664 * @param pDevIns PDM device instance
2665 * @param pThis virtio-net device instance
2666 * @param pThisCC virtio-net device instance
2667 * @param pTxVirtq Address of transmit virtq
2668 * @param fOnWorkerThread Flag to PDM whether to use caller's or or PDM transmit worker's thread.
2669 */
2670static int virtioNetR3TransmitPkts(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETCC pThisCC,
2671 PVIRTIONETVIRTQ pTxVirtq, bool fOnWorkerThread)
2672{
2673 PVIRTIOCORE pVirtio = &pThis->Virtio;
2674
2675
2676 if (!pThis->fVirtioReady)
2677 {
2678 LogFunc(("%s Ignoring Tx requests. VirtIO not ready (status=0x%x)\n",
2679 pThis->szInst, pThis->virtioNetConfig.uStatus));
2680 return VERR_IGNORED;
2681 }
2682
2683 if (!pThis->fCableConnected)
2684 {
2685 Log(("[%s] Ignoring transmit requests while cable is disconnected.\n", pThis->szInst));
2686 return VERR_IGNORED;
2687 }
2688
2689 /*
2690 * Only one thread is allowed to transmit at a time, others should skip transmission as the packets
2691 * will be picked up by the transmitting thread.
2692 */
2693 if (!ASMAtomicCmpXchgU32(&pThis->uIsTransmitting, 1, 0))
2694 return VERR_IGNORED;
2695
2696 PPDMINETWORKUP pDrv = pThisCC->pDrv;
2697 if (pDrv)
2698 {
2699 int rc = pDrv->pfnBeginXmit(pDrv, fOnWorkerThread);
2700 Assert(rc == VINF_SUCCESS || rc == VERR_TRY_AGAIN);
2701 if (rc == VERR_TRY_AGAIN)
2702 {
2703 ASMAtomicWriteU32(&pThis->uIsTransmitting, 0);
2704 return VERR_TRY_AGAIN;
2705 }
2706 }
2707 int cPkts = virtioCoreVirtqAvailBufCount(pVirtio->pDevInsR3, pVirtio, pTxVirtq->uIdx);
2708 if (!cPkts)
2709 {
2710 LogFunc(("[%s] No packets to send found on %s\n", pThis->szInst, pTxVirtq->szName));
2711
2712 if (pDrv)
2713 pDrv->pfnEndXmit(pDrv);
2714
2715 ASMAtomicWriteU32(&pThis->uIsTransmitting, 0);
2716 return VERR_MISSING;
2717 }
2718 LogFunc(("[%s] About to transmit %d pending packet%c\n", pThis->szInst, cPkts, cPkts == 1 ? ' ' : 's'));
2719
2720 virtioNetR3SetWriteLed(pThisCC, true);
2721
2722 /* Disable notifications until all available descriptors have been processed */
2723 if (!(pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX))
2724 virtioCoreVirtqEnableNotify(&pThis->Virtio, pTxVirtq->uIdx, false /* fEnable */);
2725
2726 int rc;
2727#ifdef VIRTIO_VBUF_ON_STACK
2728 VIRTQBUF_T VirtqBuf;
2729 PVIRTQBUF pVirtqBuf = &VirtqBuf;
2730 while ((rc = virtioCoreR3VirtqAvailBufPeek(pVirtio->pDevInsR3, pVirtio, pTxVirtq->uIdx, pVirtqBuf)) == VINF_SUCCESS)
2731#else /* !VIRTIO_VBUF_ON_STACK */
2732 PVIRTQBUF pVirtqBuf = NULL;
2733 while ((rc = virtioCoreR3VirtqAvailBufPeek(pVirtio->pDevInsR3, pVirtio, pTxVirtq->uIdx, &pVirtqBuf)) == VINF_SUCCESS)
2734#endif /* !VIRTIO_VBUF_ON_STACK */
2735 {
2736 Log10Func(("[%s] fetched descriptor chain from %s\n", pThis->szInst, pTxVirtq->szName));
2737
2738 PVIRTIOSGBUF pSgPhysSend = pVirtqBuf->pSgPhysSend;
2739 PVIRTIOSGSEG paSegsFromGuest = pSgPhysSend->paSegs;
2740 uint32_t cSegsFromGuest = pSgPhysSend->cSegs;
2741 size_t uFrameSize = 0;
2742
2743 AssertMsgReturn(paSegsFromGuest[0].cbSeg >= pThis->cbPktHdr,
2744 ("Desc chain's first seg has insufficient space for pkt header!\n"),
2745 VERR_INTERNAL_ERROR);
2746
2747#ifdef VIRTIO_VBUF_ON_STACK
2748 VIRTIONETPKTHDR PktHdr;
2749 PVIRTIONETPKTHDR pPktHdr = &PktHdr;
2750#else /* !VIRTIO_VBUF_ON_STACK */
2751 PVIRTIONETPKTHDR pPktHdr = (PVIRTIONETPKTHDR)RTMemAllocZ(pThis->cbPktHdr);
2752 AssertMsgReturn(pPktHdr, ("Out of Memory\n"), VERR_NO_MEMORY);
2753#endif /* !VIRTIO_VBUF_ON_STACK */
2754
2755 /* Compute total frame size from guest (including virtio-net pkt hdr) */
2756 for (unsigned i = 0; i < cSegsFromGuest && uFrameSize < VIRTIONET_MAX_FRAME_SIZE; i++)
2757 uFrameSize += paSegsFromGuest[i].cbSeg;
2758
2759 Log5Func(("[%s] complete frame is %u bytes.\n", pThis->szInst, uFrameSize));
2760 Assert(uFrameSize <= VIRTIONET_MAX_FRAME_SIZE);
2761
2762 /* Truncate oversized frames. */
2763 if (uFrameSize > VIRTIONET_MAX_FRAME_SIZE)
2764 uFrameSize = VIRTIONET_MAX_FRAME_SIZE;
2765
2766 if (pThisCC->pDrv)
2767 {
2768 uFrameSize -= pThis->cbPktHdr;
2769 /*
2770 * Peel off pkt header and convert to PDM/GSO semantics.
2771 */
2772 rc = virtioNetR3ReadVirtioTxPktHdr(pVirtio, pThis, pDevIns, paSegsFromGuest[0].GCPhys, pPktHdr, uFrameSize /* cbFrame */);
2773 if (RT_FAILURE(rc))
2774 return rc;
2775 virtioCoreGCPhysChainAdvance(pSgPhysSend, pThis->cbPktHdr);
2776
2777 PDMNETWORKGSO Gso, *pGso = virtioNetR3SetupGsoCtx(&Gso, pPktHdr);
2778
2779 /* Allocate PDM transmit buffer to send guest provided network frame from to VBox network leaf device */
2780 PPDMSCATTERGATHER pSgBufToPdmLeafDevice;
2781 rc = pThisCC->pDrv->pfnAllocBuf(pThisCC->pDrv, uFrameSize, pGso, &pSgBufToPdmLeafDevice);
2782
2783 /*
2784 * Copy virtio-net guest S/G buffer to PDM leaf driver S/G buffer
2785 * converting from GCphys to virt memory at the same time
2786 */
2787 if (RT_SUCCESS(rc))
2788 {
2789 STAM_REL_COUNTER_INC(&pThis->StatTransmitPackets);
2790 STAM_PROFILE_START(&pThis->StatTransmitSend, a);
2791
2792 size_t cbCopied = 0;
2793 size_t cbRemain = pSgBufToPdmLeafDevice->cbUsed = uFrameSize;
2794 uint64_t uOffset = 0;
2795 while (cbRemain)
2796 {
2797 PVIRTIOSGSEG paSeg = &pSgPhysSend->paSegs[pSgPhysSend->idxSeg];
2798 uint64_t srcSgStart = (uint64_t)paSeg->GCPhys;
2799 uint64_t srcSgLen = (uint64_t)paSeg->cbSeg;
2800 uint64_t srcSgCur = (uint64_t)pSgPhysSend->GCPhysCur;
2801 cbCopied = RT_MIN((uint64_t)cbRemain, srcSgLen - (srcSgCur - srcSgStart));
2802 virtioCoreGCPhysRead(pVirtio, pDevIns,
2803 (RTGCPHYS)pSgPhysSend->GCPhysCur,
2804 ((uint8_t *)pSgBufToPdmLeafDevice->aSegs[0].pvSeg) + uOffset, cbCopied);
2805 virtioCoreGCPhysChainAdvance(pSgPhysSend, cbCopied);
2806 cbRemain -= cbCopied;
2807 uOffset += cbCopied;
2808 }
2809
2810 LogFunc((".... Copied %lu/%lu bytes to %lu byte guest buffer. Buf residual=%lu\n",
2811 uOffset, uFrameSize, pVirtqBuf->cbPhysSend, virtioCoreGCPhysChainCalcLengthLeft(pSgPhysSend)));
2812
2813 rc = virtioNetR3TransmitFrame(pThis, pThisCC, pSgBufToPdmLeafDevice, pGso, pPktHdr);
2814 if (RT_FAILURE(rc))
2815 {
2816 LogFunc(("[%s] Failed to transmit frame, rc = %Rrc\n", pThis->szInst, rc));
2817 STAM_PROFILE_STOP(&pThis->StatTransmitSend, a);
2818 STAM_PROFILE_ADV_STOP(&pThis->StatTransmit, a);
2819 pThisCC->pDrv->pfnFreeBuf(pThisCC->pDrv, pSgBufToPdmLeafDevice);
2820 }
2821 STAM_PROFILE_STOP(&pThis->StatTransmitSend, a);
2822 STAM_REL_COUNTER_ADD(&pThis->StatTransmitBytes, uOffset);
2823 }
2824 else
2825 {
2826 Log4Func(("Failed to allocate S/G buffer: frame size=%u rc=%Rrc\n", uFrameSize, rc));
2827 /* Stop trying to fetch TX descriptors until we get more bandwidth. */
2828#ifndef VIRTIO_VBUF_ON_STACK
2829 virtioCoreR3VirtqBufRelease(pVirtio, pVirtqBuf);
2830#endif /* !VIRTIO_VBUF_ON_STACK */
2831 break;
2832 }
2833
2834 virtioCoreR3VirtqAvailBufNext(pVirtio, pTxVirtq->uIdx);
2835
2836 /* No data to return to guest, but necessary to put elem (e.g. desc chain head idx) on used ring */
2837 virtioCoreR3VirtqUsedBufPut(pVirtio->pDevInsR3, pVirtio, pTxVirtq->uIdx, NULL, pVirtqBuf, true /* fFence */);
2838 virtioCoreVirtqUsedRingSync(pVirtio->pDevInsR3, pVirtio, pTxVirtq->uIdx);
2839 }
2840
2841#ifndef VIRTIO_VBUF_ON_STACK
2842 virtioCoreR3VirtqBufRelease(pVirtio, pVirtqBuf);
2843 pVirtqBuf = NULL;
2844#endif /* !VIRTIO_VBUF_ON_STACK */
2845 /* Before we break the loop we need to check if the queue is empty,
2846 * re-enable notifications, and then re-check again to avoid missing
2847 * a notification for the descriptor that is added to the queue
2848 * after we have checked it on being empty, but before we re-enabled
2849 * notifications.
2850 */
2851 if (!(pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
2852 && IS_VIRTQ_EMPTY(pDevIns, &pThis->Virtio, pTxVirtq->uIdx))
2853 virtioCoreVirtqEnableNotify(&pThis->Virtio, pTxVirtq->uIdx, true /* fEnable */);
2854 }
2855 virtioNetR3SetWriteLed(pThisCC, false);
2856
2857 if (pDrv)
2858 pDrv->pfnEndXmit(pDrv);
2859
2860 ASMAtomicWriteU32(&pThis->uIsTransmitting, 0);
2861 return VINF_SUCCESS;
2862}
2863
2864/**
2865 * @interface_method_impl{PDMINETWORKDOWN,pfnXmitPending}
2866 */
2867static DECLCALLBACK(void) virtioNetR3NetworkDown_XmitPending(PPDMINETWORKDOWN pInterface)
2868{
2869 LogFunc(("\n"));
2870 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, INetworkDown);
2871 PPDMDEVINS pDevIns = pThisCC->pDevIns;
2872 PVIRTIONET pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVIRTIONET);
2873 PVIRTIONETVIRTQ pTxVirtq = &pThis->aVirtqs[TXQIDX(0)];
2874 STAM_COUNTER_INC(&pThis->StatTransmitByNetwork);
2875
2876 (void)virtioNetR3TransmitPkts(pDevIns, pThis, pThisCC, pTxVirtq, true /*fOnWorkerThread*/);
2877}
2878
2879/**
2880 * @callback_method_impl{FNTMTIMERDEV, Link Up Timer handler.}
2881 */
2882static DECLCALLBACK(void) virtioNetR3LinkUpTimer(PPDMDEVINS pDevIns, TMTIMERHANDLE hTimer, void *pvUser)
2883{
2884 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
2885 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
2886
2887 SET_LINK_UP(pThis);
2888 virtioNetWakeupRxBufWaiter(pDevIns);
2889
2890 if (pThisCC->pDrv)
2891 pThisCC->pDrv->pfnNotifyLinkChanged(pThisCC->pDrv, PDMNETWORKLINKSTATE_UP);
2892
2893 LogFunc(("[%s] Link is up\n", pThis->szInst));
2894 RT_NOREF(hTimer, pvUser);
2895}
2896
2897/**
2898 * Takes down the link temporarily if its current status is up.
2899 *
2900 * This is used during restore and when replumbing the network link.
2901 *
2902 * The temporary link outage is supposed to indicate to the OS that all network
2903 * connections have been lost and that it for instance is appropriate to
2904 * renegotiate any DHCP lease.
2905 *
2906 * @param pDevIns The device instance.
2907 * @param pThis The virtio-net shared instance data.
2908 * @param pThisCC The virtio-net ring-3 instance data.
2909 */
2910static void virtioNetR3TempLinkDown(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETCC pThisCC)
2911{
2912 if (IS_LINK_UP(pThis))
2913 {
2914 SET_LINK_DOWN(pThis);
2915
2916 /* Re-establish link in 5 seconds. */
2917 int rc = PDMDevHlpTimerSetMillies(pDevIns, pThisCC->hLinkUpTimer, pThis->cMsLinkUpDelay);
2918 AssertRC(rc);
2919
2920 LogFunc(("[%s] Link is down temporarily\n", pThis->szInst));
2921 }
2922}
2923
2924/**
2925 * @interface_method_impl{PDMINETWORKCONFIG,pfnSetLinkState}
2926 */
2927static DECLCALLBACK(int) virtioNetR3NetworkConfig_SetLinkState(PPDMINETWORKCONFIG pInterface, PDMNETWORKLINKSTATE enmState)
2928{
2929 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, INetworkConfig);
2930 PPDMDEVINS pDevIns = pThisCC->pDevIns;
2931 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
2932
2933 bool fRequestedLinkStateIsUp = (enmState == PDMNETWORKLINKSTATE_UP);
2934
2935#ifdef LOG_ENABLED
2936 if (LogIs7Enabled())
2937 {
2938 LogFunc(("[%s]", pThis->szInst));
2939 switch(enmState)
2940 {
2941 case PDMNETWORKLINKSTATE_UP:
2942 Log(("UP\n"));
2943 break;
2944 case PDMNETWORKLINKSTATE_DOWN:
2945 Log(("DOWN\n"));
2946 break;
2947 case PDMNETWORKLINKSTATE_DOWN_RESUME:
2948 Log(("DOWN (RESUME)\n"));
2949 break;
2950 default:
2951 Log(("UNKNOWN)\n"));
2952 }
2953 }
2954#endif
2955
2956 if (enmState == PDMNETWORKLINKSTATE_DOWN_RESUME)
2957 {
2958 if (IS_LINK_UP(pThis))
2959 {
2960 /*
2961 * We bother to bring the link down only if it was up previously. The UP link state
2962 * notification will be sent when the link actually goes up in virtioNetR3LinkUpTimer().
2963 */
2964 virtioNetR3TempLinkDown(pDevIns, pThis, pThisCC);
2965 if (pThisCC->pDrv)
2966 pThisCC->pDrv->pfnNotifyLinkChanged(pThisCC->pDrv, enmState);
2967 }
2968 }
2969 else if (fRequestedLinkStateIsUp != IS_LINK_UP(pThis))
2970 {
2971 if (fRequestedLinkStateIsUp)
2972 {
2973 Log(("[%s] Link is up\n", pThis->szInst));
2974 pThis->fCableConnected = true;
2975 SET_LINK_UP(pThis);
2976 virtioCoreNotifyConfigChanged(&pThis->Virtio);
2977 }
2978 else /* Link requested to be brought down */
2979 {
2980 /* The link was brought down explicitly, make sure it won't come up by timer. */
2981 PDMDevHlpTimerStop(pDevIns, pThisCC->hLinkUpTimer);
2982 Log(("[%s] Link is down\n", pThis->szInst));
2983 pThis->fCableConnected = false;
2984 SET_LINK_DOWN(pThis);
2985 virtioCoreNotifyConfigChanged(&pThis->Virtio);
2986 }
2987 if (pThisCC->pDrv)
2988 pThisCC->pDrv->pfnNotifyLinkChanged(pThisCC->pDrv, enmState);
2989 }
2990 return VINF_SUCCESS;
2991}
2992/**
2993 * @interface_method_impl{PDMINETWORKCONFIG,pfnGetLinkState}
2994 */
2995static DECLCALLBACK(PDMNETWORKLINKSTATE) virtioNetR3NetworkConfig_GetLinkState(PPDMINETWORKCONFIG pInterface)
2996{
2997 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, INetworkConfig);
2998 PVIRTIONET pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVIRTIONET);
2999
3000 return IS_LINK_UP(pThis) ? PDMNETWORKLINKSTATE_UP : PDMNETWORKLINKSTATE_DOWN;
3001}
3002
3003static int virtioNetR3DestroyWorkerThreads(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETCC pThisCC)
3004{
3005 Log10Func(("[%s]\n", pThis->szInst));
3006 int rc = VINF_SUCCESS;
3007 for (unsigned uIdxWorker = 0; uIdxWorker < pThis->cWorkers; uIdxWorker++)
3008 {
3009 PVIRTIONETWORKER pWorker = &pThis->aWorkers[uIdxWorker];
3010 PVIRTIONETWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uIdxWorker];
3011
3012 if (pWorker->hEvtProcess != NIL_SUPSEMEVENT)
3013 {
3014 PDMDevHlpSUPSemEventClose(pDevIns, pWorker->hEvtProcess);
3015 pWorker->hEvtProcess = NIL_SUPSEMEVENT;
3016 }
3017 if (pWorkerR3->pThread)
3018 {
3019 int rcThread;
3020 rc = PDMDevHlpThreadDestroy(pDevIns, pWorkerR3->pThread, &rcThread);
3021 if (RT_FAILURE(rc) || RT_FAILURE(rcThread))
3022 AssertMsgFailed(("%s Failed to destroythread rc=%Rrc rcThread=%Rrc\n", __FUNCTION__, rc, rcThread));
3023 pWorkerR3->pThread = NULL;
3024 }
3025 }
3026 return rc;
3027}
3028
3029/**
3030 * Creates a worker for specified queue, along with semaphore to throttle the worker.
3031 *
3032 * @param pDevIns - PDM device instance
3033 * @param pThis - virtio-net instance
3034 * @param pWorker - Pointer to worker state
3035 * @param pWorkerR3 - Pointer to worker state
3036 * @param pVirtq - Pointer to virtq
3037 */
3038static int virtioNetR3CreateOneWorkerThread(PPDMDEVINS pDevIns, PVIRTIONET pThis,
3039 PVIRTIONETWORKER pWorker, PVIRTIONETWORKERR3 pWorkerR3,
3040 PVIRTIONETVIRTQ pVirtq)
3041{
3042 Log10Func(("[%s]\n", pThis->szInst));
3043 RT_NOREF(pThis);
3044
3045 int rc = PDMDevHlpSUPSemEventCreate(pDevIns, &pWorker->hEvtProcess);
3046
3047 if (RT_FAILURE(rc))
3048 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
3049 N_("DevVirtioNET: Failed to create SUP event semaphore"));
3050
3051 LogFunc(("creating thread for queue %s\n", pVirtq->szName));
3052
3053 rc = PDMDevHlpThreadCreate(pDevIns, &pWorkerR3->pThread,
3054 (void *)pWorker, virtioNetR3WorkerThread,
3055 virtioNetR3WakeupWorker, 0, RTTHREADTYPE_IO, pVirtq->szName);
3056 if (RT_FAILURE(rc))
3057 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
3058 N_("Error creating thread for Virtual Virtq %s\n"), pVirtq->uIdx);
3059
3060 pWorker->fAssigned = true; /* Because worker's state in fixed-size array initialized w/empty slots */
3061
3062 LogFunc(("%s pThread: %p\n", pVirtq->szName, pWorkerR3->pThread));
3063
3064 return rc;
3065}
3066
3067static int virtioNetR3CreateWorkerThreads(PPDMDEVINS pDevIns, PVIRTIONET pThis, PVIRTIONETCC pThisCC)
3068{
3069 Log10Func(("[%s]\n", pThis->szInst));
3070 int rc;
3071
3072 /* Create the Control Queue worker anyway whether or not it is feature-negotiated or utilized by the guest.
3073 * See related comment for queue construction in the device constructor function for more context.
3074 */
3075
3076 PVIRTIONETVIRTQ pCtlVirtq = &pThis->aVirtqs[CTRLQIDX];
3077 rc = virtioNetR3CreateOneWorkerThread(pDevIns, pThis,
3078 &pThis->aWorkers[CTRLQIDX], &pThisCC->aWorkers[CTRLQIDX], pCtlVirtq);
3079 AssertRCReturn(rc, rc);
3080
3081 pCtlVirtq->fHasWorker = true;
3082
3083 for (uint16_t uVirtqPair = pThis->cInitializedVirtqPairs; uVirtqPair < pThis->cVirtqPairs; uVirtqPair++)
3084 {
3085 PVIRTIONETVIRTQ pTxVirtq = &pThis->aVirtqs[TXQIDX(uVirtqPair)];
3086 PVIRTIONETVIRTQ pRxVirtq = &pThis->aVirtqs[RXQIDX(uVirtqPair)];
3087
3088 rc = virtioNetR3CreateOneWorkerThread(pDevIns, pThis, &pThis->aWorkers[TXQIDX(uVirtqPair)],
3089 &pThisCC->aWorkers[TXQIDX(uVirtqPair)], pTxVirtq);
3090 AssertRCReturn(rc, rc);
3091
3092 pTxVirtq->fHasWorker = true;
3093 pRxVirtq->fHasWorker = false;
3094 }
3095
3096 if (pThis->cVirtqPairs > pThis->cInitializedVirtqPairs)
3097 pThis->cInitializedVirtqPairs = pThis->cVirtqPairs;
3098
3099 pThis->cWorkers = pThis->cVirtqPairs + 1 /* One control virtq */;
3100
3101 return rc;
3102}
3103
3104static void virtioNetConfigurePktHdr(PVIRTIONET pThis, uint32_t fLegacy)
3105{
3106 /* Calculate network packet header type and size based on what we know now */
3107 pThis->cbPktHdr = sizeof(VIRTIONETPKTHDR);
3108 if (!fLegacy)
3109 /* Modern (e.g. >= VirtIO 1.0) device specification's pkt size rules */
3110 if (FEATURE_ENABLED(MRG_RXBUF))
3111 pThis->ePktHdrType = kVirtioNetModernPktHdrWithMrgRx;
3112 else /* Modern guest driver with MRG_RX feature disabled */
3113 pThis->ePktHdrType = kVirtioNetModernPktHdrWithoutMrgRx;
3114 else
3115 {
3116 /* Legacy (e.g. < VirtIO 1.0) device specification's pkt size rules */
3117 if (FEATURE_ENABLED(MRG_RXBUF))
3118 pThis->ePktHdrType = kVirtioNetLegacyPktHdrWithMrgRx;
3119 else /* Legacy guest with MRG_RX feature disabled */
3120 {
3121 pThis->ePktHdrType = kVirtioNetLegacyPktHdrWithoutMrgRx;
3122 pThis->cbPktHdr -= RT_SIZEOFMEMB(VIRTIONETPKTHDR, uNumBuffers);
3123 }
3124 }
3125}
3126
3127/**
3128 * @callback_method_impl{FNPDMTHREADDEV}
3129 */
3130static DECLCALLBACK(int) virtioNetR3WorkerThread(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
3131{
3132 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
3133 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
3134 PVIRTIONETWORKER pWorker = (PVIRTIONETWORKER)pThread->pvUser;
3135 PVIRTIONETVIRTQ pVirtq = &pThis->aVirtqs[pWorker->uIdx];
3136 uint16_t uIdx = pWorker->uIdx;
3137
3138 ASMAtomicWriteBool(&pWorker->fSleeping, false);
3139
3140 Assert(pWorker->uIdx == pVirtq->uIdx);
3141
3142 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
3143 return VINF_SUCCESS;
3144
3145 LogFunc(("[%s] worker thread idx=%d started for %s (virtq idx=%d)\n", pThis->szInst, pWorker->uIdx, pVirtq->szName, pVirtq->uIdx));
3146
3147 /** @todo Race w/guest enabling/disabling guest notifications cyclically.
3148 See BugRef #8651, Comment #82 */
3149 virtioCoreVirtqEnableNotify(&pThis->Virtio, uIdx, true /* fEnable */);
3150
3151 while ( pThread->enmState != PDMTHREADSTATE_TERMINATING
3152 && pThread->enmState != PDMTHREADSTATE_TERMINATED)
3153 {
3154 if (IS_VIRTQ_EMPTY(pDevIns, &pThis->Virtio, pVirtq->uIdx))
3155 {
3156 /* Precisely coordinated atomic interlocks avoid a race condition that results in hung thread
3157 * wherein a sloppily coordinated wake-up notification during a transition into or out
3158 * of sleep leaves notifier and target mutually confused about actual & intended state.
3159 */
3160 ASMAtomicWriteBool(&pWorker->fSleeping, true);
3161 bool fNotificationSent = ASMAtomicXchgBool(&pWorker->fNotified, false);
3162 if (!fNotificationSent)
3163 {
3164 Log10Func(("[%s] %s worker sleeping...\n\n", pThis->szInst, pVirtq->szName));
3165 Assert(ASMAtomicReadBool(&pWorker->fSleeping));
3166
3167 int rc = PDMDevHlpSUPSemEventWaitNoResume(pDevIns, pWorker->hEvtProcess, RT_INDEFINITE_WAIT);
3168 STAM_COUNTER_INC(&pThis->StatTransmitByThread);
3169 AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_INTERRUPTED, ("%Rrc\n", rc), rc);
3170 if (RT_UNLIKELY(pThread->enmState != PDMTHREADSTATE_RUNNING))
3171 return VINF_SUCCESS;
3172 if (rc == VERR_INTERRUPTED)
3173 continue;
3174 ASMAtomicWriteBool(&pWorker->fNotified, false);
3175 }
3176 ASMAtomicWriteBool(&pWorker->fSleeping, false);
3177 }
3178 /*
3179 * Dispatch to the handler for the queue this worker is set up to drive
3180 */
3181 if (pVirtq->fCtlVirtq)
3182 {
3183 Log10Func(("[%s] %s worker woken. Fetching desc chain\n", pThis->szInst, pVirtq->szName));
3184#ifdef VIRTIO_VBUF_ON_STACK
3185 VIRTQBUF_T VirtqBuf;
3186 PVIRTQBUF pVirtqBuf = &VirtqBuf;
3187 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, pVirtq->uIdx, pVirtqBuf, true);
3188#else /* !VIRTIO_VBUF_ON_STACK */
3189 PVIRTQBUF pVirtqBuf = NULL;
3190 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, pVirtq->uIdx, &pVirtqBuf, true);
3191#endif /* !VIRTIO_VBUF_ON_STACK */
3192 if (rc == VERR_NOT_AVAILABLE)
3193 {
3194 Log10Func(("[%s] %s worker woken. Nothing found in queue\n", pThis->szInst, pVirtq->szName));
3195 continue;
3196 }
3197 virtioNetR3Ctrl(pDevIns, pThis, pThisCC, pVirtqBuf);
3198#ifndef VIRTIO_VBUF_ON_STACK
3199 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
3200#endif /* !VIRTIO_VBUF_ON_STACK */
3201 }
3202 else /* Must be Tx queue */
3203 {
3204 Log10Func(("[%s] %s worker woken. Virtq has data to transmit\n", pThis->szInst, pVirtq->szName));
3205 virtioNetR3TransmitPkts(pDevIns, pThis, pThisCC, pVirtq, false /* fOnWorkerThread */);
3206 }
3207 /* Note: Surprise! Rx queues aren't handled by local worker threads. Instead, the PDM network leaf driver
3208 * invokes PDMINETWORKDOWN.pfnWaitReceiveAvail() callback, which waits until woken by virtioNetVirtqNotified()
3209 * indicating that guest IN buffers have been added to Rx virt queue.
3210 */
3211 }
3212 Log10(("[%s] %s worker thread exiting\n", pThis->szInst, pVirtq->szName));
3213 return VINF_SUCCESS;
3214}
3215
3216/**
3217 * @callback_method_impl{VIRTIOCORER3,pfnStatusChanged}
3218 *
3219 * Called back by the core code when VirtIO's ready state has changed.
3220 */
3221static DECLCALLBACK(void) virtioNetR3StatusChg(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint32_t fVirtioReady)
3222{
3223 PVIRTIONET pThis = RT_FROM_MEMBER(pVirtio, VIRTIONET, Virtio);
3224 PVIRTIONETCC pThisCC = RT_FROM_MEMBER(pVirtioCC, VIRTIONETCC, Virtio);
3225
3226 pThis->fVirtioReady = fVirtioReady;
3227
3228 if (fVirtioReady)
3229 {
3230#ifdef LOG_ENABLED
3231 Log(("\n%-23s: %s *** VirtIO Ready ***\n\n", __FUNCTION__, pThis->szInst));
3232 virtioCorePrintDeviceFeatures(&pThis->Virtio, NULL, s_aDevSpecificFeatures, RT_ELEMENTS(s_aDevSpecificFeatures));
3233#endif
3234 pThis->fResetting = false;
3235 pThis->fNegotiatedFeatures = virtioCoreGetNegotiatedFeatures(pVirtio);
3236 /* Now we can properly figure out the size of virtio header! */
3237 virtioNetConfigurePktHdr(pThis, pThis->Virtio.fLegacyDriver);
3238 pThis->virtioNetConfig.uStatus = pThis->fCableConnected ? VIRTIONET_F_LINK_UP : 0;
3239
3240 for (unsigned uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
3241 {
3242 PVIRTIONETVIRTQ pVirtq = &pThis->aVirtqs[uVirtqNbr];
3243 PVIRTIONETWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
3244
3245 Assert(pWorker->uIdx == uVirtqNbr);
3246 RT_NOREF(pWorker);
3247
3248 Assert(pVirtq->uIdx == pWorker->uIdx);
3249
3250 (void) virtioCoreR3VirtqAttach(&pThis->Virtio, pVirtq->uIdx, pVirtq->szName);
3251 pVirtq->fAttachedToVirtioCore = true;
3252 if (IS_VIRTQ_EMPTY(pThisCC->pDevIns, &pThis->Virtio, pVirtq->uIdx))
3253 virtioCoreVirtqEnableNotify(&pThis->Virtio, pVirtq->uIdx, true /* fEnable */);
3254 }
3255 }
3256 else
3257 {
3258 Log(("\n%-23s: %s VirtIO is resetting ***\n", __FUNCTION__, pThis->szInst));
3259
3260 pThis->virtioNetConfig.uStatus = pThis->fCableConnected ? VIRTIONET_F_LINK_UP : 0;
3261 Log7(("%-23s: %s Link is %s\n", __FUNCTION__, pThis->szInst, pThis->fCableConnected ? "up" : "down"));
3262
3263 pThis->fPromiscuous = true;
3264 pThis->fAllMulticast = false;
3265 pThis->fAllUnicast = false;
3266 pThis->fNoMulticast = false;
3267 pThis->fNoUnicast = false;
3268 pThis->fNoBroadcast = false;
3269 pThis->uIsTransmitting = 0;
3270 pThis->cUnicastFilterMacs = 0;
3271 pThis->cMulticastFilterMacs = 0;
3272
3273 memset(pThis->aMacMulticastFilter, 0, sizeof(pThis->aMacMulticastFilter));
3274 memset(pThis->aMacUnicastFilter, 0, sizeof(pThis->aMacUnicastFilter));
3275 memset(pThis->aVlanFilter, 0, sizeof(pThis->aVlanFilter));
3276
3277 pThisCC->pDrv->pfnSetPromiscuousMode(pThisCC->pDrv, true);
3278
3279 for (uint16_t uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
3280 {
3281 virtioCoreR3VirtqDetach(&pThis->Virtio, uVirtqNbr);
3282 pThis->aVirtqs[uVirtqNbr].fAttachedToVirtioCore = false;
3283 }
3284 }
3285}
3286
3287/**
3288 * @callback_method_impl{VIRTIOCORER3,pfnFeatureNegotiationComplete}
3289 */
3290static DECLCALLBACK(void) pfnFeatureNegotiationComplete(PVIRTIOCORE pVirtio, uint64_t fDriverFeatures, uint32_t fLegacy)
3291{
3292 PVIRTIONET pThis = PDMDEVINS_2_DATA(pVirtio->pDevInsR3, PVIRTIONET);
3293
3294 LogFunc(("[Feature Negotiation Complete] Guest Driver version is: %s\n", fLegacy ? "legacy" : "modern"));
3295 virtioNetConfigurePktHdr(pThis, fLegacy);
3296 virtioNetR3SetVirtqNames(pThis, fLegacy);
3297
3298 /* Senseless for modern guest to use control queue in this case. (See Note 1 in PDM-invoked device constructor) */
3299 if (!fLegacy && !(fDriverFeatures & VIRTIONET_F_CTRL_VQ))
3300 virtioNetR3VirtqDestroy(pVirtio, &pThis->aVirtqs[CTRLQIDX]);
3301}
3302
3303#endif /* IN_RING3 */
3304
3305/**
3306 * @interface_method_impl{PDMDEVREGR3,pfnDetach}
3307 *
3308 * The VM is suspended at this point.
3309 */
3310static DECLCALLBACK(void) virtioNetR3Detach(PPDMDEVINS pDevIns, unsigned iLUN, uint32_t fFlags)
3311{
3312 RT_NOREF(fFlags);
3313
3314 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
3315 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
3316
3317 Log7Func(("[%s]\n", pThis->szInst));
3318 RT_NOREF(pThis);
3319
3320 AssertLogRelReturnVoid(iLUN == 0);
3321
3322 pThisCC->pDrvBase = NULL;
3323 pThisCC->pDrv = NULL;
3324}
3325
3326/**
3327 * @interface_method_impl{PDMDEVREGR3,pfnAttach}
3328 *
3329 * This is called when we change block driver.
3330 */
3331static DECLCALLBACK(int) virtioNetR3Attach(PPDMDEVINS pDevIns, unsigned iLUN, uint32_t fFlags)
3332{
3333 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
3334 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
3335
3336 Log7Func(("[%s]", pThis->szInst));
3337 AssertLogRelReturn(iLUN == 0, VERR_PDM_NO_SUCH_LUN);
3338
3339 int rc = PDMDevHlpDriverAttach(pDevIns, 0, &pThisCC->IBase, &pThisCC->pDrvBase, "Network Port");
3340 if (RT_SUCCESS(rc))
3341 {
3342 pThisCC->pDrv = PDMIBASE_QUERY_INTERFACE(pThisCC->pDrvBase, PDMINETWORKUP);
3343 AssertMsgStmt(pThisCC->pDrv, ("Failed to obtain the PDMINETWORKUP interface!\n"),
3344 rc = VERR_PDM_MISSING_INTERFACE_BELOW);
3345 }
3346 else if ( rc == VERR_PDM_NO_ATTACHED_DRIVER
3347 || rc == VERR_PDM_CFG_MISSING_DRIVER_NAME)
3348 Log(("[%s] No attached driver!\n", pThis->szInst));
3349
3350 RT_NOREF2(pThis, fFlags);
3351 return rc;
3352}
3353
3354/**
3355 * @interface_method_impl{PDMILEDPORTS,pfnQueryStatusLed}
3356 */
3357static DECLCALLBACK(int) virtioNetR3QueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
3358{
3359 PVIRTIONETR3 pThisR3 = RT_FROM_MEMBER(pInterface, VIRTIONETR3, ILeds);
3360 if (iLUN)
3361 return VERR_PDM_LUN_NOT_FOUND;
3362 *ppLed = &pThisR3->led;
3363 return VINF_SUCCESS;
3364}
3365
3366/**
3367 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3368 */
3369static DECLCALLBACK(void *) virtioNetR3QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
3370{
3371 PVIRTIONETR3 pThisCC = RT_FROM_MEMBER(pInterface, VIRTIONETCC, IBase);
3372 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKDOWN, &pThisCC->INetworkDown);
3373 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKCONFIG, &pThisCC->INetworkConfig);
3374 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThisCC->IBase);
3375 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pThisCC->ILeds);
3376 return NULL;
3377}
3378
3379/**
3380 * @interface_method_impl{PDMDEVREGR3,pfnDestruct}
3381 */
3382static DECLCALLBACK(int) virtioNetR3Destruct(PPDMDEVINS pDevIns)
3383{
3384 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
3385
3386 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
3387 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
3388
3389 Log(("[%s] Destroying instance\n", pThis->szInst));
3390 if (pThis->hEventRxDescAvail != NIL_SUPSEMEVENT)
3391 {
3392 PDMDevHlpSUPSemEventSignal(pDevIns, pThis->hEventRxDescAvail);
3393 PDMDevHlpSUPSemEventClose(pDevIns, pThis->hEventRxDescAvail);
3394 pThis->hEventRxDescAvail = NIL_SUPSEMEVENT;
3395 }
3396
3397 virtioNetR3DestroyWorkerThreads(pDevIns, pThis, pThisCC);
3398 virtioCoreR3Term(pDevIns, &pThis->Virtio, &pThisCC->Virtio);
3399 return VINF_SUCCESS;
3400}
3401
3402/**
3403 * @interface_method_impl{PDMDEVREGR3,pfnConstruct}
3404 *
3405 * Notes about revising originally VirtIO 1.0+ only virtio-net device emulator to be "transitional",
3406 * a VirtIO term meaning this now interoperates with both "legacy" (e.g. pre-1.0) and "modern" (1.0+)
3407 * guest virtio-net drivers. The changes include migrating VMs saved using prior DevVirtioNet.cpp (0.95)
3408 * saveExec/loadExec semantics to use 1.0 save/load semantics.
3409 *
3410 * Regardless of the 1.0 spec's overall helpful guidance for implementing transitional devices,
3411 * A bit is left to the imagination, e.g. some things have to be determined deductively
3412 * (AKA "the hard way").
3413 *
3414 * Case in point: According to VirtIO 0.95 ("legacy") specification, section 2.2.1, "historically"
3415 * drivers may start driving prior to feature negotiation and prior to drivers setting DRIVER_OK
3416 * status, "provided driver doesn't use features that alter early use of this device". Interpreted
3417 * here to mean a virtio-net driver must respect default settings (such as implicit pkt header default
3418 * size, as determined per Note 1 below).
3419 *
3420 * ----------------------------------------------------------------------------------------------
3421 * Transitional device initialization Note 1: Identifying default value for network Rx pkt hdr size.
3422 * (VirtIO 1.0 specification section 5.1.6.1)
3423 *
3424 * Guest virtio legacy drivers may begin operations prematurely, regardless of early spec's
3425 * initialization sequence (see note 2 below). Legacy drivers implicitly default to using the
3426 * (historically) shortest-length network packet header *unless* VIRTIONET_F_MRG_RXBUF feature is
3427 * negotiated. If feature negotiation phase is [optionally] enacted by a legacy guest (i.e. we strictly
3428 * enforce full initialization protocol for modern guests), virtioNetConfigurePktHdr() is invoked again to
3429 * finalize device's network packet header size. Best-guess at default packet header size is deduced, e.g.
3430 * isn't documented, as follows: A legacy guest with VIRTIONET_F_MRG_RXBUF not-yet-negotiated is the only
3431 * case where network I/O could possibly occur with any reasonable assumption about packet type/size,
3432 * because logically other permutations couldn't possibly be inferred until feature negotiation
3433 * is complete. Specifically, those cases are:
3434 *
3435 * 1. A modern driver (detected only when VIRTIONET_F_VERSION_1 feature is ack'd by guest, and,
3436 * simultaneously, VIRTIONET_F_MRG_RXBUF feature is accepted or declined (determining network receive-packet
3437 * processing behavior).
3438 *
3439 * 2. A legacy driver that has agreed to use VIRTIONET_F_MRG_RXBUF feature, resulting in a two-byte larger pkt hdr,
3440 * (as well as deciding Rx packet processing behavior).
3441 *
3442 * ----------------------------------------------------------------------------------------------
3443 * Transitional device initialization Note 2: Creating unnegotiated control queue.
3444 * (VirtIO 1.0 spec, sections 5.1.5 and 5.1.6.5)
3445 *
3446 * Create all queues immediately, prior to feature negotiation, including control queue (irrespective
3447 * of the fact it's too early in initialization for control feature to be approved by guest). This
3448 * transitional device must deal with legacy guests which *can* (and on linux have been seen to) use
3449 * the control queue prior to feature negotiation.
3450 *
3451 * The initial assumption is *modern" guest virtio-net drivers out in the wild could never reasonably
3452 * attempt something as obviously risky as using ctrlq without first acking VIRTIO_NET_F_CTRL_VQ
3453 * feature to establish it. For now, we create the control queue proactively to accomodate a potentially
3454 * badly behaved but officially sanctioned legacy virtio-net driver, but *destroy* that same queue
3455 * if a driver announces as 'modern' during feature finalization yet leaves VIRTIO_NET_F_CTRL_VQ un-ack'd.
3456 */
3457static DECLCALLBACK(int) virtioNetR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
3458{
3459 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
3460 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
3461 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
3462 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
3463
3464 /*
3465 * Quickly initialize state data to ensure destructor always works.
3466 */
3467 Log7Func(("PDM device instance: %d\n", iInstance));
3468 RTStrPrintf(pThis->szInst, sizeof(pThis->szInst), "virtio-net #%d", iInstance);
3469
3470 pThisCC->pDevIns = pDevIns;
3471 pThisCC->IBase.pfnQueryInterface = virtioNetR3QueryInterface;
3472 pThisCC->ILeds.pfnQueryStatusLed = virtioNetR3QueryStatusLed;
3473 pThisCC->led.u32Magic = PDMLED_MAGIC;
3474
3475 /* Interfaces */
3476 pThisCC->INetworkDown.pfnWaitReceiveAvail = virtioNetR3NetworkDown_WaitReceiveAvail;
3477 pThisCC->INetworkDown.pfnReceive = virtioNetR3NetworkDown_Receive;
3478 pThisCC->INetworkDown.pfnReceiveGso = virtioNetR3NetworkDown_ReceiveGso;
3479 pThisCC->INetworkDown.pfnXmitPending = virtioNetR3NetworkDown_XmitPending;
3480 pThisCC->INetworkConfig.pfnGetMac = virtioNetR3NetworkConfig_GetMac;
3481 pThisCC->INetworkConfig.pfnGetLinkState = virtioNetR3NetworkConfig_GetLinkState;
3482 pThisCC->INetworkConfig.pfnSetLinkState = virtioNetR3NetworkConfig_SetLinkState;
3483
3484 pThis->hEventRxDescAvail = NIL_SUPSEMEVENT;
3485
3486 /*
3487 * Validate configuration.
3488 */
3489 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "MAC|CableConnected|LineSpeed|LinkUpDelay|StatNo|Legacy", "");
3490
3491 /* Get config params */
3492 int rc = pHlp->pfnCFGMQueryBytes(pCfg, "MAC", pThis->macConfigured.au8, sizeof(pThis->macConfigured));
3493 if (RT_FAILURE(rc))
3494 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Failed to get MAC address"));
3495
3496 rc = pHlp->pfnCFGMQueryBool(pCfg, "CableConnected", &pThis->fCableConnected);
3497 if (RT_FAILURE(rc))
3498 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Failed to get the value of 'CableConnected'"));
3499
3500 uint32_t uStatNo = iInstance;
3501 rc = pHlp->pfnCFGMQueryU32Def(pCfg, "StatNo", &uStatNo, iInstance);
3502 if (RT_FAILURE(rc))
3503 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Failed to get the \"StatNo\" value"));
3504
3505 rc = pHlp->pfnCFGMQueryU32Def(pCfg, "LinkUpDelay", &pThis->cMsLinkUpDelay, 5000); /* ms */
3506 if (RT_FAILURE(rc))
3507 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Failed to get the value of 'LinkUpDelay'"));
3508
3509 Assert(pThis->cMsLinkUpDelay <= 300000); /* less than 5 minutes */
3510
3511 if (pThis->cMsLinkUpDelay > 5000 || pThis->cMsLinkUpDelay < 100)
3512 LogRel(("%s WARNING! Link up delay is set to %u seconds!\n",
3513 pThis->szInst, pThis->cMsLinkUpDelay / 1000));
3514
3515 Log(("[%s] Link up delay is set to %u seconds\n", pThis->szInst, pThis->cMsLinkUpDelay / 1000));
3516
3517 /* Copy the MAC address configured for the VM to the MMIO accessible Virtio dev-specific config area */
3518 memcpy(pThis->virtioNetConfig.uMacAddress.au8, pThis->macConfigured.au8, sizeof(pThis->virtioNetConfig.uMacAddress)); /* TBD */
3519
3520 Log(("Using MAC address for %s: %2x:%2x:%2x:%2x:%2x:%2x\n", pThis->szInst,
3521 pThis->macConfigured.au8[0], pThis->macConfigured.au8[1], pThis->macConfigured.au8[2],
3522 pThis->macConfigured.au8[3], pThis->macConfigured.au8[4], pThis->macConfigured.au8[5]));
3523
3524 LogFunc(("RC=%RTbool R0=%RTbool\n", pDevIns->fRCEnabled, pDevIns->fR0Enabled));
3525
3526 /*
3527 * Configure Virtio core (generic Virtio queue and infrastructure management) parameters.
3528 */
3529# if FEATURE_OFFERED(STATUS)
3530 pThis->virtioNetConfig.uStatus = 0;
3531# endif
3532
3533 pThis->virtioNetConfig.uMaxVirtqPairs = VIRTIONET_MAX_QPAIRS;
3534 pThisCC->Virtio.pfnFeatureNegotiationComplete = pfnFeatureNegotiationComplete;
3535 pThisCC->Virtio.pfnVirtqNotified = virtioNetVirtqNotified;
3536 pThisCC->Virtio.pfnStatusChanged = virtioNetR3StatusChg;
3537 pThisCC->Virtio.pfnDevCapRead = virtioNetR3DevCapRead;
3538 pThisCC->Virtio.pfnDevCapWrite = virtioNetR3DevCapWrite;
3539
3540 VIRTIOPCIPARAMS VirtioPciParams;
3541 VirtioPciParams.uDeviceId = PCI_DEVICE_ID_VIRTIONET_HOST;
3542 VirtioPciParams.uClassBase = PCI_CLASS_BASE_NETWORK_CONTROLLER;
3543 VirtioPciParams.uClassSub = PCI_CLASS_SUB_NET_ETHERNET_CONTROLLER;
3544 VirtioPciParams.uClassProg = PCI_CLASS_PROG_UNSPECIFIED;
3545 VirtioPciParams.uSubsystemId = PCI_DEVICE_ID_VIRTIONET_HOST; /* VirtIO 1.0 allows PCI Device ID here */
3546 VirtioPciParams.uInterruptLine = 0x00;
3547 VirtioPciParams.uInterruptPin = 0x01;
3548
3549 /* Create semaphore used to synchronize/throttle the downstream LUN's Rx waiter thread. */
3550 rc = PDMDevHlpSUPSemEventCreate(pDevIns, &pThis->hEventRxDescAvail);
3551 if (RT_FAILURE(rc))
3552 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to create event semaphore"));
3553
3554 pThis->fOfferLegacy = VIRTIONET_TRANSITIONAL_ENABLE_FLAG;
3555 virtioNetConfigurePktHdr(pThis, pThis->fOfferLegacy); /* set defaults */
3556
3557 /* Initialize VirtIO core. (*pfnStatusChanged)() callback occurs when both host VirtIO core & guest driver are ready) */
3558 rc = virtioCoreR3Init(pDevIns, &pThis->Virtio, &pThisCC->Virtio, &VirtioPciParams, pThis->szInst,
3559 VIRTIONET_HOST_FEATURES_OFFERED, pThis->fOfferLegacy,
3560 &pThis->virtioNetConfig /*pvDevSpecificCap*/, sizeof(pThis->virtioNetConfig));
3561 if (RT_FAILURE(rc))
3562 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-net: failed to initialize VirtIO"));
3563
3564 pThis->fNegotiatedFeatures = virtioCoreGetNegotiatedFeatures(&pThis->Virtio);
3565 /** @todo validating features at this point is most probably pointless, as the negotiation hasn't started yet. */
3566 if (!virtioNetValidateRequiredFeatures(pThis->fNegotiatedFeatures))
3567 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-net: Required features not successfully negotiated."));
3568 pThis->cVirtqPairs = pThis->virtioNetConfig.uMaxVirtqPairs;
3569 pThis->cVirtqs += pThis->cVirtqPairs * 2 + 1;
3570 pThis->aVirtqs[CTRLQIDX].fCtlVirtq = true;
3571
3572 virtioNetR3SetVirtqNames(pThis, pThis->fOfferLegacy);
3573 for (unsigned uVirtqNbr = 0; uVirtqNbr < pThis->cVirtqs; uVirtqNbr++)
3574 {
3575 PVIRTIONETVIRTQ pVirtq = &pThis->aVirtqs[uVirtqNbr];
3576 PVIRTIONETWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
3577 PVIRTIONETWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
3578 pVirtq->uIdx = pWorker->uIdx = pWorkerR3->uIdx = uVirtqNbr;
3579 }
3580 /*
3581 * Create queue workers for life of instance. (I.e. they persist through VirtIO bounces)
3582 */
3583 rc = virtioNetR3CreateWorkerThreads(pDevIns, pThis, pThisCC);
3584 if (RT_FAILURE(rc))
3585 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to create worker threads"));
3586
3587 /* Create Link Up Timer */
3588 rc = PDMDevHlpTimerCreate(pDevIns, TMCLOCK_VIRTUAL, virtioNetR3LinkUpTimer, NULL,
3589 TMTIMER_FLAGS_NO_CRIT_SECT | TMTIMER_FLAGS_NO_RING0,
3590 "VirtioNet Link Up", &pThisCC->hLinkUpTimer);
3591 /*
3592 * Attach network driver instance
3593 */
3594 rc = PDMDevHlpDriverAttach(pDevIns, 0, &pThisCC->IBase, &pThisCC->pDrvBase, "Network Port");
3595 if (RT_SUCCESS(rc))
3596 {
3597 pThisCC->pDrv = PDMIBASE_QUERY_INTERFACE(pThisCC->pDrvBase, PDMINETWORKUP);
3598 AssertMsgStmt(pThisCC->pDrv, ("Failed to obtain the PDMINETWORKUP interface!\n"),
3599 rc = VERR_PDM_MISSING_INTERFACE_BELOW);
3600 }
3601 else if ( rc == VERR_PDM_NO_ATTACHED_DRIVER
3602 || rc == VERR_PDM_CFG_MISSING_DRIVER_NAME)
3603 {
3604 Log(("[%s] No attached driver!\n", pThis->szInst));
3605 AssertRCReturn(rc, rc);
3606 }
3607 /*
3608 * Status driver
3609 */
3610 PPDMIBASE pUpBase;
3611 rc = PDMDevHlpDriverAttach(pDevIns, PDM_STATUS_LUN, &pThisCC->IBase, &pUpBase, "Status Port");
3612 if (RT_FAILURE(rc) && rc != VERR_PDM_NO_ATTACHED_DRIVER)
3613 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to attach the status LUN"));
3614
3615 pThisCC->pLedsConnector = PDMIBASE_QUERY_INTERFACE(pUpBase, PDMILEDCONNECTORS);
3616 /*
3617 * Register saved state.
3618 */
3619 rc = PDMDevHlpSSMRegister(pDevIns, VIRTIONET_SAVEDSTATE_VERSION, sizeof(*pThis),
3620 virtioNetR3ModernSaveExec, virtioNetR3ModernDeviceLoadExec);
3621 AssertRCReturn(rc, rc);
3622 /*
3623 * Statistics and debug stuff.
3624 * The /Public/ bits are official and used by session info in the GUI.
3625 */
3626# ifdef VBOX_WITH_STATISTICS
3627 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->StatReceiveBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
3628 "Amount of data received", "/Public/NetAdapter/%u/BytesReceived", uStatNo);
3629 PDMDevHlpSTAMRegisterF(pDevIns, &pThis->StatTransmitBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
3630 "Amount of data transmitted", "/Public/NetAdapter/%u/BytesTransmitted", uStatNo);
3631 PDMDevHlpSTAMRegisterF(pDevIns, &pDevIns->iInstance, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_NONE,
3632 "Device instance number", "/Public/NetAdapter/%u/%s", uStatNo, pDevIns->pReg->szName);
3633
3634 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatReceiveBytes, STAMTYPE_COUNTER, "ReceiveBytes", STAMUNIT_BYTES, "Amount of data received");
3635 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmitBytes, STAMTYPE_COUNTER, "TransmitBytes", STAMUNIT_BYTES, "Amount of data transmitted");
3636 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatReceiveGSO, STAMTYPE_COUNTER, "Packets/ReceiveGSO", STAMUNIT_COUNT, "Number of received GSO packets");
3637 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmitPackets, STAMTYPE_COUNTER, "Packets/Transmit", STAMUNIT_COUNT, "Number of sent packets");
3638 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmitGSO, STAMTYPE_COUNTER, "Packets/Transmit-Gso", STAMUNIT_COUNT, "Number of sent GSO packets");
3639 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmitCSum, STAMTYPE_COUNTER, "Packets/Transmit-Csum", STAMUNIT_COUNT, "Number of completed TX checksums");
3640 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatReceive, STAMTYPE_PROFILE, "Receive/Total", STAMUNIT_TICKS_PER_CALL, "Profiling receive");
3641 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatReceiveStore, STAMTYPE_PROFILE, "Receive/Store", STAMUNIT_TICKS_PER_CALL, "Profiling receive storing");
3642 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRxOverflow, STAMTYPE_PROFILE, "RxOverflow", STAMUNIT_TICKS_PER_OCCURENCE, "Profiling RX overflows");
3643 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRxOverflowWakeup, STAMTYPE_COUNTER, "RxOverflowWakeup", STAMUNIT_OCCURENCES, "Nr of RX overflow wakeups");
3644 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmit, STAMTYPE_PROFILE, "Transmit/Total", STAMUNIT_TICKS_PER_CALL, "Profiling transmits in HC");
3645 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmitSend, STAMTYPE_PROFILE, "Transmit/Send", STAMUNIT_TICKS_PER_CALL, "Profiling send transmit in HC");
3646 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmitByNetwork, STAMTYPE_COUNTER, "Transmit/ByNetwork", STAMUNIT_COUNT, "Network-initiated transmissions");
3647 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTransmitByThread, STAMTYPE_COUNTER, "Transmit/ByThread", STAMUNIT_COUNT, "Thread-initiated transmissions");
3648# endif
3649 /*
3650 * Register the debugger info callback (ignore errors).
3651 */
3652 char szTmp[128];
3653 rc = PDMDevHlpDBGFInfoRegister(pDevIns, "virtio-net", "Display virtio-net info (help, net, features, state, pointers, queues, all)", virtioNetR3Info);
3654 if (RT_FAILURE(rc))
3655 LogRel(("Failed to register DBGF info for device %s\n", szTmp));
3656 return rc;
3657}
3658
3659#else /* !IN_RING3 */
3660
3661/**
3662 * @callback_method_impl{PDMDEVREGR0,pfnConstruct}
3663 */
3664static DECLCALLBACK(int) virtioNetRZConstruct(PPDMDEVINS pDevIns)
3665{
3666 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
3667 PVIRTIONET pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIONET);
3668 PVIRTIONETCC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIONETCC);
3669 pThisCC->Virtio.pfnVirtqNotified = virtioNetVirtqNotified;
3670 return virtioCoreRZInit(pDevIns, &pThis->Virtio);
3671}
3672
3673#endif /* !IN_RING3 */
3674
3675/**
3676 * The device registration structure.
3677 */
3678const PDMDEVREG g_DeviceVirtioNet =
3679{
3680 /* .uVersion = */ PDM_DEVREG_VERSION,
3681 /* .uReserved0 = */ 0,
3682 /* .szName = */ "virtio-net",
3683 /* .fFlags = */ PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_NEW_STYLE | PDM_DEVREG_FLAGS_RZ,
3684 /* .fClass = */ PDM_DEVREG_CLASS_NETWORK,
3685 /* .cMaxInstances = */ ~0U,
3686 /* .uSharedVersion = */ 42,
3687 /* .cbInstanceShared = */ sizeof(VIRTIONET),
3688 /* .cbInstanceCC = */ sizeof(VIRTIONETCC),
3689 /* .cbInstanceRC = */ sizeof(VIRTIONETRC),
3690 /* .cMaxPciDevices = */ 1,
3691 /* .cMaxMsixVectors = */ VBOX_MSIX_MAX_ENTRIES,
3692 /* .pszDescription = */ "Virtio Host NET.\n",
3693#if defined(IN_RING3)
3694 /* .pszRCMod = */ "VBoxDDRC.rc",
3695 /* .pszR0Mod = */ "VBoxDDR0.r0",
3696 /* .pfnConstruct = */ virtioNetR3Construct,
3697 /* .pfnDestruct = */ virtioNetR3Destruct,
3698 /* .pfnRelocate = */ NULL,
3699 /* .pfnMemSetup = */ NULL,
3700 /* .pfnPowerOn = */ NULL,
3701 /* .pfnReset = */ NULL,
3702 /* .pfnSuspend = */ virtioNetWakeupRxBufWaiter,
3703 /* .pfnResume = */ NULL,
3704 /* .pfnAttach = */ virtioNetR3Attach,
3705 /* .pfnDetach = */ virtioNetR3Detach,
3706 /* .pfnQueryInterface = */ NULL,
3707 /* .pfnInitComplete = */ NULL,
3708 /* .pfnPowerOff = */ virtioNetWakeupRxBufWaiter,
3709 /* .pfnSoftReset = */ NULL,
3710 /* .pfnReserved0 = */ NULL,
3711 /* .pfnReserved1 = */ NULL,
3712 /* .pfnReserved2 = */ NULL,
3713 /* .pfnReserved3 = */ NULL,
3714 /* .pfnReserved4 = */ NULL,
3715 /* .pfnReserved5 = */ NULL,
3716 /* .pfnReserved6 = */ NULL,
3717 /* .pfnReserved7 = */ NULL,
3718#elif defined(IN_RING0)
3719 /* .pfnEarlyConstruct = */ NULL,
3720 /* .pfnConstruct = */ virtioNetRZConstruct,
3721 /* .pfnDestruct = */ NULL,
3722 /* .pfnFinalDestruct = */ NULL,
3723 /* .pfnRequest = */ NULL,
3724 /* .pfnReserved0 = */ NULL,
3725 /* .pfnReserved1 = */ NULL,
3726 /* .pfnReserved2 = */ NULL,
3727 /* .pfnReserved3 = */ NULL,
3728 /* .pfnReserved4 = */ NULL,
3729 /* .pfnReserved5 = */ NULL,
3730 /* .pfnReserved6 = */ NULL,
3731 /* .pfnReserved7 = */ NULL,
3732#elif defined(IN_RC)
3733 /* .pfnConstruct = */ virtioNetRZConstruct,
3734 /* .pfnReserved0 = */ NULL,
3735 /* .pfnReserved1 = */ NULL,
3736 /* .pfnReserved2 = */ NULL,
3737 /* .pfnReserved3 = */ NULL,
3738 /* .pfnReserved4 = */ NULL,
3739 /* .pfnReserved5 = */ NULL,
3740 /* .pfnReserved6 = */ NULL,
3741 /* .pfnReserved7 = */ NULL,
3742#else
3743# error "Not in IN_RING3, IN_RING0 or IN_RC!"
3744#endif
3745 /* .uVersionEnd = */ PDM_DEVREG_VERSION
3746};
3747
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use