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