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