Move pkt replication counter to the opaque2 cache line
[vpp.git] / vnet / vnet / unix / tapcli.c
1 /* 
2  *------------------------------------------------------------------
3  * tapcli.c - dynamic tap interface hookup
4  *
5  * Copyright (c) 2009 Cisco and/or its affiliates.
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at:
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *------------------------------------------------------------------
18  */
19
20 #include <fcntl.h>              /* for open */
21 #include <sys/ioctl.h>
22 #include <sys/socket.h>
23 #include <sys/stat.h>
24 #include <sys/types.h> 
25 #include <sys/uio.h>            /* for iovec */
26 #include <netinet/in.h>
27
28 #include <linux/if_arp.h>
29 #include <linux/if_tun.h>
30
31 #include <vlib/vlib.h>
32 #include <vlib/unix/unix.h>
33
34 #include <vnet/ip/ip.h>
35
36 #include <vnet/ethernet/ethernet.h>
37
38 #if DPDK == 1
39 #include <vnet/devices/dpdk/dpdk.h>
40 #endif
41
42 #include <vnet/unix/tapcli.h>
43
44 static vnet_device_class_t tapcli_dev_class;
45 static vnet_hw_interface_class_t tapcli_interface_class;
46 static vlib_node_registration_t tapcli_rx_node;
47
48 static void tapcli_nopunt_frame (vlib_main_t * vm,
49                                  vlib_node_runtime_t * node,
50                                  vlib_frame_t * frame);
51 typedef struct {
52   u32 unix_fd;
53   u32 unix_file_index;
54   u32 provision_fd;
55   u32 sw_if_index;              /* for counters */
56   u32 hw_if_index;
57   u32 is_promisc;
58   struct ifreq ifr;
59   u32 per_interface_next_index;
60   u8 active;                    /* for delete */
61 } tapcli_interface_t;
62
63 typedef struct {
64   u16 sw_if_index;
65 } tapcli_rx_trace_t;
66
67 u8 * format_tapcli_rx_trace (u8 * s, va_list * va)
68 {
69   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*va, vlib_main_t *);
70   CLIB_UNUSED (vlib_node_t * node) = va_arg (*va, vlib_node_t *);
71   vnet_main_t * vnm = vnet_get_main();
72   tapcli_rx_trace_t * t = va_arg (*va, tapcli_rx_trace_t *);
73   s = format (s, "%U", format_vnet_sw_if_index_name,
74                 vnm, t->sw_if_index);
75   return s;
76 }
77
78 typedef struct {
79   /* Vector of iovecs for readv/writev calls. */
80   struct iovec * iovecs;
81
82   /* Vector of VLIB rx buffers to use.  We allocate them in blocks
83      of VLIB_FRAME_SIZE (256). */
84   u32 * rx_buffers;
85
86   /* tap device destination MAC address. Required, or Linux drops pkts */
87   u8 ether_dst_mac[6];
88
89   /* Interface MTU in bytes and # of default sized buffers. */
90   u32 mtu_bytes, mtu_buffers;
91
92   /* Vector of tap interfaces */
93   tapcli_interface_t * tapcli_interfaces;
94
95   /* Vector of deleted tap interfaces */
96   u32 * tapcli_inactive_interfaces;
97
98   /* Bitmap of tap interfaces with pending reads */
99   uword * pending_read_bitmap;
100
101   /* Hash table to find tapcli interface given hw_if_index */
102   uword * tapcli_interface_index_by_sw_if_index;
103   
104   /* Hash table to find tapcli interface given unix fd */
105   uword * tapcli_interface_index_by_unix_fd;
106
107   /* renumbering table */
108   u32 * show_dev_instance_by_real_dev_instance;
109
110   /* 1 => disable CLI */
111   int is_disabled;
112
113   /* convenience */
114   vlib_main_t * vlib_main;
115   vnet_main_t * vnet_main;
116   unix_main_t * unix_main;
117 } tapcli_main_t;
118
119 static tapcli_main_t tapcli_main;
120
121 /*
122  * tapcli_tx
123  * Output node, writes the buffers comprising the incoming frame 
124  * to the tun/tap device, aka hands them to the Linux kernel stack.
125  * 
126  */
127 static uword
128 tapcli_tx (vlib_main_t * vm,
129            vlib_node_runtime_t * node,
130            vlib_frame_t * frame)
131 {
132   u32 * buffers = vlib_frame_args (frame);
133   uword n_packets = frame->n_vectors;
134   tapcli_main_t * tm = &tapcli_main;
135   tapcli_interface_t * ti;
136   int i;
137
138   for (i = 0; i < n_packets; i++)
139     {
140       struct iovec * iov;
141       vlib_buffer_t * b;
142       uword l;
143       vnet_hw_interface_t * hw;
144       uword * p;
145       u32 tx_sw_if_index;
146
147       b = vlib_get_buffer (vm, buffers[i]);
148
149       tx_sw_if_index = vnet_buffer(b)->sw_if_index[VLIB_TX];
150       if (tx_sw_if_index == (u32)~0)
151         tx_sw_if_index = vnet_buffer(b)->sw_if_index[VLIB_RX];
152         
153       ASSERT(tx_sw_if_index != (u32)~0);
154
155       /* Use the sup intfc to finesse vlan subifs */
156       hw = vnet_get_sup_hw_interface (tm->vnet_main, tx_sw_if_index);
157       tx_sw_if_index = hw->sw_if_index;
158
159       p = hash_get (tm->tapcli_interface_index_by_sw_if_index, 
160                     tx_sw_if_index);
161       if (p == 0)
162         {
163           clib_warning ("sw_if_index %d unknown", tx_sw_if_index);
164           /* $$$ leak, but this should never happen... */
165           continue;
166         }
167       else
168         ti = vec_elt_at_index (tm->tapcli_interfaces, p[0]);
169
170       /* Re-set iovecs if present. */
171       if (tm->iovecs)
172         _vec_len (tm->iovecs) = 0;
173
174       /* VLIB buffer chain -> Unix iovec(s). */
175       vec_add2 (tm->iovecs, iov, 1);
176       iov->iov_base = b->data + b->current_data;
177       iov->iov_len = l = b->current_length;
178
179       if (PREDICT_FALSE (b->flags & VLIB_BUFFER_NEXT_PRESENT))
180         {
181           do {
182             b = vlib_get_buffer (vm, b->next_buffer);
183
184             vec_add2 (tm->iovecs, iov, 1);
185
186             iov->iov_base = b->data + b->current_data;
187             iov->iov_len = b->current_length;
188             l += b->current_length;
189           } while (b->flags & VLIB_BUFFER_NEXT_PRESENT);
190         }
191
192       if (writev (ti->unix_fd, tm->iovecs, vec_len (tm->iovecs)) < l)
193         clib_unix_warning ("writev");
194     }
195     
196   vlib_buffer_free(vm, vlib_frame_vector_args(frame), frame->n_vectors);
197     
198   return n_packets;
199 }
200
201 VLIB_REGISTER_NODE (tapcli_tx_node,static) = {
202   .function = tapcli_tx,
203   .name = "tapcli-tx",
204   .type = VLIB_NODE_TYPE_INTERNAL,
205   .vector_size = 4,
206 };
207
208 enum {
209   TAPCLI_RX_NEXT_IP4_INPUT, 
210   TAPCLI_RX_NEXT_IP6_INPUT, 
211   TAPCLI_RX_NEXT_ETHERNET_INPUT,
212   TAPCLI_RX_NEXT_DROP,
213   TAPCLI_RX_N_NEXT,
214 };
215
216
217
218 static uword tapcli_rx_iface(vlib_main_t * vm,
219                             vlib_node_runtime_t * node,
220                             tapcli_interface_t * ti)
221 {
222   tapcli_main_t * tm = &tapcli_main;
223   const uword buffer_size = VLIB_BUFFER_DATA_SIZE;
224   u32 n_trace = vlib_get_trace_count (vm, node);
225   u8 set_trace = 0;
226
227   vnet_main_t *vnm;
228   vnet_sw_interface_t * si;
229   u8 admin_down;
230   u32 next = node->cached_next_index;
231   u32 n_left_to_next, next_index;
232   u32 *to_next;
233
234   vnm = vnet_get_main();
235   si = vnet_get_sw_interface (vnm, ti->sw_if_index);
236   admin_down = !(si->flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP);
237
238   vlib_get_next_frame(vm, node, next, to_next, n_left_to_next);
239
240   while (n_left_to_next) { // Fill at most one vector
241     vlib_buffer_t *b_first, *b, *prev;
242     u32 bi_first, bi;
243     word n_bytes_in_packet;
244     int j, n_bytes_left;
245
246     if (PREDICT_FALSE(vec_len(tm->rx_buffers) < tm->mtu_buffers)) {
247       uword len = vec_len(tm->rx_buffers);
248       _vec_len(tm->rx_buffers) +=
249           vlib_buffer_alloc_from_free_list(vm, &tm->rx_buffers[len],
250                             VLIB_FRAME_SIZE - len, VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);
251       if (PREDICT_FALSE(vec_len(tm->rx_buffers) < tm->mtu_buffers)) {
252         clib_warning("vlib_buffer_alloc failed");
253         break;
254       }
255     }
256
257     uword i_rx = vec_len (tm->rx_buffers) - 1;
258
259     /* Allocate RX buffers from end of rx_buffers.
260            Turn them into iovecs to pass to readv. */
261     vec_validate (tm->iovecs, tm->mtu_buffers - 1);
262     for (j = 0; j < tm->mtu_buffers; j++) {
263       b = vlib_get_buffer (vm, tm->rx_buffers[i_rx - j]);
264       tm->iovecs[j].iov_base = b->data;
265       tm->iovecs[j].iov_len = buffer_size;
266     }
267
268     n_bytes_left = readv (ti->unix_fd, tm->iovecs, tm->mtu_buffers);
269     n_bytes_in_packet = n_bytes_left;
270     if (n_bytes_left <= 0) {
271       if (errno != EAGAIN) {
272         vlib_node_increment_counter(vm, tapcli_rx_node.index,
273                                     TAPCLI_ERROR_READ, 1);
274       }
275       break;
276     }
277
278     bi_first = tm->rx_buffers[i_rx];
279     b = b_first = vlib_get_buffer (vm, tm->rx_buffers[i_rx]);
280     prev = NULL;
281
282     while (1) {
283       b->current_length = n_bytes_left < buffer_size ? n_bytes_left : buffer_size;
284       n_bytes_left -= buffer_size;
285
286       if (prev) {
287         prev->next_buffer = bi;
288         prev->flags |= VLIB_BUFFER_NEXT_PRESENT;
289       }
290       prev = b;
291
292       /* last segment */
293       if (n_bytes_left <= 0)
294         break;
295
296       i_rx--;
297       bi = tm->rx_buffers[i_rx];
298       b = vlib_get_buffer (vm, bi);
299     }
300
301     _vec_len (tm->rx_buffers) = i_rx;
302
303     b_first->total_length_not_including_first_buffer =
304         (n_bytes_in_packet > buffer_size) ? n_bytes_in_packet - buffer_size : 0;
305     b_first->flags |= VLIB_BUFFER_TOTAL_LENGTH_VALID;
306
307     /* Ensure mbufs are updated */
308     vlib_buffer_chain_validate(vm, b_first);
309
310     VLIB_BUFFER_TRACE_TRAJECTORY_INIT(b_first);
311
312     vnet_buffer (b_first)->sw_if_index[VLIB_RX] = ti->sw_if_index;
313     vnet_buffer (b_first)->sw_if_index[VLIB_TX] = (u32)~0;
314
315     b_first->error = node->errors[TAPCLI_ERROR_NONE];
316     next_index = TAPCLI_RX_NEXT_ETHERNET_INPUT;
317     next_index = (ti->per_interface_next_index != ~0) ?
318         ti->per_interface_next_index : next_index;
319     next_index = admin_down ? TAPCLI_RX_NEXT_DROP : next_index;
320
321     to_next[0] = bi_first;
322     to_next++;
323     n_left_to_next--;
324
325     vlib_validate_buffer_enqueue_x1 (vm, node, next,
326                                      to_next, n_left_to_next,
327                                      bi_first, next_index);
328
329     /* Interface counters for tapcli interface. */
330     if (PREDICT_TRUE(!admin_down)) {
331       vlib_increment_combined_counter (
332           vnet_main.interface_main.combined_sw_if_counters
333           + VNET_INTERFACE_COUNTER_RX,
334           os_get_cpu_number(), ti->sw_if_index,
335           1, n_bytes_in_packet);
336
337       if (PREDICT_FALSE(n_trace > 0)) {
338         vlib_trace_buffer (vm, node, next_index,
339                            b_first, /* follow_chain */ 1);
340         n_trace--;
341         set_trace = 1;
342         tapcli_rx_trace_t *t0 = vlib_add_trace (vm, node, b_first, sizeof (*t0));
343         t0->sw_if_index = si->sw_if_index;
344       }
345     }
346   }
347   vlib_put_next_frame (vm, node, next, n_left_to_next);
348   if (set_trace)
349     vlib_set_trace_count (vm, node, n_trace);
350   return VLIB_FRAME_SIZE - n_left_to_next;
351 }
352
353 static uword
354 tapcli_rx (vlib_main_t * vm,
355            vlib_node_runtime_t * node,
356            vlib_frame_t * frame)
357 {
358   tapcli_main_t * tm = &tapcli_main;
359   static u32 * ready_interface_indices;
360   tapcli_interface_t * ti;
361   int i;
362   u32 total_count = 0;
363
364   vec_reset_length (ready_interface_indices);
365   clib_bitmap_foreach (i, tm->pending_read_bitmap,
366   ({
367     vec_add1 (ready_interface_indices, i);
368   }));
369
370   if (vec_len (ready_interface_indices) == 0)
371     return 0;
372
373   for (i = 0; i < vec_len(ready_interface_indices); i++)
374   {
375     tm->pending_read_bitmap =
376         clib_bitmap_set (tm->pending_read_bitmap,
377                          ready_interface_indices[i], 0);
378
379     ti = vec_elt_at_index (tm->tapcli_interfaces, ready_interface_indices[i]);
380     total_count += tapcli_rx_iface(vm, node, ti);
381   }
382   return total_count; //This might return more than 256.
383 }
384
385 static char * tapcli_rx_error_strings[] = {
386 #define _(sym,string) string,
387   foreach_tapcli_error
388 #undef _
389 };
390
391 VLIB_REGISTER_NODE (tapcli_rx_node, static) = {
392   .function = tapcli_rx,
393   .name = "tapcli-rx",
394   .type = VLIB_NODE_TYPE_INPUT,
395   .state = VLIB_NODE_STATE_INTERRUPT,
396   .vector_size = 4,
397   .n_errors = TAPCLI_N_ERROR,
398   .error_strings = tapcli_rx_error_strings,
399   .format_trace = format_tapcli_rx_trace,
400
401   .n_next_nodes = TAPCLI_RX_N_NEXT,
402   .next_nodes = {
403     [TAPCLI_RX_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
404     [TAPCLI_RX_NEXT_IP6_INPUT] = "ip6-input",
405     [TAPCLI_RX_NEXT_DROP] = "error-drop",
406     [TAPCLI_RX_NEXT_ETHERNET_INPUT] = "ethernet-input",
407   },
408 };
409
410 /* Gets called when file descriptor is ready from epoll. */
411 static clib_error_t * tapcli_read_ready (unix_file_t * uf)
412 {
413   vlib_main_t * vm = vlib_get_main();
414   tapcli_main_t * tm = &tapcli_main;
415   uword * p;
416   
417   /* Schedule the rx node */
418   vlib_node_set_interrupt_pending (vm, tapcli_rx_node.index);
419
420   p = hash_get (tm->tapcli_interface_index_by_unix_fd, uf->file_descriptor);
421
422   /* Mark the specific tap interface ready-to-read */
423   if (p)
424     tm->pending_read_bitmap = clib_bitmap_set (tm->pending_read_bitmap,
425                                                p[0], 1);
426   else
427     clib_warning ("fd %d not in hash table", uf->file_descriptor);
428
429   return 0;
430 }
431
432 static clib_error_t *
433 tapcli_config (vlib_main_t * vm, unformat_input_t * input)
434 {
435   tapcli_main_t *tm = &tapcli_main;
436   const uword buffer_size = VLIB_BUFFER_DATA_SIZE;
437
438   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
439     {
440       if (unformat (input, "mtu %d", &tm->mtu_bytes))
441         ;
442       else if (unformat (input, "disable"))
443         tm->is_disabled = 1;
444       else
445           return clib_error_return (0, "unknown input `%U'",
446                                     format_unformat_error, input);
447     }
448
449   if (tm->is_disabled)
450     return 0;
451
452   if (geteuid()) 
453     {
454       clib_warning ("tapcli disabled: must be superuser");
455       tm->is_disabled = 1;
456       return 0;
457     }    
458
459   tm->mtu_buffers = (tm->mtu_bytes + (buffer_size - 1)) / buffer_size;
460   
461   return 0;
462 }
463
464 static int tap_name_renumber (vnet_hw_interface_t * hi,
465                               u32 new_dev_instance)
466 {
467   tapcli_main_t *tm = &tapcli_main;
468
469   vec_validate_init_empty (tm->show_dev_instance_by_real_dev_instance,
470                            hi->dev_instance, ~0);
471
472   tm->show_dev_instance_by_real_dev_instance [hi->dev_instance] =
473     new_dev_instance;
474
475   return 0;
476 }
477
478 VLIB_CONFIG_FUNCTION (tapcli_config, "tapcli");
479
480 static void
481 tapcli_nopunt_frame (vlib_main_t * vm,
482                    vlib_node_runtime_t * node,
483                    vlib_frame_t * frame)
484 {
485   u32 * buffers = vlib_frame_args (frame);
486   uword n_packets = frame->n_vectors;
487   vlib_buffer_free (vm, buffers, n_packets);
488   vlib_frame_free (vm, node, frame);
489 }
490
491 VNET_HW_INTERFACE_CLASS (tapcli_interface_class,static) = {
492   .name = "tapcli",
493 };
494
495 static u8 * format_tapcli_interface_name (u8 * s, va_list * args)
496 {
497   u32 i = va_arg (*args, u32);
498   u32 show_dev_instance = ~0;
499   tapcli_main_t * tm = &tapcli_main;
500
501   if (i < vec_len (tm->show_dev_instance_by_real_dev_instance))
502     show_dev_instance = tm->show_dev_instance_by_real_dev_instance[i];
503
504   if (show_dev_instance != ~0)
505     i = show_dev_instance;
506
507   s = format (s, "tap-%d", i);
508   return s;
509 }
510
511 static u32 tapcli_flag_change (vnet_main_t * vnm, 
512                                vnet_hw_interface_t * hw,
513                                u32 flags)
514 {
515   tapcli_main_t *tm = &tapcli_main;
516   tapcli_interface_t *ti;
517
518    ti = vec_elt_at_index (tm->tapcli_interfaces, hw->dev_instance);
519
520   if (flags & ETHERNET_INTERFACE_FLAG_MTU)
521     {
522       const uword buffer_size = VLIB_BUFFER_DATA_SIZE;
523       tm->mtu_bytes = hw->max_packet_bytes;
524       tm->mtu_buffers = (tm->mtu_bytes + (buffer_size - 1)) / buffer_size;
525     }
526    else
527     {
528       struct ifreq ifr;
529       u32 want_promisc;
530
531       memcpy (&ifr, &ti->ifr, sizeof (ifr));
532
533       /* get flags, modify to bring up interface... */
534       if (ioctl (ti->provision_fd, SIOCGIFFLAGS, &ifr) < 0)
535         {
536           clib_unix_warning ("Couldn't get interface flags for %s", hw->name);
537           return 0;
538         }
539
540       want_promisc = (flags & ETHERNET_INTERFACE_FLAG_ACCEPT_ALL) != 0;
541
542       if (want_promisc == ti->is_promisc)
543         return 0;
544
545       if (flags & ETHERNET_INTERFACE_FLAG_ACCEPT_ALL)
546         ifr.ifr_flags |= IFF_PROMISC;
547       else
548         ifr.ifr_flags &= ~(IFF_PROMISC);
549
550       /* get flags, modify to bring up interface... */
551       if (ioctl (ti->provision_fd, SIOCSIFFLAGS, &ifr) < 0)
552         {
553           clib_unix_warning ("Couldn't set interface flags for %s", hw->name);
554           return 0;
555         }
556
557       ti->is_promisc = want_promisc;
558     }
559
560   return 0;
561 }
562
563 static void tapcli_set_interface_next_node (vnet_main_t *vnm, 
564                                             u32 hw_if_index,
565                                             u32 node_index)
566 {
567   tapcli_main_t *tm = &tapcli_main;
568   tapcli_interface_t *ti;
569   vnet_hw_interface_t *hw = vnet_get_hw_interface (vnm, hw_if_index);
570
571   ti = vec_elt_at_index (tm->tapcli_interfaces, hw->dev_instance);
572   
573   /* Shut off redirection */
574   if (node_index == ~0)
575     {
576       ti->per_interface_next_index = node_index;
577       return;
578     }
579   
580   ti->per_interface_next_index = 
581     vlib_node_add_next (tm->vlib_main, tapcli_rx_node.index, node_index);
582 }
583
584 /* 
585  * Mainly exists to set link_state == admin_state
586  * otherwise, e.g. ip6 neighbor discovery breaks
587  */
588 static clib_error_t * 
589 tapcli_interface_admin_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags)
590 {
591   uword is_admin_up = (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) != 0;
592   u32 hw_flags;
593   u32 speed_duplex = VNET_HW_INTERFACE_FLAG_FULL_DUPLEX 
594     | VNET_HW_INTERFACE_FLAG_SPEED_1G;
595     
596   if (is_admin_up)
597     hw_flags = VNET_HW_INTERFACE_FLAG_LINK_UP | speed_duplex;
598   else
599     hw_flags = speed_duplex;
600   
601   vnet_hw_interface_set_flags (vnm, hw_if_index, hw_flags);
602   return 0;
603 }
604
605 VNET_DEVICE_CLASS (tapcli_dev_class,static) = {
606   .name = "tapcli",
607   .tx_function = tapcli_tx,
608   .format_device_name = format_tapcli_interface_name,
609   .rx_redirect_to_node = tapcli_set_interface_next_node,
610   .name_renumber = tap_name_renumber,
611   .admin_up_down_function = tapcli_interface_admin_up_down,
612   .no_flatten_output_chains = 1,
613 };
614
615 int vnet_tap_dump_ifs (tapcli_interface_details_t **out_tapids)
616 {
617   tapcli_main_t * tm = &tapcli_main;
618   tapcli_interface_t * ti;
619
620   tapcli_interface_details_t * r_tapids = NULL;
621   tapcli_interface_details_t * tapid = NULL;
622
623   vec_foreach (ti, tm->tapcli_interfaces) {
624     if (!ti->active)
625         continue;
626     vec_add2(r_tapids, tapid, 1);
627     tapid->sw_if_index = ti->sw_if_index;
628     strncpy((char *)tapid->dev_name, ti->ifr.ifr_name, sizeof (ti->ifr.ifr_name)-1);
629   }
630
631   *out_tapids = r_tapids;
632
633   return 0;
634 }
635
636 /* get tap interface from inactive interfaces or create new */
637 static tapcli_interface_t *tapcli_get_new_tapif()
638 {
639   tapcli_main_t * tm = &tapcli_main;
640   tapcli_interface_t *ti = NULL;
641
642   int inactive_cnt = vec_len(tm->tapcli_inactive_interfaces);
643   // if there are any inactive ifaces
644   if (inactive_cnt > 0) {
645     // take last
646     u32 ti_idx = tm->tapcli_inactive_interfaces[inactive_cnt - 1];
647     if (vec_len(tm->tapcli_interfaces) > ti_idx) {
648       ti = vec_elt_at_index (tm->tapcli_interfaces, ti_idx);
649       clib_warning("reusing tap interface");
650     }
651     // "remove" from inactive list
652     _vec_len(tm->tapcli_inactive_interfaces) -= 1;
653   }
654
655   // ti was not retrieved from inactive ifaces - create new
656   if (!ti)
657     vec_add2 (tm->tapcli_interfaces, ti, 1);
658
659   return ti;
660 }
661
662 int vnet_tap_connect (vlib_main_t * vm, u8 * intfc_name, u8 *hwaddr_arg,
663                       u32 * sw_if_indexp)
664 {
665   tapcli_main_t * tm = &tapcli_main;
666   tapcli_interface_t * ti = NULL;
667   struct ifreq ifr;
668   int flags;
669   int dev_net_tun_fd;
670   int dev_tap_fd = -1;
671   clib_error_t * error;
672   u8 hwaddr [6];
673   int rv = 0;
674
675   if (tm->is_disabled)
676     {
677       return VNET_API_ERROR_FEATURE_DISABLED;
678     }
679
680   flags = IFF_TAP | IFF_NO_PI;
681
682   if ((dev_net_tun_fd = open ("/dev/net/tun", O_RDWR)) < 0)
683     return VNET_API_ERROR_SYSCALL_ERROR_1;
684   
685   memset (&ifr, 0, sizeof (ifr));
686   strncpy(ifr.ifr_name, (char *) intfc_name, sizeof (ifr.ifr_name)-1);
687   ifr.ifr_flags = flags;
688   if (ioctl (dev_net_tun_fd, TUNSETIFF, (void *)&ifr) < 0)
689     {
690       rv = VNET_API_ERROR_SYSCALL_ERROR_2;
691       goto error;
692     }
693     
694   /* Open a provisioning socket */
695   if ((dev_tap_fd = socket(PF_PACKET, SOCK_RAW,
696                            htons(ETH_P_ALL))) < 0 )
697     {
698       rv = VNET_API_ERROR_SYSCALL_ERROR_3;
699       goto error;
700     }
701
702   /* Find the interface index. */
703   {
704     struct ifreq ifr;
705     struct sockaddr_ll sll;
706
707     memset (&ifr, 0, sizeof(ifr));
708     strncpy (ifr.ifr_name, (char *) intfc_name, sizeof (ifr.ifr_name)-1);
709     if (ioctl (dev_tap_fd, SIOCGIFINDEX, &ifr) < 0 )
710       {
711         rv = VNET_API_ERROR_SYSCALL_ERROR_4;
712         goto error;
713       }
714
715     /* Bind the provisioning socket to the interface. */
716     memset(&sll, 0, sizeof(sll));
717     sll.sll_family   = AF_PACKET;
718     sll.sll_ifindex  = ifr.ifr_ifindex;
719     sll.sll_protocol = htons(ETH_P_ALL);
720
721     if (bind(dev_tap_fd, (struct sockaddr*) &sll, sizeof(sll)) < 0)
722       {
723         rv = VNET_API_ERROR_SYSCALL_ERROR_5;
724         goto error;
725       }
726   }
727
728   /* non-blocking I/O on /dev/tapX */
729   {
730     int one = 1;
731     if (ioctl (dev_net_tun_fd, FIONBIO, &one) < 0)
732       {
733         rv = VNET_API_ERROR_SYSCALL_ERROR_6;
734         goto error;
735       }
736   }
737   ifr.ifr_mtu = tm->mtu_bytes;
738   if (ioctl (dev_tap_fd, SIOCSIFMTU, &ifr) < 0)
739     {
740       rv = VNET_API_ERROR_SYSCALL_ERROR_7;
741       goto error;
742     }
743
744   /* get flags, modify to bring up interface... */
745   if (ioctl (dev_tap_fd, SIOCGIFFLAGS, &ifr) < 0)
746     {
747       rv = VNET_API_ERROR_SYSCALL_ERROR_8;
748       goto error;
749     }
750
751   ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
752
753   if (ioctl (dev_tap_fd, SIOCSIFFLAGS, &ifr) < 0)
754     {
755       rv = VNET_API_ERROR_SYSCALL_ERROR_9;
756       goto error;
757     }
758
759   if (ioctl (dev_tap_fd, SIOCGIFHWADDR, &ifr) < 0)
760     {
761       rv = VNET_API_ERROR_SYSCALL_ERROR_1;
762       goto error;
763     }
764
765   ti = tapcli_get_new_tapif();
766   ti->per_interface_next_index = ~0;
767
768   if (hwaddr_arg != 0)
769     clib_memcpy(hwaddr, hwaddr_arg, 6);
770
771   error = ethernet_register_interface
772         (tm->vnet_main,
773          tapcli_dev_class.index,
774          ti - tm->tapcli_interfaces /* device instance */,
775          hwaddr_arg != 0 ? hwaddr :
776          (u8 *) ifr.ifr_hwaddr.sa_data /* ethernet address */,
777          &ti->hw_if_index, 
778          tapcli_flag_change);
779
780   if (error)
781     {
782       clib_error_report (error);
783       rv = VNET_API_ERROR_INVALID_REGISTRATION;
784       goto error;
785     }
786
787   {
788     unix_file_t template = {0};
789     template.read_function = tapcli_read_ready;
790     template.file_descriptor = dev_net_tun_fd;
791     ti->unix_file_index = unix_file_add (&unix_main, &template);
792     ti->unix_fd = dev_net_tun_fd;
793     ti->provision_fd = dev_tap_fd;
794     clib_memcpy (&ti->ifr, &ifr, sizeof (ifr));
795   }
796   
797   {
798     vnet_hw_interface_t * hw;
799     hw = vnet_get_hw_interface (tm->vnet_main, ti->hw_if_index);
800     hw->min_supported_packet_bytes = TAP_MTU_MIN;
801     hw->max_supported_packet_bytes = TAP_MTU_MAX;
802     hw->max_l3_packet_bytes[VLIB_RX] = hw->max_l3_packet_bytes[VLIB_TX] = hw->max_supported_packet_bytes - sizeof(ethernet_header_t);
803     ti->sw_if_index = hw->sw_if_index;
804     if (sw_if_indexp)
805       *sw_if_indexp = hw->sw_if_index;
806   }
807
808   ti->active = 1;
809   
810   hash_set (tm->tapcli_interface_index_by_sw_if_index, ti->sw_if_index,
811             ti - tm->tapcli_interfaces);
812   
813   hash_set (tm->tapcli_interface_index_by_unix_fd, ti->unix_fd,
814             ti - tm->tapcli_interfaces);
815   
816   return rv;
817
818  error:
819   close (dev_net_tun_fd);
820   close (dev_tap_fd);
821
822   return rv;
823 }
824
825 int vnet_tap_connect_renumber (vlib_main_t * vm, u8 * intfc_name,
826                                u8 *hwaddr_arg, u32 * sw_if_indexp,
827                                u8 renumber, u32 custom_dev_instance)
828 {
829     int rv = vnet_tap_connect(vm, intfc_name, hwaddr_arg, sw_if_indexp);
830
831     if (!rv && renumber)
832         vnet_interface_name_renumber (*sw_if_indexp, custom_dev_instance);
833
834     return rv;
835 }
836
837 static int tapcli_tap_disconnect (tapcli_interface_t *ti)
838 {
839   int rv = 0;
840   vnet_main_t * vnm = vnet_get_main();
841   tapcli_main_t * tm = &tapcli_main;
842   u32 sw_if_index = ti->sw_if_index;
843
844   // bring interface down
845   vnet_sw_interface_set_flags (vnm, sw_if_index, 0);
846
847   if (ti->unix_file_index != ~0) {
848     unix_file_del (&unix_main, unix_main.file_pool + ti->unix_file_index);
849     ti->unix_file_index = ~0;
850   }
851
852   hash_unset (tm->tapcli_interface_index_by_unix_fd, ti->unix_fd);
853   hash_unset (tm->tapcli_interface_index_by_sw_if_index, ti->sw_if_index);
854   close(ti->unix_fd);
855   close(ti->provision_fd);
856   ti->unix_fd = -1;
857   ti->provision_fd = -1;
858
859   return rv;
860 }
861
862 int vnet_tap_delete(vlib_main_t *vm, u32 sw_if_index)
863 {
864   int rv = 0;
865   tapcli_main_t * tm = &tapcli_main;
866   tapcli_interface_t *ti;
867   uword *p = NULL;
868
869   p = hash_get (tm->tapcli_interface_index_by_sw_if_index,
870                 sw_if_index);
871   if (p == 0) {
872     clib_warning ("sw_if_index %d unknown", sw_if_index);
873     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
874   }
875   ti = vec_elt_at_index (tm->tapcli_interfaces, p[0]);
876
877   // inactive
878   ti->active = 0;
879   tapcli_tap_disconnect(ti);
880   // add to inactive list
881   vec_add1(tm->tapcli_inactive_interfaces, ti - tm->tapcli_interfaces);
882
883   // reset renumbered iface
884   if (p[0] < vec_len (tm->show_dev_instance_by_real_dev_instance))
885     tm->show_dev_instance_by_real_dev_instance[p[0]] = ~0;
886
887   ethernet_delete_interface (tm->vnet_main, ti->hw_if_index);
888   return rv;
889 }
890
891 static clib_error_t *
892 tap_delete_command_fn (vlib_main_t * vm,
893                  unformat_input_t * input,
894                  vlib_cli_command_t * cmd)
895 {
896   tapcli_main_t * tm = &tapcli_main;
897   u32 sw_if_index = ~0;
898
899   if (tm->is_disabled)
900     {
901       return clib_error_return (0, "device disabled...");
902     }
903
904   if (unformat (input, "%U", unformat_vnet_sw_interface, tm->vnet_main,
905                 &sw_if_index))
906       ;
907   else
908     return clib_error_return (0, "unknown input `%U'",
909                               format_unformat_error, input);
910
911
912   int rc = vnet_tap_delete (vm, sw_if_index);
913
914   if (!rc) {
915     vlib_cli_output (vm, "Deleted.");
916   } else {
917     vlib_cli_output (vm, "Error during deletion of tap interface. (rc: %d)", rc);
918   }
919
920   return 0;
921 }
922
923 VLIB_CLI_COMMAND (tap_delete_command, static) = {
924     .path = "tap delete",
925     .short_help = "tap delete <vpp-tap-intfc-name>",
926     .function = tap_delete_command_fn,
927 };
928
929 /* modifies tap interface - can result in new interface being created */
930 int vnet_tap_modify (vlib_main_t * vm, u32 orig_sw_if_index,
931                      u8 * intfc_name, u8 *hwaddr_arg, 
932                      u32 * sw_if_indexp,
933                      u8 renumber, u32 custom_dev_instance)
934 {
935     int rv = vnet_tap_delete (vm, orig_sw_if_index);
936
937     if (rv)
938         return rv;
939
940     rv = vnet_tap_connect_renumber(vm, intfc_name, hwaddr_arg, sw_if_indexp,
941             renumber, custom_dev_instance);
942
943     return rv;
944 }
945
946 static clib_error_t *
947 tap_modify_command_fn (vlib_main_t * vm,
948                  unformat_input_t * input,
949                  vlib_cli_command_t * cmd)
950 {
951   u8 * intfc_name;
952   tapcli_main_t * tm = &tapcli_main;
953   u32 sw_if_index = ~0;
954   u32 new_sw_if_index = ~0;
955   int user_hwaddr = 0;
956   u8 hwaddr[6];
957     
958   if (tm->is_disabled)
959     {
960       return clib_error_return (0, "device disabled...");
961     }
962
963   if (unformat (input, "%U", unformat_vnet_sw_interface, tm->vnet_main,
964                 &sw_if_index))
965       ;
966   else
967     return clib_error_return (0, "unknown input `%U'",
968                               format_unformat_error, input);
969
970   if (unformat (input, "%s", &intfc_name))
971     ;
972   else
973     return clib_error_return (0, "unknown input `%U'",
974                               format_unformat_error, input);
975   
976   if (unformat(input, "hwaddr %U", unformat_ethernet_address,
977                &hwaddr))
978     user_hwaddr = 1;
979
980
981   int rc = vnet_tap_modify (vm, sw_if_index, intfc_name,
982                             (user_hwaddr == 1 ? hwaddr : 0),
983                             &new_sw_if_index, 0, 0);
984
985   if (!rc) {
986     vlib_cli_output (vm, "Modified %U for Linux tap '%s'",
987                    format_vnet_sw_if_index_name, tm->vnet_main, 
988                    new_sw_if_index, intfc_name);
989   } else {
990     vlib_cli_output (vm, "Error during modification of tap interface. (rc: %d)", rc);
991   }
992
993   return 0;
994 }
995
996 VLIB_CLI_COMMAND (tap_modify_command, static) = {
997     .path = "tap modify",
998     .short_help = "tap modify <vpp-tap-intfc-name> <linux-intfc-name> [hwaddr [<addr> | random]]",
999     .function = tap_modify_command_fn,
1000 };
1001
1002 static clib_error_t *
1003 tap_connect_command_fn (vlib_main_t * vm,
1004                  unformat_input_t * input,
1005                  vlib_cli_command_t * cmd)
1006 {
1007   u8 * intfc_name;
1008   tapcli_main_t * tm = &tapcli_main;
1009   int user_hwaddr = 0;
1010   u8 hwaddr[6];
1011   u8 *hwaddr_arg = 0;
1012   u32 sw_if_index;
1013
1014   if (tm->is_disabled)
1015     {
1016       return clib_error_return (0, "device disabled...");
1017     }
1018
1019   if (unformat (input, "%s", &intfc_name))
1020     ;
1021   else
1022     return clib_error_return (0, "unknown input `%U'",
1023                               format_unformat_error, input);
1024   
1025   if (unformat(input, "hwaddr %U", unformat_ethernet_address,
1026                &hwaddr))
1027     user_hwaddr = 1;
1028
1029   if (unformat(input, "hwaddr random"))
1030     {
1031       f64 now = vlib_time_now(vm);
1032       u32 rnd;
1033       rnd = (u32) (now * 1e6);
1034       rnd = random_u32 (&rnd);
1035
1036       clib_memcpy (hwaddr+2, &rnd, sizeof(rnd));
1037       hwaddr[0] = 2;
1038       hwaddr[1] = 0xfe;
1039       user_hwaddr = 1;
1040     }
1041   if (user_hwaddr) hwaddr_arg = hwaddr;
1042
1043   int rv = vnet_tap_connect(vm, intfc_name, hwaddr_arg, &sw_if_index);
1044   if (rv) {
1045     switch (rv) {
1046     case VNET_API_ERROR_SYSCALL_ERROR_1:
1047       vlib_cli_output (vm, "Couldn't open /dev/net/tun");
1048       break;
1049
1050     case VNET_API_ERROR_SYSCALL_ERROR_2:
1051       vlib_cli_output (vm, "Error setting flags on '%s'", intfc_name);
1052       break;
1053   
1054     case VNET_API_ERROR_SYSCALL_ERROR_3:
1055       vlib_cli_output (vm, "Couldn't open provisioning socket");
1056       break;
1057
1058     case VNET_API_ERROR_SYSCALL_ERROR_4:
1059       vlib_cli_output (vm, "Couldn't get if_index");
1060       break;
1061     
1062     case VNET_API_ERROR_SYSCALL_ERROR_5:
1063       vlib_cli_output (vm, "Couldn't bind provisioning socket");
1064       break;
1065
1066     case VNET_API_ERROR_SYSCALL_ERROR_6:
1067       vlib_cli_output (0, "Couldn't set device non-blocking flag");
1068       break;
1069
1070     case VNET_API_ERROR_SYSCALL_ERROR_7:
1071       vlib_cli_output (0, "Couldn't set device MTU");
1072       break;
1073
1074     case VNET_API_ERROR_SYSCALL_ERROR_8:
1075       vlib_cli_output (0, "Couldn't get interface flags");
1076       break;
1077
1078     case VNET_API_ERROR_SYSCALL_ERROR_9:
1079       vlib_cli_output (0, "Couldn't set intfc admin state up");
1080       break;
1081
1082     case VNET_API_ERROR_INVALID_REGISTRATION:
1083       vlib_cli_output (0, "Invalid registration");
1084       break;
1085     default:
1086       vlib_cli_output (0, "Unknown error: %d", rv);
1087       break;
1088     }
1089     return 0;
1090   }
1091
1092   vlib_cli_output(vm, "%U\n", format_vnet_sw_if_index_name, vnet_get_main(), sw_if_index);
1093   return 0;
1094   }
1095
1096 VLIB_CLI_COMMAND (tap_connect_command, static) = {
1097     .path = "tap connect",
1098     .short_help = "tap connect <intfc-name> [hwaddr [<addr> | random]]",
1099     .function = tap_connect_command_fn,
1100 };
1101
1102 clib_error_t *
1103 tapcli_init (vlib_main_t * vm)
1104 {
1105   tapcli_main_t * tm = &tapcli_main;
1106
1107   tm->vlib_main = vm;
1108   tm->vnet_main = vnet_get_main();
1109   tm->unix_main = &unix_main;
1110   tm->mtu_bytes = TAP_MTU_DEFAULT;
1111   tm->tapcli_interface_index_by_sw_if_index = hash_create (0, sizeof(uword));
1112   tm->tapcli_interface_index_by_unix_fd = hash_create (0, sizeof (uword));
1113   tm->rx_buffers = 0;
1114   vec_alloc(tm->rx_buffers, VLIB_FRAME_SIZE);
1115   vec_reset_length(tm->rx_buffers);
1116   vm->os_punt_frame = tapcli_nopunt_frame;
1117   return 0;
1118 }
1119
1120 VLIB_INIT_FUNCTION (tapcli_init);