Add packet/byte count output tx stats to tunap interface
[vpp.git] / vnet / vnet / unix / tuntap.c
1 /* 
2  *------------------------------------------------------------------
3  * tuntap.c - kernel stack (reverse) punt/inject path
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  TunTap Kernel stack (reverse) punt/inject path.
22  *
23  * This driver runs in one of two distinct modes:
24  * - "punt/inject" mode, where we send pkts not otherwise processed
25  * by the forwarding to the Linux kernel stack, and
26  *
27  * - "normal interface" mode, where we treat the Linux kernel stack
28  * as a peer.
29  *
30  * By default, we select punt/inject mode.
31  */
32
33 #include <fcntl.h>              /* for open */
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38 #include <sys/uio.h>            /* for iovec */
39 #include <netinet/in.h>
40
41 #include <linux/if_arp.h>
42 #include <linux/if_tun.h>
43
44 #include <vlib/vlib.h>
45 #include <vlib/unix/unix.h>
46
47 #include <vnet/ip/ip.h>
48
49 #include <vnet/ethernet/ethernet.h>
50
51 #if DPDK == 1
52 #include <vnet/devices/dpdk/dpdk.h>
53 #endif
54
55 static vnet_device_class_t tuntap_dev_class;
56 static vnet_hw_interface_class_t tuntap_interface_class;
57
58 static void tuntap_punt_frame (vlib_main_t * vm,
59                                vlib_node_runtime_t * node,
60                                vlib_frame_t * frame);
61 static void tuntap_nopunt_frame (vlib_main_t * vm,
62                                  vlib_node_runtime_t * node,
63                                  vlib_frame_t * frame);
64
65 typedef struct {
66   u32 sw_if_index;
67   u8 is_v6;
68   u8 addr[16];
69 } subif_address_t;
70
71 /**
72  * @brief TUNTAP node main state
73  */
74 typedef struct {
75   /** Vector of iovecs for readv/writev calls. */
76   struct iovec * iovecs;
77
78   /** Vector of VLIB rx buffers to use.  We allocate them in blocks
79      of VLIB_FRAME_SIZE (256). */
80   u32 * rx_buffers;
81
82   /** File descriptors for /dev/net/tun and provisioning socket. */
83   int dev_net_tun_fd, dev_tap_fd;
84
85   /** Create a "tap" [ethernet] encaps device */
86   int is_ether;
87
88   /** 1 if a "normal" routed intfc, 0 if a punt/inject interface */
89
90   int have_normal_interface;
91
92   /** tap device destination MAC address. Required, or Linux drops pkts */
93   u8 ether_dst_mac[6];
94
95   /** Interface MTU in bytes and # of default sized buffers. */
96   u32 mtu_bytes, mtu_buffers;
97
98   /** Linux interface name for tun device. */
99   char * tun_name;
100
101   /** Pool of subinterface addresses */
102   subif_address_t *subifs;
103
104   /** Hash for subif addresses */
105   mhash_t subif_mhash;
106
107   /** Unix file index */
108   u32 unix_file_index;
109
110   /** For the "normal" interface, if configured */
111   u32 hw_if_index, sw_if_index;
112
113 } tuntap_main_t;
114
115 static tuntap_main_t tuntap_main = {
116   .tun_name = "vnet",
117
118   /** Suitable defaults for an Ethernet-like tun/tap device */
119   .mtu_bytes = 4096 + 256,
120 };
121
122 /**
123  * @brief tuntap_tx
124  * @node tuntap-tx
125  *
126  * Output node, writes the buffers comprising the incoming frame
127  * to the tun/tap device, aka hands them to the Linux kernel stack.
128  *
129  * @param *vm - vlib_main_t
130  * @param *node - vlib_node_runtime_t
131  * @param *frame - vlib_frame_t
132  *
133  * @return rc - uword
134  *
135  */
136 static uword
137 tuntap_tx (vlib_main_t * vm,
138            vlib_node_runtime_t * node,
139            vlib_frame_t * frame)
140 {
141   u32 * buffers = vlib_frame_args (frame);
142   uword n_packets = frame->n_vectors;
143   tuntap_main_t * tm = &tuntap_main;
144   vnet_main_t *vnm = vnet_get_main ();
145   vnet_interface_main_t *im = &vnm->interface_main;
146   u32 n_bytes = 0;
147   int i;
148
149   for (i = 0; i < n_packets; i++)
150     {
151       struct iovec * iov;
152       vlib_buffer_t * b;
153       uword l;
154
155       b = vlib_get_buffer (vm, buffers[i]);
156
157       if (tm->is_ether && (!tm->have_normal_interface))
158         {
159           vlib_buffer_reset(b);
160           clib_memcpy (vlib_buffer_get_current (b), tm->ether_dst_mac, 6);
161         }
162
163       /* Re-set iovecs if present. */
164       if (tm->iovecs)
165         _vec_len (tm->iovecs) = 0;
166
167       /** VLIB buffer chain -> Unix iovec(s). */
168       vec_add2 (tm->iovecs, iov, 1);
169       iov->iov_base = b->data + b->current_data;
170       iov->iov_len = l = b->current_length;
171
172       if (PREDICT_FALSE (b->flags & VLIB_BUFFER_NEXT_PRESENT))
173         {
174           do {
175             b = vlib_get_buffer (vm, b->next_buffer);
176
177             vec_add2 (tm->iovecs, iov, 1);
178
179             iov->iov_base = b->data + b->current_data;
180             iov->iov_len = b->current_length;
181             l += b->current_length;
182           } while (b->flags & VLIB_BUFFER_NEXT_PRESENT);
183         }
184
185       if (writev (tm->dev_net_tun_fd, tm->iovecs, vec_len (tm->iovecs)) < l)
186         clib_unix_warning ("writev");
187
188       n_bytes += l;
189     }
190
191   /* Update tuntap interface output stats. */
192   vlib_increment_combined_counter (im->combined_sw_if_counters
193                                    + VNET_INTERFACE_COUNTER_TX,
194                                    vm->cpu_index,
195                                    tm->sw_if_index, n_packets, n_bytes);
196
197
198   /** The normal interface path flattens the buffer chain */
199   if (tm->have_normal_interface)
200     vlib_buffer_free_no_next (vm, buffers, n_packets);
201   else
202     vlib_buffer_free (vm, buffers, n_packets);
203
204   return n_packets;
205 }
206
207 VLIB_REGISTER_NODE (tuntap_tx_node,static) = {
208   .function = tuntap_tx,
209   .name = "tuntap-tx",
210   .type = VLIB_NODE_TYPE_INTERNAL,
211   .vector_size = 4,
212 };
213
214 enum {
215   TUNTAP_RX_NEXT_IP4_INPUT,
216   TUNTAP_RX_NEXT_IP6_INPUT,
217   TUNTAP_RX_NEXT_ETHERNET_INPUT,
218   TUNTAP_RX_NEXT_DROP,
219   TUNTAP_RX_N_NEXT,
220 };
221
222 /**
223  * @brief TUNTAP receive node
224  * @node tuntap-rx
225  *
226  * @param *vm - vlib_main_t
227  * @param *node - vlib_node_runtime_t
228  * @param *frame - vlib_frame_t
229  *
230  * @return rc - uword
231  *
232  */
233 static uword
234 tuntap_rx (vlib_main_t * vm,
235            vlib_node_runtime_t * node,
236            vlib_frame_t * frame)
237 {
238   tuntap_main_t * tm = &tuntap_main;
239   vlib_buffer_t * b;
240   u32 bi;
241   const uword buffer_size = VLIB_BUFFER_DATA_SIZE;
242 #if DPDK == 0
243   u32 free_list_index = VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX;
244 #else
245   dpdk_main_t * dm = &dpdk_main;
246   u32 free_list_index = dm->vlib_buffer_free_list_index;
247   struct rte_mbuf *first_mb = NULL, *prev_mb = NULL;
248 #endif
249
250   /** Make sure we have some RX buffers. */
251   {
252     uword n_left = vec_len (tm->rx_buffers);
253     uword n_alloc;
254
255     if (n_left < VLIB_FRAME_SIZE / 2)
256       {
257         if (! tm->rx_buffers)
258           vec_alloc (tm->rx_buffers, VLIB_FRAME_SIZE);
259
260         n_alloc = vlib_buffer_alloc_from_free_list 
261             (vm, tm->rx_buffers + n_left, VLIB_FRAME_SIZE - n_left, 
262              free_list_index);
263         _vec_len (tm->rx_buffers) = n_left + n_alloc;
264       }
265   }
266
267   /** Allocate RX buffers from end of rx_buffers.
268      Turn them into iovecs to pass to readv. */
269   {
270     uword i_rx = vec_len (tm->rx_buffers) - 1;
271     vlib_buffer_t * b;
272     word i, n_bytes_left, n_bytes_in_packet;
273
274     /** We should have enough buffers left for an MTU sized packet. */
275     ASSERT (vec_len (tm->rx_buffers) >= tm->mtu_buffers);
276
277     vec_validate (tm->iovecs, tm->mtu_buffers - 1);
278     for (i = 0; i < tm->mtu_buffers; i++)
279       {
280         b = vlib_get_buffer (vm, tm->rx_buffers[i_rx - i]);
281         tm->iovecs[i].iov_base = b->data;
282         tm->iovecs[i].iov_len = buffer_size;
283       }
284
285     n_bytes_left = readv (tm->dev_net_tun_fd, tm->iovecs, tm->mtu_buffers);
286     n_bytes_in_packet = n_bytes_left;
287     if (n_bytes_left <= 0)
288       {
289         if (errno != EAGAIN)
290           clib_unix_warning ("readv %d", n_bytes_left);
291         return 0;
292       }
293
294     bi = tm->rx_buffers[i_rx];
295
296     while (1)
297       {
298 #if DPDK == 1
299         struct rte_mbuf * mb;
300 #endif
301         b = vlib_get_buffer (vm, tm->rx_buffers[i_rx]);
302 #if DPDK == 1
303         mb = rte_mbuf_from_vlib_buffer(b);
304
305         if (first_mb == NULL)
306             first_mb = mb;
307
308         if (prev_mb != NULL)
309           {
310             prev_mb->next = mb;
311             first_mb->nb_segs++;
312           }
313 #endif
314         b->flags = 0;
315         b->current_data = 0;
316         b->current_length = n_bytes_left < buffer_size ? n_bytes_left : buffer_size;
317
318         n_bytes_left -= buffer_size;
319 #if DPDK == 1
320         rte_pktmbuf_data_len (mb) = b->current_length;
321         mb->data_off = RTE_PKTMBUF_HEADROOM + b->current_data;
322 #endif
323
324         if (n_bytes_left <= 0)
325           {
326 #if DPDK == 1
327             rte_pktmbuf_pkt_len (first_mb) = n_bytes_in_packet;
328 #endif
329             break;
330           }
331
332         i_rx--;
333         b->flags |= VLIB_BUFFER_NEXT_PRESENT;
334         b->next_buffer = tm->rx_buffers[i_rx];
335 #if DPDK == 1
336         prev_mb = mb;
337 #endif
338       }
339
340     /** Interface counters for tuntap interface. */
341     vlib_increment_combined_counter
342         (vnet_main.interface_main.combined_sw_if_counters
343          + VNET_INTERFACE_COUNTER_RX,
344          os_get_cpu_number(),
345          tm->sw_if_index,
346          1, n_bytes_in_packet);
347
348     _vec_len (tm->rx_buffers) = i_rx;
349   }
350
351   b = vlib_get_buffer (vm, bi);
352
353   {
354     u32 next_index;
355     uword n_trace = vlib_get_trace_count (vm, node);
356
357     vnet_buffer (b)->sw_if_index[VLIB_RX] = tm->sw_if_index;
358     vnet_buffer (b)->sw_if_index[VLIB_TX] = (u32)~0;
359
360     /*
361      * Turn this on if you run into
362      * "bad monkey" contexts, and you want to know exactly
363      * which nodes they've visited...
364      */
365     if (VLIB_BUFFER_TRACE_TRAJECTORY)
366         b->pre_data[0] = 0;
367
368     b->error = node->errors[0];
369
370     if (tm->is_ether)
371       {
372         next_index = TUNTAP_RX_NEXT_ETHERNET_INPUT;
373       }
374     else
375       switch (b->data[0] & 0xf0)
376         {
377         case 0x40:
378           next_index = TUNTAP_RX_NEXT_IP4_INPUT;
379           break;
380         case 0x60:
381           next_index = TUNTAP_RX_NEXT_IP6_INPUT;
382           break;
383         default:
384           next_index = TUNTAP_RX_NEXT_DROP;
385           break;
386         }
387
388     /* The linux kernel couldn't care less if our interface is up */
389     if (tm->have_normal_interface)
390       {
391         vnet_main_t *vnm = vnet_get_main();
392         vnet_sw_interface_t * si;
393         si = vnet_get_sw_interface (vnm, tm->sw_if_index);
394         if (!(si->flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP))
395           next_index = TUNTAP_RX_NEXT_DROP;
396       }
397
398     vlib_set_next_frame_buffer (vm, node, next_index, bi);
399
400     if (n_trace > 0)
401       {
402         vlib_trace_buffer (vm, node, next_index,
403                            b, /* follow_chain */ 1);
404         vlib_set_trace_count (vm, node, n_trace - 1);
405       }
406   }
407
408   return 1;
409 }
410
411 /**
412  * @brief TUNTAP_RX error strings
413  */
414 static char * tuntap_rx_error_strings[] = {
415   "unknown packet type",
416 };
417
418 VLIB_REGISTER_NODE (tuntap_rx_node,static) = {
419   .function = tuntap_rx,
420   .name = "tuntap-rx",
421   .type = VLIB_NODE_TYPE_INPUT,
422   .state = VLIB_NODE_STATE_INTERRUPT,
423   .vector_size = 4,
424   .n_errors = 1,
425   .error_strings = tuntap_rx_error_strings,
426
427   .n_next_nodes = TUNTAP_RX_N_NEXT,
428   .next_nodes = {
429     [TUNTAP_RX_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
430     [TUNTAP_RX_NEXT_IP6_INPUT] = "ip6-input",
431     [TUNTAP_RX_NEXT_DROP] = "error-drop",
432     [TUNTAP_RX_NEXT_ETHERNET_INPUT] = "ethernet-input",
433   },
434 };
435
436 /**
437  * @brief Gets called when file descriptor is ready from epoll.
438  *
439  * @param *uf - unix_file_t
440  *
441  * @return error - clib_error_t
442  */
443 static clib_error_t * tuntap_read_ready (unix_file_t * uf)
444 {
445   vlib_main_t * vm = vlib_get_main();
446   vlib_node_set_interrupt_pending (vm, tuntap_rx_node.index);
447   return 0;
448 }
449
450 /**
451  * @brief Clean up the tun/tap device
452  *
453  * @param *vm - vlib_main_t
454  *
455  * @return error - clib_error_t
456  *
457  */
458 static clib_error_t *
459 tuntap_exit (vlib_main_t * vm)
460 {
461   tuntap_main_t *tm = &tuntap_main;
462   struct ifreq ifr;
463   int sfd;
464
465   /* Not present. */
466   if (! tm->dev_net_tun_fd || tm->dev_net_tun_fd < 0)
467     return 0;
468
469   sfd = socket (AF_INET, SOCK_STREAM, 0);
470   if (sfd < 0)
471     clib_unix_warning("provisioning socket");
472
473   memset(&ifr, 0, sizeof (ifr));
474   strncpy (ifr.ifr_name, tm->tun_name, sizeof (ifr.ifr_name)-1);
475
476   /* get flags, modify to bring down interface... */
477   if (ioctl (sfd, SIOCGIFFLAGS, &ifr) < 0)
478     clib_unix_warning ("SIOCGIFFLAGS");
479
480   ifr.ifr_flags &= ~(IFF_UP | IFF_RUNNING);
481
482   if (ioctl (sfd, SIOCSIFFLAGS, &ifr) < 0)
483     clib_unix_warning ("SIOCSIFFLAGS");
484
485   /* Turn off persistence */
486   if (ioctl (tm->dev_net_tun_fd, TUNSETPERSIST, 0) < 0)
487     clib_unix_warning ("TUNSETPERSIST");
488   close(tm->dev_tap_fd);
489   if (tm->dev_net_tun_fd >= 0)
490     close(tm->dev_net_tun_fd);
491   if (sfd >= 0)
492     close (sfd);
493
494   return 0;
495 }
496
497 VLIB_MAIN_LOOP_EXIT_FUNCTION (tuntap_exit);
498
499 /**
500  * @brief CLI function for tun/tap config
501  *
502  * @param *vm - vlib_main_t
503  * @param *input - unformat_input_t
504  *
505  * @return error - clib_error_t
506  *
507  */
508 static clib_error_t *
509 tuntap_config (vlib_main_t * vm, unformat_input_t * input)
510 {
511   tuntap_main_t *tm = &tuntap_main;
512   clib_error_t * error = 0;
513   struct ifreq ifr;
514   u8 * name;
515   int flags = IFF_TUN | IFF_NO_PI;
516   int is_enabled = 0, is_ether = 0, have_normal_interface = 0;
517   const uword buffer_size = VLIB_BUFFER_DATA_SIZE;
518
519   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
520     {
521       if (unformat (input, "mtu %d", &tm->mtu_bytes))
522         ;
523       else if (unformat (input, "enable"))
524         is_enabled = 1;
525       else if (unformat (input, "disable"))
526         is_enabled = 0;
527       else if (unformat (input, "ethernet") ||
528                unformat (input, "ether"))
529         is_ether = 1;
530       else if (unformat (input, "have-normal-interface") ||
531                unformat (input, "have-normal"))
532         have_normal_interface = 1;
533       else if (unformat (input, "name %s", &name))
534         tm->tun_name = (char *) name;
535       else
536         return clib_error_return (0, "unknown input `%U'",
537                                   format_unformat_error, input);
538     }
539
540   tm->dev_net_tun_fd = -1;
541   tm->dev_tap_fd = -1;
542
543   if (is_enabled == 0)
544     return 0;
545
546   if (geteuid()) 
547     {
548       clib_warning ("tuntap disabled: must be superuser");
549       return 0;
550     }    
551
552   tm->is_ether = is_ether;
553   tm->have_normal_interface = have_normal_interface;
554
555   if (is_ether)
556     flags = IFF_TAP | IFF_NO_PI;
557
558   if ((tm->dev_net_tun_fd = open ("/dev/net/tun", O_RDWR)) < 0)
559     {
560       error = clib_error_return_unix (0, "open /dev/net/tun");
561       goto done;
562     }
563
564   memset (&ifr, 0, sizeof (ifr));
565   strncpy(ifr.ifr_name, tm->tun_name, sizeof(ifr.ifr_name)-1);
566   ifr.ifr_flags = flags;
567   if (ioctl (tm->dev_net_tun_fd, TUNSETIFF, (void *)&ifr) < 0)
568     {
569       error = clib_error_return_unix (0, "ioctl TUNSETIFF");
570       goto done;
571     }
572     
573   /* Make it persistent, at least until we split. */
574   if (ioctl (tm->dev_net_tun_fd, TUNSETPERSIST, 1) < 0)
575     {
576       error = clib_error_return_unix (0, "TUNSETPERSIST");
577       goto done;
578     }
579
580   /* Open a provisioning socket */
581   if ((tm->dev_tap_fd = socket(PF_PACKET, SOCK_RAW,
582                                htons(ETH_P_ALL))) < 0 )
583     {
584       error = clib_error_return_unix (0, "socket");
585       goto done;
586     }
587
588   /* Find the interface index. */
589   {
590     struct ifreq ifr;
591     struct sockaddr_ll sll;
592
593     memset (&ifr, 0, sizeof(ifr));
594     strncpy (ifr.ifr_name, tm->tun_name, sizeof(ifr.ifr_name)-1);
595     if (ioctl (tm->dev_tap_fd, SIOCGIFINDEX, &ifr) < 0 )
596       {
597         error = clib_error_return_unix (0, "ioctl SIOCGIFINDEX");
598         goto done;
599       }
600
601     /* Bind the provisioning socket to the interface. */
602     memset(&sll, 0, sizeof(sll));
603     sll.sll_family   = AF_PACKET;
604     sll.sll_ifindex  = ifr.ifr_ifindex;
605     sll.sll_protocol = htons(ETH_P_ALL);
606
607     if (bind(tm->dev_tap_fd, (struct sockaddr*) &sll, sizeof(sll)) < 0)
608       {
609         error = clib_error_return_unix (0, "bind");
610         goto done;
611       }
612   }
613
614   /* non-blocking I/O on /dev/tapX */
615   {
616     int one = 1;
617     if (ioctl (tm->dev_net_tun_fd, FIONBIO, &one) < 0)
618       {
619         error = clib_error_return_unix (0, "ioctl FIONBIO");
620         goto done;
621       }
622   }
623
624   tm->mtu_buffers = (tm->mtu_bytes + (buffer_size - 1)) / buffer_size;
625
626   ifr.ifr_mtu = tm->mtu_bytes;
627   if (ioctl (tm->dev_tap_fd, SIOCSIFMTU, &ifr) < 0)
628     {
629       error = clib_error_return_unix (0, "ioctl SIOCSIFMTU");
630       goto done;
631     }
632
633   /* get flags, modify to bring up interface... */
634   if (ioctl (tm->dev_tap_fd, SIOCGIFFLAGS, &ifr) < 0)
635     {
636       error = clib_error_return_unix (0, "ioctl SIOCGIFFLAGS");
637       goto done;
638     }
639
640   ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
641
642   if (ioctl (tm->dev_tap_fd, SIOCSIFFLAGS, &ifr) < 0)
643     {
644       error = clib_error_return_unix (0, "ioctl SIOCSIFFLAGS");
645       goto done;
646     }
647
648   if (is_ether)
649     {
650       if (ioctl (tm->dev_tap_fd, SIOCGIFHWADDR, &ifr) < 0)
651         {
652           error = clib_error_return_unix (0, "ioctl SIOCGIFHWADDR");
653           goto done;
654         }
655       else
656         clib_memcpy (tm->ether_dst_mac, ifr.ifr_hwaddr.sa_data, 6);
657     }
658
659   if (have_normal_interface)
660     {
661       vnet_main_t *vnm = vnet_get_main();
662       error = ethernet_register_interface
663         (vnm,
664          tuntap_dev_class.index,
665          0 /* device instance */,
666          tm->ether_dst_mac /* ethernet address */,
667          &tm->hw_if_index, 
668          0 /* flag change */);
669       if (error)
670         clib_error_report (error);
671       tm->sw_if_index = tm->hw_if_index;
672       vm->os_punt_frame = tuntap_nopunt_frame;
673     }
674   else
675     {
676       vnet_main_t *vnm = vnet_get_main();
677       vnet_hw_interface_t * hi;
678       
679       vm->os_punt_frame = tuntap_punt_frame;
680       
681       tm->hw_if_index = vnet_register_interface
682         (vnm,
683          tuntap_dev_class.index, 0 /* device instance */,
684          tuntap_interface_class.index, 0);
685       hi = vnet_get_hw_interface (vnm, tm->hw_if_index);
686       tm->sw_if_index = hi->sw_if_index;
687       
688       /* Interface is always up. */
689       vnet_hw_interface_set_flags (vnm, tm->hw_if_index, 
690                                    VNET_HW_INTERFACE_FLAG_LINK_UP);
691       vnet_sw_interface_set_flags (vnm, tm->sw_if_index, 
692                                    VNET_SW_INTERFACE_FLAG_ADMIN_UP);
693     }
694
695   {
696     unix_file_t template = {0};
697     template.read_function = tuntap_read_ready;
698     template.file_descriptor = tm->dev_net_tun_fd;
699     tm->unix_file_index = unix_file_add (&unix_main, &template);
700   }
701
702  done:
703   if (error)
704     {
705       if (tm->dev_net_tun_fd >= 0)
706         close (tm->dev_net_tun_fd);
707       if (tm->dev_tap_fd >= 0)
708         close (tm->dev_tap_fd);
709     }
710
711   return error;
712 }
713
714 VLIB_CONFIG_FUNCTION (tuntap_config, "tuntap");
715
716 /**
717  * @brief Add or Del IP4 address to tun/tap interface
718  *
719  * @param *im - ip4_main_t
720  * @param opaque - uword
721  * @param sw_if_index - u32
722  * @param *address - ip4_address_t
723  * @param is_delete - u32
724  *
725  */
726 void
727 tuntap_ip4_add_del_interface_address (ip4_main_t * im,
728                                       uword opaque,
729                                       u32 sw_if_index,
730                                       ip4_address_t * address,
731                                       u32 address_length,
732                                       u32 if_address_index,
733                                       u32 is_delete)
734 {
735   tuntap_main_t * tm = &tuntap_main;
736   struct ifreq ifr;
737   subif_address_t subif_addr, * ap;
738   uword * p;
739
740   /** Tuntap disabled, or using a "normal" interface. */
741   if (tm->have_normal_interface ||  tm->dev_tap_fd < 0)
742     return;
743
744   /** See if we already know about this subif */
745   memset (&subif_addr, 0, sizeof (subif_addr));
746   subif_addr.sw_if_index = sw_if_index;
747   clib_memcpy (&subif_addr.addr, address, sizeof (*address));
748
749   p = mhash_get (&tm->subif_mhash, &subif_addr);
750
751   if (p)
752     ap = pool_elt_at_index (tm->subifs, p[0]);
753   else
754     {
755       pool_get (tm->subifs, ap);
756       *ap = subif_addr;
757       mhash_set (&tm->subif_mhash, ap, ap - tm->subifs, 0);
758     }
759
760   /* Use subif pool index to select alias device. */
761   memset (&ifr, 0, sizeof (ifr));
762   snprintf (ifr.ifr_name, sizeof(ifr.ifr_name), 
763             "%s:%d", tm->tun_name, (int)(ap - tm->subifs));
764
765   if (! is_delete)
766     {
767       struct sockaddr_in * sin;
768
769       sin = (struct sockaddr_in *)&ifr.ifr_addr;
770
771       /* Set ipv4 address, netmask. */
772       sin->sin_family = AF_INET;
773       clib_memcpy (&sin->sin_addr.s_addr, address, 4);
774       if (ioctl (tm->dev_tap_fd, SIOCSIFADDR, &ifr) < 0)
775         clib_unix_warning ("ioctl SIOCSIFADDR");
776     
777       sin->sin_addr.s_addr = im->fib_masks[address_length];
778       if (ioctl (tm->dev_tap_fd, SIOCSIFNETMASK, &ifr) < 0)
779         clib_unix_warning ("ioctl SIOCSIFNETMASK");
780     }
781   else
782     {
783       mhash_unset (&tm->subif_mhash, &subif_addr, 0 /* old value ptr */);
784       pool_put (tm->subifs, ap);
785     }
786
787   /* get flags, modify to bring up interface... */
788   if (ioctl (tm->dev_tap_fd, SIOCGIFFLAGS, &ifr) < 0)
789     clib_unix_warning ("ioctl SIOCGIFFLAGS");
790
791   if (is_delete)
792     ifr.ifr_flags &= ~(IFF_UP | IFF_RUNNING);
793   else
794     ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
795
796   if (ioctl (tm->dev_tap_fd, SIOCSIFFLAGS, &ifr) < 0)
797     clib_unix_warning ("ioctl SIOCSIFFLAGS");
798 }
799
800 /**
801  * @brief workaround for a known include file bug.
802  * including @c <linux/ipv6.h> causes multiple definitions if
803  * @c <netinet/in.h is also included.
804  */
805 struct in6_ifreq {
806         struct in6_addr ifr6_addr;
807         u32             ifr6_prefixlen;
808         int             ifr6_ifindex;
809 };
810
811 /**
812  * @brief Add or Del tun/tap interface address.
813  *
814  * Both the v6 interface address API and the way ifconfig
815  * displays subinterfaces differ from their v4 couterparts.
816  * The code given here seems to work but YMMV.
817  *
818  * @param *im - ip6_main_t
819  * @param opaque - uword
820  * @param sw_if_index - u32
821  * @param *address - ip6_address_t
822  * @param address_length - u32
823  * @param if_address_index - u32
824  * @param is_delete - u32
825  */
826 void
827 tuntap_ip6_add_del_interface_address (ip6_main_t * im,
828                                       uword opaque,
829                                       u32 sw_if_index,
830                                       ip6_address_t * address,
831                                       u32 address_length,
832                                       u32 if_address_index,
833                                       u32 is_delete)
834 {
835   tuntap_main_t * tm = &tuntap_main;
836   struct ifreq ifr;
837   struct in6_ifreq ifr6;
838   subif_address_t subif_addr, * ap;
839   uword * p;
840
841   /* Tuntap disabled, or using a "normal" interface. */
842   if (tm->have_normal_interface ||  tm->dev_tap_fd < 0)
843     return;
844
845   /* See if we already know about this subif */
846   memset (&subif_addr, 0, sizeof (subif_addr));
847   subif_addr.sw_if_index = sw_if_index;
848   subif_addr.is_v6 = 1;
849   clib_memcpy (&subif_addr.addr, address, sizeof (*address));
850
851   p = mhash_get (&tm->subif_mhash, &subif_addr);
852
853   if (p)
854     ap = pool_elt_at_index (tm->subifs, p[0]);
855   else
856     {
857       pool_get (tm->subifs, ap);
858       *ap = subif_addr;
859       mhash_set (&tm->subif_mhash, ap, ap - tm->subifs, 0);
860     }
861
862   /* Use subif pool index to select alias device. */
863   memset (&ifr, 0, sizeof (ifr));
864   memset (&ifr6, 0, sizeof (ifr6));
865   snprintf (ifr.ifr_name, sizeof(ifr.ifr_name), 
866             "%s:%d", tm->tun_name, (int)(ap - tm->subifs));
867
868   if (! is_delete)
869     {
870       int sockfd = socket (AF_INET6, SOCK_STREAM, 0);
871       if (sockfd < 0)
872         clib_unix_warning ("get ifindex socket");
873
874       if (ioctl (sockfd, SIOGIFINDEX, &ifr) < 0)
875         clib_unix_warning ("get ifindex");
876
877       ifr6.ifr6_ifindex = ifr.ifr_ifindex;
878       ifr6.ifr6_prefixlen = address_length;
879       clib_memcpy (&ifr6.ifr6_addr, address, 16);
880
881       if (ioctl (sockfd, SIOCSIFADDR, &ifr6) < 0)
882         clib_unix_warning ("set address");
883
884       if (sockfd >= 0)
885         close (sockfd);
886     }
887   else
888     {
889       int sockfd = socket (AF_INET6, SOCK_STREAM, 0);
890       if (sockfd < 0)
891         clib_unix_warning ("get ifindex socket");
892
893       if (ioctl (sockfd, SIOGIFINDEX, &ifr) < 0)
894         clib_unix_warning ("get ifindex");
895
896       ifr6.ifr6_ifindex = ifr.ifr_ifindex;
897       ifr6.ifr6_prefixlen = address_length;
898       clib_memcpy (&ifr6.ifr6_addr, address, 16);
899
900       if (ioctl (sockfd, SIOCDIFADDR, &ifr6) < 0)
901         clib_unix_warning ("del address");
902
903       if (sockfd >= 0)
904         close (sockfd);
905
906       mhash_unset (&tm->subif_mhash, &subif_addr, 0 /* old value ptr */);
907       pool_put (tm->subifs, ap);
908     }
909 }
910
911 /**
912  * @brief TX the tun/tap frame
913  *
914  * @param *vm - vlib_main_t
915  * @param *node - vlib_node_runtime_t
916  * @param *frame - vlib_frame_t
917  *
918  */
919 static void
920 tuntap_punt_frame (vlib_main_t * vm,
921                    vlib_node_runtime_t * node,
922                    vlib_frame_t * frame)
923 {
924   tuntap_tx (vm, node, frame);
925   vlib_frame_free (vm, node, frame);
926 }
927
928 /**
929  * @brief Free the tun/tap frame
930  *
931  * @param *vm - vlib_main_t
932  * @param *node - vlib_node_runtime_t
933  * @param *frame - vlib_frame_t
934  *
935  */
936 static void
937 tuntap_nopunt_frame (vlib_main_t * vm,
938                    vlib_node_runtime_t * node,
939                    vlib_frame_t * frame)
940 {
941   u32 * buffers = vlib_frame_args (frame);
942   uword n_packets = frame->n_vectors;
943   vlib_buffer_free (vm, buffers, n_packets);
944   vlib_frame_free (vm, node, frame);
945 }
946
947 VNET_HW_INTERFACE_CLASS (tuntap_interface_class,static) = {
948   .name = "tuntap",
949 };
950
951 /**
952  * @brief Format tun/tap interface name
953  *
954  * @param *s - u8 - formatter string
955  * @param *args - va_list
956  *
957  * @return *s - u8 - formatted string
958  *
959  */
960 static u8 * format_tuntap_interface_name (u8 * s, va_list * args)
961 {
962   u32 i = va_arg (*args, u32);
963
964   s = format (s, "tuntap-%d", i);
965   return s;
966 }
967
968 /**
969  * @brief TX packet out tun/tap
970  *
971  * @param *vm - vlib_main_t
972  * @param *node - vlib_node_runtime_t
973  * @param *frame - vlib_frame_t
974  *
975  * @return n_buffers - uword - Packets transmitted
976  *
977  */
978 static uword
979 tuntap_intfc_tx (vlib_main_t * vm,
980                  vlib_node_runtime_t * node,
981                  vlib_frame_t * frame)
982 {
983   tuntap_main_t * tm = &tuntap_main;
984   u32 * buffers = vlib_frame_args (frame);
985   uword n_buffers = frame->n_vectors;
986
987   /* Normal interface transmit happens only on the normal interface... */
988   if (tm->have_normal_interface)
989     return tuntap_tx (vm, node, frame);
990
991   vlib_buffer_free (vm, buffers, n_buffers);
992   return n_buffers;
993 }
994
995 VNET_DEVICE_CLASS (tuntap_dev_class,static) = {
996   .name = "tuntap",
997   .tx_function = tuntap_intfc_tx,
998   .format_device_name = format_tuntap_interface_name,
999 };
1000
1001 /**
1002  * @brief tun/tap node init
1003  *
1004  * @param *vm - vlib_main_t
1005  *
1006  * @return error - clib_error_t
1007  *
1008  */
1009 static clib_error_t *
1010 tuntap_init (vlib_main_t * vm)
1011 {
1012   clib_error_t * error;
1013   ip4_main_t * im4 = &ip4_main;
1014   ip6_main_t * im6 = &ip6_main;
1015   ip4_add_del_interface_address_callback_t cb4;
1016   ip6_add_del_interface_address_callback_t cb6;
1017   tuntap_main_t * tm = &tuntap_main;
1018
1019   error = vlib_call_init_function (vm, ip4_init);
1020   if (error)
1021     return error;
1022
1023   mhash_init (&tm->subif_mhash, sizeof (u32), sizeof(subif_address_t));
1024
1025   cb4.function = tuntap_ip4_add_del_interface_address;
1026   cb4.function_opaque = 0;
1027   vec_add1 (im4->add_del_interface_address_callbacks, cb4);
1028
1029   cb6.function = tuntap_ip6_add_del_interface_address;
1030   cb6.function_opaque = 0;
1031   vec_add1 (im6->add_del_interface_address_callbacks, cb6);
1032
1033   return 0;
1034 }
1035
1036 VLIB_INIT_FUNCTION (tuntap_init);