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