Palacios Public Git Repository

To checkout Palacios execute

  git clone http://v3vee.org/palacios/palacios.web/palacios.git
This will give you the master branch. You probably want the devel branch or one of the release branches. To switch to the devel branch, simply execute
  cd palacios
  git checkout --track -b devel origin/devel
The other branches are similar.


Fix to VNET bug when vnet_host_hooks is not properly initiated
[palacios.git] / palacios / src / devices / lnx_virtio_nic.c
1 /* 
2  * This file is part of the Palacios Virtual Machine Monitor developed
3  * by the V3VEE Project with funding from the United States National 
4  * Science Foundation and the Department of Energy.  
5  *
6  * The V3VEE Project is a joint project between Northwestern University
7  * and the University of New Mexico.  You can find out more at 
8  * http://www.v3vee.org
9  *
10  * Copyright (c) 2010, Lei Xia <lxia@northwestern.edu>
11  * Copyright (c) 2010, Cui Zheng <cuizheng@cs.unm.edu>
12  * Copyright (c) 2010, The V3VEE Project <http://www.v3vee.org> 
13  * All rights reserved.
14  *
15  * Author: Lei Xia <lxia@northwestern.edu>
16  *         Cui Zheng <cuizheng@cs.unm.edu>
17  *               
18  *
19  * This is free software.  You are permitted to use,
20  * redistribute, and modify it as specified in the file "V3VEE_LICENSE".
21  */
22  
23 #include <palacios/vmm.h>
24 #include <palacios/vmm_dev_mgr.h>
25 #include <devices/lnx_virtio_pci.h>
26 #include <palacios/vm_guest_mem.h>
27 #include <palacios/vmm_sprintf.h>
28 #include <vnet/vnet.h>
29 #include <palacios/vmm_lock.h>
30 #include <palacios/vmm_util.h>
31 #include <devices/pci.h>
32 #include <palacios/vmm_ethernet.h>
33 #include <palacios/vmm_time.h>
34
35
36 #ifndef V3_CONFIG_DEBUG_VIRTIO_NET
37 #undef PrintDebug
38 #define PrintDebug(fmt, args...)
39 #endif
40
41 #ifndef V3_CONFIG_VNET
42 static int net_debug = 0;
43 #endif
44
45 #define TX_QUEUE_SIZE 4096
46 #define RX_QUEUE_SIZE 4096
47 #define CTRL_QUEUE_SIZE 64
48
49 /* The feature bitmap for virtio nic
50   * from Linux */
51 #define VIRTIO_NET_F_CSUM       0       /* Host handles pkts w/ partial csum */
52 #define VIRTIO_NET_F_GUEST_CSUM 1       /* Guest handles pkts w/ partial csum */
53 #define VIRTIO_NET_F_MAC        5       /* Host has given MAC address. */
54 #define VIRTIO_NET_F_GSO        6       /* Host handles pkts w/ any GSO type */
55 #define VIRTIO_NET_F_GUEST_TSO4 7       /* Guest can handle TSOv4 in. */
56 #define VIRTIO_NET_F_GUEST_TSO6 8       /* Guest can handle TSOv6 in. */
57 #define VIRTIO_NET_F_GUEST_ECN  9       /* Guest can handle TSO[6] w/ ECN in. */
58 #define VIRTIO_NET_F_GUEST_UFO  10      /* Guest can handle UFO in. */
59 #define VIRTIO_NET_F_HOST_TSO4  11      /* Host can handle TSOv4 in. */
60 #define VIRTIO_NET_F_HOST_TSO6  12      /* Host can handle TSOv6 in. */
61 #define VIRTIO_NET_F_HOST_ECN   13      /* Host can handle TSO[6] w/ ECN in. */
62 #define VIRTIO_NET_F_HOST_UFO   14      /* Host can handle UFO in. */
63 #define VIRTIO_NET_F_MRG_RXBUF  15      /* Host can merge receive buffers. */
64 #define VIRTIO_NET_F_STATUS     16      /* virtio_net_config.status available */
65
66 /* Port to get virtio config */
67 #define VIRTIO_NET_CONFIG 20  
68
69 #define VIRTIO_NET_MAX_BUFSIZE (sizeof(struct virtio_net_hdr) + (64 << 10))
70
71 /* for gso_type in virtio_net_hdr */
72 #define VIRTIO_NET_HDR_GSO_NONE         0      
73 #define VIRTIO_NET_HDR_GSO_TCPV4        1     /* GSO frame, IPv4 TCP (TSO) */
74 #define VIRTIO_NET_HDR_GSO_UDP          3       /* GSO frame, IPv4 UDP (UFO) */
75 #define VIRTIO_NET_HDR_GSO_TCPV6        4       /* GSO frame, IPv6 TCP */
76 #define VIRTIO_NET_HDR_GSO_ECN          0x80    /* TCP has ECN set */   
77
78
79 /* for flags in virtio_net_hdr */
80 #define VIRTIO_NET_HDR_F_NEEDS_CSUM     1       /* Use csum_start, csum_offset */
81
82
83 /* First element of the scatter-gather list, used with GSO or CSUM features */
84 struct virtio_net_hdr
85 {
86     uint8_t flags;
87     uint8_t gso_type;
88     uint16_t hdr_len;           /* Ethernet + IP + tcp/udp hdrs */
89     uint16_t gso_size;          /* Bytes to append to hdr_len per frame */
90     uint16_t csum_start;        /* Position to start checksumming from */
91     uint16_t csum_offset;       /* Offset after that to place checksum */
92 }__attribute__((packed));
93
94
95 /* The header to use when the MRG_RXBUF 
96  * feature has been negotiated. */
97 struct virtio_net_hdr_mrg_rxbuf {
98     struct virtio_net_hdr hdr;
99     uint16_t num_buffers;       /* Number of merged rx buffers */
100 };
101
102 struct virtio_net_config
103 {
104     uint8_t mac[ETH_ALEN];      /* VIRTIO_NET_F_MAC */
105     uint16_t status;
106 } __attribute__((packed));
107
108 struct virtio_dev_state {
109     struct vm_device * pci_bus;
110     struct list_head dev_list;
111     struct v3_vm_info *vm;
112
113     uint8_t mac[ETH_ALEN];
114 };
115
116 struct virtio_net_state {
117     struct virtio_net_config net_cfg;
118     struct virtio_config virtio_cfg;
119
120     struct v3_vm_info * vm;
121     struct vm_device * dev;
122     struct pci_device * pci_dev; 
123     int io_range_size;
124
125     uint16_t status;
126     
127     struct virtio_queue rx_vq;          /* idx 0*/
128     struct virtio_queue tx_vq;          /* idx 1*/
129     struct virtio_queue ctrl_vq;        /* idx 2*/
130
131     uint8_t mergeable_rx_bufs;
132
133     struct v3_timer * timer;
134     struct vnet_thread * poll_thread;
135
136     struct nic_statistics stats;
137
138     struct v3_dev_net_ops * net_ops;
139     v3_lock_t rx_lock, tx_lock;
140
141     uint8_t tx_notify, rx_notify;
142     uint32_t tx_pkts, rx_pkts;
143     uint64_t past_us;
144
145     void * backend_data;
146     struct virtio_dev_state * virtio_dev;
147     struct list_head dev_link;
148 };
149
150
151 static int virtio_init_state(struct virtio_net_state * virtio) 
152 {
153     virtio->rx_vq.queue_size = RX_QUEUE_SIZE;
154     virtio->tx_vq.queue_size = TX_QUEUE_SIZE;
155     virtio->ctrl_vq.queue_size = CTRL_QUEUE_SIZE;
156
157     virtio->rx_vq.ring_desc_addr = 0;
158     virtio->rx_vq.ring_avail_addr = 0;
159     virtio->rx_vq.ring_used_addr = 0;
160     virtio->rx_vq.pfn = 0;
161     virtio->rx_vq.cur_avail_idx = 0;
162
163     virtio->tx_vq.ring_desc_addr = 0;
164     virtio->tx_vq.ring_avail_addr = 0;
165     virtio->tx_vq.ring_used_addr = 0;
166     virtio->tx_vq.pfn = 0;
167     virtio->tx_vq.cur_avail_idx = 0;
168
169     virtio->ctrl_vq.ring_desc_addr = 0;
170     virtio->ctrl_vq.ring_avail_addr = 0;
171     virtio->ctrl_vq.ring_used_addr = 0;
172     virtio->ctrl_vq.pfn = 0;
173     virtio->ctrl_vq.cur_avail_idx = 0;
174
175     virtio->virtio_cfg.pci_isr = 0;
176
177     virtio->mergeable_rx_bufs = 0;
178         
179     virtio->virtio_cfg.host_features = 0 | (1 << VIRTIO_NET_F_MAC);
180     if(virtio->mergeable_rx_bufs) {
181         virtio->virtio_cfg.host_features |= (1 << VIRTIO_NET_F_MRG_RXBUF);
182     }
183
184     if ((v3_lock_init(&(virtio->rx_lock)) == -1) ||
185         (v3_lock_init(&(virtio->tx_lock)) == -1)){
186         PrintError("Virtio NIC: Failure to init locks for net_state\n");
187     }
188
189     return 0;
190 }
191
192 static int tx_one_pkt(struct guest_info * core, 
193                       struct virtio_net_state * virtio, 
194                       struct vring_desc * buf_desc) 
195 {
196     uint8_t * buf = NULL;
197     uint32_t len = buf_desc->length;
198     int synchronize = virtio->tx_notify;
199
200     if (v3_gpa_to_hva(core, buf_desc->addr_gpa, (addr_t *)&(buf)) == -1) {
201         PrintDebug("Could not translate buffer address\n");
202         return -1;
203     }
204
205     V3_Net_Print(2, "Virtio-NIC: virtio_tx: size: %d\n", len);
206     if(net_debug >= 4){
207         v3_hexdump(buf, len, NULL, 0);
208     }
209
210     if(virtio->net_ops->send(buf, len, synchronize, virtio->backend_data) < 0){
211         virtio->stats.tx_dropped ++;
212         return -1;
213     }
214
215     virtio->stats.tx_pkts ++;
216     virtio->stats.tx_bytes += len;
217
218     return 0;
219 }
220
221
222 static inline int copy_data_to_desc(struct guest_info * core, 
223                   struct virtio_net_state * virtio_state, 
224                   struct vring_desc * desc, 
225                   uchar_t * buf, 
226                   uint_t buf_len,
227                   uint_t dst_offset){
228     uint32_t len;
229     uint8_t * desc_buf = NULL;
230
231     if (v3_gpa_to_hva(core, desc->addr_gpa, (addr_t *)&(desc_buf)) == -1) {
232         PrintDebug("Could not translate buffer address\n");
233         return -1;
234     }
235     len = (desc->length < buf_len)?(desc->length - dst_offset):buf_len;
236     memcpy(desc_buf+dst_offset, buf, len);
237
238     return len;
239 }
240
241
242 static inline int get_desc_count(struct virtio_queue * q, int index) {
243     struct vring_desc * tmp_desc = &(q->desc[index]);
244     int cnt = 1;
245     
246     while (tmp_desc->flags & VIRTIO_NEXT_FLAG) {
247         tmp_desc = &(q->desc[tmp_desc->next]);
248         cnt++;
249     }
250
251     return cnt;
252 }
253
254 static inline void enable_cb(struct virtio_queue *queue){
255     if(queue->used){
256         queue->used->flags &= ~ VRING_NO_NOTIFY_FLAG;
257     }
258 }
259
260 static inline void disable_cb(struct virtio_queue *queue) {
261     if(queue->used){
262         queue->used->flags |= VRING_NO_NOTIFY_FLAG;
263     }
264 }
265
266 static int handle_pkt_tx(struct guest_info * core, 
267                          struct virtio_net_state * virtio_state) 
268 {
269     struct virtio_queue *q = &(virtio_state->tx_vq);
270     int txed = 0;
271     unsigned long flags; 
272
273     if (!q->ring_avail_addr) {
274         return -1;
275     }
276
277     flags = v3_lock_irqsave(virtio_state->tx_lock);
278     while (q->cur_avail_idx != q->avail->index) {
279         struct virtio_net_hdr_mrg_rxbuf * hdr = NULL;
280         struct vring_desc * hdr_desc = NULL;
281         addr_t hdr_addr = 0;
282         uint16_t desc_idx = q->avail->ring[q->cur_avail_idx % q->queue_size];
283         int desc_cnt = get_desc_count(q, desc_idx);
284
285         if(desc_cnt > 2){
286             PrintError("VNIC: merged rx buffer not supported, desc_cnt %d\n", desc_cnt);
287             goto exit_error;
288         }
289
290         hdr_desc = &(q->desc[desc_idx]);
291         if (v3_gpa_to_hva(core, hdr_desc->addr_gpa, &(hdr_addr)) == -1) {
292             PrintError("Could not translate block header address\n");
293             goto exit_error;
294         }
295
296         hdr = (struct virtio_net_hdr_mrg_rxbuf *)hdr_addr;
297         desc_idx = hdr_desc->next;
298
299         V3_Net_Print(2, "Virtio NIC: TX hdr count : %d\n", hdr->num_buffers);
300
301         /* here we assumed that one ethernet pkt is not splitted into multiple buffer */        
302         struct vring_desc * buf_desc = &(q->desc[desc_idx]);
303         if (tx_one_pkt(core, virtio_state, buf_desc) == -1) {
304             PrintError("Virtio NIC: Error handling nic operation\n");
305             goto exit_error;
306         }
307         if(buf_desc->next & VIRTIO_NEXT_FLAG){
308             V3_Net_Print(2, "Virtio NIC: TX more buffer need to read\n");
309         }
310             
311         q->used->ring[q->used->index % q->queue_size].id = q->avail->ring[q->cur_avail_idx % q->queue_size];
312         q->used->ring[q->used->index % q->queue_size].length = buf_desc->length; /* What do we set this to???? */
313         q->used->index ++;
314         
315         q->cur_avail_idx ++;
316
317         txed ++;
318     }
319
320     v3_unlock_irqrestore(virtio_state->tx_lock, flags);
321
322     if (txed && !(q->avail->flags & VIRTIO_NO_IRQ_FLAG)) {
323         v3_pci_raise_irq(virtio_state->virtio_dev->pci_bus, 0, virtio_state->pci_dev);
324         virtio_state->virtio_cfg.pci_isr = 0x1;
325
326         virtio_state->stats.rx_interrupts ++;
327     }
328
329     if(txed > 0) {
330         V3_Net_Print(2, "Virtio Handle TX: txed pkts: %d\n", txed);
331     }
332
333     return 0;
334
335 exit_error:
336         
337     v3_unlock_irqrestore(virtio_state->tx_lock, flags);
338     return -1;
339 }
340
341
342 static int virtio_setup_queue(struct guest_info *core, 
343                               struct virtio_net_state * virtio_state, 
344                               struct virtio_queue * queue, 
345                               addr_t pfn, addr_t page_addr) {
346     queue->pfn = pfn;
347                 
348     queue->ring_desc_addr = page_addr;
349     queue->ring_avail_addr = page_addr + (queue->queue_size * sizeof(struct vring_desc));
350     queue->ring_used_addr = ((queue->ring_avail_addr) + 
351                              (sizeof(struct vring_avail)) + 
352                              (queue->queue_size * sizeof(uint16_t)));
353
354     // round up to next page boundary.
355     queue->ring_used_addr = (queue->ring_used_addr + 0xfff) & ~0xfff;
356     if (v3_gpa_to_hva(core, queue->ring_desc_addr, (addr_t *)&(queue->desc)) == -1) {
357         PrintError("Could not translate ring descriptor address\n");
358          return -1;
359     }
360  
361     if (v3_gpa_to_hva(core, queue->ring_avail_addr, (addr_t *)&(queue->avail)) == -1) {
362         PrintError("Could not translate ring available address\n");
363         return -1;
364     }
365
366     if (v3_gpa_to_hva(core, queue->ring_used_addr, (addr_t *)&(queue->used)) == -1) {
367         PrintError("Could not translate ring used address\n");
368         return -1;
369     }
370
371     PrintDebug("RingDesc_addr=%p, Avail_addr=%p, Used_addr=%p\n",
372                (void *)(queue->ring_desc_addr),
373                (void *)(queue->ring_avail_addr),
374                (void *)(queue->ring_used_addr));
375     
376     PrintDebug("RingDesc=%p, Avail=%p, Used=%p\n", 
377                queue->desc, queue->avail, queue->used);
378     
379     return 0;
380 }
381
382 static int virtio_io_write(struct guest_info *core, 
383                            uint16_t port, void * src, 
384                            uint_t length, void * private_data) 
385 {
386     struct virtio_net_state * virtio = (struct virtio_net_state *)private_data;
387     int port_idx = port % virtio->io_range_size;
388
389     PrintDebug("VIRTIO NIC %p Write for port %d (index=%d) len=%d, value=%x\n", private_data,
390                port, port_idx,  length, *(uint32_t *)src);
391
392     switch (port_idx) {
393         case GUEST_FEATURES_PORT:
394             if (length != 4) {
395                 PrintError("Illegal write length for guest features\n");
396                 return -1;
397             }       
398             virtio->virtio_cfg.guest_features = *(uint32_t *)src;
399             break;
400                 
401         case VRING_PG_NUM_PORT:
402             if (length != 4) {
403                 PrintError("Illegal write length for page frame number\n");
404                 return -1;
405             }
406             addr_t pfn = *(uint32_t *)src;
407             addr_t page_addr = (pfn << VIRTIO_PAGE_SHIFT);
408             uint16_t queue_idx = virtio->virtio_cfg.vring_queue_selector;
409             switch (queue_idx) {
410                 case 0:
411                     virtio_setup_queue(core, virtio, &virtio->rx_vq, pfn, page_addr);
412                     break;
413                 case 1:
414                     virtio_setup_queue(core, virtio, &virtio->tx_vq, pfn, page_addr);
415                     if(virtio->tx_notify == 0){
416                         disable_cb(&virtio->tx_vq);
417                         vnet_thread_wakeup(virtio->poll_thread);
418                     }
419                     break;
420                 case 2:
421                     virtio_setup_queue(core, virtio, &virtio->ctrl_vq, pfn, page_addr);
422                     break;          
423                 default:
424                     break;
425             }
426             break;
427                 
428         case VRING_Q_SEL_PORT:
429             virtio->virtio_cfg.vring_queue_selector = *(uint16_t *)src;
430             if (virtio->virtio_cfg.vring_queue_selector > 2) {
431                 PrintError("Virtio NIC: wrong queue idx: %d\n", 
432                            virtio->virtio_cfg.vring_queue_selector);
433                 return -1;
434             }
435             break;
436                 
437         case VRING_Q_NOTIFY_PORT: 
438             {
439                 uint16_t queue_idx = *(uint16_t *)src;                  
440                 if (queue_idx == 0){
441                     /* receive queue refill */
442                     virtio->stats.tx_interrupts ++;
443                 } else if (queue_idx == 1){
444                     if (handle_pkt_tx(core, virtio) == -1) {
445                         PrintError("Could not handle Virtio NIC tx kick\n");
446                         return -1;
447                     }
448                     virtio->stats.tx_interrupts ++;
449                 } else if (queue_idx == 2){
450                     /* ctrl */
451                 } else {
452                     PrintError("Wrong queue index %d\n", queue_idx);
453                 }       
454                 break;          
455             }
456         
457         case VIRTIO_STATUS_PORT:
458             virtio->virtio_cfg.status = *(uint8_t *)src;
459             if (virtio->virtio_cfg.status == 0) {
460                 virtio_init_state(virtio);
461             }
462             break;
463
464         case VIRTIO_ISR_PORT:
465             virtio->virtio_cfg.pci_isr = *(uint8_t *)src;
466             break;
467                 
468         default:
469             return -1;
470             break;
471     }
472
473     return length;
474 }
475
476 static int virtio_io_read(struct guest_info *core, 
477                           uint16_t port, void * dst, 
478                           uint_t length, void * private_data) 
479 {
480     struct virtio_net_state * virtio = (struct virtio_net_state *)private_data;
481     int port_idx = port % virtio->io_range_size;
482     uint16_t queue_idx = virtio->virtio_cfg.vring_queue_selector;
483
484     PrintDebug("Virtio NIC %p: Read  for port 0x%x (index =%d), length=%d\n", private_data,
485                port, port_idx, length);
486         
487     switch (port_idx) {
488         case HOST_FEATURES_PORT:
489             if (length != 4) {
490                 PrintError("Illegal read length for host features\n");
491                 //return -1;
492             }
493             *(uint32_t *)dst = virtio->virtio_cfg.host_features;
494             break;
495
496         case VRING_PG_NUM_PORT:
497             if (length != 4) {
498                 PrintError("Illegal read length for page frame number\n");
499                 return -1;
500             }
501             switch (queue_idx) {
502                 case 0:
503                     *(uint32_t *)dst = virtio->rx_vq.pfn;
504                     break;
505                 case 1:
506                     *(uint32_t *)dst = virtio->tx_vq.pfn;
507                     break;      
508                 case 2:
509                     *(uint32_t *)dst = virtio->ctrl_vq.pfn;
510                     break;
511                 default:
512                     break;
513             }
514             break;
515
516         case VRING_SIZE_PORT:
517             if (length != 2) {
518                 PrintError("Illegal read length for vring size\n");
519                 return -1;
520             }
521             switch (queue_idx) {
522                 case 0:
523                     *(uint16_t *)dst = virtio->rx_vq.queue_size;
524                     break;
525                 case 1:
526                     *(uint16_t *)dst = virtio->tx_vq.queue_size;
527                     break;      
528                 case 2:
529                     *(uint16_t *)dst = virtio->ctrl_vq.queue_size;
530                     break;
531                 default:
532                     break;
533             }
534             break;
535
536         case VIRTIO_STATUS_PORT:
537             if (length != 1) {
538                 PrintError("Illegal read length for status\n");
539                 return -1;
540             }
541             *(uint8_t *)dst = virtio->virtio_cfg.status;
542             break;
543                 
544         case VIRTIO_ISR_PORT:
545             *(uint8_t *)dst = virtio->virtio_cfg.pci_isr;
546             virtio->virtio_cfg.pci_isr = 0;
547             v3_pci_lower_irq(virtio->virtio_dev->pci_bus, 0, virtio->pci_dev);
548             break;
549
550         case VIRTIO_NET_CONFIG ... VIRTIO_NET_CONFIG + ETH_ALEN:
551             *(uint8_t *)dst = virtio->net_cfg.mac[port_idx-VIRTIO_NET_CONFIG];
552             break;
553
554         default:
555             PrintError("Virtio NIC: Read of Unhandled Virtio Read:%d\n", port_idx);
556             return -1;
557     }
558
559     return length;
560 }
561
562
563 /* receiving raw ethernet pkt from backend */
564 static int virtio_rx(uint8_t * buf, uint32_t size, void * private_data) {
565     struct virtio_net_state * virtio = (struct virtio_net_state *)private_data;
566     struct virtio_queue * q = &(virtio->rx_vq);
567     struct virtio_net_hdr_mrg_rxbuf hdr;
568     uint32_t data_len;
569     unsigned long flags;
570
571     V3_Net_Print(2, "Virtio-NIC: virtio_rx: size: %d\n", size);
572     if(net_debug >= 4){
573         v3_hexdump(buf, size, NULL, 0);
574     }
575
576     flags = v3_lock_irqsave(virtio->rx_lock);
577
578     data_len = size;
579     memset(&hdr, 0, sizeof(struct virtio_net_hdr_mrg_rxbuf));
580
581     if (q->ring_avail_addr == 0) {
582         V3_Net_Print(2, "Virtio NIC: RX Queue not set\n");
583         virtio->stats.rx_dropped ++;
584         goto err_exit;
585     }
586
587     if (q->cur_avail_idx != q->avail->index){
588         addr_t hdr_addr = 0;
589         uint16_t buf_idx = 0;
590         uint16_t hdr_idx = q->avail->ring[q->cur_avail_idx % q->queue_size];
591         struct vring_desc * hdr_desc = NULL;
592         struct vring_desc * buf_desc = NULL;
593         uint32_t hdr_len = 0;
594         uint32_t len;
595
596         hdr_desc = &(q->desc[hdr_idx]);
597         if (v3_gpa_to_hva(&(virtio->virtio_dev->vm->cores[0]), hdr_desc->addr_gpa, &(hdr_addr)) == -1) {
598             V3_Net_Print(2, "Virtio NIC: Could not translate receive buffer address\n");
599             virtio->stats.rx_dropped ++;
600             goto err_exit;
601         }
602
603         hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
604
605         if(virtio->mergeable_rx_bufs){/* merged buffer */
606             uint32_t offset = 0;
607             len = 0;
608             hdr.num_buffers = 0;
609
610             hdr_desc = &(q->desc[buf_idx]);
611             hdr_desc->flags &= ~VIRTIO_NEXT_FLAG;
612
613             len = copy_data_to_desc(&(virtio->virtio_dev->vm->cores[0]), virtio, hdr_desc, buf, data_len, hdr_len);
614             offset += len;
615
616             hdr.num_buffers ++;
617             q->used->ring[q->used->index % q->queue_size].id = q->avail->ring[q->cur_avail_idx % q->queue_size];
618             q->used->ring[q->used->index % q->queue_size].length = hdr_len + len;
619             q->cur_avail_idx ++;
620
621             while(offset < data_len) {
622                 buf_idx = q->avail->ring[q->cur_avail_idx % q->queue_size];
623                 buf_desc = &(q->desc[buf_idx]);
624
625                 len = copy_data_to_desc(&(virtio->virtio_dev->vm->cores[0]), virtio, buf_desc, buf + offset, data_len - offset, 0);     
626                 if (len <= 0){
627                     V3_Net_Print(2, "Virtio NIC:merged buffer, %d buffer size %d\n", hdr.num_buffers, data_len);
628                     virtio->stats.rx_dropped ++;
629                     goto err_exit;
630                 }
631                 offset += len;
632                 buf_desc->flags &= ~VIRTIO_NEXT_FLAG;
633
634                 hdr.num_buffers ++;
635                 q->used->ring[(q->used->index + hdr.num_buffers) % q->queue_size].id = q->avail->ring[q->cur_avail_idx % q->queue_size];
636                 q->used->ring[(q->used->index + hdr.num_buffers) % q->queue_size].length = len;
637                 q->cur_avail_idx ++;   
638             }
639             q->used->index += hdr.num_buffers;
640             copy_data_to_desc(&(virtio->virtio_dev->vm->cores[0]), virtio, hdr_desc, (uchar_t *)&hdr, hdr_len, 0);
641         }else{
642             hdr_desc = &(q->desc[buf_idx]);
643             copy_data_to_desc(&(virtio->virtio_dev->vm->cores[0]), virtio, hdr_desc, (uchar_t *)&hdr, hdr_len, 0);
644
645             buf_idx = hdr_desc->next;
646             buf_desc = &(q->desc[buf_idx]);
647             len = copy_data_to_desc(&(virtio->virtio_dev->vm->cores[0]), virtio, buf_desc, buf, data_len, 0);       
648             if (len < data_len) {
649                 V3_Net_Print(2, "Virtio NIC: ring buffer len less than pkt size, merged buffer not supported, buffer size %d\n", len);
650                 virtio->stats.rx_dropped ++;
651                 
652                 goto err_exit;
653             }
654             buf_desc->flags &= ~VIRTIO_NEXT_FLAG;
655                 
656             q->used->ring[q->used->index % q->queue_size].id = q->avail->ring[q->cur_avail_idx % q->queue_size];
657             q->used->ring[q->used->index % q->queue_size].length = data_len + hdr_len; /* This should be the total length of data sent to guest (header+pkt_data) */
658             q->used->index++;
659             q->cur_avail_idx++;
660         } 
661
662         virtio->stats.rx_pkts ++;
663         virtio->stats.rx_bytes += size;
664     } else {
665         V3_Net_Print(2, "Virtio NIC: Guest RX queue is full\n");
666         virtio->stats.rx_dropped ++;
667
668         /* kick guest to refill the queue */
669         virtio->virtio_cfg.pci_isr = 0x1;       
670         v3_pci_raise_irq(virtio->virtio_dev->pci_bus, 0, virtio->pci_dev);
671         v3_interrupt_cpu(virtio->virtio_dev->vm, virtio->virtio_dev->vm->cores[0].pcpu_id, 0);
672         virtio->stats.rx_interrupts ++;
673         
674         goto err_exit;
675     }
676
677     if (!(q->avail->flags & VIRTIO_NO_IRQ_FLAG)) {
678         V3_Net_Print(2, "Raising IRQ %d\n",  virtio->pci_dev->config_header.intr_line);
679
680         virtio->virtio_cfg.pci_isr = 0x1;       
681         v3_pci_raise_irq(virtio->virtio_dev->pci_bus, 0, virtio->pci_dev);
682
683         virtio->stats.rx_interrupts ++;
684     }
685
686     v3_unlock_irqrestore(virtio->rx_lock, flags);
687
688     /* notify guest if it is in guest mode */
689     if(virtio->rx_notify == 1 && 
690         V3_Get_CPU() != virtio->virtio_dev->vm->cores[0].pcpu_id){
691         v3_interrupt_cpu(virtio->virtio_dev->vm, virtio->virtio_dev->vm->cores[0].pcpu_id, 0);
692     }
693
694     return 0;
695
696 err_exit:
697
698     v3_unlock_irqrestore(virtio->rx_lock, flags);
699  
700     return -1;
701 }
702
703 static int virtio_free(struct virtio_dev_state * virtio) {
704     struct virtio_net_state * backend = NULL;
705     struct virtio_net_state * tmp = NULL;
706
707
708     list_for_each_entry_safe(backend, tmp, &(virtio->dev_list), dev_link) {
709
710         // unregister from PCI
711
712         list_del(&(backend->dev_link));
713         V3_Free(backend);
714     }
715
716     V3_Free(virtio);
717     return 0;
718 }
719
720
721 static struct v3_device_ops dev_ops = {
722     .free = (int (*)(void *))virtio_free,
723 };
724
725
726 static int virtio_tx_flush(void * args){
727     struct virtio_net_state *virtio  = (struct virtio_net_state *)args;
728
729     V3_Print("Virtio TX Poll Thread Starting for %s\n", virtio->vm->name);
730
731     while(1){
732         if(virtio->tx_notify == 0){
733             handle_pkt_tx(&(virtio->vm->cores[0]), virtio);
734             v3_yield(NULL);
735         }else {
736             vnet_thread_sleep(-1);
737         }
738     }
739
740     return 0;
741 }
742
743 static int register_dev(struct virtio_dev_state * virtio, 
744                         struct virtio_net_state * net_state) 
745 {
746     struct pci_device * pci_dev = NULL;
747     struct v3_pci_bar bars[6];
748     int num_ports = sizeof(struct virtio_config);
749     int tmp_ports = num_ports;
750     int i;
751
752     // This gets the number of ports, rounded up to a power of 2
753     net_state->io_range_size = 1; // must be a power of 2
754     while (tmp_ports > 0) {
755         tmp_ports >>= 1;
756         net_state->io_range_size <<= 1;
757     }
758         
759     /* this is to account for any low order bits being set in num_ports
760       * if there are none, then num_ports was already a power of 2 so we shift right to reset it
761       */
762     if ((num_ports & ((net_state->io_range_size >> 1) - 1)) == 0) {
763         net_state->io_range_size >>= 1;
764     }
765     
766     for (i = 0; i < 6; i++) {
767         bars[i].type = PCI_BAR_NONE;
768     }
769     
770     PrintDebug("Virtio-NIC io_range_size = %d\n", net_state->io_range_size);
771     
772     bars[0].type = PCI_BAR_IO;
773     bars[0].default_base_port = -1;
774     bars[0].num_ports = net_state->io_range_size;
775     bars[0].io_read = virtio_io_read;
776     bars[0].io_write = virtio_io_write;
777     bars[0].private_data = net_state;
778     
779     pci_dev = v3_pci_register_device(virtio->pci_bus, PCI_STD_DEVICE, 
780                                      0, 4/*PCI_AUTO_DEV_NUM*/, 0,
781                                      "LNX_VIRTIO_NIC", bars,
782                                      NULL, NULL, NULL, net_state);
783     
784     if (!pci_dev) {
785         PrintError("Virtio NIC: Could not register PCI Device\n");
786         return -1;
787     }
788
789     PrintDebug("Virtio NIC:  registered to PCI bus\n");
790     
791     pci_dev->config_header.vendor_id = VIRTIO_VENDOR_ID;
792     pci_dev->config_header.subsystem_vendor_id = VIRTIO_SUBVENDOR_ID;
793         
794
795     pci_dev->config_header.device_id = VIRTIO_NET_DEV_ID;
796     pci_dev->config_header.class = PCI_CLASS_NETWORK;
797     pci_dev->config_header.subclass = PCI_NET_SUBCLASS_OTHER;  
798     pci_dev->config_header.subsystem_id = VIRTIO_NET_SUBDEVICE_ID;
799     pci_dev->config_header.intr_pin = 1;
800     pci_dev->config_header.max_latency = 1; // ?? (qemu does it...)
801
802     net_state->pci_dev = pci_dev;
803     net_state->virtio_dev = virtio;
804
805     memcpy(net_state->net_cfg.mac, virtio->mac, 6);                           
806         
807     virtio_init_state(net_state);
808
809     /* Add backend to list of devices */
810     list_add(&(net_state->dev_link), &(virtio->dev_list));
811
812     return 0;
813 }
814
815
816 #define RATE_UPPER_THRESHOLD 10  /* 10000 pkts per second, around 100Mbits */
817 #define RATE_LOWER_THRESHOLD 1
818 #define PROFILE_PERIOD 10000 /*us*/
819
820 static void virtio_nic_timer(struct guest_info * core, 
821                              uint64_t cpu_cycles, uint64_t cpu_freq, 
822                              void * priv_data) {
823     struct virtio_net_state * net_state = (struct virtio_net_state *)priv_data;
824     uint64_t period_us;
825     static int profile_ms = 0;
826
827     if(!net_state->status){ /* VNIC is not in working status */
828         return;
829     }
830
831     period_us = (1000*cpu_cycles)/cpu_freq;
832     net_state->past_us += period_us;
833
834     if(net_state->past_us > PROFILE_PERIOD){ 
835         uint32_t tx_rate, rx_rate;
836         
837         tx_rate = (net_state->stats.tx_pkts - net_state->tx_pkts)/(net_state->past_us/1000); /* pkts/per ms */
838         rx_rate = (net_state->stats.rx_pkts - net_state->rx_pkts)/(net_state->past_us/1000);
839
840         net_state->tx_pkts = net_state->stats.tx_pkts;
841         net_state->rx_pkts = net_state->stats.rx_pkts;
842
843         if(tx_rate > RATE_UPPER_THRESHOLD && net_state->tx_notify == 1){
844             V3_Print("Virtio NIC: Switch TX to VMM driven mode\n");
845             disable_cb(&(net_state->tx_vq));
846             net_state->tx_notify = 0;
847             vnet_thread_wakeup(net_state->poll_thread);
848         }
849
850         if(tx_rate < RATE_LOWER_THRESHOLD && net_state->tx_notify == 0){
851             V3_Print("Virtio NIC: Switch TX to Guest  driven mode\n");
852             enable_cb(&(net_state->tx_vq));
853             net_state->tx_notify = 1;
854         }
855
856         if(rx_rate > RATE_UPPER_THRESHOLD && net_state->rx_notify == 1){
857             V3_Print("Virtio NIC: Switch RX to VMM None notify mode\n");
858             net_state->rx_notify = 0;
859         }
860
861         if(rx_rate < RATE_LOWER_THRESHOLD && net_state->rx_notify == 0){
862             V3_Print("Virtio NIC: Switch RX to VMM notify mode\n");
863             net_state->rx_notify = 1;
864         }
865
866         net_state->past_us = 0;
867     }
868
869     profile_ms += period_us/1000;
870     if(profile_ms > 20000){
871         V3_Net_Print(1, "Virtio NIC: TX: Pkt: %lld, Bytes: %lld\n\t\tRX Pkt: %lld. Bytes: %lld\n\t\tDropped: tx %lld, rx %lld\nInterrupts: tx %d, rx %d\nTotal Exit: %lld\n",
872                 net_state->stats.tx_pkts, net_state->stats.tx_bytes,
873                 net_state->stats.rx_pkts, net_state->stats.rx_bytes,
874                 net_state->stats.tx_dropped, net_state->stats.rx_dropped,
875                 net_state->stats.tx_interrupts, net_state->stats.rx_interrupts,
876                 net_state->vm->cores[0].num_exits);
877         profile_ms = 0;
878     }
879 }
880
881 static struct v3_timer_ops timer_ops = {
882     .update_timer = virtio_nic_timer,
883 };
884
885
886 static int connect_fn(struct v3_vm_info * info, 
887                       void * frontend_data, 
888                       struct v3_dev_net_ops * ops, 
889                       v3_cfg_tree_t * cfg, 
890                       void * private_data) {
891     struct virtio_dev_state * virtio = (struct virtio_dev_state *)frontend_data;
892     struct virtio_net_state * net_state  = (struct virtio_net_state *)V3_Malloc(sizeof(struct virtio_net_state));
893
894     memset(net_state, 0, sizeof(struct virtio_net_state));
895     register_dev(virtio, net_state);
896
897     net_state->vm = info;
898     net_state->net_ops = ops;
899     net_state->backend_data = private_data;
900     net_state->virtio_dev = virtio;
901     net_state->tx_notify = 0;
902     net_state->rx_notify = 0;
903         
904     net_state->timer = v3_add_timer(&(info->cores[0]),&timer_ops,net_state);
905
906     PrintError("net_state 0x%p\n", (void *)net_state);
907
908     ops->recv = virtio_rx;
909     ops->frontend_data = net_state;
910     memcpy(ops->fnt_mac, virtio->mac, ETH_ALEN);
911
912     net_state->poll_thread = vnet_start_thread(virtio_tx_flush, (void *)net_state, "Virtio_Poll");
913
914     net_state->status = 1;
915
916     return 0;
917 }
918
919 static int virtio_init(struct v3_vm_info * vm, v3_cfg_tree_t * cfg) {
920     struct vm_device * pci_bus = v3_find_dev(vm, v3_cfg_val(cfg, "bus"));
921     struct virtio_dev_state * virtio_state = NULL;
922     char * dev_id = v3_cfg_val(cfg, "ID");
923     char macstr[128];
924     char * str = v3_cfg_val(cfg, "mac");
925     memcpy(macstr, str, strlen(str));
926
927     if (pci_bus == NULL) {
928         PrintError("Virtio NIC: VirtIO devices require a PCI Bus");
929         return -1;
930     }
931
932     virtio_state  = (struct virtio_dev_state *)V3_Malloc(sizeof(struct virtio_dev_state));
933     memset(virtio_state, 0, sizeof(struct virtio_dev_state));
934
935     INIT_LIST_HEAD(&(virtio_state->dev_list));
936     virtio_state->pci_bus = pci_bus;
937     virtio_state->vm = vm;
938
939     if (macstr != NULL && !str2mac(macstr, virtio_state->mac)) {
940         PrintDebug("Virtio NIC: Mac specified %s\n", macstr);
941     }else {
942         random_ethaddr(virtio_state->mac);
943     }
944
945     struct vm_device * dev = v3_add_device(vm, dev_id, &dev_ops, virtio_state);
946
947     if (dev == NULL) {
948         PrintError("Virtio NIC: Could not attach device %s\n", dev_id);
949         V3_Free(virtio_state);
950         return -1;
951     }
952
953     if (v3_dev_add_net_frontend(vm, dev_id, connect_fn, (void *)virtio_state) == -1) {
954         PrintError("Virtio NIC: Could not register %s as net frontend\n", dev_id);
955         v3_remove_device(dev);
956         return -1;
957     }
958         
959     return 0;
960 }
961
962 device_register("LNX_VIRTIO_NIC", virtio_init)
963