aboutsummaryrefslogtreecommitdiffstats
path: root/bootstrap.sh
blob: cfb5a8f32016ada0b6c5134905c50e46b9e3043f (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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#!/bin/bash
# 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.

set -x

cat /etc/hostname
cat /etc/hosts

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export PYTHONPATH=${SCRIPT_DIR}

if [ -f "/etc/redhat-release" ]; then
    DISTRO="CENTOS"
    sudo yum install -y python-devel python-virtualenv
    VPP_ARTIFACTS="vpp vpp-selinux-policy vpp-devel vpp-lib vpp-plugins"
    DPDK_ARTIFACTS=""
    PACKAGE="rpm"
    VPP_CLASSIFIER=""
    DPDK_STABLE_VER=$(cat ${SCRIPT_DIR}/DPDK_STABLE_VER).x86_64
    VPP_REPO_URL=$(cat ${SCRIPT_DIR}/VPP_REPO_URL_CENTOS)
    VPP_STABLE_VER=$(cat ${SCRIPT_DIR}/VPP_STABLE_VER_CENTOS)
    VIRL_TOPOLOGY=$(cat ${SCRIPT_DIR}/VIRL_TOPOLOGY_CENTOS)
    VIRL_RELEASE=$(cat ${SCRIPT_DIR}/VIRL_RELEASE_CENTOS)
else
    DISTRO="UBUNTU"
    export DEBIAN_FRONTEND=noninteractive
    sudo apt-get -y update
    sudo apt-get -y install libpython2.7-dev python-virtualenv
    VPP_ARTIFACTS="vpp vpp-dbg vpp-dev vpp-lib vpp-plugins"
    DPDK_ARTIFACTS="vpp-dpdk-dkms"
    PACKAGE="deb"
    VPP_CLASSIFIER="-deb"
    DPDK_STABLE_VER=$(cat ${SCRIPT_DIR}/DPDK_STABLE_VER)_amd64
    VPP_REPO_URL=$(cat ${SCRIPT_DIR}/VPP_REPO_URL_UBUNTU)
    VPP_STABLE_VER=$(cat ${SCRIPT_DIR}/VPP_STABLE_VER_UBUNTU)
    VIRL_TOPOLOGY=$(cat ${SCRIPT_DIR}/VIRL_TOPOLOGY_UBUNTU)
    VIRL_RELEASE=$(cat ${SCRIPT_DIR}/VIRL_RELEASE_UBUNTU)
fi

VIRL_SERVERS=("10.30.51.28" "10.30.51.29" "10.30.51.30")
IPS_PER_VIRL=( "10.30.51.28:252"
               "10.30.51.29:252"
               "10.30.51.30:252" )
SIMS_PER_VIRL=( "10.30.51.28:13"
               "10.30.51.29:13"
               "10.30.51.30:13" )
IPS_PER_SIMULATION=5

function get_max_ip_nr() {
    virl_server=$1
    IP_VALUE="0"
    for item in "${IPS_PER_VIRL[@]}" ; do
        if [ "${item%%:*}" == "${virl_server}" ]
        then
            IP_VALUE=${item#*:}
            break
        fi
    done
    echo "$IP_VALUE"
}

function get_max_sim_nr() {
    virl_server=$1
    SIM_VALUE="0"
    for item in "${SIMS_PER_VIRL[@]}" ; do
        if [ "${item%%:*}" == "${virl_server}" ]
        then
            SIM_VALUE=${item#*:}
            break
        fi
    done
    echo "$SIM_VALUE"
}

VIRL_USERNAME=jenkins-in
VIRL_PKEY=priv_key
VIRL_SERVER_STATUS_FILE="status"
VIRL_SERVER_EXPECTED_STATUS="PRODUCTION"

SSH_OPTIONS="-i ${VIRL_PKEY} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=error"

TEST_GROUPS=("crypto,ip4_tunnels.softwire,ip4_tunnels.vxlan" "ip4,ip4_tunnels.gre,ip4_tunnels.lisp,ip6_tunnels.vxlan,ip6_tunnels.lisp,vm_vhost.ip4,vm_vhost.ip6" "interfaces,ip6,l2bd,l2xc,vm_vhost.l2bd,vm_vhost.l2xc,telemetry")
SUITE_PATH="tests.vpp.func"
SKIP_PATCH="SKIP_PATCH"

# Create tmp dir
mkdir ${SCRIPT_DIR}/tmp

# Use tmp dir to store log files
LOG_PATH="${SCRIPT_DIR}/tmp"

# Use tmp dir for tarballs
export TMPDIR="${SCRIPT_DIR}/tmp"

function ssh_do() {
    echo
    echo "### "  ssh $@
    ssh ${SSH_OPTIONS} $@
}

rm -f ${VIRL_PKEY}
cat > ${VIRL_PKEY} <<EOF
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA+IHXq87GcqMR1C47rzx6Cbip5Ghq8pKrbqKrP5Nf41HcYrT6
GOXl9nFWKsMOzIlIn+8y7Il27eZh7csQGApbg8QLiHMtcYEmWNzKZpkqg4nuAPxX
VXwlKgnKX902SrET9Gp9TDayiHtCRWVfrlPPPSA0UEXW6BjLN/uHJ+W/Xzrrab+9
asBVa05vT2W6n0KJ66zfCaeDM912mQ6SttscAwFoWDmdHlegiVqrlIG2ABxOvxxz
L3dM3iSmlmQlzv9bThjo+nI4KFYh6m5wrZmAo5r/4q9CIJc21HVnTqkGOWJIZz6J
73lePJVSq5gYqaoGw3swFEA/MDkOx7baWKSoLQIDAQABAoIBAQCNBeolNp+JWJ76
gQ4fwLsknyXSV6sxYyhkDW4PEwwcTU06uqce0AAzXVffxne0fMe48x47+zqBgPbb
4huM+Pu8B9nfojUMr5TaYtl9Zbgpk3F8H7dT7LKOa6XrxvZTZrADSRc30+Z26zPN
e9zTaf42Gvt0/l0Zs1BHwbaOXqO+XuwJ3/F9Sf3PQYWXD3EOWjpHDP/X/1vAs6lV
SLkm6J/9KKE1m6I6LTYjIXuYt4SXybW6N2TSy54hhQtYcDUnIU2hR/PHVWKrGA0J
kELgrtTNTdbML27O5gFWU4PLUEYTZ9fN11D6qUZKxLcPOiPPHXkiILMRCCnG5DYI
ksBAU/YlAoGBAPxZO9VO18TYc8THV1nLKcvT2+1oSs1UcA2wNQMU55t910ZYinRa
MRwUhMOf8Mv5wOeiZaRICQB1PnVWtDVmGECgPpK6jUxqAwn8rgJcnoafLGL5YKMY
RVafTe6N5LXgCaOcJrk21wxs6v7ninEbUxxc575urOvZMBkymDw91dwbAoGBAPwa
YRhKhrzFKZzdK0RadVjnxKvolUllpoqqg3XuvmeAJHAOAnaOgVWq68NAcp5FZJv0
2D2Up7TX8pjf9MofP1SJbcraKBpK4NzfNkA0dSdEi+FhVofAJ9umB2o5LW1n7sab
UIrjsdzSJK/9Zb9yTTHPyibYzNEgaJV1HsbxfEFXAoGAYO2RmvRm0phll18OQVJV
IpKk9kLKAKZ/R/K32hAsikBC8SVPQTPniyaifFWx81diblalff2hX4ipTf7Yx24I
wMIMZuW7Im/R7QMef4+94G3Bad7p7JuE/qnAEHJ2OBnu+eYfxaK35XDsrq6XMazS
NqHE7hOq3giVfgg+C12hCKMCgYEAtu9dbYcG5owbehxzfRI2/OCRsjz/t1bv1seM
xVMND4XI6xb/apBWAZgZpIFrqrWoIBM3ptfsKipZe91ngBPUnL9s0Dolx452RVAj
yctHB8uRxWYgqDkjsxtzXf1HnZBBkBS8CUzYj+hdfuddoeKLaY3invXLCiV+PpXS
U4KAK9kCgYEAtSv0m5+Fg74BbAiFB6kCh11FYkW94YI6B/E2D/uVTD5dJhyEUFgZ
cWsudXjMki8734WSpMBqBp/J8wG3C9ZS6IpQD+U7UXA+roB7Qr+j4TqtWfM+87Rh
maOpG56uAyR0w5Z9BhwzA3VakibVk9KwDgZ29WtKFzuATLFnOtCS46E=
-----END RSA PRIVATE KEY-----
EOF
chmod 600 ${VIRL_PKEY}

#
# The server must be reachable and have a "status" file with
# the content "PRODUCTION" to be selected.
#
# If the server is not reachable or does not have the correct
# status remove it from the array and start again.
#
# Abort if there are no more servers left in the array.
#
VIRL_PROD_SERVERS=()
for index in "${!VIRL_SERVERS[@]}"; do
    virl_server_status=$(ssh ${SSH_OPTIONS} ${VIRL_USERNAME}@${VIRL_SERVERS[$index]} cat $VIRL_SERVER_STATUS_FILE 2>&1)
    echo VIRL HOST ${VIRL_SERVERS[$index]} status is \"$virl_server_status\"
    if [ "$virl_server_status" == "$VIRL_SERVER_EXPECTED_STATUS" ]
    then
        # Candidate is in good status. Add to array.
        VIRL_PROD_SERVERS+=(${VIRL_SERVERS[$index]})
    fi
done

VIRL_SERVERS=("${VIRL_PROD_SERVERS[@]}")
echo "VIRL servers in production: ${VIRL_SERVERS[@]}"
num_hosts=${#VIRL_SERVERS[@]}
if [ $num_hosts == 0 ]
then
    echo "No more VIRL candidate hosts available, failing."
    exit 127
fi

# Get the LOAD of each server based on number of active simulations (testcases)
VIRL_SERVER_LOAD=()
for index in "${!VIRL_SERVERS[@]}"; do
    VIRL_SERVER_LOAD[${index}]=$(ssh ${SSH_OPTIONS} ${VIRL_USERNAME}@${VIRL_SERVERS[$index]} "list-testcases | grep session | wc -l")
done

# Pick for each TEST_GROUP least loaded server
VIRL_SERVER=()
for index in "${!TEST_GROUPS[@]}"; do
    least_load_server_idx=$(echo "${VIRL_SERVER_LOAD[*]}" | tr -s ' ' '\n' | awk '{print($0" "NR)}' | sort -g -k1,1 | head -1 | cut -f2 -d' ')
    least_load_server=${VIRL_SERVERS[$least_load_server_idx-1]}
    VIRL_SERVER+=($least_load_server)
    # Adjusting load as we are not going run simulation immediately
    VIRL_SERVER_LOAD[$least_load_server_idx-1]=$((VIRL_SERVER_LOAD[$least_load_server_idx-1]+1))
done

echo "Selected VIRL servers: ${VIRL_SERVER[@]}"

# Temporarily download VPP and DPDK packages from nexus.fd.io
if [ "${#}" -ne "0" ]; then
    arr=(${@})
    echo ${arr[0]}
    SKIP_PATCH="skip_patchORskip_vpp_patch"
else
    rm -f *.${PACKAGE}
    for ARTIFACT in ${DPDK_ARTIFACTS}; do
        wget -q "${VPP_REPO_URL}/${ARTIFACT}/${DPDK_STABLE_VER}/${ARTIFACT}-${DPDK_STABLE_VER}${VPP_CLASSIFIER}.${PACKAGE}" || exit
    done
    for ARTIFACT in ${VPP_ARTIFACTS}; do
        wget -q "${VPP_REPO_URL}/${ARTIFACT}/${VPP_STABLE_VER}/${ARTIFACT}-${VPP_STABLE_VER}${VPP_CLASSIFIER}.${PACKAGE}" || exit
    done
fi

VPP_PKGS=(*.$PACKAGE)
echo ${VPP_PKGS[@]}
VIRL_DIR_LOC="/tmp"
VPP_PKGS_FULL=(${VPP_PKGS[@]})

# Prepend directory location at remote host to package file list
for index in "${!VPP_PKGS_FULL[@]}"; do
    VPP_PKGS_FULL[${index}]=${VIRL_DIR_LOC}/${VPP_PKGS_FULL[${index}]}
done

echo "Updated file names: " ${VPP_PKGS_FULL[@]}

cat ${VIRL_PKEY}

# Copy the files to VIRL hosts
DONE=""
for index in "${!VIRL_SERVER[@]}"; do
    # Do not copy files in case they have already been copied to the VIRL host
    [[ "${DONE[@]}" =~ "${VIRL_SERVER[${index}]}" ]] && copy=0 || copy=1

    if [ "${copy}" -eq "0" ]; then
        echo "VPP packages have already been copied to the VIRL host ${VIRL_SERVER[${index}]}"
    else
        scp ${SSH_OPTIONS} *.${PACKAGE} \
        ${VIRL_USERNAME}@${VIRL_SERVER[${index}]}:${VIRL_DIR_LOC}/

        result=$?
        if [ "${result}" -ne "0" ]; then
            echo "Failed to copy VPP packages to VIRL host ${VIRL_SERVER[${index}]}"
            echo ${result}
            exit ${result}
        else
            echo "VPP packages successfully copied to the VIRL host ${VIRL_SERVER[${index}]}"
        fi
        DONE+=(${VIRL_SERVER[${index}]})
    fi
done

# Start a simulation on VIRL server

function stop_virl_simulation {
    for index in "${!VIRL_SERVER[@]}"; do
        ssh ${SSH_OPTIONS} ${VIRL_USERNAME}@${VIRL_SERVER[${index}]}\
            "stop-testcase ${VIRL_SID[${index}]}"
    done
}

# Upon script exit, cleanup the simulation execution
trap stop_virl_simulation EXIT

for index in "${!VIRL_SERVER[@]}"; do
    echo "Starting simulation nr. ${index} on VIRL server ${VIRL_SERVER[${index}]}"
    # Get given VIRL server limits for max. number of VMs and IPs
    max_ips=$(get_max_ip_nr ${VIRL_SERVER[${index}]})
    max_ips_from_sims=$(($(get_max_sim_nr ${VIRL_SERVER[${index}]})*IPS_PER_SIMULATION))
    # Set quota to lower value
    IP_QUOTA=$([ $max_ips -le $max_ips_from_sims ] && echo "$max_ips" || echo "$max_ips_from_sims")
    # Start the simulation
    VIRL_SID[${index}]=$(ssh ${SSH_OPTIONS} \
        ${VIRL_USERNAME}@${VIRL_SERVER[${index}]} \
        "start-testcase -vv --quota ${IP_QUOTA} --copy ${VIRL_TOPOLOGY} \
        --release ${VIRL_RELEASE} ${VPP_PKGS_FULL[@]}")
        # TODO: remove param ${VPP_PKGS_FULL[@]} when start-testcase script is
        # updated on all virl servers
    retval=$?
    if [ ${retval} -ne "0" ]; then
        echo "VIRL simulation start failed on ${VIRL_SERVER[${index}]}"
        exit ${retval}
    fi
    if [[ ! "${VIRL_SID[${index}]}" =~ session-[a-zA-Z0-9_]{6} ]]; then
        echo "No VIRL session ID reported."
        exit 127
    fi
    echo "VIRL simulation nr. ${index} started on ${VIRL_SERVER[${index}]}"

    ssh_do ${VIRL_USERNAME}@${VIRL_SERVER[${index}]}\
     cat /scratch/${VIRL_SID[${index}]}/topology.yaml

    # Download the topology file from VIRL session and rename it
    scp ${SSH_OPTIONS} \
        ${VIRL_USERNAME}@${VIRL_SERVER[${index}]}:/scratch/${VIRL_SID[${index}]}/topology.yaml \
        topologies/enabled/topology${index}.yaml

    retval=$?
    if [ ${retval} -ne "0" ]; then
        echo "Failed to copy topology file from VIRL simulation nr. ${index} on VIRL server ${VIRL_SERVER[${index}]}"
        exit ${retval}
    fi
done

echo ${VIRL_SID[@]}

virtualenv --system-site-packages env
. env/bin/activate

echo pip install
pip install -r ${SCRIPT_DIR}/requirements.txt

for index in "${!VIRL_SERVER[@]}"; do
    pykwalify -s ${SCRIPT_DIR}/resources/topology_schemas/3_node_topology.sch.yaml \
              -s ${SCRIPT_DIR}/resources/topology_schemas/topology.sch.yaml \
              -d ${SCRIPT_DIR}/topologies/enabled/topology${index}.yaml \
              -vvv
    if [ "$?" -ne "0" ]; then
        echo "Topology${index} schema validation failed."
        echo "However, the tests will start."
    fi
done

function run_test_set() {
    set +x
    OLDIFS=$IFS
    IFS=","
    nr=$(echo $1)
    rm -f ${LOG_PATH}/test_run${nr}.log
    exec &> >(while read line; do echo "$(date +'%H:%M:%S') $line" \
     >> ${LOG_PATH}/test_run${nr}.log; done;)
    suite_str=""
    for suite in ${TEST_GROUPS[${nr}]}; do
        suite_str="${suite_str} --suite ${SUITE_PATH}.${suite}"
    done
    IFS=$OLDIFS

    echo "PYTHONPATH=`pwd` pybot -L TRACE -W 136\
        -v TOPOLOGY_PATH:${SCRIPT_DIR}/topologies/enabled/topology${nr}.yaml \
        ${suite_str} \
        --include vm_envAND3_node_single_link_topo \
        --include vm_envAND3_node_double_link_topo \
        --exclude PERFTEST \
        --exclude ${SKIP_PATCH} \
        --noncritical EXPECTED_FAILING \
        --output ${LOG_PATH}/log_test_set_run${nr} \
        tests/"

    PYTHONPATH=`pwd` pybot -L TRACE -W 136\
        -v TOPOLOGY_PATH:${SCRIPT_DIR}/topologies/enabled/topology${nr}.yaml \
        ${suite_str} \
        --include vm_envAND3_node_single_link_topo \
        --include vm_envAND3_node_double_link_topo \
        --exclude PERFTEST \
        --exclude ${SKIP_PATCH} \
        --noncritical EXPECTED_FAILING \
        --output ${LOG_PATH}/log_test_set_run${nr} \
        tests/

    local local_run_rc=$?
    set -x
    echo ${local_run_rc} > ${LOG_PATH}/rc_test_run${nr}
}

set +x
# Send to background an instance of the run_test_set() function for each number,
# record the pid.
for index in "${!VIRL_SERVER[@]}"; do
    run_test_set ${index} &
    pid=$!
    echo "Sent to background: Test_set${index} (pid=$pid)"
    pids[$pid]=$index
done

echo
echo -n "Waiting..."

# Watch the stable of background processes.
# If a pid goes away, remove it from the array.
while [ -n "${pids[*]}" ]; do
    for i in $(seq 0 9); do
        sleep 1
        echo -n "."
    done
    for pid in "${!pids[@]}"; do
        if ! ps "$pid" >/dev/null; then
            echo -e "\n"
            echo "Test_set${pids[$pid]} with PID $pid finished."
            unset pids[$pid]
        fi
    done
    if [ -z "${!pids[*]}" ]; then
        break
    fi
    echo -n -e "\nStill waiting for test set(s): ${pids[*]} ..."
done

echo
echo "All test set runs finished."
echo

set -x

RC=0
for index in "${!VIRL_SERVER[@]}"; do
    echo "Test_set${index} log:"
    cat ${LOG_PATH}/test_run${index}.log
    RC_PARTIAL_RUN=$(cat ${LOG_PATH}/rc_test_run${index})
    if [ -z "$RC_PARTIAL_RUN" ]; then
        echo "Failed to retrieve return code from test run ${index}"
        exit 1
    fi
    RC=$((RC+RC_PARTIAL_RUN))
    rm -f ${LOG_PATH}/rc_test_run${index}
    rm -f ${LOG_PATH}/test_run${index}.log
    echo
done

# Log the final result
if [ "${RC}" -eq "0" ]; then
    set +x
    echo
    echo "========================================================================================================================================"
    echo "Final result of all test loops:                                                                                                 | PASS |"
    echo "All critical tests have passed."
    echo "========================================================================================================================================"
    echo
    set -x
else
    if [ "${RC}" -eq "1" ]; then
        HLP_STR="test has"
    else
        HLP_STR="tests have"
    fi
    set +x
    echo
    echo "========================================================================================================================================"
    echo "Final result of all test loops:                                                                                                 | FAIL |"
    echo "${RC} critical ${HLP_STR} failed."
    echo "========================================================================================================================================"
    echo
    set -x
fi

echo Post-processing test data...

partial_logs=""
for index in "${!VIRL_SERVER[@]}"; do
    partial_logs="${partial_logs} ${LOG_PATH}/log_test_set_run${index}.xml"
done

# Rebot output post-processing
rebot --noncritical EXPECTED_FAILING \
      --output output.xml ${partial_logs}

# Remove unnecessary log files
rm -f ${partial_logs}

echo Post-processing finished.

if [ ${RC} -eq 0 ]; then
    RETURN_STATUS=0
else
    RETURN_STATUS=1
fi

exit ${RETURN_STATUS}
#n2461'>2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141
/*
 * 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.
 */

#include <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vnet/pg/pg.h>
#include <vnet/handoff.h>

#include <vnet/ip/ip.h>
#include <vnet/ethernet/ethernet.h>
#include <vnet/fib/ip4_fib.h>
#include <nat/nat.h>
#include <nat/nat_ipfix_logging.h>
#include <nat/nat_det.h>
#include <nat/nat_reass.h>

#include <vppinfra/hash.h>
#include <vppinfra/error.h>
#include <vppinfra/elog.h>

typedef struct {
  u32 sw_if_index;
  u32 next_index;
  u32 session_index;
  u32 is_slow_path;
} snat_in2out_trace_t;

typedef struct {
  u32 next_worker_index;
  u8 do_handoff;
} snat_in2out_worker_handoff_trace_t;

/* packet trace format function */
static u8 * format_snat_in2out_trace (u8 * s, va_list * args)
{
  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
  snat_in2out_trace_t * t = va_arg (*args, snat_in2out_trace_t *);
  char * tag;

  tag = t->is_slow_path ? "NAT44_IN2OUT_SLOW_PATH" : "NAT44_IN2OUT_FAST_PATH";

  s = format (s, "%s: sw_if_index %d, next index %d, session %d", tag,
              t->sw_if_index, t->next_index, t->session_index);

  return s;
}

static u8 * format_snat_in2out_fast_trace (u8 * s, va_list * args)
{
  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
  snat_in2out_trace_t * t = va_arg (*args, snat_in2out_trace_t *);

  s = format (s, "NAT44_IN2OUT_FAST: sw_if_index %d, next index %d",
              t->sw_if_index, t->next_index);

  return s;
}

static u8 * format_snat_in2out_worker_handoff_trace (u8 * s, va_list * args)
{
  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
  snat_in2out_worker_handoff_trace_t * t =
    va_arg (*args, snat_in2out_worker_handoff_trace_t *);
  char * m;

  m = t->do_handoff ? "next worker" : "same worker";
  s = format (s, "NAT44_IN2OUT_WORKER_HANDOFF: %s %d", m, t->next_worker_index);

  return s;
}

typedef struct {
  u32 sw_if_index;
  u32 next_index;
  u8 cached;
} nat44_in2out_reass_trace_t;

static u8 * format_nat44_in2out_reass_trace (u8 * s, va_list * args)
{
  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
  nat44_in2out_reass_trace_t * t = va_arg (*args, nat44_in2out_reass_trace_t *);

  s = format (s, "NAT44_IN2OUT_REASS: sw_if_index %d, next index %d, status %s",
              t->sw_if_index, t->next_index,
              t->cached ? "cached" : "translated");

  return s;
}

vlib_node_registration_t snat_in2out_node;
vlib_node_registration_t snat_in2out_slowpath_node;
vlib_node_registration_t snat_in2out_fast_node;
vlib_node_registration_t snat_in2out_worker_handoff_node;
vlib_node_registration_t snat_det_in2out_node;
vlib_node_registration_t snat_in2out_output_node;
vlib_node_registration_t snat_in2out_output_slowpath_node;
vlib_node_registration_t snat_in2out_output_worker_handoff_node;
vlib_node_registration_t snat_hairpin_dst_node;
vlib_node_registration_t snat_hairpin_src_node;
vlib_node_registration_t nat44_hairpinning_node;
vlib_node_registration_t nat44_in2out_reass_node;


#define foreach_snat_in2out_error                       \
_(UNSUPPORTED_PROTOCOL, "Unsupported protocol")         \
_(IN2OUT_PACKETS, "Good in2out packets processed")      \
_(OUT_OF_PORTS, "Out of ports")                         \
_(BAD_OUTSIDE_FIB, "Outside VRF ID not found")          \
_(BAD_ICMP_TYPE, "unsupported ICMP type")               \
_(NO_TRANSLATION, "No translation")                     \
_(MAX_SESSIONS_EXCEEDED, "Maximum sessions exceeded")   \
_(DROP_FRAGMENT, "Drop fragment")                       \
_(MAX_REASS, "Maximum reassemblies exceeded")           \
_(MAX_FRAG, "Maximum fragments per reassembly exceeded")

typedef enum {
#define _(sym,str) SNAT_IN2OUT_ERROR_##sym,
  foreach_snat_in2out_error
#undef _
  SNAT_IN2OUT_N_ERROR,
} snat_in2out_error_t;

static char * snat_in2out_error_strings[] = {
#define _(sym,string) string,
  foreach_snat_in2out_error
#undef _
};

typedef enum {
  SNAT_IN2OUT_NEXT_LOOKUP,
  SNAT_IN2OUT_NEXT_DROP,
  SNAT_IN2OUT_NEXT_ICMP_ERROR,
  SNAT_IN2OUT_NEXT_SLOW_PATH,
  SNAT_IN2OUT_NEXT_REASS,
  SNAT_IN2OUT_N_NEXT,
} snat_in2out_next_t;

typedef enum {
  SNAT_HAIRPIN_SRC_NEXT_DROP,
  SNAT_HAIRPIN_SRC_NEXT_SNAT_IN2OUT,
  SNAT_HAIRPIN_SRC_NEXT_SNAT_IN2OUT_WH,
  SNAT_HAIRPIN_SRC_NEXT_INTERFACE_OUTPUT,
  SNAT_HAIRPIN_SRC_N_NEXT,
} snat_hairpin_next_t;

/**
 * @brief Check if packet should be translated
 *
 * Packets aimed at outside interface and external address with active session
 * should be translated.
 *
 * @param sm            NAT main
 * @param rt            NAT runtime data
 * @param sw_if_index0  index of the inside interface
 * @param ip0           IPv4 header
 * @param proto0        NAT protocol
 * @param rx_fib_index0 RX FIB index
 *
 * @returns 0 if packet should be translated otherwise 1
 */
static inline int
snat_not_translate_fast (snat_main_t * sm, vlib_node_runtime_t *node,
                         u32 sw_if_index0, ip4_header_t * ip0, u32 proto0,
                         u32 rx_fib_index0)
{
  if (sm->out2in_dpo)
    return 0;

  fib_node_index_t fei = FIB_NODE_INDEX_INVALID;
  fib_prefix_t pfx = {
    .fp_proto = FIB_PROTOCOL_IP4,
    .fp_len = 32,
    .fp_addr = {
        .ip4.as_u32 = ip0->dst_address.as_u32,
    },
  };

  /* Don't NAT packet aimed at the intfc address */
  if (PREDICT_FALSE(is_interface_addr(sm, node, sw_if_index0,
                                      ip0->dst_address.as_u32)))
    return 1;

  fei = fib_table_lookup (rx_fib_index0, &pfx);
  if (FIB_NODE_INDEX_INVALID != fei)
    {
      u32 sw_if_index = fib_entry_get_resolving_interface (fei);
      if (sw_if_index == ~0)
        {
          fei = fib_table_lookup (sm->outside_fib_index, &pfx);
          if (FIB_NODE_INDEX_INVALID != fei)
            sw_if_index = fib_entry_get_resolving_interface (fei);
        }
      snat_interface_t *i;
      pool_foreach (i, sm->interfaces,
      ({
        /* NAT packet aimed at outside interface */
        if ((nat_interface_is_outside(i)) && (sw_if_index == i->sw_if_index))
          return 0;
      }));
    }

  return 1;
}

static inline int
snat_not_translate (snat_main_t * sm, vlib_node_runtime_t *node,
                    u32 sw_if_index0, ip4_header_t * ip0, u32 proto0,
                    u32 rx_fib_index0, u32 thread_index)
{
  udp_header_t * udp0 = ip4_next_header (ip0);
  snat_session_key_t key0, sm0;
  clib_bihash_kv_8_8_t kv0, value0;

  key0.addr = ip0->dst_address;
  key0.port = udp0->dst_port;
  key0.protocol = proto0;
  key0.fib_index = sm->outside_fib_index;
  kv0.key = key0.as_u64;

  /* NAT packet aimed at external address if */
  /* has active sessions */
  if (clib_bihash_search_8_8 (&sm->per_thread_data[thread_index].out2in, &kv0,
                              &value0))
    {
      /* or is static mappings */
      if (!snat_static_mapping_match(sm, key0, &sm0, 1, 0, 0))
        return 0;
    }
  else
    return 0;

  if (sm->forwarding_enabled)
    return 1;

  return snat_not_translate_fast(sm, node, sw_if_index0, ip0, proto0,
                                 rx_fib_index0);
}

static inline int
nat_not_translate_output_feature (snat_main_t * sm, ip4_header_t * ip0,
                                  u32 proto0, u16 src_port, u16 dst_port,
                                  u32 thread_index, u32 sw_if_index)
{
  snat_session_key_t key0;
  clib_bihash_kv_8_8_t kv0, value0;
  snat_interface_t *i;

  /* src NAT check */
  key0.addr = ip0->src_address;
  key0.port = src_port;
  key0.protocol = proto0;
  key0.fib_index = sm->outside_fib_index;
  kv0.key = key0.as_u64;

  if (!clib_bihash_search_8_8 (&sm->per_thread_data[thread_index].out2in, &kv0,
                               &value0))
    return 1;

  /* dst NAT check */
  key0.addr = ip0->dst_address;
  key0.port = dst_port;
  key0.protocol = proto0;
  key0.fib_index = sm->inside_fib_index;
  kv0.key = key0.as_u64;
  if (!clib_bihash_search_8_8 (&sm->per_thread_data[thread_index].in2out, &kv0,
                               &value0))
  {
    /* hairpinning */
    pool_foreach (i, sm->output_feature_interfaces,
    ({
      if ((nat_interface_is_inside(i)) && (sw_if_index == i->sw_if_index))
        return 0;
    }));
    return 1;
  }

  return 0;
}

static u32 slow_path (snat_main_t *sm, vlib_buffer_t *b0,
                      ip4_header_t * ip0,
                      u32 rx_fib_index0,
                      snat_session_key_t * key0,
                      snat_session_t ** sessionp,
                      vlib_node_runtime_t * node,
                      u32 next0,
                      u32 thread_index)
{
  snat_user_t *u;
  snat_session_t *s;
  clib_bihash_kv_8_8_t kv0;
  snat_session_key_t key1;
  u32 address_index = ~0;
  u32 outside_fib_index;
  uword * p;
  udp_header_t * udp0 = ip4_next_header (ip0);
  u8 is_sm = 0;

  if (PREDICT_FALSE (maximum_sessions_exceeded(sm, thread_index)))
    {
      b0->error = node->errors[SNAT_IN2OUT_ERROR_MAX_SESSIONS_EXCEEDED];
      nat_ipfix_logging_max_sessions(sm->max_translations);
      return SNAT_IN2OUT_NEXT_DROP;
    }

  p = hash_get (sm->ip4_main->fib_index_by_table_id, sm->outside_vrf_id);
  if (! p)
    {
      b0->error = node->errors[SNAT_IN2OUT_ERROR_BAD_OUTSIDE_FIB];
      return SNAT_IN2OUT_NEXT_DROP;
    }
  outside_fib_index = p[0];

  key1.protocol = key0->protocol;

  u = nat_user_get_or_create (sm, &ip0->src_address, rx_fib_index0,
                              thread_index);
  if (!u)
    {
      clib_warning ("create NAT user failed");
      return SNAT_IN2OUT_NEXT_DROP;
    }

  /* First try to match static mapping by local address and port */
  if (snat_static_mapping_match (sm, *key0, &key1, 0, 0, 0))
    {
      /* Try to create dynamic translation */
      if (snat_alloc_outside_address_and_port (sm->addresses, rx_fib_index0,
                                               thread_index, &key1,
                                               &address_index,
                                               sm->port_per_thread,
                                               sm->per_thread_data[thread_index].snat_thread_index))
        {
          b0->error = node->errors[SNAT_IN2OUT_ERROR_OUT_OF_PORTS];
          return SNAT_IN2OUT_NEXT_DROP;
        }
    }
  else
    is_sm = 1;

  s = nat_session_alloc_or_recycle (sm, u, thread_index);
  if (!s)
    {
      clib_warning ("create NAT session failed");
      return SNAT_IN2OUT_NEXT_DROP;
    }

  if (is_sm)
    s->flags |= SNAT_SESSION_FLAG_STATIC_MAPPING;
  user_session_increment (sm, u, is_sm);
  s->outside_address_index = address_index;
  s->in2out = *key0;
  s->out2in = key1;
  s->out2in.protocol = key0->protocol;
  s->out2in.fib_index = outside_fib_index;
  s->ext_host_addr.as_u32 = ip0->dst_address.as_u32;
  s->ext_host_port = udp0->dst_port;
  *sessionp = s;

  /* Add to translation hashes */
  kv0.key = s->in2out.as_u64;
  kv0.value = s - sm->per_thread_data[thread_index].sessions;
  if (clib_bihash_add_del_8_8 (&sm->per_thread_data[thread_index].in2out, &kv0,
                               1 /* is_add */))
      clib_warning ("in2out key add failed");

  kv0.key = s->out2in.as_u64;
  kv0.value = s - sm->per_thread_data[thread_index].sessions;

  if (clib_bihash_add_del_8_8 (&sm->per_thread_data[thread_index].out2in, &kv0,
                               1 /* is_add */))
      clib_warning ("out2in key add failed");

  /* log NAT event */
  snat_ipfix_logging_nat44_ses_create(s->in2out.addr.as_u32,
                                      s->out2in.addr.as_u32,
                                      s->in2out.protocol,
                                      s->in2out.port,
                                      s->out2in.port,
                                      s->in2out.fib_index);
  return next0;
}

static_always_inline
snat_in2out_error_t icmp_get_key(ip4_header_t *ip0,
                                 snat_session_key_t *p_key0)
{
  icmp46_header_t *icmp0;
  snat_session_key_t key0;
  icmp_echo_header_t *echo0, *inner_echo0 = 0;
  ip4_header_t *inner_ip0 = 0;
  void *l4_header = 0;
  icmp46_header_t *inner_icmp0;

  icmp0 = (icmp46_header_t *) ip4_next_header (ip0);
  echo0 = (icmp_echo_header_t *)(icmp0+1);

  if (!icmp_is_error_message (icmp0))
    {
      key0.protocol = SNAT_PROTOCOL_ICMP;
      key0.addr = ip0->src_address;
      key0.port = echo0->identifier;
    }
  else
    {
      inner_ip0 = (ip4_header_t *)(echo0+1);
      l4_header = ip4_next_header (inner_ip0);
      key0.protocol = ip_proto_to_snat_proto (inner_ip0->protocol);
      key0.addr = inner_ip0->dst_address;
      switch (key0.protocol)
        {
        case SNAT_PROTOCOL_ICMP:
          inner_icmp0 = (icmp46_header_t*)l4_header;
          inner_echo0 = (icmp_echo_header_t *)(inner_icmp0+1);
          key0.port = inner_echo0->identifier;
          break;
        case SNAT_PROTOCOL_UDP:
        case SNAT_PROTOCOL_TCP:
          key0.port = ((tcp_udp_header_t*)l4_header)->dst_port;
          break;
        default:
          return SNAT_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL;
        }
    }
  *p_key0 = key0;
  return -1; /* success */
}

static_always_inline int
icmp_get_ed_key(ip4_header_t *ip0, nat_ed_ses_key_t *p_key0)
{
  icmp46_header_t *icmp0;
  nat_ed_ses_key_t key0;
  icmp_echo_header_t *echo0, *inner_echo0 = 0;
  ip4_header_t *inner_ip0 = 0;
  void *l4_header = 0;
  icmp46_header_t *inner_icmp0;

  icmp0 = (icmp46_header_t *) ip4_next_header (ip0);
  echo0 = (icmp_echo_header_t *)(icmp0+1);

  if (!icmp_is_error_message (icmp0))
    {
      key0.proto = IP_PROTOCOL_ICMP;
      key0.l_addr = ip0->src_address;
      key0.r_addr = ip0->dst_address;
      key0.l_port = key0.r_port = echo0->identifier;
    }
  else
    {
      inner_ip0 = (ip4_header_t *)(echo0+1);
      l4_header = ip4_next_header (inner_ip0);
      key0.proto = inner_ip0->protocol;
      key0.r_addr = inner_ip0->src_address;
      key0.l_addr = inner_ip0->dst_address;
      switch (ip_proto_to_snat_proto (inner_ip0->protocol))
        {
        case SNAT_PROTOCOL_ICMP:
          inner_icmp0 = (icmp46_header_t*)l4_header;
          inner_echo0 = (icmp_echo_header_t *)(inner_icmp0+1);
          key0.r_port = key0.l_port = inner_echo0->identifier;
          break;
        case SNAT_PROTOCOL_UDP:
        case SNAT_PROTOCOL_TCP:
          key0.l_port = ((tcp_udp_header_t*)l4_header)->dst_port;
          key0.r_port = ((tcp_udp_header_t*)l4_header)->src_port;
          break;
        default:
          return SNAT_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL;
        }
    }
  *p_key0 = key0;
  return 0;
}

static inline int
nat_not_translate_output_feature_fwd (snat_main_t * sm, ip4_header_t * ip)
{
  nat_ed_ses_key_t key;
  clib_bihash_kv_16_8_t kv, value;
  udp_header_t *udp;

  if (!sm->forwarding_enabled)
    return 0;

  if (ip->protocol == IP_PROTOCOL_ICMP)
    {
      if (icmp_get_ed_key (ip, &key))
        return 0;
    }
  else if (ip->protocol == IP_PROTOCOL_UDP || ip->protocol == IP_PROTOCOL_TCP)
    {
      udp = ip4_next_header(ip);
      key.l_addr = ip->src_address;
      key.r_addr = ip->dst_address;
      key.proto = ip->protocol;
      key.r_port = udp->dst_port;
      key.l_port = udp->src_port;
    }
  else
    {
      key.l_addr = ip->src_address;
      key.r_addr = ip->dst_address;
      key.proto = ip->protocol;
      key.l_port = key.r_port = 0;
    }
  key.fib_index = 0;
  kv.key[0] = key.as_u64[0];
  kv.key[1] = key.as_u64[1];

  if (!clib_bihash_search_16_8 (&sm->in2out_ed, &kv, &value))
    return value.value == ~0ULL;

  return 0;
}

/**
 * Get address and port values to be used for ICMP packet translation
 * and create session if needed
 *
 * @param[in,out] sm             NAT main
 * @param[in,out] node           NAT node runtime
 * @param[in] thread_index       thread index
 * @param[in,out] b0             buffer containing packet to be translated
 * @param[out] p_proto           protocol used for matching
 * @param[out] p_value           address and port after NAT translation
 * @param[out] p_dont_translate  if packet should not be translated
 * @param d                      optional parameter
 * @param e                      optional parameter
 */
u32 icmp_match_in2out_slow(snat_main_t *sm, vlib_node_runtime_t *node,
                           u32 thread_index, vlib_buffer_t *b0,
                           ip4_header_t *ip0, u8 *p_proto,
                           snat_session_key_t *p_value,
                           u8 *p_dont_translate, void *d, void *e)
{
  icmp46_header_t *icmp0;
  u32 sw_if_index0;
  u32 rx_fib_index0;
  snat_session_key_t key0;
  snat_session_t *s0 = 0;
  u8 dont_translate = 0;
  clib_bihash_kv_8_8_t kv0, value0;
  u32 next0 = ~0;
  int err;

  icmp0 = (icmp46_header_t *) ip4_next_header (ip0);
  sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
  rx_fib_index0 = ip4_fib_table_get_index_for_sw_if_index (sw_if_index0);

  err = icmp_get_key (ip0, &key0);
  if (err != -1)
    {
      b0->error = node->errors[err];
      next0 = SNAT_IN2OUT_NEXT_DROP;
      goto out;
    }
  key0.fib_index = rx_fib_index0;

  kv0.key = key0.as_u64;

  if (clib_bihash_search_8_8 (&sm->per_thread_data[thread_index].in2out, &kv0,
                              &value0))
    {
      if (vnet_buffer(b0)->sw_if_index[VLIB_TX] != ~0)
        {
          if (PREDICT_FALSE(nat_not_translate_output_feature(sm,
              ip0, SNAT_PROTOCOL_ICMP, key0.port, key0.port, thread_index, sw_if_index0)))
            {
              dont_translate = 1;
              goto out;
            }
        }
      else
        {
          if (PREDICT_FALSE(snat_not_translate(sm, node, sw_if_index0,
              ip0, SNAT_PROTOCOL_ICMP, rx_fib_index0, thread_index)))
            {
              dont_translate = 1;
              goto out;
            }
        }

      if (PREDICT_FALSE(icmp_is_error_message (icmp0)))
        {
          b0->error = node->errors[SNAT_IN2OUT_ERROR_BAD_ICMP_TYPE];
          next0 = SNAT_IN2OUT_NEXT_DROP;
          goto out;
        }

      next0 = slow_path (sm, b0, ip0, rx_fib_index0, &key0,
                         &s0, node, next0, thread_index);

      if (PREDICT_FALSE (next0 == SNAT_IN2OUT_NEXT_DROP))
        goto out;
    }
  else
    {
      if (PREDICT_FALSE(icmp0->type != ICMP4_echo_request &&
                        icmp0->type != ICMP4_echo_reply &&
                        !icmp_is_error_message (icmp0)))
        {
          b0->error = node->errors[SNAT_IN2OUT_ERROR_BAD_ICMP_TYPE];
          next0 = SNAT_IN2OUT_NEXT_DROP;
          goto out;
        }

      if (PREDICT_FALSE (value0.value == ~0ULL))
        {
          nat_ed_ses_key_t key;
          clib_bihash_kv_16_8_t s_kv, s_value;

          key.as_u64[0] = 0;
          key.as_u64[1] = 0;
          if (icmp_get_ed_key (ip0, &key))
            {
              b0->error = node->errors[SNAT_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL];
              next0 = SNAT_IN2OUT_NEXT_DROP;
              goto out;
            }
          key.fib_index = rx_fib_index0;
          s_kv.key[0] = key.as_u64[0];
          s_kv.key[1] = key.as_u64[1];
          if (!clib_bihash_search_16_8 (&sm->in2out_ed, &s_kv, &s_value))
            s0 = pool_elt_at_index (sm->per_thread_data[thread_index].sessions,
                                    s_value.value);
          else
           {
              next0 = SNAT_IN2OUT_NEXT_DROP;
              goto out;
           }
        }
      else
        s0 = pool_elt_at_index (sm->per_thread_data[thread_index].sessions,
                                value0.value);
    }

out:
  *p_proto = key0.protocol;
  if (s0)
    *p_value = s0->out2in;
  *p_dont_translate = dont_translate;
  if (d)
    *(snat_session_t**)d = s0;
  return next0;
}

/**
 * Get address and port values to be used for ICMP packet translation
 *
 * @param[in] sm                 NAT main
 * @param[in,out] node           NAT node runtime
 * @param[in] thread_index       thread index
 * @param[in,out] b0             buffer containing packet to be translated
 * @param[out] p_proto           protocol used for matching
 * @param[out] p_value           address and port after NAT translation
 * @param[out] p_dont_translate  if packet should not be translated
 * @param d                      optional parameter
 * @param e                      optional parameter
 */
u32 icmp_match_in2out_fast(snat_main_t *sm, vlib_node_runtime_t *node,
                           u32 thread_index, vlib_buffer_t *b0,
                           ip4_header_t *ip0, u8 *p_proto,
                           snat_session_key_t *p_value,
                           u8 *p_dont_translate, void *d, void *e)
{
  icmp46_header_t *icmp0;
  u32 sw_if_index0;
  u32 rx_fib_index0;
  snat_session_key_t key0;
  snat_session_key_t sm0;
  u8 dont_translate = 0;
  u8 is_addr_only;
  u32 next0 = ~0;
  int err;

  icmp0 = (icmp46_header_t *) ip4_next_header (ip0);
  sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
  rx_fib_index0 = ip4_fib_table_get_index_for_sw_if_index (sw_if_index0);

  err = icmp_get_key (ip0, &key0);
  if (err != -1)
    {
      b0->error = node->errors[err];
      next0 = SNAT_IN2OUT_NEXT_DROP;
      goto out2;
    }
  key0.fib_index = rx_fib_index0;

  if (snat_static_mapping_match(sm, key0, &sm0, 0, &is_addr_only, 0))
    {
      if (PREDICT_FALSE(snat_not_translate_fast(sm, node, sw_if_index0, ip0,
          IP_PROTOCOL_ICMP, rx_fib_index0)))
        {
          dont_translate = 1;
          goto out;
        }

      if (icmp_is_error_message (icmp0))
        {
          next0 = SNAT_IN2OUT_NEXT_DROP;
          goto out;
        }

      b0->error = node->errors[SNAT_IN2OUT_ERROR_NO_TRANSLATION];
      next0 = SNAT_IN2OUT_NEXT_DROP;
      goto out;
    }

  if (PREDICT_FALSE(icmp0->type != ICMP4_echo_request &&
                    (icmp0->type != ICMP4_echo_reply || !is_addr_only) &&
                    !icmp_is_error_message (icmp0)))
    {
      b0->error = node->errors[SNAT_IN2OUT_ERROR_BAD_ICMP_TYPE];
      next0 = SNAT_IN2OUT_NEXT_DROP;
      goto out;
    }

out:
  *p_value = sm0;
out2:
  *p_proto = key0.protocol;
  *p_dont_translate = dont_translate;
  return next0;
}

static inline u32 icmp_in2out (snat_main_t *sm,
                               vlib_buffer_t * b0,
                               ip4_header_t * ip0,
                               icmp46_header_t * icmp0,
                               u32 sw_if_index0,
                               u32 rx_fib_index0,
                               vlib_node_runtime_t * node,
                               u32 next0,
                               u32 thread_index,
                               void *d,
                               void *e)
{
  snat_session_key_t sm0;
  u8 protocol;
  icmp_echo_header_t *echo0, *inner_echo0 = 0;
  ip4_header_t *inner_ip0;
  void *l4_header = 0;
  icmp46_header_t *inner_icmp0;
  u8 dont_translate;
  u32 new_addr0, old_addr0;
  u16 old_id0, new_id0;
  ip_csum_t sum0;
  u16 checksum0;
  u32 next0_tmp;

  echo0 = (icmp_echo_header_t *)(icmp0+1);

  next0_tmp = sm->icmp_match_in2out_cb(sm, node, thread_index, b0, ip0,
                                       &protocol, &sm0, &dont_translate, d, e);
  if (next0_tmp != ~0)
    next0 = next0_tmp;
  if (next0 == SNAT_IN2OUT_NEXT_DROP || dont_translate)
    goto out;

  sum0 = ip_incremental_checksum (0, icmp0,
                                  ntohs(ip0->length) - ip4_header_bytes (ip0));
  checksum0 = ~ip_csum_fold (sum0);
  if (PREDICT_FALSE(checksum0 != 0 && checksum0 != 0xffff))
    {
      next0 = SNAT_IN2OUT_NEXT_DROP;
      goto out;
    }

  old_addr0 = ip0->src_address.as_u32;
  new_addr0 = ip0->src_address.as_u32 = sm0.addr.as_u32;
  if (vnet_buffer(b0)->sw_if_index[VLIB_TX] == ~0)
    vnet_buffer(b0)->sw_if_index[VLIB_TX] = sm0.fib_index;

  sum0 = ip0->checksum;
  sum0 = ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t,
                         src_address /* changed member */);
  ip0->checksum = ip_csum_fold (sum0);

  if (icmp0->checksum == 0)
    icmp0->checksum = 0xffff;

  if (!icmp_is_error_message (icmp0))
    {
      new_id0 = sm0.port;
      if (PREDICT_FALSE(new_id0 != echo0->identifier))
        {
          old_id0 = echo0->identifier;
          new_id0 = sm0.port;
          echo0->identifier = new_id0;

          sum0 = icmp0->checksum;
          sum0 = ip_csum_update (sum0, old_id0, new_id0, icmp_echo_header_t,
                                 identifier);
          icmp0->checksum = ip_csum_fold (sum0);
        }
    }
  else
    {
      inner_ip0 = (ip4_header_t *)(echo0+1);
      l4_header = ip4_next_header (inner_ip0);

      if (!ip4_header_checksum_is_valid (inner_ip0))
        {
          next0 = SNAT_IN2OUT_NEXT_DROP;
          goto out;
        }

      old_addr0 = inner_ip0->dst_address.as_u32;
      inner_ip0->dst_address = sm0.addr;
      new_addr0 = inner_ip0->dst_address.as_u32;

      sum0 = icmp0->checksum;
      sum0 = ip_csum_update (sum0, old_addr0, new_addr0, ip4_header_t,
                             dst_address /* changed member */);
      icmp0->checksum = ip_csum_fold (sum0);

      switch (protocol)
        {
          case SNAT_PROTOCOL_ICMP:
            inner_icmp0 = (icmp46_header_t*)l4_header;
            inner_echo0 = (icmp_echo_header_t *)(inner_icmp0+1);

            old_id0 = inner_echo0->identifier;
            new_id0 = sm0.port;
            inner_echo0->identifier = new_id0;

            sum0 = icmp0->checksum;
            sum0 = ip_csum_update (sum0, old_id0, new_id0, icmp_echo_header_t,
                                   identifier);
            icmp0->checksum = ip_csum_fold (sum0);
            break;
          case SNAT_PROTOCOL_UDP:
          case SNAT_PROTOCOL_TCP:
            old_id0 = ((tcp_udp_header_t*)l4_header)->dst_port;
            new_id0 = sm0.port;
            ((tcp_udp_header_t*)l4_header)->dst_port = new_id0;

            sum0 = icmp0->checksum;
            sum0 = ip_csum_update (sum0, old_id0, new_id0, tcp_udp_header_t,
                                   dst_port);
            icmp0->checksum = ip_csum_fold (sum0);
            break;
          default:
            ASSERT(0);
        }
    }

out:
  return next0;
}

/**
 * @brief Hairpinning
 *
 * Hairpinning allows two endpoints on the internal side of the NAT to
 * communicate even if they only use each other's external IP addresses
 * and ports.
 *
 * @param sm     NAT main.
 * @param b0     Vlib buffer.
 * @param ip0    IP header.
 * @param udp0   UDP header.
 * @param tcp0   TCP header.
 * @param proto0 NAT protocol.
 */
static inline int
snat_hairpinning (snat_main_t *sm,
                  vlib_buffer_t * b0,
                  ip4_header_t * ip0,
                  udp_header_t * udp0,
                  tcp_header_t * tcp0,
                  u32 proto0)
{
  snat_session_key_t key0, sm0;
  snat_session_t * s0;
  clib_bihash_kv_8_8_t kv0, value0;
  ip_csum_t sum0;
  u32 new_dst_addr0 = 0, old_dst_addr0, ti = 0, si;
  u16 new_dst_port0, old_dst_port0;

  key0.addr = ip0->dst_address;
  key0.port = udp0->dst_port;
  key0.protocol = proto0;
  key0.fib_index = sm->outside_fib_index;
  kv0.key = key0.as_u64;

  /* Check if destination is static mappings */
  if (!snat_static_mapping_match(sm, key0, &sm0, 1, 0, 0))
    {
      new_dst_addr0 = sm0.addr.as_u32;
      new_dst_port0 = sm0.port;
      vnet_buffer(b0)->sw_if_index[VLIB_TX] = sm0.fib_index;
    }
  /* or active session */
  else
    {
      if (sm->num_workers > 1)
        ti = (clib_net_to_host_u16 (udp0->dst_port) - 1024) / sm->port_per_thread;
      else
        ti = sm->num_workers;

      if (!clib_bihash_search_8_8 (&sm->per_thread_data[ti].out2in, &kv0, &value0))
        {
          si = value0.value;

          s0 = pool_elt_at_index (sm->per_thread_data[ti].sessions, si);
          new_dst_addr0 = s0->in2out.addr.as_u32;
          new_dst_port0 = s0->in2out.port;
          vnet_buffer(b0)->sw_if_index[VLIB_TX] = s0->in2out.fib_index;
        }
    }

  /* Destination is behind the same NAT, use internal address and port */
  if (new_dst_addr0)
    {
      old_dst_addr0 = ip0->dst_address.as_u32;
      ip0->dst_address.as_u32 = new_dst_addr0;
      sum0 = ip0->checksum;
      sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                             ip4_header_t, dst_address);
      ip0->checksum = ip_csum_fold (sum0);

      old_dst_port0 = tcp0->dst;
      if (PREDICT_TRUE(new_dst_port0 != old_dst_port0))
        {
          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              tcp0->dst = new_dst_port0;
              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                                     ip4_header_t, dst_address);
              sum0 = ip_csum_update (sum0, old_dst_port0, new_dst_port0,
                                     ip4_header_t /* cheat */, length);
              tcp0->checksum = ip_csum_fold(sum0);
            }
          else
            {
              udp0->dst_port = new_dst_port0;
              udp0->checksum = 0;
            }
        }
      else
        {
          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                                     ip4_header_t, dst_address);
              tcp0->checksum = ip_csum_fold(sum0);
            }
        }
      return 1;
    }
  return 0;
}

static inline void
snat_icmp_hairpinning (snat_main_t *sm,
                       vlib_buffer_t * b0,
                       ip4_header_t * ip0,
                       icmp46_header_t * icmp0)
{
  snat_session_key_t key0, sm0;
  clib_bihash_kv_8_8_t kv0, value0;
  u32 new_dst_addr0 = 0, old_dst_addr0, si, ti = 0;
  ip_csum_t sum0;
  snat_session_t *s0;

  if (!icmp_is_error_message (icmp0))
    {
      icmp_echo_header_t *echo0 = (icmp_echo_header_t *)(icmp0+1);
      u16 icmp_id0 = echo0->identifier;
      key0.addr = ip0->dst_address;
      key0.port = icmp_id0;
      key0.protocol = SNAT_PROTOCOL_ICMP;
      key0.fib_index = sm->outside_fib_index;
      kv0.key = key0.as_u64;

      if (sm->num_workers > 1)
        ti = (clib_net_to_host_u16 (icmp_id0) - 1024) / sm->port_per_thread;
      else
        ti = sm->num_workers;

      /* Check if destination is in active sessions */
      if (clib_bihash_search_8_8 (&sm->per_thread_data[ti].out2in, &kv0,
                                  &value0))
        {
          /* or static mappings */
          if (!snat_static_mapping_match(sm, key0, &sm0, 1, 0, 0))
            {
              new_dst_addr0 = sm0.addr.as_u32;
              vnet_buffer(b0)->sw_if_index[VLIB_TX] = sm0.fib_index;
            }
        }
      else
        {
          si = value0.value;

          s0 = pool_elt_at_index (sm->per_thread_data[ti].sessions, si);
          new_dst_addr0 = s0->in2out.addr.as_u32;
          vnet_buffer(b0)->sw_if_index[VLIB_TX] = s0->in2out.fib_index;
          echo0->identifier = s0->in2out.port;
          sum0 = icmp0->checksum;
          sum0 = ip_csum_update (sum0, icmp_id0, s0->in2out.port,
                                 icmp_echo_header_t, identifier);
          icmp0->checksum = ip_csum_fold (sum0);
        }

      /* Destination is behind the same NAT, use internal address and port */
      if (new_dst_addr0)
        {
          old_dst_addr0 = ip0->dst_address.as_u32;
          ip0->dst_address.as_u32 = new_dst_addr0;
          sum0 = ip0->checksum;
          sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                                 ip4_header_t, dst_address);
          ip0->checksum = ip_csum_fold (sum0);
        }
    }

}

static inline u32 icmp_in2out_slow_path (snat_main_t *sm,
                                         vlib_buffer_t * b0,
                                         ip4_header_t * ip0,
                                         icmp46_header_t * icmp0,
                                         u32 sw_if_index0,
                                         u32 rx_fib_index0,
                                         vlib_node_runtime_t * node,
                                         u32 next0,
                                         f64 now,
                                         u32 thread_index,
                                         snat_session_t ** p_s0)
{
  next0 = icmp_in2out(sm, b0, ip0, icmp0, sw_if_index0, rx_fib_index0, node,
                      next0, thread_index, p_s0, 0);
  snat_session_t * s0 = *p_s0;
  if (PREDICT_TRUE(next0 != SNAT_IN2OUT_NEXT_DROP && s0))
    {
      /* Hairpinning */
      if (vnet_buffer(b0)->sw_if_index[VLIB_TX] == 0)
        snat_icmp_hairpinning(sm, b0, ip0, icmp0);
      /* Accounting */
      s0->last_heard = now;
      s0->total_pkts++;
      s0->total_bytes += vlib_buffer_length_in_chain (sm->vlib_main, b0);
      /* Per-user LRU list maintenance */
      clib_dlist_remove (sm->per_thread_data[thread_index].list_pool,
                         s0->per_user_index);
      clib_dlist_addtail (sm->per_thread_data[thread_index].list_pool,
                          s0->per_user_list_head_index,
                          s0->per_user_index);
    }
  return next0;
}
static inline void
snat_hairpinning_unknown_proto (snat_main_t *sm,
                                vlib_buffer_t * b,
                                ip4_header_t * ip)
{
  u32 old_addr, new_addr = 0, ti = 0;
  clib_bihash_kv_8_8_t kv, value;
  clib_bihash_kv_16_8_t s_kv, s_value;
  nat_ed_ses_key_t key;
  snat_session_key_t m_key;
  snat_static_mapping_t *m;
  ip_csum_t sum;
  snat_session_t *s;

  old_addr = ip->dst_address.as_u32;
  key.l_addr.as_u32 = ip->dst_address.as_u32;
  key.r_addr.as_u32 = ip->src_address.as_u32;
  key.fib_index = sm->outside_fib_index;
  key.proto = ip->protocol;
  key.r_port = 0;
  key.l_port = 0;
  s_kv.key[0] = key.as_u64[0];
  s_kv.key[1] = key.as_u64[1];
  if (clib_bihash_search_16_8 (&sm->out2in_ed, &s_kv, &s_value))
    {
      m_key.addr = ip->dst_address;
      m_key.fib_index = sm->outside_fib_index;
      m_key.port = 0;
      m_key.protocol = 0;
      kv.key = m_key.as_u64;
      if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
        return;

      m = pool_elt_at_index (sm->static_mappings, value.value);
      if (vnet_buffer(b)->sw_if_index[VLIB_TX] == ~0)
        vnet_buffer(b)->sw_if_index[VLIB_TX] = m->fib_index;
      new_addr = ip->dst_address.as_u32 = m->local_addr.as_u32;
    }
  else
    {
      if (sm->num_workers > 1)
        ti = sm->worker_out2in_cb (ip, sm->outside_fib_index);
      else
        ti = sm->num_workers;

      s = pool_elt_at_index (sm->per_thread_data[ti].sessions, s_value.value);
      if (vnet_buffer(b)->sw_if_index[VLIB_TX] == ~0)
        vnet_buffer(b)->sw_if_index[VLIB_TX] = s->in2out.fib_index;
      new_addr = ip->dst_address.as_u32 = s->in2out.addr.as_u32;
    }
  sum = ip->checksum;
  sum = ip_csum_update (sum, old_addr, new_addr, ip4_header_t, dst_address);
  ip->checksum = ip_csum_fold (sum);
}

static snat_session_t *
snat_in2out_unknown_proto (snat_main_t *sm,
                           vlib_buffer_t * b,
                           ip4_header_t * ip,
                           u32 rx_fib_index,
                           u32 thread_index,
                           f64 now,
                           vlib_main_t * vm,
                           vlib_node_runtime_t * node)
{
  clib_bihash_kv_8_8_t kv, value;
  clib_bihash_kv_16_8_t s_kv, s_value;
  snat_static_mapping_t *m;
  snat_session_key_t m_key;
  u32 old_addr, new_addr = 0;
  ip_csum_t sum;
  snat_user_t *u;
  dlist_elt_t *head, *elt;
  snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
  u32 elt_index, head_index, ses_index;
  snat_session_t * s;
  nat_ed_ses_key_t key;
  u32 address_index = ~0;
  int i;
  u8 is_sm = 0;

  old_addr = ip->src_address.as_u32;

  key.l_addr = ip->src_address;
  key.r_addr = ip->dst_address;
  key.fib_index = rx_fib_index;
  key.proto = ip->protocol;
  key.l_port = 0;
  key.r_port = 0;
  s_kv.key[0] = key.as_u64[0];
  s_kv.key[1] = key.as_u64[1];

  if (!clib_bihash_search_16_8 (&sm->in2out_ed, &s_kv, &s_value))
    {
      s = pool_elt_at_index (tsm->sessions, s_value.value);
      new_addr = ip->src_address.as_u32 = s->out2in.addr.as_u32;
    }
  else
    {
      if (PREDICT_FALSE (maximum_sessions_exceeded(sm, thread_index)))
        {
          b->error = node->errors[SNAT_IN2OUT_ERROR_MAX_SESSIONS_EXCEEDED];
          nat_ipfix_logging_max_sessions(sm->max_translations);
          return 0;
        }

      u = nat_user_get_or_create (sm, &ip->src_address, rx_fib_index,
                                  thread_index);
      if (!u)
        {
          clib_warning ("create NAT user failed");
          return 0;
        }

      m_key.addr = ip->src_address;
      m_key.port = 0;
      m_key.protocol = 0;
      m_key.fib_index = rx_fib_index;
      kv.key = m_key.as_u64;

      /* Try to find static mapping first */
      if (!clib_bihash_search_8_8 (&sm->static_mapping_by_local, &kv, &value))
        {
          m = pool_elt_at_index (sm->static_mappings, value.value);
          new_addr = ip->src_address.as_u32 = m->external_addr.as_u32;
          is_sm = 1;
          goto create_ses;
        }
      /* Fallback to 3-tuple key */
      else
        {
          /* Choose same out address as for TCP/UDP session to same destination */
          if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
            {
              head_index = u->sessions_per_user_list_head_index;
              head = pool_elt_at_index (tsm->list_pool, head_index);
              elt_index = head->next;
              elt = pool_elt_at_index (tsm->list_pool, elt_index);
              ses_index = elt->value;
              while (ses_index != ~0)
                {
                  s =  pool_elt_at_index (tsm->sessions, ses_index);
                  elt_index = elt->next;
                  elt = pool_elt_at_index (tsm->list_pool, elt_index);
                  ses_index = elt->value;

                  if (s->ext_host_addr.as_u32 == ip->dst_address.as_u32)
                    {
                      new_addr = ip->src_address.as_u32 = s->out2in.addr.as_u32;
                      address_index = s->outside_address_index;

                      key.fib_index = sm->outside_fib_index;
                      key.l_addr.as_u32 = new_addr;
                      s_kv.key[0] = key.as_u64[0];
                      s_kv.key[1] = key.as_u64[1];
                      if (clib_bihash_search_16_8 (&sm->out2in_ed, &s_kv, &s_value))
                        break;

                      goto create_ses;
                    }
                }
            }
          key.fib_index = sm->outside_fib_index;
          for (i = 0; i < vec_len (sm->addresses); i++)
            {
              key.l_addr.as_u32 = sm->addresses[i].addr.as_u32;
              s_kv.key[0] = key.as_u64[0];
              s_kv.key[1] = key.as_u64[1];
              if (clib_bihash_search_16_8 (&sm->out2in_ed, &s_kv, &s_value))
                {
                  new_addr = ip->src_address.as_u32 = key.l_addr.as_u32;
                  address_index = i;
                  goto create_ses;
                }
            }
          return 0;
        }

create_ses:
      s = nat_session_alloc_or_recycle (sm, u, thread_index);
      if (!s)
        {
          clib_warning ("create NAT session failed");
          return 0;
        }

      s->ext_host_addr.as_u32 = ip->dst_address.as_u32;
      s->flags |= SNAT_SESSION_FLAG_UNKNOWN_PROTO;
      s->outside_address_index = address_index;
      s->out2in.addr.as_u32 = new_addr;
      s->out2in.fib_index = sm->outside_fib_index;
      s->in2out.addr.as_u32 = old_addr;
      s->in2out.fib_index = rx_fib_index;
      s->in2out.port = s->out2in.port = ip->protocol;
      if (is_sm)
	s->flags |= SNAT_SESSION_FLAG_STATIC_MAPPING;
      user_session_increment (sm, u, is_sm);

      /* Add to lookup tables */
      key.l_addr.as_u32 = old_addr;
      key.r_addr = ip->dst_address;
      key.proto = ip->protocol;
      key.fib_index = rx_fib_index;
      s_kv.key[0] = key.as_u64[0];
      s_kv.key[1] = key.as_u64[1];
      s_kv.value = s - tsm->sessions;
      if (clib_bihash_add_del_16_8 (&sm->in2out_ed, &s_kv, 1))
        clib_warning ("in2out key add failed");

      key.l_addr.as_u32 = new_addr;
      key.fib_index = sm->outside_fib_index;
      s_kv.key[0] = key.as_u64[0];
      s_kv.key[1] = key.as_u64[1];
      if (clib_bihash_add_del_16_8 (&sm->out2in_ed, &s_kv, 1))
        clib_warning ("out2in key add failed");
  }

  /* Update IP checksum */
  sum = ip->checksum;
  sum = ip_csum_update (sum, old_addr, new_addr, ip4_header_t, src_address);
  ip->checksum = ip_csum_fold (sum);

  /* Accounting */
  s->last_heard = now;
  s->total_pkts++;
  s->total_bytes += vlib_buffer_length_in_chain (vm, b);
  /* Per-user LRU list maintenance */
  clib_dlist_remove (tsm->list_pool, s->per_user_index);
  clib_dlist_addtail (tsm->list_pool, s->per_user_list_head_index,
                      s->per_user_index);

  /* Hairpinning */
  if (vnet_buffer(b)->sw_if_index[VLIB_TX] == ~0)
    snat_hairpinning_unknown_proto(sm, b, ip);

  if (vnet_buffer(b)->sw_if_index[VLIB_TX] == ~0)
    vnet_buffer(b)->sw_if_index[VLIB_TX] = sm->outside_fib_index;

  return s;
}

static snat_session_t *
snat_in2out_lb (snat_main_t *sm,
                vlib_buffer_t * b,
                ip4_header_t * ip,
                u32 rx_fib_index,
                u32 thread_index,
                f64 now,
                vlib_main_t * vm,
                vlib_node_runtime_t * node)
{
  nat_ed_ses_key_t key;
  clib_bihash_kv_16_8_t s_kv, s_value;
  udp_header_t *udp = ip4_next_header (ip);
  tcp_header_t *tcp = (tcp_header_t *) udp;
  snat_session_t *s = 0;
  snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
  u32 old_addr, new_addr;
  u16 new_port, old_port;
  ip_csum_t sum;
  u32 proto = ip_proto_to_snat_proto (ip->protocol);
  snat_session_key_t e_key, l_key;
  snat_user_t *u;

  old_addr = ip->src_address.as_u32;

  key.l_addr = ip->src_address;
  key.r_addr = ip->dst_address;
  key.fib_index = rx_fib_index;
  key.proto = ip->protocol;
  key.r_port = udp->dst_port;
  key.l_port = udp->src_port;
  s_kv.key[0] = key.as_u64[0];
  s_kv.key[1] = key.as_u64[1];

  if (!clib_bihash_search_16_8 (&sm->in2out_ed, &s_kv, &s_value))
    {
      if (s_value.value == ~0ULL)
        return 0;
      s = pool_elt_at_index (tsm->sessions, s_value.value);
    }
  else
    {
      if (PREDICT_FALSE (maximum_sessions_exceeded (sm, thread_index)))
        {
          b->error = node->errors[SNAT_IN2OUT_ERROR_MAX_SESSIONS_EXCEEDED];
          nat_ipfix_logging_max_sessions(sm->max_translations);
          return 0;
        }

      l_key.addr = ip->src_address;
      l_key.port = udp->src_port;
      l_key.protocol = proto;
      l_key.fib_index = rx_fib_index;
      if (snat_static_mapping_match(sm, l_key, &e_key, 0, 0, 0))
        return 0;

      u = nat_user_get_or_create (sm, &ip->src_address, rx_fib_index,
                                  thread_index);
      if (!u)
        {
          clib_warning ("create NAT user failed");
          return 0;
        }

      s = nat_session_alloc_or_recycle (sm, u, thread_index);
      if (!s)
        {
          clib_warning ("create NAT session failed");
          return 0;
        }

      s->ext_host_addr.as_u32 = ip->dst_address.as_u32;
      s->flags |= SNAT_SESSION_FLAG_STATIC_MAPPING;
      s->flags |= SNAT_SESSION_FLAG_LOAD_BALANCING;
      s->outside_address_index = ~0;
      s->in2out = l_key;
      s->out2in = e_key;
      s->out2in.protocol = l_key.protocol;
      user_session_increment (sm, u, 1 /* static */);

      /* Add to lookup tables */
      s_kv.value = s - tsm->sessions;
      if (clib_bihash_add_del_16_8 (&sm->in2out_ed, &s_kv, 1))
        clib_warning ("in2out-ed key add failed");

      key.l_addr = e_key.addr;
      key.fib_index = e_key.fib_index;
      key.l_port = e_key.port;
      s_kv.key[0] = key.as_u64[0];
      s_kv.key[1] = key.as_u64[1];
      if (clib_bihash_add_del_16_8 (&sm->out2in_ed, &s_kv, 1))
        clib_warning ("out2in-ed key add failed");
    }

  new_addr = ip->src_address.as_u32 = s->out2in.addr.as_u32;

  /* Update IP checksum */
  sum = ip->checksum;
  sum = ip_csum_update (sum, old_addr, new_addr, ip4_header_t, src_address);
  if (is_twice_nat_session (s))
    sum = ip_csum_update (sum, ip->dst_address.as_u32,
                          s->ext_host_addr.as_u32, ip4_header_t, dst_address);
  ip->checksum = ip_csum_fold (sum);

  if (PREDICT_TRUE(proto == SNAT_PROTOCOL_TCP))
    {
      old_port = tcp->src_port;
      tcp->src_port = s->out2in.port;
      new_port = tcp->src_port;

      sum = tcp->checksum;
      sum = ip_csum_update (sum, old_addr, new_addr, ip4_header_t, src_address);
      sum = ip_csum_update (sum, old_port, new_port, ip4_header_t, length);
      if (is_twice_nat_session (s))
        {
          sum = ip_csum_update (sum, ip->dst_address.as_u32,
                                s->ext_host_addr.as_u32, ip4_header_t,
                                dst_address);
          sum = ip_csum_update (sum, tcp->dst_port, s->ext_host_port,
                                ip4_header_t, length);
          tcp->dst_port = s->ext_host_port;
          ip->dst_address.as_u32 = s->ext_host_addr.as_u32;
        }
      tcp->checksum = ip_csum_fold(sum);
    }
  else
    {
      udp->src_port = s->out2in.port;
      if (is_twice_nat_session (s))
        {
          udp->dst_port = s->ext_host_port;
          ip->dst_address.as_u32 = s->ext_host_addr.as_u32;
        }
      udp->checksum = 0;
    }

  if (vnet_buffer(b)->sw_if_index[VLIB_TX] == ~0)
    vnet_buffer(b)->sw_if_index[VLIB_TX] = sm->outside_fib_index;

  /* Accounting */
  s->last_heard = now;
  s->total_pkts++;
  s->total_bytes += vlib_buffer_length_in_chain (vm, b);
  /* Per-user LRU list maintenance */
  clib_dlist_remove (tsm->list_pool, s->per_user_index);
  clib_dlist_addtail (tsm->list_pool, s->per_user_list_head_index,
                      s->per_user_index);
  return s;
}

static inline uword
snat_in2out_node_fn_inline (vlib_main_t * vm,
                            vlib_node_runtime_t * node,
                            vlib_frame_t * frame, int is_slow_path,
                            int is_output_feature)
{
  u32 n_left_from, * from, * to_next;
  snat_in2out_next_t next_index;
  u32 pkts_processed = 0;
  snat_main_t * sm = &snat_main;
  f64 now = vlib_time_now (vm);
  u32 stats_node_index;
  u32 thread_index = vlib_get_thread_index ();

  stats_node_index = is_slow_path ? snat_in2out_slowpath_node.index :
    snat_in2out_node.index;

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;
  next_index = node->cached_next_index;

  while (n_left_from > 0)
    {
      u32 n_left_to_next;

      vlib_get_next_frame (vm, node, next_index,
			   to_next, n_left_to_next);

      while (n_left_from >= 4 && n_left_to_next >= 2)
	{
          u32 bi0, bi1;
	  vlib_buffer_t * b0, * b1;
          u32 next0, next1;
          u32 sw_if_index0, sw_if_index1;
          ip4_header_t * ip0, * ip1;
          ip_csum_t sum0, sum1;
          u32 new_addr0, old_addr0, new_addr1, old_addr1;
          u16 old_port0, new_port0, old_port1, new_port1;
          udp_header_t * udp0, * udp1;
          tcp_header_t * tcp0, * tcp1;
          icmp46_header_t * icmp0, * icmp1;
          snat_session_key_t key0, key1;
          u32 rx_fib_index0, rx_fib_index1;
          u32 proto0, proto1;
          snat_session_t * s0 = 0, * s1 = 0;
          clib_bihash_kv_8_8_t kv0, value0, kv1, value1;
          u32 iph_offset0 = 0, iph_offset1 = 0;

	  /* Prefetch next iteration. */
	  {
	    vlib_buffer_t * p2, * p3;

	    p2 = vlib_get_buffer (vm, from[2]);
	    p3 = vlib_get_buffer (vm, from[3]);

	    vlib_prefetch_buffer_header (p2, LOAD);
	    vlib_prefetch_buffer_header (p3, LOAD);

	    CLIB_PREFETCH (p2->data, CLIB_CACHE_LINE_BYTES, STORE);
	    CLIB_PREFETCH (p3->data, CLIB_CACHE_LINE_BYTES, STORE);
	  }

          /* speculatively enqueue b0 and b1 to the current next frame */
	  to_next[0] = bi0 = from[0];
	  to_next[1] = bi1 = from[1];
	  from += 2;
	  to_next += 2;
	  n_left_from -= 2;
	  n_left_to_next -= 2;

	  b0 = vlib_get_buffer (vm, bi0);
	  b1 = vlib_get_buffer (vm, bi1);

          if (is_output_feature)
            iph_offset0 = vnet_buffer (b0)->ip.save_rewrite_length;

          ip0 = (ip4_header_t *) ((u8 *) vlib_buffer_get_current (b0) +
                 iph_offset0);

          udp0 = ip4_next_header (ip0);
          tcp0 = (tcp_header_t *) udp0;
          icmp0 = (icmp46_header_t *) udp0;

          sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
	  rx_fib_index0 = vec_elt (sm->ip4_main->fib_index_by_sw_if_index,
                                   sw_if_index0);

          next0 = next1 = SNAT_IN2OUT_NEXT_LOOKUP;

          if (PREDICT_FALSE(ip0->ttl == 1))
            {
              vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
              icmp4_error_set_vnet_buffer (b0, ICMP4_time_exceeded,
                                           ICMP4_time_exceeded_ttl_exceeded_in_transit,
                                           0);
              next0 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
              goto trace00;
            }

          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          /* Next configured feature, probably ip4-lookup */
          if (is_slow_path)
            {
              if (PREDICT_FALSE (proto0 == ~0))
                {
                  s0 = snat_in2out_unknown_proto (sm, b0, ip0, rx_fib_index0,
                                                  thread_index, now, vm, node);
                  if (!s0)
                    next0 = SNAT_IN2OUT_NEXT_DROP;
                  goto trace00;
                }

              if (PREDICT_FALSE (proto0 == SNAT_PROTOCOL_ICMP))
                {
                  next0 = icmp_in2out_slow_path
                    (sm, b0, ip0, icmp0, sw_if_index0, rx_fib_index0,
                     node, next0, now, thread_index, &s0);
                  goto trace00;
                }
            }
          else
            {
              if (is_output_feature)
                {
                  if (PREDICT_FALSE(nat_not_translate_output_feature_fwd(sm, ip0)))
                    goto trace00;
                }

              if (PREDICT_FALSE (proto0 == ~0 || proto0 == SNAT_PROTOCOL_ICMP))
                {
                  next0 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                  goto trace00;
                }

              if (ip4_is_fragment (ip0))
                {
                  next0 = SNAT_IN2OUT_NEXT_REASS;
                  goto trace00;
                }
            }

          key0.addr = ip0->src_address;
          key0.port = udp0->src_port;
          key0.protocol = proto0;
          key0.fib_index = rx_fib_index0;

          kv0.key = key0.as_u64;

          if (PREDICT_FALSE (clib_bihash_search_8_8 (
              &sm->per_thread_data[thread_index].in2out, &kv0, &value0) != 0))
            {
              if (is_slow_path)
                {
                  if (is_output_feature)
                    {
                      if (PREDICT_FALSE(nat_not_translate_output_feature(sm,
                          ip0, proto0, udp0->src_port, udp0->dst_port, thread_index, sw_if_index0)))
                        goto trace00;
                    }
                  else
                    {
                      if (PREDICT_FALSE(snat_not_translate(sm, node, sw_if_index0,
                          ip0, proto0, rx_fib_index0, thread_index)))
                        goto trace00;
                    }

                  next0 = slow_path (sm, b0, ip0, rx_fib_index0, &key0,
                                     &s0, node, next0, thread_index);
                  if (PREDICT_FALSE (next0 == SNAT_IN2OUT_NEXT_DROP))
                    goto trace00;
                }
              else
                {
                  next0 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                  goto trace00;
                }
            }
          else
            {
              if (PREDICT_FALSE (value0.value == ~0ULL))
                {
                  if (is_slow_path)
                    {
                      s0 = snat_in2out_lb(sm, b0, ip0, rx_fib_index0,
                                          thread_index, now, vm, node);
                      if (!s0 && !sm->forwarding_enabled)
                        next0 = SNAT_IN2OUT_NEXT_DROP;
                      goto trace00;
                    }
                  else
                    {
                      next0 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                      goto trace00;
                    }
                }
              else
                {
                  s0 = pool_elt_at_index (
                    sm->per_thread_data[thread_index].sessions,
                    value0.value);
                }
            }

          b0->flags |= VNET_BUFFER_F_IS_NATED;

          old_addr0 = ip0->src_address.as_u32;
          ip0->src_address = s0->out2in.addr;
          new_addr0 = ip0->src_address.as_u32;
          if (!is_output_feature)
            vnet_buffer(b0)->sw_if_index[VLIB_TX] = s0->out2in.fib_index;

          sum0 = ip0->checksum;
          sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip0->checksum = ip_csum_fold (sum0);

          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              old_port0 = tcp0->src_port;
              tcp0->src_port = s0->out2in.port;
              new_port0 = tcp0->src_port;

              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                     ip4_header_t,
                                     dst_address /* changed member */);
              sum0 = ip_csum_update (sum0, old_port0, new_port0,
                                     ip4_header_t /* cheat */,
                                     length /* changed member */);
              tcp0->checksum = ip_csum_fold(sum0);
            }
          else
            {
              old_port0 = udp0->src_port;
              udp0->src_port = s0->out2in.port;
              udp0->checksum = 0;
            }

          /* Accounting */
          s0->last_heard = now;
          s0->total_pkts++;
          s0->total_bytes += vlib_buffer_length_in_chain (vm, b0);
          /* Per-user LRU list maintenance */
          clib_dlist_remove (sm->per_thread_data[thread_index].list_pool,
                             s0->per_user_index);
          clib_dlist_addtail (sm->per_thread_data[thread_index].list_pool,
                              s0->per_user_list_head_index,
                              s0->per_user_index);
        trace00:

          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
            {
              snat_in2out_trace_t *t =
                 vlib_add_trace (vm, node, b0, sizeof (*t));
              t->is_slow_path = is_slow_path;
              t->sw_if_index = sw_if_index0;
              t->next_index = next0;
                  t->session_index = ~0;
              if (s0)
                t->session_index = s0 - sm->per_thread_data[thread_index].sessions;
            }

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          if (is_output_feature)
            iph_offset1 = vnet_buffer (b1)->ip.save_rewrite_length;

          ip1 = (ip4_header_t *) ((u8 *) vlib_buffer_get_current (b1) +
                 iph_offset1);

          udp1 = ip4_next_header (ip1);
          tcp1 = (tcp_header_t *) udp1;
          icmp1 = (icmp46_header_t *) udp1;

          sw_if_index1 = vnet_buffer(b1)->sw_if_index[VLIB_RX];
	  rx_fib_index1 = vec_elt (sm->ip4_main->fib_index_by_sw_if_index,
                                   sw_if_index1);

          if (PREDICT_FALSE(ip1->ttl == 1))
            {
              vnet_buffer (b1)->sw_if_index[VLIB_TX] = (u32) ~ 0;
              icmp4_error_set_vnet_buffer (b1, ICMP4_time_exceeded,
                                           ICMP4_time_exceeded_ttl_exceeded_in_transit,
                                           0);
              next1 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
              goto trace01;
            }

          proto1 = ip_proto_to_snat_proto (ip1->protocol);

          /* Next configured feature, probably ip4-lookup */
          if (is_slow_path)
            {
              if (PREDICT_FALSE (proto1 == ~0))
                {
                  s1 = snat_in2out_unknown_proto (sm, b1, ip1, rx_fib_index1,
                                                  thread_index, now, vm, node);
                  if (!s1)
                    next1 = SNAT_IN2OUT_NEXT_DROP;
                  goto trace01;
                }

              if (PREDICT_FALSE (proto1 == SNAT_PROTOCOL_ICMP))
                {
                  next1 = icmp_in2out_slow_path
                    (sm, b1, ip1, icmp1, sw_if_index1, rx_fib_index1, node,
                     next1, now, thread_index, &s1);
                  goto trace01;
                }
            }
          else
            {
              if (is_output_feature)
                {
                  if (PREDICT_FALSE(nat_not_translate_output_feature_fwd(sm, ip1)))
                    goto trace01;
                }

              if (PREDICT_FALSE (proto1 == ~0 || proto1 == SNAT_PROTOCOL_ICMP))
                {
                  next1 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                  goto trace01;
                }

              if (ip4_is_fragment (ip1))
                {
                  next1 = SNAT_IN2OUT_NEXT_REASS;
                  goto trace01;
                }
            }

          key1.addr = ip1->src_address;
          key1.port = udp1->src_port;
          key1.protocol = proto1;
          key1.fib_index = rx_fib_index1;

          kv1.key = key1.as_u64;

            if (PREDICT_FALSE(clib_bihash_search_8_8 (
                &sm->per_thread_data[thread_index].in2out, &kv1, &value1) != 0))
            {
              if (is_slow_path)
                {
                  if (is_output_feature)
                    {
                      if (PREDICT_FALSE(nat_not_translate_output_feature(sm,
                          ip1, proto1, udp1->src_port, udp1->dst_port, thread_index, sw_if_index1)))
                        goto trace01;
                    }
                  else
                    {
                      if (PREDICT_FALSE(snat_not_translate(sm, node, sw_if_index1,
                          ip1, proto1, rx_fib_index1, thread_index)))
                        goto trace01;
                    }

                  next1 = slow_path (sm, b1, ip1, rx_fib_index1, &key1,
                                     &s1, node, next1, thread_index);
                  if (PREDICT_FALSE (next1 == SNAT_IN2OUT_NEXT_DROP))
                    goto trace01;
                }
              else
                {
                  next1 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                  goto trace01;
                }
            }
          else
            {
              if (PREDICT_FALSE (value1.value == ~0ULL))
                {
                  if (is_slow_path)
                    {
                      s1 = snat_in2out_lb(sm, b1, ip1, rx_fib_index1,
                                          thread_index, now, vm, node);
                      if (!s1 && !sm->forwarding_enabled)
                        next1 = SNAT_IN2OUT_NEXT_DROP;
                      goto trace01;
                    }
                  else
                    {
                      next1 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                      goto trace01;
                    }
                }
              else
                {
                  s1 = pool_elt_at_index (
                    sm->per_thread_data[thread_index].sessions,
                    value1.value);
                }
            }

          b1->flags |= VNET_BUFFER_F_IS_NATED;

          old_addr1 = ip1->src_address.as_u32;
          ip1->src_address = s1->out2in.addr;
          new_addr1 = ip1->src_address.as_u32;
          if (!is_output_feature)
            vnet_buffer(b1)->sw_if_index[VLIB_TX] = s1->out2in.fib_index;

          sum1 = ip1->checksum;
          sum1 = ip_csum_update (sum1, old_addr1, new_addr1,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip1->checksum = ip_csum_fold (sum1);

          if (PREDICT_TRUE(proto1 == SNAT_PROTOCOL_TCP))
            {
              old_port1 = tcp1->src_port;
              tcp1->src_port = s1->out2in.port;
              new_port1 = tcp1->src_port;

              sum1 = tcp1->checksum;
              sum1 = ip_csum_update (sum1, old_addr1, new_addr1,
                                     ip4_header_t,
                                     dst_address /* changed member */);
              sum1 = ip_csum_update (sum1, old_port1, new_port1,
                                     ip4_header_t /* cheat */,
                                     length /* changed member */);
              tcp1->checksum = ip_csum_fold(sum1);
            }
          else
            {
              old_port1 = udp1->src_port;
              udp1->src_port = s1->out2in.port;
              udp1->checksum = 0;
            }

          /* Accounting */
          s1->last_heard = now;
          s1->total_pkts++;
          s1->total_bytes += vlib_buffer_length_in_chain (vm, b1);
          /* Per-user LRU list maintenance */
          clib_dlist_remove (sm->per_thread_data[thread_index].list_pool,
                             s1->per_user_index);
          clib_dlist_addtail (sm->per_thread_data[thread_index].list_pool,
                              s1->per_user_list_head_index,
                              s1->per_user_index);
        trace01:

          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b1->flags & VLIB_BUFFER_IS_TRACED)))
            {
              snat_in2out_trace_t *t =
                 vlib_add_trace (vm, node, b1, sizeof (*t));
              t->sw_if_index = sw_if_index1;
              t->next_index = next1;
              t->session_index = ~0;
              if (s1)
                t->session_index = s1 - sm->per_thread_data[thread_index].sessions;
            }

          pkts_processed += next1 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueues, maybe switch current next frame */
          vlib_validate_buffer_enqueue_x2 (vm, node, next_index,
                                           to_next, n_left_to_next,
                                           bi0, bi1, next0, next1);
        }

      while (n_left_from > 0 && n_left_to_next > 0)
	{
          u32 bi0;
	  vlib_buffer_t * b0;
          u32 next0;
          u32 sw_if_index0;
          ip4_header_t * ip0;
          ip_csum_t sum0;
          u32 new_addr0, old_addr0;
          u16 old_port0, new_port0;
          udp_header_t * udp0;
          tcp_header_t * tcp0;
          icmp46_header_t * icmp0;
          snat_session_key_t key0;
          u32 rx_fib_index0;
          u32 proto0;
          snat_session_t * s0 = 0;
          clib_bihash_kv_8_8_t kv0, value0;
          u32 iph_offset0 = 0;

          /* speculatively enqueue b0 to the current next frame */
	  bi0 = from[0];
	  to_next[0] = bi0;
	  from += 1;
	  to_next += 1;
	  n_left_from -= 1;
	  n_left_to_next -= 1;

	  b0 = vlib_get_buffer (vm, bi0);
          next0 = SNAT_IN2OUT_NEXT_LOOKUP;

          if (is_output_feature)
            iph_offset0 = vnet_buffer (b0)->ip.save_rewrite_length;

          ip0 = (ip4_header_t *) ((u8 *) vlib_buffer_get_current (b0) +
                 iph_offset0);

          udp0 = ip4_next_header (ip0);
          tcp0 = (tcp_header_t *) udp0;
          icmp0 = (icmp46_header_t *) udp0;

          sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
	  rx_fib_index0 = vec_elt (sm->ip4_main->fib_index_by_sw_if_index,
                                   sw_if_index0);

          if (PREDICT_FALSE(ip0->ttl == 1))
            {
              vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
              icmp4_error_set_vnet_buffer (b0, ICMP4_time_exceeded,
                                           ICMP4_time_exceeded_ttl_exceeded_in_transit,
                                           0);
              next0 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
              goto trace0;
            }

          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          /* Next configured feature, probably ip4-lookup */
          if (is_slow_path)
            {
              if (PREDICT_FALSE (proto0 == ~0))
                {
                  s0 = snat_in2out_unknown_proto (sm, b0, ip0, rx_fib_index0,
                                                  thread_index, now, vm, node);
                  if (!s0)
                    next0 = SNAT_IN2OUT_NEXT_DROP;
                  goto trace0;
                }

              if (PREDICT_FALSE (proto0 == SNAT_PROTOCOL_ICMP))
                {
                  next0 = icmp_in2out_slow_path
                    (sm, b0, ip0, icmp0, sw_if_index0, rx_fib_index0, node,
                     next0, now, thread_index, &s0);
                  goto trace0;
                }
            }
          else
            {
               if (is_output_feature)
                {
                  if (PREDICT_FALSE(nat_not_translate_output_feature_fwd(sm, ip0)))
                    goto trace0;
                }

              if (PREDICT_FALSE (proto0 == ~0 || proto0 == SNAT_PROTOCOL_ICMP))
                {
                  next0 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                  goto trace0;
                }

              if (ip4_is_fragment (ip0))
                {
                  next0 = SNAT_IN2OUT_NEXT_REASS;
                  goto trace0;
                }
            }

          key0.addr = ip0->src_address;
          key0.port = udp0->src_port;
          key0.protocol = proto0;
          key0.fib_index = rx_fib_index0;

          kv0.key = key0.as_u64;

          if (clib_bihash_search_8_8 (&sm->per_thread_data[thread_index].in2out,
                                      &kv0, &value0))
            {
              if (is_slow_path)
                {
                  if (is_output_feature)
                    {
                      if (PREDICT_FALSE(nat_not_translate_output_feature(sm,
                          ip0, proto0, udp0->src_port, udp0->dst_port, thread_index, sw_if_index0)))
                        goto trace0;
                    }
                  else
                    {
                      if (PREDICT_FALSE(snat_not_translate(sm, node, sw_if_index0,
                          ip0, proto0, rx_fib_index0, thread_index)))
                        goto trace0;
                    }

                  next0 = slow_path (sm, b0, ip0, rx_fib_index0, &key0,
                                     &s0, node, next0, thread_index);

                  if (PREDICT_FALSE (next0 == SNAT_IN2OUT_NEXT_DROP))
                    goto trace0;
                }
              else
                {
                  next0 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                  goto trace0;
                }
            }
          else
            {
              if (PREDICT_FALSE (value0.value == ~0ULL))
                {
                  if (is_slow_path)
                    {
                      s0 = snat_in2out_lb(sm, b0, ip0, rx_fib_index0,
                                          thread_index, now, vm, node);
                      if (!s0 && !sm->forwarding_enabled)
                        next0 = SNAT_IN2OUT_NEXT_DROP;
                      goto trace0;
                    }
                  else
                    {
                      next0 = SNAT_IN2OUT_NEXT_SLOW_PATH;
                      goto trace0;
                    }
                }
              else
                {
                  s0 = pool_elt_at_index (
                    sm->per_thread_data[thread_index].sessions,
                    value0.value);
                }
            }

          b0->flags |= VNET_BUFFER_F_IS_NATED;

          old_addr0 = ip0->src_address.as_u32;
          ip0->src_address = s0->out2in.addr;
          new_addr0 = ip0->src_address.as_u32;
          if (!is_output_feature)
            vnet_buffer(b0)->sw_if_index[VLIB_TX] = s0->out2in.fib_index;

          sum0 = ip0->checksum;
          sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip0->checksum = ip_csum_fold (sum0);

          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              old_port0 = tcp0->src_port;
              tcp0->src_port = s0->out2in.port;
              new_port0 = tcp0->src_port;

              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                     ip4_header_t,
                                     dst_address /* changed member */);
              sum0 = ip_csum_update (sum0, old_port0, new_port0,
                                     ip4_header_t /* cheat */,
                                     length /* changed member */);
              tcp0->checksum = ip_csum_fold(sum0);
            }
          else
            {
              old_port0 = udp0->src_port;
              udp0->src_port = s0->out2in.port;
              udp0->checksum = 0;
            }

          /* Accounting */
          s0->last_heard = now;
          s0->total_pkts++;
          s0->total_bytes += vlib_buffer_length_in_chain (vm, b0);
          /* Per-user LRU list maintenance */
          clib_dlist_remove (sm->per_thread_data[thread_index].list_pool,
                             s0->per_user_index);
          clib_dlist_addtail (sm->per_thread_data[thread_index].list_pool,
                              s0->per_user_list_head_index,
                              s0->per_user_index);

        trace0:
          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
            {
              snat_in2out_trace_t *t =
                 vlib_add_trace (vm, node, b0, sizeof (*t));
              t->is_slow_path = is_slow_path;
              t->sw_if_index = sw_if_index0;
              t->next_index = next0;
                  t->session_index = ~0;
              if (s0)
                t->session_index = s0 - sm->per_thread_data[thread_index].sessions;
            }

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueue, maybe switch current next frame */
	  vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
					   to_next, n_left_to_next,
					   bi0, next0);
	}

      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
    }

  vlib_node_increment_counter (vm, stats_node_index,
                               SNAT_IN2OUT_ERROR_IN2OUT_PACKETS,
                               pkts_processed);
  return frame->n_vectors;
}

static uword
snat_in2out_fast_path_fn (vlib_main_t * vm,
                          vlib_node_runtime_t * node,
                          vlib_frame_t * frame)
{
  return snat_in2out_node_fn_inline (vm, node, frame, 0 /* is_slow_path */, 0);
}

VLIB_REGISTER_NODE (snat_in2out_node) = {
  .function = snat_in2out_fast_path_fn,
  .name = "nat44-in2out",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,

  .runtime_data_bytes = sizeof (snat_runtime_t),

  .n_next_nodes = SNAT_IN2OUT_N_NEXT,

  /* edit / add dispositions here */
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
    [SNAT_IN2OUT_NEXT_SLOW_PATH] = "nat44-in2out-slowpath",
    [SNAT_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
    [SNAT_IN2OUT_NEXT_REASS] = "nat44-in2out-reass",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_in2out_node, snat_in2out_fast_path_fn);

static uword
snat_in2out_output_fast_path_fn (vlib_main_t * vm,
                                 vlib_node_runtime_t * node,
                                 vlib_frame_t * frame)
{
  return snat_in2out_node_fn_inline (vm, node, frame, 0 /* is_slow_path */, 1);
}

VLIB_REGISTER_NODE (snat_in2out_output_node) = {
  .function = snat_in2out_output_fast_path_fn,
  .name = "nat44-in2out-output",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,

  .runtime_data_bytes = sizeof (snat_runtime_t),

  .n_next_nodes = SNAT_IN2OUT_N_NEXT,

  /* edit / add dispositions here */
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "interface-output",
    [SNAT_IN2OUT_NEXT_SLOW_PATH] = "nat44-in2out-output-slowpath",
    [SNAT_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
    [SNAT_IN2OUT_NEXT_REASS] = "nat44-in2out-reass",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_in2out_output_node,
                              snat_in2out_output_fast_path_fn);

static uword
snat_in2out_slow_path_fn (vlib_main_t * vm,
                          vlib_node_runtime_t * node,
                          vlib_frame_t * frame)
{
  return snat_in2out_node_fn_inline (vm, node, frame, 1 /* is_slow_path */, 0);
}

VLIB_REGISTER_NODE (snat_in2out_slowpath_node) = {
  .function = snat_in2out_slow_path_fn,
  .name = "nat44-in2out-slowpath",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,

  .runtime_data_bytes = sizeof (snat_runtime_t),

  .n_next_nodes = SNAT_IN2OUT_N_NEXT,

  /* edit / add dispositions here */
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
    [SNAT_IN2OUT_NEXT_SLOW_PATH] = "nat44-in2out-slowpath",
    [SNAT_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
    [SNAT_IN2OUT_NEXT_REASS] = "nat44-in2out-reass",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_in2out_slowpath_node,
                              snat_in2out_slow_path_fn);

static uword
snat_in2out_output_slow_path_fn (vlib_main_t * vm,
                                 vlib_node_runtime_t * node,
                                 vlib_frame_t * frame)
{
  return snat_in2out_node_fn_inline (vm, node, frame, 1 /* is_slow_path */, 1);
}

VLIB_REGISTER_NODE (snat_in2out_output_slowpath_node) = {
  .function = snat_in2out_output_slow_path_fn,
  .name = "nat44-in2out-output-slowpath",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,

  .runtime_data_bytes = sizeof (snat_runtime_t),

  .n_next_nodes = SNAT_IN2OUT_N_NEXT,

  /* edit / add dispositions here */
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "interface-output",
    [SNAT_IN2OUT_NEXT_SLOW_PATH] = "nat44-in2out-output-slowpath",
    [SNAT_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
    [SNAT_IN2OUT_NEXT_REASS] = "nat44-in2out-reass",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_in2out_output_slowpath_node,
                              snat_in2out_output_slow_path_fn);

extern vnet_feature_arc_registration_t vnet_feat_arc_ip4_local;

static uword
nat44_hairpinning_fn (vlib_main_t * vm,
                      vlib_node_runtime_t * node,
                      vlib_frame_t * frame)
{
  u32 n_left_from, * from, * to_next;
  snat_in2out_next_t next_index;
  u32 pkts_processed = 0;
  snat_main_t * sm = &snat_main;
  vnet_feature_main_t *fm = &feature_main;
  u8 arc_index = vnet_feat_arc_ip4_local.feature_arc_index;
  vnet_feature_config_main_t *cm = &fm->feature_config_mains[arc_index];

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;
  next_index = node->cached_next_index;

  while (n_left_from > 0)
    {
      u32 n_left_to_next;

      vlib_get_next_frame (vm, node, next_index,
			   to_next, n_left_to_next);

      while (n_left_from > 0 && n_left_to_next > 0)
	{
          u32 bi0;
	  vlib_buffer_t * b0;
          u32 next0;
          ip4_header_t * ip0;
          u32 proto0;
          udp_header_t * udp0;
          tcp_header_t * tcp0;

          /* speculatively enqueue b0 to the current next frame */
	  bi0 = from[0];
	  to_next[0] = bi0;
	  from += 1;
	  to_next += 1;
	  n_left_from -= 1;
	  n_left_to_next -= 1;

	  b0 = vlib_get_buffer (vm, bi0);
          ip0 = vlib_buffer_get_current (b0);
          udp0 = ip4_next_header (ip0);
          tcp0 = (tcp_header_t *) udp0;

          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          vnet_get_config_data (&cm->config_main, &b0->current_config_index,
                                &next0, 0);

          if (snat_hairpinning (sm, b0, ip0, udp0, tcp0, proto0))
            next0 = SNAT_IN2OUT_NEXT_LOOKUP;

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueue, maybe switch current next frame */
	  vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
					   to_next, n_left_to_next,
					   bi0, next0);
         }

      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
    }

  vlib_node_increment_counter (vm, nat44_hairpinning_node.index,
                               SNAT_IN2OUT_ERROR_IN2OUT_PACKETS,
                               pkts_processed);
  return frame->n_vectors;
}

VLIB_REGISTER_NODE (nat44_hairpinning_node) = {
  .function = nat44_hairpinning_fn,
  .name = "nat44-hairpinning",
  .vector_size = sizeof (u32),
  .type = VLIB_NODE_TYPE_INTERNAL,
  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,
  .n_next_nodes = 2,
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (nat44_hairpinning_node,
                              nat44_hairpinning_fn);

static inline void
nat44_reass_hairpinning (snat_main_t *sm,
                         vlib_buffer_t * b0,
                         ip4_header_t * ip0,
                         u16 sport,
                         u16 dport,
                         u32 proto0)
{
  snat_session_key_t key0, sm0;
  snat_session_t * s0;
  clib_bihash_kv_8_8_t kv0, value0;
  ip_csum_t sum0;
  u32 new_dst_addr0 = 0, old_dst_addr0, ti = 0, si;
  u16 new_dst_port0, old_dst_port0;
  udp_header_t * udp0;
  tcp_header_t * tcp0;

  key0.addr = ip0->dst_address;
  key0.port = dport;
  key0.protocol = proto0;
  key0.fib_index = sm->outside_fib_index;
  kv0.key = key0.as_u64;

  udp0 = ip4_next_header (ip0);

  /* Check if destination is static mappings */
  if (!snat_static_mapping_match(sm, key0, &sm0, 1, 0, 0))
    {
      new_dst_addr0 = sm0.addr.as_u32;
      new_dst_port0 = sm0.port;
      vnet_buffer(b0)->sw_if_index[VLIB_TX] = sm0.fib_index;
    }
  /* or active sessions */
  else
    {
      if (sm->num_workers > 1)
        ti = (clib_net_to_host_u16 (udp0->dst_port) - 1024) / sm->port_per_thread;
      else
        ti = sm->num_workers;

      if (!clib_bihash_search_8_8 (&sm->per_thread_data[ti].out2in, &kv0, &value0))
        {
          si = value0.value;
          s0 = pool_elt_at_index (sm->per_thread_data[ti].sessions, si);
          new_dst_addr0 = s0->in2out.addr.as_u32;
          new_dst_port0 = s0->in2out.port;
          vnet_buffer(b0)->sw_if_index[VLIB_TX] = s0->in2out.fib_index;
        }
    }

  /* Destination is behind the same NAT, use internal address and port */
  if (new_dst_addr0)
    {
      old_dst_addr0 = ip0->dst_address.as_u32;
      ip0->dst_address.as_u32 = new_dst_addr0;
      sum0 = ip0->checksum;
      sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                             ip4_header_t, dst_address);
      ip0->checksum = ip_csum_fold (sum0);

      old_dst_port0 = dport;
      if (PREDICT_TRUE(new_dst_port0 != old_dst_port0 &&
                       ip4_is_first_fragment (ip0)))
        {
          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              tcp0 = ip4_next_header (ip0);
              tcp0->dst = new_dst_port0;
              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                                     ip4_header_t, dst_address);
              sum0 = ip_csum_update (sum0, old_dst_port0, new_dst_port0,
                                     ip4_header_t /* cheat */, length);
              tcp0->checksum = ip_csum_fold(sum0);
            }
          else
            {
              udp0->dst_port = new_dst_port0;
              udp0->checksum = 0;
            }
        }
      else
        {
          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              tcp0 = ip4_next_header (ip0);
              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_dst_addr0, new_dst_addr0,
                                     ip4_header_t, dst_address);
              tcp0->checksum = ip_csum_fold(sum0);
            }
        }
    }
}

static uword
nat44_in2out_reass_node_fn (vlib_main_t * vm,
                            vlib_node_runtime_t * node,
                            vlib_frame_t * frame)
{
  u32 n_left_from, *from, *to_next;
  snat_in2out_next_t next_index;
  u32 pkts_processed = 0;
  snat_main_t *sm = &snat_main;
  f64 now = vlib_time_now (vm);
  u32 thread_index = vlib_get_thread_index ();
  snat_main_per_thread_data_t *per_thread_data =
    &sm->per_thread_data[thread_index];
  u32 *fragments_to_drop = 0;
  u32 *fragments_to_loopback = 0;

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;
  next_index = node->cached_next_index;

  while (n_left_from > 0)
    {
      u32 n_left_to_next;

      vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);

      while (n_left_from > 0 && n_left_to_next > 0)
       {
          u32 bi0, sw_if_index0, proto0, rx_fib_index0, new_addr0, old_addr0;
	  vlib_buffer_t *b0;
          u32 next0;
          u8 cached0 = 0;
          ip4_header_t *ip0;
          nat_reass_ip4_t *reass0;
          udp_header_t * udp0;
          tcp_header_t * tcp0;
          snat_session_key_t key0;
          clib_bihash_kv_8_8_t kv0, value0;
          snat_session_t * s0 = 0;
          u16 old_port0, new_port0;
          ip_csum_t sum0;

          /* speculatively enqueue b0 to the current next frame */
	  bi0 = from[0];
	  to_next[0] = bi0;
	  from += 1;
	  to_next += 1;
	  n_left_from -= 1;
	  n_left_to_next -= 1;

	  b0 = vlib_get_buffer (vm, bi0);
          next0 = SNAT_IN2OUT_NEXT_LOOKUP;

          sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
          rx_fib_index0 = fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4,
                                                               sw_if_index0);

          if (PREDICT_FALSE (nat_reass_is_drop_frag(0)))
            {
              next0 = SNAT_IN2OUT_NEXT_DROP;
              b0->error = node->errors[SNAT_IN2OUT_ERROR_DROP_FRAGMENT];
              goto trace0;
            }

          ip0 = (ip4_header_t *) vlib_buffer_get_current (b0);
          udp0 = ip4_next_header (ip0);
          tcp0 = (tcp_header_t *) udp0;
          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          reass0 = nat_ip4_reass_find_or_create (ip0->src_address,
                                                 ip0->dst_address,
                                                 ip0->fragment_id,
                                                 ip0->protocol,
                                                 1,
                                                 &fragments_to_drop);

          if (PREDICT_FALSE (!reass0))
            {
              next0 = SNAT_IN2OUT_NEXT_DROP;
              b0->error = node->errors[SNAT_IN2OUT_ERROR_MAX_REASS];
              goto trace0;
            }

          if (PREDICT_FALSE (ip4_is_first_fragment (ip0)))
            {
              key0.addr = ip0->src_address;
              key0.port = udp0->src_port;
              key0.protocol = proto0;
              key0.fib_index = rx_fib_index0;
              kv0.key = key0.as_u64;

              if (clib_bihash_search_8_8 (&per_thread_data->in2out, &kv0, &value0))
                {
                  if (PREDICT_FALSE(snat_not_translate(sm, node, sw_if_index0,
                      ip0, proto0, rx_fib_index0, thread_index)))
                    goto trace0;

                  next0 = slow_path (sm, b0, ip0, rx_fib_index0, &key0,
                                     &s0, node, next0, thread_index);

                  if (PREDICT_FALSE (next0 == SNAT_IN2OUT_NEXT_DROP))
                    goto trace0;

                  reass0->sess_index = s0 - per_thread_data->sessions;
                }
              else
                {
                  s0 = pool_elt_at_index (per_thread_data->sessions,
                                          value0.value);
                  reass0->sess_index = value0.value;
                }
              nat_ip4_reass_get_frags (reass0, &fragments_to_loopback);
            }
          else
            {
              if (PREDICT_FALSE (reass0->sess_index == (u32) ~0))
                {
                  if (nat_ip4_reass_add_fragment (reass0, bi0))
                    {
                      b0->error = node->errors[SNAT_IN2OUT_ERROR_MAX_FRAG];
                      next0 = SNAT_IN2OUT_NEXT_DROP;
                      goto trace0;
                    }
                  cached0 = 1;
                  goto trace0;
                }
              s0 = pool_elt_at_index (per_thread_data->sessions,
                                      reass0->sess_index);
            }

          old_addr0 = ip0->src_address.as_u32;
          ip0->src_address = s0->out2in.addr;
          new_addr0 = ip0->src_address.as_u32;
          vnet_buffer(b0)->sw_if_index[VLIB_TX] = s0->out2in.fib_index;

          sum0 = ip0->checksum;
          sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip0->checksum = ip_csum_fold (sum0);

          if (PREDICT_FALSE (ip4_is_first_fragment (ip0)))
            {
              if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
                {
                  old_port0 = tcp0->src_port;
                  tcp0->src_port = s0->out2in.port;
                  new_port0 = tcp0->src_port;

                  sum0 = tcp0->checksum;
                  sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                         ip4_header_t,
                                         dst_address /* changed member */);
                  sum0 = ip_csum_update (sum0, old_port0, new_port0,
                                         ip4_header_t /* cheat */,
                                         length /* changed member */);
                  tcp0->checksum = ip_csum_fold(sum0);
                }
              else
                {
                  old_port0 = udp0->src_port;
                  udp0->src_port = s0->out2in.port;
                  udp0->checksum = 0;
                }
            }

          /* Hairpinning */
          nat44_reass_hairpinning (sm, b0, ip0, s0->out2in.port,
                                   s0->ext_host_port, proto0);

          /* Accounting */
          s0->last_heard = now;
          s0->total_pkts++;
          s0->total_bytes += vlib_buffer_length_in_chain (vm, b0);
          /* Per-user LRU list maintenance */
          clib_dlist_remove (sm->per_thread_data[thread_index].list_pool,
                             s0->per_user_index);
          clib_dlist_addtail (sm->per_thread_data[thread_index].list_pool,
                              s0->per_user_list_head_index,
                              s0->per_user_index);

        trace0:
          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
            {
              nat44_in2out_reass_trace_t *t =
                 vlib_add_trace (vm, node, b0, sizeof (*t));
              t->cached = cached0;
              t->sw_if_index = sw_if_index0;
              t->next_index = next0;
            }

          if (cached0)
            {
              n_left_to_next++;
              to_next--;
            }
          else
            {
              pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

              /* verify speculative enqueue, maybe switch current next frame */
              vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
                                               to_next, n_left_to_next,
                                               bi0, next0);
            }

	  if (n_left_from == 0 && vec_len (fragments_to_loopback))
	    {
	      from = vlib_frame_vector_args (frame);
	      u32 len = vec_len (fragments_to_loopback);
	      if (len <= VLIB_FRAME_SIZE)
		{
		  clib_memcpy (from, fragments_to_loopback, sizeof (u32) * len);
		  n_left_from = len;
		  vec_reset_length (fragments_to_loopback);
		}
	      else
		{
		  clib_memcpy (from,
                               fragments_to_loopback + (len - VLIB_FRAME_SIZE),
                               sizeof (u32) * VLIB_FRAME_SIZE);
		  n_left_from = VLIB_FRAME_SIZE;
		  _vec_len (fragments_to_loopback) = len - VLIB_FRAME_SIZE;
		}
	    }
       }

      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
    }

  vlib_node_increment_counter (vm, nat44_in2out_reass_node.index,
                               SNAT_IN2OUT_ERROR_IN2OUT_PACKETS,
                               pkts_processed);

  nat_send_all_to_node (vm, fragments_to_drop, node,
                        &node->errors[SNAT_IN2OUT_ERROR_DROP_FRAGMENT],
                        SNAT_IN2OUT_NEXT_DROP);

  vec_free (fragments_to_drop);
  vec_free (fragments_to_loopback);
  return frame->n_vectors;
}

VLIB_REGISTER_NODE (nat44_in2out_reass_node) = {
  .function = nat44_in2out_reass_node_fn,
  .name = "nat44-in2out-reass",
  .vector_size = sizeof (u32),
  .format_trace = format_nat44_in2out_reass_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,

  .n_next_nodes = SNAT_IN2OUT_N_NEXT,
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
    [SNAT_IN2OUT_NEXT_SLOW_PATH] = "nat44-in2out-slowpath",
    [SNAT_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
    [SNAT_IN2OUT_NEXT_REASS] = "nat44-in2out-reass",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (nat44_in2out_reass_node,
                              nat44_in2out_reass_node_fn);

/**************************/
/*** deterministic mode ***/
/**************************/
static uword
snat_det_in2out_node_fn (vlib_main_t * vm,
                         vlib_node_runtime_t * node,
                         vlib_frame_t * frame)
{
  u32 n_left_from, * from, * to_next;
  snat_in2out_next_t next_index;
  u32 pkts_processed = 0;
  snat_main_t * sm = &snat_main;
  u32 now = (u32) vlib_time_now (vm);
  u32 thread_index = vlib_get_thread_index ();

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;
  next_index = node->cached_next_index;

  while (n_left_from > 0)
    {
      u32 n_left_to_next;

      vlib_get_next_frame (vm, node, next_index,
			   to_next, n_left_to_next);

      while (n_left_from >= 4 && n_left_to_next >= 2)
        {
          u32 bi0, bi1;
	  vlib_buffer_t * b0, * b1;
          u32 next0, next1;
          u32 sw_if_index0, sw_if_index1;
          ip4_header_t * ip0, * ip1;
          ip_csum_t sum0, sum1;
          ip4_address_t new_addr0, old_addr0, new_addr1, old_addr1;
          u16 old_port0, new_port0, lo_port0, i0;
          u16 old_port1, new_port1, lo_port1, i1;
          udp_header_t * udp0, * udp1;
          tcp_header_t * tcp0, * tcp1;
          u32 proto0, proto1;
          snat_det_out_key_t key0, key1;
          snat_det_map_t * dm0, * dm1;
          snat_det_session_t * ses0 = 0, * ses1 = 0;
          u32 rx_fib_index0, rx_fib_index1;
          icmp46_header_t * icmp0, * icmp1;

	  /* Prefetch next iteration. */
	  {
	    vlib_buffer_t * p2, * p3;

	    p2 = vlib_get_buffer (vm, from[2]);
	    p3 = vlib_get_buffer (vm, from[3]);

	    vlib_prefetch_buffer_header (p2, LOAD);
	    vlib_prefetch_buffer_header (p3, LOAD);

	    CLIB_PREFETCH (p2->data, CLIB_CACHE_LINE_BYTES, STORE);
	    CLIB_PREFETCH (p3->data, CLIB_CACHE_LINE_BYTES, STORE);
	  }

          /* speculatively enqueue b0 and b1 to the current next frame */
	  to_next[0] = bi0 = from[0];
	  to_next[1] = bi1 = from[1];
	  from += 2;
	  to_next += 2;
	  n_left_from -= 2;
	  n_left_to_next -= 2;

	  b0 = vlib_get_buffer (vm, bi0);
	  b1 = vlib_get_buffer (vm, bi1);

          next0 = SNAT_IN2OUT_NEXT_LOOKUP;
          next1 = SNAT_IN2OUT_NEXT_LOOKUP;

          ip0 = vlib_buffer_get_current (b0);
          udp0 = ip4_next_header (ip0);
          tcp0 = (tcp_header_t *) udp0;

          sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];

          if (PREDICT_FALSE(ip0->ttl == 1))
            {
              vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
              icmp4_error_set_vnet_buffer (b0, ICMP4_time_exceeded,
                                           ICMP4_time_exceeded_ttl_exceeded_in_transit,
                                           0);
              next0 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
              goto trace0;
            }

          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          if (PREDICT_FALSE(proto0 == SNAT_PROTOCOL_ICMP))
            {
              rx_fib_index0 = ip4_fib_table_get_index_for_sw_if_index(sw_if_index0);
              icmp0 = (icmp46_header_t *) udp0;

              next0 = icmp_in2out(sm, b0, ip0, icmp0, sw_if_index0,
                                  rx_fib_index0, node, next0, thread_index,
                                  &ses0, &dm0);
              goto trace0;
            }

          dm0 = snat_det_map_by_user(sm, &ip0->src_address);
          if (PREDICT_FALSE(!dm0))
            {
              clib_warning("no match for internal host %U",
                           format_ip4_address, &ip0->src_address);
              next0 = SNAT_IN2OUT_NEXT_DROP;
              b0->error = node->errors[SNAT_IN2OUT_ERROR_NO_TRANSLATION];
              goto trace0;
            }

          snat_det_forward(dm0, &ip0->src_address, &new_addr0, &lo_port0);

          key0.ext_host_addr = ip0->dst_address;
          key0.ext_host_port = tcp0->dst;

          ses0 = snat_det_find_ses_by_in(dm0, &ip0->src_address, tcp0->src, key0);
          if (PREDICT_FALSE(!ses0))
            {
              for (i0 = 0; i0 < dm0->ports_per_host; i0++)
                {
                  key0.out_port = clib_host_to_net_u16 (lo_port0 +
                    ((i0 + clib_net_to_host_u16 (tcp0->src)) % dm0->ports_per_host));

                  if (snat_det_get_ses_by_out (dm0, &ip0->src_address, key0.as_u64))
                    continue;

                  ses0 = snat_det_ses_create(dm0, &ip0->src_address, tcp0->src, &key0);
                  break;
                }
              if (PREDICT_FALSE(!ses0))
                {
                  /* too many sessions for user, send ICMP error packet */

                  vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
                  icmp4_error_set_vnet_buffer (b0, ICMP4_destination_unreachable,
                                               ICMP4_destination_unreachable_destination_unreachable_host,
                                               0);
                  next0 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
                  goto trace0;
                }
            }

          new_port0 = ses0->out.out_port;

          old_addr0.as_u32 = ip0->src_address.as_u32;
          ip0->src_address.as_u32 = new_addr0.as_u32;
          vnet_buffer(b0)->sw_if_index[VLIB_TX] = sm->outside_fib_index;

          sum0 = ip0->checksum;
          sum0 = ip_csum_update (sum0, old_addr0.as_u32, new_addr0.as_u32,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip0->checksum = ip_csum_fold (sum0);

          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              if (tcp0->flags & TCP_FLAG_SYN)
                ses0->state = SNAT_SESSION_TCP_SYN_SENT;
              else if (tcp0->flags & TCP_FLAG_ACK && ses0->state == SNAT_SESSION_TCP_SYN_SENT)
                ses0->state = SNAT_SESSION_TCP_ESTABLISHED;
              else if (tcp0->flags & TCP_FLAG_FIN && ses0->state == SNAT_SESSION_TCP_ESTABLISHED)
                ses0->state = SNAT_SESSION_TCP_FIN_WAIT;
              else if (tcp0->flags & TCP_FLAG_ACK && ses0->state == SNAT_SESSION_TCP_FIN_WAIT)
                snat_det_ses_close(dm0, ses0);
              else if (tcp0->flags & TCP_FLAG_FIN && ses0->state == SNAT_SESSION_TCP_CLOSE_WAIT)
                ses0->state = SNAT_SESSION_TCP_LAST_ACK;
              else if (tcp0->flags == 0 && ses0->state == SNAT_SESSION_UNKNOWN)
                ses0->state = SNAT_SESSION_TCP_ESTABLISHED;

              old_port0 = tcp0->src;
              tcp0->src = new_port0;

              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_addr0.as_u32, new_addr0.as_u32,
                                     ip4_header_t,
                                     dst_address /* changed member */);
              sum0 = ip_csum_update (sum0, old_port0, new_port0,
                                     ip4_header_t /* cheat */,
                                     length /* changed member */);
              tcp0->checksum = ip_csum_fold(sum0);
            }
          else
            {
              ses0->state = SNAT_SESSION_UDP_ACTIVE;
              old_port0 = udp0->src_port;
              udp0->src_port = new_port0;
              udp0->checksum = 0;
            }

          switch(ses0->state)
            {
            case SNAT_SESSION_UDP_ACTIVE:
                ses0->expire = now + sm->udp_timeout;
                break;
            case SNAT_SESSION_TCP_SYN_SENT:
            case SNAT_SESSION_TCP_FIN_WAIT:
            case SNAT_SESSION_TCP_CLOSE_WAIT:
            case SNAT_SESSION_TCP_LAST_ACK:
                ses0->expire = now + sm->tcp_transitory_timeout;
                break;
            case SNAT_SESSION_TCP_ESTABLISHED:
                ses0->expire = now + sm->tcp_established_timeout;
                break;
            }

        trace0:
          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
            {
              snat_in2out_trace_t *t =
                 vlib_add_trace (vm, node, b0, sizeof (*t));
              t->is_slow_path = 0;
              t->sw_if_index = sw_if_index0;
              t->next_index = next0;
              t->session_index = ~0;
              if (ses0)
                t->session_index = ses0 - dm0->sessions;
            }

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          ip1 = vlib_buffer_get_current (b1);
          udp1 = ip4_next_header (ip1);
          tcp1 = (tcp_header_t *) udp1;

          sw_if_index1 = vnet_buffer(b1)->sw_if_index[VLIB_RX];

          if (PREDICT_FALSE(ip1->ttl == 1))
            {
              vnet_buffer (b1)->sw_if_index[VLIB_TX] = (u32) ~ 0;
              icmp4_error_set_vnet_buffer (b1, ICMP4_time_exceeded,
                                           ICMP4_time_exceeded_ttl_exceeded_in_transit,
                                           0);
              next1 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
              goto trace1;
            }

          proto1 = ip_proto_to_snat_proto (ip1->protocol);

          if (PREDICT_FALSE(proto1 == SNAT_PROTOCOL_ICMP))
            {
              rx_fib_index1 = ip4_fib_table_get_index_for_sw_if_index(sw_if_index1);
              icmp1 = (icmp46_header_t *) udp1;

              next1 = icmp_in2out(sm, b1, ip1, icmp1, sw_if_index1,
                                  rx_fib_index1, node, next1, thread_index,
                                  &ses1, &dm1);
              goto trace1;
            }

          dm1 = snat_det_map_by_user(sm, &ip1->src_address);
          if (PREDICT_FALSE(!dm1))
            {
              clib_warning("no match for internal host %U",
                           format_ip4_address, &ip0->src_address);
              next1 = SNAT_IN2OUT_NEXT_DROP;
              b1->error = node->errors[SNAT_IN2OUT_ERROR_NO_TRANSLATION];
              goto trace1;
            }

          snat_det_forward(dm1, &ip1->src_address, &new_addr1, &lo_port1);

          key1.ext_host_addr = ip1->dst_address;
          key1.ext_host_port = tcp1->dst;

          ses1 = snat_det_find_ses_by_in(dm1, &ip1->src_address, tcp1->src, key1);
          if (PREDICT_FALSE(!ses1))
            {
              for (i1 = 0; i1 < dm1->ports_per_host; i1++)
                {
                  key1.out_port = clib_host_to_net_u16 (lo_port1 +
                    ((i1 + clib_net_to_host_u16 (tcp1->src)) % dm1->ports_per_host));

                  if (snat_det_get_ses_by_out (dm1, &ip1->src_address, key1.as_u64))
                    continue;

                  ses1 = snat_det_ses_create(dm1, &ip1->src_address, tcp1->src, &key1);
                  break;
                }
              if (PREDICT_FALSE(!ses1))
                {
                  /* too many sessions for user, send ICMP error packet */

                  vnet_buffer (b1)->sw_if_index[VLIB_TX] = (u32) ~ 0;
                  icmp4_error_set_vnet_buffer (b1, ICMP4_destination_unreachable,
                                               ICMP4_destination_unreachable_destination_unreachable_host,
                                               0);
                  next1 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
                  goto trace1;
                }
            }

          new_port1 = ses1->out.out_port;

          old_addr1.as_u32 = ip1->src_address.as_u32;
          ip1->src_address.as_u32 = new_addr1.as_u32;
          vnet_buffer(b1)->sw_if_index[VLIB_TX] = sm->outside_fib_index;

          sum1 = ip1->checksum;
          sum1 = ip_csum_update (sum1, old_addr1.as_u32, new_addr1.as_u32,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip1->checksum = ip_csum_fold (sum1);

          if (PREDICT_TRUE(proto1 == SNAT_PROTOCOL_TCP))
            {
              if (tcp1->flags & TCP_FLAG_SYN)
                ses1->state = SNAT_SESSION_TCP_SYN_SENT;
              else if (tcp1->flags & TCP_FLAG_ACK && ses1->state == SNAT_SESSION_TCP_SYN_SENT)
                ses1->state = SNAT_SESSION_TCP_ESTABLISHED;
              else if (tcp1->flags & TCP_FLAG_FIN && ses1->state == SNAT_SESSION_TCP_ESTABLISHED)
                ses1->state = SNAT_SESSION_TCP_FIN_WAIT;
              else if (tcp1->flags & TCP_FLAG_ACK && ses1->state == SNAT_SESSION_TCP_FIN_WAIT)
                snat_det_ses_close(dm1, ses1);
              else if (tcp1->flags & TCP_FLAG_FIN && ses1->state == SNAT_SESSION_TCP_CLOSE_WAIT)
                ses1->state = SNAT_SESSION_TCP_LAST_ACK;
              else if (tcp1->flags == 0 && ses1->state == SNAT_SESSION_UNKNOWN)
                ses1->state = SNAT_SESSION_TCP_ESTABLISHED;

              old_port1 = tcp1->src;
              tcp1->src = new_port1;

              sum1 = tcp1->checksum;
              sum1 = ip_csum_update (sum1, old_addr1.as_u32, new_addr1.as_u32,
                                     ip4_header_t,
                                     dst_address /* changed member */);
              sum1 = ip_csum_update (sum1, old_port1, new_port1,
                                     ip4_header_t /* cheat */,
                                     length /* changed member */);
              tcp1->checksum = ip_csum_fold(sum1);
            }
          else
            {
              ses1->state = SNAT_SESSION_UDP_ACTIVE;
              old_port1 = udp1->src_port;
              udp1->src_port = new_port1;
              udp1->checksum = 0;
            }

          switch(ses1->state)
            {
            case SNAT_SESSION_UDP_ACTIVE:
                ses1->expire = now + sm->udp_timeout;
                break;
            case SNAT_SESSION_TCP_SYN_SENT:
            case SNAT_SESSION_TCP_FIN_WAIT:
            case SNAT_SESSION_TCP_CLOSE_WAIT:
            case SNAT_SESSION_TCP_LAST_ACK:
                ses1->expire = now + sm->tcp_transitory_timeout;
                break;
            case SNAT_SESSION_TCP_ESTABLISHED:
                ses1->expire = now + sm->tcp_established_timeout;
                break;
            }

        trace1:
          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b1->flags & VLIB_BUFFER_IS_TRACED)))
            {
              snat_in2out_trace_t *t =
                 vlib_add_trace (vm, node, b1, sizeof (*t));
              t->is_slow_path = 0;
              t->sw_if_index = sw_if_index1;
              t->next_index = next1;
              t->session_index = ~0;
              if (ses1)
                t->session_index = ses1 - dm1->sessions;
            }

          pkts_processed += next1 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueues, maybe switch current next frame */
          vlib_validate_buffer_enqueue_x2 (vm, node, next_index,
                                           to_next, n_left_to_next,
                                           bi0, bi1, next0, next1);
         }

      while (n_left_from > 0 && n_left_to_next > 0)
	{
          u32 bi0;
	  vlib_buffer_t * b0;
          u32 next0;
          u32 sw_if_index0;
          ip4_header_t * ip0;
          ip_csum_t sum0;
          ip4_address_t new_addr0, old_addr0;
          u16 old_port0, new_port0, lo_port0, i0;
          udp_header_t * udp0;
          tcp_header_t * tcp0;
          u32 proto0;
          snat_det_out_key_t key0;
          snat_det_map_t * dm0;
          snat_det_session_t * ses0 = 0;
          u32 rx_fib_index0;
          icmp46_header_t * icmp0;

          /* speculatively enqueue b0 to the current next frame */
	  bi0 = from[0];
	  to_next[0] = bi0;
	  from += 1;
	  to_next += 1;
	  n_left_from -= 1;
	  n_left_to_next -= 1;

	  b0 = vlib_get_buffer (vm, bi0);
          next0 = SNAT_IN2OUT_NEXT_LOOKUP;

          ip0 = vlib_buffer_get_current (b0);
          udp0 = ip4_next_header (ip0);
          tcp0 = (tcp_header_t *) udp0;

          sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];

          if (PREDICT_FALSE(ip0->ttl == 1))
            {
              vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
              icmp4_error_set_vnet_buffer (b0, ICMP4_time_exceeded,
                                           ICMP4_time_exceeded_ttl_exceeded_in_transit,
                                           0);
              next0 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
              goto trace00;
            }

          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          if (PREDICT_FALSE(proto0 == SNAT_PROTOCOL_ICMP))
            {
              rx_fib_index0 = ip4_fib_table_get_index_for_sw_if_index(sw_if_index0);
              icmp0 = (icmp46_header_t *) udp0;

              next0 = icmp_in2out(sm, b0, ip0, icmp0, sw_if_index0,
                                  rx_fib_index0, node, next0, thread_index,
                                  &ses0, &dm0);
              goto trace00;
            }

          dm0 = snat_det_map_by_user(sm, &ip0->src_address);
          if (PREDICT_FALSE(!dm0))
            {
              clib_warning("no match for internal host %U",
                           format_ip4_address, &ip0->src_address);
              next0 = SNAT_IN2OUT_NEXT_DROP;
              b0->error = node->errors[SNAT_IN2OUT_ERROR_NO_TRANSLATION];
              goto trace00;
            }

          snat_det_forward(dm0, &ip0->src_address, &new_addr0, &lo_port0);

          key0.ext_host_addr = ip0->dst_address;
          key0.ext_host_port = tcp0->dst;

          ses0 = snat_det_find_ses_by_in(dm0, &ip0->src_address, tcp0->src, key0);
          if (PREDICT_FALSE(!ses0))
            {
              for (i0 = 0; i0 < dm0->ports_per_host; i0++)
                {
                  key0.out_port = clib_host_to_net_u16 (lo_port0 +
                    ((i0 + clib_net_to_host_u16 (tcp0->src)) % dm0->ports_per_host));

                  if (snat_det_get_ses_by_out (dm0, &ip0->src_address, key0.as_u64))
                    continue;

                  ses0 = snat_det_ses_create(dm0, &ip0->src_address, tcp0->src, &key0);
                  break;
                }
              if (PREDICT_FALSE(!ses0))
                {
                  /* too many sessions for user, send ICMP error packet */

                  vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
                  icmp4_error_set_vnet_buffer (b0, ICMP4_destination_unreachable,
                                               ICMP4_destination_unreachable_destination_unreachable_host,
                                               0);
                  next0 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
                  goto trace00;
                }
            }

          new_port0 = ses0->out.out_port;

          old_addr0.as_u32 = ip0->src_address.as_u32;
          ip0->src_address.as_u32 = new_addr0.as_u32;
          vnet_buffer(b0)->sw_if_index[VLIB_TX] = sm->outside_fib_index;

          sum0 = ip0->checksum;
          sum0 = ip_csum_update (sum0, old_addr0.as_u32, new_addr0.as_u32,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip0->checksum = ip_csum_fold (sum0);

          if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
            {
              if (tcp0->flags & TCP_FLAG_SYN)
                ses0->state = SNAT_SESSION_TCP_SYN_SENT;
              else if (tcp0->flags & TCP_FLAG_ACK && ses0->state == SNAT_SESSION_TCP_SYN_SENT)
                ses0->state = SNAT_SESSION_TCP_ESTABLISHED;
              else if (tcp0->flags & TCP_FLAG_FIN && ses0->state == SNAT_SESSION_TCP_ESTABLISHED)
                ses0->state = SNAT_SESSION_TCP_FIN_WAIT;
              else if (tcp0->flags & TCP_FLAG_ACK && ses0->state == SNAT_SESSION_TCP_FIN_WAIT)
                snat_det_ses_close(dm0, ses0);
              else if (tcp0->flags & TCP_FLAG_FIN && ses0->state == SNAT_SESSION_TCP_CLOSE_WAIT)
                ses0->state = SNAT_SESSION_TCP_LAST_ACK;
              else if (tcp0->flags == 0 && ses0->state == SNAT_SESSION_UNKNOWN)
                ses0->state = SNAT_SESSION_TCP_ESTABLISHED;

              old_port0 = tcp0->src;
              tcp0->src = new_port0;

              sum0 = tcp0->checksum;
              sum0 = ip_csum_update (sum0, old_addr0.as_u32, new_addr0.as_u32,
                                     ip4_header_t,
                                     dst_address /* changed member */);
              sum0 = ip_csum_update (sum0, old_port0, new_port0,
                                     ip4_header_t /* cheat */,
                                     length /* changed member */);
              tcp0->checksum = ip_csum_fold(sum0);
            }
          else
            {
              ses0->state = SNAT_SESSION_UDP_ACTIVE;
              old_port0 = udp0->src_port;
              udp0->src_port = new_port0;
              udp0->checksum = 0;
            }

          switch(ses0->state)
            {
            case SNAT_SESSION_UDP_ACTIVE:
                ses0->expire = now + sm->udp_timeout;
                break;
            case SNAT_SESSION_TCP_SYN_SENT:
            case SNAT_SESSION_TCP_FIN_WAIT:
            case SNAT_SESSION_TCP_CLOSE_WAIT:
            case SNAT_SESSION_TCP_LAST_ACK:
                ses0->expire = now + sm->tcp_transitory_timeout;
                break;
            case SNAT_SESSION_TCP_ESTABLISHED:
                ses0->expire = now + sm->tcp_established_timeout;
                break;
            }

        trace00:
          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
            {
              snat_in2out_trace_t *t =
                 vlib_add_trace (vm, node, b0, sizeof (*t));
              t->is_slow_path = 0;
              t->sw_if_index = sw_if_index0;
              t->next_index = next0;
              t->session_index = ~0;
              if (ses0)
                t->session_index = ses0 - dm0->sessions;
            }

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueue, maybe switch current next frame */
	  vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
					   to_next, n_left_to_next,
					   bi0, next0);
	}

      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
    }

  vlib_node_increment_counter (vm, snat_det_in2out_node.index,
                               SNAT_IN2OUT_ERROR_IN2OUT_PACKETS,
                               pkts_processed);
  return frame->n_vectors;
}

VLIB_REGISTER_NODE (snat_det_in2out_node) = {
  .function = snat_det_in2out_node_fn,
  .name = "nat44-det-in2out",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,

  .runtime_data_bytes = sizeof (snat_runtime_t),

  .n_next_nodes = 3,

  /* edit / add dispositions here */
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
    [SNAT_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_det_in2out_node, snat_det_in2out_node_fn);

/**
 * Get address and port values to be used for ICMP packet translation
 * and create session if needed
 *
 * @param[in,out] sm             NAT main
 * @param[in,out] node           NAT node runtime
 * @param[in] thread_index       thread index
 * @param[in,out] b0             buffer containing packet to be translated
 * @param[out] p_proto           protocol used for matching
 * @param[out] p_value           address and port after NAT translation
 * @param[out] p_dont_translate  if packet should not be translated
 * @param d                      optional parameter
 * @param e                      optional parameter
 */
u32 icmp_match_in2out_det(snat_main_t *sm, vlib_node_runtime_t *node,
                          u32 thread_index, vlib_buffer_t *b0,
                          ip4_header_t *ip0, u8 *p_proto,
                          snat_session_key_t *p_value,
                          u8 *p_dont_translate, void *d, void *e)
{
  icmp46_header_t *icmp0;
  u32 sw_if_index0;
  u32 rx_fib_index0;
  u8 protocol;
  snat_det_out_key_t key0;
  u8 dont_translate = 0;
  u32 next0 = ~0;
  icmp_echo_header_t *echo0, *inner_echo0 = 0;
  ip4_header_t *inner_ip0;
  void *l4_header = 0;
  icmp46_header_t *inner_icmp0;
  snat_det_map_t * dm0 = 0;
  ip4_address_t new_addr0;
  u16 lo_port0, i0;
  snat_det_session_t * ses0 = 0;
  ip4_address_t in_addr;
  u16 in_port;

  icmp0 = (icmp46_header_t *) ip4_next_header (ip0);
  echo0 = (icmp_echo_header_t *)(icmp0+1);
  sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
  rx_fib_index0 = ip4_fib_table_get_index_for_sw_if_index (sw_if_index0);

  if (!icmp_is_error_message (icmp0))
    {
      protocol = SNAT_PROTOCOL_ICMP;
      in_addr = ip0->src_address;
      in_port = echo0->identifier;
    }
  else
    {
      inner_ip0 = (ip4_header_t *)(echo0+1);
      l4_header = ip4_next_header (inner_ip0);
      protocol = ip_proto_to_snat_proto (inner_ip0->protocol);
      in_addr = inner_ip0->dst_address;
      switch (protocol)
        {
        case SNAT_PROTOCOL_ICMP:
          inner_icmp0 = (icmp46_header_t*)l4_header;
          inner_echo0 = (icmp_echo_header_t *)(inner_icmp0+1);
          in_port = inner_echo0->identifier;
          break;
        case SNAT_PROTOCOL_UDP:
        case SNAT_PROTOCOL_TCP:
          in_port = ((tcp_udp_header_t*)l4_header)->dst_port;
          break;
        default:
          b0->error = node->errors[SNAT_IN2OUT_ERROR_UNSUPPORTED_PROTOCOL];
          next0 = SNAT_IN2OUT_NEXT_DROP;
          goto out;
        }
    }

  dm0 = snat_det_map_by_user(sm, &in_addr);
  if (PREDICT_FALSE(!dm0))
    {
      clib_warning("no match for internal host %U",
                   format_ip4_address, &in_addr);
      if (PREDICT_FALSE(snat_not_translate_fast(sm, node, sw_if_index0, ip0,
          IP_PROTOCOL_ICMP, rx_fib_index0)))
        {
          dont_translate = 1;
          goto out;
        }
      next0 = SNAT_IN2OUT_NEXT_DROP;
      b0->error = node->errors[SNAT_IN2OUT_ERROR_NO_TRANSLATION];
      goto out;
    }

  snat_det_forward(dm0, &in_addr, &new_addr0, &lo_port0);

  key0.ext_host_addr = ip0->dst_address;
  key0.ext_host_port = 0;

  ses0 = snat_det_find_ses_by_in(dm0, &in_addr, in_port, key0);
  if (PREDICT_FALSE(!ses0))
    {
      if (PREDICT_FALSE(snat_not_translate_fast(sm, node, sw_if_index0, ip0,
          IP_PROTOCOL_ICMP, rx_fib_index0)))
        {
          dont_translate = 1;
          goto out;
        }
      if (icmp0->type != ICMP4_echo_request)
        {
          b0->error = node->errors[SNAT_IN2OUT_ERROR_BAD_ICMP_TYPE];
          next0 = SNAT_IN2OUT_NEXT_DROP;
          goto out;
        }
      for (i0 = 0; i0 < dm0->ports_per_host; i0++)
        {
          key0.out_port = clib_host_to_net_u16 (lo_port0 +
            ((i0 + clib_net_to_host_u16 (echo0->identifier)) % dm0->ports_per_host));

          if (snat_det_get_ses_by_out (dm0, &in_addr, key0.as_u64))
            continue;

          ses0 = snat_det_ses_create(dm0, &in_addr, echo0->identifier, &key0);
          break;
        }
      if (PREDICT_FALSE(!ses0))
        {
          next0 = SNAT_IN2OUT_NEXT_DROP;
          b0->error = node->errors[SNAT_IN2OUT_ERROR_OUT_OF_PORTS];
          goto out;
        }
    }

  if (PREDICT_FALSE(icmp0->type != ICMP4_echo_request &&
                    !icmp_is_error_message (icmp0)))
    {
      b0->error = node->errors[SNAT_IN2OUT_ERROR_BAD_ICMP_TYPE];
      next0 = SNAT_IN2OUT_NEXT_DROP;
      goto out;
    }

  u32 now = (u32) vlib_time_now (sm->vlib_main);

  ses0->state = SNAT_SESSION_ICMP_ACTIVE;
  ses0->expire = now + sm->icmp_timeout;

out:
  *p_proto = protocol;
  if (ses0)
    {
      p_value->addr = new_addr0;
      p_value->fib_index = sm->outside_fib_index;
      p_value->port = ses0->out.out_port;
    }
  *p_dont_translate = dont_translate;
  if (d)
    *(snat_det_session_t**)d = ses0;
  if (e)
    *(snat_det_map_t**)e = dm0;
  return next0;
}

/**********************/
/*** worker handoff ***/
/**********************/
static inline uword
snat_in2out_worker_handoff_fn_inline (vlib_main_t * vm,
                                      vlib_node_runtime_t * node,
                                      vlib_frame_t * frame,
                                      u8 is_output)
{
  snat_main_t *sm = &snat_main;
  vlib_thread_main_t *tm = vlib_get_thread_main ();
  u32 n_left_from, *from, *to_next = 0;
  static __thread vlib_frame_queue_elt_t **handoff_queue_elt_by_worker_index;
  static __thread vlib_frame_queue_t **congested_handoff_queue_by_worker_index
    = 0;
  vlib_frame_queue_elt_t *hf = 0;
  vlib_frame_t *f = 0;
  int i;
  u32 n_left_to_next_worker = 0, *to_next_worker = 0;
  u32 next_worker_index = 0;
  u32 current_worker_index = ~0;
  u32 thread_index = vlib_get_thread_index ();
  u32 fq_index;
  u32 to_node_index;

  ASSERT (vec_len (sm->workers));

  if (is_output)
    {
      fq_index = sm->fq_in2out_output_index;
      to_node_index = sm->in2out_output_node_index;
    }
  else
    {
      fq_index = sm->fq_in2out_index;
      to_node_index = sm->in2out_node_index;
    }

  if (PREDICT_FALSE (handoff_queue_elt_by_worker_index == 0))
    {
      vec_validate (handoff_queue_elt_by_worker_index, tm->n_vlib_mains - 1);

      vec_validate_init_empty (congested_handoff_queue_by_worker_index,
			       sm->first_worker_index + sm->num_workers - 1,
			       (vlib_frame_queue_t *) (~0));
    }

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;

  while (n_left_from > 0)
    {
      u32 bi0;
      vlib_buffer_t *b0;
      u32 sw_if_index0;
      u32 rx_fib_index0;
      ip4_header_t * ip0;
      u8 do_handoff;

      bi0 = from[0];
      from += 1;
      n_left_from -= 1;

      b0 = vlib_get_buffer (vm, bi0);

      sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
      rx_fib_index0 = ip4_fib_table_get_index_for_sw_if_index(sw_if_index0);

      ip0 = vlib_buffer_get_current (b0);

      next_worker_index = sm->worker_in2out_cb(ip0, rx_fib_index0);

      if (PREDICT_FALSE (next_worker_index != thread_index))
        {
          do_handoff = 1;

          if (next_worker_index != current_worker_index)
            {
              if (hf)
                hf->n_vectors = VLIB_FRAME_SIZE - n_left_to_next_worker;

              hf = vlib_get_worker_handoff_queue_elt (fq_index,
                                                      next_worker_index,
                                                      handoff_queue_elt_by_worker_index);

              n_left_to_next_worker = VLIB_FRAME_SIZE - hf->n_vectors;
              to_next_worker = &hf->buffer_index[hf->n_vectors];
              current_worker_index = next_worker_index;
            }

          /* enqueue to correct worker thread */
          to_next_worker[0] = bi0;
          to_next_worker++;
          n_left_to_next_worker--;

          if (n_left_to_next_worker == 0)
            {
              hf->n_vectors = VLIB_FRAME_SIZE;
              vlib_put_frame_queue_elt (hf);
              current_worker_index = ~0;
              handoff_queue_elt_by_worker_index[next_worker_index] = 0;
              hf = 0;
            }
        }
      else
        {
          do_handoff = 0;
          /* if this is 1st frame */
          if (!f)
            {
              f = vlib_get_frame_to_node (vm, to_node_index);
              to_next = vlib_frame_vector_args (f);
            }

          to_next[0] = bi0;
          to_next += 1;
          f->n_vectors++;
        }

      if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
			 && (b0->flags & VLIB_BUFFER_IS_TRACED)))
	{
          snat_in2out_worker_handoff_trace_t *t =
            vlib_add_trace (vm, node, b0, sizeof (*t));
          t->next_worker_index = next_worker_index;
          t->do_handoff = do_handoff;
        }
    }

  if (f)
    vlib_put_frame_to_node (vm, to_node_index, f);

  if (hf)
    hf->n_vectors = VLIB_FRAME_SIZE - n_left_to_next_worker;

  /* Ship frames to the worker nodes */
  for (i = 0; i < vec_len (handoff_queue_elt_by_worker_index); i++)
    {
      if (handoff_queue_elt_by_worker_index[i])
	{
	  hf = handoff_queue_elt_by_worker_index[i];
	  /*
	   * It works better to let the handoff node
	   * rate-adapt, always ship the handoff queue element.
	   */
	  if (1 || hf->n_vectors == hf->last_n_vectors)
	    {
	      vlib_put_frame_queue_elt (hf);
	      handoff_queue_elt_by_worker_index[i] = 0;
	    }
	  else
	    hf->last_n_vectors = hf->n_vectors;
	}
      congested_handoff_queue_by_worker_index[i] =
	(vlib_frame_queue_t *) (~0);
    }
  hf = 0;
  current_worker_index = ~0;
  return frame->n_vectors;
}

static uword
snat_in2out_worker_handoff_fn (vlib_main_t * vm,
                               vlib_node_runtime_t * node,
                               vlib_frame_t * frame)
{
  return snat_in2out_worker_handoff_fn_inline (vm, node, frame, 0);
}

VLIB_REGISTER_NODE (snat_in2out_worker_handoff_node) = {
  .function = snat_in2out_worker_handoff_fn,
  .name = "nat44-in2out-worker-handoff",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_worker_handoff_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_next_nodes = 1,

  .next_nodes = {
    [0] = "error-drop",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_in2out_worker_handoff_node,
                              snat_in2out_worker_handoff_fn);

static uword
snat_in2out_output_worker_handoff_fn (vlib_main_t * vm,
                                      vlib_node_runtime_t * node,
                                      vlib_frame_t * frame)
{
  return snat_in2out_worker_handoff_fn_inline (vm, node, frame, 1);
}

VLIB_REGISTER_NODE (snat_in2out_output_worker_handoff_node) = {
  .function = snat_in2out_output_worker_handoff_fn,
  .name = "nat44-in2out-output-worker-handoff",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_worker_handoff_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_next_nodes = 1,

  .next_nodes = {
    [0] = "error-drop",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_in2out_output_worker_handoff_node,
                              snat_in2out_output_worker_handoff_fn);

static_always_inline int
is_hairpinning (snat_main_t *sm, ip4_address_t * dst_addr)
{
  snat_address_t * ap;
  clib_bihash_kv_8_8_t kv, value;
  snat_session_key_t m_key;

  vec_foreach (ap, sm->addresses)
    {
      if (ap->addr.as_u32 == dst_addr->as_u32)
        return 1;
    }

  m_key.addr.as_u32 = dst_addr->as_u32;
  m_key.fib_index = sm->outside_fib_index;
  m_key.port = 0;
  m_key.protocol = 0;
  kv.key = m_key.as_u64;
  if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
    return 1;

  return 0;
}

static uword
snat_hairpin_dst_fn (vlib_main_t * vm,
                     vlib_node_runtime_t * node,
                     vlib_frame_t * frame)
{
  u32 n_left_from, * from, * to_next;
  snat_in2out_next_t next_index;
  u32 pkts_processed = 0;
  snat_main_t * sm = &snat_main;

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;
  next_index = node->cached_next_index;

  while (n_left_from > 0)
    {
      u32 n_left_to_next;

      vlib_get_next_frame (vm, node, next_index,
			   to_next, n_left_to_next);

      while (n_left_from > 0 && n_left_to_next > 0)
	{
          u32 bi0;
	  vlib_buffer_t * b0;
          u32 next0;
          ip4_header_t * ip0;
          u32 proto0;

          /* speculatively enqueue b0 to the current next frame */
	  bi0 = from[0];
	  to_next[0] = bi0;
	  from += 1;
	  to_next += 1;
	  n_left_from -= 1;
	  n_left_to_next -= 1;

	  b0 = vlib_get_buffer (vm, bi0);
          next0 = SNAT_IN2OUT_NEXT_LOOKUP;
          ip0 = vlib_buffer_get_current (b0);

          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          vnet_buffer (b0)->snat.flags = 0;
          if (PREDICT_FALSE (is_hairpinning (sm, &ip0->dst_address)))
            {
              if (proto0 == SNAT_PROTOCOL_TCP || proto0 == SNAT_PROTOCOL_UDP)
                {
                  udp_header_t * udp0 = ip4_next_header (ip0);
                  tcp_header_t * tcp0 = (tcp_header_t *) udp0;

                  snat_hairpinning (sm, b0, ip0, udp0, tcp0, proto0);
                }
              else if (proto0 == SNAT_PROTOCOL_ICMP)
                {
                  icmp46_header_t * icmp0 = ip4_next_header (ip0);

                  snat_icmp_hairpinning (sm, b0, ip0, icmp0);
                }
              else
                {
                  snat_hairpinning_unknown_proto (sm, b0, ip0);
                }

              vnet_buffer (b0)->snat.flags = SNAT_FLAG_HAIRPINNING;
            }

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueue, maybe switch current next frame */
	  vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
					   to_next, n_left_to_next,
					   bi0, next0);
         }

      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
    }

  vlib_node_increment_counter (vm, snat_hairpin_dst_node.index,
                               SNAT_IN2OUT_ERROR_IN2OUT_PACKETS,
                               pkts_processed);
  return frame->n_vectors;
}

VLIB_REGISTER_NODE (snat_hairpin_dst_node) = {
  .function = snat_hairpin_dst_fn,
  .name = "nat44-hairpin-dst",
  .vector_size = sizeof (u32),
  .type = VLIB_NODE_TYPE_INTERNAL,
  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,
  .n_next_nodes = 2,
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_hairpin_dst_node,
                              snat_hairpin_dst_fn);

static uword
snat_hairpin_src_fn (vlib_main_t * vm,
                     vlib_node_runtime_t * node,
                     vlib_frame_t * frame)
{
  u32 n_left_from, * from, * to_next;
  snat_in2out_next_t next_index;
  u32 pkts_processed = 0;
  snat_main_t *sm = &snat_main;

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;
  next_index = node->cached_next_index;

  while (n_left_from > 0)
    {
      u32 n_left_to_next;

      vlib_get_next_frame (vm, node, next_index,
			   to_next, n_left_to_next);

      while (n_left_from > 0 && n_left_to_next > 0)
	{
          u32 bi0;
	  vlib_buffer_t * b0;
          u32 next0;
          snat_interface_t *i;
          u32 sw_if_index0;

          /* speculatively enqueue b0 to the current next frame */
	  bi0 = from[0];
	  to_next[0] = bi0;
	  from += 1;
	  to_next += 1;
	  n_left_from -= 1;
	  n_left_to_next -= 1;

	  b0 = vlib_get_buffer (vm, bi0);
          sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
          next0 = SNAT_HAIRPIN_SRC_NEXT_INTERFACE_OUTPUT;

          pool_foreach (i, sm->output_feature_interfaces,
          ({
            /* Only packets from NAT inside interface */
            if ((nat_interface_is_inside(i)) && (sw_if_index0 == i->sw_if_index))
              {
                if (PREDICT_FALSE ((vnet_buffer (b0)->snat.flags) &
                                    SNAT_FLAG_HAIRPINNING))
                  {
                    if (PREDICT_TRUE (sm->num_workers > 1))
                      next0 = SNAT_HAIRPIN_SRC_NEXT_SNAT_IN2OUT_WH;
                    else
                      next0 = SNAT_HAIRPIN_SRC_NEXT_SNAT_IN2OUT;
                  }
                break;
              }
          }));

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueue, maybe switch current next frame */
	  vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
					   to_next, n_left_to_next,
					   bi0, next0);
         }

      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
    }

  vlib_node_increment_counter (vm, snat_hairpin_src_node.index,
                               SNAT_IN2OUT_ERROR_IN2OUT_PACKETS,
                               pkts_processed);
  return frame->n_vectors;
}

VLIB_REGISTER_NODE (snat_hairpin_src_node) = {
  .function = snat_hairpin_src_fn,
  .name = "nat44-hairpin-src",
  .vector_size = sizeof (u32),
  .type = VLIB_NODE_TYPE_INTERNAL,
  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,
  .n_next_nodes = SNAT_HAIRPIN_SRC_N_NEXT,
  .next_nodes = {
     [SNAT_HAIRPIN_SRC_NEXT_DROP] = "error-drop",
     [SNAT_HAIRPIN_SRC_NEXT_SNAT_IN2OUT] = "nat44-in2out-output",
     [SNAT_HAIRPIN_SRC_NEXT_INTERFACE_OUTPUT] = "interface-output",
     [SNAT_HAIRPIN_SRC_NEXT_SNAT_IN2OUT_WH] = "nat44-in2out-output-worker-handoff",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_hairpin_src_node,
                              snat_hairpin_src_fn);

static uword
snat_in2out_fast_static_map_fn (vlib_main_t * vm,
                                vlib_node_runtime_t * node,
                                vlib_frame_t * frame)
{
  u32 n_left_from, * from, * to_next;
  snat_in2out_next_t next_index;
  u32 pkts_processed = 0;
  snat_main_t * sm = &snat_main;
  u32 stats_node_index;

  stats_node_index = snat_in2out_fast_node.index;

  from = vlib_frame_vector_args (frame);
  n_left_from = frame->n_vectors;
  next_index = node->cached_next_index;

  while (n_left_from > 0)
    {
      u32 n_left_to_next;

      vlib_get_next_frame (vm, node, next_index,
			   to_next, n_left_to_next);

      while (n_left_from > 0 && n_left_to_next > 0)
	{
          u32 bi0;
	  vlib_buffer_t * b0;
          u32 next0;
          u32 sw_if_index0;
          ip4_header_t * ip0;
          ip_csum_t sum0;
          u32 new_addr0, old_addr0;
          u16 old_port0, new_port0;
          udp_header_t * udp0;
          tcp_header_t * tcp0;
          icmp46_header_t * icmp0;
          snat_session_key_t key0, sm0;
          u32 proto0;
          u32 rx_fib_index0;

          /* speculatively enqueue b0 to the current next frame */
	  bi0 = from[0];
	  to_next[0] = bi0;
	  from += 1;
	  to_next += 1;
	  n_left_from -= 1;
	  n_left_to_next -= 1;

	  b0 = vlib_get_buffer (vm, bi0);
          next0 = SNAT_IN2OUT_NEXT_LOOKUP;

          ip0 = vlib_buffer_get_current (b0);
          udp0 = ip4_next_header (ip0);
          tcp0 = (tcp_header_t *) udp0;
          icmp0 = (icmp46_header_t *) udp0;

          sw_if_index0 = vnet_buffer(b0)->sw_if_index[VLIB_RX];
	  rx_fib_index0 = ip4_fib_table_get_index_for_sw_if_index(sw_if_index0);

          if (PREDICT_FALSE(ip0->ttl == 1))
            {
              vnet_buffer (b0)->sw_if_index[VLIB_TX] = (u32) ~ 0;
              icmp4_error_set_vnet_buffer (b0, ICMP4_time_exceeded,
                                           ICMP4_time_exceeded_ttl_exceeded_in_transit,
                                           0);
              next0 = SNAT_IN2OUT_NEXT_ICMP_ERROR;
              goto trace0;
            }

          proto0 = ip_proto_to_snat_proto (ip0->protocol);

          if (PREDICT_FALSE (proto0 == ~0))
              goto trace0;

          if (PREDICT_FALSE (proto0 == SNAT_PROTOCOL_ICMP))
            {
              next0 = icmp_in2out(sm, b0, ip0, icmp0, sw_if_index0,
                                  rx_fib_index0, node, next0, ~0, 0, 0);
              goto trace0;
            }

          key0.addr = ip0->src_address;
          key0.protocol = proto0;
          key0.port = udp0->src_port;
          key0.fib_index = rx_fib_index0;

          if (snat_static_mapping_match(sm, key0, &sm0, 0, 0, 0))
            {
              b0->error = node->errors[SNAT_IN2OUT_ERROR_NO_TRANSLATION];
              next0= SNAT_IN2OUT_NEXT_DROP;
              goto trace0;
            }

          new_addr0 = sm0.addr.as_u32;
          new_port0 = sm0.port;
          vnet_buffer(b0)->sw_if_index[VLIB_TX] = sm0.fib_index;
          old_addr0 = ip0->src_address.as_u32;
          ip0->src_address.as_u32 = new_addr0;

          sum0 = ip0->checksum;
          sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                 ip4_header_t,
                                 src_address /* changed member */);
          ip0->checksum = ip_csum_fold (sum0);

          if (PREDICT_FALSE(new_port0 != udp0->dst_port))
            {
              if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
                {
                  old_port0 = tcp0->src_port;
                  tcp0->src_port = new_port0;

                  sum0 = tcp0->checksum;
                  sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                         ip4_header_t,
                                         dst_address /* changed member */);
                  sum0 = ip_csum_update (sum0, old_port0, new_port0,
                                         ip4_header_t /* cheat */,
                                         length /* changed member */);
                  tcp0->checksum = ip_csum_fold(sum0);
                }
              else
                {
                  old_port0 = udp0->src_port;
                  udp0->src_port = new_port0;
                  udp0->checksum = 0;
                }
            }
          else
            {
              if (PREDICT_TRUE(proto0 == SNAT_PROTOCOL_TCP))
                {
                  sum0 = tcp0->checksum;
                  sum0 = ip_csum_update (sum0, old_addr0, new_addr0,
                                         ip4_header_t,
                                         dst_address /* changed member */);
                  tcp0->checksum = ip_csum_fold(sum0);
                }
            }

          /* Hairpinning */
          snat_hairpinning (sm, b0, ip0, udp0, tcp0, proto0);

        trace0:
          if (PREDICT_FALSE((node->flags & VLIB_NODE_FLAG_TRACE)
                            && (b0->flags & VLIB_BUFFER_IS_TRACED)))
            {
              snat_in2out_trace_t *t =
                 vlib_add_trace (vm, node, b0, sizeof (*t));
              t->sw_if_index = sw_if_index0;
              t->next_index = next0;
            }

          pkts_processed += next0 != SNAT_IN2OUT_NEXT_DROP;

          /* verify speculative enqueue, maybe switch current next frame */
	  vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
					   to_next, n_left_to_next,
					   bi0, next0);
	}

      vlib_put_next_frame (vm, node, next_index, n_left_to_next);
    }

  vlib_node_increment_counter (vm, stats_node_index,
                               SNAT_IN2OUT_ERROR_IN2OUT_PACKETS,
                               pkts_processed);
  return frame->n_vectors;
}


VLIB_REGISTER_NODE (snat_in2out_fast_node) = {
  .function = snat_in2out_fast_static_map_fn,
  .name = "nat44-in2out-fast",
  .vector_size = sizeof (u32),
  .format_trace = format_snat_in2out_fast_trace,
  .type = VLIB_NODE_TYPE_INTERNAL,

  .n_errors = ARRAY_LEN(snat_in2out_error_strings),
  .error_strings = snat_in2out_error_strings,

  .runtime_data_bytes = sizeof (snat_runtime_t),

  .n_next_nodes = SNAT_IN2OUT_N_NEXT,

  /* edit / add dispositions here */
  .next_nodes = {
    [SNAT_IN2OUT_NEXT_DROP] = "error-drop",
    [SNAT_IN2OUT_NEXT_LOOKUP] = "ip4-lookup",
    [SNAT_IN2OUT_NEXT_SLOW_PATH] = "nat44-in2out-slowpath",
    [SNAT_IN2OUT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
    [SNAT_IN2OUT_NEXT_REASS] = "nat44-in2out-reass",
  },
};

VLIB_NODE_FUNCTION_MULTIARCH (snat_in2out_fast_node, snat_in2out_fast_static_map_fn);