aboutsummaryrefslogtreecommitdiffstats
path: root/doc/guides/sample_app_ug/l3_forward.rst
blob: c885cdb7b9f3b530b97cdb202c09f10717846d80 (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
..  BSD LICENSE
    Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.
    * Neither the name of Intel Corporation nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

L3 Forwarding Sample Application
================================

The L3 Forwarding application is a simple example of packet processing using the DPDK.
The application performs L3 forwarding.

Overview
--------

The application demonstrates the use of the hash and LPM libraries in the DPDK to implement packet forwarding.
The initialization and run-time paths are very similar to those of the :doc:`l2_forward_real_virtual`.
The main difference from the L2 Forwarding sample application is that the forwarding decision
is made based on information read from the input packet.

The lookup method is either hash-based or LPM-based and is selected at compile time. When the selected lookup method is hash-based,
a hash object is used to emulate the flow classification stage.
The hash object is used in correlation with a flow table to map each input packet to its flow at runtime.

The hash lookup key is represented by a DiffServ 5-tuple composed of the following fields read from the input packet:
Source IP Address, Destination IP Address, Protocol, Source Port and Destination Port.
The ID of the output interface for the input packet is read from the identified flow table entry.
The set of flows used by the application is statically configured and loaded into the hash at initialization time.
When the selected lookup method is LPM based, an LPM object is used to emulate the forwarding stage for IPv4 packets.
The LPM object is used as the routing table to identify the next hop for each input packet at runtime.

The LPM lookup key is represented by the Destination IP Address field read from the input packet.
The ID of the output interface for the input packet is the next hop returned by the LPM lookup.
The set of LPM rules used by the application is statically configured and loaded into the LPM object at initialization time.

In the sample application, hash-based forwarding supports IPv4 and IPv6. LPM-based forwarding supports IPv4 only.

Compiling the Application
-------------------------

To compile the application:

#.  Go to the sample application directory:

    .. code-block:: console

        export RTE_SDK=/path/to/rte_sdk
        cd ${RTE_SDK}/examples/l3fwd

#.  Set the target (a default target is used if not specified). For example:

    .. code-block:: console

        export RTE_TARGET=x86_64-native-linuxapp-gcc

    See the *DPDK Getting Started Guide* for possible RTE_TARGET values.

#.  Build the application:

    .. code-block:: console

        make

Running the Application
-----------------------

The application has a number of command line options::

    ./l3fwd [EAL options] -- -p PORTMASK
                             [-P]
                             [-E]
                             [-L]
                             --config(port,queue,lcore)[,(port,queue,lcore)]
                             [--eth-dest=X,MM:MM:MM:MM:MM:MM]
                             [--enable-jumbo [--max-pkt-len PKTLEN]]
                             [--no-numa]
                             [--hash-entry-num]
                             [--ipv6]
                             [--parse-ptype]

Where,

* ``-p PORTMASK:`` Hexadecimal bitmask of ports to configure

* ``-P:`` Optional, sets all ports to promiscuous mode so that packets are accepted regardless of the packet's Ethernet MAC destination address.
  Without this option, only packets with the Ethernet MAC destination address set to the Ethernet address of the port are accepted.

* ``-E:`` Optional, enable exact match.

* ``-L:`` Optional, enable longest prefix match.

* ``--config (port,queue,lcore)[,(port,queue,lcore)]:`` Determines which queues from which ports are mapped to which cores.

* ``--eth-dest=X,MM:MM:MM:MM:MM:MM:`` Optional, ethernet destination for port X.

* ``--enable-jumbo:`` Optional, enables jumbo frames.

* ``--max-pkt-len:`` Optional, under the premise of enabling jumbo, maximum packet length in decimal (64-9600).

* ``--no-numa:`` Optional, disables numa awareness.

* ``--hash-entry-num:`` Optional, specifies the hash entry number in hexadecimal to be setup.

* ``--ipv6:`` Optional, set if running ipv6 packets.

* ``--parse-ptype:`` Optional, set to use software to analyze packet type. Without this option, hardware will check the packet type.

For example, consider a dual processor socket platform where cores 0-7 and 16-23 appear on socket 0, while cores 8-15 and 24-31 appear on socket 1.
Let's say that the programmer wants to use memory from both NUMA nodes, the platform has only two ports, one connected to each NUMA node,
and the programmer wants to use two cores from each processor socket to do the packet processing.

To enable L3 forwarding between two ports, using two cores, cores 1 and 2, from each processor,
while also taking advantage of local memory access by optimizing around NUMA, the programmer must enable two queues from each port,
pin to the appropriate cores and allocate memory from the appropriate NUMA node. This is achieved using the following command:

.. code-block:: console

    ./build/l3fwd -c 606 -n 4 -- -p 0x3 --config="(0,0,1),(0,1,2),(1,0,9),(1,1,10)"

In this command:

*   The -c option enables cores 0, 1, 2, 3

*   The -p option enables ports 0 and 1

*   The --config option enables two queues on each port and maps each (port,queue) pair to a specific core.
    Logic to enable multiple RX queues using RSS and to allocate memory from the correct NUMA nodes
    is included in the application and is done transparently.
    The following table shows the mapping in this example:

+----------+-----------+-----------+-------------------------------------+
| **Port** | **Queue** | **lcore** | **Description**                     |
|          |           |           |                                     |
+----------+-----------+-----------+-------------------------------------+
| 0        | 0         | 0         | Map queue 0 from port 0 to lcore 0. |
|          |           |           |                                     |
+----------+-----------+-----------+-------------------------------------+
| 0        | 1         | 2         | Map queue 1 from port 0 to lcore 2. |
|          |           |           |                                     |
+----------+-----------+-----------+-------------------------------------+
| 1        | 0         | 1         | Map queue 0 from port 1 to lcore 1. |
|          |           |           |                                     |
+----------+-----------+-----------+-------------------------------------+
| 1        | 1         | 3         | Map queue 1 from port 1 to lcore 3. |
|          |           |           |                                     |
+----------+-----------+-----------+-------------------------------------+

Refer to the *DPDK Getting Started Guide* for general information on running applications and
the Environment Abstraction Layer (EAL) options.

.. _l3_fwd_explanation:

Explanation
-----------

The following sections provide some explanation of the sample application code. As mentioned in the overview section,
the initialization and run-time paths are very similar to those of the :doc:`l2_forward_real_virtual`.
The following sections describe aspects that are specific to the L3 Forwarding sample application.

Hash Initialization
~~~~~~~~~~~~~~~~~~~

The hash object is created and loaded with the pre-configured entries read from a global array,
and then generate the expected 5-tuple as key to keep consistence with those of real flow
for the convenience to execute hash performance test on 4M/8M/16M flows.

.. note::

    The Hash initialization will setup both ipv4 and ipv6 hash table,
    and populate the either table depending on the value of variable ipv6.
    To support the hash performance test with up to 8M single direction flows/16M bi-direction flows,
    populate_ipv4_many_flow_into_table() function will populate the hash table with specified hash table entry number(default 4M).

.. note::

    Value of global variable ipv6 can be specified with --ipv6 in the command line.
    Value of global variable hash_entry_number,
    which is used to specify the total hash entry number for all used ports in hash performance test,
    can be specified with --hash-entry-num VALUE in command line, being its default value 4.

.. code-block:: c

    #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)

        static void
        setup_hash(int socketid)
        {
            // ...

            if (hash_entry_number != HASH_ENTRY_NUMBER_DEFAULT) {
                if (ipv6 == 0) {
                    /* populate the ipv4 hash */
                    populate_ipv4_many_flow_into_table(ipv4_l3fwd_lookup_struct[socketid], hash_entry_number);
                } else {
                    /* populate the ipv6 hash */
                    populate_ipv6_many_flow_into_table( ipv6_l3fwd_lookup_struct[socketid], hash_entry_number);
                }
            } else
                if (ipv6 == 0) {
                    /* populate the ipv4 hash */
                    populate_ipv4_few_flow_into_table(ipv4_l3fwd_lookup_struct[socketid]);
                } else {
                    /* populate the ipv6 hash */
                    populate_ipv6_few_flow_into_table(ipv6_l3fwd_lookup_struct[socketid]);
                }
            }
        }
    #endif

LPM Initialization
~~~~~~~~~~~~~~~~~~

The LPM object is created and loaded with the pre-configured entries read from a global array.

.. code-block:: c

    #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)

    static void
    setup_lpm(int socketid)
    {
        unsigned i;
        int ret;
        char s[64];

        /* create the LPM table */

        snprintf(s, sizeof(s), "IPV4_L3FWD_LPM_%d", socketid);

        ipv4_l3fwd_lookup_struct[socketid] = rte_lpm_create(s, socketid, IPV4_L3FWD_LPM_MAX_RULES, 0);

        if (ipv4_l3fwd_lookup_struct[socketid] == NULL)
            rte_exit(EXIT_FAILURE, "Unable to create the l3fwd LPM table"
                " on socket %d\n", socketid);

        /* populate the LPM table */

        for (i = 0; i < IPV4_L3FWD_NUM_ROUTES; i++) {
            /* skip unused ports */

            if ((1 << ipv4_l3fwd_route_array[i].if_out & enabled_port_mask) == 0)
                continue;

            ret = rte_lpm_add(ipv4_l3fwd_lookup_struct[socketid], ipv4_l3fwd_route_array[i].ip,
           	                    ipv4_l3fwd_route_array[i].depth, ipv4_l3fwd_route_array[i].if_out);

            if (ret < 0) {
                rte_exit(EXIT_FAILURE, "Unable to add entry %u to the "
                        "l3fwd LPM table on socket %d\n", i, socketid);
            }

            printf("LPM: Adding route 0x%08x / %d (%d)\n",
                (unsigned)ipv4_l3fwd_route_array[i].ip, ipv4_l3fwd_route_array[i].depth, ipv4_l3fwd_route_array[i].if_out);
        }
    }
    #endif

Packet Forwarding for Hash-based Lookups
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For each input packet, the packet forwarding operation is done by the l3fwd_simple_forward()
or simple_ipv4_fwd_4pkts() function for IPv4 packets or the simple_ipv6_fwd_4pkts() function for IPv6 packets.
The l3fwd_simple_forward() function provides the basic functionality for both IPv4 and IPv6 packet forwarding
for any number of burst packets received,
and the packet forwarding decision (that is, the identification of the output interface for the packet)
for hash-based lookups is done by the  get_ipv4_dst_port() or get_ipv6_dst_port() function.
The get_ipv4_dst_port() function is shown below:

.. code-block:: c

    static inline uint8_t
    get_ipv4_dst_port(void *ipv4_hdr, uint8_t portid, lookup_struct_t *ipv4_l3fwd_lookup_struct)
    {
        int ret = 0;
        union ipv4_5tuple_host key;

        ipv4_hdr = (uint8_t \*)ipv4_hdr + offsetof(struct ipv4_hdr, time_to_live);

        m128i data = _mm_loadu_si128(( m128i*)(ipv4_hdr));

        /* Get 5 tuple: dst port, src port, dst IP address, src IP address and protocol */

        key.xmm = _mm_and_si128(data, mask0);

        /* Find destination port */

        ret = rte_hash_lookup(ipv4_l3fwd_lookup_struct, (const void *)&key);

        return (uint8_t)((ret < 0)? portid : ipv4_l3fwd_out_if[ret]);
    }

The get_ipv6_dst_port() function is similar to the get_ipv4_dst_port() function.

The simple_ipv4_fwd_4pkts() and simple_ipv6_fwd_4pkts() function are optimized for continuous 4 valid ipv4 and ipv6 packets,
they leverage the multiple buffer optimization to boost the performance of forwarding packets with the exact match on hash table.
The key code snippet of simple_ipv4_fwd_4pkts() is shown below:

.. code-block:: c

    static inline void
    simple_ipv4_fwd_4pkts(struct rte_mbuf* m[4], uint8_t portid, struct lcore_conf *qconf)
    {
        // ...

        data[0] = _mm_loadu_si128(( m128i*)(rte_pktmbuf_mtod(m[0], unsigned char *) + sizeof(struct ether_hdr) + offsetof(struct ipv4_hdr, time_to_live)));
        data[1] = _mm_loadu_si128(( m128i*)(rte_pktmbuf_mtod(m[1], unsigned char *) + sizeof(struct ether_hdr) + offsetof(struct ipv4_hdr, time_to_live)));
        data[2] = _mm_loadu_si128(( m128i*)(rte_pktmbuf_mtod(m[2], unsigned char *) + sizeof(struct ether_hdr) + offsetof(struct ipv4_hdr, time_to_live)));
        data[3] = _mm_loadu_si128(( m128i*)(rte_pktmbuf_mtod(m[3], unsigned char *) + sizeof(struct ether_hdr) + offsetof(struct ipv4_hdr, time_to_live)));

        key[0].xmm = _mm_and_si128(data[0], mask0);
        key[1].xmm = _mm_and_si128(data[1], mask0);
        key[2].xmm = _mm_and_si128(data[2], mask0);
        key[3].xmm = _mm_and_si128(data[3], mask0);

        const void *key_array[4] = {&key[0], &key[1], &key[2],&key[3]};

        rte_hash_lookup_bulk(qconf->ipv4_lookup_struct, &key_array[0], 4, ret);

        dst_port[0] = (ret[0] < 0)? portid:ipv4_l3fwd_out_if[ret[0]];
        dst_port[1] = (ret[1] < 0)? portid:ipv4_l3fwd_out_if[ret[1]];
        dst_port[2] = (ret[2] < 0)? portid:ipv4_l3fwd_out_if[ret[2]];
        dst_port[3] = (ret[3] < 0)? portid:ipv4_l3fwd_out_if[ret[3]];

        // ...
    }

The simple_ipv6_fwd_4pkts() function is similar to the simple_ipv4_fwd_4pkts() function.

Known issue: IP packets with extensions or IP packets which are not TCP/UDP cannot work well at this mode.

Packet Forwarding for LPM-based Lookups
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For each input packet, the packet forwarding operation is done by the l3fwd_simple_forward() function,
but the packet forwarding decision (that is, the identification of the output interface for the packet)
for LPM-based lookups is done by the get_ipv4_dst_port() function below:

.. code-block:: c

    static inline uint8_t
    get_ipv4_dst_port(struct ipv4_hdr *ipv4_hdr, uint8_t portid, lookup_struct_t *ipv4_l3fwd_lookup_struct)
    {
        uint8_t next_hop;

        return (uint8_t) ((rte_lpm_lookup(ipv4_l3fwd_lookup_struct, rte_be_to_cpu_32(ipv4_hdr->dst_addr), &next_hop) == 0)? next_hop : portid);
    }
'>1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 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
/* SPDX-License-Identifier: BSD-3-Clause
 *
 *   Copyright (c) 2016 Freescale Semiconductor, Inc. All rights reserved.
 *   Copyright 2017-2018 NXP
 *
 */

#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <net/if.h>

#include <rte_byteorder.h>
#include <rte_common.h>
#include <rte_cryptodev_pmd.h>
#include <rte_crypto.h>
#include <rte_cryptodev.h>
#include <rte_security_driver.h>
#include <rte_cycles.h>
#include <rte_dev.h>
#include <rte_kvargs.h>
#include <rte_malloc.h>
#include <rte_mbuf.h>
#include <rte_memcpy.h>
#include <rte_string_fns.h>
#include <rte_spinlock.h>

#include <fsl_usd.h>
#include <fsl_qman.h>
#include <of.h>

/* RTA header files */
#include <hw/desc/common.h>
#include <hw/desc/algo.h>
#include <hw/desc/ipsec.h>

#include <rte_dpaa_bus.h>
#include <dpaa_sec.h>
#include <dpaa_sec_log.h>

enum rta_sec_era rta_sec_era;

int dpaa_logtype_sec;

static uint8_t cryptodev_driver_id;

static __thread struct rte_crypto_op **dpaa_sec_ops;
static __thread int dpaa_sec_op_nb;

static int
dpaa_sec_attach_sess_q(struct dpaa_sec_qp *qp, dpaa_sec_session *sess);

static inline void
dpaa_sec_op_ending(struct dpaa_sec_op_ctx *ctx)
{
	if (!ctx->fd_status) {
		ctx->op->status = RTE_CRYPTO_OP_STATUS_SUCCESS;
	} else {
		DPAA_SEC_DP_WARN("SEC return err: 0x%x", ctx->fd_status);
		ctx->op->status = RTE_CRYPTO_OP_STATUS_ERROR;
	}

	/* report op status to sym->op and then free the ctx memeory  */
	rte_mempool_put(ctx->ctx_pool, (void *)ctx);
}

static inline struct dpaa_sec_op_ctx *
dpaa_sec_alloc_ctx(dpaa_sec_session *ses)
{
	struct dpaa_sec_op_ctx *ctx;
	int retval;

	retval = rte_mempool_get(ses->ctx_pool, (void **)(&ctx));
	if (!ctx || retval) {
		DPAA_SEC_DP_WARN("Alloc sec descriptor failed!");
		return NULL;
	}
	/*
	 * Clear SG memory. There are 16 SG entries of 16 Bytes each.
	 * one call to dcbz_64() clear 64 bytes, hence calling it 4 times
	 * to clear all the SG entries. dpaa_sec_alloc_ctx() is called for
	 * each packet, memset is costlier than dcbz_64().
	 */
	dcbz_64(&ctx->job.sg[SG_CACHELINE_0]);
	dcbz_64(&ctx->job.sg[SG_CACHELINE_1]);
	dcbz_64(&ctx->job.sg[SG_CACHELINE_2]);
	dcbz_64(&ctx->job.sg[SG_CACHELINE_3]);

	ctx->ctx_pool = ses->ctx_pool;
	ctx->vtop_offset = (size_t) ctx
				- rte_mempool_virt2iova(ctx);

	return ctx;
}

static inline rte_iova_t
dpaa_mem_vtop(void *vaddr)
{
	const struct rte_memseg *ms;

	ms = rte_mem_virt2memseg(vaddr, NULL);
	if (ms)
		return ms->iova + RTE_PTR_DIFF(vaddr, ms->addr);
	return (size_t)NULL;
}

static inline void *
dpaa_mem_ptov(rte_iova_t paddr)
{
	void *va;

	va = (void *)dpaax_iova_table_get_va(paddr);
	if (likely(va))
		return va;

	return rte_mem_iova2virt(paddr);
}

static void
ern_sec_fq_handler(struct qman_portal *qm __rte_unused,
		   struct qman_fq *fq,
		   const struct qm_mr_entry *msg)
{
	DPAA_SEC_DP_ERR("sec fq %d error, RC = %x, seqnum = %x\n",
			fq->fqid, msg->ern.rc, msg->ern.seqnum);
}

/* initialize the queue with dest chan as caam chan so that
 * all the packets in this queue could be dispatched into caam
 */
static int
dpaa_sec_init_rx(struct qman_fq *fq_in, rte_iova_t hwdesc,
		 uint32_t fqid_out)
{
	struct qm_mcc_initfq fq_opts;
	uint32_t flags;
	int ret = -1;

	/* Clear FQ options */
	memset(&fq_opts, 0x00, sizeof(struct qm_mcc_initfq));

	flags = QMAN_INITFQ_FLAG_SCHED;
	fq_opts.we_mask = QM_INITFQ_WE_DESTWQ | QM_INITFQ_WE_CONTEXTA |
			  QM_INITFQ_WE_CONTEXTB;

	qm_fqd_context_a_set64(&fq_opts.fqd, hwdesc);
	fq_opts.fqd.context_b = fqid_out;
	fq_opts.fqd.dest.channel = qm_channel_caam;
	fq_opts.fqd.dest.wq = 0;

	fq_in->cb.ern  = ern_sec_fq_handler;

	DPAA_SEC_DEBUG("in-%x out-%x", fq_in->fqid, fqid_out);

	ret = qman_init_fq(fq_in, flags, &fq_opts);
	if (unlikely(ret != 0))
		DPAA_SEC_ERR("qman_init_fq failed %d", ret);

	return ret;
}

/* something is put into in_fq and caam put the crypto result into out_fq */
static enum qman_cb_dqrr_result
dqrr_out_fq_cb_rx(struct qman_portal *qm __always_unused,
		  struct qman_fq *fq __always_unused,
		  const struct qm_dqrr_entry *dqrr)
{
	const struct qm_fd *fd;
	struct dpaa_sec_job *job;
	struct dpaa_sec_op_ctx *ctx;

	if (dpaa_sec_op_nb >= DPAA_SEC_BURST)
		return qman_cb_dqrr_defer;

	if (!(dqrr->stat & QM_DQRR_STAT_FD_VALID))
		return qman_cb_dqrr_consume;

	fd = &dqrr->fd;
	/* sg is embedded in an op ctx,
	 * sg[0] is for output
	 * sg[1] for input
	 */
	job = dpaa_mem_ptov(qm_fd_addr_get64(fd));

	ctx = container_of(job, struct dpaa_sec_op_ctx, job);
	ctx->fd_status = fd->status;
	if (ctx->op->sess_type == RTE_CRYPTO_OP_SECURITY_SESSION) {
		struct qm_sg_entry *sg_out;
		uint32_t len;

		sg_out = &job->sg[0];
		hw_sg_to_cpu(sg_out);
		len = sg_out->length;
		ctx->op->sym->m_src->pkt_len = len;
		ctx->op->sym->m_src->data_len = len;
	}
	dpaa_sec_ops[dpaa_sec_op_nb++] = ctx->op;
	dpaa_sec_op_ending(ctx);

	return qman_cb_dqrr_consume;
}

/* caam result is put into this queue */
static int
dpaa_sec_init_tx(struct qman_fq *fq)
{
	int ret;
	struct qm_mcc_initfq opts;
	uint32_t flags;

	flags = QMAN_FQ_FLAG_NO_ENQUEUE | QMAN_FQ_FLAG_LOCKED |
		QMAN_FQ_FLAG_DYNAMIC_FQID;

	ret = qman_create_fq(0, flags, fq);
	if (unlikely(ret)) {
		DPAA_SEC_ERR("qman_create_fq failed");
		return ret;
	}

	memset(&opts, 0, sizeof(opts));
	opts.we_mask = QM_INITFQ_WE_DESTWQ | QM_INITFQ_WE_FQCTRL |
		       QM_INITFQ_WE_CONTEXTA | QM_INITFQ_WE_CONTEXTB;

	/* opts.fqd.dest.channel = dpaa_sec_pool_chan; */

	fq->cb.dqrr = dqrr_out_fq_cb_rx;
	fq->cb.ern  = ern_sec_fq_handler;

	ret = qman_init_fq(fq, 0, &opts);
	if (unlikely(ret)) {
		DPAA_SEC_ERR("unable to init caam source fq!");
		return ret;
	}

	return ret;
}

static inline int is_cipher_only(dpaa_sec_session *ses)
{
	return ((ses->cipher_alg != RTE_CRYPTO_CIPHER_NULL) &&
		(ses->auth_alg == RTE_CRYPTO_AUTH_NULL));
}

static inline int is_auth_only(dpaa_sec_session *ses)
{
	return ((ses->cipher_alg == RTE_CRYPTO_CIPHER_NULL) &&
		(ses->auth_alg != RTE_CRYPTO_AUTH_NULL));
}

static inline int is_aead(dpaa_sec_session *ses)
{
	return ((ses->cipher_alg == 0) &&
		(ses->auth_alg == 0) &&
		(ses->aead_alg != 0));
}

static inline int is_auth_cipher(dpaa_sec_session *ses)
{
	return ((ses->cipher_alg != RTE_CRYPTO_CIPHER_NULL) &&
		(ses->auth_alg != RTE_CRYPTO_AUTH_NULL) &&
		(ses->proto_alg != RTE_SECURITY_PROTOCOL_IPSEC));
}

static inline int is_proto_ipsec(dpaa_sec_session *ses)
{
	return (ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC);
}

static inline int is_encode(dpaa_sec_session *ses)
{
	return ses->dir == DIR_ENC;
}

static inline int is_decode(dpaa_sec_session *ses)
{
	return ses->dir == DIR_DEC;
}

static inline void
caam_auth_alg(dpaa_sec_session *ses, struct alginfo *alginfo_a)
{
	switch (ses->auth_alg) {
	case RTE_CRYPTO_AUTH_NULL:
		alginfo_a->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_HMAC_NULL : 0;
		ses->digest_length = 0;
		break;
	case RTE_CRYPTO_AUTH_MD5_HMAC:
		alginfo_a->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_HMAC_MD5_96 : OP_ALG_ALGSEL_MD5;
		alginfo_a->algmode = OP_ALG_AAI_HMAC;
		break;
	case RTE_CRYPTO_AUTH_SHA1_HMAC:
		alginfo_a->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_HMAC_SHA1_96 : OP_ALG_ALGSEL_SHA1;
		alginfo_a->algmode = OP_ALG_AAI_HMAC;
		break;
	case RTE_CRYPTO_AUTH_SHA224_HMAC:
		alginfo_a->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_HMAC_SHA1_160 : OP_ALG_ALGSEL_SHA224;
		alginfo_a->algmode = OP_ALG_AAI_HMAC;
		break;
	case RTE_CRYPTO_AUTH_SHA256_HMAC:
		alginfo_a->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_HMAC_SHA2_256_128 : OP_ALG_ALGSEL_SHA256;
		alginfo_a->algmode = OP_ALG_AAI_HMAC;
		break;
	case RTE_CRYPTO_AUTH_SHA384_HMAC:
		alginfo_a->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_HMAC_SHA2_384_192 : OP_ALG_ALGSEL_SHA384;
		alginfo_a->algmode = OP_ALG_AAI_HMAC;
		break;
	case RTE_CRYPTO_AUTH_SHA512_HMAC:
		alginfo_a->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_HMAC_SHA2_512_256 : OP_ALG_ALGSEL_SHA512;
		alginfo_a->algmode = OP_ALG_AAI_HMAC;
		break;
	default:
		DPAA_SEC_ERR("unsupported auth alg %u", ses->auth_alg);
	}
}

static inline void
caam_cipher_alg(dpaa_sec_session *ses, struct alginfo *alginfo_c)
{
	switch (ses->cipher_alg) {
	case RTE_CRYPTO_CIPHER_NULL:
		alginfo_c->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_NULL : 0;
		break;
	case RTE_CRYPTO_CIPHER_AES_CBC:
		alginfo_c->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_AES_CBC : OP_ALG_ALGSEL_AES;
		alginfo_c->algmode = OP_ALG_AAI_CBC;
		break;
	case RTE_CRYPTO_CIPHER_3DES_CBC:
		alginfo_c->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_3DES : OP_ALG_ALGSEL_3DES;
		alginfo_c->algmode = OP_ALG_AAI_CBC;
		break;
	case RTE_CRYPTO_CIPHER_AES_CTR:
		alginfo_c->algtype =
			(ses->proto_alg == RTE_SECURITY_PROTOCOL_IPSEC) ?
			OP_PCL_IPSEC_AES_CTR : OP_ALG_ALGSEL_AES;
		alginfo_c->algmode = OP_ALG_AAI_CTR;
		break;
	default:
		DPAA_SEC_ERR("unsupported cipher alg %d", ses->cipher_alg);
	}
}

static inline void
caam_aead_alg(dpaa_sec_session *ses, struct alginfo *alginfo)
{
	switch (ses->aead_alg) {
	case RTE_CRYPTO_AEAD_AES_GCM:
		alginfo->algtype = OP_ALG_ALGSEL_AES;
		alginfo->algmode = OP_ALG_AAI_GCM;
		break;
	default:
		DPAA_SEC_ERR("unsupported AEAD alg %d", ses->aead_alg);
	}
}

/* prepare ipsec proto command block of the session */
static int
dpaa_sec_prep_ipsec_cdb(dpaa_sec_session *ses)
{
	struct alginfo cipherdata = {0}, authdata = {0};
	struct sec_cdb *cdb = &ses->cdb;
	int32_t shared_desc_len = 0;
	int err;
#if RTE_BYTE_ORDER == RTE_BIG_ENDIAN
	int swap = false;
#else
	int swap = true;
#endif

	caam_cipher_alg(ses, &cipherdata);
	if (cipherdata.algtype == (unsigned int)DPAA_SEC_ALG_UNSUPPORT) {
		DPAA_SEC_ERR("not supported cipher alg");
		return -ENOTSUP;
	}

	cipherdata.key = (size_t)ses->cipher_key.data;
	cipherdata.keylen = ses->cipher_key.length;
	cipherdata.key_enc_flags = 0;
	cipherdata.key_type = RTA_DATA_IMM;

	caam_auth_alg(ses, &authdata);
	if (authdata.algtype == (unsigned int)DPAA_SEC_ALG_UNSUPPORT) {
		DPAA_SEC_ERR("not supported auth alg");
		return -ENOTSUP;
	}

	authdata.key = (size_t)ses->auth_key.data;
	authdata.keylen = ses->auth_key.length;
	authdata.key_enc_flags = 0;
	authdata.key_type = RTA_DATA_IMM;

	cdb->sh_desc[0] = cipherdata.keylen;
	cdb->sh_desc[1] = authdata.keylen;
	err = rta_inline_query(IPSEC_AUTH_VAR_AES_DEC_BASE_DESC_LEN,
			       MIN_JOB_DESC_SIZE,
			       (unsigned int *)cdb->sh_desc,
			       &cdb->sh_desc[2], 2);

	if (err < 0) {
		DPAA_SEC_ERR("Crypto: Incorrect key lengths");
		return err;
	}
	if (cdb->sh_desc[2] & 1)
		cipherdata.key_type = RTA_DATA_IMM;
	else {
		cipherdata.key = (size_t)dpaa_mem_vtop(
					(void *)(size_t)cipherdata.key);
		cipherdata.key_type = RTA_DATA_PTR;
	}
	if (cdb->sh_desc[2] & (1<<1))
		authdata.key_type = RTA_DATA_IMM;
	else {
		authdata.key = (size_t)dpaa_mem_vtop(
					(void *)(size_t)authdata.key);
		authdata.key_type = RTA_DATA_PTR;
	}

	cdb->sh_desc[0] = 0;
	cdb->sh_desc[1] = 0;
	cdb->sh_desc[2] = 0;
	if (ses->dir == DIR_ENC) {
		shared_desc_len = cnstr_shdsc_ipsec_new_encap(
				cdb->sh_desc,
				true, swap, SHR_SERIAL,
				&ses->encap_pdb,
				(uint8_t *)&ses->ip4_hdr,
				&cipherdata, &authdata);
	} else if (ses->dir == DIR_DEC) {
		shared_desc_len = cnstr_shdsc_ipsec_new_decap(
				cdb->sh_desc,
				true, swap, SHR_SERIAL,
				&ses->decap_pdb,
				&cipherdata, &authdata);
	}
	return shared_desc_len;
}

/* prepare command block of the session */
static int
dpaa_sec_prep_cdb(dpaa_sec_session *ses)
{
	struct alginfo alginfo_c = {0}, alginfo_a = {0}, alginfo = {0};
	int32_t shared_desc_len = 0;
	struct sec_cdb *cdb = &ses->cdb;
	int err;
#if RTE_BYTE_ORDER == RTE_BIG_ENDIAN
	int swap = false;
#else
	int swap = true;
#endif

	memset(cdb, 0, sizeof(struct sec_cdb));

	if (is_proto_ipsec(ses)) {
		shared_desc_len = dpaa_sec_prep_ipsec_cdb(ses);
	} else if (is_cipher_only(ses)) {
		caam_cipher_alg(ses, &alginfo_c);
		if (alginfo_c.algtype == (unsigned int)DPAA_SEC_ALG_UNSUPPORT) {
			DPAA_SEC_ERR("not supported cipher alg");
			return -ENOTSUP;
		}

		alginfo_c.key = (size_t)ses->cipher_key.data;
		alginfo_c.keylen = ses->cipher_key.length;
		alginfo_c.key_enc_flags = 0;
		alginfo_c.key_type = RTA_DATA_IMM;

		shared_desc_len = cnstr_shdsc_blkcipher(
						cdb->sh_desc, true,
						swap, &alginfo_c,
						NULL,
						ses->iv.length,
						ses->dir);
	} else if (is_auth_only(ses)) {
		caam_auth_alg(ses, &alginfo_a);
		if (alginfo_a.algtype == (unsigned int)DPAA_SEC_ALG_UNSUPPORT) {
			DPAA_SEC_ERR("not supported auth alg");
			return -ENOTSUP;
		}

		alginfo_a.key = (size_t)ses->auth_key.data;
		alginfo_a.keylen = ses->auth_key.length;
		alginfo_a.key_enc_flags = 0;
		alginfo_a.key_type = RTA_DATA_IMM;

		shared_desc_len = cnstr_shdsc_hmac(cdb->sh_desc, true,
						   swap, &alginfo_a,
						   !ses->dir,
						   ses->digest_length);
	} else if (is_aead(ses)) {
		caam_aead_alg(ses, &alginfo);
		if (alginfo.algtype == (unsigned int)DPAA_SEC_ALG_UNSUPPORT) {
			DPAA_SEC_ERR("not supported aead alg");
			return -ENOTSUP;
		}
		alginfo.key = (size_t)ses->aead_key.data;
		alginfo.keylen = ses->aead_key.length;
		alginfo.key_enc_flags = 0;
		alginfo.key_type = RTA_DATA_IMM;

		if (ses->dir == DIR_ENC)
			shared_desc_len = cnstr_shdsc_gcm_encap(
					cdb->sh_desc, true, swap,
					&alginfo,
					ses->iv.length,
					ses->digest_length);
		else
			shared_desc_len = cnstr_shdsc_gcm_decap(
					cdb->sh_desc, true, swap,
					&alginfo,
					ses->iv.length,
					ses->digest_length);
	} else {
		caam_cipher_alg(ses, &alginfo_c);
		if (alginfo_c.algtype == (unsigned int)DPAA_SEC_ALG_UNSUPPORT) {
			DPAA_SEC_ERR("not supported cipher alg");
			return -ENOTSUP;
		}

		alginfo_c.key = (size_t)ses->cipher_key.data;
		alginfo_c.keylen = ses->cipher_key.length;
		alginfo_c.key_enc_flags = 0;
		alginfo_c.key_type = RTA_DATA_IMM;

		caam_auth_alg(ses, &alginfo_a);
		if (alginfo_a.algtype == (unsigned int)DPAA_SEC_ALG_UNSUPPORT) {
			DPAA_SEC_ERR("not supported auth alg");
			return -ENOTSUP;
		}

		alginfo_a.key = (size_t)ses->auth_key.data;
		alginfo_a.keylen = ses->auth_key.length;
		alginfo_a.key_enc_flags = 0;
		alginfo_a.key_type = RTA_DATA_IMM;

		cdb->sh_desc[0] = alginfo_c.keylen;
		cdb->sh_desc[1] = alginfo_a.keylen;
		err = rta_inline_query(IPSEC_AUTH_VAR_AES_DEC_BASE_DESC_LEN,
				       MIN_JOB_DESC_SIZE,
				       (unsigned int *)cdb->sh_desc,
				       &cdb->sh_desc[2], 2);

		if (err < 0) {
			DPAA_SEC_ERR("Crypto: Incorrect key lengths");
			return err;
		}
		if (cdb->sh_desc[2] & 1)
			alginfo_c.key_type = RTA_DATA_IMM;
		else {
			alginfo_c.key = (size_t)dpaa_mem_vtop(
						(void *)(size_t)alginfo_c.key);
			alginfo_c.key_type = RTA_DATA_PTR;
		}
		if (cdb->sh_desc[2] & (1<<1))
			alginfo_a.key_type = RTA_DATA_IMM;
		else {
			alginfo_a.key = (size_t)dpaa_mem_vtop(
						(void *)(size_t)alginfo_a.key);
			alginfo_a.key_type = RTA_DATA_PTR;
		}
		cdb->sh_desc[0] = 0;
		cdb->sh_desc[1] = 0;
		cdb->sh_desc[2] = 0;
		/* Auth_only_len is set as 0 here and it will be
		 * overwritten in fd for each packet.
		 */
		shared_desc_len = cnstr_shdsc_authenc(cdb->sh_desc,
				true, swap, &alginfo_c, &alginfo_a,
				ses->iv.length, 0,
				ses->digest_length, ses->dir);
	}

	if (shared_desc_len < 0) {
		DPAA_SEC_ERR("error in preparing command block");
		return shared_desc_len;
	}

	cdb->sh_hdr.hi.field.idlen = shared_desc_len;
	cdb->sh_hdr.hi.word = rte_cpu_to_be_32(cdb->sh_hdr.hi.word);
	cdb->sh_hdr.lo.word = rte_cpu_to_be_32(cdb->sh_hdr.lo.word);

	return 0;
}

/* qp is lockless, should be accessed by only one thread */
static int
dpaa_sec_deq(struct dpaa_sec_qp *qp, struct rte_crypto_op **ops, int nb_ops)
{
	struct qman_fq *fq;
	unsigned int pkts = 0;
	int num_rx_bufs, ret;
	struct qm_dqrr_entry *dq;
	uint32_t vdqcr_flags = 0;

	fq = &qp->outq;
	/*
	 * Until request for four buffers, we provide exact number of buffers.
	 * Otherwise we do not set the QM_VDQCR_EXACT flag.
	 * Not setting QM_VDQCR_EXACT flag can provide two more buffers than
	 * requested, so we request two less in this case.
	 */
	if (nb_ops < 4) {
		vdqcr_flags = QM_VDQCR_EXACT;
		num_rx_bufs = nb_ops;
	} else {
		num_rx_bufs = nb_ops > DPAA_MAX_DEQUEUE_NUM_FRAMES ?
			(DPAA_MAX_DEQUEUE_NUM_FRAMES - 2) : (nb_ops - 2);
	}
	ret = qman_set_vdq(fq, num_rx_bufs, vdqcr_flags);
	if (ret)
		return 0;

	do {
		const struct qm_fd *fd;
		struct dpaa_sec_job *job;
		struct dpaa_sec_op_ctx *ctx;
		struct rte_crypto_op *op;

		dq = qman_dequeue(fq);
		if (!dq)
			continue;

		fd = &dq->fd;
		/* sg is embedded in an op ctx,
		 * sg[0] is for output
		 * sg[1] for input
		 */
		job = dpaa_mem_ptov(qm_fd_addr_get64(fd));

		ctx = container_of(job, struct dpaa_sec_op_ctx, job);
		ctx->fd_status = fd->status;
		op = ctx->op;
		if (op->sess_type == RTE_CRYPTO_OP_SECURITY_SESSION) {
			struct qm_sg_entry *sg_out;
			uint32_t len;

			sg_out = &job->sg[0];
			hw_sg_to_cpu(sg_out);
			len = sg_out->length;
			op->sym->m_src->pkt_len = len;
			op->sym->m_src->data_len = len;
		}
		if (!ctx->fd_status) {
			op->status = RTE_CRYPTO_OP_STATUS_SUCCESS;
		} else {
			DPAA_SEC_DP_WARN("SEC return err:0x%x", ctx->fd_status);
			op->status = RTE_CRYPTO_OP_STATUS_ERROR;
		}
		ops[pkts++] = op;

		/* report op status to sym->op and then free the ctx memeory */
		rte_mempool_put(ctx->ctx_pool, (void *)ctx);

		qman_dqrr_consume(fq, dq);
	} while (fq->flags & QMAN_FQ_STATE_VDQCR);

	return pkts;
}

static inline struct dpaa_sec_job *
build_auth_only_sg(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct rte_mbuf *mbuf = sym->m_src;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg, *out_sg, *in_sg;
	phys_addr_t start_addr;
	uint8_t *old_digest, extra_segs;

	if (is_decode(ses))
		extra_segs = 3;
	else
		extra_segs = 2;

	if ((mbuf->nb_segs + extra_segs) > MAX_SG_ENTRIES) {
		DPAA_SEC_DP_ERR("Auth: Max sec segs supported is %d",
				MAX_SG_ENTRIES);
		return NULL;
	}
	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;
	old_digest = ctx->digest;

	/* output */
	out_sg = &cf->sg[0];
	qm_sg_entry_set64(out_sg, sym->auth.digest.phys_addr);
	out_sg->length = ses->digest_length;
	cpu_to_hw_sg(out_sg);

	/* input */
	in_sg = &cf->sg[1];
	/* need to extend the input to a compound frame */
	in_sg->extension = 1;
	in_sg->final = 1;
	in_sg->length = sym->auth.data.length;
	qm_sg_entry_set64(in_sg, dpaa_mem_vtop(&cf->sg[2]));

	/* 1st seg */
	sg = in_sg + 1;
	qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
	sg->length = mbuf->data_len - sym->auth.data.offset;
	sg->offset = sym->auth.data.offset;

	/* Successive segs */
	mbuf = mbuf->next;
	while (mbuf) {
		cpu_to_hw_sg(sg);
		sg++;
		qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
		sg->length = mbuf->data_len;
		mbuf = mbuf->next;
	}

	if (is_decode(ses)) {
		/* Digest verification case */
		cpu_to_hw_sg(sg);
		sg++;
		rte_memcpy(old_digest, sym->auth.digest.data,
				ses->digest_length);
		start_addr = dpaa_mem_vtop(old_digest);
		qm_sg_entry_set64(sg, start_addr);
		sg->length = ses->digest_length;
		in_sg->length += ses->digest_length;
	} else {
		/* Digest calculation case */
		sg->length -= ses->digest_length;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);
	cpu_to_hw_sg(in_sg);

	return cf;
}

/**
 * packet looks like:
 *		|<----data_len------->|
 *    |ip_header|ah_header|icv|payload|
 *              ^
 *		|
 *	   mbuf->pkt.data
 */
static inline struct dpaa_sec_job *
build_auth_only(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct rte_mbuf *mbuf = sym->m_src;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg;
	rte_iova_t start_addr;
	uint8_t *old_digest;

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;
	old_digest = ctx->digest;

	start_addr = rte_pktmbuf_iova(mbuf);
	/* output */
	sg = &cf->sg[0];
	qm_sg_entry_set64(sg, sym->auth.digest.phys_addr);
	sg->length = ses->digest_length;
	cpu_to_hw_sg(sg);

	/* input */
	sg = &cf->sg[1];
	if (is_decode(ses)) {
		/* need to extend the input to a compound frame */
		sg->extension = 1;
		qm_sg_entry_set64(sg, dpaa_mem_vtop(&cf->sg[2]));
		sg->length = sym->auth.data.length + ses->digest_length;
		sg->final = 1;
		cpu_to_hw_sg(sg);

		sg = &cf->sg[2];
		/* hash result or digest, save digest first */
		rte_memcpy(old_digest, sym->auth.digest.data,
			   ses->digest_length);
		qm_sg_entry_set64(sg, start_addr + sym->auth.data.offset);
		sg->length = sym->auth.data.length;
		cpu_to_hw_sg(sg);

		/* let's check digest by hw */
		start_addr = dpaa_mem_vtop(old_digest);
		sg++;
		qm_sg_entry_set64(sg, start_addr);
		sg->length = ses->digest_length;
		sg->final = 1;
		cpu_to_hw_sg(sg);
	} else {
		qm_sg_entry_set64(sg, start_addr + sym->auth.data.offset);
		sg->length = sym->auth.data.length;
		sg->final = 1;
		cpu_to_hw_sg(sg);
	}

	return cf;
}

static inline struct dpaa_sec_job *
build_cipher_only_sg(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg, *out_sg, *in_sg;
	struct rte_mbuf *mbuf;
	uint8_t req_segs;
	uint8_t *IV_ptr = rte_crypto_op_ctod_offset(op, uint8_t *,
			ses->iv.offset);

	if (sym->m_dst) {
		mbuf = sym->m_dst;
		req_segs = mbuf->nb_segs + sym->m_src->nb_segs + 3;
	} else {
		mbuf = sym->m_src;
		req_segs = mbuf->nb_segs * 2 + 3;
	}

	if (req_segs > MAX_SG_ENTRIES) {
		DPAA_SEC_DP_ERR("Cipher: Max sec segs supported is %d",
				MAX_SG_ENTRIES);
		return NULL;
	}

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;

	/* output */
	out_sg = &cf->sg[0];
	out_sg->extension = 1;
	out_sg->length = sym->cipher.data.length;
	qm_sg_entry_set64(out_sg, dpaa_mem_vtop(&cf->sg[2]));
	cpu_to_hw_sg(out_sg);

	/* 1st seg */
	sg = &cf->sg[2];
	qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
	sg->length = mbuf->data_len - sym->cipher.data.offset;
	sg->offset = sym->cipher.data.offset;

	/* Successive segs */
	mbuf = mbuf->next;
	while (mbuf) {
		cpu_to_hw_sg(sg);
		sg++;
		qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
		sg->length = mbuf->data_len;
		mbuf = mbuf->next;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	/* input */
	mbuf = sym->m_src;
	in_sg = &cf->sg[1];
	in_sg->extension = 1;
	in_sg->final = 1;
	in_sg->length = sym->cipher.data.length + ses->iv.length;

	sg++;
	qm_sg_entry_set64(in_sg, dpaa_mem_vtop(sg));
	cpu_to_hw_sg(in_sg);

	/* IV */
	qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
	sg->length = ses->iv.length;
	cpu_to_hw_sg(sg);

	/* 1st seg */
	sg++;
	qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
	sg->length = mbuf->data_len - sym->cipher.data.offset;
	sg->offset = sym->cipher.data.offset;

	/* Successive segs */
	mbuf = mbuf->next;
	while (mbuf) {
		cpu_to_hw_sg(sg);
		sg++;
		qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
		sg->length = mbuf->data_len;
		mbuf = mbuf->next;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	return cf;
}

static inline struct dpaa_sec_job *
build_cipher_only(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg;
	rte_iova_t src_start_addr, dst_start_addr;
	uint8_t *IV_ptr = rte_crypto_op_ctod_offset(op, uint8_t *,
			ses->iv.offset);

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;

	src_start_addr = rte_pktmbuf_iova(sym->m_src);

	if (sym->m_dst)
		dst_start_addr = rte_pktmbuf_iova(sym->m_dst);
	else
		dst_start_addr = src_start_addr;

	/* output */
	sg = &cf->sg[0];
	qm_sg_entry_set64(sg, dst_start_addr + sym->cipher.data.offset);
	sg->length = sym->cipher.data.length + ses->iv.length;
	cpu_to_hw_sg(sg);

	/* input */
	sg = &cf->sg[1];

	/* need to extend the input to a compound frame */
	sg->extension = 1;
	sg->final = 1;
	sg->length = sym->cipher.data.length + ses->iv.length;
	qm_sg_entry_set64(sg, dpaa_mem_vtop(&cf->sg[2]));
	cpu_to_hw_sg(sg);

	sg = &cf->sg[2];
	qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
	sg->length = ses->iv.length;
	cpu_to_hw_sg(sg);

	sg++;
	qm_sg_entry_set64(sg, src_start_addr + sym->cipher.data.offset);
	sg->length = sym->cipher.data.length;
	sg->final = 1;
	cpu_to_hw_sg(sg);

	return cf;
}

static inline struct dpaa_sec_job *
build_cipher_auth_gcm_sg(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg, *out_sg, *in_sg;
	struct rte_mbuf *mbuf;
	uint8_t req_segs;
	uint8_t *IV_ptr = rte_crypto_op_ctod_offset(op, uint8_t *,
			ses->iv.offset);

	if (sym->m_dst) {
		mbuf = sym->m_dst;
		req_segs = mbuf->nb_segs + sym->m_src->nb_segs + 4;
	} else {
		mbuf = sym->m_src;
		req_segs = mbuf->nb_segs * 2 + 4;
	}

	if (ses->auth_only_len)
		req_segs++;

	if (req_segs > MAX_SG_ENTRIES) {
		DPAA_SEC_DP_ERR("AEAD: Max sec segs supported is %d",
				MAX_SG_ENTRIES);
		return NULL;
	}

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;

	rte_prefetch0(cf->sg);

	/* output */
	out_sg = &cf->sg[0];
	out_sg->extension = 1;
	if (is_encode(ses))
		out_sg->length = sym->aead.data.length + ses->auth_only_len
						+ ses->digest_length;
	else
		out_sg->length = sym->aead.data.length + ses->auth_only_len;

	/* output sg entries */
	sg = &cf->sg[2];
	qm_sg_entry_set64(out_sg, dpaa_mem_vtop(sg));
	cpu_to_hw_sg(out_sg);

	/* 1st seg */
	qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
	sg->length = mbuf->data_len - sym->aead.data.offset +
					ses->auth_only_len;
	sg->offset = sym->aead.data.offset - ses->auth_only_len;

	/* Successive segs */
	mbuf = mbuf->next;
	while (mbuf) {
		cpu_to_hw_sg(sg);
		sg++;
		qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
		sg->length = mbuf->data_len;
		mbuf = mbuf->next;
	}
	sg->length -= ses->digest_length;

	if (is_encode(ses)) {
		cpu_to_hw_sg(sg);
		/* set auth output */
		sg++;
		qm_sg_entry_set64(sg, sym->aead.digest.phys_addr);
		sg->length = ses->digest_length;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	/* input */
	mbuf = sym->m_src;
	in_sg = &cf->sg[1];
	in_sg->extension = 1;
	in_sg->final = 1;
	if (is_encode(ses))
		in_sg->length = ses->iv.length + sym->aead.data.length
							+ ses->auth_only_len;
	else
		in_sg->length = ses->iv.length + sym->aead.data.length
				+ ses->auth_only_len + ses->digest_length;

	/* input sg entries */
	sg++;
	qm_sg_entry_set64(in_sg, dpaa_mem_vtop(sg));
	cpu_to_hw_sg(in_sg);

	/* 1st seg IV */
	qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
	sg->length = ses->iv.length;
	cpu_to_hw_sg(sg);

	/* 2nd seg auth only */
	if (ses->auth_only_len) {
		sg++;
		qm_sg_entry_set64(sg, dpaa_mem_vtop(sym->aead.aad.data));
		sg->length = ses->auth_only_len;
		cpu_to_hw_sg(sg);
	}

	/* 3rd seg */
	sg++;
	qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
	sg->length = mbuf->data_len - sym->aead.data.offset;
	sg->offset = sym->aead.data.offset;

	/* Successive segs */
	mbuf = mbuf->next;
	while (mbuf) {
		cpu_to_hw_sg(sg);
		sg++;
		qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
		sg->length = mbuf->data_len;
		mbuf = mbuf->next;
	}

	if (is_decode(ses)) {
		cpu_to_hw_sg(sg);
		sg++;
		memcpy(ctx->digest, sym->aead.digest.data,
			ses->digest_length);
		qm_sg_entry_set64(sg, dpaa_mem_vtop(ctx->digest));
		sg->length = ses->digest_length;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	return cf;
}

static inline struct dpaa_sec_job *
build_cipher_auth_gcm(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg;
	uint32_t length = 0;
	rte_iova_t src_start_addr, dst_start_addr;
	uint8_t *IV_ptr = rte_crypto_op_ctod_offset(op, uint8_t *,
			ses->iv.offset);

	src_start_addr = sym->m_src->buf_iova + sym->m_src->data_off;

	if (sym->m_dst)
		dst_start_addr = sym->m_dst->buf_iova + sym->m_dst->data_off;
	else
		dst_start_addr = src_start_addr;

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;

	/* input */
	rte_prefetch0(cf->sg);
	sg = &cf->sg[2];
	qm_sg_entry_set64(&cf->sg[1], dpaa_mem_vtop(sg));
	if (is_encode(ses)) {
		qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
		sg->length = ses->iv.length;
		length += sg->length;
		cpu_to_hw_sg(sg);

		sg++;
		if (ses->auth_only_len) {
			qm_sg_entry_set64(sg,
					  dpaa_mem_vtop(sym->aead.aad.data));
			sg->length = ses->auth_only_len;
			length += sg->length;
			cpu_to_hw_sg(sg);
			sg++;
		}
		qm_sg_entry_set64(sg, src_start_addr + sym->aead.data.offset);
		sg->length = sym->aead.data.length;
		length += sg->length;
		sg->final = 1;
		cpu_to_hw_sg(sg);
	} else {
		qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
		sg->length = ses->iv.length;
		length += sg->length;
		cpu_to_hw_sg(sg);

		sg++;
		if (ses->auth_only_len) {
			qm_sg_entry_set64(sg,
					  dpaa_mem_vtop(sym->aead.aad.data));
			sg->length = ses->auth_only_len;
			length += sg->length;
			cpu_to_hw_sg(sg);
			sg++;
		}
		qm_sg_entry_set64(sg, src_start_addr + sym->aead.data.offset);
		sg->length = sym->aead.data.length;
		length += sg->length;
		cpu_to_hw_sg(sg);

		memcpy(ctx->digest, sym->aead.digest.data,
		       ses->digest_length);
		sg++;

		qm_sg_entry_set64(sg, dpaa_mem_vtop(ctx->digest));
		sg->length = ses->digest_length;
		length += sg->length;
		sg->final = 1;
		cpu_to_hw_sg(sg);
	}
	/* input compound frame */
	cf->sg[1].length = length;
	cf->sg[1].extension = 1;
	cf->sg[1].final = 1;
	cpu_to_hw_sg(&cf->sg[1]);

	/* output */
	sg++;
	qm_sg_entry_set64(&cf->sg[0], dpaa_mem_vtop(sg));
	qm_sg_entry_set64(sg,
		dst_start_addr + sym->aead.data.offset - ses->auth_only_len);
	sg->length = sym->aead.data.length + ses->auth_only_len;
	length = sg->length;
	if (is_encode(ses)) {
		cpu_to_hw_sg(sg);
		/* set auth output */
		sg++;
		qm_sg_entry_set64(sg, sym->aead.digest.phys_addr);
		sg->length = ses->digest_length;
		length += sg->length;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	/* output compound frame */
	cf->sg[0].length = length;
	cf->sg[0].extension = 1;
	cpu_to_hw_sg(&cf->sg[0]);

	return cf;
}

static inline struct dpaa_sec_job *
build_cipher_auth_sg(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg, *out_sg, *in_sg;
	struct rte_mbuf *mbuf;
	uint8_t req_segs;
	uint8_t *IV_ptr = rte_crypto_op_ctod_offset(op, uint8_t *,
			ses->iv.offset);

	if (sym->m_dst) {
		mbuf = sym->m_dst;
		req_segs = mbuf->nb_segs + sym->m_src->nb_segs + 4;
	} else {
		mbuf = sym->m_src;
		req_segs = mbuf->nb_segs * 2 + 4;
	}

	if (req_segs > MAX_SG_ENTRIES) {
		DPAA_SEC_DP_ERR("Cipher-Auth: Max sec segs supported is %d",
				MAX_SG_ENTRIES);
		return NULL;
	}

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;

	rte_prefetch0(cf->sg);

	/* output */
	out_sg = &cf->sg[0];
	out_sg->extension = 1;
	if (is_encode(ses))
		out_sg->length = sym->auth.data.length + ses->digest_length;
	else
		out_sg->length = sym->auth.data.length;

	/* output sg entries */
	sg = &cf->sg[2];
	qm_sg_entry_set64(out_sg, dpaa_mem_vtop(sg));
	cpu_to_hw_sg(out_sg);

	/* 1st seg */
	qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
	sg->length = mbuf->data_len - sym->auth.data.offset;
	sg->offset = sym->auth.data.offset;

	/* Successive segs */
	mbuf = mbuf->next;
	while (mbuf) {
		cpu_to_hw_sg(sg);
		sg++;
		qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
		sg->length = mbuf->data_len;
		mbuf = mbuf->next;
	}
	sg->length -= ses->digest_length;

	if (is_encode(ses)) {
		cpu_to_hw_sg(sg);
		/* set auth output */
		sg++;
		qm_sg_entry_set64(sg, sym->auth.digest.phys_addr);
		sg->length = ses->digest_length;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	/* input */
	mbuf = sym->m_src;
	in_sg = &cf->sg[1];
	in_sg->extension = 1;
	in_sg->final = 1;
	if (is_encode(ses))
		in_sg->length = ses->iv.length + sym->auth.data.length;
	else
		in_sg->length = ses->iv.length + sym->auth.data.length
						+ ses->digest_length;

	/* input sg entries */
	sg++;
	qm_sg_entry_set64(in_sg, dpaa_mem_vtop(sg));
	cpu_to_hw_sg(in_sg);

	/* 1st seg IV */
	qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
	sg->length = ses->iv.length;
	cpu_to_hw_sg(sg);

	/* 2nd seg */
	sg++;
	qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
	sg->length = mbuf->data_len - sym->auth.data.offset;
	sg->offset = sym->auth.data.offset;

	/* Successive segs */
	mbuf = mbuf->next;
	while (mbuf) {
		cpu_to_hw_sg(sg);
		sg++;
		qm_sg_entry_set64(sg, rte_pktmbuf_mtophys(mbuf));
		sg->length = mbuf->data_len;
		mbuf = mbuf->next;
	}

	sg->length -= ses->digest_length;
	if (is_decode(ses)) {
		cpu_to_hw_sg(sg);
		sg++;
		memcpy(ctx->digest, sym->auth.digest.data,
			ses->digest_length);
		qm_sg_entry_set64(sg, dpaa_mem_vtop(ctx->digest));
		sg->length = ses->digest_length;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	return cf;
}

static inline struct dpaa_sec_job *
build_cipher_auth(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg;
	rte_iova_t src_start_addr, dst_start_addr;
	uint32_t length = 0;
	uint8_t *IV_ptr = rte_crypto_op_ctod_offset(op, uint8_t *,
			ses->iv.offset);

	src_start_addr = sym->m_src->buf_iova + sym->m_src->data_off;
	if (sym->m_dst)
		dst_start_addr = sym->m_dst->buf_iova + sym->m_dst->data_off;
	else
		dst_start_addr = src_start_addr;

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;

	cf = &ctx->job;
	ctx->op = op;

	/* input */
	rte_prefetch0(cf->sg);
	sg = &cf->sg[2];
	qm_sg_entry_set64(&cf->sg[1], dpaa_mem_vtop(sg));
	if (is_encode(ses)) {
		qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
		sg->length = ses->iv.length;
		length += sg->length;
		cpu_to_hw_sg(sg);

		sg++;
		qm_sg_entry_set64(sg, src_start_addr + sym->auth.data.offset);
		sg->length = sym->auth.data.length;
		length += sg->length;
		sg->final = 1;
		cpu_to_hw_sg(sg);
	} else {
		qm_sg_entry_set64(sg, dpaa_mem_vtop(IV_ptr));
		sg->length = ses->iv.length;
		length += sg->length;
		cpu_to_hw_sg(sg);

		sg++;

		qm_sg_entry_set64(sg, src_start_addr + sym->auth.data.offset);
		sg->length = sym->auth.data.length;
		length += sg->length;
		cpu_to_hw_sg(sg);

		memcpy(ctx->digest, sym->auth.digest.data,
		       ses->digest_length);
		sg++;

		qm_sg_entry_set64(sg, dpaa_mem_vtop(ctx->digest));
		sg->length = ses->digest_length;
		length += sg->length;
		sg->final = 1;
		cpu_to_hw_sg(sg);
	}
	/* input compound frame */
	cf->sg[1].length = length;
	cf->sg[1].extension = 1;
	cf->sg[1].final = 1;
	cpu_to_hw_sg(&cf->sg[1]);

	/* output */
	sg++;
	qm_sg_entry_set64(&cf->sg[0], dpaa_mem_vtop(sg));
	qm_sg_entry_set64(sg, dst_start_addr + sym->cipher.data.offset);
	sg->length = sym->cipher.data.length;
	length = sg->length;
	if (is_encode(ses)) {
		cpu_to_hw_sg(sg);
		/* set auth output */
		sg++;
		qm_sg_entry_set64(sg, sym->auth.digest.phys_addr);
		sg->length = ses->digest_length;
		length += sg->length;
	}
	sg->final = 1;
	cpu_to_hw_sg(sg);

	/* output compound frame */
	cf->sg[0].length = length;
	cf->sg[0].extension = 1;
	cpu_to_hw_sg(&cf->sg[0]);

	return cf;
}

static inline struct dpaa_sec_job *
build_proto(struct rte_crypto_op *op, dpaa_sec_session *ses)
{
	struct rte_crypto_sym_op *sym = op->sym;
	struct dpaa_sec_job *cf;
	struct dpaa_sec_op_ctx *ctx;
	struct qm_sg_entry *sg;
	phys_addr_t src_start_addr, dst_start_addr;

	ctx = dpaa_sec_alloc_ctx(ses);
	if (!ctx)
		return NULL;
	cf = &ctx->job;
	ctx->op = op;

	src_start_addr = rte_pktmbuf_mtophys(sym->m_src);

	if (sym->m_dst)
		dst_start_addr = rte_pktmbuf_mtophys(sym->m_dst);
	else
		dst_start_addr = src_start_addr;

	/* input */
	sg = &cf->sg[1];
	qm_sg_entry_set64(sg, src_start_addr);
	sg->length = sym->m_src->pkt_len;
	sg->final = 1;
	cpu_to_hw_sg(sg);

	sym->m_src->packet_type &= ~RTE_PTYPE_L4_MASK;
	/* output */
	sg = &cf->sg[0];
	qm_sg_entry_set64(sg, dst_start_addr);
	sg->length = sym->m_src->buf_len - sym->m_src->data_off;
	cpu_to_hw_sg(sg);

	return cf;
}

static uint16_t
dpaa_sec_enqueue_burst(void *qp, struct rte_crypto_op **ops,
		       uint16_t nb_ops)
{
	/* Function to transmit the frames to given device and queuepair */
	uint32_t loop;
	struct dpaa_sec_qp *dpaa_qp = (struct dpaa_sec_qp *)qp;
	uint16_t num_tx = 0;
	struct qm_fd fds[DPAA_SEC_BURST], *fd;
	uint32_t frames_to_send;
	struct rte_crypto_op *op;
	struct dpaa_sec_job *cf;
	dpaa_sec_session *ses;
	uint32_t auth_only_len;
	struct qman_fq *inq[DPAA_SEC_BURST];

	while (nb_ops) {
		frames_to_send = (nb_ops > DPAA_SEC_BURST) ?
				DPAA_SEC_BURST : nb_ops;
		for (loop = 0; loop < frames_to_send; loop++) {
			op = *(ops++);
			switch (op->sess_type) {
			case RTE_CRYPTO_OP_WITH_SESSION:
				ses = (dpaa_sec_session *)
					get_sym_session_private_data(
							op->sym->session,
							cryptodev_driver_id);
				break;
			case RTE_CRYPTO_OP_SECURITY_SESSION:
				ses = (dpaa_sec_session *)
					get_sec_session_private_data(
							op->sym->sec_session);
				break;
			default:
				DPAA_SEC_DP_ERR(
					"sessionless crypto op not supported");
				frames_to_send = loop;
				nb_ops = loop;
				goto send_pkts;
			}
			if (unlikely(!ses->qp)) {
				if (dpaa_sec_attach_sess_q(qp, ses)) {
					frames_to_send = loop;
					nb_ops = loop;
					goto send_pkts;
				}
			} else if (unlikely(ses->qp != qp)) {
				DPAA_SEC_DP_ERR("Old:sess->qp = %p"
					" New qp = %p\n", ses->qp, qp);
				frames_to_send = loop;
				nb_ops = loop;
				goto send_pkts;
			}

			auth_only_len = op->sym->auth.data.length -
						op->sym->cipher.data.length;
			if (rte_pktmbuf_is_contiguous(op->sym->m_src)) {
				if (is_proto_ipsec(ses)) {
					cf = build_proto(op, ses);
				} else if (is_auth_only(ses)) {
					cf = build_auth_only(op, ses);
				} else if (is_cipher_only(ses)) {
					cf = build_cipher_only(op, ses);
				} else if (is_aead(ses)) {
					cf = build_cipher_auth_gcm(op, ses);
					auth_only_len = ses->auth_only_len;
				} else if (is_auth_cipher(ses)) {
					cf = build_cipher_auth(op, ses);
				} else {
					DPAA_SEC_DP_ERR("not supported ops");
					frames_to_send = loop;
					nb_ops = loop;
					goto send_pkts;
				}
			} else {
				if (is_auth_only(ses)) {
					cf = build_auth_only_sg(op, ses);
				} else if (is_cipher_only(ses)) {
					cf = build_cipher_only_sg(op, ses);
				} else if (is_aead(ses)) {
					cf = build_cipher_auth_gcm_sg(op, ses);
					auth_only_len = ses->auth_only_len;
				} else if (is_auth_cipher(ses)) {
					cf = build_cipher_auth_sg(op, ses);
				} else {
					DPAA_SEC_DP_ERR("not supported ops");
					frames_to_send = loop;
					nb_ops = loop;
					goto send_pkts;
				}
			}
			if (unlikely(!cf)) {
				frames_to_send = loop;
				nb_ops = loop;
				goto send_pkts;
			}

			fd = &fds[loop];
			inq[loop] = ses->inq;
			fd->opaque_addr = 0;
			fd->cmd = 0;
			qm_fd_addr_set64(fd, dpaa_mem_vtop(cf->sg));
			fd->_format1 = qm_fd_compound;
			fd->length29 = 2 * sizeof(struct qm_sg_entry);
			/* Auth_only_len is set as 0 in descriptor and it is
			 * overwritten here in the fd.cmd which will update
			 * the DPOVRD reg.
			 */
			if (auth_only_len)
				fd->cmd = 0x80000000 | auth_only_len;

		}
send_pkts:
		loop = 0;
		while (loop < frames_to_send) {
			loop += qman_enqueue_multi_fq(&inq[loop], &fds[loop],
					frames_to_send - loop);
		}
		nb_ops -= frames_to_send;
		num_tx += frames_to_send;
	}

	dpaa_qp->tx_pkts += num_tx;
	dpaa_qp->tx_errs += nb_ops - num_tx;

	return num_tx;
}

static uint16_t
dpaa_sec_dequeue_burst(void *qp, struct rte_crypto_op **ops,
		       uint16_t nb_ops)
{
	uint16_t num_rx;
	struct dpaa_sec_qp *dpaa_qp = (struct dpaa_sec_qp *)qp;

	num_rx = dpaa_sec_deq(dpaa_qp, ops, nb_ops);

	dpaa_qp->rx_pkts += num_rx;
	dpaa_qp->rx_errs += nb_ops - num_rx;

	DPAA_SEC_DP_DEBUG("SEC Received %d Packets\n", num_rx);

	return num_rx;
}

/** Release queue pair */
static int
dpaa_sec_queue_pair_release(struct rte_cryptodev *dev,
			    uint16_t qp_id)
{
	struct dpaa_sec_dev_private *internals;
	struct dpaa_sec_qp *qp = NULL;

	PMD_INIT_FUNC_TRACE();

	DPAA_SEC_DEBUG("dev =%p, queue =%d", dev, qp_id);

	internals = dev->data->dev_private;
	if (qp_id >= internals->max_nb_queue_pairs) {
		DPAA_SEC_ERR("Max supported qpid %d",
			     internals->max_nb_queue_pairs);
		return -EINVAL;
	}

	qp = &internals->qps[qp_id];
	qp->internals = NULL;
	dev->data->queue_pairs[qp_id] = NULL;

	return 0;
}

/** Setup a queue pair */
static int
dpaa_sec_queue_pair_setup(struct rte_cryptodev *dev, uint16_t qp_id,
		__rte_unused const struct rte_cryptodev_qp_conf *qp_conf,
		__rte_unused int socket_id,
		__rte_unused struct rte_mempool *session_pool)
{
	struct dpaa_sec_dev_private *internals;
	struct dpaa_sec_qp *qp = NULL;

	DPAA_SEC_DEBUG("dev =%p, queue =%d, conf =%p", dev, qp_id, qp_conf);

	internals = dev->data->dev_private;
	if (qp_id >= internals->max_nb_queue_pairs) {
		DPAA_SEC_ERR("Max supported qpid %d",
			     internals->max_nb_queue_pairs);
		return -EINVAL;
	}

	qp = &internals->qps[qp_id];
	qp->internals = internals;
	dev->data->queue_pairs[qp_id] = qp;

	return 0;
}

/** Return the number of allocated queue pairs */
static uint32_t
dpaa_sec_queue_pair_count(struct rte_cryptodev *dev)
{
	PMD_INIT_FUNC_TRACE();

	return dev->data->nb_queue_pairs;
}

/** Returns the size of session structure */
static unsigned int
dpaa_sec_sym_session_get_size(struct rte_cryptodev *dev __rte_unused)
{
	PMD_INIT_FUNC_TRACE();

	return sizeof(dpaa_sec_session);
}

static int
dpaa_sec_cipher_init(struct rte_cryptodev *dev __rte_unused,
		     struct rte_crypto_sym_xform *xform,
		     dpaa_sec_session *session)
{
	session->cipher_alg = xform->cipher.algo;
	session->iv.length = xform->cipher.iv.length;
	session->iv.offset = xform->cipher.iv.offset;
	session->cipher_key.data = rte_zmalloc(NULL, xform->cipher.key.length,
					       RTE_CACHE_LINE_SIZE);
	if (session->cipher_key.data == NULL && xform->cipher.key.length > 0) {
		DPAA_SEC_ERR("No Memory for cipher key");
		return -ENOMEM;
	}
	session->cipher_key.length = xform->cipher.key.length;

	memcpy(session->cipher_key.data, xform->cipher.key.data,
	       xform->cipher.key.length);
	session->dir = (xform->cipher.op == RTE_CRYPTO_CIPHER_OP_ENCRYPT) ?
			DIR_ENC : DIR_DEC;

	return 0;
}

static int
dpaa_sec_auth_init(struct rte_cryptodev *dev __rte_unused,
		   struct rte_crypto_sym_xform *xform,
		   dpaa_sec_session *session)
{
	session->auth_alg = xform->auth.algo;
	session->auth_key.data = rte_zmalloc(NULL, xform->auth.key.length,
					     RTE_CACHE_LINE_SIZE);
	if (session->auth_key.data == NULL && xform->auth.key.length > 0) {
		DPAA_SEC_ERR("No Memory for auth key");
		return -ENOMEM;
	}
	session->auth_key.length = xform->auth.key.length;
	session->digest_length = xform->auth.digest_length;

	memcpy(session->auth_key.data, xform->auth.key.data,
	       xform->auth.key.length);
	session->dir = (xform->auth.op == RTE_CRYPTO_AUTH_OP_GENERATE) ?
			DIR_ENC : DIR_DEC;

	return 0;
}

static int
dpaa_sec_aead_init(struct rte_cryptodev *dev __rte_unused,
		   struct rte_crypto_sym_xform *xform,
		   dpaa_sec_session *session)
{
	session->aead_alg = xform->aead.algo;
	session->iv.length = xform->aead.iv.length;
	session->iv.offset = xform->aead.iv.offset;
	session->auth_only_len = xform->aead.aad_length;
	session->aead_key.data = rte_zmalloc(NULL, xform->aead.key.length,
					     RTE_CACHE_LINE_SIZE);
	if (session->aead_key.data == NULL && xform->aead.key.length > 0) {
		DPAA_SEC_ERR("No Memory for aead key\n");
		return -ENOMEM;
	}
	session->aead_key.length = xform->aead.key.length;
	session->digest_length = xform->aead.digest_length;

	memcpy(session->aead_key.data, xform->aead.key.data,
	       xform->aead.key.length);
	session->dir = (xform->aead.op == RTE_CRYPTO_AEAD_OP_ENCRYPT) ?
			DIR_ENC : DIR_DEC;

	return 0;
}

static struct qman_fq *
dpaa_sec_attach_rxq(struct dpaa_sec_dev_private *qi)
{
	unsigned int i;

	for (i = 0; i < qi->max_nb_sessions; i++) {
		if (qi->inq_attach[i] == 0) {
			qi->inq_attach[i] = 1;
			return &qi->inq[i];
		}
	}
	DPAA_SEC_WARN("All ses session in use %x", qi->max_nb_sessions);

	return NULL;
}

static int
dpaa_sec_detach_rxq(struct dpaa_sec_dev_private *qi, struct qman_fq *fq)
{
	unsigned int i;

	for (i = 0; i < qi->max_nb_sessions; i++) {
		if (&qi->inq[i] == fq) {
			qman_retire_fq(fq, NULL);
			qman_oos_fq(fq);
			qi->inq_attach[i] = 0;
			return 0;
		}
	}
	return -1;
}

static int
dpaa_sec_attach_sess_q(struct dpaa_sec_qp *qp, dpaa_sec_session *sess)
{
	int ret;

	sess->qp = qp;
	ret = dpaa_sec_prep_cdb(sess);
	if (ret) {
		DPAA_SEC_ERR("Unable to prepare sec cdb");
		return -1;
	}
	if (unlikely(!RTE_PER_LCORE(dpaa_io))) {
		ret = rte_dpaa_portal_init((void *)0);
		if (ret) {
			DPAA_SEC_ERR("Failure in affining portal");
			return ret;
		}
	}
	ret = dpaa_sec_init_rx(sess->inq, dpaa_mem_vtop(&sess->cdb),
			       qman_fq_fqid(&qp->outq));
	if (ret)
		DPAA_SEC_ERR("Unable to init sec queue");

	return ret;
}

static int
dpaa_sec_set_session_parameters(struct rte_cryptodev *dev,
			    struct rte_crypto_sym_xform *xform,	void *sess)
{
	struct dpaa_sec_dev_private *internals = dev->data->dev_private;
	dpaa_sec_session *session = sess;

	PMD_INIT_FUNC_TRACE();

	if (unlikely(sess == NULL)) {
		DPAA_SEC_ERR("invalid session struct");
		return -EINVAL;
	}
	memset(session, 0, sizeof(dpaa_sec_session));

	/* Default IV length = 0 */
	session->iv.length = 0;

	/* Cipher Only */
	if (xform->type == RTE_CRYPTO_SYM_XFORM_CIPHER && xform->next == NULL) {
		session->auth_alg = RTE_CRYPTO_AUTH_NULL;
		dpaa_sec_cipher_init(dev, xform, session);

	/* Authentication Only */
	} else if (xform->type == RTE_CRYPTO_SYM_XFORM_AUTH &&
		   xform->next == NULL) {
		session->cipher_alg = RTE_CRYPTO_CIPHER_NULL;
		dpaa_sec_auth_init(dev, xform, session);

	/* Cipher then Authenticate */
	} else if (xform->type == RTE_CRYPTO_SYM_XFORM_CIPHER &&
		   xform->next->type == RTE_CRYPTO_SYM_XFORM_AUTH) {
		if (xform->cipher.op == RTE_CRYPTO_CIPHER_OP_ENCRYPT) {
			dpaa_sec_cipher_init(dev, xform, session);
			dpaa_sec_auth_init(dev, xform->next, session);
		} else {
			DPAA_SEC_ERR("Not supported: Auth then Cipher");
			return -EINVAL;
		}

	/* Authenticate then Cipher */
	} else if (xform->type == RTE_CRYPTO_SYM_XFORM_AUTH &&
		   xform->next->type == RTE_CRYPTO_SYM_XFORM_CIPHER) {
		if (xform->next->cipher.op == RTE_CRYPTO_CIPHER_OP_DECRYPT) {
			dpaa_sec_auth_init(dev, xform, session);
			dpaa_sec_cipher_init(dev, xform->next, session);
		} else {
			DPAA_SEC_ERR("Not supported: Auth then Cipher");
			return -EINVAL;
		}

	/* AEAD operation for AES-GCM kind of Algorithms */
	} else if (xform->type == RTE_CRYPTO_SYM_XFORM_AEAD &&
		   xform->next == NULL) {
		dpaa_sec_aead_init(dev, xform, session);

	} else {
		DPAA_SEC_ERR("Invalid crypto type");
		return -EINVAL;
	}
	session->ctx_pool = internals->ctx_pool;
	rte_spinlock_lock(&internals->lock);
	session->inq = dpaa_sec_attach_rxq(internals);
	rte_spinlock_unlock(&internals->lock);
	if (session->inq == NULL) {
		DPAA_SEC_ERR("unable to attach sec queue");
		goto err1;
	}

	return 0;

err1:
	rte_free(session->cipher_key.data);
	rte_free(session->auth_key.data);
	memset(session, 0, sizeof(dpaa_sec_session));

	return -EINVAL;
}

static int
dpaa_sec_sym_session_configure(struct rte_cryptodev *dev,
		struct rte_crypto_sym_xform *xform,
		struct rte_cryptodev_sym_session *sess,
		struct rte_mempool *mempool)
{
	void *sess_private_data;
	int ret;

	PMD_INIT_FUNC_TRACE();

	if (rte_mempool_get(mempool, &sess_private_data)) {
		DPAA_SEC_ERR("Couldn't get object from session mempool");
		return -ENOMEM;
	}

	ret = dpaa_sec_set_session_parameters(dev, xform, sess_private_data);
	if (ret != 0) {
		DPAA_SEC_ERR("failed to configure session parameters");

		/* Return session to mempool */
		rte_mempool_put(mempool, sess_private_data);
		return ret;
	}

	set_sym_session_private_data(sess, dev->driver_id,
			sess_private_data);


	return 0;
}

/** Clear the memory of session so it doesn't leave key material behind */
static void
dpaa_sec_sym_session_clear(struct rte_cryptodev *dev,
		struct rte_cryptodev_sym_session *sess)
{
	struct dpaa_sec_dev_private *qi = dev->data->dev_private;
	uint8_t index = dev->driver_id;
	void *sess_priv = get_sym_session_private_data(sess, index);

	PMD_INIT_FUNC_TRACE();

	dpaa_sec_session *s = (dpaa_sec_session *)sess_priv;

	if (sess_priv) {
		struct rte_mempool *sess_mp = rte_mempool_from_obj(sess_priv);

		if (s->inq)
			dpaa_sec_detach_rxq(qi, s->inq);
		rte_free(s->cipher_key.data);
		rte_free(s->auth_key.data);
		memset(s, 0, sizeof(dpaa_sec_session));
		set_sym_session_private_data(sess, index, NULL);
		rte_mempool_put(sess_mp, sess_priv);
	}
}

static int
dpaa_sec_set_ipsec_session(__rte_unused struct rte_cryptodev *dev,
			   struct rte_security_session_conf *conf,
			   void *sess)
{
	struct dpaa_sec_dev_private *internals = dev->data->dev_private;
	struct rte_security_ipsec_xform *ipsec_xform = &conf->ipsec;
	struct rte_crypto_auth_xform *auth_xform = NULL;
	struct rte_crypto_cipher_xform *cipher_xform = NULL;
	dpaa_sec_session *session = (dpaa_sec_session *)sess;

	PMD_INIT_FUNC_TRACE();

	memset(session, 0, sizeof(dpaa_sec_session));
	if (ipsec_xform->direction == RTE_SECURITY_IPSEC_SA_DIR_EGRESS) {
		cipher_xform = &conf->crypto_xform->cipher;
		if (conf->crypto_xform->next)
			auth_xform = &conf->crypto_xform->next->auth;
	} else {
		auth_xform = &conf->crypto_xform->auth;
		if (conf->crypto_xform->next)
			cipher_xform = &conf->crypto_xform->next->cipher;
	}
	session->proto_alg = conf->protocol;

	if (cipher_xform && cipher_xform->algo != RTE_CRYPTO_CIPHER_NULL) {
		session->cipher_key.data = rte_zmalloc(NULL,
						       cipher_xform->key.length,
						       RTE_CACHE_LINE_SIZE);
		if (session->cipher_key.data == NULL &&
				cipher_xform->key.length > 0) {
			DPAA_SEC_ERR("No Memory for cipher key");
			return -ENOMEM;
		}
		memcpy(session->cipher_key.data, cipher_xform->key.data,
				cipher_xform->key.length);
		session->cipher_key.length = cipher_xform->key.length;

		switch (cipher_xform->algo) {
		case RTE_CRYPTO_CIPHER_AES_CBC:
		case RTE_CRYPTO_CIPHER_3DES_CBC:
		case RTE_CRYPTO_CIPHER_AES_CTR:
			break;
		default:
			DPAA_SEC_ERR("Crypto: Unsupported Cipher alg %u",
				cipher_xform->algo);
			goto out;
		}
		session->cipher_alg = cipher_xform->algo;
	} else {
		session->cipher_key.data = NULL;
		session->cipher_key.length = 0;
		session->cipher_alg = RTE_CRYPTO_CIPHER_NULL;
	}

	if (auth_xform && auth_xform->algo != RTE_CRYPTO_AUTH_NULL) {
		session->auth_key.data = rte_zmalloc(NULL,
						auth_xform->key.length,
						RTE_CACHE_LINE_SIZE);
		if (session->auth_key.data == NULL &&
				auth_xform->key.length > 0) {
			DPAA_SEC_ERR("No Memory for auth key");
			rte_free(session->cipher_key.data);
			return -ENOMEM;
		}
		memcpy(session->auth_key.data, auth_xform->key.data,
				auth_xform->key.length);
		session->auth_key.length = auth_xform->key.length;

		switch (auth_xform->algo) {
		case RTE_CRYPTO_AUTH_SHA1_HMAC:
		case RTE_CRYPTO_AUTH_MD5_HMAC:
		case RTE_CRYPTO_AUTH_SHA256_HMAC:
		case RTE_CRYPTO_AUTH_SHA384_HMAC:
		case RTE_CRYPTO_AUTH_SHA512_HMAC:
		case RTE_CRYPTO_AUTH_AES_CMAC:
			break;
		default:
			DPAA_SEC_ERR("Crypto: Unsupported auth alg %u",
				auth_xform->algo);
			goto out;
		}
		session->auth_alg = auth_xform->algo;
	} else {
		session->auth_key.data = NULL;
		session->auth_key.length = 0;
		session->auth_alg = RTE_CRYPTO_AUTH_NULL;
	}

	if (ipsec_xform->direction == RTE_SECURITY_IPSEC_SA_DIR_EGRESS) {
		memset(&session->encap_pdb, 0, sizeof(struct ipsec_encap_pdb) +
				sizeof(session->ip4_hdr));
		session->ip4_hdr.ip_v = IPVERSION;
		session->ip4_hdr.ip_hl = 5;
		session->ip4_hdr.ip_len = rte_cpu_to_be_16(
						sizeof(session->ip4_hdr));
		session->ip4_hdr.ip_tos = ipsec_xform->tunnel.ipv4.dscp;
		session->ip4_hdr.ip_id = 0;
		session->ip4_hdr.ip_off = 0;
		session->ip4_hdr.ip_ttl = ipsec_xform->tunnel.ipv4.ttl;
		session->ip4_hdr.ip_p = (ipsec_xform->proto ==
				RTE_SECURITY_IPSEC_SA_PROTO_ESP) ? IPPROTO_ESP
				: IPPROTO_AH;
		session->ip4_hdr.ip_sum = 0;
		session->ip4_hdr.ip_src = ipsec_xform->tunnel.ipv4.src_ip;
		session->ip4_hdr.ip_dst = ipsec_xform->tunnel.ipv4.dst_ip;
		session->ip4_hdr.ip_sum = calc_chksum((uint16_t *)
						(void *)&session->ip4_hdr,
						sizeof(struct ip));

		session->encap_pdb.options =
			(IPVERSION << PDBNH_ESP_ENCAP_SHIFT) |
			PDBOPTS_ESP_OIHI_PDB_INL |
			PDBOPTS_ESP_IVSRC |
			PDBHMO_ESP_ENCAP_DTTL |
			PDBHMO_ESP_SNR;
		session->encap_pdb.spi = ipsec_xform->spi;
		session->encap_pdb.ip_hdr_len = sizeof(struct ip);

		session->dir = DIR_ENC;
	} else if (ipsec_xform->direction ==
			RTE_SECURITY_IPSEC_SA_DIR_INGRESS) {
		memset(&session->decap_pdb, 0, sizeof(struct ipsec_decap_pdb));
		session->decap_pdb.options = sizeof(struct ip) << 16;
		session->dir = DIR_DEC;
	} else
		goto out;
	session->ctx_pool = internals->ctx_pool;
	rte_spinlock_lock(&internals->lock);
	session->inq = dpaa_sec_attach_rxq(internals);
	rte_spinlock_unlock(&internals->lock);
	if (session->inq == NULL) {
		DPAA_SEC_ERR("unable to attach sec queue");
		goto out;
	}


	return 0;
out:
	rte_free(session->auth_key.data);
	rte_free(session->cipher_key.data);
	memset(session, 0, sizeof(dpaa_sec_session));
	return -1;
}

static int
dpaa_sec_security_session_create(void *dev,
				 struct rte_security_session_conf *conf,
				 struct rte_security_session *sess,
				 struct rte_mempool *mempool)
{
	void *sess_private_data;
	struct rte_cryptodev *cdev = (struct rte_cryptodev *)dev;
	int ret;

	if (rte_mempool_get(mempool, &sess_private_data)) {
		DPAA_SEC_ERR("Couldn't get object from session mempool");
		return -ENOMEM;
	}

	switch (conf->protocol) {
	case RTE_SECURITY_PROTOCOL_IPSEC:
		ret = dpaa_sec_set_ipsec_session(cdev, conf,
				sess_private_data);
		break;
	case RTE_SECURITY_PROTOCOL_MACSEC:
		return -ENOTSUP;
	default:
		return -EINVAL;
	}
	if (ret != 0) {
		DPAA_SEC_ERR("failed to configure session parameters");
		/* Return session to mempool */
		rte_mempool_put(mempool, sess_private_data);
		return ret;
	}

	set_sec_session_private_data(sess, sess_private_data);

	return ret;
}

/** Clear the memory of session so it doesn't leave key material behind */
static int
dpaa_sec_security_session_destroy(void *dev __rte_unused,
		struct rte_security_session *sess)
{
	PMD_INIT_FUNC_TRACE();
	void *sess_priv = get_sec_session_private_data(sess);

	dpaa_sec_session *s = (dpaa_sec_session *)sess_priv;

	if (sess_priv) {
		struct rte_mempool *sess_mp = rte_mempool_from_obj(sess_priv);

		rte_free(s->cipher_key.data);
		rte_free(s->auth_key.data);
		memset(sess, 0, sizeof(dpaa_sec_session));
		set_sec_session_private_data(sess, NULL);
		rte_mempool_put(sess_mp, sess_priv);
	}
	return 0;
}


static int
dpaa_sec_dev_configure(struct rte_cryptodev *dev,
		       struct rte_cryptodev_config *config __rte_unused)
{

	char str[20];
	struct dpaa_sec_dev_private *internals;

	PMD_INIT_FUNC_TRACE();

	internals = dev->data->dev_private;
	sprintf(str, "ctx_pool_%d", dev->data->dev_id);
	if (!internals->ctx_pool) {
		internals->ctx_pool = rte_mempool_create((const char *)str,
							CTX_POOL_NUM_BUFS,
							CTX_POOL_BUF_SIZE,
							CTX_POOL_CACHE_SIZE, 0,
							NULL, NULL, NULL, NULL,
							SOCKET_ID_ANY, 0);
		if (!internals->ctx_pool) {
			DPAA_SEC_ERR("%s create failed\n", str);
			return -ENOMEM;
		}
	} else
		DPAA_SEC_INFO("mempool already created for dev_id : %d",
				dev->data->dev_id);

	return 0;
}

static int
dpaa_sec_dev_start(struct rte_cryptodev *dev __rte_unused)
{
	PMD_INIT_FUNC_TRACE();
	return 0;
}

static void
dpaa_sec_dev_stop(struct rte_cryptodev *dev __rte_unused)
{
	PMD_INIT_FUNC_TRACE();
}

static int
dpaa_sec_dev_close(struct rte_cryptodev *dev)
{
	struct dpaa_sec_dev_private *internals;

	PMD_INIT_FUNC_TRACE();

	if (dev == NULL)
		return -ENOMEM;

	internals = dev->data->dev_private;
	rte_mempool_free(internals->ctx_pool);
	internals->ctx_pool = NULL;

	return 0;
}

static void
dpaa_sec_dev_infos_get(struct rte_cryptodev *dev,
		       struct rte_cryptodev_info *info)
{
	struct dpaa_sec_dev_private *internals = dev->data->dev_private;

	PMD_INIT_FUNC_TRACE();
	if (info != NULL) {
		info->max_nb_queue_pairs = internals->max_nb_queue_pairs;
		info->feature_flags = dev->feature_flags;
		info->capabilities = dpaa_sec_capabilities;
		info->sym.max_nb_sessions = internals->max_nb_sessions;
		info->driver_id = cryptodev_driver_id;
	}
}

static struct rte_cryptodev_ops crypto_ops = {
	.dev_configure	      = dpaa_sec_dev_configure,
	.dev_start	      = dpaa_sec_dev_start,
	.dev_stop	      = dpaa_sec_dev_stop,
	.dev_close	      = dpaa_sec_dev_close,
	.dev_infos_get        = dpaa_sec_dev_infos_get,
	.queue_pair_setup     = dpaa_sec_queue_pair_setup,
	.queue_pair_release   = dpaa_sec_queue_pair_release,
	.queue_pair_count     = dpaa_sec_queue_pair_count,
	.sym_session_get_size     = dpaa_sec_sym_session_get_size,
	.sym_session_configure    = dpaa_sec_sym_session_configure,
	.sym_session_clear        = dpaa_sec_sym_session_clear
};

static const struct rte_security_capability *
dpaa_sec_capabilities_get(void *device __rte_unused)
{
	return dpaa_sec_security_cap;
}

static const struct rte_security_ops dpaa_sec_security_ops = {
	.session_create = dpaa_sec_security_session_create,
	.session_update = NULL,
	.session_stats_get = NULL,
	.session_destroy = dpaa_sec_security_session_destroy,
	.set_pkt_metadata = NULL,
	.capabilities_get = dpaa_sec_capabilities_get
};

static int
dpaa_sec_uninit(struct rte_cryptodev *dev)
{
	struct dpaa_sec_dev_private *internals;

	if (dev == NULL)
		return -ENODEV;

	internals = dev->data->dev_private;
	rte_free(dev->security_ctx);

	/* In case close has been called, internals->ctx_pool would be NULL */
	rte_mempool_free(internals->ctx_pool);
	rte_free(internals);

	DPAA_SEC_INFO("Closing DPAA_SEC device %s on numa socket %u",
		      dev->data->name, rte_socket_id());

	return 0;
}

static int
dpaa_sec_dev_init(struct rte_cryptodev *cryptodev)
{
	struct dpaa_sec_dev_private *internals;
	struct rte_security_ctx *security_instance;
	struct dpaa_sec_qp *qp;
	uint32_t i, flags;
	int ret;

	PMD_INIT_FUNC_TRACE();

	cryptodev->driver_id = cryptodev_driver_id;
	cryptodev->dev_ops = &crypto_ops;

	cryptodev->enqueue_burst = dpaa_sec_enqueue_burst;
	cryptodev->dequeue_burst = dpaa_sec_dequeue_burst;
	cryptodev->feature_flags = RTE_CRYPTODEV_FF_SYMMETRIC_CRYPTO |
			RTE_CRYPTODEV_FF_HW_ACCELERATED |
			RTE_CRYPTODEV_FF_SYM_OPERATION_CHAINING |
			RTE_CRYPTODEV_FF_SECURITY |
			RTE_CRYPTODEV_FF_IN_PLACE_SGL |
			RTE_CRYPTODEV_FF_OOP_SGL_IN_SGL_OUT |
			RTE_CRYPTODEV_FF_OOP_SGL_IN_LB_OUT |
			RTE_CRYPTODEV_FF_OOP_LB_IN_SGL_OUT |
			RTE_CRYPTODEV_FF_OOP_LB_IN_LB_OUT;

	internals = cryptodev->data->dev_private;
	internals->max_nb_queue_pairs = RTE_DPAA_MAX_NB_SEC_QPS;
	internals->max_nb_sessions = RTE_DPAA_SEC_PMD_MAX_NB_SESSIONS;

	/*
	 * For secondary processes, we don't initialise any further as primary
	 * has already done this work. Only check we don't need a different
	 * RX function
	 */
	if (rte_eal_process_type() != RTE_PROC_PRIMARY) {
		DPAA_SEC_WARN("Device already init by primary process");
		return 0;
	}

	/* Initialize security_ctx only for primary process*/
	security_instance = rte_malloc("rte_security_instances_ops",
				sizeof(struct rte_security_ctx), 0);
	if (security_instance == NULL)
		return -ENOMEM;
	security_instance->device = (void *)cryptodev;
	security_instance->ops = &dpaa_sec_security_ops;
	security_instance->sess_cnt = 0;
	cryptodev->security_ctx = security_instance;

	rte_spinlock_init(&internals->lock);
	for (i = 0; i < internals->max_nb_queue_pairs; i++) {
		/* init qman fq for queue pair */
		qp = &internals->qps[i];
		ret = dpaa_sec_init_tx(&qp->outq);
		if (ret) {
			DPAA_SEC_ERR("config tx of queue pair  %d", i);
			goto init_error;
		}
	}

	flags = QMAN_FQ_FLAG_LOCKED | QMAN_FQ_FLAG_DYNAMIC_FQID |
		QMAN_FQ_FLAG_TO_DCPORTAL;
	for (i = 0; i < internals->max_nb_sessions; i++) {
		/* create rx qman fq for sessions*/
		ret = qman_create_fq(0, flags, &internals->inq[i]);
		if (unlikely(ret != 0)) {
			DPAA_SEC_ERR("sec qman_create_fq failed");
			goto init_error;
		}
	}

	RTE_LOG(INFO, PMD, "%s cryptodev init\n", cryptodev->data->name);
	return 0;

init_error:
	DPAA_SEC_ERR("driver %s: create failed\n", cryptodev->data->name);

	dpaa_sec_uninit(cryptodev);
	return -EFAULT;
}

static int
cryptodev_dpaa_sec_probe(struct rte_dpaa_driver *dpaa_drv __rte_unused,
				struct rte_dpaa_device *dpaa_dev)
{
	struct rte_cryptodev *cryptodev;
	char cryptodev_name[RTE_CRYPTODEV_NAME_MAX_LEN];

	int retval;

	sprintf(cryptodev_name, "dpaa_sec-%d", dpaa_dev->id.dev_id);

	cryptodev = rte_cryptodev_pmd_allocate(cryptodev_name, rte_socket_id());
	if (cryptodev == NULL)
		return -ENOMEM;

	if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
		cryptodev->data->dev_private = rte_zmalloc_socket(
					"cryptodev private structure",
					sizeof(struct dpaa_sec_dev_private),
					RTE_CACHE_LINE_SIZE,
					rte_socket_id());

		if (cryptodev->data->dev_private == NULL)
			rte_panic("Cannot allocate memzone for private "
					"device data");
	}

	dpaa_dev->crypto_dev = cryptodev;
	cryptodev->device = &dpaa_dev->device;

	/* init user callbacks */
	TAILQ_INIT(&(cryptodev->link_intr_cbs));

	/* if sec device version is not configured */
	if (!rta_get_sec_era()) {
		const struct device_node *caam_node;

		for_each_compatible_node(caam_node, NULL, "fsl,sec-v4.0") {
			const uint32_t *prop = of_get_property(caam_node,
					"fsl,sec-era",
					NULL);
			if (prop) {
				rta_set_sec_era(
					INTL_SEC_ERA(rte_cpu_to_be_32(*prop)));
				break;
			}
		}
	}

	/* Invoke PMD device initialization function */
	retval = dpaa_sec_dev_init(cryptodev);
	if (retval == 0)
		return 0;

	/* In case of error, cleanup is done */
	if (rte_eal_process_type() == RTE_PROC_PRIMARY)
		rte_free(cryptodev->data->dev_private);

	rte_cryptodev_pmd_release_device(cryptodev);

	return -ENXIO;
}

static int
cryptodev_dpaa_sec_remove(struct rte_dpaa_device *dpaa_dev)
{
	struct rte_cryptodev *cryptodev;
	int ret;

	cryptodev = dpaa_dev->crypto_dev;
	if (cryptodev == NULL)
		return -ENODEV;

	ret = dpaa_sec_uninit(cryptodev);
	if (ret)
		return ret;

	return rte_cryptodev_pmd_destroy(cryptodev);
}

static struct rte_dpaa_driver rte_dpaa_sec_driver = {
	.drv_type = FSL_DPAA_CRYPTO,
	.driver = {
		.name = "DPAA SEC PMD"
	},
	.probe = cryptodev_dpaa_sec_probe,
	.remove = cryptodev_dpaa_sec_remove,
};

static struct cryptodev_driver dpaa_sec_crypto_drv;

RTE_PMD_REGISTER_DPAA(CRYPTODEV_NAME_DPAA_SEC_PMD, rte_dpaa_sec_driver);
RTE_PMD_REGISTER_CRYPTO_DRIVER(dpaa_sec_crypto_drv, rte_dpaa_sec_driver.driver,
		cryptodev_driver_id);

RTE_INIT(dpaa_sec_init_log)
{
	dpaa_logtype_sec = rte_log_register("pmd.crypto.dpaa");
	if (dpaa_logtype_sec >= 0)
		rte_log_set_level(dpaa_logtype_sec, RTE_LOG_NOTICE);
}