forked from intel/QAT_Engine
/
e_qat.c
1502 lines (1331 loc) · 47.9 KB
/
e_qat.c
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ====================================================================
*
*
* BSD LICENSE
*
* Copyright(c) 2016 Intel Corporation.
* 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.
*
*
* ====================================================================
*/
/*****************************************************************************
* @file e_qat.c
*
* This file provides a OpenSSL engine for the quick assist API
*
*****************************************************************************/
/* macros defined to allow use of the cpu get and set affinity functions */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#ifndef __USE_GNU
# define __USE_GNU
#endif
/* Defines */
#if defined(USE_QAT_CONTIG_MEM) && !defined(USE_QAE_MEM)
# define QAT_DEV "/dev/qat_contig_mem"
#elif defined(USE_QAE_MEM) && !defined(USE_QAT_CONTIG_MEM)
# define QAT_DEV "/dev/qae_mem"
#elif defined(USE_QAE_MEM) && defined(USE_QAT_CONFIG_MEM)
# error "USE_QAT_CONTIG_MEM and USE_QAE_MEM both defined"
#else
# error "No memory driver type defined"
#endif
/*
* The default interval in nanoseconds used for the internal polling thread
*/
#define QAT_POLL_PERIOD_IN_NS 10000
/*
* The number of retries of the nanosleep if it gets interrupted during
* waiting between polling.
*/
#define QAT_CRYPTO_NUM_POLLING_RETRIES (5)
/*
* The number of seconds to wait for a response back after submitting a
* request before raising an error.
*/
#define QAT_CRYPTO_RESPONSE_TIMEOUT (5)
/*
* The default timeout in milliseconds used for epoll_wait when event driven
* polling mode is enabled.
*/
#define QAT_EPOLL_TIMEOUT_IN_MS 1000
/* Standard Includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/eventfd.h>
#include <unistd.h>
/* Local Includes */
#include "qat_ciphers.h"
#include "qat_rsa.h"
#include "qat_dsa.h"
#include "qat_dh.h"
#include "qat_ec.h"
#include "e_qat.h"
#include "qat_utils.h"
#include "e_qat_err.h"
#include "qat_prf.h"
/* OpenSSL Includes */
#include <openssl/err.h>
#include <openssl/async.h>
#include <openssl/objects.h>
#include <openssl/crypto.h>
/* QAT includes */
#ifdef USE_QAT_CONTIG_MEM
# include "qae_mem_utils.h"
#endif
#ifdef USE_QAE_MEM
# include "cmn_mem_drv_inf.h"
#endif
#include "cpa.h"
#include "cpa_cy_im.h"
#include "cpa_types.h"
#include "icp_sal_user.h"
#include "icp_sal_poll.h"
#include "qat_parseconf.h"
#define MAX_EVENTS 32
#define MAX_CRYPTO_INSTANCES 64
#define likely(x) __builtin_expect (!!(x), 1)
#define unlikely(x) __builtin_expect (!!(x), 0)
/* Macro used to handle errors in qat_engine_ctrl() */
#define BREAK_IF(cond, mesg) \
if(unlikely(cond)) { retVal = 0; WARN(mesg); break; }
/* Forward Declarations */
static int qat_engine_finish(ENGINE *e);
/* Qat engine id declaration */
static const char *engine_qat_id = "qat";
static const char *engine_qat_name =
"Reference implementation of QAT crypto engine";
char *ICPConfigSectionName_libcrypto = "SHIM";
/* Globals */
typedef struct {
int eng_fd;
int inst_index;
} ENGINE_EPOLL_ST;
struct epoll_event eng_epoll_events[MAX_CRYPTO_INSTANCES] = { { 0, 0 } };
static int internal_efd = 0;
static ENGINE_EPOLL_ST eng_poll_st[MAX_CRYPTO_INSTANCES] = { {-1} };
CpaInstanceHandle *qatInstanceHandles = NULL;
static pthread_key_t qatInstanceForThread;
pthread_t *icp_polling_threads;
static int keep_polling = 1;
static int enable_external_polling = 0;
static int enable_event_driven_polling = 0;
static int enable_instance_for_thread = 0;
Cpa16U numInstances = 0;
int qatPerformOpRetries = 0;
static int currInst = 0;
static pthread_mutex_t qat_instance_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t qat_engine_mutex = PTHREAD_MUTEX_INITIALIZER;
static unsigned int engine_inited = 0;
static unsigned int instance_started[MAX_CRYPTO_INSTANCES] = {0};
static useconds_t qat_poll_interval = QAT_POLL_PERIOD_IN_NS;
static int qat_epoll_timeout = QAT_EPOLL_TIMEOUT_IN_MS;
static int qat_max_retry_count = QAT_CRYPTO_NUM_POLLING_RETRIES;
static int qat_engine_init(ENGINE *e);
int getQatMsgRetryCount()
{
return qat_max_retry_count;
}
useconds_t getQatPollInterval()
{
return qat_poll_interval;
}
int qat_is_event_driven()
{
return enable_event_driven_polling;
}
#ifndef OPENSSL_ENABLE_QAT_SMALL_PACKET_CIPHER_OFFLOADS
int setQatSmallPacketThreshold(unsigned char *cipher_name, int threshold)
{
if(threshold < 0)
threshold = 0;
else if (threshold > 16384)
threshold = 16384;
return qat_pkt_threshold_table_set_threshold(OBJ_sn2nid(cipher_name),threshold);
}
#endif
/******************************************************************************
* function:
* incr_curr_inst(void)
*
* description:
* Increment the logical Cy instance number to use for the next operation.
*
******************************************************************************/
static inline void incr_curr_inst(void)
{
pthread_mutex_lock(&qat_instance_mutex);
currInst = (currInst + 1) % numInstances;
pthread_mutex_unlock(&qat_instance_mutex);
}
/******************************************************************************
* function:
* get_next_inst(void)
*
* description:
* Return the next instance handle to use for an operation.
*
******************************************************************************/
CpaInstanceHandle get_next_inst(void)
{
CpaInstanceHandle instanceHandle = NULL;
CpaStatus status = CPA_STATUS_SUCCESS;
ENGINE* e = NULL;
if (1 == enable_instance_for_thread) {
instanceHandle = pthread_getspecific(qatInstanceForThread);
/* If no thread specific data is found then return NULL
as there should be as the flag is set */
if (instanceHandle == NULL)
return instanceHandle;
}
e = ENGINE_by_id(engine_qat_id);
if(e == NULL) {
instanceHandle = NULL;
return instanceHandle;
}
if(!qat_engine_init(e)){
instanceHandle = NULL;
return instanceHandle;
}
/* Anytime we use external polling then we want to loop
through the instances. Any time we are using internal polling
then we also want to loop through the instances assuming
one was not retrieved from thread specific data. */
if (1 == enable_external_polling || instanceHandle == NULL)
{
if (qatInstanceHandles) {
instanceHandle = qatInstanceHandles[currInst];
incr_curr_inst();
} else {
instanceHandle = NULL;
}
}
return instanceHandle;
}
static void engine_fork_handler(void)
{
/*Reset engine*/
ENGINE* e = ENGINE_by_id(engine_qat_id);
if(e == NULL) {
return;
}
qat_engine_finish(e);
keep_polling = 1;
}
/******************************************************************************
* function:
* qat_set_instance_for_thread(long instanceNum)
*
* @param instanceNum [IN] - logical instance number
*
* description:
* Bind the current thread to a particular logical Cy instance. Note that if
* instanceNum is greater than the number of configured instances, the
* modulus operation is used.
*
******************************************************************************/
void qat_set_instance_for_thread(long instanceNum)
{
int rc;
if ((rc =
pthread_setspecific(qatInstanceForThread,
qatInstanceHandles[instanceNum %
numInstances])) != 0) {
fprintf(stderr, "pthread_setspecific: %s\n", strerror(rc));
return;
}
enable_instance_for_thread = 1;
}
/******************************************************************************
* function:
* initOpDone(struct op_done *opDone)
*
* @param opDone [IN] - pointer to op done callback structure
*
* description:
* Initialise the QAT operation "done" callback structure.
*
******************************************************************************/
void initOpDone(struct op_done *opDone)
{
if (opDone == NULL) {
return;
}
opDone->flag = 0;
opDone->verifyResult = CPA_FALSE;
opDone->job = ASYNC_get_current_job();
}
/******************************************************************************
* function:
* cleanupOpDone(struct op_done *opDone)
*
* @param opDone [IN] - pointer to op done callback structure
*
* description:
* Cleanup the data in the "done" callback structure.
*
******************************************************************************/
void cleanupOpDone(struct op_done *opDone)
{
if (opDone == NULL) {
return;
}
/*
* op_done:verifyResult is used after return from this function
* Donot change this value.
*/
if (opDone->job) {
opDone->job = NULL;
}
}
/******************************************************************************
* function:
* qat_crypto_callbackFn(void *callbackTag, CpaStatus status,
* const CpaCySymOp operationType, void *pOpData,
* CpaBufferList * pDstBuffer, CpaBoolean verifyResult)
*
* @param pCallbackTag [IN] - Opaque value provided by user while making
* individual function call. Cast to op_done.
* @param status [IN] - Status of the operation.
* @param operationType [IN] - Identifies the operation type requested.
* @param pOpData [IN] - Pointer to structure with input parameters.
* @param pDstBuffer [IN] - Destination buffer to hold the data output.
* @param verifyResult [IN] - Used to verify digest result.
*
* description:
* Callback function used by cpaCySymPerformOp to indicate completion.
*
******************************************************************************/
void qat_crypto_callbackFn(void *callbackTag, CpaStatus status,
const CpaCySymOp operationType, void *pOpData,
CpaBufferList * pDstBuffer,
CpaBoolean verifyResult)
{
struct op_done *opDone = (struct op_done *)callbackTag;
if (opDone == NULL) {
return;
}
DEBUG("e_qat.%s: status %d verifyResult %d\n", __func__, status,
verifyResult);
opDone->verifyResult = (status == CPA_STATUS_SUCCESS) && verifyResult
? CPA_TRUE : CPA_FALSE;
if (opDone->job) {
opDone->flag = 1;
qat_wake_job(opDone->job, 0);
} else {
opDone->flag = 1;
}
}
/******************************************************************************
* function:
* CpaStatus myPerformOp(const CpaInstanceHandle instanceHandle,
* void * pCallbackTag,
* const CpaCySymOpData *pOpData,
* const CpaBufferList *pSrcBuffer,
* CpaBufferList *pDstBuffer,
* CpaBoolean *pVerifyResult)
*
* @param ih [IN] - Instance handle
* @param instanceHandle [IN] - Instance handle
* @param pCallbackTag [IN] - Pointer to op_done struct
* @param pOpData [IN] - Operation parameters
* @param pSrcBuffer [IN] - Source buffer list
* @param pDstBuffer [OUT] - Destination buffer list
* @param pVerifyResult [OUT] - Whether hash verified or not
*
* description:
* Wrapper around cpaCySymPerformOp which handles retries for us.
*
******************************************************************************/
CpaStatus myPerformOp(const CpaInstanceHandle instanceHandle,
void *pCallbackTag,
const CpaCySymOpData * pOpData,
const CpaBufferList * pSrcBuffer,
CpaBufferList * pDstBuffer, CpaBoolean * pVerifyResult)
{
CpaStatus status;
struct op_done *opDone = (struct op_done *)pCallbackTag;
unsigned int uiRetry = 0;
do {
status = cpaCySymPerformOp(instanceHandle,
pCallbackTag,
pOpData,
pSrcBuffer, pDstBuffer, pVerifyResult);
if (status == CPA_STATUS_RETRY) {
if (opDone->job) {
if ((qat_wake_job(opDone->job, 0) == 0) ||
(qat_pause_job(opDone->job, 0) == 0)) {
status = CPA_STATUS_FAIL;
break;
}
} else {
qatPerformOpRetries++;
if (uiRetry >= qat_max_retry_count
&& qat_max_retry_count != QAT_INFINITE_MAX_NUM_RETRIES) {
break;
}
uiRetry++;
usleep(qat_poll_interval +
(uiRetry % QAT_RETRY_BACKOFF_MODULO_DIVISOR));
}
}
}
while (status == CPA_STATUS_RETRY);
return status;
}
static void qat_fd_cleanup(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD readfd, void *custom)
{
close(readfd);
}
int qat_setup_async_event_notification(int notificationNo)
{
/* We will ignore notificationNo for the moment */
ASYNC_JOB *job;
ASYNC_WAIT_CTX *waitctx;
OSSL_ASYNC_FD efd;
void *custom = NULL;
int ret = 0;
if ((job = ASYNC_get_current_job()) == NULL)
return ret;
if ((waitctx = ASYNC_get_wait_ctx(job)) == NULL)
return ret;
if (ASYNC_WAIT_CTX_get_fd(waitctx, engine_qat_id, &efd,
&custom)) {
ret = 1;
} else {
efd = eventfd(0, 0);
if (efd == -1) {
WARN("Failed to get eventfd = %d\n", errno);
return ret;
}
if ((ret = ASYNC_WAIT_CTX_set_wait_fd(waitctx, engine_qat_id, efd,
custom, qat_fd_cleanup)) == 0) {
qat_fd_cleanup(waitctx, engine_qat_id, efd, NULL);
}
}
return ret;
}
int qat_pause_job(ASYNC_JOB *job, int notificationNo)
{
/* We will ignore notificationNo for the moment */
ASYNC_WAIT_CTX *waitctx;
OSSL_ASYNC_FD efd;
void *custom = NULL;
uint64_t buf = 0;
int ret = 0;
if (ASYNC_pause_job() == 0)
return ret;
if ((waitctx = ASYNC_get_wait_ctx(job)) == NULL)
return ret;
if ((ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_qat_id, &efd,
&custom)) > 0) {
read(efd, &buf, sizeof(uint64_t));
}
return ret;
}
int qat_wake_job(ASYNC_JOB *job, int notificationNo)
{
/* We will ignore notificationNo for the moment */
ASYNC_WAIT_CTX *waitctx;
OSSL_ASYNC_FD efd;
void *custom = NULL;
/* Arbitary character 'X' to write down the pipe to trigger event */
uint64_t buf = 1;
int ret = 0;
if ((waitctx = ASYNC_get_wait_ctx(job)) == NULL)
return ret;
if ((ret = ASYNC_WAIT_CTX_get_fd(waitctx, engine_qat_id, &efd,
&custom)) > 0) {
write(efd, &buf, sizeof(uint64_t));
}
return ret;
}
/******************************************************************************
* function:
* int qat_create_thread(pthread_t *pThreadId,
* const pthread_attr_t *attr,
* void *(*start_func) (void *), void *pArg)
*
* @param pThreadId [OUT] - Pointer to Thread ID
* @param start_func [IN] - Pointer to Thread Start routine
* @param attr [IN] - Pointer to Thread attributes
* @param pArg [IN] - Arguments to start routine
*
* description:
* Wrapper function for pthread_create
******************************************************************************/
int qat_create_thread(pthread_t *pThreadId, const pthread_attr_t *attr,
void *(*start_func) (void *), void *pArg)
{
return pthread_create(pThreadId, attr, start_func,(void *)pArg);
}
/******************************************************************************
* function:
* int qat_join_thread(pthread_t threadId, void **retval)
*
* @param pThreadId [IN ] - Thread ID of the created thread
* @param retval [OUT] - Pointer that contains thread's exit status
*
* description:
* Wrapper function for pthread_create
******************************************************************************/
int qat_join_thread(pthread_t threadId, void **retval)
{
return pthread_join(threadId, retval);
}
/******************************************************************************
* function:
* void *sendPoll_ns(void *ih)
*
* @param ih [IN] - Instance handle
*
* description:
* Poll the QAT instances (nanosleep version)
* NB: Delay in this function is set by default at runtime by an engine
* specific message. If not set then the default is QAT_POLL_PERIOD_IN_NS.
*
******************************************************************************/
static void *sendPoll_ns(void *ih)
{
CpaStatus status = 0;
CpaInstanceHandle instanceHandle;
struct timespec reqTime = { 0 };
struct timespec remTime = { 0 };
unsigned int retry_count = 0; /* to prevent too much time drift */
instanceHandle = (CpaInstanceHandle) ih;
if (NULL == instanceHandle) {
WARN("WARNING sendPoll_ns - instanceHandle is NULL\n");
return NULL;
}
while (keep_polling) {
reqTime.tv_nsec = qat_poll_interval;
/* Poll for 0 means process all packets on the instance */
status = icp_sal_CyPollInstance(instanceHandle, 0);
if (likely
(CPA_STATUS_SUCCESS == status || CPA_STATUS_RETRY == status)) {
/* Do nothing */
} else {
WARN("WARNING icp_sal_CyPollInstance returned status %d\n",
status);
}
retry_count = 0;
do {
retry_count++;
nanosleep(&reqTime, &remTime);
reqTime.tv_sec = remTime.tv_sec;
reqTime.tv_nsec = remTime.tv_nsec;
if (unlikely((errno < 0) && (EINTR != errno))) {
WARN("WARNING nanosleep system call failed: errno %i\n",
errno);
break;
}
}
while ((retry_count <= QAT_CRYPTO_NUM_POLLING_RETRIES)
&& (EINTR == errno));
}
end:
return NULL;
}
static void *eventPoll_ns(void *ih)
{
CpaStatus status = 0;
struct epoll_event *events = NULL;
ENGINE_EPOLL_ST* epollst = NULL;
/* Buffer where events are returned */
events = OPENSSL_zalloc(sizeof(struct epoll_event) * MAX_EVENTS);
if (NULL == events) {
WARN("Error allocating events list\n");
goto end;
}
while (keep_polling) {
int n = 0;
int i = 0;
n = epoll_wait(internal_efd, events, MAX_EVENTS, qat_epoll_timeout);
for (i = 0; i < n; ++i) {
if (events[i].events & EPOLLIN) {
/* poll for 0 means process all packets on the ET ring */
epollst = (ENGINE_EPOLL_ST*)events[i].data.ptr;
status = icp_sal_CyPollInstance(qatInstanceHandles[epollst->inst_index], 0);
if (CPA_STATUS_SUCCESS == status) {
/* do nothing */
} else {
WARN("WARNING icp_sal_CyPollInstance returned status %d\n", status);
}
}
}
}
OPENSSL_free(events);
events = 0;
end:
return NULL;
}
static CpaStatus poll_instances(void)
{
unsigned int poll_loop;
CpaInstanceHandle instanceHandle = NULL;
CpaStatus internal_status = CPA_STATUS_SUCCESS,
ret_status = CPA_STATUS_SUCCESS;
if (enable_instance_for_thread)
instanceHandle = pthread_getspecific(qatInstanceForThread);
if (instanceHandle) {
ret_status = icp_sal_CyPollInstance(instanceHandle, 0);
} else {
for (poll_loop = 0; poll_loop < numInstances; poll_loop++) {
if (qatInstanceHandles[poll_loop] != NULL) {
internal_status =
icp_sal_CyPollInstance(qatInstanceHandles[poll_loop], 0);
if (CPA_STATUS_SUCCESS == internal_status) {
/* Do nothing */
} else if (CPA_STATUS_RETRY == internal_status) {
ret_status = internal_status;
} else {
WARN("WARNING icp_sal_CyPollInstance returned status %d\n", internal_status);
ret_status = internal_status;
break;
}
}
}
}
return ret_status;
}
/******************************************************************************
* function:
* virtualToPhysical(void *virtualAddr)
*
* @param virtualAddr [IN] - Virtual address.
*
* description:
* Translates virtual address to hardware physical address. See the qae_mem
* module for more details. The virtual to physical translator is required
* by the QAT hardware to map from virtual addresses to physical locations
* in pinned memory.
*
* This function is designed to work with the allocator defined in
* qae_mem_utils.c and qat_contig_mem/qat_contig_mem.c
*
******************************************************************************/
static CpaPhysicalAddr virtualToPhysical(void *virtualAddr)
{
return qaeCryptoMemV2P(virtualAddr);
}
int qat_adjust_thread_affinity(pthread_t threadptr)
{
#ifdef QAT_POLL_CORE_AFFINITY
int coreID = 0;
int sts = 1;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(coreID, &cpuset);
sts = pthread_setaffinity_np(threadptr, sizeof(cpu_set_t), &cpuset);
if (sts != 0) {
DEBUG("pthread_setaffinity_np error, status = %d \n", sts);
return 0;
}
sts = pthread_getaffinity_np(threadptr, sizeof(cpu_set_t), &cpuset);
if (sts != 0) {
DEBUG("pthread_getaffinity_np error, status = %d \n", sts);
return 0;
}
if (CPU_ISSET(coreID, &cpuset)) {
DEBUG("Polling thread assigned on CPU core %d\n", coreID);
}
#endif
return 1;
}
/******************************************************************************
* function:
* qat_engine_init(ENGINE *e)
*
* @param e [IN] - OpenSSL engine pointer
*
* description:
* Qat engine init function, associated with Crypto memory setup
* and cpaStartInstance setups.
******************************************************************************/
static int qat_engine_init(ENGINE *e)
{
int instNum, err, checkLimitStatus;
CpaStatus status = CPA_STATUS_SUCCESS;
CpaBoolean limitDevAccess = CPA_FALSE;
pthread_mutex_lock(&qat_engine_mutex);
if(engine_inited) {
pthread_mutex_unlock(&qat_engine_mutex);
return 1;
}
DEBUG("[%s] ---- Engine Initing\n\n", __func__);
CRYPTO_INIT_QAT_LOG();
if ((err = pthread_key_create(&qatInstanceForThread, NULL)) != 0) {
fprintf(stderr, "pthread_key_create: %s\n", strerror(err));
pthread_mutex_unlock(&qat_engine_mutex);
return 0;
}
checkLimitStatus =
checkLimitDevAccessValue((int *)&limitDevAccess,
ICPConfigSectionName_libcrypto);
if (!checkLimitStatus) {
WARN("Assuming LimitDevAccess = 0\n");
}
/* Initialise the QAT hardware */
if (CPA_STATUS_SUCCESS !=
icp_sal_userStartMultiProcess(ICPConfigSectionName_libcrypto,
limitDevAccess)) {
WARN("icp_sal_userStart failed\n");
pthread_mutex_unlock(&qat_engine_mutex);
return 0;
}
/* Get the number of available instances */
status = cpaCyGetNumInstances(&numInstances);
if (CPA_STATUS_SUCCESS != status) {
WARN("cpaCyGetNumInstances failed, status=%d\n", status);
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
if (!numInstances) {
WARN("No crypto instances found\n");
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
DEBUG("%s: %d Cy instances got\n", __func__, numInstances);
/* Allocate memory for the instance handle array */
qatInstanceHandles =
(CpaInstanceHandle *) OPENSSL_zalloc(((int)numInstances) *
sizeof(CpaInstanceHandle));
if (NULL == qatInstanceHandles) {
WARN("OPENSSL_zalloc() failed for instance handles.\n");
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
/* Get the Cy instances */
status = cpaCyGetInstances(numInstances, qatInstanceHandles);
if (CPA_STATUS_SUCCESS != status) {
WARN("cpaCyGetInstances failed, status=%d\n", status);
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
if (0 == enable_external_polling) {
if (qat_is_event_driven()) {
CpaStatus status;
int flags;
int engine_fd;
icp_polling_threads =
(pthread_t *) OPENSSL_zalloc(sizeof(pthread_t));
/* Add the file descriptor to an epoll event list */
internal_efd = epoll_create1(0);
if (-1 == internal_efd) {
WARN("Error creating epoll fd\n");
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
for (instNum = 0; instNum < numInstances; instNum++) {
/* Get the file descriptor for the instance */
status =
icp_sal_CyGetFileDescriptor(qatInstanceHandles[instNum],
&engine_fd);
if (CPA_STATUS_FAIL == status) {
WARN("Error getting file descriptor for instance\n");
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
/* Make the file descriptor non-blocking */
eng_poll_st[instNum].eng_fd = engine_fd;
eng_poll_st[instNum].inst_index = instNum;
flags = fcntl(engine_fd, F_GETFL, 0);
fcntl(engine_fd, F_SETFL, flags | O_NONBLOCK);
eng_epoll_events[instNum].data.ptr = &eng_poll_st[instNum];
eng_epoll_events[instNum].events = EPOLLIN | EPOLLET;
if (-1 ==
epoll_ctl(internal_efd, EPOLL_CTL_ADD, engine_fd,
&eng_epoll_events[instNum])) {
WARN("Error adding fd to epoll\n");
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
}
} else {
icp_polling_threads =
(pthread_t *) OPENSSL_zalloc(((int)numInstances) *
sizeof(pthread_t));
}
if (NULL == icp_polling_threads) {
WARN("OPENSSL_malloc() failed for icp_polling_threads.\n");
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
}
/* Set translation function and start each instance */
for (instNum = 0; instNum < numInstances; instNum++) {
/* Set the address translation function */
status = cpaCySetAddressTranslation(qatInstanceHandles[instNum],
virtualToPhysical);
if (CPA_STATUS_SUCCESS != status) {
WARN("cpaCySetAddressTranslation failed, status=%d\n", status);
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
/* Start the instances */
status = cpaCyStartInstance(qatInstanceHandles[instNum]);
if (CPA_STATUS_SUCCESS != status) {
WARN("cpaCyStartInstance failed, status=%d\n", status);
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
if (0 == enable_external_polling && !qat_is_event_driven()) {
/* Create the polling threads */
if (qat_create_thread(&icp_polling_threads[instNum], NULL,
sendPoll_ns, qatInstanceHandles[instNum])) {
WARN("Polling thread create failed\n");
instance_started[instNum] = 1;
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
if (qat_adjust_thread_affinity(icp_polling_threads[instNum]) == 0) {
instance_started[instNum] = 1;
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
}
instance_started[instNum] = 1;
}
if (0 == enable_external_polling && qat_is_event_driven()) {
if (qat_create_thread(&icp_polling_threads[0], NULL, eventPoll_ns, NULL)) {
WARN("Epoll thread create failed\n");
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
if (qat_adjust_thread_affinity(icp_polling_threads[0]) == 0) {
pthread_mutex_unlock(&qat_engine_mutex);
qat_engine_finish(e);
return 0;
}
}
/* Reset currInst */
currInst = 0;
engine_inited = 1;
pthread_mutex_unlock(&qat_engine_mutex);
return 1;
}
#define QAT_CMD_ENABLE_EXTERNAL_POLLING ENGINE_CMD_BASE
#define QAT_CMD_POLL (ENGINE_CMD_BASE + 1)
#define QAT_CMD_SET_INSTANCE_FOR_THREAD (ENGINE_CMD_BASE + 2)
#define QAT_CMD_GET_NUM_OP_RETRIES (ENGINE_CMD_BASE + 3)
#define QAT_CMD_SET_MAX_RETRY_COUNT (ENGINE_CMD_BASE + 4)
#define QAT_CMD_SET_INTERNAL_POLL_INTERVAL (ENGINE_CMD_BASE + 5)
#define QAT_CMD_GET_EXTERNAL_POLLING_FD (ENGINE_CMD_BASE + 6)
#define QAT_CMD_ENABLE_EVENT_DRIVEN_POLLING_MODE (ENGINE_CMD_BASE + 7)
#define QAT_CMD_GET_NUM_CRYPTO_INSTANCES (ENGINE_CMD_BASE + 8)
#define QAT_CMD_DISABLE_EVENT_DRIVEN_POLLING_MODE (ENGINE_CMD_BASE + 9)
#define QAT_CMD_SET_EPOLL_TIMEOUT (ENGINE_CMD_BASE + 10)
#define QAT_CMD_SET_CRYPTO_SMALL_PACKET_OFFLOAD_THRESHOLD (ENGINE_CMD_BASE + 11)
static const ENGINE_CMD_DEFN qat_cmd_defns[] = {
{
QAT_CMD_ENABLE_EXTERNAL_POLLING,
"ENABLE_EXTERNAL_POLLING",
"Enables the external polling interface to the engine.",
ENGINE_CMD_FLAG_NO_INPUT},
{
QAT_CMD_POLL,
"POLL",
"Polls the engine for any completed requests",
ENGINE_CMD_FLAG_NO_INPUT},
{
QAT_CMD_SET_INSTANCE_FOR_THREAD,
"SET_INSTANCE_FOR_THREAD",
"Set instance to be used by this thread",
ENGINE_CMD_FLAG_NUMERIC},
{
QAT_CMD_GET_NUM_OP_RETRIES,
"GET_NUM_OP_RETRIES",
"Get number of retries",
ENGINE_CMD_FLAG_NO_INPUT},
{
QAT_CMD_SET_MAX_RETRY_COUNT,
"SET_MAX_RETRY_COUNT",
"Set maximum retry count",
ENGINE_CMD_FLAG_NUMERIC},