Tap: Fix hardware address assignment
[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   ti = tapcli_get_new_tapif();
760   ti->per_interface_next_index = ~0;
761
762   if (hwaddr_arg != 0)
763     clib_memcpy(hwaddr, hwaddr_arg, 6);
764   else
765     {
766       f64 now = vlib_time_now(vm);
767       u32 rnd;
768       rnd = (u32) (now * 1e6);
769       rnd = random_u32 (&rnd);
770
771       memcpy (hwaddr+2, &rnd, sizeof(rnd));
772       hwaddr[0] = 2;
773       hwaddr[1] = 0xfe;
774     }
775
776   error = ethernet_register_interface
777         (tm->vnet_main,
778          tapcli_dev_class.index,
779          ti - tm->tapcli_interfaces /* device instance */,
780          hwaddr /* ethernet address */,
781          &ti->hw_if_index, 
782          tapcli_flag_change);
783
784   if (error)
785     {
786       clib_error_report (error);
787       rv = VNET_API_ERROR_INVALID_REGISTRATION;
788       goto error;
789     }
790
791   {
792     unix_file_t template = {0};
793     template.read_function = tapcli_read_ready;
794     template.file_descriptor = dev_net_tun_fd;
795     ti->unix_file_index = unix_file_add (&unix_main, &template);
796     ti->unix_fd = dev_net_tun_fd;
797     ti->provision_fd = dev_tap_fd;
798     clib_memcpy (&ti->ifr, &ifr, sizeof (ifr));
799   }
800   
801   {
802     vnet_hw_interface_t * hw;
803     hw = vnet_get_hw_interface (tm->vnet_main, ti->hw_if_index);
804     hw->min_supported_packet_bytes = TAP_MTU_MIN;
805     hw->max_supported_packet_bytes = TAP_MTU_MAX;
806     hw->max_l3_packet_bytes[VLIB_RX] = hw->max_l3_packet_bytes[VLIB_TX] = hw->max_supported_packet_bytes - sizeof(ethernet_header_t);
807     ti->sw_if_index = hw->sw_if_index;
808     if (sw_if_indexp)
809       *sw_if_indexp = hw->sw_if_index;
810   }
811
812   ti->active = 1;
813   
814   hash_set (tm->tapcli_interface_index_by_sw_if_index, ti->sw_if_index,
815             ti - tm->tapcli_interfaces);
816   
817   hash_set (tm->tapcli_interface_index_by_unix_fd, ti->unix_fd,
818             ti - tm->tapcli_interfaces);
819   
820   return rv;
821
822  error:
823   close (dev_net_tun_fd);
824   close (dev_tap_fd);
825
826   return rv;
827 }
828
829 int vnet_tap_connect_renumber (vlib_main_t * vm, u8 * intfc_name,
830                                u8 *hwaddr_arg, u32 * sw_if_indexp,
831                                u8 renumber, u32 custom_dev_instance)
832 {
833     int rv = vnet_tap_connect(vm, intfc_name, hwaddr_arg, sw_if_indexp);
834
835     if (!rv && renumber)
836         vnet_interface_name_renumber (*sw_if_indexp, custom_dev_instance);
837
838     return rv;
839 }
840
841 static int tapcli_tap_disconnect (tapcli_interface_t *ti)
842 {
843   int rv = 0;
844   vnet_main_t * vnm = vnet_get_main();
845   tapcli_main_t * tm = &tapcli_main;
846   u32 sw_if_index = ti->sw_if_index;
847
848   // bring interface down
849   vnet_sw_interface_set_flags (vnm, sw_if_index, 0);
850
851   if (ti->unix_file_index != ~0) {
852     unix_file_del (&unix_main, unix_main.file_pool + ti->unix_file_index);
853     ti->unix_file_index = ~0;
854   }
855
856   hash_unset (tm->tapcli_interface_index_by_unix_fd, ti->unix_fd);
857   hash_unset (tm->tapcli_interface_index_by_sw_if_index, ti->sw_if_index);
858   close(ti->unix_fd);
859   close(ti->provision_fd);
860   ti->unix_fd = -1;
861   ti->provision_fd = -1;
862
863   return rv;
864 }
865
866 int vnet_tap_delete(vlib_main_t *vm, u32 sw_if_index)
867 {
868   int rv = 0;
869   tapcli_main_t * tm = &tapcli_main;
870   tapcli_interface_t *ti;
871   uword *p = NULL;
872
873   p = hash_get (tm->tapcli_interface_index_by_sw_if_index,
874                 sw_if_index);
875   if (p == 0) {
876     clib_warning ("sw_if_index %d unknown", sw_if_index);
877     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
878   }
879   ti = vec_elt_at_index (tm->tapcli_interfaces, p[0]);
880
881   // inactive
882   ti->active = 0;
883   tapcli_tap_disconnect(ti);
884   // add to inactive list
885   vec_add1(tm->tapcli_inactive_interfaces, ti - tm->tapcli_interfaces);
886
887   // reset renumbered iface
888   if (p[0] < vec_len (tm->show_dev_instance_by_real_dev_instance))
889     tm->show_dev_instance_by_real_dev_instance[p[0]] = ~0;
890
891   ethernet_delete_interface (tm->vnet_main, ti->hw_if_index);
892   return rv;
893 }
894
895 static clib_error_t *
896 tap_delete_command_fn (vlib_main_t * vm,
897                  unformat_input_t * input,
898                  vlib_cli_command_t * cmd)
899 {
900   tapcli_main_t * tm = &tapcli_main;
901   u32 sw_if_index = ~0;
902
903   if (tm->is_disabled)
904     {
905       return clib_error_return (0, "device disabled...");
906     }
907
908   if (unformat (input, "%U", unformat_vnet_sw_interface, tm->vnet_main,
909                 &sw_if_index))
910       ;
911   else
912     return clib_error_return (0, "unknown input `%U'",
913                               format_unformat_error, input);
914
915
916   int rc = vnet_tap_delete (vm, sw_if_index);
917
918   if (!rc) {
919     vlib_cli_output (vm, "Deleted.");
920   } else {
921     vlib_cli_output (vm, "Error during deletion of tap interface. (rc: %d)", rc);
922   }
923
924   return 0;
925 }
926
927 VLIB_CLI_COMMAND (tap_delete_command, static) = {
928     .path = "tap delete",
929     .short_help = "tap delete <vpp-tap-intfc-name>",
930     .function = tap_delete_command_fn,
931 };
932
933 /* modifies tap interface - can result in new interface being created */
934 int vnet_tap_modify (vlib_main_t * vm, u32 orig_sw_if_index,
935                      u8 * intfc_name, u8 *hwaddr_arg, 
936                      u32 * sw_if_indexp,
937                      u8 renumber, u32 custom_dev_instance)
938 {
939     int rv = vnet_tap_delete (vm, orig_sw_if_index);
940
941     if (rv)
942         return rv;
943
944     rv = vnet_tap_connect_renumber(vm, intfc_name, hwaddr_arg, sw_if_indexp,
945             renumber, custom_dev_instance);
946
947     return rv;
948 }
949
950 static clib_error_t *
951 tap_modify_command_fn (vlib_main_t * vm,
952                  unformat_input_t * input,
953                  vlib_cli_command_t * cmd)
954 {
955   u8 * intfc_name;
956   tapcli_main_t * tm = &tapcli_main;
957   u32 sw_if_index = ~0;
958   u32 new_sw_if_index = ~0;
959   int user_hwaddr = 0;
960   u8 hwaddr[6];
961     
962   if (tm->is_disabled)
963     {
964       return clib_error_return (0, "device disabled...");
965     }
966
967   if (unformat (input, "%U", unformat_vnet_sw_interface, tm->vnet_main,
968                 &sw_if_index))
969       ;
970   else
971     return clib_error_return (0, "unknown input `%U'",
972                               format_unformat_error, input);
973
974   if (unformat (input, "%s", &intfc_name))
975     ;
976   else
977     return clib_error_return (0, "unknown input `%U'",
978                               format_unformat_error, input);
979   
980   if (unformat(input, "hwaddr %U", unformat_ethernet_address,
981                &hwaddr))
982     user_hwaddr = 1;
983
984
985   int rc = vnet_tap_modify (vm, sw_if_index, intfc_name,
986                             (user_hwaddr == 1 ? hwaddr : 0),
987                             &new_sw_if_index, 0, 0);
988
989   if (!rc) {
990     vlib_cli_output (vm, "Modified %U for Linux tap '%s'",
991                    format_vnet_sw_if_index_name, tm->vnet_main, 
992                    new_sw_if_index, intfc_name);
993   } else {
994     vlib_cli_output (vm, "Error during modification of tap interface. (rc: %d)", rc);
995   }
996
997   return 0;
998 }
999
1000 VLIB_CLI_COMMAND (tap_modify_command, static) = {
1001     .path = "tap modify",
1002     .short_help = "tap modify <vpp-tap-intfc-name> <linux-intfc-name> [hwaddr <addr>]",
1003     .function = tap_modify_command_fn,
1004 };
1005
1006 static clib_error_t *
1007 tap_connect_command_fn (vlib_main_t * vm,
1008                  unformat_input_t * input,
1009                  vlib_cli_command_t * cmd)
1010 {
1011   u8 * intfc_name;
1012   tapcli_main_t * tm = &tapcli_main;
1013   u8 hwaddr[6];
1014   u8 *hwaddr_arg = 0;
1015   u32 sw_if_index;
1016
1017   if (tm->is_disabled)
1018     {
1019       return clib_error_return (0, "device disabled...");
1020     }
1021
1022   if (unformat (input, "%s", &intfc_name))
1023     ;
1024   else
1025     return clib_error_return (0, "unknown input `%U'",
1026                               format_unformat_error, input);
1027   
1028   if (unformat(input, "hwaddr %U", unformat_ethernet_address,
1029                &hwaddr))
1030     hwaddr_arg = hwaddr;
1031
1032   /* It is here for backward compatibility */
1033   if (unformat(input, "hwaddr random"))
1034     ;
1035
1036   int rv = vnet_tap_connect(vm, intfc_name, hwaddr_arg, &sw_if_index);
1037   if (rv) {
1038     switch (rv) {
1039     case VNET_API_ERROR_SYSCALL_ERROR_1:
1040       vlib_cli_output (vm, "Couldn't open /dev/net/tun");
1041       break;
1042
1043     case VNET_API_ERROR_SYSCALL_ERROR_2:
1044       vlib_cli_output (vm, "Error setting flags on '%s'", intfc_name);
1045       break;
1046   
1047     case VNET_API_ERROR_SYSCALL_ERROR_3:
1048       vlib_cli_output (vm, "Couldn't open provisioning socket");
1049       break;
1050
1051     case VNET_API_ERROR_SYSCALL_ERROR_4:
1052       vlib_cli_output (vm, "Couldn't get if_index");
1053       break;
1054     
1055     case VNET_API_ERROR_SYSCALL_ERROR_5:
1056       vlib_cli_output (vm, "Couldn't bind provisioning socket");
1057       break;
1058
1059     case VNET_API_ERROR_SYSCALL_ERROR_6:
1060       vlib_cli_output (0, "Couldn't set device non-blocking flag");
1061       break;
1062
1063     case VNET_API_ERROR_SYSCALL_ERROR_7:
1064       vlib_cli_output (0, "Couldn't set device MTU");
1065       break;
1066
1067     case VNET_API_ERROR_SYSCALL_ERROR_8:
1068       vlib_cli_output (0, "Couldn't get interface flags");
1069       break;
1070
1071     case VNET_API_ERROR_SYSCALL_ERROR_9:
1072       vlib_cli_output (0, "Couldn't set intfc admin state up");
1073       break;
1074
1075     case VNET_API_ERROR_INVALID_REGISTRATION:
1076       vlib_cli_output (0, "Invalid registration");
1077       break;
1078     default:
1079       vlib_cli_output (0, "Unknown error: %d", rv);
1080       break;
1081     }
1082     return 0;
1083   }
1084
1085   vlib_cli_output(vm, "%U\n", format_vnet_sw_if_index_name, vnet_get_main(), sw_if_index);
1086   return 0;
1087   }
1088
1089 VLIB_CLI_COMMAND (tap_connect_command, static) = {
1090     .path = "tap connect",
1091     .short_help = "tap connect <intfc-name> [hwaddr <addr>]",
1092     .function = tap_connect_command_fn,
1093 };
1094
1095 clib_error_t *
1096 tapcli_init (vlib_main_t * vm)
1097 {
1098   tapcli_main_t * tm = &tapcli_main;
1099
1100   tm->vlib_main = vm;
1101   tm->vnet_main = vnet_get_main();
1102   tm->unix_main = &unix_main;
1103   tm->mtu_bytes = TAP_MTU_DEFAULT;
1104   tm->tapcli_interface_index_by_sw_if_index = hash_create (0, sizeof(uword));
1105   tm->tapcli_interface_index_by_unix_fd = hash_create (0, sizeof (uword));
1106   tm->rx_buffers = 0;
1107   vec_alloc(tm->rx_buffers, VLIB_FRAME_SIZE);
1108   vec_reset_length(tm->rx_buffers);
1109   vm->os_punt_frame = tapcli_nopunt_frame;
1110   return 0;
1111 }
1112
1113 VLIB_INIT_FUNCTION (tapcli_init);