Collect per Q stats for vhost-user interface
[vpp.git] / vnet / vnet / devices / dpdk / device.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <vnet/vnet.h>
16 #include <vppinfra/vec.h>
17 #include <vppinfra/format.h>
18 #include <vlib/unix/cj.h>
19 #include <assert.h>
20
21 #include <vnet/ethernet/ethernet.h>
22 #include <vnet/devices/dpdk/dpdk.h>
23
24 #include "dpdk_priv.h"
25 #include <vppinfra/error.h>
26
27 #define foreach_dpdk_tx_func_error                      \
28   _(BAD_RETVAL, "DPDK tx function returned an error")   \
29   _(RING_FULL, "Tx packet drops (ring full)")           \
30   _(PKT_DROP, "Tx packet drops (dpdk tx failure)")      \
31   _(REPL_FAIL, "Tx packet drops (replication failure)")
32
33 typedef enum {
34 #define _(f,s) DPDK_TX_FUNC_ERROR_##f,
35   foreach_dpdk_tx_func_error
36 #undef _
37   DPDK_TX_FUNC_N_ERROR,
38 } dpdk_tx_func_error_t;
39
40 static char * dpdk_tx_func_error_strings[] = {
41 #define _(n,s) s,
42     foreach_dpdk_tx_func_error
43 #undef _
44 };
45
46 clib_error_t *
47 dpdk_set_mac_address (vnet_hw_interface_t * hi, char * address)
48 {
49    int error;
50    dpdk_main_t * dm = &dpdk_main;
51    dpdk_device_t * xd = vec_elt_at_index (dm->devices, hi->dev_instance);
52
53    error=rte_eth_dev_default_mac_addr_set(xd->device_index,
54                                           (struct ether_addr *) address);
55
56    if (error) {
57      return clib_error_return (0, "mac address set failed: %d", error);
58    } else {
59      return NULL;
60   }
61 }
62
63 clib_error_t *
64 dpdk_set_mc_filter (vnet_hw_interface_t * hi,
65                     struct ether_addr mc_addr_vec[], int naddr)
66 {
67   int error;
68   dpdk_main_t * dm = &dpdk_main;
69   dpdk_device_t * xd = vec_elt_at_index (dm->devices, hi->dev_instance);
70
71   error=rte_eth_dev_set_mc_addr_list(xd->device_index, mc_addr_vec, naddr);
72
73   if (error) {
74     return clib_error_return (0, "mc addr list failed: %d", error);
75   } else {
76     return NULL;
77   }
78 }
79
80 static struct rte_mbuf * dpdk_replicate_packet_mb (vlib_buffer_t * b)
81 {
82   vlib_main_t * vm = vlib_get_main();
83   vlib_buffer_main_t * bm = vm->buffer_main;
84   struct rte_mbuf * first_mb = 0, * new_mb, * pkt_mb, ** prev_mb_next = 0;
85   u8 nb_segs, nb_segs_left;
86   u32 copy_bytes;
87   unsigned socket_id = rte_socket_id();
88
89   ASSERT (bm->pktmbuf_pools[socket_id]);
90   pkt_mb = ((struct rte_mbuf *)b)-1;
91   nb_segs = pkt_mb->nb_segs;
92   for (nb_segs_left = nb_segs; nb_segs_left; nb_segs_left--)
93     {
94       if (PREDICT_FALSE(pkt_mb == 0))
95         {
96           clib_warning ("Missing %d mbuf chain segment(s):   "
97                         "(nb_segs = %d, nb_segs_left = %d)!",
98                         nb_segs - nb_segs_left, nb_segs, nb_segs_left);
99           if (first_mb)
100             rte_pktmbuf_free(first_mb);
101           return NULL;
102         }
103       new_mb = rte_pktmbuf_alloc (bm->pktmbuf_pools[socket_id]);
104       if (PREDICT_FALSE(new_mb == 0))
105         {
106           if (first_mb)
107             rte_pktmbuf_free(first_mb);
108           return NULL;
109         }
110       
111       /*
112        * Copy packet info into 1st segment.
113        */
114       if (first_mb == 0)
115         {
116           first_mb = new_mb;
117           rte_pktmbuf_pkt_len (first_mb) = pkt_mb->pkt_len;
118           first_mb->nb_segs = pkt_mb->nb_segs;
119           first_mb->port = pkt_mb->port;
120 #ifdef DAW_FIXME // TX Offload support TBD
121           first_mb->vlan_macip = pkt_mb->vlan_macip;
122           first_mb->hash = pkt_mb->hash;
123           first_mb->ol_flags = pkt_mb->ol_flags
124 #endif
125         }
126       else
127         {
128           ASSERT(prev_mb_next != 0);
129           *prev_mb_next = new_mb;
130         }
131       
132       /*
133        * Copy packet segment data into new mbuf segment.
134        */
135       rte_pktmbuf_data_len (new_mb) = pkt_mb->data_len;
136       copy_bytes = pkt_mb->data_len + RTE_PKTMBUF_HEADROOM;
137       ASSERT(copy_bytes <= pkt_mb->buf_len);
138       memcpy(new_mb->buf_addr, pkt_mb->buf_addr, copy_bytes);
139
140       prev_mb_next = &new_mb->next;
141       pkt_mb = pkt_mb->next;
142     }
143
144   ASSERT(pkt_mb == 0);
145   __rte_mbuf_sanity_check(first_mb, 1);
146
147   return first_mb;
148 }
149
150 static void
151 dpdk_tx_trace_buffer (dpdk_main_t * dm,
152                       vlib_node_runtime_t * node,
153                       dpdk_device_t * xd,
154                       u16 queue_id,
155                       u32 buffer_index,
156                       vlib_buffer_t * buffer)
157 {
158   vlib_main_t * vm = vlib_get_main();
159   dpdk_tx_dma_trace_t * t0;
160   struct rte_mbuf * mb;
161
162   mb = ((struct rte_mbuf *)buffer)-1;
163
164   t0 = vlib_add_trace (vm, node, buffer, sizeof (t0[0]));
165   t0->queue_index = queue_id;
166   t0->device_index = xd->device_index;
167   t0->buffer_index = buffer_index;
168   memcpy (&t0->mb, mb, sizeof (t0->mb));
169   memcpy (&t0->buffer, buffer, sizeof (buffer[0]) - sizeof (buffer->pre_data));
170   memcpy (t0->buffer.pre_data, buffer->data + buffer->current_data,
171           sizeof (t0->buffer.pre_data));
172 }
173
174 /*
175  * This function calls the dpdk's tx_burst function to transmit the packets
176  * on the tx_vector. It manages a lock per-device if the device does not
177  * support multiple queues. It returns the number of packets untransmitted 
178  * on the tx_vector. If all packets are transmitted (the normal case), the 
179  * function returns 0.
180  * 
181  * The tx_burst function may not be able to transmit all packets because the 
182  * dpdk ring is full. If a flowcontrol callback function has been configured
183  * then the function simply returns. If no callback has been configured, the 
184  * function will retry calling tx_burst with the remaining packets. This will 
185  * continue until all packets are transmitted or tx_burst indicates no packets
186  * could be transmitted. (The caller can drop the remaining packets.)
187  *
188  * The function assumes there is at least one packet on the tx_vector.
189  */
190 static_always_inline
191 u32 tx_burst_vector_internal (vlib_main_t * vm, 
192                               dpdk_device_t * xd,
193                               struct rte_mbuf ** tx_vector)
194 {
195   dpdk_main_t * dm = &dpdk_main;
196   u32 n_packets;
197   u32 tx_head;
198   u32 tx_tail;
199   u32 n_retry;
200   int rv;
201   int queue_id;
202   tx_ring_hdr_t *ring;
203
204   ring = vec_header(tx_vector, sizeof(*ring));
205
206   n_packets = ring->tx_head - ring->tx_tail;
207
208   tx_head = ring->tx_head % DPDK_TX_RING_SIZE;
209
210   /*
211    * Ensure rte_eth_tx_burst is not called with 0 packets, which can lead to
212    * unpredictable results.
213    */
214   ASSERT(n_packets > 0);
215
216   /*
217    * Check for tx_vector overflow. If this fails it is a system configuration
218    * error. The ring should be sized big enough to handle the largest un-flowed
219    * off burst from a traffic manager. A larger size also helps performance
220    * a bit because it decreases the probability of having to issue two tx_burst
221    * calls due to a ring wrap.
222    */
223   ASSERT(n_packets < DPDK_TX_RING_SIZE);
224
225   /*
226    * If there is no flowcontrol callback, there is only temporary buffering
227    * on the tx_vector and so the tail should always be 0.
228    */
229   ASSERT(dm->flowcontrol_callback || ring->tx_tail == 0);
230
231   /*
232    * If there is a flowcontrol callback, don't retry any incomplete tx_bursts. 
233    * Apply backpressure instead. If there is no callback, keep retrying until
234    * a tx_burst sends no packets. n_retry of 255 essentially means no retry 
235    * limit.
236    */
237   n_retry = dm->flowcontrol_callback ? 0 : 255;
238
239   queue_id = vm->cpu_index;
240
241   do {
242       /* start the burst at the tail */
243       tx_tail = ring->tx_tail % DPDK_TX_RING_SIZE;
244
245       /* 
246        * This device only supports one TX queue,
247        * and we're running multi-threaded...
248        */
249       if (PREDICT_FALSE(xd->dev_type != VNET_DPDK_DEV_VHOST_USER &&
250         xd->lockp != 0))
251         {
252           queue_id = queue_id % xd->tx_q_used;
253           while (__sync_lock_test_and_set (xd->lockp[queue_id], 1))
254             /* zzzz */
255             queue_id = (queue_id + 1) % xd->tx_q_used;
256         }
257
258       if (PREDICT_TRUE(xd->dev_type == VNET_DPDK_DEV_ETH)) 
259         {
260           if (PREDICT_TRUE(tx_head > tx_tail)) 
261             {
262               /* no wrap, transmit in one burst */
263               rv = rte_eth_tx_burst(xd->device_index, 
264                                     (uint16_t) queue_id,
265                                     &tx_vector[tx_tail], 
266                                     (uint16_t) (tx_head-tx_tail));
267             }
268           else 
269             {
270               /* 
271                * This can only happen if there is a flowcontrol callback.
272                * We need to split the transmit into two calls: one for
273                * the packets up to the wrap point, and one to continue
274                * at the start of the ring.
275                * Transmit pkts up to the wrap point.
276                */
277               rv = rte_eth_tx_burst(xd->device_index, 
278                                     (uint16_t) queue_id,
279                                     &tx_vector[tx_tail], 
280                                     (uint16_t) (DPDK_TX_RING_SIZE - tx_tail));
281
282               /* 
283                * If we transmitted everything we wanted, then allow 1 retry 
284                * so we can try to transmit the rest. If we didn't transmit
285                * everything, stop now.
286                */
287               n_retry = (rv == DPDK_TX_RING_SIZE - tx_tail) ? 1 : 0;
288             }
289         } 
290       else if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER)
291         {
292           u32 offset = 0;
293           if (xd->need_txlock) {
294             queue_id = 0;
295             while (__sync_lock_test_and_set (xd->lockp[queue_id], 1));
296           }
297 #if RTE_VERSION >= RTE_VERSION_NUM(2, 2, 0, 0)
298           else {
299               dpdk_device_and_queue_t * dq;
300               vec_foreach (dq, dm->devices_by_cpu[vm->cpu_index])
301               {
302                 if (xd->device_index == dq->device)
303                     break; 
304               }
305               assert (dq);
306               offset = dq->queue_id * VIRTIO_QNUM;
307           }
308 #endif
309           if (PREDICT_TRUE(tx_head > tx_tail)) 
310             {
311               int i; u32 bytes = 0;
312               struct rte_mbuf **pkts = &tx_vector[tx_tail];
313               for (i = 0; i < (tx_head - tx_tail); i++) {
314                   struct rte_mbuf *buff = pkts[i];
315                   bytes += rte_pktmbuf_data_len(buff);
316               } 
317                 
318               /* no wrap, transmit in one burst */
319               rv = rte_vhost_enqueue_burst(&xd->vu_vhost_dev, offset + VIRTIO_RXQ,
320                                            &tx_vector[tx_tail],
321                                            (uint16_t) (tx_head-tx_tail));
322               if (PREDICT_TRUE(rv > 0))
323                 {
324                   dpdk_vu_vring *vring = &(xd->vu_intf->vrings[offset + VIRTIO_RXQ]);
325                   vring->packets += rv;
326                   vring->bytes += bytes;
327
328                   if (dpdk_vhost_user_want_interrupt(xd, offset + VIRTIO_RXQ)) {
329                     vring->n_since_last_int += rv;
330
331                     f64 now = vlib_time_now (vm);
332                     if (vring->int_deadline < now ||
333                         vring->n_since_last_int > dm->vhost_coalesce_frames)
334                       dpdk_vhost_user_send_interrupt(vm, xd, offset + VIRTIO_RXQ);
335                   }
336
337                   int c = rv;
338                   while(c--)
339                     rte_pktmbuf_free (tx_vector[tx_tail+c]);
340                 }
341             }
342           else
343             {
344               /*
345                * If we transmitted everything we wanted, then allow 1 retry
346                * so we can try to transmit the rest. If we didn't transmit
347                * everything, stop now.
348                */
349               int i; u32 bytes = 0;
350               struct rte_mbuf **pkts = &tx_vector[tx_tail];
351               for (i = 0; i < (DPDK_TX_RING_SIZE - tx_tail); i++) {
352                   struct rte_mbuf *buff = pkts[i];
353                   bytes += rte_pktmbuf_data_len(buff);
354               }
355               rv = rte_vhost_enqueue_burst(&xd->vu_vhost_dev, offset + VIRTIO_RXQ,
356                                            &tx_vector[tx_tail], 
357                                            (uint16_t) (DPDK_TX_RING_SIZE - tx_tail));
358
359               if (PREDICT_TRUE(rv > 0))
360                 {
361                   dpdk_vu_vring *vring = &(xd->vu_intf->vrings[offset + VIRTIO_RXQ]);
362                   vring->packets += rv;
363                   vring->bytes += bytes;
364
365                   if (dpdk_vhost_user_want_interrupt(xd, offset + VIRTIO_RXQ)) {
366                     vring->n_since_last_int += rv;
367
368                     f64 now = vlib_time_now (vm);
369                     if (vring->int_deadline < now ||
370                         vring->n_since_last_int > dm->vhost_coalesce_frames)
371                       dpdk_vhost_user_send_interrupt(vm, xd, offset + VIRTIO_RXQ);
372                   }
373
374                   int c = rv;
375                   while(c--)
376                     rte_pktmbuf_free (tx_vector[tx_tail+c]);
377                 }
378
379               n_retry = (rv == DPDK_TX_RING_SIZE - tx_tail) ? 1 : 0;
380             }
381
382           if (xd->need_txlock)
383             *xd->lockp[queue_id] = 0;
384         }
385 #if RTE_LIBRTE_KNI
386       else if (xd->dev_type == VNET_DPDK_DEV_KNI)
387         {
388           if (PREDICT_TRUE(tx_head > tx_tail)) 
389             {
390               /* no wrap, transmit in one burst */
391               rv = rte_kni_tx_burst(xd->kni, 
392                                     &tx_vector[tx_tail], 
393                                     (uint16_t) (tx_head-tx_tail));
394             }
395           else 
396             {
397               /* 
398                * This can only happen if there is a flowcontrol callback.
399                * We need to split the transmit into two calls: one for
400                * the packets up to the wrap point, and one to continue
401                * at the start of the ring.
402                * Transmit pkts up to the wrap point.
403                */
404               rv = rte_kni_tx_burst(xd->kni, 
405                                     &tx_vector[tx_tail], 
406                                     (uint16_t) (DPDK_TX_RING_SIZE - tx_tail));
407
408               /* 
409                * If we transmitted everything we wanted, then allow 1 retry 
410                * so we can try to transmit the rest. If we didn't transmit
411                * everything, stop now.
412                */
413               n_retry = (rv == DPDK_TX_RING_SIZE - tx_tail) ? 1 : 0;
414             }
415         } 
416 #endif
417       else
418         {
419           ASSERT(0);
420           rv = 0;
421         }
422
423       if (PREDICT_FALSE(xd->dev_type != VNET_DPDK_DEV_VHOST_USER &&
424             xd->lockp != 0))
425           *xd->lockp[queue_id] = 0;
426
427       if (PREDICT_FALSE(rv < 0))
428         {
429           // emit non-fatal message, bump counter
430           vnet_main_t * vnm = dm->vnet_main;
431           vnet_interface_main_t * im = &vnm->interface_main;
432           u32 node_index;
433
434           node_index = vec_elt_at_index(im->hw_interfaces, 
435                                         xd->vlib_hw_if_index)->tx_node_index;
436
437           vlib_error_count (vm, node_index, DPDK_TX_FUNC_ERROR_BAD_RETVAL, 1);
438           clib_warning ("rte_eth_tx_burst[%d]: error %d", xd->device_index, rv);
439           return n_packets; // untransmitted packets
440         }
441       ring->tx_tail += (u16)rv;
442       n_packets -= (uint16_t) rv;
443   } while (rv && n_packets && (n_retry>0));
444
445   return n_packets;
446 }
447
448
449 /*
450  * This function transmits any packets on the interface's tx_vector and returns
451  * the number of packets untransmitted on the tx_vector. If the tx_vector is 
452  * empty the function simply returns 0. 
453  *
454  * It is intended to be called by a traffic manager which has flowed-off an
455  * interface to see if the interface can be flowed-on again.
456  */
457 u32 dpdk_interface_tx_vector (vlib_main_t * vm, u32 dev_instance)
458 {
459   dpdk_main_t * dm = &dpdk_main;
460   dpdk_device_t * xd;
461   int queue_id;
462   struct rte_mbuf ** tx_vector;
463   tx_ring_hdr_t *ring;
464  
465   /* param is dev_instance and not hw_if_index to save another lookup */
466   xd = vec_elt_at_index (dm->devices, dev_instance);
467
468   queue_id = vm->cpu_index;
469   tx_vector = xd->tx_vectors[queue_id];
470
471   /* If no packets on the ring, don't bother calling tx function */
472   ring = vec_header(tx_vector, sizeof(*ring));
473   if (ring->tx_head == ring->tx_tail) 
474     {
475       return 0;
476     }
477
478   return tx_burst_vector_internal (vm, xd, tx_vector);
479 }
480
481 /*
482  * Transmits the packets on the frame to the interface associated with the
483  * node. It first copies packets on the frame to a tx_vector containing the 
484  * rte_mbuf pointers. It then passes this vector to tx_burst_vector_internal 
485  * which calls the dpdk tx_burst function.
486  *
487  * The tx_vector is treated slightly differently depending on whether or
488  * not a flowcontrol callback function has been configured. If there is no
489  * callback, the tx_vector is a temporary array of rte_mbuf packet pointers.
490  * Its entries are written and consumed before the function exits. 
491  *
492  * If there is a callback then the transmit is being invoked in the presence
493  * of a traffic manager. Here the tx_vector is treated like a ring of rte_mbuf
494  * pointers. If not all packets can be transmitted, the untransmitted packets
495  * stay on the tx_vector until the next call. The callback allows the traffic
496  * manager to flow-off dequeues to the interface. The companion function
497  * dpdk_interface_tx_vector() allows the traffic manager to detect when
498  * it should flow-on the interface again.
499  */
500 static uword
501 dpdk_interface_tx (vlib_main_t * vm,
502            vlib_node_runtime_t * node,
503            vlib_frame_t * f)
504 {
505   dpdk_main_t * dm = &dpdk_main;
506   vnet_interface_output_runtime_t * rd = (void *) node->runtime_data;
507   dpdk_device_t * xd = vec_elt_at_index (dm->devices, rd->dev_instance);
508   u32 n_packets = f->n_vectors;
509   u32 n_left;
510   u32 * from;
511   struct rte_mbuf ** tx_vector;
512   int i;
513   int queue_id;
514   u32 my_cpu;
515   u32 tx_pkts = 0;
516   tx_ring_hdr_t *ring;
517   u32 n_on_ring;
518
519   my_cpu = vm->cpu_index;
520
521   queue_id = my_cpu;
522
523   tx_vector = xd->tx_vectors[queue_id];
524   ring = vec_header(tx_vector, sizeof(*ring));
525
526   n_on_ring = ring->tx_head - ring->tx_tail;
527   from = vlib_frame_vector_args (f);
528
529   ASSERT(n_packets <= VLIB_FRAME_SIZE);
530
531   if (PREDICT_FALSE(n_on_ring + n_packets > DPDK_TX_RING_SIZE))
532     {
533       /*
534        * Overflowing the ring should never happen. 
535        * If it does then drop the whole frame.
536        */
537       vlib_error_count (vm, node->node_index, DPDK_TX_FUNC_ERROR_RING_FULL,
538                         n_packets);
539
540       while (n_packets--) 
541         {
542           u32 bi0 = from[n_packets];
543           vlib_buffer_t *b0 = vlib_get_buffer (vm, bi0);
544           struct rte_mbuf *mb0 = ((struct rte_mbuf *)b0) - 1;
545           rte_pktmbuf_free (mb0);
546         }
547       return n_on_ring;
548     }
549
550   if (PREDICT_FALSE(dm->tx_pcap_enable))
551     {
552       n_left = n_packets;
553       while (n_left > 0)
554         {
555           u32 bi0 = from[0];
556           vlib_buffer_t * b0 = vlib_get_buffer (vm, bi0);
557           if (dm->pcap_sw_if_index == 0 ||
558               dm->pcap_sw_if_index == vnet_buffer(b0)->sw_if_index [VLIB_TX])
559               pcap_add_buffer (&dm->pcap_main, vm, bi0, 512);
560           from++;
561           n_left--;
562         }
563     }
564
565   from = vlib_frame_vector_args (f);
566   n_left = n_packets;
567   i = ring->tx_head % DPDK_TX_RING_SIZE;
568
569   while (n_left >= 4)
570     {
571       u32 bi0, bi1;
572       u32 pi0, pi1;
573       struct rte_mbuf * mb0, * mb1;
574       struct rte_mbuf * prefmb0, * prefmb1;
575       vlib_buffer_t * b0, * b1;
576       vlib_buffer_t * pref0, * pref1;
577       i16 delta0, delta1;
578       u16 new_data_len0, new_data_len1;
579       u16 new_pkt_len0, new_pkt_len1;
580       u32 any_clone;
581
582       pi0 = from[2];
583       pi1 = from[3];
584       pref0 = vlib_get_buffer (vm, pi0);
585       pref1 = vlib_get_buffer (vm, pi1);
586
587       prefmb0 = ((struct rte_mbuf *)pref0) - 1;
588       prefmb1 = ((struct rte_mbuf *)pref1) - 1;
589       
590       CLIB_PREFETCH(prefmb0, CLIB_CACHE_LINE_BYTES, LOAD);
591       CLIB_PREFETCH(pref0, CLIB_CACHE_LINE_BYTES, LOAD);
592       CLIB_PREFETCH(prefmb1, CLIB_CACHE_LINE_BYTES, LOAD);
593       CLIB_PREFETCH(pref1, CLIB_CACHE_LINE_BYTES, LOAD);
594
595       bi0 = from[0];
596       bi1 = from[1];
597       from += 2;
598       
599       b0 = vlib_get_buffer (vm, bi0);
600       b1 = vlib_get_buffer (vm, bi1);
601
602       mb0 = ((struct rte_mbuf *)b0) - 1;
603       mb1 = ((struct rte_mbuf *)b1) - 1;
604
605       any_clone = b0->clone_count | b1->clone_count;
606       if (PREDICT_FALSE(any_clone != 0))
607         {
608           if (PREDICT_FALSE(b0->clone_count != 0))
609         {
610           struct rte_mbuf * mb0_new = dpdk_replicate_packet_mb (b0);
611           if (PREDICT_FALSE(mb0_new == 0))
612             {
613               vlib_error_count (vm, node->node_index,
614                     DPDK_TX_FUNC_ERROR_REPL_FAIL, 1);
615               b0->flags |= VLIB_BUFFER_REPL_FAIL;
616             }
617           else
618             mb0 = mb0_new;
619           vec_add1 (dm->recycle[my_cpu], bi0);
620         }
621           if (PREDICT_FALSE(b1->clone_count != 0))
622         {
623           struct rte_mbuf * mb1_new = dpdk_replicate_packet_mb (b1);
624           if (PREDICT_FALSE(mb1_new == 0))
625             {
626               vlib_error_count (vm, node->node_index,
627                     DPDK_TX_FUNC_ERROR_REPL_FAIL, 1);
628               b1->flags |= VLIB_BUFFER_REPL_FAIL;
629             }
630           else
631             mb1 = mb1_new;
632           vec_add1 (dm->recycle[my_cpu], bi1);
633         }
634     }
635
636       delta0 = PREDICT_FALSE(b0->flags & VLIB_BUFFER_REPL_FAIL) ? 0 :
637     vlib_buffer_length_in_chain (vm, b0) - (i16) mb0->pkt_len;
638       delta1 = PREDICT_FALSE(b1->flags & VLIB_BUFFER_REPL_FAIL) ? 0 :
639     vlib_buffer_length_in_chain (vm, b1) - (i16) mb1->pkt_len;
640       
641       new_data_len0 = (u16)((i16) mb0->data_len + delta0);
642       new_data_len1 = (u16)((i16) mb1->data_len + delta1);
643       new_pkt_len0 = (u16)((i16) mb0->pkt_len + delta0);
644       new_pkt_len1 = (u16)((i16) mb1->pkt_len + delta1);
645
646       b0->current_length = new_data_len0;
647       b1->current_length = new_data_len1;
648       mb0->data_len = new_data_len0;
649       mb1->data_len = new_data_len1;
650       mb0->pkt_len = new_pkt_len0;
651       mb1->pkt_len = new_pkt_len1;
652
653       mb0->data_off = (PREDICT_FALSE(b0->flags & VLIB_BUFFER_REPL_FAIL)) ?
654           mb0->data_off : (u16)(RTE_PKTMBUF_HEADROOM + b0->current_data);
655       mb1->data_off = (PREDICT_FALSE(b1->flags & VLIB_BUFFER_REPL_FAIL)) ?
656           mb1->data_off : (u16)(RTE_PKTMBUF_HEADROOM + b1->current_data);
657
658       if (PREDICT_FALSE(node->flags & VLIB_NODE_FLAG_TRACE))
659     {
660           if (b0->flags & VLIB_BUFFER_IS_TRACED)
661               dpdk_tx_trace_buffer (dm, node, xd, queue_id, bi0, b0);
662           if (b1->flags & VLIB_BUFFER_IS_TRACED)
663               dpdk_tx_trace_buffer (dm, node, xd, queue_id, bi1, b1);
664     }
665
666       if (PREDICT_TRUE(any_clone == 0))
667         {
668       tx_vector[i % DPDK_TX_RING_SIZE] = mb0;
669           i++;
670       tx_vector[i % DPDK_TX_RING_SIZE] = mb1;
671           i++;
672         }
673       else
674         {
675           /* cloning was done, need to check for failure */
676           if (PREDICT_TRUE((b0->flags & VLIB_BUFFER_REPL_FAIL) == 0))
677             {
678           tx_vector[i % DPDK_TX_RING_SIZE] = mb0;
679               i++;
680             }
681           if (PREDICT_TRUE((b1->flags & VLIB_BUFFER_REPL_FAIL) == 0))
682             {
683           tx_vector[i % DPDK_TX_RING_SIZE] = mb1;
684               i++;
685             }
686         }
687
688       n_left -= 2;
689     }
690   while (n_left > 0)
691     {
692       u32 bi0;
693       struct rte_mbuf * mb0;
694       vlib_buffer_t * b0;
695       i16 delta0;
696       u16 new_data_len0;
697       u16 new_pkt_len0;
698
699       bi0 = from[0];
700       from++;
701       
702       b0 = vlib_get_buffer (vm, bi0);
703
704       mb0 = ((struct rte_mbuf *)b0) - 1;
705       if (PREDICT_FALSE(b0->clone_count != 0))
706     {
707       struct rte_mbuf * mb0_new = dpdk_replicate_packet_mb (b0);
708       if (PREDICT_FALSE(mb0_new == 0))
709         {
710           vlib_error_count (vm, node->node_index,
711                 DPDK_TX_FUNC_ERROR_REPL_FAIL, 1);
712           b0->flags |= VLIB_BUFFER_REPL_FAIL;
713         }
714       else
715         mb0 = mb0_new;
716       vec_add1 (dm->recycle[my_cpu], bi0);
717     }
718
719       delta0 = PREDICT_FALSE(b0->flags & VLIB_BUFFER_REPL_FAIL) ? 0 :
720     vlib_buffer_length_in_chain (vm, b0) - (i16) mb0->pkt_len;
721       
722       new_data_len0 = (u16)((i16) mb0->data_len + delta0);
723       new_pkt_len0 = (u16)((i16) mb0->pkt_len + delta0);
724       
725       b0->current_length = new_data_len0;
726       mb0->data_len = new_data_len0;
727       mb0->pkt_len = new_pkt_len0;
728       mb0->data_off = (PREDICT_FALSE(b0->flags & VLIB_BUFFER_REPL_FAIL)) ?
729           mb0->data_off : (u16)(RTE_PKTMBUF_HEADROOM + b0->current_data);
730
731       if (PREDICT_FALSE(node->flags & VLIB_NODE_FLAG_TRACE))
732           if (b0->flags & VLIB_BUFFER_IS_TRACED)
733               dpdk_tx_trace_buffer (dm, node, xd, queue_id, bi0, b0);
734
735       if (PREDICT_TRUE((b0->flags & VLIB_BUFFER_REPL_FAIL) == 0))
736         {
737       tx_vector[i % DPDK_TX_RING_SIZE] = mb0;
738           i++;
739         }
740       n_left--;
741     }
742
743   /* account for additional packets in the ring */
744   ring->tx_head += n_packets;
745   n_on_ring = ring->tx_head - ring->tx_tail;
746
747   /* transmit as many packets as possible */
748   n_packets = tx_burst_vector_internal (vm, xd, tx_vector);
749
750   /*
751    * tx_pkts is the number of packets successfully transmitted
752    * This is the number originally on ring minus the number remaining on ring
753    */
754   tx_pkts = n_on_ring - n_packets; 
755
756   if (PREDICT_FALSE(dm->flowcontrol_callback != 0))
757     {
758       if (PREDICT_FALSE(n_packets))
759         {
760           /* Callback may want to enable flowcontrol */
761           dm->flowcontrol_callback(vm, xd->vlib_hw_if_index, ring->tx_head - ring->tx_tail);
762         } 
763       else 
764         {
765           /* Reset head/tail to avoid unnecessary wrap */
766           ring->tx_head = 0;
767           ring->tx_tail = 0;
768         }
769     }
770   else 
771     {
772       /* If there is no callback then drop any non-transmitted packets */
773       if (PREDICT_FALSE(n_packets))
774         {
775           vlib_simple_counter_main_t * cm;
776           vnet_main_t * vnm = vnet_get_main();
777
778           cm = vec_elt_at_index (vnm->interface_main.sw_if_counters,
779                                  VNET_INTERFACE_COUNTER_TX_ERROR);
780
781           vlib_increment_simple_counter (cm, my_cpu, xd->vlib_sw_if_index, n_packets);
782
783           vlib_error_count (vm, node->node_index, DPDK_TX_FUNC_ERROR_PKT_DROP,
784                 n_packets);
785
786           while (n_packets--)
787             rte_pktmbuf_free (tx_vector[ring->tx_tail + n_packets]);
788         }
789
790         /* Reset head/tail to avoid unnecessary wrap */
791         ring->tx_head = 0;
792         ring->tx_tail = 0;
793     }
794
795   /* Recycle replicated buffers */
796   if (PREDICT_FALSE(vec_len(dm->recycle[my_cpu])))
797     {
798       vlib_buffer_free (vm, dm->recycle[my_cpu], vec_len(dm->recycle[my_cpu]));
799       _vec_len(dm->recycle[my_cpu]) = 0;
800     }
801
802   ASSERT(ring->tx_head >= ring->tx_tail);
803
804   return tx_pkts;
805 }
806
807 static int dpdk_device_renumber (vnet_hw_interface_t * hi,
808                                  u32 new_dev_instance)
809 {
810   dpdk_main_t * dm = &dpdk_main;
811   dpdk_device_t * xd = vec_elt_at_index (dm->devices, hi->dev_instance);
812
813   if (!xd || xd->dev_type != VNET_DPDK_DEV_VHOST_USER) {
814       clib_warning("cannot renumber non-vhost-user interface (sw_if_index: %d)",
815               hi->sw_if_index);
816       return 0;
817   }
818
819   xd->vu_if_id = new_dev_instance;
820   return 0;
821 }
822
823 static void dpdk_clear_hw_interface_counters (u32 instance)
824 {
825   dpdk_main_t * dm = &dpdk_main;
826   dpdk_device_t * xd = vec_elt_at_index (dm->devices, instance);
827
828   /*
829    * DAW-FIXME: VMXNET3 device stop/start doesn't work, 
830    * therefore fake the stop in the dpdk driver by
831    * silently dropping all of the incoming pkts instead of 
832    * stopping the driver / hardware.
833    */
834   if (xd->admin_up != 0xff)
835     {
836       rte_eth_stats_reset (xd->device_index);
837       memset (&xd->last_stats, 0, sizeof (xd->last_stats));
838       dpdk_update_counters (xd, vlib_time_now (dm->vlib_main));
839     }
840   else
841     {
842       rte_eth_stats_reset (xd->device_index);
843       memset(&xd->stats, 0, sizeof(xd->stats));
844       memset (&xd->last_stats, 0, sizeof (xd->last_stats));
845     }
846   rte_eth_xstats_reset(xd->device_index);
847
848   if (PREDICT_FALSE(xd->dev_type == VNET_DPDK_DEV_VHOST_USER)) {
849     int i;
850     for (i = 0; i < xd->rx_q_used * VIRTIO_QNUM; i++) {
851         xd->vu_intf->vrings[i].packets = 0;
852         xd->vu_intf->vrings[i].bytes = 0;
853     }
854   }
855 }
856
857 #ifdef RTE_LIBRTE_KNI
858 static int
859 kni_config_network_if(u8 port_id, u8 if_up)
860 {
861   vnet_main_t * vnm = vnet_get_main();
862   dpdk_main_t * dm = &dpdk_main;
863   dpdk_device_t * xd;
864   uword *p;
865
866   p = hash_get (dm->dpdk_device_by_kni_port_id, port_id);
867   if (p == 0) {
868     clib_warning("unknown interface");
869     return 0;
870   } else {
871     xd = vec_elt_at_index (dm->devices, p[0]);
872   }
873
874   vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,
875                                if_up ? VNET_HW_INTERFACE_FLAG_LINK_UP |
876                                ETH_LINK_FULL_DUPLEX : 0);
877   return 0;
878 }
879
880 static int
881 kni_change_mtu(u8 port_id, unsigned new_mtu)
882 {
883   vnet_main_t * vnm = vnet_get_main();
884   dpdk_main_t * dm = &dpdk_main;
885   dpdk_device_t * xd;
886   uword *p;
887   vnet_hw_interface_t * hif;
888
889   p = hash_get (dm->dpdk_device_by_kni_port_id, port_id);
890   if (p == 0) {
891     clib_warning("unknown interface");
892     return 0;
893   } else {
894     xd = vec_elt_at_index (dm->devices, p[0]);
895   }
896   hif = vnet_get_hw_interface (vnm, xd->vlib_hw_if_index);
897
898   hif->max_packet_bytes = new_mtu;
899
900   return 0;
901 }
902 #endif
903
904 static clib_error_t *
905 dpdk_interface_admin_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags)
906 {
907   vnet_hw_interface_t * hif = vnet_get_hw_interface (vnm, hw_if_index);
908   uword is_up = (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) != 0;
909   dpdk_main_t * dm = &dpdk_main;
910   dpdk_device_t * xd = vec_elt_at_index (dm->devices, hif->dev_instance);
911   int rv = 0;
912
913 #ifdef RTE_LIBRTE_KNI
914   if (xd->dev_type == VNET_DPDK_DEV_KNI)
915   {
916       if (is_up)
917       {
918           struct rte_kni_conf conf;
919           struct rte_kni_ops ops;
920           vlib_main_t * vm = vlib_get_main();
921           vlib_buffer_main_t * bm = vm->buffer_main;
922           memset(&conf, 0, sizeof(conf));
923           snprintf(conf.name, RTE_KNI_NAMESIZE, "vpp%u", xd->kni_port_id);
924           conf.mbuf_size = MBUF_SIZE;
925           memset(&ops, 0, sizeof(ops));
926           ops.port_id = xd->kni_port_id;
927           ops.change_mtu = kni_change_mtu;
928           ops.config_network_if = kni_config_network_if;
929
930           xd->kni = rte_kni_alloc(bm->pktmbuf_pools[rte_socket_id()], &conf, &ops);
931           if (!xd->kni)
932           {
933             clib_warning("failed to allocate kni interface");
934           }
935           else
936           {
937             hif->max_packet_bytes = 1500; /* kni interface default value */
938             xd->admin_up = 1;
939           }
940       }
941       else
942       {
943         xd->admin_up = 0;
944         rte_kni_release(xd->kni);
945       }
946       return 0;
947   }
948 #endif
949   if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER)
950     {
951       if (is_up)
952         {
953           if (xd->vu_is_running)
954             vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,
955                                  VNET_HW_INTERFACE_FLAG_LINK_UP |
956                                  ETH_LINK_FULL_DUPLEX );
957           xd->admin_up = 1;
958         }
959       else
960         {
961           vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index, 0);
962                               xd->admin_up = 0;
963         }
964
965       return 0;
966     }
967
968
969   if (is_up)
970     {
971       f64 now = vlib_time_now (dm->vlib_main);
972
973       /*
974        * DAW-FIXME: VMXNET3 device stop/start doesn't work, 
975        * therefore fake the stop in the dpdk driver by
976        * silently dropping all of the incoming pkts instead of 
977        * stopping the driver / hardware.
978        */
979       if (xd->admin_up == 0)
980         rv = rte_eth_dev_start (xd->device_index);
981
982       if (xd->promisc)
983           rte_eth_promiscuous_enable(xd->device_index);
984       else
985           rte_eth_promiscuous_disable(xd->device_index);
986
987       rte_eth_allmulticast_enable (xd->device_index);
988       xd->admin_up = 1;
989       dpdk_update_counters (xd, now);
990       dpdk_update_link_state (xd, now);
991     }
992   else
993     {
994       /*
995        * DAW-FIXME: VMXNET3 device stop/start doesn't work,
996        * therefore fake the stop in the dpdk driver by
997        * silently dropping all of the incoming pkts instead of
998        * stopping the driver / hardware.
999        */
1000       if (xd->pmd != VNET_DPDK_PMD_VMXNET3)
1001          xd->admin_up = 0;
1002       else
1003          xd->admin_up = ~0;
1004
1005       rte_eth_allmulticast_disable (xd->device_index);
1006       vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index, 0);
1007
1008       /*
1009        * DAW-FIXME: VMXNET3 device stop/start doesn't work, 
1010        * therefore fake the stop in the dpdk driver by
1011        * silently dropping all of the incoming pkts instead of 
1012        * stopping the driver / hardware.
1013        */
1014       if (xd->pmd != VNET_DPDK_PMD_VMXNET3)
1015           rte_eth_dev_stop (xd->device_index);
1016     }
1017
1018   if (rv < 0)
1019     clib_warning ("rte_eth_dev_%s error: %d", is_up ? "start" : "stop",
1020                   rv);
1021
1022   return /* no error */ 0;
1023 }
1024
1025 /*
1026  * Dynamically redirect all pkts from a specific interface
1027  * to the specified node
1028  */
1029 static void dpdk_set_interface_next_node (vnet_main_t *vnm, u32 hw_if_index,
1030                                           u32 node_index)
1031 {
1032   dpdk_main_t * xm = &dpdk_main;
1033   vnet_hw_interface_t *hw = vnet_get_hw_interface (vnm, hw_if_index);
1034   dpdk_device_t * xd = vec_elt_at_index (xm->devices, hw->dev_instance);
1035   
1036   /* Shut off redirection */
1037   if (node_index == ~0)
1038     {
1039       xd->per_interface_next_index = node_index;
1040       return;
1041     }
1042   
1043   xd->per_interface_next_index = 
1044     vlib_node_add_next (xm->vlib_main, dpdk_input_node.index, node_index);
1045 }
1046
1047
1048 static clib_error_t *
1049 dpdk_subif_add_del_function (vnet_main_t * vnm,
1050                              u32 hw_if_index,
1051                              struct vnet_sw_interface_t * st,
1052                              int is_add)
1053 {
1054   dpdk_main_t * xm = &dpdk_main;
1055   vnet_hw_interface_t *hw = vnet_get_hw_interface (vnm, hw_if_index);
1056   dpdk_device_t * xd = vec_elt_at_index (xm->devices, hw->dev_instance);
1057   vnet_sw_interface_t * t = (vnet_sw_interface_t *) st;
1058   int r, vlan_offload;
1059
1060
1061   if (xd->dev_type != VNET_DPDK_DEV_ETH)
1062         return 0;
1063   /* currently we program VLANS only for IXGBE VF */
1064   if (xd->pmd != VNET_DPDK_PMD_IXGBEVF)
1065         return 0;
1066
1067   if (t->sub.eth.flags.no_tags == 1)
1068         return 0;
1069
1070   if ((t->sub.eth.flags.one_tag != 1) || (t->sub.eth.flags.exact_match != 1 ))
1071         return clib_error_return (0, "unsupported VLAN setup");
1072
1073
1074   vlan_offload = rte_eth_dev_get_vlan_offload(xd->device_index);
1075   vlan_offload |= ETH_VLAN_FILTER_OFFLOAD;
1076
1077   if ((r = rte_eth_dev_set_vlan_offload(xd->device_index, vlan_offload)))
1078         return clib_error_return (0, "rte_eth_dev_set_vlan_offload[%d]: err %d",
1079                                   xd->device_index, r);
1080
1081
1082   if ((r = rte_eth_dev_vlan_filter(xd->device_index, t->sub.eth.outer_vlan_id, is_add)))
1083         return clib_error_return (0, "rte_eth_dev_vlan_filter[%d]: err %d",
1084                                  xd->device_index, r);
1085
1086   return 0;
1087 }
1088
1089 VNET_DEVICE_CLASS (dpdk_device_class) = {
1090   .name = "dpdk",
1091   .tx_function = dpdk_interface_tx,
1092   .tx_function_n_errors = DPDK_TX_FUNC_N_ERROR,
1093   .tx_function_error_strings = dpdk_tx_func_error_strings,
1094   .format_device_name = format_dpdk_device_name,
1095   .format_device = format_dpdk_device,
1096   .format_tx_trace = format_dpdk_tx_dma_trace,
1097   .clear_counters = dpdk_clear_hw_interface_counters,
1098   .admin_up_down_function = dpdk_interface_admin_up_down,
1099   .subif_add_del_function = dpdk_subif_add_del_function,
1100   .rx_redirect_to_node = dpdk_set_interface_next_node,
1101   .no_flatten_output_chains = 1,
1102   .name_renumber = dpdk_device_renumber,
1103 };
1104
1105 void dpdk_set_flowcontrol_callback (vlib_main_t *vm, 
1106                                     dpdk_flowcontrol_callback_t callback)
1107 {
1108   dpdk_main.flowcontrol_callback = callback;
1109 }
1110
1111 #define UP_DOWN_FLAG_EVENT 1
1112
1113
1114 u32 dpdk_get_admin_up_down_in_progress (void)
1115 {
1116   return dpdk_main.admin_up_down_in_progress;
1117 }
1118
1119 static uword
1120 admin_up_down_process (vlib_main_t * vm,
1121                        vlib_node_runtime_t * rt,
1122                        vlib_frame_t * f)
1123 {
1124   clib_error_t * error = 0;
1125   uword event_type;
1126   uword *event_data = 0;
1127   u32 index;
1128   u32 sw_if_index;
1129   u32 flags;
1130
1131   while (1)  
1132     { 
1133       vlib_process_wait_for_event (vm);
1134
1135       event_type = vlib_process_get_events (vm, &event_data);
1136
1137       dpdk_main.admin_up_down_in_progress = 1;
1138
1139       for (index=0; index<vec_len(event_data); index++)
1140         {
1141           sw_if_index = event_data[index] >> 32;
1142           flags = (u32) event_data[index];
1143
1144           switch (event_type) {
1145           case UP_DOWN_FLAG_EVENT:
1146             error = vnet_sw_interface_set_flags (vnet_get_main(), sw_if_index, flags);
1147             clib_error_report(error);
1148             break;
1149           }
1150         }
1151
1152       vec_reset_length (event_data);
1153
1154       dpdk_main.admin_up_down_in_progress = 0;
1155
1156     }
1157   return 0; /* or not */
1158 }
1159
1160 VLIB_REGISTER_NODE (admin_up_down_process_node,static) = {
1161     .function = admin_up_down_process,
1162     .type = VLIB_NODE_TYPE_PROCESS,
1163     .name = "admin-up-down-process",
1164     .process_log2_n_stack_bytes = 17,  // 256KB
1165 };
1166
1167 /*
1168  * Asynchronously invoke vnet_sw_interface_set_flags via the admin_up_down 
1169  * process. Useful for avoiding long blocking delays (>150ms) in the dpdk 
1170  * drivers.
1171  * WARNING: when posting this event, no other interface-related calls should
1172  * be made (e.g. vnet_create_sw_interface()) while the event is being
1173  * processed (admin_up_down_in_progress). This is required in order to avoid 
1174  * race conditions in manipulating interface data structures.
1175  */
1176 void post_sw_interface_set_flags (vlib_main_t *vm, u32 sw_if_index, u32 flags)
1177 {
1178   vlib_process_signal_event
1179       (vm, admin_up_down_process_node.index,
1180        UP_DOWN_FLAG_EVENT, 
1181        (((uword)sw_if_index << 32) | flags));
1182 }
1183
1184 /*
1185  * Called by the dpdk driver's rte_delay_us() function. 
1186  * Return 0 to have the dpdk do a regular delay loop.
1187  * Return 1 if to skip the delay loop because we are suspending
1188  * the calling vlib process instead.
1189  */
1190 int rte_delay_us_override (unsigned us) {
1191   vlib_main_t * vm;
1192
1193   /* Don't bother intercepting for short delays */
1194   if (us < 10) return 0;
1195
1196   /* 
1197    * Only intercept if we are in a vlib process. 
1198    * If we are called from a vlib worker thread or the vlib main
1199    * thread then do not intercept. (Must not be called from an 
1200    * independent pthread).
1201    */
1202   if (os_get_cpu_number() == 0)
1203     {
1204       /* 
1205        * We're in the vlib main thread or a vlib process. Make sure
1206        * the process is running and we're not still initializing.
1207        */
1208       vm = vlib_get_main();
1209       if (vlib_in_process_context(vm))
1210         {
1211           /* Only suspend for the admin_down_process */
1212           vlib_process_t * proc = vlib_get_current_process(vm);
1213           if (!(proc->flags & VLIB_PROCESS_IS_RUNNING) ||
1214               (proc->node_runtime.function != admin_up_down_process))
1215                 return 0;
1216
1217           f64 delay = 1e-6 * us;
1218           vlib_process_suspend(vm, delay);
1219           return 1;
1220         }
1221     }
1222   return 0; // no override
1223 }