xref: /dpdk/drivers/net/virtio/virtio_ethdev.c (revision dafc04c1)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2016 Intel Corporation
3  */
4 
5 #include <stdint.h>
6 #include <string.h>
7 #include <stdio.h>
8 #include <errno.h>
9 #include <unistd.h>
10 
11 #include <rte_ethdev_driver.h>
12 #include <rte_ethdev_pci.h>
13 #include <rte_memcpy.h>
14 #include <rte_string_fns.h>
15 #include <rte_memzone.h>
16 #include <rte_malloc.h>
17 #include <rte_branch_prediction.h>
18 #include <rte_pci.h>
19 #include <rte_bus_pci.h>
20 #include <rte_ether.h>
21 #include <rte_ip.h>
22 #include <rte_arp.h>
23 #include <rte_common.h>
24 #include <rte_errno.h>
25 #include <rte_cpuflags.h>
26 
27 #include <rte_memory.h>
28 #include <rte_eal.h>
29 #include <rte_dev.h>
30 #include <rte_cycles.h>
31 #include <rte_kvargs.h>
32 
33 #include "virtio_ethdev.h"
34 #include "virtio_pci.h"
35 #include "virtio_logs.h"
36 #include "virtqueue.h"
37 #include "virtio_rxtx.h"
38 
39 static int eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev);
40 static int  virtio_dev_configure(struct rte_eth_dev *dev);
41 static int  virtio_dev_start(struct rte_eth_dev *dev);
42 static void virtio_dev_stop(struct rte_eth_dev *dev);
43 static void virtio_dev_promiscuous_enable(struct rte_eth_dev *dev);
44 static void virtio_dev_promiscuous_disable(struct rte_eth_dev *dev);
45 static void virtio_dev_allmulticast_enable(struct rte_eth_dev *dev);
46 static void virtio_dev_allmulticast_disable(struct rte_eth_dev *dev);
47 static void virtio_dev_info_get(struct rte_eth_dev *dev,
48 				struct rte_eth_dev_info *dev_info);
49 static int virtio_dev_link_update(struct rte_eth_dev *dev,
50 	int wait_to_complete);
51 static int virtio_dev_vlan_offload_set(struct rte_eth_dev *dev, int mask);
52 
53 static void virtio_set_hwaddr(struct virtio_hw *hw);
54 static void virtio_get_hwaddr(struct virtio_hw *hw);
55 
56 static int virtio_dev_stats_get(struct rte_eth_dev *dev,
57 				 struct rte_eth_stats *stats);
58 static int virtio_dev_xstats_get(struct rte_eth_dev *dev,
59 				 struct rte_eth_xstat *xstats, unsigned n);
60 static int virtio_dev_xstats_get_names(struct rte_eth_dev *dev,
61 				       struct rte_eth_xstat_name *xstats_names,
62 				       unsigned limit);
63 static void virtio_dev_stats_reset(struct rte_eth_dev *dev);
64 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev);
65 static int virtio_vlan_filter_set(struct rte_eth_dev *dev,
66 				uint16_t vlan_id, int on);
67 static int virtio_mac_addr_add(struct rte_eth_dev *dev,
68 				struct ether_addr *mac_addr,
69 				uint32_t index, uint32_t vmdq);
70 static void virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index);
71 static int virtio_mac_addr_set(struct rte_eth_dev *dev,
72 				struct ether_addr *mac_addr);
73 
74 static int virtio_intr_enable(struct rte_eth_dev *dev);
75 static int virtio_intr_disable(struct rte_eth_dev *dev);
76 
77 static int virtio_dev_queue_stats_mapping_set(
78 	struct rte_eth_dev *eth_dev,
79 	uint16_t queue_id,
80 	uint8_t stat_idx,
81 	uint8_t is_rx);
82 
83 int virtio_logtype_init;
84 int virtio_logtype_driver;
85 
86 static void virtio_notify_peers(struct rte_eth_dev *dev);
87 static void virtio_ack_link_announce(struct rte_eth_dev *dev);
88 
89 /*
90  * The set of PCI devices this driver supports
91  */
92 static const struct rte_pci_id pci_id_virtio_map[] = {
93 	{ RTE_PCI_DEVICE(VIRTIO_PCI_VENDORID, VIRTIO_PCI_LEGACY_DEVICEID_NET) },
94 	{ RTE_PCI_DEVICE(VIRTIO_PCI_VENDORID, VIRTIO_PCI_MODERN_DEVICEID_NET) },
95 	{ .vendor_id = 0, /* sentinel */ },
96 };
97 
98 struct rte_virtio_xstats_name_off {
99 	char name[RTE_ETH_XSTATS_NAME_SIZE];
100 	unsigned offset;
101 };
102 
103 /* [rt]x_qX_ is prepended to the name string here */
104 static const struct rte_virtio_xstats_name_off rte_virtio_rxq_stat_strings[] = {
105 	{"good_packets",           offsetof(struct virtnet_rx, stats.packets)},
106 	{"good_bytes",             offsetof(struct virtnet_rx, stats.bytes)},
107 	{"errors",                 offsetof(struct virtnet_rx, stats.errors)},
108 	{"multicast_packets",      offsetof(struct virtnet_rx, stats.multicast)},
109 	{"broadcast_packets",      offsetof(struct virtnet_rx, stats.broadcast)},
110 	{"undersize_packets",      offsetof(struct virtnet_rx, stats.size_bins[0])},
111 	{"size_64_packets",        offsetof(struct virtnet_rx, stats.size_bins[1])},
112 	{"size_65_127_packets",    offsetof(struct virtnet_rx, stats.size_bins[2])},
113 	{"size_128_255_packets",   offsetof(struct virtnet_rx, stats.size_bins[3])},
114 	{"size_256_511_packets",   offsetof(struct virtnet_rx, stats.size_bins[4])},
115 	{"size_512_1023_packets",  offsetof(struct virtnet_rx, stats.size_bins[5])},
116 	{"size_1024_1518_packets", offsetof(struct virtnet_rx, stats.size_bins[6])},
117 	{"size_1519_max_packets",  offsetof(struct virtnet_rx, stats.size_bins[7])},
118 };
119 
120 /* [rt]x_qX_ is prepended to the name string here */
121 static const struct rte_virtio_xstats_name_off rte_virtio_txq_stat_strings[] = {
122 	{"good_packets",           offsetof(struct virtnet_tx, stats.packets)},
123 	{"good_bytes",             offsetof(struct virtnet_tx, stats.bytes)},
124 	{"errors",                 offsetof(struct virtnet_tx, stats.errors)},
125 	{"multicast_packets",      offsetof(struct virtnet_tx, stats.multicast)},
126 	{"broadcast_packets",      offsetof(struct virtnet_tx, stats.broadcast)},
127 	{"undersize_packets",      offsetof(struct virtnet_tx, stats.size_bins[0])},
128 	{"size_64_packets",        offsetof(struct virtnet_tx, stats.size_bins[1])},
129 	{"size_65_127_packets",    offsetof(struct virtnet_tx, stats.size_bins[2])},
130 	{"size_128_255_packets",   offsetof(struct virtnet_tx, stats.size_bins[3])},
131 	{"size_256_511_packets",   offsetof(struct virtnet_tx, stats.size_bins[4])},
132 	{"size_512_1023_packets",  offsetof(struct virtnet_tx, stats.size_bins[5])},
133 	{"size_1024_1518_packets", offsetof(struct virtnet_tx, stats.size_bins[6])},
134 	{"size_1519_max_packets",  offsetof(struct virtnet_tx, stats.size_bins[7])},
135 };
136 
137 #define VIRTIO_NB_RXQ_XSTATS (sizeof(rte_virtio_rxq_stat_strings) / \
138 			    sizeof(rte_virtio_rxq_stat_strings[0]))
139 #define VIRTIO_NB_TXQ_XSTATS (sizeof(rte_virtio_txq_stat_strings) / \
140 			    sizeof(rte_virtio_txq_stat_strings[0]))
141 
142 struct virtio_hw_internal virtio_hw_internal[RTE_MAX_ETHPORTS];
143 
144 static int
145 virtio_send_command(struct virtnet_ctl *cvq, struct virtio_pmd_ctrl *ctrl,
146 		int *dlen, int pkt_num)
147 {
148 	uint32_t head, i;
149 	int k, sum = 0;
150 	virtio_net_ctrl_ack status = ~0;
151 	struct virtio_pmd_ctrl *result;
152 	struct virtqueue *vq;
153 
154 	ctrl->status = status;
155 
156 	if (!cvq || !cvq->vq) {
157 		PMD_INIT_LOG(ERR, "Control queue is not supported.");
158 		return -1;
159 	}
160 
161 	rte_spinlock_lock(&cvq->lock);
162 	vq = cvq->vq;
163 	head = vq->vq_desc_head_idx;
164 
165 	PMD_INIT_LOG(DEBUG, "vq->vq_desc_head_idx = %d, status = %d, "
166 		"vq->hw->cvq = %p vq = %p",
167 		vq->vq_desc_head_idx, status, vq->hw->cvq, vq);
168 
169 	if (vq->vq_free_cnt < pkt_num + 2 || pkt_num < 1) {
170 		rte_spinlock_unlock(&cvq->lock);
171 		return -1;
172 	}
173 
174 	memcpy(cvq->virtio_net_hdr_mz->addr, ctrl,
175 		sizeof(struct virtio_pmd_ctrl));
176 
177 	/*
178 	 * Format is enforced in qemu code:
179 	 * One TX packet for header;
180 	 * At least one TX packet per argument;
181 	 * One RX packet for ACK.
182 	 */
183 	vq->vq_ring.desc[head].flags = VRING_DESC_F_NEXT;
184 	vq->vq_ring.desc[head].addr = cvq->virtio_net_hdr_mem;
185 	vq->vq_ring.desc[head].len = sizeof(struct virtio_net_ctrl_hdr);
186 	vq->vq_free_cnt--;
187 	i = vq->vq_ring.desc[head].next;
188 
189 	for (k = 0; k < pkt_num; k++) {
190 		vq->vq_ring.desc[i].flags = VRING_DESC_F_NEXT;
191 		vq->vq_ring.desc[i].addr = cvq->virtio_net_hdr_mem
192 			+ sizeof(struct virtio_net_ctrl_hdr)
193 			+ sizeof(ctrl->status) + sizeof(uint8_t)*sum;
194 		vq->vq_ring.desc[i].len = dlen[k];
195 		sum += dlen[k];
196 		vq->vq_free_cnt--;
197 		i = vq->vq_ring.desc[i].next;
198 	}
199 
200 	vq->vq_ring.desc[i].flags = VRING_DESC_F_WRITE;
201 	vq->vq_ring.desc[i].addr = cvq->virtio_net_hdr_mem
202 			+ sizeof(struct virtio_net_ctrl_hdr);
203 	vq->vq_ring.desc[i].len = sizeof(ctrl->status);
204 	vq->vq_free_cnt--;
205 
206 	vq->vq_desc_head_idx = vq->vq_ring.desc[i].next;
207 
208 	vq_update_avail_ring(vq, head);
209 	vq_update_avail_idx(vq);
210 
211 	PMD_INIT_LOG(DEBUG, "vq->vq_queue_index = %d", vq->vq_queue_index);
212 
213 	virtqueue_notify(vq);
214 
215 	rte_rmb();
216 	while (VIRTQUEUE_NUSED(vq) == 0) {
217 		rte_rmb();
218 		usleep(100);
219 	}
220 
221 	while (VIRTQUEUE_NUSED(vq)) {
222 		uint32_t idx, desc_idx, used_idx;
223 		struct vring_used_elem *uep;
224 
225 		used_idx = (uint32_t)(vq->vq_used_cons_idx
226 				& (vq->vq_nentries - 1));
227 		uep = &vq->vq_ring.used->ring[used_idx];
228 		idx = (uint32_t) uep->id;
229 		desc_idx = idx;
230 
231 		while (vq->vq_ring.desc[desc_idx].flags & VRING_DESC_F_NEXT) {
232 			desc_idx = vq->vq_ring.desc[desc_idx].next;
233 			vq->vq_free_cnt++;
234 		}
235 
236 		vq->vq_ring.desc[desc_idx].next = vq->vq_desc_head_idx;
237 		vq->vq_desc_head_idx = idx;
238 
239 		vq->vq_used_cons_idx++;
240 		vq->vq_free_cnt++;
241 	}
242 
243 	PMD_INIT_LOG(DEBUG, "vq->vq_free_cnt=%d\nvq->vq_desc_head_idx=%d",
244 			vq->vq_free_cnt, vq->vq_desc_head_idx);
245 
246 	result = cvq->virtio_net_hdr_mz->addr;
247 
248 	rte_spinlock_unlock(&cvq->lock);
249 	return result->status;
250 }
251 
252 static int
253 virtio_set_multiple_queues(struct rte_eth_dev *dev, uint16_t nb_queues)
254 {
255 	struct virtio_hw *hw = dev->data->dev_private;
256 	struct virtio_pmd_ctrl ctrl;
257 	int dlen[1];
258 	int ret;
259 
260 	ctrl.hdr.class = VIRTIO_NET_CTRL_MQ;
261 	ctrl.hdr.cmd = VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET;
262 	memcpy(ctrl.data, &nb_queues, sizeof(uint16_t));
263 
264 	dlen[0] = sizeof(uint16_t);
265 
266 	ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
267 	if (ret) {
268 		PMD_INIT_LOG(ERR, "Multiqueue configured but send command "
269 			  "failed, this is too late now...");
270 		return -EINVAL;
271 	}
272 
273 	return 0;
274 }
275 
276 static void
277 virtio_dev_queue_release(void *queue __rte_unused)
278 {
279 	/* do nothing */
280 }
281 
282 static uint16_t
283 virtio_get_nr_vq(struct virtio_hw *hw)
284 {
285 	uint16_t nr_vq = hw->max_queue_pairs * 2;
286 
287 	if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ))
288 		nr_vq += 1;
289 
290 	return nr_vq;
291 }
292 
293 static void
294 virtio_init_vring(struct virtqueue *vq)
295 {
296 	int size = vq->vq_nentries;
297 	struct vring *vr = &vq->vq_ring;
298 	uint8_t *ring_mem = vq->vq_ring_virt_mem;
299 
300 	PMD_INIT_FUNC_TRACE();
301 
302 	/*
303 	 * Reinitialise since virtio port might have been stopped and restarted
304 	 */
305 	memset(ring_mem, 0, vq->vq_ring_size);
306 	vring_init(vr, size, ring_mem, VIRTIO_PCI_VRING_ALIGN);
307 	vq->vq_used_cons_idx = 0;
308 	vq->vq_desc_head_idx = 0;
309 	vq->vq_avail_idx = 0;
310 	vq->vq_desc_tail_idx = (uint16_t)(vq->vq_nentries - 1);
311 	vq->vq_free_cnt = vq->vq_nentries;
312 	memset(vq->vq_descx, 0, sizeof(struct vq_desc_extra) * vq->vq_nentries);
313 
314 	vring_desc_init(vr->desc, size);
315 
316 	/*
317 	 * Disable device(host) interrupting guest
318 	 */
319 	virtqueue_disable_intr(vq);
320 }
321 
322 static int
323 virtio_init_queue(struct rte_eth_dev *dev, uint16_t vtpci_queue_idx)
324 {
325 	char vq_name[VIRTQUEUE_MAX_NAME_SZ];
326 	char vq_hdr_name[VIRTQUEUE_MAX_NAME_SZ];
327 	const struct rte_memzone *mz = NULL, *hdr_mz = NULL;
328 	unsigned int vq_size, size;
329 	struct virtio_hw *hw = dev->data->dev_private;
330 	struct virtnet_rx *rxvq = NULL;
331 	struct virtnet_tx *txvq = NULL;
332 	struct virtnet_ctl *cvq = NULL;
333 	struct virtqueue *vq;
334 	size_t sz_hdr_mz = 0;
335 	void *sw_ring = NULL;
336 	int queue_type = virtio_get_queue_type(hw, vtpci_queue_idx);
337 	int ret;
338 	int numa_node = dev->device->numa_node;
339 
340 	PMD_INIT_LOG(INFO, "setting up queue: %u on NUMA node %d",
341 			vtpci_queue_idx, numa_node);
342 
343 	/*
344 	 * Read the virtqueue size from the Queue Size field
345 	 * Always power of 2 and if 0 virtqueue does not exist
346 	 */
347 	vq_size = VTPCI_OPS(hw)->get_queue_num(hw, vtpci_queue_idx);
348 	PMD_INIT_LOG(DEBUG, "vq_size: %u", vq_size);
349 	if (vq_size == 0) {
350 		PMD_INIT_LOG(ERR, "virtqueue does not exist");
351 		return -EINVAL;
352 	}
353 
354 	if (!rte_is_power_of_2(vq_size)) {
355 		PMD_INIT_LOG(ERR, "virtqueue size is not powerof 2");
356 		return -EINVAL;
357 	}
358 
359 	snprintf(vq_name, sizeof(vq_name), "port%d_vq%d",
360 		 dev->data->port_id, vtpci_queue_idx);
361 
362 	size = RTE_ALIGN_CEIL(sizeof(*vq) +
363 				vq_size * sizeof(struct vq_desc_extra),
364 				RTE_CACHE_LINE_SIZE);
365 	if (queue_type == VTNET_TQ) {
366 		/*
367 		 * For each xmit packet, allocate a virtio_net_hdr
368 		 * and indirect ring elements
369 		 */
370 		sz_hdr_mz = vq_size * sizeof(struct virtio_tx_region);
371 	} else if (queue_type == VTNET_CQ) {
372 		/* Allocate a page for control vq command, data and status */
373 		sz_hdr_mz = PAGE_SIZE;
374 	}
375 
376 	vq = rte_zmalloc_socket(vq_name, size, RTE_CACHE_LINE_SIZE,
377 				numa_node);
378 	if (vq == NULL) {
379 		PMD_INIT_LOG(ERR, "can not allocate vq");
380 		return -ENOMEM;
381 	}
382 	hw->vqs[vtpci_queue_idx] = vq;
383 
384 	vq->hw = hw;
385 	vq->vq_queue_index = vtpci_queue_idx;
386 	vq->vq_nentries = vq_size;
387 
388 	/*
389 	 * Reserve a memzone for vring elements
390 	 */
391 	size = vring_size(vq_size, VIRTIO_PCI_VRING_ALIGN);
392 	vq->vq_ring_size = RTE_ALIGN_CEIL(size, VIRTIO_PCI_VRING_ALIGN);
393 	PMD_INIT_LOG(DEBUG, "vring_size: %d, rounded_vring_size: %d",
394 		     size, vq->vq_ring_size);
395 
396 	mz = rte_memzone_reserve_aligned(vq_name, vq->vq_ring_size,
397 			numa_node, RTE_MEMZONE_IOVA_CONTIG,
398 			VIRTIO_PCI_VRING_ALIGN);
399 	if (mz == NULL) {
400 		if (rte_errno == EEXIST)
401 			mz = rte_memzone_lookup(vq_name);
402 		if (mz == NULL) {
403 			ret = -ENOMEM;
404 			goto fail_q_alloc;
405 		}
406 	}
407 
408 	memset(mz->addr, 0, mz->len);
409 
410 	vq->vq_ring_mem = mz->iova;
411 	vq->vq_ring_virt_mem = mz->addr;
412 	PMD_INIT_LOG(DEBUG, "vq->vq_ring_mem:      0x%" PRIx64,
413 		     (uint64_t)mz->iova);
414 	PMD_INIT_LOG(DEBUG, "vq->vq_ring_virt_mem: 0x%" PRIx64,
415 		     (uint64_t)(uintptr_t)mz->addr);
416 
417 	virtio_init_vring(vq);
418 
419 	if (sz_hdr_mz) {
420 		snprintf(vq_hdr_name, sizeof(vq_hdr_name), "port%d_vq%d_hdr",
421 			 dev->data->port_id, vtpci_queue_idx);
422 		hdr_mz = rte_memzone_reserve_aligned(vq_hdr_name, sz_hdr_mz,
423 				numa_node, RTE_MEMZONE_IOVA_CONTIG,
424 				RTE_CACHE_LINE_SIZE);
425 		if (hdr_mz == NULL) {
426 			if (rte_errno == EEXIST)
427 				hdr_mz = rte_memzone_lookup(vq_hdr_name);
428 			if (hdr_mz == NULL) {
429 				ret = -ENOMEM;
430 				goto fail_q_alloc;
431 			}
432 		}
433 	}
434 
435 	if (queue_type == VTNET_RQ) {
436 		size_t sz_sw = (RTE_PMD_VIRTIO_RX_MAX_BURST + vq_size) *
437 			       sizeof(vq->sw_ring[0]);
438 
439 		sw_ring = rte_zmalloc_socket("sw_ring", sz_sw,
440 				RTE_CACHE_LINE_SIZE, numa_node);
441 		if (!sw_ring) {
442 			PMD_INIT_LOG(ERR, "can not allocate RX soft ring");
443 			ret = -ENOMEM;
444 			goto fail_q_alloc;
445 		}
446 
447 		vq->sw_ring = sw_ring;
448 		rxvq = &vq->rxq;
449 		rxvq->vq = vq;
450 		rxvq->port_id = dev->data->port_id;
451 		rxvq->mz = mz;
452 	} else if (queue_type == VTNET_TQ) {
453 		txvq = &vq->txq;
454 		txvq->vq = vq;
455 		txvq->port_id = dev->data->port_id;
456 		txvq->mz = mz;
457 		txvq->virtio_net_hdr_mz = hdr_mz;
458 		txvq->virtio_net_hdr_mem = hdr_mz->iova;
459 	} else if (queue_type == VTNET_CQ) {
460 		cvq = &vq->cq;
461 		cvq->vq = vq;
462 		cvq->mz = mz;
463 		cvq->virtio_net_hdr_mz = hdr_mz;
464 		cvq->virtio_net_hdr_mem = hdr_mz->iova;
465 		memset(cvq->virtio_net_hdr_mz->addr, 0, PAGE_SIZE);
466 
467 		hw->cvq = cvq;
468 	}
469 
470 	/* For virtio_user case (that is when hw->dev is NULL), we use
471 	 * virtual address. And we need properly set _offset_, please see
472 	 * VIRTIO_MBUF_DATA_DMA_ADDR in virtqueue.h for more information.
473 	 */
474 	if (!hw->virtio_user_dev)
475 		vq->offset = offsetof(struct rte_mbuf, buf_iova);
476 	else {
477 		vq->vq_ring_mem = (uintptr_t)mz->addr;
478 		vq->offset = offsetof(struct rte_mbuf, buf_addr);
479 		if (queue_type == VTNET_TQ)
480 			txvq->virtio_net_hdr_mem = (uintptr_t)hdr_mz->addr;
481 		else if (queue_type == VTNET_CQ)
482 			cvq->virtio_net_hdr_mem = (uintptr_t)hdr_mz->addr;
483 	}
484 
485 	if (queue_type == VTNET_TQ) {
486 		struct virtio_tx_region *txr;
487 		unsigned int i;
488 
489 		txr = hdr_mz->addr;
490 		memset(txr, 0, vq_size * sizeof(*txr));
491 		for (i = 0; i < vq_size; i++) {
492 			struct vring_desc *start_dp = txr[i].tx_indir;
493 
494 			vring_desc_init(start_dp, RTE_DIM(txr[i].tx_indir));
495 
496 			/* first indirect descriptor is always the tx header */
497 			start_dp->addr = txvq->virtio_net_hdr_mem
498 				+ i * sizeof(*txr)
499 				+ offsetof(struct virtio_tx_region, tx_hdr);
500 
501 			start_dp->len = hw->vtnet_hdr_size;
502 			start_dp->flags = VRING_DESC_F_NEXT;
503 		}
504 	}
505 
506 	if (VTPCI_OPS(hw)->setup_queue(hw, vq) < 0) {
507 		PMD_INIT_LOG(ERR, "setup_queue failed");
508 		return -EINVAL;
509 	}
510 
511 	return 0;
512 
513 fail_q_alloc:
514 	rte_free(sw_ring);
515 	rte_memzone_free(hdr_mz);
516 	rte_memzone_free(mz);
517 	rte_free(vq);
518 
519 	return ret;
520 }
521 
522 static void
523 virtio_free_queues(struct virtio_hw *hw)
524 {
525 	uint16_t nr_vq = virtio_get_nr_vq(hw);
526 	struct virtqueue *vq;
527 	int queue_type;
528 	uint16_t i;
529 
530 	if (hw->vqs == NULL)
531 		return;
532 
533 	for (i = 0; i < nr_vq; i++) {
534 		vq = hw->vqs[i];
535 		if (!vq)
536 			continue;
537 
538 		queue_type = virtio_get_queue_type(hw, i);
539 		if (queue_type == VTNET_RQ) {
540 			rte_free(vq->sw_ring);
541 			rte_memzone_free(vq->rxq.mz);
542 		} else if (queue_type == VTNET_TQ) {
543 			rte_memzone_free(vq->txq.mz);
544 			rte_memzone_free(vq->txq.virtio_net_hdr_mz);
545 		} else {
546 			rte_memzone_free(vq->cq.mz);
547 			rte_memzone_free(vq->cq.virtio_net_hdr_mz);
548 		}
549 
550 		rte_free(vq);
551 		hw->vqs[i] = NULL;
552 	}
553 
554 	rte_free(hw->vqs);
555 	hw->vqs = NULL;
556 }
557 
558 static int
559 virtio_alloc_queues(struct rte_eth_dev *dev)
560 {
561 	struct virtio_hw *hw = dev->data->dev_private;
562 	uint16_t nr_vq = virtio_get_nr_vq(hw);
563 	uint16_t i;
564 	int ret;
565 
566 	hw->vqs = rte_zmalloc(NULL, sizeof(struct virtqueue *) * nr_vq, 0);
567 	if (!hw->vqs) {
568 		PMD_INIT_LOG(ERR, "failed to allocate vqs");
569 		return -ENOMEM;
570 	}
571 
572 	for (i = 0; i < nr_vq; i++) {
573 		ret = virtio_init_queue(dev, i);
574 		if (ret < 0) {
575 			virtio_free_queues(hw);
576 			return ret;
577 		}
578 	}
579 
580 	return 0;
581 }
582 
583 static void virtio_queues_unbind_intr(struct rte_eth_dev *dev);
584 
585 static void
586 virtio_dev_close(struct rte_eth_dev *dev)
587 {
588 	struct virtio_hw *hw = dev->data->dev_private;
589 	struct rte_intr_conf *intr_conf = &dev->data->dev_conf.intr_conf;
590 
591 	PMD_INIT_LOG(DEBUG, "virtio_dev_close");
592 
593 	if (!hw->opened)
594 		return;
595 	hw->opened = false;
596 
597 	/* reset the NIC */
598 	if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
599 		VTPCI_OPS(hw)->set_config_irq(hw, VIRTIO_MSI_NO_VECTOR);
600 	if (intr_conf->rxq)
601 		virtio_queues_unbind_intr(dev);
602 
603 	if (intr_conf->lsc || intr_conf->rxq) {
604 		virtio_intr_disable(dev);
605 		rte_intr_efd_disable(dev->intr_handle);
606 		rte_free(dev->intr_handle->intr_vec);
607 		dev->intr_handle->intr_vec = NULL;
608 	}
609 
610 	vtpci_reset(hw);
611 	virtio_dev_free_mbufs(dev);
612 	virtio_free_queues(hw);
613 }
614 
615 static void
616 virtio_dev_promiscuous_enable(struct rte_eth_dev *dev)
617 {
618 	struct virtio_hw *hw = dev->data->dev_private;
619 	struct virtio_pmd_ctrl ctrl;
620 	int dlen[1];
621 	int ret;
622 
623 	if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
624 		PMD_INIT_LOG(INFO, "host does not support rx control");
625 		return;
626 	}
627 
628 	ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
629 	ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
630 	ctrl.data[0] = 1;
631 	dlen[0] = 1;
632 
633 	ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
634 	if (ret)
635 		PMD_INIT_LOG(ERR, "Failed to enable promisc");
636 }
637 
638 static void
639 virtio_dev_promiscuous_disable(struct rte_eth_dev *dev)
640 {
641 	struct virtio_hw *hw = dev->data->dev_private;
642 	struct virtio_pmd_ctrl ctrl;
643 	int dlen[1];
644 	int ret;
645 
646 	if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
647 		PMD_INIT_LOG(INFO, "host does not support rx control");
648 		return;
649 	}
650 
651 	ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
652 	ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_PROMISC;
653 	ctrl.data[0] = 0;
654 	dlen[0] = 1;
655 
656 	ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
657 	if (ret)
658 		PMD_INIT_LOG(ERR, "Failed to disable promisc");
659 }
660 
661 static void
662 virtio_dev_allmulticast_enable(struct rte_eth_dev *dev)
663 {
664 	struct virtio_hw *hw = dev->data->dev_private;
665 	struct virtio_pmd_ctrl ctrl;
666 	int dlen[1];
667 	int ret;
668 
669 	if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
670 		PMD_INIT_LOG(INFO, "host does not support rx control");
671 		return;
672 	}
673 
674 	ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
675 	ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
676 	ctrl.data[0] = 1;
677 	dlen[0] = 1;
678 
679 	ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
680 	if (ret)
681 		PMD_INIT_LOG(ERR, "Failed to enable allmulticast");
682 }
683 
684 static void
685 virtio_dev_allmulticast_disable(struct rte_eth_dev *dev)
686 {
687 	struct virtio_hw *hw = dev->data->dev_private;
688 	struct virtio_pmd_ctrl ctrl;
689 	int dlen[1];
690 	int ret;
691 
692 	if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_RX)) {
693 		PMD_INIT_LOG(INFO, "host does not support rx control");
694 		return;
695 	}
696 
697 	ctrl.hdr.class = VIRTIO_NET_CTRL_RX;
698 	ctrl.hdr.cmd = VIRTIO_NET_CTRL_RX_ALLMULTI;
699 	ctrl.data[0] = 0;
700 	dlen[0] = 1;
701 
702 	ret = virtio_send_command(hw->cvq, &ctrl, dlen, 1);
703 	if (ret)
704 		PMD_INIT_LOG(ERR, "Failed to disable allmulticast");
705 }
706 
707 #define VLAN_TAG_LEN           4    /* 802.3ac tag (not DMA'd) */
708 static int
709 virtio_mtu_set(struct rte_eth_dev *dev, uint16_t mtu)
710 {
711 	struct virtio_hw *hw = dev->data->dev_private;
712 	uint32_t ether_hdr_len = ETHER_HDR_LEN + VLAN_TAG_LEN +
713 				 hw->vtnet_hdr_size;
714 	uint32_t frame_size = mtu + ether_hdr_len;
715 	uint32_t max_frame_size = hw->max_mtu + ether_hdr_len;
716 
717 	max_frame_size = RTE_MIN(max_frame_size, VIRTIO_MAX_RX_PKTLEN);
718 
719 	if (mtu < ETHER_MIN_MTU || frame_size > max_frame_size) {
720 		PMD_INIT_LOG(ERR, "MTU should be between %d and %d",
721 			ETHER_MIN_MTU, max_frame_size - ether_hdr_len);
722 		return -EINVAL;
723 	}
724 	return 0;
725 }
726 
727 static int
728 virtio_dev_rx_queue_intr_enable(struct rte_eth_dev *dev, uint16_t queue_id)
729 {
730 	struct virtnet_rx *rxvq = dev->data->rx_queues[queue_id];
731 	struct virtqueue *vq = rxvq->vq;
732 
733 	virtqueue_enable_intr(vq);
734 	return 0;
735 }
736 
737 static int
738 virtio_dev_rx_queue_intr_disable(struct rte_eth_dev *dev, uint16_t queue_id)
739 {
740 	struct virtnet_rx *rxvq = dev->data->rx_queues[queue_id];
741 	struct virtqueue *vq = rxvq->vq;
742 
743 	virtqueue_disable_intr(vq);
744 	return 0;
745 }
746 
747 /*
748  * dev_ops for virtio, bare necessities for basic operation
749  */
750 static const struct eth_dev_ops virtio_eth_dev_ops = {
751 	.dev_configure           = virtio_dev_configure,
752 	.dev_start               = virtio_dev_start,
753 	.dev_stop                = virtio_dev_stop,
754 	.dev_close               = virtio_dev_close,
755 	.promiscuous_enable      = virtio_dev_promiscuous_enable,
756 	.promiscuous_disable     = virtio_dev_promiscuous_disable,
757 	.allmulticast_enable     = virtio_dev_allmulticast_enable,
758 	.allmulticast_disable    = virtio_dev_allmulticast_disable,
759 	.mtu_set                 = virtio_mtu_set,
760 	.dev_infos_get           = virtio_dev_info_get,
761 	.stats_get               = virtio_dev_stats_get,
762 	.xstats_get              = virtio_dev_xstats_get,
763 	.xstats_get_names        = virtio_dev_xstats_get_names,
764 	.stats_reset             = virtio_dev_stats_reset,
765 	.xstats_reset            = virtio_dev_stats_reset,
766 	.link_update             = virtio_dev_link_update,
767 	.vlan_offload_set        = virtio_dev_vlan_offload_set,
768 	.rx_queue_setup          = virtio_dev_rx_queue_setup,
769 	.rx_queue_intr_enable    = virtio_dev_rx_queue_intr_enable,
770 	.rx_queue_intr_disable   = virtio_dev_rx_queue_intr_disable,
771 	.rx_queue_release        = virtio_dev_queue_release,
772 	.rx_descriptor_done      = virtio_dev_rx_queue_done,
773 	.tx_queue_setup          = virtio_dev_tx_queue_setup,
774 	.tx_queue_release        = virtio_dev_queue_release,
775 	/* collect stats per queue */
776 	.queue_stats_mapping_set = virtio_dev_queue_stats_mapping_set,
777 	.vlan_filter_set         = virtio_vlan_filter_set,
778 	.mac_addr_add            = virtio_mac_addr_add,
779 	.mac_addr_remove         = virtio_mac_addr_remove,
780 	.mac_addr_set            = virtio_mac_addr_set,
781 };
782 
783 static void
784 virtio_update_stats(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
785 {
786 	unsigned i;
787 
788 	for (i = 0; i < dev->data->nb_tx_queues; i++) {
789 		const struct virtnet_tx *txvq = dev->data->tx_queues[i];
790 		if (txvq == NULL)
791 			continue;
792 
793 		stats->opackets += txvq->stats.packets;
794 		stats->obytes += txvq->stats.bytes;
795 		stats->oerrors += txvq->stats.errors;
796 
797 		if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
798 			stats->q_opackets[i] = txvq->stats.packets;
799 			stats->q_obytes[i] = txvq->stats.bytes;
800 		}
801 	}
802 
803 	for (i = 0; i < dev->data->nb_rx_queues; i++) {
804 		const struct virtnet_rx *rxvq = dev->data->rx_queues[i];
805 		if (rxvq == NULL)
806 			continue;
807 
808 		stats->ipackets += rxvq->stats.packets;
809 		stats->ibytes += rxvq->stats.bytes;
810 		stats->ierrors += rxvq->stats.errors;
811 
812 		if (i < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
813 			stats->q_ipackets[i] = rxvq->stats.packets;
814 			stats->q_ibytes[i] = rxvq->stats.bytes;
815 		}
816 	}
817 
818 	stats->rx_nombuf = dev->data->rx_mbuf_alloc_failed;
819 }
820 
821 static int virtio_dev_xstats_get_names(struct rte_eth_dev *dev,
822 				       struct rte_eth_xstat_name *xstats_names,
823 				       __rte_unused unsigned limit)
824 {
825 	unsigned i;
826 	unsigned count = 0;
827 	unsigned t;
828 
829 	unsigned nstats = dev->data->nb_tx_queues * VIRTIO_NB_TXQ_XSTATS +
830 		dev->data->nb_rx_queues * VIRTIO_NB_RXQ_XSTATS;
831 
832 	if (xstats_names != NULL) {
833 		/* Note: limit checked in rte_eth_xstats_names() */
834 
835 		for (i = 0; i < dev->data->nb_rx_queues; i++) {
836 			struct virtnet_rx *rxvq = dev->data->rx_queues[i];
837 			if (rxvq == NULL)
838 				continue;
839 			for (t = 0; t < VIRTIO_NB_RXQ_XSTATS; t++) {
840 				snprintf(xstats_names[count].name,
841 					sizeof(xstats_names[count].name),
842 					"rx_q%u_%s", i,
843 					rte_virtio_rxq_stat_strings[t].name);
844 				count++;
845 			}
846 		}
847 
848 		for (i = 0; i < dev->data->nb_tx_queues; i++) {
849 			struct virtnet_tx *txvq = dev->data->tx_queues[i];
850 			if (txvq == NULL)
851 				continue;
852 			for (t = 0; t < VIRTIO_NB_TXQ_XSTATS; t++) {
853 				snprintf(xstats_names[count].name,
854 					sizeof(xstats_names[count].name),
855 					"tx_q%u_%s", i,
856 					rte_virtio_txq_stat_strings[t].name);
857 				count++;
858 			}
859 		}
860 		return count;
861 	}
862 	return nstats;
863 }
864 
865 static int
866 virtio_dev_xstats_get(struct rte_eth_dev *dev, struct rte_eth_xstat *xstats,
867 		      unsigned n)
868 {
869 	unsigned i;
870 	unsigned count = 0;
871 
872 	unsigned nstats = dev->data->nb_tx_queues * VIRTIO_NB_TXQ_XSTATS +
873 		dev->data->nb_rx_queues * VIRTIO_NB_RXQ_XSTATS;
874 
875 	if (n < nstats)
876 		return nstats;
877 
878 	for (i = 0; i < dev->data->nb_rx_queues; i++) {
879 		struct virtnet_rx *rxvq = dev->data->rx_queues[i];
880 
881 		if (rxvq == NULL)
882 			continue;
883 
884 		unsigned t;
885 
886 		for (t = 0; t < VIRTIO_NB_RXQ_XSTATS; t++) {
887 			xstats[count].value = *(uint64_t *)(((char *)rxvq) +
888 				rte_virtio_rxq_stat_strings[t].offset);
889 			xstats[count].id = count;
890 			count++;
891 		}
892 	}
893 
894 	for (i = 0; i < dev->data->nb_tx_queues; i++) {
895 		struct virtnet_tx *txvq = dev->data->tx_queues[i];
896 
897 		if (txvq == NULL)
898 			continue;
899 
900 		unsigned t;
901 
902 		for (t = 0; t < VIRTIO_NB_TXQ_XSTATS; t++) {
903 			xstats[count].value = *(uint64_t *)(((char *)txvq) +
904 				rte_virtio_txq_stat_strings[t].offset);
905 			xstats[count].id = count;
906 			count++;
907 		}
908 	}
909 
910 	return count;
911 }
912 
913 static int
914 virtio_dev_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
915 {
916 	virtio_update_stats(dev, stats);
917 
918 	return 0;
919 }
920 
921 static void
922 virtio_dev_stats_reset(struct rte_eth_dev *dev)
923 {
924 	unsigned int i;
925 
926 	for (i = 0; i < dev->data->nb_tx_queues; i++) {
927 		struct virtnet_tx *txvq = dev->data->tx_queues[i];
928 		if (txvq == NULL)
929 			continue;
930 
931 		txvq->stats.packets = 0;
932 		txvq->stats.bytes = 0;
933 		txvq->stats.errors = 0;
934 		txvq->stats.multicast = 0;
935 		txvq->stats.broadcast = 0;
936 		memset(txvq->stats.size_bins, 0,
937 		       sizeof(txvq->stats.size_bins[0]) * 8);
938 	}
939 
940 	for (i = 0; i < dev->data->nb_rx_queues; i++) {
941 		struct virtnet_rx *rxvq = dev->data->rx_queues[i];
942 		if (rxvq == NULL)
943 			continue;
944 
945 		rxvq->stats.packets = 0;
946 		rxvq->stats.bytes = 0;
947 		rxvq->stats.errors = 0;
948 		rxvq->stats.multicast = 0;
949 		rxvq->stats.broadcast = 0;
950 		memset(rxvq->stats.size_bins, 0,
951 		       sizeof(rxvq->stats.size_bins[0]) * 8);
952 	}
953 }
954 
955 static void
956 virtio_set_hwaddr(struct virtio_hw *hw)
957 {
958 	vtpci_write_dev_config(hw,
959 			offsetof(struct virtio_net_config, mac),
960 			&hw->mac_addr, ETHER_ADDR_LEN);
961 }
962 
963 static void
964 virtio_get_hwaddr(struct virtio_hw *hw)
965 {
966 	if (vtpci_with_feature(hw, VIRTIO_NET_F_MAC)) {
967 		vtpci_read_dev_config(hw,
968 			offsetof(struct virtio_net_config, mac),
969 			&hw->mac_addr, ETHER_ADDR_LEN);
970 	} else {
971 		eth_random_addr(&hw->mac_addr[0]);
972 		virtio_set_hwaddr(hw);
973 	}
974 }
975 
976 static int
977 virtio_mac_table_set(struct virtio_hw *hw,
978 		     const struct virtio_net_ctrl_mac *uc,
979 		     const struct virtio_net_ctrl_mac *mc)
980 {
981 	struct virtio_pmd_ctrl ctrl;
982 	int err, len[2];
983 
984 	if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
985 		PMD_DRV_LOG(INFO, "host does not support mac table");
986 		return -1;
987 	}
988 
989 	ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
990 	ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
991 
992 	len[0] = uc->entries * ETHER_ADDR_LEN + sizeof(uc->entries);
993 	memcpy(ctrl.data, uc, len[0]);
994 
995 	len[1] = mc->entries * ETHER_ADDR_LEN + sizeof(mc->entries);
996 	memcpy(ctrl.data + len[0], mc, len[1]);
997 
998 	err = virtio_send_command(hw->cvq, &ctrl, len, 2);
999 	if (err != 0)
1000 		PMD_DRV_LOG(NOTICE, "mac table set failed: %d", err);
1001 	return err;
1002 }
1003 
1004 static int
1005 virtio_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
1006 		    uint32_t index, uint32_t vmdq __rte_unused)
1007 {
1008 	struct virtio_hw *hw = dev->data->dev_private;
1009 	const struct ether_addr *addrs = dev->data->mac_addrs;
1010 	unsigned int i;
1011 	struct virtio_net_ctrl_mac *uc, *mc;
1012 
1013 	if (index >= VIRTIO_MAX_MAC_ADDRS) {
1014 		PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
1015 		return -EINVAL;
1016 	}
1017 
1018 	uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
1019 	uc->entries = 0;
1020 	mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
1021 	mc->entries = 0;
1022 
1023 	for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
1024 		const struct ether_addr *addr
1025 			= (i == index) ? mac_addr : addrs + i;
1026 		struct virtio_net_ctrl_mac *tbl
1027 			= is_multicast_ether_addr(addr) ? mc : uc;
1028 
1029 		memcpy(&tbl->macs[tbl->entries++], addr, ETHER_ADDR_LEN);
1030 	}
1031 
1032 	return virtio_mac_table_set(hw, uc, mc);
1033 }
1034 
1035 static void
1036 virtio_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
1037 {
1038 	struct virtio_hw *hw = dev->data->dev_private;
1039 	struct ether_addr *addrs = dev->data->mac_addrs;
1040 	struct virtio_net_ctrl_mac *uc, *mc;
1041 	unsigned int i;
1042 
1043 	if (index >= VIRTIO_MAX_MAC_ADDRS) {
1044 		PMD_DRV_LOG(ERR, "mac address index %u out of range", index);
1045 		return;
1046 	}
1047 
1048 	uc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(uc->entries));
1049 	uc->entries = 0;
1050 	mc = alloca(VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN + sizeof(mc->entries));
1051 	mc->entries = 0;
1052 
1053 	for (i = 0; i < VIRTIO_MAX_MAC_ADDRS; i++) {
1054 		struct virtio_net_ctrl_mac *tbl;
1055 
1056 		if (i == index || is_zero_ether_addr(addrs + i))
1057 			continue;
1058 
1059 		tbl = is_multicast_ether_addr(addrs + i) ? mc : uc;
1060 		memcpy(&tbl->macs[tbl->entries++], addrs + i, ETHER_ADDR_LEN);
1061 	}
1062 
1063 	virtio_mac_table_set(hw, uc, mc);
1064 }
1065 
1066 static int
1067 virtio_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
1068 {
1069 	struct virtio_hw *hw = dev->data->dev_private;
1070 
1071 	memcpy(hw->mac_addr, mac_addr, ETHER_ADDR_LEN);
1072 
1073 	/* Use atomic update if available */
1074 	if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1075 		struct virtio_pmd_ctrl ctrl;
1076 		int len = ETHER_ADDR_LEN;
1077 
1078 		ctrl.hdr.class = VIRTIO_NET_CTRL_MAC;
1079 		ctrl.hdr.cmd = VIRTIO_NET_CTRL_MAC_ADDR_SET;
1080 
1081 		memcpy(ctrl.data, mac_addr, ETHER_ADDR_LEN);
1082 		return virtio_send_command(hw->cvq, &ctrl, &len, 1);
1083 	}
1084 
1085 	if (!vtpci_with_feature(hw, VIRTIO_NET_F_MAC))
1086 		return -ENOTSUP;
1087 
1088 	virtio_set_hwaddr(hw);
1089 	return 0;
1090 }
1091 
1092 static int
1093 virtio_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
1094 {
1095 	struct virtio_hw *hw = dev->data->dev_private;
1096 	struct virtio_pmd_ctrl ctrl;
1097 	int len;
1098 
1099 	if (!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN))
1100 		return -ENOTSUP;
1101 
1102 	ctrl.hdr.class = VIRTIO_NET_CTRL_VLAN;
1103 	ctrl.hdr.cmd = on ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
1104 	memcpy(ctrl.data, &vlan_id, sizeof(vlan_id));
1105 	len = sizeof(vlan_id);
1106 
1107 	return virtio_send_command(hw->cvq, &ctrl, &len, 1);
1108 }
1109 
1110 static int
1111 virtio_intr_enable(struct rte_eth_dev *dev)
1112 {
1113 	struct virtio_hw *hw = dev->data->dev_private;
1114 
1115 	if (rte_intr_enable(dev->intr_handle) < 0)
1116 		return -1;
1117 
1118 	if (!hw->virtio_user_dev)
1119 		hw->use_msix = vtpci_msix_detect(RTE_ETH_DEV_TO_PCI(dev));
1120 
1121 	return 0;
1122 }
1123 
1124 static int
1125 virtio_intr_disable(struct rte_eth_dev *dev)
1126 {
1127 	struct virtio_hw *hw = dev->data->dev_private;
1128 
1129 	if (rte_intr_disable(dev->intr_handle) < 0)
1130 		return -1;
1131 
1132 	if (!hw->virtio_user_dev)
1133 		hw->use_msix = vtpci_msix_detect(RTE_ETH_DEV_TO_PCI(dev));
1134 
1135 	return 0;
1136 }
1137 
1138 static int
1139 virtio_negotiate_features(struct virtio_hw *hw, uint64_t req_features)
1140 {
1141 	uint64_t host_features;
1142 
1143 	/* Prepare guest_features: feature that driver wants to support */
1144 	PMD_INIT_LOG(DEBUG, "guest_features before negotiate = %" PRIx64,
1145 		req_features);
1146 
1147 	/* Read device(host) feature bits */
1148 	host_features = VTPCI_OPS(hw)->get_features(hw);
1149 	PMD_INIT_LOG(DEBUG, "host_features before negotiate = %" PRIx64,
1150 		host_features);
1151 
1152 	/* If supported, ensure MTU value is valid before acknowledging it. */
1153 	if (host_features & req_features & (1ULL << VIRTIO_NET_F_MTU)) {
1154 		struct virtio_net_config config;
1155 
1156 		vtpci_read_dev_config(hw,
1157 			offsetof(struct virtio_net_config, mtu),
1158 			&config.mtu, sizeof(config.mtu));
1159 
1160 		if (config.mtu < ETHER_MIN_MTU)
1161 			req_features &= ~(1ULL << VIRTIO_NET_F_MTU);
1162 	}
1163 
1164 	/*
1165 	 * Negotiate features: Subset of device feature bits are written back
1166 	 * guest feature bits.
1167 	 */
1168 	hw->guest_features = req_features;
1169 	hw->guest_features = vtpci_negotiate_features(hw, host_features);
1170 	PMD_INIT_LOG(DEBUG, "features after negotiate = %" PRIx64,
1171 		hw->guest_features);
1172 
1173 	if (hw->modern) {
1174 		if (!vtpci_with_feature(hw, VIRTIO_F_VERSION_1)) {
1175 			PMD_INIT_LOG(ERR,
1176 				"VIRTIO_F_VERSION_1 features is not enabled.");
1177 			return -1;
1178 		}
1179 		vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_FEATURES_OK);
1180 		if (!(vtpci_get_status(hw) & VIRTIO_CONFIG_STATUS_FEATURES_OK)) {
1181 			PMD_INIT_LOG(ERR,
1182 				"failed to set FEATURES_OK status!");
1183 			return -1;
1184 		}
1185 	}
1186 
1187 	hw->req_guest_features = req_features;
1188 
1189 	return 0;
1190 }
1191 
1192 int
1193 virtio_dev_pause(struct rte_eth_dev *dev)
1194 {
1195 	struct virtio_hw *hw = dev->data->dev_private;
1196 
1197 	rte_spinlock_lock(&hw->state_lock);
1198 
1199 	if (hw->started == 0) {
1200 		/* Device is just stopped. */
1201 		rte_spinlock_unlock(&hw->state_lock);
1202 		return -1;
1203 	}
1204 	hw->started = 0;
1205 	/*
1206 	 * Prevent the worker threads from touching queues to avoid contention,
1207 	 * 1 ms should be enough for the ongoing Tx function to finish.
1208 	 */
1209 	rte_delay_ms(1);
1210 	return 0;
1211 }
1212 
1213 /*
1214  * Recover hw state to let the worker threads continue.
1215  */
1216 void
1217 virtio_dev_resume(struct rte_eth_dev *dev)
1218 {
1219 	struct virtio_hw *hw = dev->data->dev_private;
1220 
1221 	hw->started = 1;
1222 	rte_spinlock_unlock(&hw->state_lock);
1223 }
1224 
1225 /*
1226  * Should be called only after device is paused.
1227  */
1228 int
1229 virtio_inject_pkts(struct rte_eth_dev *dev, struct rte_mbuf **tx_pkts,
1230 		int nb_pkts)
1231 {
1232 	struct virtio_hw *hw = dev->data->dev_private;
1233 	struct virtnet_tx *txvq = dev->data->tx_queues[0];
1234 	int ret;
1235 
1236 	hw->inject_pkts = tx_pkts;
1237 	ret = dev->tx_pkt_burst(txvq, tx_pkts, nb_pkts);
1238 	hw->inject_pkts = NULL;
1239 
1240 	return ret;
1241 }
1242 
1243 static void
1244 virtio_notify_peers(struct rte_eth_dev *dev)
1245 {
1246 	struct virtio_hw *hw = dev->data->dev_private;
1247 	struct virtnet_rx *rxvq;
1248 	struct rte_mbuf *rarp_mbuf;
1249 
1250 	if (!dev->data->rx_queues)
1251 		return;
1252 
1253 	rxvq = dev->data->rx_queues[0];
1254 	if (!rxvq)
1255 		return;
1256 
1257 	rarp_mbuf = rte_net_make_rarp_packet(rxvq->mpool,
1258 			(struct ether_addr *)hw->mac_addr);
1259 	if (rarp_mbuf == NULL) {
1260 		PMD_DRV_LOG(ERR, "failed to make RARP packet.");
1261 		return;
1262 	}
1263 
1264 	/* If virtio port just stopped, no need to send RARP */
1265 	if (virtio_dev_pause(dev) < 0) {
1266 		rte_pktmbuf_free(rarp_mbuf);
1267 		return;
1268 	}
1269 
1270 	virtio_inject_pkts(dev, &rarp_mbuf, 1);
1271 	virtio_dev_resume(dev);
1272 }
1273 
1274 static void
1275 virtio_ack_link_announce(struct rte_eth_dev *dev)
1276 {
1277 	struct virtio_hw *hw = dev->data->dev_private;
1278 	struct virtio_pmd_ctrl ctrl;
1279 
1280 	ctrl.hdr.class = VIRTIO_NET_CTRL_ANNOUNCE;
1281 	ctrl.hdr.cmd = VIRTIO_NET_CTRL_ANNOUNCE_ACK;
1282 
1283 	virtio_send_command(hw->cvq, &ctrl, NULL, 0);
1284 }
1285 
1286 /*
1287  * Process virtio config changed interrupt. Call the callback
1288  * if link state changed, generate gratuitous RARP packet if
1289  * the status indicates an ANNOUNCE.
1290  */
1291 void
1292 virtio_interrupt_handler(void *param)
1293 {
1294 	struct rte_eth_dev *dev = param;
1295 	struct virtio_hw *hw = dev->data->dev_private;
1296 	uint8_t isr;
1297 	uint16_t status;
1298 
1299 	/* Read interrupt status which clears interrupt */
1300 	isr = vtpci_isr(hw);
1301 	PMD_DRV_LOG(INFO, "interrupt status = %#x", isr);
1302 
1303 	if (virtio_intr_enable(dev) < 0)
1304 		PMD_DRV_LOG(ERR, "interrupt enable failed");
1305 
1306 	if (isr & VIRTIO_PCI_ISR_CONFIG) {
1307 		if (virtio_dev_link_update(dev, 0) == 0)
1308 			_rte_eth_dev_callback_process(dev,
1309 						      RTE_ETH_EVENT_INTR_LSC,
1310 						      NULL);
1311 
1312 		if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1313 			vtpci_read_dev_config(hw,
1314 				offsetof(struct virtio_net_config, status),
1315 				&status, sizeof(status));
1316 			if (status & VIRTIO_NET_S_ANNOUNCE) {
1317 				virtio_notify_peers(dev);
1318 				if (hw->cvq)
1319 					virtio_ack_link_announce(dev);
1320 			}
1321 		}
1322 	}
1323 }
1324 
1325 /* set rx and tx handlers according to what is supported */
1326 static void
1327 set_rxtx_funcs(struct rte_eth_dev *eth_dev)
1328 {
1329 	struct virtio_hw *hw = eth_dev->data->dev_private;
1330 
1331 	if (hw->use_simple_rx) {
1332 		PMD_INIT_LOG(INFO, "virtio: using simple Rx path on port %u",
1333 			eth_dev->data->port_id);
1334 		eth_dev->rx_pkt_burst = virtio_recv_pkts_vec;
1335 	} else if (hw->use_inorder_rx) {
1336 		PMD_INIT_LOG(INFO,
1337 			"virtio: using inorder mergeable buffer Rx path on port %u",
1338 			eth_dev->data->port_id);
1339 		eth_dev->rx_pkt_burst = &virtio_recv_mergeable_pkts_inorder;
1340 	} else if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF)) {
1341 		PMD_INIT_LOG(INFO,
1342 			"virtio: using mergeable buffer Rx path on port %u",
1343 			eth_dev->data->port_id);
1344 		eth_dev->rx_pkt_burst = &virtio_recv_mergeable_pkts;
1345 	} else {
1346 		PMD_INIT_LOG(INFO, "virtio: using standard Rx path on port %u",
1347 			eth_dev->data->port_id);
1348 		eth_dev->rx_pkt_burst = &virtio_recv_pkts;
1349 	}
1350 
1351 	if (hw->use_inorder_tx) {
1352 		PMD_INIT_LOG(INFO, "virtio: using inorder Tx path on port %u",
1353 			eth_dev->data->port_id);
1354 		eth_dev->tx_pkt_burst = virtio_xmit_pkts_inorder;
1355 	} else {
1356 		PMD_INIT_LOG(INFO, "virtio: using standard Tx path on port %u",
1357 			eth_dev->data->port_id);
1358 		eth_dev->tx_pkt_burst = virtio_xmit_pkts;
1359 	}
1360 }
1361 
1362 /* Only support 1:1 queue/interrupt mapping so far.
1363  * TODO: support n:1 queue/interrupt mapping when there are limited number of
1364  * interrupt vectors (<N+1).
1365  */
1366 static int
1367 virtio_queues_bind_intr(struct rte_eth_dev *dev)
1368 {
1369 	uint32_t i;
1370 	struct virtio_hw *hw = dev->data->dev_private;
1371 
1372 	PMD_INIT_LOG(INFO, "queue/interrupt binding");
1373 	for (i = 0; i < dev->data->nb_rx_queues; ++i) {
1374 		dev->intr_handle->intr_vec[i] = i + 1;
1375 		if (VTPCI_OPS(hw)->set_queue_irq(hw, hw->vqs[i * 2], i + 1) ==
1376 						 VIRTIO_MSI_NO_VECTOR) {
1377 			PMD_DRV_LOG(ERR, "failed to set queue vector");
1378 			return -EBUSY;
1379 		}
1380 	}
1381 
1382 	return 0;
1383 }
1384 
1385 static void
1386 virtio_queues_unbind_intr(struct rte_eth_dev *dev)
1387 {
1388 	uint32_t i;
1389 	struct virtio_hw *hw = dev->data->dev_private;
1390 
1391 	PMD_INIT_LOG(INFO, "queue/interrupt unbinding");
1392 	for (i = 0; i < dev->data->nb_rx_queues; ++i)
1393 		VTPCI_OPS(hw)->set_queue_irq(hw,
1394 					     hw->vqs[i * VTNET_CQ],
1395 					     VIRTIO_MSI_NO_VECTOR);
1396 }
1397 
1398 static int
1399 virtio_configure_intr(struct rte_eth_dev *dev)
1400 {
1401 	struct virtio_hw *hw = dev->data->dev_private;
1402 
1403 	if (!rte_intr_cap_multiple(dev->intr_handle)) {
1404 		PMD_INIT_LOG(ERR, "Multiple intr vector not supported");
1405 		return -ENOTSUP;
1406 	}
1407 
1408 	if (rte_intr_efd_enable(dev->intr_handle, dev->data->nb_rx_queues)) {
1409 		PMD_INIT_LOG(ERR, "Fail to create eventfd");
1410 		return -1;
1411 	}
1412 
1413 	if (!dev->intr_handle->intr_vec) {
1414 		dev->intr_handle->intr_vec =
1415 			rte_zmalloc("intr_vec",
1416 				    hw->max_queue_pairs * sizeof(int), 0);
1417 		if (!dev->intr_handle->intr_vec) {
1418 			PMD_INIT_LOG(ERR, "Failed to allocate %u rxq vectors",
1419 				     hw->max_queue_pairs);
1420 			return -ENOMEM;
1421 		}
1422 	}
1423 
1424 	/* Re-register callback to update max_intr */
1425 	rte_intr_callback_unregister(dev->intr_handle,
1426 				     virtio_interrupt_handler,
1427 				     dev);
1428 	rte_intr_callback_register(dev->intr_handle,
1429 				   virtio_interrupt_handler,
1430 				   dev);
1431 
1432 	/* DO NOT try to remove this! This function will enable msix, or QEMU
1433 	 * will encounter SIGSEGV when DRIVER_OK is sent.
1434 	 * And for legacy devices, this should be done before queue/vec binding
1435 	 * to change the config size from 20 to 24, or VIRTIO_MSI_QUEUE_VECTOR
1436 	 * (22) will be ignored.
1437 	 */
1438 	if (virtio_intr_enable(dev) < 0) {
1439 		PMD_DRV_LOG(ERR, "interrupt enable failed");
1440 		return -1;
1441 	}
1442 
1443 	if (virtio_queues_bind_intr(dev) < 0) {
1444 		PMD_INIT_LOG(ERR, "Failed to bind queue/interrupt");
1445 		return -1;
1446 	}
1447 
1448 	return 0;
1449 }
1450 
1451 /* reset device and renegotiate features if needed */
1452 static int
1453 virtio_init_device(struct rte_eth_dev *eth_dev, uint64_t req_features)
1454 {
1455 	struct virtio_hw *hw = eth_dev->data->dev_private;
1456 	struct virtio_net_config *config;
1457 	struct virtio_net_config local_config;
1458 	struct rte_pci_device *pci_dev = NULL;
1459 	int ret;
1460 
1461 	/* Reset the device although not necessary at startup */
1462 	vtpci_reset(hw);
1463 
1464 	if (hw->vqs) {
1465 		virtio_dev_free_mbufs(eth_dev);
1466 		virtio_free_queues(hw);
1467 	}
1468 
1469 	/* Tell the host we've noticed this device. */
1470 	vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_ACK);
1471 
1472 	/* Tell the host we've known how to drive the device. */
1473 	vtpci_set_status(hw, VIRTIO_CONFIG_STATUS_DRIVER);
1474 	if (virtio_negotiate_features(hw, req_features) < 0)
1475 		return -1;
1476 
1477 	if (!hw->virtio_user_dev) {
1478 		pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
1479 		rte_eth_copy_pci_info(eth_dev, pci_dev);
1480 	}
1481 
1482 	/* If host does not support both status and MSI-X then disable LSC */
1483 	if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS) &&
1484 	    hw->use_msix != VIRTIO_MSIX_NONE)
1485 		eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_LSC;
1486 	else
1487 		eth_dev->data->dev_flags &= ~RTE_ETH_DEV_INTR_LSC;
1488 
1489 	/* Setting up rx_header size for the device */
1490 	if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF) ||
1491 	    vtpci_with_feature(hw, VIRTIO_F_VERSION_1))
1492 		hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1493 	else
1494 		hw->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
1495 
1496 	/* Copy the permanent MAC address to: virtio_hw */
1497 	virtio_get_hwaddr(hw);
1498 	ether_addr_copy((struct ether_addr *) hw->mac_addr,
1499 			&eth_dev->data->mac_addrs[0]);
1500 	PMD_INIT_LOG(DEBUG,
1501 		     "PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1502 		     hw->mac_addr[0], hw->mac_addr[1], hw->mac_addr[2],
1503 		     hw->mac_addr[3], hw->mac_addr[4], hw->mac_addr[5]);
1504 
1505 	if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ)) {
1506 		config = &local_config;
1507 
1508 		vtpci_read_dev_config(hw,
1509 			offsetof(struct virtio_net_config, mac),
1510 			&config->mac, sizeof(config->mac));
1511 
1512 		if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
1513 			vtpci_read_dev_config(hw,
1514 				offsetof(struct virtio_net_config, status),
1515 				&config->status, sizeof(config->status));
1516 		} else {
1517 			PMD_INIT_LOG(DEBUG,
1518 				     "VIRTIO_NET_F_STATUS is not supported");
1519 			config->status = 0;
1520 		}
1521 
1522 		if (vtpci_with_feature(hw, VIRTIO_NET_F_MQ)) {
1523 			vtpci_read_dev_config(hw,
1524 				offsetof(struct virtio_net_config, max_virtqueue_pairs),
1525 				&config->max_virtqueue_pairs,
1526 				sizeof(config->max_virtqueue_pairs));
1527 		} else {
1528 			PMD_INIT_LOG(DEBUG,
1529 				     "VIRTIO_NET_F_MQ is not supported");
1530 			config->max_virtqueue_pairs = 1;
1531 		}
1532 
1533 		hw->max_queue_pairs = config->max_virtqueue_pairs;
1534 
1535 		if (vtpci_with_feature(hw, VIRTIO_NET_F_MTU)) {
1536 			vtpci_read_dev_config(hw,
1537 				offsetof(struct virtio_net_config, mtu),
1538 				&config->mtu,
1539 				sizeof(config->mtu));
1540 
1541 			/*
1542 			 * MTU value has already been checked at negotiation
1543 			 * time, but check again in case it has changed since
1544 			 * then, which should not happen.
1545 			 */
1546 			if (config->mtu < ETHER_MIN_MTU) {
1547 				PMD_INIT_LOG(ERR, "invalid max MTU value (%u)",
1548 						config->mtu);
1549 				return -1;
1550 			}
1551 
1552 			hw->max_mtu = config->mtu;
1553 			/* Set initial MTU to maximum one supported by vhost */
1554 			eth_dev->data->mtu = config->mtu;
1555 
1556 		} else {
1557 			hw->max_mtu = VIRTIO_MAX_RX_PKTLEN - ETHER_HDR_LEN -
1558 				VLAN_TAG_LEN - hw->vtnet_hdr_size;
1559 		}
1560 
1561 		PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=%d",
1562 				config->max_virtqueue_pairs);
1563 		PMD_INIT_LOG(DEBUG, "config->status=%d", config->status);
1564 		PMD_INIT_LOG(DEBUG,
1565 				"PORT MAC: %02X:%02X:%02X:%02X:%02X:%02X",
1566 				config->mac[0], config->mac[1],
1567 				config->mac[2], config->mac[3],
1568 				config->mac[4], config->mac[5]);
1569 	} else {
1570 		PMD_INIT_LOG(DEBUG, "config->max_virtqueue_pairs=1");
1571 		hw->max_queue_pairs = 1;
1572 		hw->max_mtu = VIRTIO_MAX_RX_PKTLEN - ETHER_HDR_LEN -
1573 			VLAN_TAG_LEN - hw->vtnet_hdr_size;
1574 	}
1575 
1576 	ret = virtio_alloc_queues(eth_dev);
1577 	if (ret < 0)
1578 		return ret;
1579 
1580 	if (eth_dev->data->dev_conf.intr_conf.rxq) {
1581 		if (virtio_configure_intr(eth_dev) < 0) {
1582 			PMD_INIT_LOG(ERR, "failed to configure interrupt");
1583 			return -1;
1584 		}
1585 	}
1586 
1587 	vtpci_reinit_complete(hw);
1588 
1589 	if (pci_dev)
1590 		PMD_INIT_LOG(DEBUG, "port %d vendorID=0x%x deviceID=0x%x",
1591 			eth_dev->data->port_id, pci_dev->id.vendor_id,
1592 			pci_dev->id.device_id);
1593 
1594 	return 0;
1595 }
1596 
1597 /*
1598  * Remap the PCI device again (IO port map for legacy device and
1599  * memory map for modern device), so that the secondary process
1600  * could have the PCI initiated correctly.
1601  */
1602 static int
1603 virtio_remap_pci(struct rte_pci_device *pci_dev, struct virtio_hw *hw)
1604 {
1605 	if (hw->modern) {
1606 		/*
1607 		 * We don't have to re-parse the PCI config space, since
1608 		 * rte_pci_map_device() makes sure the mapped address
1609 		 * in secondary process would equal to the one mapped in
1610 		 * the primary process: error will be returned if that
1611 		 * requirement is not met.
1612 		 *
1613 		 * That said, we could simply reuse all cap pointers
1614 		 * (such as dev_cfg, common_cfg, etc.) parsed from the
1615 		 * primary process, which is stored in shared memory.
1616 		 */
1617 		if (rte_pci_map_device(pci_dev)) {
1618 			PMD_INIT_LOG(DEBUG, "failed to map pci device!");
1619 			return -1;
1620 		}
1621 	} else {
1622 		if (rte_pci_ioport_map(pci_dev, 0, VTPCI_IO(hw)) < 0)
1623 			return -1;
1624 	}
1625 
1626 	return 0;
1627 }
1628 
1629 static void
1630 virtio_set_vtpci_ops(struct virtio_hw *hw)
1631 {
1632 #ifdef RTE_VIRTIO_USER
1633 	if (hw->virtio_user_dev)
1634 		VTPCI_OPS(hw) = &virtio_user_ops;
1635 	else
1636 #endif
1637 	if (hw->modern)
1638 		VTPCI_OPS(hw) = &modern_ops;
1639 	else
1640 		VTPCI_OPS(hw) = &legacy_ops;
1641 }
1642 
1643 /*
1644  * This function is based on probe() function in virtio_pci.c
1645  * It returns 0 on success.
1646  */
1647 int
1648 eth_virtio_dev_init(struct rte_eth_dev *eth_dev)
1649 {
1650 	struct virtio_hw *hw = eth_dev->data->dev_private;
1651 	int ret;
1652 
1653 	RTE_BUILD_BUG_ON(RTE_PKTMBUF_HEADROOM < sizeof(struct virtio_net_hdr_mrg_rxbuf));
1654 
1655 	eth_dev->dev_ops = &virtio_eth_dev_ops;
1656 
1657 	if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1658 		if (!hw->virtio_user_dev) {
1659 			ret = virtio_remap_pci(RTE_ETH_DEV_TO_PCI(eth_dev), hw);
1660 			if (ret)
1661 				return ret;
1662 		}
1663 
1664 		virtio_set_vtpci_ops(hw);
1665 		set_rxtx_funcs(eth_dev);
1666 
1667 		return 0;
1668 	}
1669 
1670 	/* Allocate memory for storing MAC addresses */
1671 	eth_dev->data->mac_addrs = rte_zmalloc("virtio", VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN, 0);
1672 	if (eth_dev->data->mac_addrs == NULL) {
1673 		PMD_INIT_LOG(ERR,
1674 			"Failed to allocate %d bytes needed to store MAC addresses",
1675 			VIRTIO_MAX_MAC_ADDRS * ETHER_ADDR_LEN);
1676 		return -ENOMEM;
1677 	}
1678 
1679 	hw->port_id = eth_dev->data->port_id;
1680 	/* For virtio_user case the hw->virtio_user_dev is populated by
1681 	 * virtio_user_eth_dev_alloc() before eth_virtio_dev_init() is called.
1682 	 */
1683 	if (!hw->virtio_user_dev) {
1684 		ret = vtpci_init(RTE_ETH_DEV_TO_PCI(eth_dev), hw);
1685 		if (ret)
1686 			goto out;
1687 	}
1688 
1689 	/* reset device and negotiate default features */
1690 	ret = virtio_init_device(eth_dev, VIRTIO_PMD_DEFAULT_GUEST_FEATURES);
1691 	if (ret < 0)
1692 		goto out;
1693 
1694 	return 0;
1695 
1696 out:
1697 	rte_free(eth_dev->data->mac_addrs);
1698 	return ret;
1699 }
1700 
1701 static int
1702 eth_virtio_dev_uninit(struct rte_eth_dev *eth_dev)
1703 {
1704 	PMD_INIT_FUNC_TRACE();
1705 
1706 	if (rte_eal_process_type() == RTE_PROC_SECONDARY)
1707 		return 0;
1708 
1709 	virtio_dev_stop(eth_dev);
1710 	virtio_dev_close(eth_dev);
1711 
1712 	eth_dev->dev_ops = NULL;
1713 	eth_dev->tx_pkt_burst = NULL;
1714 	eth_dev->rx_pkt_burst = NULL;
1715 
1716 	if (eth_dev->device)
1717 		rte_pci_unmap_device(RTE_ETH_DEV_TO_PCI(eth_dev));
1718 
1719 	PMD_INIT_LOG(DEBUG, "dev_uninit completed");
1720 
1721 	return 0;
1722 }
1723 
1724 static int vdpa_check_handler(__rte_unused const char *key,
1725 		const char *value, __rte_unused void *opaque)
1726 {
1727 	if (strcmp(value, "1"))
1728 		return -1;
1729 
1730 	return 0;
1731 }
1732 
1733 static int
1734 vdpa_mode_selected(struct rte_devargs *devargs)
1735 {
1736 	struct rte_kvargs *kvlist;
1737 	const char *key = "vdpa";
1738 	int ret = 0;
1739 
1740 	if (devargs == NULL)
1741 		return 0;
1742 
1743 	kvlist = rte_kvargs_parse(devargs->args, NULL);
1744 	if (kvlist == NULL)
1745 		return 0;
1746 
1747 	if (!rte_kvargs_count(kvlist, key))
1748 		goto exit;
1749 
1750 	/* vdpa mode selected when there's a key-value pair: vdpa=1 */
1751 	if (rte_kvargs_process(kvlist, key,
1752 				vdpa_check_handler, NULL) < 0) {
1753 		goto exit;
1754 	}
1755 	ret = 1;
1756 
1757 exit:
1758 	rte_kvargs_free(kvlist);
1759 	return ret;
1760 }
1761 
1762 static int eth_virtio_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
1763 	struct rte_pci_device *pci_dev)
1764 {
1765 	if (rte_eal_iopl_init() != 0) {
1766 		PMD_INIT_LOG(ERR, "IOPL call failed - cannot use virtio PMD");
1767 		return 1;
1768 	}
1769 
1770 	/* virtio pmd skips probe if device needs to work in vdpa mode */
1771 	if (vdpa_mode_selected(pci_dev->device.devargs))
1772 		return 1;
1773 
1774 	return rte_eth_dev_pci_generic_probe(pci_dev, sizeof(struct virtio_hw),
1775 		eth_virtio_dev_init);
1776 }
1777 
1778 static int eth_virtio_pci_remove(struct rte_pci_device *pci_dev)
1779 {
1780 	return rte_eth_dev_pci_generic_remove(pci_dev, eth_virtio_dev_uninit);
1781 }
1782 
1783 static struct rte_pci_driver rte_virtio_pmd = {
1784 	.driver = {
1785 		.name = "net_virtio",
1786 	},
1787 	.id_table = pci_id_virtio_map,
1788 	.drv_flags = 0,
1789 	.probe = eth_virtio_pci_probe,
1790 	.remove = eth_virtio_pci_remove,
1791 };
1792 
1793 RTE_INIT(rte_virtio_pmd_init)
1794 {
1795 	rte_eal_iopl_init();
1796 	rte_pci_register(&rte_virtio_pmd);
1797 }
1798 
1799 static bool
1800 rx_offload_enabled(struct virtio_hw *hw)
1801 {
1802 	return vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_CSUM) ||
1803 		vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO4) ||
1804 		vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO6);
1805 }
1806 
1807 static bool
1808 tx_offload_enabled(struct virtio_hw *hw)
1809 {
1810 	return vtpci_with_feature(hw, VIRTIO_NET_F_CSUM) ||
1811 		vtpci_with_feature(hw, VIRTIO_NET_F_HOST_TSO4) ||
1812 		vtpci_with_feature(hw, VIRTIO_NET_F_HOST_TSO6);
1813 }
1814 
1815 /*
1816  * Configure virtio device
1817  * It returns 0 on success.
1818  */
1819 static int
1820 virtio_dev_configure(struct rte_eth_dev *dev)
1821 {
1822 	const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
1823 	const struct rte_eth_txmode *txmode = &dev->data->dev_conf.txmode;
1824 	struct virtio_hw *hw = dev->data->dev_private;
1825 	uint64_t rx_offloads = rxmode->offloads;
1826 	uint64_t tx_offloads = txmode->offloads;
1827 	uint64_t req_features;
1828 	int ret;
1829 
1830 	PMD_INIT_LOG(DEBUG, "configure");
1831 	req_features = VIRTIO_PMD_DEFAULT_GUEST_FEATURES;
1832 
1833 	if (dev->data->dev_conf.intr_conf.rxq) {
1834 		ret = virtio_init_device(dev, hw->req_guest_features);
1835 		if (ret < 0)
1836 			return ret;
1837 	}
1838 
1839 	if (rx_offloads & (DEV_RX_OFFLOAD_UDP_CKSUM |
1840 			   DEV_RX_OFFLOAD_TCP_CKSUM))
1841 		req_features |= (1ULL << VIRTIO_NET_F_GUEST_CSUM);
1842 
1843 	if (rx_offloads & DEV_RX_OFFLOAD_TCP_LRO)
1844 		req_features |=
1845 			(1ULL << VIRTIO_NET_F_GUEST_TSO4) |
1846 			(1ULL << VIRTIO_NET_F_GUEST_TSO6);
1847 
1848 	if (tx_offloads & (DEV_TX_OFFLOAD_UDP_CKSUM |
1849 			   DEV_TX_OFFLOAD_TCP_CKSUM))
1850 		req_features |= (1ULL << VIRTIO_NET_F_CSUM);
1851 
1852 	if (tx_offloads & DEV_TX_OFFLOAD_TCP_TSO)
1853 		req_features |=
1854 			(1ULL << VIRTIO_NET_F_HOST_TSO4) |
1855 			(1ULL << VIRTIO_NET_F_HOST_TSO6);
1856 
1857 	/* if request features changed, reinit the device */
1858 	if (req_features != hw->req_guest_features) {
1859 		ret = virtio_init_device(dev, req_features);
1860 		if (ret < 0)
1861 			return ret;
1862 	}
1863 
1864 	if ((rx_offloads & (DEV_RX_OFFLOAD_UDP_CKSUM |
1865 			    DEV_RX_OFFLOAD_TCP_CKSUM)) &&
1866 		!vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_CSUM)) {
1867 		PMD_DRV_LOG(ERR,
1868 			"rx checksum not available on this host");
1869 		return -ENOTSUP;
1870 	}
1871 
1872 	if ((rx_offloads & DEV_RX_OFFLOAD_TCP_LRO) &&
1873 		(!vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO4) ||
1874 		 !vtpci_with_feature(hw, VIRTIO_NET_F_GUEST_TSO6))) {
1875 		PMD_DRV_LOG(ERR,
1876 			"Large Receive Offload not available on this host");
1877 		return -ENOTSUP;
1878 	}
1879 
1880 	/* start control queue */
1881 	if (vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VQ))
1882 		virtio_dev_cq_start(dev);
1883 
1884 	if (rx_offloads & DEV_RX_OFFLOAD_VLAN_STRIP)
1885 		hw->vlan_strip = 1;
1886 
1887 	if ((rx_offloads & DEV_RX_OFFLOAD_VLAN_FILTER)
1888 	    && !vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN)) {
1889 		PMD_DRV_LOG(ERR,
1890 			    "vlan filtering not available on this host");
1891 		return -ENOTSUP;
1892 	}
1893 
1894 	hw->has_tx_offload = tx_offload_enabled(hw);
1895 	hw->has_rx_offload = rx_offload_enabled(hw);
1896 
1897 	if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1898 		/* Enable vector (0) for Link State Intrerrupt */
1899 		if (VTPCI_OPS(hw)->set_config_irq(hw, 0) ==
1900 				VIRTIO_MSI_NO_VECTOR) {
1901 			PMD_DRV_LOG(ERR, "failed to set config vector");
1902 			return -EBUSY;
1903 		}
1904 
1905 	rte_spinlock_init(&hw->state_lock);
1906 
1907 	hw->use_simple_rx = 1;
1908 
1909 	if (vtpci_with_feature(hw, VIRTIO_F_IN_ORDER)) {
1910 		hw->use_inorder_tx = 1;
1911 		if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF)) {
1912 			hw->use_inorder_rx = 1;
1913 			hw->use_simple_rx = 0;
1914 		} else {
1915 			hw->use_inorder_rx = 0;
1916 		}
1917 	}
1918 
1919 #if defined RTE_ARCH_ARM64 || defined RTE_ARCH_ARM
1920 	if (!rte_cpu_get_flag_enabled(RTE_CPUFLAG_NEON)) {
1921 		hw->use_simple_rx = 0;
1922 	}
1923 #endif
1924 	if (vtpci_with_feature(hw, VIRTIO_NET_F_MRG_RXBUF)) {
1925 		 hw->use_simple_rx = 0;
1926 	}
1927 
1928 	if (rx_offloads & (DEV_RX_OFFLOAD_UDP_CKSUM |
1929 			   DEV_RX_OFFLOAD_TCP_CKSUM |
1930 			   DEV_RX_OFFLOAD_TCP_LRO |
1931 			   DEV_RX_OFFLOAD_VLAN_STRIP))
1932 		hw->use_simple_rx = 0;
1933 
1934 	hw->opened = true;
1935 
1936 	return 0;
1937 }
1938 
1939 
1940 static int
1941 virtio_dev_start(struct rte_eth_dev *dev)
1942 {
1943 	uint16_t nb_queues, i;
1944 	struct virtnet_rx *rxvq;
1945 	struct virtnet_tx *txvq __rte_unused;
1946 	struct virtio_hw *hw = dev->data->dev_private;
1947 	int ret;
1948 
1949 	/* Finish the initialization of the queues */
1950 	for (i = 0; i < dev->data->nb_rx_queues; i++) {
1951 		ret = virtio_dev_rx_queue_setup_finish(dev, i);
1952 		if (ret < 0)
1953 			return ret;
1954 	}
1955 	for (i = 0; i < dev->data->nb_tx_queues; i++) {
1956 		ret = virtio_dev_tx_queue_setup_finish(dev, i);
1957 		if (ret < 0)
1958 			return ret;
1959 	}
1960 
1961 	/* check if lsc interrupt feature is enabled */
1962 	if (dev->data->dev_conf.intr_conf.lsc) {
1963 		if (!(dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)) {
1964 			PMD_DRV_LOG(ERR, "link status not supported by host");
1965 			return -ENOTSUP;
1966 		}
1967 	}
1968 
1969 	/* Enable uio/vfio intr/eventfd mapping: althrough we already did that
1970 	 * in device configure, but it could be unmapped  when device is
1971 	 * stopped.
1972 	 */
1973 	if (dev->data->dev_conf.intr_conf.lsc ||
1974 	    dev->data->dev_conf.intr_conf.rxq) {
1975 		virtio_intr_disable(dev);
1976 
1977 		/* Setup interrupt callback  */
1978 		if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1979 			rte_intr_callback_register(dev->intr_handle,
1980 						   virtio_interrupt_handler,
1981 						   dev);
1982 
1983 		if (virtio_intr_enable(dev) < 0) {
1984 			PMD_DRV_LOG(ERR, "interrupt enable failed");
1985 			return -EIO;
1986 		}
1987 	}
1988 
1989 	/*Notify the backend
1990 	 *Otherwise the tap backend might already stop its queue due to fullness.
1991 	 *vhost backend will have no chance to be waked up
1992 	 */
1993 	nb_queues = RTE_MAX(dev->data->nb_rx_queues, dev->data->nb_tx_queues);
1994 	if (hw->max_queue_pairs > 1) {
1995 		if (virtio_set_multiple_queues(dev, nb_queues) != 0)
1996 			return -EINVAL;
1997 	}
1998 
1999 	PMD_INIT_LOG(DEBUG, "nb_queues=%d", nb_queues);
2000 
2001 	for (i = 0; i < dev->data->nb_rx_queues; i++) {
2002 		rxvq = dev->data->rx_queues[i];
2003 		/* Flush the old packets */
2004 		virtqueue_rxvq_flush(rxvq->vq);
2005 		virtqueue_notify(rxvq->vq);
2006 	}
2007 
2008 	for (i = 0; i < dev->data->nb_tx_queues; i++) {
2009 		txvq = dev->data->tx_queues[i];
2010 		virtqueue_notify(txvq->vq);
2011 	}
2012 
2013 	PMD_INIT_LOG(DEBUG, "Notified backend at initialization");
2014 
2015 	for (i = 0; i < dev->data->nb_rx_queues; i++) {
2016 		rxvq = dev->data->rx_queues[i];
2017 		VIRTQUEUE_DUMP(rxvq->vq);
2018 	}
2019 
2020 	for (i = 0; i < dev->data->nb_tx_queues; i++) {
2021 		txvq = dev->data->tx_queues[i];
2022 		VIRTQUEUE_DUMP(txvq->vq);
2023 	}
2024 
2025 	set_rxtx_funcs(dev);
2026 	hw->started = true;
2027 
2028 	/* Initialize Link state */
2029 	virtio_dev_link_update(dev, 0);
2030 
2031 	return 0;
2032 }
2033 
2034 static void virtio_dev_free_mbufs(struct rte_eth_dev *dev)
2035 {
2036 	struct virtio_hw *hw = dev->data->dev_private;
2037 	uint16_t nr_vq = virtio_get_nr_vq(hw);
2038 	const char *type __rte_unused;
2039 	unsigned int i, mbuf_num = 0;
2040 	struct virtqueue *vq;
2041 	struct rte_mbuf *buf;
2042 	int queue_type;
2043 
2044 	if (hw->vqs == NULL)
2045 		return;
2046 
2047 	for (i = 0; i < nr_vq; i++) {
2048 		vq = hw->vqs[i];
2049 		if (!vq)
2050 			continue;
2051 
2052 		queue_type = virtio_get_queue_type(hw, i);
2053 		if (queue_type == VTNET_RQ)
2054 			type = "rxq";
2055 		else if (queue_type == VTNET_TQ)
2056 			type = "txq";
2057 		else
2058 			continue;
2059 
2060 		PMD_INIT_LOG(DEBUG,
2061 			"Before freeing %s[%d] used and unused buf",
2062 			type, i);
2063 		VIRTQUEUE_DUMP(vq);
2064 
2065 		while ((buf = virtqueue_detach_unused(vq)) != NULL) {
2066 			rte_pktmbuf_free(buf);
2067 			mbuf_num++;
2068 		}
2069 
2070 		PMD_INIT_LOG(DEBUG,
2071 			"After freeing %s[%d] used and unused buf",
2072 			type, i);
2073 		VIRTQUEUE_DUMP(vq);
2074 	}
2075 
2076 	PMD_INIT_LOG(DEBUG, "%d mbufs freed", mbuf_num);
2077 }
2078 
2079 /*
2080  * Stop device: disable interrupt and mark link down
2081  */
2082 static void
2083 virtio_dev_stop(struct rte_eth_dev *dev)
2084 {
2085 	struct virtio_hw *hw = dev->data->dev_private;
2086 	struct rte_eth_link link;
2087 	struct rte_intr_conf *intr_conf = &dev->data->dev_conf.intr_conf;
2088 
2089 	PMD_INIT_LOG(DEBUG, "stop");
2090 
2091 	rte_spinlock_lock(&hw->state_lock);
2092 	if (!hw->started)
2093 		goto out_unlock;
2094 	hw->started = false;
2095 
2096 	if (intr_conf->lsc || intr_conf->rxq) {
2097 		virtio_intr_disable(dev);
2098 
2099 		/* Reset interrupt callback  */
2100 		if (dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC) {
2101 			rte_intr_callback_unregister(dev->intr_handle,
2102 						     virtio_interrupt_handler,
2103 						     dev);
2104 		}
2105 	}
2106 
2107 	memset(&link, 0, sizeof(link));
2108 	rte_eth_linkstatus_set(dev, &link);
2109 out_unlock:
2110 	rte_spinlock_unlock(&hw->state_lock);
2111 }
2112 
2113 static int
2114 virtio_dev_link_update(struct rte_eth_dev *dev, __rte_unused int wait_to_complete)
2115 {
2116 	struct rte_eth_link link;
2117 	uint16_t status;
2118 	struct virtio_hw *hw = dev->data->dev_private;
2119 
2120 	memset(&link, 0, sizeof(link));
2121 	link.link_duplex = ETH_LINK_FULL_DUPLEX;
2122 	link.link_speed  = ETH_SPEED_NUM_10G;
2123 	link.link_autoneg = ETH_LINK_FIXED;
2124 
2125 	if (!hw->started) {
2126 		link.link_status = ETH_LINK_DOWN;
2127 	} else if (vtpci_with_feature(hw, VIRTIO_NET_F_STATUS)) {
2128 		PMD_INIT_LOG(DEBUG, "Get link status from hw");
2129 		vtpci_read_dev_config(hw,
2130 				offsetof(struct virtio_net_config, status),
2131 				&status, sizeof(status));
2132 		if ((status & VIRTIO_NET_S_LINK_UP) == 0) {
2133 			link.link_status = ETH_LINK_DOWN;
2134 			PMD_INIT_LOG(DEBUG, "Port %d is down",
2135 				     dev->data->port_id);
2136 		} else {
2137 			link.link_status = ETH_LINK_UP;
2138 			PMD_INIT_LOG(DEBUG, "Port %d is up",
2139 				     dev->data->port_id);
2140 		}
2141 	} else {
2142 		link.link_status = ETH_LINK_UP;
2143 	}
2144 
2145 	return rte_eth_linkstatus_set(dev, &link);
2146 }
2147 
2148 static int
2149 virtio_dev_vlan_offload_set(struct rte_eth_dev *dev, int mask)
2150 {
2151 	const struct rte_eth_rxmode *rxmode = &dev->data->dev_conf.rxmode;
2152 	struct virtio_hw *hw = dev->data->dev_private;
2153 	uint64_t offloads = rxmode->offloads;
2154 
2155 	if (mask & ETH_VLAN_FILTER_MASK) {
2156 		if ((offloads & DEV_RX_OFFLOAD_VLAN_FILTER) &&
2157 				!vtpci_with_feature(hw, VIRTIO_NET_F_CTRL_VLAN)) {
2158 
2159 			PMD_DRV_LOG(NOTICE,
2160 				"vlan filtering not available on this host");
2161 
2162 			return -ENOTSUP;
2163 		}
2164 	}
2165 
2166 	if (mask & ETH_VLAN_STRIP_MASK)
2167 		hw->vlan_strip = !!(offloads & DEV_RX_OFFLOAD_VLAN_STRIP);
2168 
2169 	return 0;
2170 }
2171 
2172 static void
2173 virtio_dev_info_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
2174 {
2175 	uint64_t tso_mask, host_features;
2176 	struct virtio_hw *hw = dev->data->dev_private;
2177 
2178 	dev_info->speed_capa = ETH_LINK_SPEED_10G; /* fake value */
2179 
2180 	dev_info->max_rx_queues =
2181 		RTE_MIN(hw->max_queue_pairs, VIRTIO_MAX_RX_QUEUES);
2182 	dev_info->max_tx_queues =
2183 		RTE_MIN(hw->max_queue_pairs, VIRTIO_MAX_TX_QUEUES);
2184 	dev_info->min_rx_bufsize = VIRTIO_MIN_RX_BUFSIZE;
2185 	dev_info->max_rx_pktlen = VIRTIO_MAX_RX_PKTLEN;
2186 	dev_info->max_mac_addrs = VIRTIO_MAX_MAC_ADDRS;
2187 
2188 	host_features = VTPCI_OPS(hw)->get_features(hw);
2189 	dev_info->rx_offload_capa = DEV_RX_OFFLOAD_VLAN_STRIP;
2190 	if (host_features & (1ULL << VIRTIO_NET_F_GUEST_CSUM)) {
2191 		dev_info->rx_offload_capa |=
2192 			DEV_RX_OFFLOAD_TCP_CKSUM |
2193 			DEV_RX_OFFLOAD_UDP_CKSUM;
2194 	}
2195 	if (host_features & (1ULL << VIRTIO_NET_F_CTRL_VLAN))
2196 		dev_info->rx_offload_capa |= DEV_RX_OFFLOAD_VLAN_FILTER;
2197 	tso_mask = (1ULL << VIRTIO_NET_F_GUEST_TSO4) |
2198 		(1ULL << VIRTIO_NET_F_GUEST_TSO6);
2199 	if ((host_features & tso_mask) == tso_mask)
2200 		dev_info->rx_offload_capa |= DEV_RX_OFFLOAD_TCP_LRO;
2201 
2202 	dev_info->tx_offload_capa = DEV_TX_OFFLOAD_MULTI_SEGS |
2203 				    DEV_TX_OFFLOAD_VLAN_INSERT;
2204 	if (host_features & (1ULL << VIRTIO_NET_F_CSUM)) {
2205 		dev_info->tx_offload_capa |=
2206 			DEV_TX_OFFLOAD_UDP_CKSUM |
2207 			DEV_TX_OFFLOAD_TCP_CKSUM;
2208 	}
2209 	tso_mask = (1ULL << VIRTIO_NET_F_HOST_TSO4) |
2210 		(1ULL << VIRTIO_NET_F_HOST_TSO6);
2211 	if ((host_features & tso_mask) == tso_mask)
2212 		dev_info->tx_offload_capa |= DEV_TX_OFFLOAD_TCP_TSO;
2213 }
2214 
2215 /*
2216  * It enables testpmd to collect per queue stats.
2217  */
2218 static int
2219 virtio_dev_queue_stats_mapping_set(__rte_unused struct rte_eth_dev *eth_dev,
2220 __rte_unused uint16_t queue_id, __rte_unused uint8_t stat_idx,
2221 __rte_unused uint8_t is_rx)
2222 {
2223 	return 0;
2224 }
2225 
2226 RTE_PMD_EXPORT_NAME(net_virtio, __COUNTER__);
2227 RTE_PMD_REGISTER_PCI_TABLE(net_virtio, pci_id_virtio_map);
2228 RTE_PMD_REGISTER_KMOD_DEP(net_virtio, "* igb_uio | uio_pci_generic | vfio-pci");
2229 
2230 RTE_INIT(virtio_init_log)
2231 {
2232 	virtio_logtype_init = rte_log_register("pmd.net.virtio.init");
2233 	if (virtio_logtype_init >= 0)
2234 		rte_log_set_level(virtio_logtype_init, RTE_LOG_NOTICE);
2235 	virtio_logtype_driver = rte_log_register("pmd.net.virtio.driver");
2236 	if (virtio_logtype_driver >= 0)
2237 		rte_log_set_level(virtio_logtype_driver, RTE_LOG_NOTICE);
2238 }
2239