tapcli: Use error counter for buffer allocation error
[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           vlib_node_increment_counter(vm, tapcli_rx_node.index,
253                                       TAPCLI_ERROR_BUFFER_ALLOC,
254                                       tm->mtu_buffers - vec_len(tm->rx_buffers));
255         break;
256       }
257     }
258
259     uword i_rx = vec_len (tm->rx_buffers) - 1;
260
261     /* Allocate RX buffers from end of rx_buffers.
262            Turn them into iovecs to pass to readv. */
263     vec_validate (tm->iovecs, tm->mtu_buffers - 1);
264     for (j = 0; j < tm->mtu_buffers; j++) {
265       b = vlib_get_buffer (vm, tm->rx_buffers[i_rx - j]);
266       tm->iovecs[j].iov_base = b->data;
267       tm->iovecs[j].iov_len = buffer_size;
268     }
269
270     n_bytes_left = readv (ti->unix_fd, tm->iovecs, tm->mtu_buffers);
271     n_bytes_in_packet = n_bytes_left;
272     if (n_bytes_left <= 0) {
273       if (errno != EAGAIN) {
274         vlib_node_increment_counter(vm, tapcli_rx_node.index,
275                                     TAPCLI_ERROR_READ, 1);
276       }
277       break;
278     }
279
280     bi_first = tm->rx_buffers[i_rx];
281     b = b_first = vlib_get_buffer (vm, tm->rx_buffers[i_rx]);
282     prev = NULL;
283
284     while (1) {
285       b->current_length = n_bytes_left < buffer_size ? n_bytes_left : buffer_size;
286       n_bytes_left -= buffer_size;
287
288       if (prev) {
289         prev->next_buffer = bi;
290         prev->flags |= VLIB_BUFFER_NEXT_PRESENT;
291       }
292       prev = b;
293
294       /* last segment */
295       if (n_bytes_left <= 0)
296         break;
297
298       i_rx--;
299       bi = tm->rx_buffers[i_rx];
300       b = vlib_get_buffer (vm, bi);
301     }
302
303     _vec_len (tm->rx_buffers) = i_rx;
304
305     b_first->total_length_not_including_first_buffer =
306         (n_bytes_in_packet > buffer_size) ? n_bytes_in_packet - buffer_size : 0;
307     b_first->flags |= VLIB_BUFFER_TOTAL_LENGTH_VALID;
308
309     /* Ensure mbufs are updated */
310     vlib_buffer_chain_validate(vm, b_first);
311
312     VLIB_BUFFER_TRACE_TRAJECTORY_INIT(b_first);
313
314     vnet_buffer (b_first)->sw_if_index[VLIB_RX] = ti->sw_if_index;
315     vnet_buffer (b_first)->sw_if_index[VLIB_TX] = (u32)~0;
316
317     b_first->error = node->errors[TAPCLI_ERROR_NONE];
318     next_index = TAPCLI_RX_NEXT_ETHERNET_INPUT;
319     next_index = (ti->per_interface_next_index != ~0) ?
320         ti->per_interface_next_index : next_index;
321     next_index = admin_down ? TAPCLI_RX_NEXT_DROP : next_index;
322
323     to_next[0] = bi_first;
324     to_next++;
325     n_left_to_next--;
326
327     vlib_validate_buffer_enqueue_x1 (vm, node, next,
328                                      to_next, n_left_to_next,
329                                      bi_first, next_index);
330
331     /* Interface counters for tapcli interface. */
332     if (PREDICT_TRUE(!admin_down)) {
333       vlib_increment_combined_counter (
334           vnet_main.interface_main.combined_sw_if_counters
335           + VNET_INTERFACE_COUNTER_RX,
336           os_get_cpu_number(), ti->sw_if_index,
337           1, n_bytes_in_packet);
338
339       if (PREDICT_FALSE(n_trace > 0)) {
340         vlib_trace_buffer (vm, node, next_index,
341                            b_first, /* follow_chain */ 1);
342         n_trace--;
343         set_trace = 1;
344         tapcli_rx_trace_t *t0 = vlib_add_trace (vm, node, b_first, sizeof (*t0));
345         t0->sw_if_index = si->sw_if_index;
346       }
347     }
348   }
349   vlib_put_next_frame (vm, node, next, n_left_to_next);
350   if (set_trace)
351     vlib_set_trace_count (vm, node, n_trace);
352   return VLIB_FRAME_SIZE - n_left_to_next;
353 }
354
355 static uword
356 tapcli_rx (vlib_main_t * vm,
357            vlib_node_runtime_t * node,
358            vlib_frame_t * frame)
359 {
360   tapcli_main_t * tm = &tapcli_main;
361   static u32 * ready_interface_indices;
362   tapcli_interface_t * ti;
363   int i;
364   u32 total_count = 0;
365
366   vec_reset_length (ready_interface_indices);
367   clib_bitmap_foreach (i, tm->pending_read_bitmap,
368   ({
369     vec_add1 (ready_interface_indices, i);
370   }));
371
372   if (vec_len (ready_interface_indices) == 0)
373     return 0;
374
375   for (i = 0; i < vec_len(ready_interface_indices); i++)
376   {
377     tm->pending_read_bitmap =
378         clib_bitmap_set (tm->pending_read_bitmap,
379                          ready_interface_indices[i], 0);
380
381     ti = vec_elt_at_index (tm->tapcli_interfaces, ready_interface_indices[i]);
382     total_count += tapcli_rx_iface(vm, node, ti);
383   }
384   return total_count; //This might return more than 256.
385 }
386
387 static char * tapcli_rx_error_strings[] = {
388 #define _(sym,string) string,
389   foreach_tapcli_error
390 #undef _
391 };
392
393 VLIB_REGISTER_NODE (tapcli_rx_node, static) = {
394   .function = tapcli_rx,
395   .name = "tapcli-rx",
396   .type = VLIB_NODE_TYPE_INPUT,
397   .state = VLIB_NODE_STATE_INTERRUPT,
398   .vector_size = 4,
399   .n_errors = TAPCLI_N_ERROR,
400   .error_strings = tapcli_rx_error_strings,
401   .format_trace = format_tapcli_rx_trace,
402
403   .n_next_nodes = TAPCLI_RX_N_NEXT,
404   .next_nodes = {
405     [TAPCLI_RX_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
406     [TAPCLI_RX_NEXT_IP6_INPUT] = "ip6-input",
407     [TAPCLI_RX_NEXT_DROP] = "error-drop",
408     [TAPCLI_RX_NEXT_ETHERNET_INPUT] = "ethernet-input",
409   },
410 };
411
412 /* Gets called when file descriptor is ready from epoll. */
413 static clib_error_t * tapcli_read_ready (unix_file_t * uf)
414 {
415   vlib_main_t * vm = vlib_get_main();
416   tapcli_main_t * tm = &tapcli_main;
417   uword * p;
418   
419   /* Schedule the rx node */
420   vlib_node_set_interrupt_pending (vm, tapcli_rx_node.index);
421
422   p = hash_get (tm->tapcli_interface_index_by_unix_fd, uf->file_descriptor);
423
424   /* Mark the specific tap interface ready-to-read */
425   if (p)
426     tm->pending_read_bitmap = clib_bitmap_set (tm->pending_read_bitmap,
427                                                p[0], 1);
428   else
429     clib_warning ("fd %d not in hash table", uf->file_descriptor);
430
431   return 0;
432 }
433
434 static clib_error_t *
435 tapcli_config (vlib_main_t * vm, unformat_input_t * input)
436 {
437   tapcli_main_t *tm = &tapcli_main;
438   const uword buffer_size = VLIB_BUFFER_DATA_SIZE;
439
440   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
441     {
442       if (unformat (input, "mtu %d", &tm->mtu_bytes))
443         ;
444       else if (unformat (input, "disable"))
445         tm->is_disabled = 1;
446       else
447           return clib_error_return (0, "unknown input `%U'",
448                                     format_unformat_error, input);
449     }
450
451   if (tm->is_disabled)
452     return 0;
453
454   if (geteuid()) 
455     {
456       clib_warning ("tapcli disabled: must be superuser");
457       tm->is_disabled = 1;
458       return 0;
459     }    
460
461   tm->mtu_buffers = (tm->mtu_bytes + (buffer_size - 1)) / buffer_size;
462   
463   return 0;
464 }
465
466 static int tap_name_renumber (vnet_hw_interface_t * hi,
467                               u32 new_dev_instance)
468 {
469   tapcli_main_t *tm = &tapcli_main;
470
471   vec_validate_init_empty (tm->show_dev_instance_by_real_dev_instance,
472                            hi->dev_instance, ~0);
473
474   tm->show_dev_instance_by_real_dev_instance [hi->dev_instance] =
475     new_dev_instance;
476
477   return 0;
478 }
479
480 VLIB_CONFIG_FUNCTION (tapcli_config, "tapcli");
481
482 static void
483 tapcli_nopunt_frame (vlib_main_t * vm,
484                    vlib_node_runtime_t * node,
485                    vlib_frame_t * frame)
486 {
487   u32 * buffers = vlib_frame_args (frame);
488   uword n_packets = frame->n_vectors;
489   vlib_buffer_free (vm, buffers, n_packets);
490   vlib_frame_free (vm, node, frame);
491 }
492
493 VNET_HW_INTERFACE_CLASS (tapcli_interface_class,static) = {
494   .name = "tapcli",
495 };
496
497 static u8 * format_tapcli_interface_name (u8 * s, va_list * args)
498 {
499   u32 i = va_arg (*args, u32);
500   u32 show_dev_instance = ~0;
501   tapcli_main_t * tm = &tapcli_main;
502
503   if (i < vec_len (tm->show_dev_instance_by_real_dev_instance))
504     show_dev_instance = tm->show_dev_instance_by_real_dev_instance[i];
505
506   if (show_dev_instance != ~0)
507     i = show_dev_instance;
508
509   s = format (s, "tap-%d", i);
510   return s;
511 }
512
513 static u32 tapcli_flag_change (vnet_main_t * vnm, 
514                                vnet_hw_interface_t * hw,
515                                u32 flags)
516 {
517   tapcli_main_t *tm = &tapcli_main;
518   tapcli_interface_t *ti;
519
520    ti = vec_elt_at_index (tm->tapcli_interfaces, hw->dev_instance);
521
522   if (flags & ETHERNET_INTERFACE_FLAG_MTU)
523     {
524       const uword buffer_size = VLIB_BUFFER_DATA_SIZE;
525       tm->mtu_bytes = hw->max_packet_bytes;
526       tm->mtu_buffers = (tm->mtu_bytes + (buffer_size - 1)) / buffer_size;
527     }
528    else
529     {
530       struct ifreq ifr;
531       u32 want_promisc;
532
533       memcpy (&ifr, &ti->ifr, sizeof (ifr));
534
535       /* get flags, modify to bring up interface... */
536       if (ioctl (ti->provision_fd, SIOCGIFFLAGS, &ifr) < 0)
537         {
538           clib_unix_warning ("Couldn't get interface flags for %s", hw->name);
539           return 0;
540         }
541
542       want_promisc = (flags & ETHERNET_INTERFACE_FLAG_ACCEPT_ALL) != 0;
543
544       if (want_promisc == ti->is_promisc)
545         return 0;
546
547       if (flags & ETHERNET_INTERFACE_FLAG_ACCEPT_ALL)
548         ifr.ifr_flags |= IFF_PROMISC;
549       else
550         ifr.ifr_flags &= ~(IFF_PROMISC);
551
552       /* get flags, modify to bring up interface... */
553       if (ioctl (ti->provision_fd, SIOCSIFFLAGS, &ifr) < 0)
554         {
555           clib_unix_warning ("Couldn't set interface flags for %s", hw->name);
556           return 0;
557         }
558
559       ti->is_promisc = want_promisc;
560     }
561
562   return 0;
563 }
564
565 static void tapcli_set_interface_next_node (vnet_main_t *vnm, 
566                                             u32 hw_if_index,
567                                             u32 node_index)
568 {
569   tapcli_main_t *tm = &tapcli_main;
570   tapcli_interface_t *ti;
571   vnet_hw_interface_t *hw = vnet_get_hw_interface (vnm, hw_if_index);
572
573   ti = vec_elt_at_index (tm->tapcli_interfaces, hw->dev_instance);
574   
575   /* Shut off redirection */
576   if (node_index == ~0)
577     {
578       ti->per_interface_next_index = node_index;
579       return;
580     }
581   
582   ti->per_interface_next_index = 
583     vlib_node_add_next (tm->vlib_main, tapcli_rx_node.index, node_index);
584 }
585
586 /* 
587  * Mainly exists to set link_state == admin_state
588  * otherwise, e.g. ip6 neighbor discovery breaks
589  */
590 static clib_error_t * 
591 tapcli_interface_admin_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags)
592 {
593   uword is_admin_up = (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) != 0;
594   u32 hw_flags;
595   u32 speed_duplex = VNET_HW_INTERFACE_FLAG_FULL_DUPLEX 
596     | VNET_HW_INTERFACE_FLAG_SPEED_1G;
597     
598   if (is_admin_up)
599     hw_flags = VNET_HW_INTERFACE_FLAG_LINK_UP | speed_duplex;
600   else
601     hw_flags = speed_duplex;
602   
603   vnet_hw_interface_set_flags (vnm, hw_if_index, hw_flags);
604   return 0;
605 }
606
607 VNET_DEVICE_CLASS (tapcli_dev_class,static) = {
608   .name = "tapcli",
609   .tx_function = tapcli_tx,
610   .format_device_name = format_tapcli_interface_name,
611   .rx_redirect_to_node = tapcli_set_interface_next_node,
612   .name_renumber = tap_name_renumber,
613   .admin_up_down_function = tapcli_interface_admin_up_down,
614   .no_flatten_output_chains = 1,
615 };
616
617 int vnet_tap_dump_ifs (tapcli_interface_details_t **out_tapids)
618 {
619   tapcli_main_t * tm = &tapcli_main;
620   tapcli_interface_t * ti;
621
622   tapcli_interface_details_t * r_tapids = NULL;
623   tapcli_interface_details_t * tapid = NULL;
624
625   vec_foreach (ti, tm->tapcli_interfaces) {
626     if (!ti->active)
627         continue;
628     vec_add2(r_tapids, tapid, 1);
629     tapid->sw_if_index = ti->sw_if_index;
630     strncpy((char *)tapid->dev_name, ti->ifr.ifr_name, sizeof (ti->ifr.ifr_name)-1);
631   }
632
633   *out_tapids = r_tapids;
634
635   return 0;
636 }
637
638 /* get tap interface from inactive interfaces or create new */
639 static tapcli_interface_t *tapcli_get_new_tapif()
640 {
641   tapcli_main_t * tm = &tapcli_main;
642   tapcli_interface_t *ti = NULL;
643
644   int inactive_cnt = vec_len(tm->tapcli_inactive_interfaces);
645   // if there are any inactive ifaces
646   if (inactive_cnt > 0) {
647     // take last
648     u32 ti_idx = tm->tapcli_inactive_interfaces[inactive_cnt - 1];
649     if (vec_len(tm->tapcli_interfaces) > ti_idx) {
650       ti = vec_elt_at_index (tm->tapcli_interfaces, ti_idx);
651       clib_warning("reusing tap interface");
652     }
653     // "remove" from inactive list
654     _vec_len(tm->tapcli_inactive_interfaces) -= 1;
655   }
656
657   // ti was not retrieved from inactive ifaces - create new
658   if (!ti)
659     vec_add2 (tm->tapcli_interfaces, ti, 1);
660
661   return ti;
662 }
663
664 int vnet_tap_connect (vlib_main_t * vm, u8 * intfc_name, u8 *hwaddr_arg,
665                       u32 * sw_if_indexp)
666 {
667   tapcli_main_t * tm = &tapcli_main;
668   tapcli_interface_t * ti = NULL;
669   struct ifreq ifr;
670   int flags;
671   int dev_net_tun_fd;
672   int dev_tap_fd = -1;
673   clib_error_t * error;
674   u8 hwaddr [6];
675   int rv = 0;
676
677   if (tm->is_disabled)
678     {
679       return VNET_API_ERROR_FEATURE_DISABLED;
680     }
681
682   flags = IFF_TAP | IFF_NO_PI;
683
684   if ((dev_net_tun_fd = open ("/dev/net/tun", O_RDWR)) < 0)
685     return VNET_API_ERROR_SYSCALL_ERROR_1;
686   
687   memset (&ifr, 0, sizeof (ifr));
688   strncpy(ifr.ifr_name, (char *) intfc_name, sizeof (ifr.ifr_name)-1);
689   ifr.ifr_flags = flags;
690   if (ioctl (dev_net_tun_fd, TUNSETIFF, (void *)&ifr) < 0)
691     {
692       rv = VNET_API_ERROR_SYSCALL_ERROR_2;
693       goto error;
694     }
695     
696   /* Open a provisioning socket */
697   if ((dev_tap_fd = socket(PF_PACKET, SOCK_RAW,
698                            htons(ETH_P_ALL))) < 0 )
699     {
700       rv = VNET_API_ERROR_SYSCALL_ERROR_3;
701       goto error;
702     }
703
704   /* Find the interface index. */
705   {
706     struct ifreq ifr;
707     struct sockaddr_ll sll;
708
709     memset (&ifr, 0, sizeof(ifr));
710     strncpy (ifr.ifr_name, (char *) intfc_name, sizeof (ifr.ifr_name)-1);
711     if (ioctl (dev_tap_fd, SIOCGIFINDEX, &ifr) < 0 )
712       {
713         rv = VNET_API_ERROR_SYSCALL_ERROR_4;
714         goto error;
715       }
716
717     /* Bind the provisioning socket to the interface. */
718     memset(&sll, 0, sizeof(sll));
719     sll.sll_family   = AF_PACKET;
720     sll.sll_ifindex  = ifr.ifr_ifindex;
721     sll.sll_protocol = htons(ETH_P_ALL);
722
723     if (bind(dev_tap_fd, (struct sockaddr*) &sll, sizeof(sll)) < 0)
724       {
725         rv = VNET_API_ERROR_SYSCALL_ERROR_5;
726         goto error;
727       }
728   }
729
730   /* non-blocking I/O on /dev/tapX */
731   {
732     int one = 1;
733     if (ioctl (dev_net_tun_fd, FIONBIO, &one) < 0)
734       {
735         rv = VNET_API_ERROR_SYSCALL_ERROR_6;
736         goto error;
737       }
738   }
739   ifr.ifr_mtu = tm->mtu_bytes;
740   if (ioctl (dev_tap_fd, SIOCSIFMTU, &ifr) < 0)
741     {
742       rv = VNET_API_ERROR_SYSCALL_ERROR_7;
743       goto error;
744     }
745
746   /* get flags, modify to bring up interface... */
747   if (ioctl (dev_tap_fd, SIOCGIFFLAGS, &ifr) < 0)
748     {
749       rv = VNET_API_ERROR_SYSCALL_ERROR_8;
750       goto error;
751     }
752
753   ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
754
755   if (ioctl (dev_tap_fd, SIOCSIFFLAGS, &ifr) < 0)
756     {
757       rv = VNET_API_ERROR_SYSCALL_ERROR_9;
758       goto error;
759     }
760
761   ti = tapcli_get_new_tapif();
762   ti->per_interface_next_index = ~0;
763
764   if (hwaddr_arg != 0)
765     clib_memcpy(hwaddr, hwaddr_arg, 6);
766   else
767     {
768       f64 now = vlib_time_now(vm);
769       u32 rnd;
770       rnd = (u32) (now * 1e6);
771       rnd = random_u32 (&rnd);
772
773       memcpy (hwaddr+2, &rnd, sizeof(rnd));
774       hwaddr[0] = 2;
775       hwaddr[1] = 0xfe;
776     }
777
778   error = ethernet_register_interface
779         (tm->vnet_main,
780          tapcli_dev_class.index,
781          ti - tm->tapcli_interfaces /* device instance */,
782          hwaddr /* ethernet address */,
783          &ti->hw_if_index, 
784          tapcli_flag_change);
785
786   if (error)
787     {
788       clib_error_report (error);
789       rv = VNET_API_ERROR_INVALID_REGISTRATION;
790       goto error;
791     }
792
793   {
794     unix_file_t template = {0};
795     template.read_function = tapcli_read_ready;
796     template.file_descriptor = dev_net_tun_fd;
797     ti->unix_file_index = unix_file_add (&unix_main, &template);
798     ti->unix_fd = dev_net_tun_fd;
799     ti->provision_fd = dev_tap_fd;
800     clib_memcpy (&ti->ifr, &ifr, sizeof (ifr));
801   }
802   
803   {
804     vnet_hw_interface_t * hw;
805     hw = vnet_get_hw_interface (tm->vnet_main, ti->hw_if_index);
806     hw->min_supported_packet_bytes = TAP_MTU_MIN;
807     hw->max_supported_packet_bytes = TAP_MTU_MAX;
808     hw->max_l3_packet_bytes[VLIB_RX] = hw->max_l3_packet_bytes[VLIB_TX] = hw->max_supported_packet_bytes - sizeof(ethernet_header_t);
809     ti->sw_if_index = hw->sw_if_index;
810     if (sw_if_indexp)
811       *sw_if_indexp = hw->sw_if_index;
812   }
813
814   ti->active = 1;
815   
816   hash_set (tm->tapcli_interface_index_by_sw_if_index, ti->sw_if_index,
817             ti - tm->tapcli_interfaces);
818   
819   hash_set (tm->tapcli_interface_index_by_unix_fd, ti->unix_fd,
820             ti - tm->tapcli_interfaces);
821   
822   return rv;
823
824  error:
825   close (dev_net_tun_fd);
826   close (dev_tap_fd);
827
828   return rv;
829 }
830
831 int vnet_tap_connect_renumber (vlib_main_t * vm, u8 * intfc_name,
832                                u8 *hwaddr_arg, u32 * sw_if_indexp,
833                                u8 renumber, u32 custom_dev_instance)
834 {
835     int rv = vnet_tap_connect(vm, intfc_name, hwaddr_arg, sw_if_indexp);
836
837     if (!rv && renumber)
838         vnet_interface_name_renumber (*sw_if_indexp, custom_dev_instance);
839
840     return rv;
841 }
842
843 static int tapcli_tap_disconnect (tapcli_interface_t *ti)
844 {
845   int rv = 0;
846   vnet_main_t * vnm = vnet_get_main();
847   tapcli_main_t * tm = &tapcli_main;
848   u32 sw_if_index = ti->sw_if_index;
849
850   // bring interface down
851   vnet_sw_interface_set_flags (vnm, sw_if_index, 0);
852
853   if (ti->unix_file_index != ~0) {
854     unix_file_del (&unix_main, unix_main.file_pool + ti->unix_file_index);
855     ti->unix_file_index = ~0;
856   }
857
858   hash_unset (tm->tapcli_interface_index_by_unix_fd, ti->unix_fd);
859   hash_unset (tm->tapcli_interface_index_by_sw_if_index, ti->sw_if_index);
860   close(ti->unix_fd);
861   close(ti->provision_fd);
862   ti->unix_fd = -1;
863   ti->provision_fd = -1;
864
865   return rv;
866 }
867
868 int vnet_tap_delete(vlib_main_t *vm, u32 sw_if_index)
869 {
870   int rv = 0;
871   tapcli_main_t * tm = &tapcli_main;
872   tapcli_interface_t *ti;
873   uword *p = NULL;
874
875   p = hash_get (tm->tapcli_interface_index_by_sw_if_index,
876                 sw_if_index);
877   if (p == 0) {
878     clib_warning ("sw_if_index %d unknown", sw_if_index);
879     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
880   }
881   ti = vec_elt_at_index (tm->tapcli_interfaces, p[0]);
882
883   // inactive
884   ti->active = 0;
885   tapcli_tap_disconnect(ti);
886   // add to inactive list
887   vec_add1(tm->tapcli_inactive_interfaces, ti - tm->tapcli_interfaces);
888
889   // reset renumbered iface
890   if (p[0] < vec_len (tm->show_dev_instance_by_real_dev_instance))
891     tm->show_dev_instance_by_real_dev_instance[p[0]] = ~0;
892
893   ethernet_delete_interface (tm->vnet_main, ti->hw_if_index);
894   return rv;
895 }
896
897 static clib_error_t *
898 tap_delete_command_fn (vlib_main_t * vm,
899                  unformat_input_t * input,
900                  vlib_cli_command_t * cmd)
901 {
902   tapcli_main_t * tm = &tapcli_main;
903   u32 sw_if_index = ~0;
904
905   if (tm->is_disabled)
906     {
907       return clib_error_return (0, "device disabled...");
908     }
909
910   if (unformat (input, "%U", unformat_vnet_sw_interface, tm->vnet_main,
911                 &sw_if_index))
912       ;
913   else
914     return clib_error_return (0, "unknown input `%U'",
915                               format_unformat_error, input);
916
917
918   int rc = vnet_tap_delete (vm, sw_if_index);
919
920   if (!rc) {
921     vlib_cli_output (vm, "Deleted.");
922   } else {
923     vlib_cli_output (vm, "Error during deletion of tap interface. (rc: %d)", rc);
924   }
925
926   return 0;
927 }
928
929 VLIB_CLI_COMMAND (tap_delete_command, static) = {
930     .path = "tap delete",
931     .short_help = "tap delete <vpp-tap-intfc-name>",
932     .function = tap_delete_command_fn,
933 };
934
935 /* modifies tap interface - can result in new interface being created */
936 int vnet_tap_modify (vlib_main_t * vm, u32 orig_sw_if_index,
937                      u8 * intfc_name, u8 *hwaddr_arg, 
938                      u32 * sw_if_indexp,
939                      u8 renumber, u32 custom_dev_instance)
940 {
941     int rv = vnet_tap_delete (vm, orig_sw_if_index);
942
943     if (rv)
944         return rv;
945
946     rv = vnet_tap_connect_renumber(vm, intfc_name, hwaddr_arg, sw_if_indexp,
947             renumber, custom_dev_instance);
948
949     return rv;
950 }
951
952 static clib_error_t *
953 tap_modify_command_fn (vlib_main_t * vm,
954                  unformat_input_t * input,
955                  vlib_cli_command_t * cmd)
956 {
957   u8 * intfc_name;
958   tapcli_main_t * tm = &tapcli_main;
959   u32 sw_if_index = ~0;
960   u32 new_sw_if_index = ~0;
961   int user_hwaddr = 0;
962   u8 hwaddr[6];
963     
964   if (tm->is_disabled)
965     {
966       return clib_error_return (0, "device disabled...");
967     }
968
969   if (unformat (input, "%U", unformat_vnet_sw_interface, tm->vnet_main,
970                 &sw_if_index))
971       ;
972   else
973     return clib_error_return (0, "unknown input `%U'",
974                               format_unformat_error, input);
975
976   if (unformat (input, "%s", &intfc_name))
977     ;
978   else
979     return clib_error_return (0, "unknown input `%U'",
980                               format_unformat_error, input);
981   
982   if (unformat(input, "hwaddr %U", unformat_ethernet_address,
983                &hwaddr))
984     user_hwaddr = 1;
985
986
987   int rc = vnet_tap_modify (vm, sw_if_index, intfc_name,
988                             (user_hwaddr == 1 ? hwaddr : 0),
989                             &new_sw_if_index, 0, 0);
990
991   if (!rc) {
992     vlib_cli_output (vm, "Modified %U for Linux tap '%s'",
993                    format_vnet_sw_if_index_name, tm->vnet_main, 
994                    new_sw_if_index, intfc_name);
995   } else {
996     vlib_cli_output (vm, "Error during modification of tap interface. (rc: %d)", rc);
997   }
998
999   return 0;
1000 }
1001
1002 VLIB_CLI_COMMAND (tap_modify_command, static) = {
1003     .path = "tap modify",
1004     .short_help = "tap modify <vpp-tap-intfc-name> <linux-intfc-name> [hwaddr <addr>]",
1005     .function = tap_modify_command_fn,
1006 };
1007
1008 static clib_error_t *
1009 tap_connect_command_fn (vlib_main_t * vm,
1010                  unformat_input_t * input,
1011                  vlib_cli_command_t * cmd)
1012 {
1013   u8 * intfc_name;
1014   tapcli_main_t * tm = &tapcli_main;
1015   u8 hwaddr[6];
1016   u8 *hwaddr_arg = 0;
1017   u32 sw_if_index;
1018
1019   if (tm->is_disabled)
1020     {
1021       return clib_error_return (0, "device disabled...");
1022     }
1023
1024   if (unformat (input, "%s", &intfc_name))
1025     ;
1026   else
1027     return clib_error_return (0, "unknown input `%U'",
1028                               format_unformat_error, input);
1029   
1030   if (unformat(input, "hwaddr %U", unformat_ethernet_address,
1031                &hwaddr))
1032     hwaddr_arg = hwaddr;
1033
1034   /* It is here for backward compatibility */
1035   if (unformat(input, "hwaddr random"))
1036     ;
1037
1038   int rv = vnet_tap_connect(vm, intfc_name, hwaddr_arg, &sw_if_index);
1039   if (rv) {
1040     switch (rv) {
1041     case VNET_API_ERROR_SYSCALL_ERROR_1:
1042       vlib_cli_output (vm, "Couldn't open /dev/net/tun");
1043       break;
1044
1045     case VNET_API_ERROR_SYSCALL_ERROR_2:
1046       vlib_cli_output (vm, "Error setting flags on '%s'", intfc_name);
1047       break;
1048   
1049     case VNET_API_ERROR_SYSCALL_ERROR_3:
1050       vlib_cli_output (vm, "Couldn't open provisioning socket");
1051       break;
1052
1053     case VNET_API_ERROR_SYSCALL_ERROR_4:
1054       vlib_cli_output (vm, "Couldn't get if_index");
1055       break;
1056     
1057     case VNET_API_ERROR_SYSCALL_ERROR_5:
1058       vlib_cli_output (vm, "Couldn't bind provisioning socket");
1059       break;
1060
1061     case VNET_API_ERROR_SYSCALL_ERROR_6:
1062       vlib_cli_output (0, "Couldn't set device non-blocking flag");
1063       break;
1064
1065     case VNET_API_ERROR_SYSCALL_ERROR_7:
1066       vlib_cli_output (0, "Couldn't set device MTU");
1067       break;
1068
1069     case VNET_API_ERROR_SYSCALL_ERROR_8:
1070       vlib_cli_output (0, "Couldn't get interface flags");
1071       break;
1072
1073     case VNET_API_ERROR_SYSCALL_ERROR_9:
1074       vlib_cli_output (0, "Couldn't set intfc admin state up");
1075       break;
1076
1077     case VNET_API_ERROR_INVALID_REGISTRATION:
1078       vlib_cli_output (0, "Invalid registration");
1079       break;
1080     default:
1081       vlib_cli_output (0, "Unknown error: %d", rv);
1082       break;
1083     }
1084     return 0;
1085   }
1086
1087   vlib_cli_output(vm, "%U\n", format_vnet_sw_if_index_name, vnet_get_main(), sw_if_index);
1088   return 0;
1089   }
1090
1091 VLIB_CLI_COMMAND (tap_connect_command, static) = {
1092     .path = "tap connect",
1093     .short_help = "tap connect <intfc-name> [hwaddr <addr>]",
1094     .function = tap_connect_command_fn,
1095 };
1096
1097 clib_error_t *
1098 tapcli_init (vlib_main_t * vm)
1099 {
1100   tapcli_main_t * tm = &tapcli_main;
1101
1102   tm->vlib_main = vm;
1103   tm->vnet_main = vnet_get_main();
1104   tm->unix_main = &unix_main;
1105   tm->mtu_bytes = TAP_MTU_DEFAULT;
1106   tm->tapcli_interface_index_by_sw_if_index = hash_create (0, sizeof(uword));
1107   tm->tapcli_interface_index_by_unix_fd = hash_create (0, sizeof (uword));
1108   tm->rx_buffers = 0;
1109   vec_alloc(tm->rx_buffers, VLIB_FRAME_SIZE);
1110   vec_reset_length(tm->rx_buffers);
1111   vm->os_punt_frame = tapcli_nopunt_frame;
1112   return 0;
1113 }
1114
1115 VLIB_INIT_FUNCTION (tapcli_init);