summaryrefslogtreecommitdiffstats
path: root/src/vppinfra/timing_wheel.h
blob: e668eb031a223b168b79fecd0f24bb6e3f7f864d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/*
 * Copyright (c) 2015 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef included_clib_timing_wheel_h
#define included_clib_timing_wheel_h

#include <vppinfra/format.h>

typedef struct
{
  /* Time of this element in units cpu clock ticks relative to time
     base. 32 bits should be large enough for several kilo-seconds
     to elapse before we have to re-set time base. */
  u32 cpu_time_relative_to_base;

  /* User data to store in this bin. */
  u32 user_data;
} timing_wheel_elt_t;

/* Overflow wheel elements where time does not fit into 32 bits. */
typedef struct
{
  /* Absolute time of this element. */
  u64 cpu_time;

  /* User data to store in this bin. */
  u32 user_data;

  u32 pad;
} timing_wheel_overflow_elt_t;

typedef struct
{
  /* 2^M bits: 1 means vector is non-zero else zero. */
  uword *occupancy_bitmap;

  /* 2^M element table of element vectors, one for each time bin. */
  timing_wheel_elt_t **elts;
} timing_wheel_level_t;

typedef struct
{
  /* Vector of refill counts per level. */
  u64 *refills;

  /* Number of times cpu time base was rescaled. */
  u64 cpu_time_base_advances;
} timing_wheel_stats_t;

typedef struct
{
  /* Each bin is a power of two clock ticks (N)
     chosen so that 2^N >= min_sched_time. */
  u8 log2_clocks_per_bin;

  /* Wheels are 2^M bins where 2^(N+M) >= max_sched_time. */
  u8 log2_bins_per_wheel;

  /* N + M. */
  u8 log2_clocks_per_wheel;

  /* Number of bits to use in cpu_time_relative_to_base field
     of timing_wheel_elt_t. */
  u8 n_wheel_elt_time_bits;

  /* 2^M. */
  u32 bins_per_wheel;

  /* 2^M - 1. */
  u32 bins_per_wheel_mask;

  timing_wheel_level_t *levels;

  timing_wheel_overflow_elt_t *overflow_pool;

  /* Free list of element vector so we can recycle old allocated vectors. */
  timing_wheel_elt_t **free_elt_vectors;

  timing_wheel_elt_t *unexpired_elts_pending_insert;

  /* Hash table of user data values which have been deleted but not yet re-inserted. */
  uword *deleted_user_data_hash;

  /* Enable validation for debugging. */
  u32 validate;

  /* Time index.  Measures time in units of 2^N clock ticks from
     when wheel starts. */
  u64 current_time_index;

  /* All times are 32 bit numbers relative to cpu_time_base.
     So, roughly every 2^(32 + N) clocks we'll need to subtract from
     all timing_wheel_elt_t times to make sure they never overflow. */
  u64 cpu_time_base;

  /* When current_time_index is >= this we update cpu_time_base
     to avoid overflowing 32 bit cpu_time_relative_to_base
     in timing_wheel_elt_t. */
  u64 time_index_next_cpu_time_base_update;

  /* Cached earliest element on wheel; 0 if not valid. */
  u64 cached_min_cpu_time_on_wheel;

  f64 min_sched_time, max_sched_time, cpu_clocks_per_second;

  timing_wheel_stats_t stats;
} timing_wheel_t;

/* Initialization function. */
void timing_wheel_init (timing_wheel_t * w,
			u64 current_cpu_time, f64 cpu_clocks_per_second);

/* Insert user data on wheel at given CPU time stamp. */
void timing_wheel_insert (timing_wheel_t * w, u64 insert_cpu_time,
			  u32 user_data);

/* Delete user data from wheel (until it is again inserted). */
void timing_wheel_delete (timing_wheel_t * w, u32 user_data);

/* Advance wheel and return any expired user data in vector.  If non-zero
   min_next_expiring_element_cpu_time will return a cpu time stamp
   before which there are guaranteed to be no elements in the current wheel. */
u32 *timing_wheel_advance (timing_wheel_t * w, u64 advance_cpu_time,
			   u32 * expired_user_data,
			   u64 * min_next_expiring_element_cpu_time);

/* Returns absolute time in clock cycles of next expiring element. */
u64 timing_wheel_next_expiring_elt_time (timing_wheel_t * w);

/* Format a timing wheel. */
format_function_t format_timing_wheel;

/* Testing function to validate wheel. */
void timing_wheel_validate (timing_wheel_t * w);

#endif /* included_clib_timing_wheel_h */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ }
#!/usr/bin/env python
# Copyright (c) 2016 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Traffic script that sends DHCPv6 proxy packets."""

from scapy.layers.dhcp6 import *
from scapy.layers.inet6 import IPv6, UDP, UDP_SERVICES

from resources.libraries.python.PacketVerifier import RxQueue, TxQueue
from resources.libraries.python.TrafficScriptArg import TrafficScriptArg


def _check_udp_checksum(pkt):
    """Check udp checksum in ip packet.
    Return true if checksum is correct."""
    new = pkt.__class__(str(pkt))
    del new['UDP'].chksum
    new = new.__class__(str(new))
    return new['UDP'].chksum == pkt['UDP'].chksum


def _get_dhcpv6_msgtype(msg_index):
    """Return DHCPv6 message type string.

    :param msg_index: Index of message type.
    :return: Message type.
    :type msg_index: int
    :rtype msg_str: str
    """
    dhcp6_messages = {
        1: "SOLICIT",
        2: "ADVERTISE",
        3: "REQUEST",
        4: "CONFIRM",
        5: "RENEW",
        6: "REBIND",
        7: "REPLY",
        8: "RELEASE",
        9: "DECLINE",
        10: "RECONFIGURE",
        11: "INFORMATION-REQUEST",
        12: "RELAY-FORW",
        13: "RELAY-REPL"
    }
    return dhcp6_messages[msg_index]


def dhcpv6_solicit(tx_if, rx_if, dhcp_multicast_ip, link_local_ip, proxy_ip,
                   server_ip, server_mac, client_duid, client_mac):
    """Send and check DHCPv6 SOLICIT proxy packet.

    :param tx_if: Client interface.
    :param rx_if: DHCPv6 server interface.
    :param dhcp_multicast_ip: Servers and relay agents multicast address.
    :param link_local_ip: Client link-local address.
    :param proxy_ip: IP address of DHCPv6 proxy server.
    :param server_ip: IP address of DHCPv6 server.
    :param server_mac: MAC address of DHCPv6 server.
    :param client_duid: Client DHCP Unique Identifier.
    :param client_mac: Client MAC address.
    :type tx_if: str
    :type rx_if: str
    :type dhcp_multicast_ip: str
    :type link_local_ip: str
    :type proxy_ip: str
    :type server_ip: str
    :type server_mac: str
    :type client_duid: str
    :type client_mac: str
    :return interface_id: ID of proxy interface.
    :rtype interface_id: str
    """

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    sent_packets = []

    dhcp6_solicit_pkt = Ether(src=client_mac, dst="33:33:00:01:00:02") / \
                        IPv6(src=link_local_ip, dst=dhcp_multicast_ip) / \
                        UDP(sport=UDP_SERVICES.dhcpv6_client,
                            dport=UDP_SERVICES.dhcpv6_server) / \
                        DHCP6_Solicit() / \
                        DHCP6OptClientId(duid=client_duid)

    sent_packets.append(dhcp6_solicit_pkt)
    txq.send(dhcp6_solicit_pkt)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError('DHCPv6 SOLICIT timeout')

    if ether.dst != server_mac:
        raise RuntimeError("Destination MAC address error: {} != {}".format(
            ether.dst, server_mac))
    print "Destination MAC address: OK."

    if ether['IPv6'].src != proxy_ip:
        raise RuntimeError("Source IP address error: {} != {}".format(
            ether['IPv6'].src, proxy_ip))
    print "Source IP address: OK."

    if ether['IPv6'].dst != server_ip:
        raise RuntimeError("Destination IP address error: {} != {}".format(
            ether['IPv6'].dst, server_ip))
    print "Destination IP address: OK."

    msgtype = _get_dhcpv6_msgtype(ether['IPv6']['UDP']
        ['DHCPv6 Relay Forward Message (Relay Agent/Server Message)'].msgtype)
    if msgtype != 'RELAY-FORW':
        raise RuntimeError("Message type error: {} != RELAY-FORW".format(
            msgtype))
    print "Message type: OK."

    linkaddr = ether['IPv6']['UDP']\
        ['DHCPv6 Relay Forward Message (Relay Agent/Server Message)'].linkaddr
    if linkaddr != proxy_ip:
        raise RuntimeError("Proxy IP address error: {} != {}".format(
           linkaddr, proxy_ip))
    print "Proxy IP address: OK."

    try:
        interface_id =  ether['IPv6']['UDP']\
            ['DHCPv6 Relay Forward Message (Relay Agent/Server Message)']\
            ['Unknown DHCPv6 OPtion']['DHCP6 Interface-Id Option'].ifaceid
    except Exception:
        raise RuntimeError("DHCP6 Interface-Id error!")

    return interface_id


def dhcpv6_advertise(rx_if, tx_if, link_local_ip, proxy_ip,
                     server_ip, server_mac, proxy_to_server_mac, interface_id):
    """Send and check DHCPv6 ADVERTISE proxy packet.

    :param rx_if: DHCPv6 server interface.
    :param tx_if: Client interface.
    :param link_local_ip: Client link-local address.
    :param proxy_ip: IP address of DHCPv6 proxy server.
    :param server_ip: IP address of DHCPv6 server.
    :param server_mac: MAC address of DHCPv6 server.
    :param proxy_to_server_mac: MAC address of DHCPv6 proxy interface.
    :param interface_id: ID of proxy interface.
    :type rx_if: str
    :type tx_if: str
    :type link_local_ip: str
    :type proxy_ip: str
    :type server_ip: str
    :type server_mac: str
    :type proxy_to_server_mac: str
    :type interface_id: str
    """

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    sent_packets = []

    dhcp6_advertise_pkt = Ether(src=server_mac, dst=proxy_to_server_mac) / \
                          IPv6(src=server_ip, dst=proxy_ip) / \
                          UDP(sport=UDP_SERVICES.dhcpv6_server,
                              dport=UDP_SERVICES.dhcpv6_client) / \
                          DHCP6_RelayReply(peeraddr=link_local_ip,
                                           linkaddr=proxy_ip) / \
                          DHCP6OptIfaceId(ifaceid=interface_id) / \
                          DHCP6OptRelayMsg() / \
                          DHCP6_Advertise()

    sent_packets.append(dhcp6_advertise_pkt)
    txq.send(dhcp6_advertise_pkt)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError('DHCPv6 ADVERTISE timeout')

    if ether['IPv6'].src != proxy_ip:
        raise RuntimeError("Source IP address error: {} != {}".format(
            ether['IPv6'].src, proxy_ip))
    print "Source IP address: OK."

    if not _check_udp_checksum(ether['IPv6']):
        raise RuntimeError("Checksum error!")
    print "Checksum: OK."

    msgtype = _get_dhcpv6_msgtype(ether['IPv6']['UDP']
                                  ['DHCPv6 Advertise Message'].msgtype)
    if msgtype != 'ADVERTISE':
        raise RuntimeError("Message type error: {} != ADVERTISE".format(
            msgtype))
    print "Message type: OK."


def dhcpv6_request(tx_if, rx_if, dhcp_multicast_ip, link_local_ip, proxy_ip,
                   server_ip, client_duid, client_mac):
    """Send and check DHCPv6 REQUEST proxy packet.

    :param tx_if: Client interface.
    :param rx_if: DHCPv6 server interface.
    :param dhcp_multicast_ip: Servers and relay agents multicast address.
    :param link_local_ip: Client link-local address.
    :param proxy_ip: IP address of DHCPv6 proxy server.
    :param server_ip: IP address of DHCPv6 server.
    :param client_duid: Client DHCP Unique Identifier.
    :param client_mac: Client MAC address.
    :type tx_if: str
    :type rx_if: str
    :type dhcp_multicast_ip: str
    :type link_local_ip: str
    :type proxy_ip: str
    :type server_ip: str
    :type client_duid: str
    :type client_mac: str
    """

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    sent_packets = []

    dhcp6_request_pkt = Ether(src=client_mac, dst="33:33:00:01:00:02") / \
                        IPv6(src=link_local_ip, dst=dhcp_multicast_ip) / \
                        UDP(sport=UDP_SERVICES.dhcpv6_client,
                            dport=UDP_SERVICES.dhcpv6_server) / \
                        DHCP6_Request() / \
                        DHCP6OptClientId(duid=client_duid)

    sent_packets.append(dhcp6_request_pkt)
    txq.send(dhcp6_request_pkt)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError('DHCPv6 REQUEST timeout')

    if ether['IPv6'].src != proxy_ip:
        raise RuntimeError("Source IP address error: {} != {}".format(
            ether['IPv6'].src, proxy_ip))
    print "Source IP address: OK."

    if ether['IPv6'].dst != server_ip:
        raise RuntimeError("Destination IP address error: {} != {}".format(
            ether['IPv6'].dst, server_ip))
    print "Destination IP address: OK."

    msgtype = _get_dhcpv6_msgtype(ether['IPv6']['UDP']
        ['DHCPv6 Relay Forward Message (Relay Agent/Server Message)'].msgtype)
    if msgtype != 'RELAY-FORW':
        raise RuntimeError("Message type error: {} != RELAY-FORW".format(
            msgtype))
    print "Message type: OK."

    linkaddr = ether['IPv6']['UDP']\
        ['DHCPv6 Relay Forward Message (Relay Agent/Server Message)'].linkaddr
    if linkaddr != proxy_ip:
        raise RuntimeError("Proxy IP address error: {} != {}".format(
           linkaddr, proxy_ip))
    print "Proxy IP address: OK."


def dhcpv6_reply(rx_if, tx_if, link_local_ip, proxy_ip, server_ip, server_mac,
                 interface_id):
    """Send and check DHCPv6 REPLY proxy packet.

    :param rx_if: DHCPv6 server interface.
    :param tx_if: Client interface.
    :param link_local_ip: Client link-local address.
    :param proxy_ip: IP address of DHCPv6 proxy server.
    :param server_ip: IP address of DHCPv6 server.
    :param server_mac: MAC address of DHCPv6 server.
    :param interface_id: ID of proxy interface.
    :type rx_if: str
    :type tx_if: str
    :type link_local_ip: str
    :type proxy_ip: str
    :type server_ip: str
    :type server_mac: str
    :type interface_id: str
    """

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    sent_packets = []

    dhcp_reply_pkt = Ether(src=server_mac) / \
                    IPv6(src=server_ip, dst=proxy_ip) / \
                    UDP(sport=UDP_SERVICES.dhcpv6_server,
                        dport=UDP_SERVICES.dhcpv6_client) / \
                    DHCP6_RelayReply(peeraddr=link_local_ip,
                                     linkaddr=proxy_ip) / \
                    DHCP6OptIfaceId(ifaceid=interface_id) / \
                    DHCP6OptRelayMsg() / \
                    DHCP6_Reply()

    sent_packets.append(dhcp_reply_pkt)
    txq.send(dhcp_reply_pkt)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError('DHCPv6 REPLY timeout')

    if ether['IPv6'].src != proxy_ip:
        raise RuntimeError("Source IP address error: {} != {}".format(
            ether['IPv6'].src, proxy_ip))
    print "Source IP address: OK."

    if not _check_udp_checksum(ether['IPv6']):
        raise RuntimeError("Checksum error!")
    print "Checksum: OK."

    msgtype = _get_dhcpv6_msgtype(ether['IPv6']['UDP']
                                  ['DHCPv6 Reply Message'].msgtype)
    if msgtype != 'REPLY':
        raise RuntimeError("Message type error: {} != REPLY".format(msgtype))
    print "Message type: OK."


def main():
    """Send DHCPv6 proxy messages."""

    args = TrafficScriptArg(['tx_src_ip', 'tx_dst_ip', 'proxy_ip', 'proxy_mac',
                             'server_ip', 'client_mac', 'server_mac',
                             'proxy_to_server_mac'])

    client_if = args.get_arg('tx_if')
    server_if = args.get_arg('rx_if')
    proxy_ip = args.get_arg('proxy_ip')
    proxy_mac = args.get_arg('proxy_mac')
    proxy_to_server_mac = args.get_arg('proxy_to_server_mac')
    server_ip = args.get_arg('server_ip')
    client_mac = args.get_arg('client_mac')
    server_mac = args.get_arg('server_mac')

    link_local_ip = "fe80::1"
    dhcp_multicast_ip = "ff02::1:2"
    client_duid = str(random.randint(0, 9999))

    # SOLICIT
    interface_id = dhcpv6_solicit(client_if, server_if, dhcp_multicast_ip,
                                  link_local_ip, proxy_ip, server_ip,
                                  server_mac, client_duid, client_mac)

    # ADVERTISE
    dhcpv6_advertise(client_if, server_if, link_local_ip, proxy_ip,
                     server_ip, server_mac, proxy_to_server_mac, interface_id)

    # REQUEST
    dhcpv6_request(client_if, server_if, dhcp_multicast_ip, link_local_ip,
                   proxy_ip, server_ip, client_duid, client_mac)

    # REPLY
    dhcpv6_reply(client_if, server_if, link_local_ip, proxy_ip, server_ip,
                 server_mac, interface_id)

    sys.exit(0)

if __name__ == "__main__":
    main()