summaryrefslogtreecommitdiff
path: root/sys/opencrypto/crypto.c
blob: 8b9a33f2480c5e98be9963194a52daf8c5f28fdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
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
/*	$NetBSD: crypto.c,v 1.130 2022/05/22 11:40:54 riastradh Exp $ */
/*	$FreeBSD: src/sys/opencrypto/crypto.c,v 1.4.2.5 2003/02/26 00:14:05 sam Exp $	*/
/*	$OpenBSD: crypto.c,v 1.41 2002/07/17 23:52:38 art Exp $	*/

/*-
 * Copyright (c) 2008 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Coyote Point Systems, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
 */

/*
 * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
 *
 * This code was written by Angelos D. Keromytis in Athens, Greece, in
 * February 2000. Network Security Technologies Inc. (NSTI) kindly
 * supported the development of this code.
 *
 * Copyright (c) 2000, 2001 Angelos D. Keromytis
 *
 * Permission to use, copy, and modify this software with or without fee
 * is hereby granted, provided that this entire notice is included in
 * all source code copies of any software which is or includes a copy or
 * modification of this software.
 *
 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
 * PURPOSE.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: crypto.c,v 1.130 2022/05/22 11:40:54 riastradh Exp $");

#include <sys/param.h>
#include <sys/reboot.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/pool.h>
#include <sys/kthread.h>
#include <sys/once.h>
#include <sys/sysctl.h>
#include <sys/intr.h>
#include <sys/errno.h>
#include <sys/module.h>
#include <sys/xcall.h>
#include <sys/device.h>
#include <sys/cpu.h>
#include <sys/percpu.h>
#include <sys/kmem.h>

#if defined(_KERNEL_OPT)
#include "opt_ocf.h"
#endif

#include <opencrypto/cryptodev.h>
#include <opencrypto/xform.h>			/* XXX for M_XDATA */

/*
 * Crypto drivers register themselves by allocating a slot in the
 * crypto_drivers table with crypto_get_driverid() and then registering
 * each algorithm they support with crypto_register() and crypto_kregister().
 */
/* Don't directly access crypto_drivers[i], use crypto_checkdriver(i). */
static struct {
	kmutex_t mtx;
	int num;
	struct cryptocap *list;
} crypto_drv __cacheline_aligned;
#define crypto_drv_mtx		(crypto_drv.mtx)
#define crypto_drivers_num	(crypto_drv.num)
#define crypto_drivers		(crypto_drv.list)

static	void *crypto_q_si;
static	void *crypto_ret_si;

/*
 * There are two queues for crypto requests; one for symmetric (e.g.
 * cipher) operations and one for asymmetric (e.g. MOD) operations.
 * See below for how synchronization is handled.
 */
TAILQ_HEAD(crypto_crp_q, cryptop);
TAILQ_HEAD(crypto_crp_kq, cryptkop);
struct crypto_crp_qs {
	struct crypto_crp_q *crp_q;
	struct crypto_crp_kq *crp_kq;
};
static percpu_t *crypto_crp_qs_percpu;

static inline struct crypto_crp_qs *
crypto_get_crp_qs(int *s)
{

	KASSERT(s != NULL);

	*s = splsoftnet();
	return percpu_getref(crypto_crp_qs_percpu);
}

static inline void
crypto_put_crp_qs(int *s)
{

	KASSERT(s != NULL);

	percpu_putref(crypto_crp_qs_percpu);
	splx(*s);
}

static void
crypto_crp_q_is_busy_pc(void *p, void *arg, struct cpu_info *ci __unused)
{
	struct crypto_crp_qs *qs_pc = p;
	bool *isempty = arg;

	if (!TAILQ_EMPTY(qs_pc->crp_q) || !TAILQ_EMPTY(qs_pc->crp_kq))
		*isempty = true;
}

static void
crypto_crp_qs_init_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
{
	struct crypto_crp_qs *qs = p;

	qs->crp_q = kmem_alloc(sizeof(struct crypto_crp_q), KM_SLEEP);
	qs->crp_kq = kmem_alloc(sizeof(struct crypto_crp_kq), KM_SLEEP);

	TAILQ_INIT(qs->crp_q);
	TAILQ_INIT(qs->crp_kq);
}

/*
 * There are two queues for processing completed crypto requests; one
 * for the symmetric and one for the asymmetric ops.  We only need one
 * but have two to avoid type futzing (cryptop vs. cryptkop).  See below
 * for how synchronization is handled.
 */
TAILQ_HEAD(crypto_crp_ret_q, cryptop);
TAILQ_HEAD(crypto_crp_ret_kq, cryptkop);
struct crypto_crp_ret_qs {
	kmutex_t crp_ret_q_mtx;
	bool crp_ret_q_exit_flag;

	struct crypto_crp_ret_q crp_ret_q;
	int crp_ret_q_len;
	int crp_ret_q_maxlen; /* queue length limit. <=0 means unlimited. */
	int crp_ret_q_drops;

	struct crypto_crp_ret_kq crp_ret_kq;
	int crp_ret_kq_len;
	int crp_ret_kq_maxlen; /* queue length limit. <=0 means unlimited. */
	int crp_ret_kq_drops;
};
struct crypto_crp_ret_qs **crypto_crp_ret_qs_list;


static inline struct crypto_crp_ret_qs *
crypto_get_crp_ret_qs(struct cpu_info *ci)
{
	u_int cpuid;
	struct crypto_crp_ret_qs *qs;

	KASSERT(ci != NULL);

	cpuid = cpu_index(ci);
	qs = crypto_crp_ret_qs_list[cpuid];
	mutex_enter(&qs->crp_ret_q_mtx);
	return qs;
}

static inline void
crypto_put_crp_ret_qs(struct cpu_info *ci)
{
	u_int cpuid;
	struct crypto_crp_ret_qs *qs;

	KASSERT(ci != NULL);

	cpuid = cpu_index(ci);
	qs = crypto_crp_ret_qs_list[cpuid];
	mutex_exit(&qs->crp_ret_q_mtx);
}

#ifndef CRYPTO_RET_Q_MAXLEN
#define CRYPTO_RET_Q_MAXLEN 0
#endif
#ifndef CRYPTO_RET_KQ_MAXLEN
#define CRYPTO_RET_KQ_MAXLEN 0
#endif

static int
sysctl_opencrypto_q_len(SYSCTLFN_ARGS)
{
	int error, len = 0;
	struct sysctlnode node = *rnode;

	for (int i = 0; i < ncpu; i++) {
		struct crypto_crp_ret_qs *qs;
		struct cpu_info *ci = cpu_lookup(i);

		qs = crypto_get_crp_ret_qs(ci);
		len += qs->crp_ret_q_len;
		crypto_put_crp_ret_qs(ci);
	}

	node.sysctl_data = &len;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return error;

	return 0;
}

static int
sysctl_opencrypto_q_drops(SYSCTLFN_ARGS)
{
	int error, drops = 0;
	struct sysctlnode node = *rnode;

	for (int i = 0; i < ncpu; i++) {
		struct crypto_crp_ret_qs *qs;
		struct cpu_info *ci = cpu_lookup(i);

		qs = crypto_get_crp_ret_qs(ci);
		drops += qs->crp_ret_q_drops;
		crypto_put_crp_ret_qs(ci);
	}

	node.sysctl_data = &drops;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return error;

	return 0;
}

static int
sysctl_opencrypto_q_maxlen(SYSCTLFN_ARGS)
{
	int error, maxlen;
	struct crypto_crp_ret_qs *qs;
	struct sysctlnode node = *rnode;

	/* each crp_ret_kq_maxlen is the same. */
	qs = crypto_get_crp_ret_qs(curcpu());
	maxlen = qs->crp_ret_q_maxlen;
	crypto_put_crp_ret_qs(curcpu());

	node.sysctl_data = &maxlen;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return error;

	for (int i = 0; i < ncpu; i++) {
		struct cpu_info *ci = cpu_lookup(i);

		qs = crypto_get_crp_ret_qs(ci);
		qs->crp_ret_q_maxlen = maxlen;
		crypto_put_crp_ret_qs(ci);
	}

	return 0;
}

static int
sysctl_opencrypto_kq_len(SYSCTLFN_ARGS)
{
	int error, len = 0;
	struct sysctlnode node = *rnode;

	for (int i = 0; i < ncpu; i++) {
		struct crypto_crp_ret_qs *qs;
		struct cpu_info *ci = cpu_lookup(i);

		qs = crypto_get_crp_ret_qs(ci);
		len += qs->crp_ret_kq_len;
		crypto_put_crp_ret_qs(ci);
	}

	node.sysctl_data = &len;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return error;

	return 0;
}

static int
sysctl_opencrypto_kq_drops(SYSCTLFN_ARGS)
{
	int error, drops = 0;
	struct sysctlnode node = *rnode;

	for (int i = 0; i < ncpu; i++) {
		struct crypto_crp_ret_qs *qs;
		struct cpu_info *ci = cpu_lookup(i);

		qs = crypto_get_crp_ret_qs(ci);
		drops += qs->crp_ret_kq_drops;
		crypto_put_crp_ret_qs(ci);
	}

	node.sysctl_data = &drops;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return error;

	return 0;
}

static int
sysctl_opencrypto_kq_maxlen(SYSCTLFN_ARGS)
{
	int error, maxlen;
	struct crypto_crp_ret_qs *qs;
	struct sysctlnode node = *rnode;

	/* each crp_ret_kq_maxlen is the same. */
	qs = crypto_get_crp_ret_qs(curcpu());
	maxlen = qs->crp_ret_kq_maxlen;
	crypto_put_crp_ret_qs(curcpu());

	node.sysctl_data = &maxlen;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return error;

	for (int i = 0; i < ncpu; i++) {
		struct cpu_info *ci = cpu_lookup(i);

		qs = crypto_get_crp_ret_qs(ci);
		qs->crp_ret_kq_maxlen = maxlen;
		crypto_put_crp_ret_qs(ci);
	}

	return 0;
}

/*
 * Crypto op and descriptor data structures are allocated
 * from separate private zones(FreeBSD)/pools(netBSD/OpenBSD) .
 */
static pool_cache_t cryptop_cache;
static pool_cache_t cryptodesc_cache;
static pool_cache_t cryptkop_cache;

int	crypto_usercrypto = 1;		/* userland may open /dev/crypto */
int	crypto_userasymcrypto = 1;	/* userland may do asym crypto reqs */
/*
 * cryptodevallowsoft is (intended to be) sysctl'able, controlling
 * access to hardware versus software transforms as below:
 *
 * crypto_devallowsoft < 0:  Force userlevel requests to use software
 *                              transforms, always
 * crypto_devallowsoft = 0:  Use hardware if present, grant userlevel
 *                              requests for non-accelerated transforms
 *                              (handling the latter in software)
 * crypto_devallowsoft > 0:  Allow user requests only for transforms which
 *                               are hardware-accelerated.
 */
int	crypto_devallowsoft = 1;	/* only use hardware crypto */

static void
sysctl_opencrypto_setup(struct sysctllog **clog)
{
	const struct sysctlnode *ocnode;
	const struct sysctlnode *retqnode, *retkqnode;

	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
		       CTLTYPE_INT, "usercrypto",
		       SYSCTL_DESCR("Enable/disable user-mode access to "
			   "crypto support"),
		       NULL, 0, &crypto_usercrypto, 0,
		       CTL_KERN, CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
		       CTLTYPE_INT, "userasymcrypto",
		       SYSCTL_DESCR("Enable/disable user-mode access to "
			   "asymmetric crypto support"),
		       NULL, 0, &crypto_userasymcrypto, 0,
		       CTL_KERN, CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
		       CTLTYPE_INT, "cryptodevallowsoft",
		       SYSCTL_DESCR("Enable/disable use of software "
			   "asymmetric crypto support"),
		       NULL, 0, &crypto_devallowsoft, 0,
		       CTL_KERN, CTL_CREATE, CTL_EOL);

	sysctl_createv(clog, 0, NULL, &ocnode,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_NODE, "opencrypto",
		       SYSCTL_DESCR("opencrypto related entries"),
		       NULL, 0, NULL, 0,
		       CTL_CREATE, CTL_EOL);

	sysctl_createv(clog, 0, &ocnode, &retqnode,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_NODE, "crypto_ret_q",
		       SYSCTL_DESCR("crypto_ret_q related entries"),
		       NULL, 0, NULL, 0,
		       CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, &retqnode, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
		       CTLTYPE_INT, "len",
		       SYSCTL_DESCR("Current queue length"),
		       sysctl_opencrypto_q_len, 0,
		       NULL, 0,
		       CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, &retqnode, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
		       CTLTYPE_INT, "drops",
		       SYSCTL_DESCR("Crypto requests dropped due to full ret queue"),
		       sysctl_opencrypto_q_drops, 0,
		       NULL, 0,
		       CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, &retqnode, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
		       CTLTYPE_INT, "maxlen",
		       SYSCTL_DESCR("Maximum allowed queue length"),
		       sysctl_opencrypto_q_maxlen, 0,
		       NULL, 0,
		       CTL_CREATE, CTL_EOL);


	sysctl_createv(clog, 0, &ocnode, &retkqnode,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_NODE, "crypto_ret_kq",
		       SYSCTL_DESCR("crypto_ret_kq related entries"),
		       NULL, 0, NULL, 0,
		       CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, &retkqnode, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
		       CTLTYPE_INT, "len",
		       SYSCTL_DESCR("Current queue length"),
		       sysctl_opencrypto_kq_len, 0,
		       NULL, 0,
		       CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, &retkqnode, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
		       CTLTYPE_INT, "drops",
		       SYSCTL_DESCR("Crypto requests dropped due to full ret queue"),
		       sysctl_opencrypto_kq_drops, 0,
		       NULL, 0,
		       CTL_CREATE, CTL_EOL);
	sysctl_createv(clog, 0, &retkqnode, NULL,
		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
		       CTLTYPE_INT, "maxlen",
		       SYSCTL_DESCR("Maximum allowed queue length"),
		       sysctl_opencrypto_kq_maxlen, 0,
		       NULL, 0,
		       CTL_CREATE, CTL_EOL);
}

/*
 * Synchronization: read carefully, this is non-trivial.
 *
 * Crypto requests are submitted via crypto_dispatch.  Typically
 * these come in from network protocols at spl0 (output path) or
 * spl[,soft]net (input path).
 *
 * Requests are typically passed on the driver directly, but they
 * may also be queued for processing by a software interrupt thread,
 * cryptointr, that runs at splsoftcrypto.  This thread dispatches
 * the requests to crypto drivers (h/w or s/w) who call crypto_done
 * when a request is complete.  Hardware crypto drivers are assumed
 * to register their IRQ's as network devices so their interrupt handlers
 * and subsequent "done callbacks" happen at spl[imp,net].
 *
 * Completed crypto ops are queued for a separate kernel thread that
 * handles the callbacks at spl0.  This decoupling insures the crypto
 * driver interrupt service routine is not delayed while the callback
 * takes place and that callbacks are delivered after a context switch
 * (as opposed to a software interrupt that clients must block).
 *
 * This scheme is not intended for SMP machines.
 */
static	void cryptointr(void *);	/* swi thread to dispatch ops */
static	void cryptoret_softint(void *);	/* kernel thread for callbacks*/
static	int crypto_destroy(bool);
static	int crypto_invoke(struct cryptop *crp, int hint);
static	int crypto_kinvoke(struct cryptkop *krp, int hint);

static struct cryptocap *crypto_checkdriver_lock(u_int32_t);
static struct cryptocap *crypto_checkdriver_uninit(u_int32_t);
static struct cryptocap *crypto_checkdriver(u_int32_t);
static void crypto_driver_lock(struct cryptocap *);
static void crypto_driver_unlock(struct cryptocap *);
static void crypto_driver_clear(struct cryptocap *);

static int crypto_init_finalize(device_t);

static struct cryptostats cryptostats;
#ifdef CRYPTO_TIMING
static	int crypto_timing = 0;
#endif

static struct sysctllog *sysctl_opencrypto_clog;

static void
crypto_crp_ret_qs_init(void)
{
	int i;

	crypto_crp_ret_qs_list = kmem_alloc(sizeof(struct crypto_crp_ret_qs *) * ncpu,
	    KM_SLEEP);

	for (i = 0; i < ncpu; i++) {
		struct crypto_crp_ret_qs *qs;

		qs = kmem_alloc(sizeof(struct crypto_crp_ret_qs), KM_SLEEP);
		mutex_init(&qs->crp_ret_q_mtx, MUTEX_DEFAULT, IPL_NET);
		qs->crp_ret_q_exit_flag = false;

		TAILQ_INIT(&qs->crp_ret_q);
		qs->crp_ret_q_len = 0;
		qs->crp_ret_q_maxlen = CRYPTO_RET_Q_MAXLEN;
		qs->crp_ret_q_drops = 0;

		TAILQ_INIT(&qs->crp_ret_kq);
		qs->crp_ret_kq_len = 0;
		qs->crp_ret_kq_maxlen = CRYPTO_RET_KQ_MAXLEN;
		qs->crp_ret_kq_drops = 0;

		crypto_crp_ret_qs_list[i] = qs;
	}
}

static int
crypto_init0(void)
{

	mutex_init(&crypto_drv_mtx, MUTEX_DEFAULT, IPL_NONE);
	cryptop_cache = pool_cache_init(sizeof(struct cryptop),
	    coherency_unit, 0, 0, "cryptop", NULL, IPL_NET, NULL, NULL, NULL);
	cryptodesc_cache = pool_cache_init(sizeof(struct cryptodesc),
	    coherency_unit, 0, 0, "cryptdesc", NULL, IPL_NET, NULL, NULL, NULL);
	cryptkop_cache = pool_cache_init(sizeof(struct cryptkop),
	    coherency_unit, 0, 0, "cryptkop", NULL, IPL_NET, NULL, NULL, NULL);

	crypto_crp_qs_percpu = percpu_create(sizeof(struct crypto_crp_qs),
	    crypto_crp_qs_init_pc, /*XXX*/NULL, NULL);

	crypto_crp_ret_qs_init();

	crypto_drivers = kmem_zalloc(CRYPTO_DRIVERS_INITIAL *
	    sizeof(struct cryptocap), KM_SLEEP);
	crypto_drivers_num = CRYPTO_DRIVERS_INITIAL;

	crypto_q_si = softint_establish(SOFTINT_NET|SOFTINT_MPSAFE, cryptointr, NULL);
	if (crypto_q_si == NULL) {
		printf("crypto_init: cannot establish request queue handler\n");
		return crypto_destroy(false);
	}

	/*
	 * Some encryption devices (such as mvcesa) are attached before
	 * ipi_sysinit(). That causes an assertion in ipi_register() as
	 * crypto_ret_si softint uses SOFTINT_RCPU.
	 */
	if (config_finalize_register(NULL, crypto_init_finalize) != 0) {
		printf("crypto_init: cannot register crypto_init_finalize\n");
		return crypto_destroy(false);
	}

	sysctl_opencrypto_setup(&sysctl_opencrypto_clog);

	return 0;
}

static int
crypto_init_finalize(device_t self __unused)
{

	crypto_ret_si = softint_establish(SOFTINT_NET|SOFTINT_MPSAFE|SOFTINT_RCPU,
	    &cryptoret_softint, NULL);
	KASSERT(crypto_ret_si != NULL);

	return 0;
}

int
crypto_init(void)
{
	static ONCE_DECL(crypto_init_once);

	return RUN_ONCE(&crypto_init_once, crypto_init0);
}

static int
crypto_destroy(bool exit_kthread)
{
	int i;

	if (exit_kthread) {
		struct cryptocap *cap = NULL;
		bool is_busy = false;

		/* if we have any in-progress requests, don't unload */
		percpu_foreach(crypto_crp_qs_percpu, crypto_crp_q_is_busy_pc,
				   &is_busy);
		if (is_busy)
			return EBUSY;
		/* FIXME:
		 * prohibit enqueue to crp_q and crp_kq after here.
		 */

		mutex_enter(&crypto_drv_mtx);
		for (i = 0; i < crypto_drivers_num; i++) {
			cap = crypto_checkdriver(i);
			if (cap == NULL)
				continue;
			if (cap->cc_sessions != 0) {
				mutex_exit(&crypto_drv_mtx);
				return EBUSY;
			}
		}
		mutex_exit(&crypto_drv_mtx);
		/* FIXME:
		 * prohibit touch crypto_drivers[] and each element after here.
		 */

		/* Ensure cryptoret_softint() is never scheduled again.  */
		for (i = 0; i < ncpu; i++) {
			struct crypto_crp_ret_qs *qs;
			struct cpu_info *ci = cpu_lookup(i);

			qs = crypto_get_crp_ret_qs(ci);
			qs->crp_ret_q_exit_flag = true;
			crypto_put_crp_ret_qs(ci);
		}
	}

	if (sysctl_opencrypto_clog != NULL)
		sysctl_teardown(&sysctl_opencrypto_clog);

	if (crypto_ret_si != NULL)
		softint_disestablish(crypto_ret_si);

	if (crypto_q_si != NULL)
		softint_disestablish(crypto_q_si);

	mutex_enter(&crypto_drv_mtx);
	if (crypto_drivers != NULL)
		kmem_free(crypto_drivers,
		    crypto_drivers_num * sizeof(struct cryptocap));
	mutex_exit(&crypto_drv_mtx);

	percpu_free(crypto_crp_qs_percpu, sizeof(struct crypto_crp_qs));

	pool_cache_destroy(cryptop_cache);
	pool_cache_destroy(cryptodesc_cache);
	pool_cache_destroy(cryptkop_cache);

	mutex_destroy(&crypto_drv_mtx);

	return 0;
}

static bool
crypto_driver_suitable(struct cryptocap *cap, struct cryptoini *cri)
{
	struct cryptoini *cr;

	for (cr = cri; cr; cr = cr->cri_next)
		if (cap->cc_alg[cr->cri_alg] == 0) {
			DPRINTF("alg %d not supported\n", cr->cri_alg);
			return false;
		}

	return true;
}

#define CRYPTO_ACCEPT_HARDWARE 0x1
#define CRYPTO_ACCEPT_SOFTWARE 0x2
/*
 * The algorithm we use here is pretty stupid; just use the
 * first driver that supports all the algorithms we need.
 * If there are multiple drivers we choose the driver with
 * the fewest active sessions. We prefer hardware-backed
 * drivers to software ones.
 *
 * XXX We need more smarts here (in real life too, but that's
 * XXX another story altogether).
 */
static struct cryptocap *
crypto_select_driver_lock(struct cryptoini *cri, int hard)
{
	u_int32_t hid;
	int accept;
	struct cryptocap *cap, *best;
	int error = 0;

	best = NULL;
	/*
	 * hard == 0 can use both hardware and software drivers.
	 * We use hardware drivers prior to software drivers, so search
	 * hardware drivers at first time.
	 */
	if (hard >= 0)
		accept = CRYPTO_ACCEPT_HARDWARE;
	else
		accept = CRYPTO_ACCEPT_SOFTWARE;
again:
	for (hid = 0; hid < crypto_drivers_num; hid++) {
		cap = crypto_checkdriver(hid);
		if (cap == NULL)
			continue;

		crypto_driver_lock(cap);

		/*
		 * If it's not initialized or has remaining sessions
		 * referencing it, skip.
		 */
		if (cap->cc_newsession == NULL ||
		    (cap->cc_flags & CRYPTOCAP_F_CLEANUP)) {
			crypto_driver_unlock(cap);
			continue;
		}

		/* Hardware required -- ignore software drivers. */
		if ((accept & CRYPTO_ACCEPT_SOFTWARE) == 0
		    && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE)) {
			crypto_driver_unlock(cap);
			continue;
		}
		/* Software required -- ignore hardware drivers. */
		if ((accept & CRYPTO_ACCEPT_HARDWARE) == 0
		    && (cap->cc_flags & CRYPTOCAP_F_SOFTWARE) == 0) {
			crypto_driver_unlock(cap);
			continue;
		}

		/* See if all the algorithms are supported. */
		if (crypto_driver_suitable(cap, cri)) {
			if (best == NULL) {
				/* keep holding crypto_driver_lock(cap) */
				best = cap;
				continue;
			} else if (cap->cc_sessions < best->cc_sessions) {
				crypto_driver_unlock(best);
				/* keep holding crypto_driver_lock(cap) */
				best = cap;
				continue;
			}
		}

		crypto_driver_unlock(cap);
	}
	if (best == NULL && hard == 0
	    && (accept & CRYPTO_ACCEPT_SOFTWARE) == 0) {
		accept = CRYPTO_ACCEPT_SOFTWARE;
		goto again;
	}

	if (best == NULL && hard == 0 && error == 0) {
		mutex_exit(&crypto_drv_mtx);
		error = module_autoload("swcrypto", MODULE_CLASS_DRIVER);
		mutex_enter(&crypto_drv_mtx);
		if (error == 0) {
			error = EINVAL;
			goto again;
		}
	}

	return best;
}

/*
 * Create a new session.
 */
int
crypto_newsession(u_int64_t *sid, struct cryptoini *cri, int hard)
{
	struct cryptocap *cap;
	int err = EINVAL;

	/*
	 * On failure, leave *sid initialized to a sentinel value that
	 * crypto_freesession will ignore.  This is the same as what
	 * you get from zero-initialized memory -- some callers (I'm
	 * looking at you, netipsec!) have paths that lead from
	 * zero-initialized memory into crypto_freesession without any
	 * crypto_newsession.
	 */
	*sid = 0;

	mutex_enter(&crypto_drv_mtx);

	cap = crypto_select_driver_lock(cri, hard);
	if (cap != NULL) {
		u_int32_t hid, lid;

		hid = cap - crypto_drivers;
		KASSERT(hid < 0xffffff);
		/*
		 * Can't do everything in one session.
		 *
		 * XXX Fix this. We need to inject a "virtual" session layer right
		 * XXX about here.
		 */

		/* Call the driver initialization routine. */
		lid = hid;		/* Pass the driver ID. */
		crypto_driver_unlock(cap);
		err = cap->cc_newsession(cap->cc_arg, &lid, cri);
		crypto_driver_lock(cap);
		if (err == 0) {
			(*sid) = hid + 1;
			(*sid) <<= 32;
			(*sid) |= (lid & 0xffffffff);
			KASSERT(*sid != 0);
			cap->cc_sessions++;
		} else {
			DPRINTF("crypto_drivers[%d].cc_newsession() failed. error=%d\n",
			    hid, err);
		}
		crypto_driver_unlock(cap);
	}

	mutex_exit(&crypto_drv_mtx);

	return err;
}

/*
 * Delete an existing session (or a reserved session on an unregistered
 * driver).
 */
void
crypto_freesession(u_int64_t sid)
{
	struct cryptocap *cap;

	/*
	 * crypto_newsession never returns 0 as a sid (by virtue of
	 * never returning 0 as a hid, which is part of the sid).
	 * However, some callers assume that freeing zero is safe.
	 * Previously this relied on all drivers to agree that freeing
	 * invalid sids is a no-op, but that's a terrible API contract
	 * that we're getting rid of.
	 */
	if (sid == 0)
		return;

	/* Determine two IDs. */
	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(sid));
	KASSERTMSG(cap != NULL, "sid=%"PRIx64, sid);

	KASSERT(cap->cc_sessions > 0);
	cap->cc_sessions--;

	/* Call the driver cleanup routine, if available. */
	if (cap->cc_freesession)
		cap->cc_freesession(cap->cc_arg, sid);

	/*
	 * If this was the last session of a driver marked as invalid,
	 * make the entry available for reuse.
	 */
	if ((cap->cc_flags & CRYPTOCAP_F_CLEANUP) && cap->cc_sessions == 0)
		crypto_driver_clear(cap);

	crypto_driver_unlock(cap);
}

static bool
crypto_checkdriver_initialized(const struct cryptocap *cap)
{

	return cap->cc_process != NULL ||
	    (cap->cc_flags & CRYPTOCAP_F_CLEANUP) != 0 ||
	    cap->cc_sessions != 0;
}

/*
 * Return an unused driver id.  Used by drivers prior to registering
 * support for the algorithms they handle.
 */
int32_t
crypto_get_driverid(u_int32_t flags)
{
	struct cryptocap *newdrv;
	struct cryptocap *cap = NULL;
	int i;

	(void)crypto_init();		/* XXX oh, this is foul! */

	mutex_enter(&crypto_drv_mtx);
	for (i = 0; i < crypto_drivers_num; i++) {
		cap = crypto_checkdriver_uninit(i);
		if (cap == NULL || crypto_checkdriver_initialized(cap))
			continue;
		break;
	}

	/* Out of entries, allocate some more. */
	if (cap == NULL) {
		/* Be careful about wrap-around. */
		if (2 * crypto_drivers_num <= crypto_drivers_num) {
			mutex_exit(&crypto_drv_mtx);
			printf("crypto: driver count wraparound!\n");
			return -1;
		}

		newdrv = kmem_zalloc(2 * crypto_drivers_num *
		    sizeof(struct cryptocap), KM_SLEEP);
		memcpy(newdrv, crypto_drivers,
		    crypto_drivers_num * sizeof(struct cryptocap));
		kmem_free(crypto_drivers,
		    crypto_drivers_num * sizeof(struct cryptocap));

		crypto_drivers_num *= 2;
		crypto_drivers = newdrv;

		cap = crypto_checkdriver_uninit(i);
		KASSERT(cap != NULL);
	}

	/* NB: state is zero'd on free */
	cap->cc_sessions = 1;	/* Mark */
	cap->cc_flags = flags;
	mutex_init(&cap->cc_lock, MUTEX_DEFAULT, IPL_NET);

	if (bootverbose)
		printf("crypto: assign driver %u, flags %u\n", i, flags);

	mutex_exit(&crypto_drv_mtx);

	return i;
}

static struct cryptocap *
crypto_checkdriver_lock(u_int32_t hid)
{
	struct cryptocap *cap;

	KASSERT(crypto_drivers != NULL);

	if (hid >= crypto_drivers_num)
		return NULL;

	cap = &crypto_drivers[hid];
	mutex_enter(&cap->cc_lock);
	return cap;
}

/*
 * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
 * situations
 *     - crypto_drivers[] may not be allocated
 *     - crypto_drivers[hid] may not be initialized
 */
static struct cryptocap *
crypto_checkdriver_uninit(u_int32_t hid)
{

	KASSERT(mutex_owned(&crypto_drv_mtx));

	if (crypto_drivers == NULL)
		return NULL;

	return (hid >= crypto_drivers_num ? NULL : &crypto_drivers[hid]);
}

/*
 * Use crypto_checkdriver_uninit() instead of crypto_checkdriver() below two
 * situations
 *     - crypto_drivers[] may not be allocated
 *     - crypto_drivers[hid] may not be initialized
 */
static struct cryptocap *
crypto_checkdriver(u_int32_t hid)
{

	KASSERT(mutex_owned(&crypto_drv_mtx));

	if (crypto_drivers == NULL || hid >= crypto_drivers_num)
		return NULL;

	struct cryptocap *cap = &crypto_drivers[hid];
	return crypto_checkdriver_initialized(cap) ? cap : NULL;
}

static inline void
crypto_driver_lock(struct cryptocap *cap)
{

	KASSERT(cap != NULL);

	mutex_enter(&cap->cc_lock);
}

static inline void
crypto_driver_unlock(struct cryptocap *cap)
{

	KASSERT(cap != NULL);

	mutex_exit(&cap->cc_lock);
}

static void
crypto_driver_clear(struct cryptocap *cap)
{

	if (cap == NULL)
		return;

	KASSERT(mutex_owned(&cap->cc_lock));

	cap->cc_sessions = 0;
	memset(&cap->cc_max_op_len, 0, sizeof(cap->cc_max_op_len));
	memset(&cap->cc_alg, 0, sizeof(cap->cc_alg));
	memset(&cap->cc_kalg, 0, sizeof(cap->cc_kalg));
	cap->cc_flags = 0;
	cap->cc_qblocked = 0;
	cap->cc_kqblocked = 0;

	cap->cc_arg = NULL;
	cap->cc_newsession = NULL;
	cap->cc_process = NULL;
	cap->cc_freesession = NULL;
	cap->cc_kprocess = NULL;
}

/*
 * Register support for a key-related algorithm.  This routine
 * is called once for each algorithm supported a driver.
 */
int
crypto_kregister(u_int32_t driverid, int kalg, u_int32_t flags,
    int (*kprocess)(void *, struct cryptkop *, int),
    void *karg)
{
	struct cryptocap *cap;
	int err;

	mutex_enter(&crypto_drv_mtx);

	cap = crypto_checkdriver_lock(driverid);
	if (cap != NULL &&
	    (CRK_ALGORITHM_MIN <= kalg && kalg <= CRK_ALGORITHM_MAX)) {
		/*
		 * XXX Do some performance testing to determine placing.
		 * XXX We probably need an auxiliary data structure that
		 * XXX describes relative performances.
		 */

		cap->cc_kalg[kalg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
		if (bootverbose) {
			printf("crypto: driver %u registers key alg %u "
			       " flags %u\n",
				driverid,
				kalg,
				flags
			);
		}

		if (cap->cc_kprocess == NULL) {
			cap->cc_karg = karg;
			cap->cc_kprocess = kprocess;
		}
		err = 0;
	} else
		err = EINVAL;

	mutex_exit(&crypto_drv_mtx);
	return err;
}

/*
 * Register support for a non-key-related algorithm.  This routine
 * is called once for each such algorithm supported by a driver.
 */
int
crypto_register(u_int32_t driverid, int alg, u_int16_t maxoplen,
    u_int32_t flags,
    int (*newses)(void *, u_int32_t*, struct cryptoini*),
    void (*freeses)(void *, u_int64_t),
    int (*process)(void *, struct cryptop *, int),
    void *arg)
{
	struct cryptocap *cap;
	int err;

	cap = crypto_checkdriver_lock(driverid);
	if (cap == NULL)
		return EINVAL;

	/* NB: algorithms are in the range [1..max] */
	if (CRYPTO_ALGORITHM_MIN <= alg && alg <= CRYPTO_ALGORITHM_MAX) {
		/*
		 * XXX Do some performance testing to determine placing.
		 * XXX We probably need an auxiliary data structure that
		 * XXX describes relative performances.
		 */

		cap->cc_alg[alg] = flags | CRYPTO_ALG_FLAG_SUPPORTED;
		cap->cc_max_op_len[alg] = maxoplen;
		if (bootverbose) {
			printf("crypto: driver %u registers alg %u "
				"flags %u maxoplen %u\n",
				driverid,
				alg,
				flags,
				maxoplen
			);
		}

		if (cap->cc_process == NULL) {
			cap->cc_arg = arg;
			cap->cc_newsession = newses;
			cap->cc_process = process;
			cap->cc_freesession = freeses;
			cap->cc_sessions = 0;		/* Unmark */
		}
		err = 0;
	} else
		err = EINVAL;

	crypto_driver_unlock(cap);

	return err;
}

static int
crypto_unregister_locked(struct cryptocap *cap, int alg, bool all)
{
	int i;
	u_int32_t ses;
	bool lastalg = true;

	KASSERT(cap != NULL);
	KASSERT(mutex_owned(&cap->cc_lock));

	if (alg < CRYPTO_ALGORITHM_MIN || CRYPTO_ALGORITHM_MAX < alg)
		return EINVAL;

	if (!all && cap->cc_alg[alg] == 0)
		return EINVAL;

	cap->cc_alg[alg] = 0;
	cap->cc_max_op_len[alg] = 0;

	if (all) {
		if (alg != CRYPTO_ALGORITHM_MAX)
			lastalg = false;
	} else {
		/* Was this the last algorithm ? */
		for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++)
			if (cap->cc_alg[i] != 0) {
				lastalg = false;
				break;
			}
	}
	if (lastalg) {
		ses = cap->cc_sessions;
		crypto_driver_clear(cap);
		if (ses != 0) {
			/*
			 * If there are pending sessions, just mark as invalid.
			 */
			cap->cc_flags |= CRYPTOCAP_F_CLEANUP;
			cap->cc_sessions = ses;
		}
	}

	return 0;
}

/*
 * Unregister a crypto driver. If there are pending sessions using it,
 * leave enough information around so that subsequent calls using those
 * sessions will correctly detect the driver has been unregistered and
 * reroute requests.
 */
int
crypto_unregister(u_int32_t driverid, int alg)
{
	int err;
	struct cryptocap *cap;

	cap = crypto_checkdriver_lock(driverid);
	err = crypto_unregister_locked(cap, alg, false);
	crypto_driver_unlock(cap);

	return err;
}

/*
 * Unregister all algorithms associated with a crypto driver.
 * If there are pending sessions using it, leave enough information
 * around so that subsequent calls using those sessions will
 * correctly detect the driver has been unregistered and reroute
 * requests.
 */
int
crypto_unregister_all(u_int32_t driverid)
{
	int err, i;
	struct cryptocap *cap;

	cap = crypto_checkdriver_lock(driverid);
	for (i = CRYPTO_ALGORITHM_MIN; i <= CRYPTO_ALGORITHM_MAX; i++) {
		err = crypto_unregister_locked(cap, i, true);
		if (err)
			break;
	}
	crypto_driver_unlock(cap);

	return err;
}

/*
 * Clear blockage on a driver.  The what parameter indicates whether
 * the driver is now ready for cryptop's and/or cryptokop's.
 */
int
crypto_unblock(u_int32_t driverid, int what)
{
	struct cryptocap *cap;
	int needwakeup = 0;

	cap = crypto_checkdriver_lock(driverid);
	if (cap == NULL)
		return EINVAL;

	if (what & CRYPTO_SYMQ) {
		needwakeup |= cap->cc_qblocked;
		cap->cc_qblocked = 0;
	}
	if (what & CRYPTO_ASYMQ) {
		needwakeup |= cap->cc_kqblocked;
		cap->cc_kqblocked = 0;
	}
	crypto_driver_unlock(cap);
	if (needwakeup) {
		kpreempt_disable();
		softint_schedule(crypto_q_si);
		kpreempt_enable();
	}

	return 0;
}

/*
 * Dispatch a crypto request to a driver or queue
 * it, to be processed by the kernel thread.
 */
void
crypto_dispatch(struct cryptop *crp)
{
	int result, s;
	struct cryptocap *cap;
	struct crypto_crp_qs *crp_qs;
	struct crypto_crp_q *crp_q;

	KASSERT(crp != NULL);
	KASSERT(crp->crp_callback != NULL);
	KASSERT(crp->crp_desc != NULL);
	KASSERT(crp->crp_buf != NULL);
	KASSERT(!cpu_intr_p());

	DPRINTF("crp %p, alg %d\n", crp, crp->crp_desc->crd_alg);

	cryptostats.cs_ops++;

#ifdef CRYPTO_TIMING
	if (crypto_timing)
		nanouptime(&crp->crp_tstamp);
#endif

	if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
		int wasempty;
		/*
		 * Caller marked the request as ``ok to delay'';
		 * queue it for the swi thread.  This is desirable
		 * when the operation is low priority and/or suitable
		 * for batching.
		 *
		 * don't care list order in batch job.
		 */
		crp_qs = crypto_get_crp_qs(&s);
		crp_q = crp_qs->crp_q;
		wasempty  = TAILQ_EMPTY(crp_q);
		TAILQ_INSERT_TAIL(crp_q, crp, crp_next);
		crypto_put_crp_qs(&s);
		crp_q = NULL;
		if (wasempty) {
			kpreempt_disable();
			softint_schedule(crypto_q_si);
			kpreempt_enable();
		}
		return;
	}

	crp_qs = crypto_get_crp_qs(&s);
	crp_q = crp_qs->crp_q;
	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
	/*
	 * TODO:
	 * If we can ensure the driver has been valid until the driver is
	 * done crypto_unregister(), this migrate operation is not required.
	 */
	if (cap == NULL) {
		/*
		 * The driver must be detached, so this request will migrate
		 * to other drivers in cryptointr() later.
		 */
		TAILQ_INSERT_TAIL(crp_q, crp, crp_next);
		goto out;
	}

	if (cap->cc_qblocked != 0) {
		crypto_driver_unlock(cap);
		/*
		 * The driver is blocked, just queue the op until
		 * it unblocks and the swi thread gets kicked.
		 */
		TAILQ_INSERT_TAIL(crp_q, crp, crp_next);
		goto out;
	}

	/*
	 * Caller marked the request to be processed
	 * immediately; dispatch it directly to the
	 * driver unless the driver is currently blocked.
	 */
	crypto_driver_unlock(cap);
	result = crypto_invoke(crp, 0);
	KASSERTMSG(result == 0 || result == ERESTART, "result=%d", result);
	if (result == ERESTART) {
		/*
		 * The driver ran out of resources, mark the
		 * driver ``blocked'' for cryptop's and put
		 * the op on the queue.
		 */
		crypto_driver_lock(cap);
		cap->cc_qblocked = 1;
		crypto_driver_unlock(cap);
		TAILQ_INSERT_HEAD(crp_q, crp, crp_next);
		cryptostats.cs_blocks++;
	}

out:
	crypto_put_crp_qs(&s);
}

/*
 * Add an asymmetric crypto request to a queue,
 * to be processed by the kernel thread.
 */
void
crypto_kdispatch(struct cryptkop *krp)
{
	int result, s;
	struct cryptocap *cap;
	struct crypto_crp_qs *crp_qs;
	struct crypto_crp_kq *crp_kq;

	KASSERT(krp != NULL);
	KASSERT(krp->krp_callback != NULL);
	KASSERT(!cpu_intr_p());

	cryptostats.cs_kops++;

	crp_qs = crypto_get_crp_qs(&s);
	crp_kq = crp_qs->crp_kq;
	cap = crypto_checkdriver_lock(krp->krp_hid);
	/*
	 * TODO:
	 * If we can ensure the driver has been valid until the driver is
	 * done crypto_unregister(), this migrate operation is not required.
	 */
	if (cap == NULL) {
		TAILQ_INSERT_TAIL(crp_kq, krp, krp_next);
		goto out;
	}

	if (cap->cc_kqblocked != 0) {
		crypto_driver_unlock(cap);
		/*
		 * The driver is blocked, just queue the op until
		 * it unblocks and the swi thread gets kicked.
		 */
		TAILQ_INSERT_TAIL(crp_kq, krp, krp_next);
		goto out;
	}

	crypto_driver_unlock(cap);
	result = crypto_kinvoke(krp, 0);
	KASSERTMSG(result == 0 || result == ERESTART, "result=%d", result);
	if (result == ERESTART) {
		/*
		 * The driver ran out of resources, mark the
		 * driver ``blocked'' for cryptop's and put
		 * the op on the queue.
		 */
		crypto_driver_lock(cap);
		cap->cc_kqblocked = 1;
		crypto_driver_unlock(cap);
		TAILQ_INSERT_HEAD(crp_kq, krp, krp_next);
		cryptostats.cs_kblocks++;
	}

out:
	crypto_put_crp_qs(&s);
}

/*
 * Dispatch an asymmetric crypto request to the appropriate crypto devices.
 */
static int
crypto_kinvoke(struct cryptkop *krp, int hint)
{
	struct cryptocap *cap = NULL;
	u_int32_t hid;
	int error;

	KASSERT(krp != NULL);
	KASSERT(krp->krp_callback != NULL);
	KASSERT(!cpu_intr_p());

	mutex_enter(&crypto_drv_mtx);
	for (hid = 0; hid < crypto_drivers_num; hid++) {
		cap = crypto_checkdriver(hid);
		if (cap == NULL)
			continue;
		crypto_driver_lock(cap);
		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
		    crypto_devallowsoft == 0) {
			crypto_driver_unlock(cap);
			continue;
		}
		if (cap->cc_kprocess == NULL) {
			crypto_driver_unlock(cap);
			continue;
		}
		if ((cap->cc_kalg[krp->krp_op] &
			CRYPTO_ALG_FLAG_SUPPORTED) == 0) {
			crypto_driver_unlock(cap);
			continue;
		}
		break;
	}
	mutex_exit(&crypto_drv_mtx);
	if (cap != NULL) {
		int (*process)(void *, struct cryptkop *, int);
		void *arg;

		process = cap->cc_kprocess;
		arg = cap->cc_karg;
		krp->krp_hid = hid;
		krp->reqcpu = curcpu();
		crypto_driver_unlock(cap);
		error = (*process)(arg, krp, hint);
		KASSERTMSG(error == 0 || error == ERESTART, "error=%d",
		    error);
		return error;
	} else {
		krp->krp_status = ENODEV;
		crypto_kdone(krp);
		return 0;
	}
}

#ifdef CRYPTO_TIMING
static void
crypto_tstat(struct cryptotstat *ts, struct timespec *tv)
{
	struct timespec now, t;

	nanouptime(&now);
	t.tv_sec = now.tv_sec - tv->tv_sec;
	t.tv_nsec = now.tv_nsec - tv->tv_nsec;
	if (t.tv_nsec < 0) {
		t.tv_sec--;
		t.tv_nsec += 1000000000;
	}
	timespecadd(&ts->acc, &t, &t);
	if (timespeccmp(&t, &ts->min, <))
		ts->min = t;
	if (timespeccmp(&t, &ts->max, >))
		ts->max = t;
	ts->count++;

	*tv = now;
}
#endif

/*
 * Dispatch a crypto request to the appropriate crypto devices.
 */
static int
crypto_invoke(struct cryptop *crp, int hint)
{
	struct cryptocap *cap;
	int error;

	KASSERT(crp != NULL);
	KASSERT(crp->crp_callback != NULL);
	KASSERT(crp->crp_desc != NULL);
	KASSERT(!cpu_intr_p());

#ifdef CRYPTO_TIMING
	if (crypto_timing)
		crypto_tstat(&cryptostats.cs_invoke, &crp->crp_tstamp);
#endif

	cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(crp->crp_sid));
	if (cap != NULL && (cap->cc_flags & CRYPTOCAP_F_CLEANUP) == 0) {
		int (*process)(void *, struct cryptop *, int);
		void *arg;

		process = cap->cc_process;
		arg = cap->cc_arg;
		crp->reqcpu = curcpu();

		/*
		 * Invoke the driver to process the request.
		 */
		DPRINTF("calling process for %p\n", crp);
		crypto_driver_unlock(cap);
		error = (*process)(arg, crp, hint);
		KASSERTMSG(error == 0 || error == ERESTART, "error=%d",
		    error);
		return error;
	} else {
		if (cap != NULL) {
			crypto_driver_unlock(cap);
			crypto_freesession(crp->crp_sid);
		}
		crp->crp_etype = ENODEV;
		crypto_done(crp);
		return 0;
	}
}

/*
 * Release a set of crypto descriptors.
 */
void
crypto_freereq(struct cryptop *crp)
{
	struct cryptodesc *crd;

	if (crp == NULL)
		return;
	DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);

	/* sanity check */
	if (crp->crp_flags & CRYPTO_F_ONRETQ) {
		panic("crypto_freereq() freeing crp on RETQ\n");
	}

	while ((crd = crp->crp_desc) != NULL) {
		crp->crp_desc = crd->crd_next;
		pool_cache_put(cryptodesc_cache, crd);
	}
	pool_cache_put(cryptop_cache, crp);
}

/*
 * Acquire a set of crypto descriptors.
 */
struct cryptop *
crypto_getreq(int num)
{
	struct cryptodesc *crd;
	struct cryptop *crp;
	struct crypto_crp_ret_qs *qs;

	KASSERT(num > 0);

	/*
	 * When crp_ret_q is full, we restrict here to avoid crp_ret_q overflow
	 * by error callback.
	 */
	qs = crypto_get_crp_ret_qs(curcpu());
	if (qs->crp_ret_q_maxlen > 0
	    && qs->crp_ret_q_len > qs->crp_ret_q_maxlen) {
		qs->crp_ret_q_drops++;
		crypto_put_crp_ret_qs(curcpu());
		return NULL;
	}
	crypto_put_crp_ret_qs(curcpu());

	crp = pool_cache_get(cryptop_cache, PR_NOWAIT);
	if (crp == NULL) {
		return NULL;
	}
	memset(crp, 0, sizeof(struct cryptop));

	while (num--) {
		crd = pool_cache_get(cryptodesc_cache, PR_NOWAIT);
		if (crd == NULL) {
			crypto_freereq(crp);
			return NULL;
		}

		memset(crd, 0, sizeof(struct cryptodesc));
		crd->crd_next = crp->crp_desc;
		crp->crp_desc = crd;
	}

	return crp;
}

/*
 * Release a set of asymmetric crypto descriptors.
 * Currently, support one descriptor only.
 */
void
crypto_kfreereq(struct cryptkop *krp)
{

	if (krp == NULL)
		return;

	DPRINTF("krp %p\n", krp);

	/* sanity check */
	if (krp->krp_flags & CRYPTO_F_ONRETQ) {
		panic("crypto_kfreereq() freeing krp on RETQ\n");
	}

	pool_cache_put(cryptkop_cache, krp);
}

/*
 * Acquire a set of asymmetric crypto descriptors.
 * Currently, support one descriptor only.
 */
struct cryptkop *
crypto_kgetreq(int num __diagused, int prflags)
{
	struct cryptkop *krp;
	struct crypto_crp_ret_qs *qs;

	KASSERTMSG(num == 1, "num=%d not supported", num);

	/*
	 * When crp_ret_kq is full, we restrict here to avoid crp_ret_kq
	 * overflow by error callback.
	 */
	qs = crypto_get_crp_ret_qs(curcpu());
	if (qs->crp_ret_kq_maxlen > 0
	    && qs->crp_ret_kq_len > qs->crp_ret_kq_maxlen) {
		qs->crp_ret_kq_drops++;
		crypto_put_crp_ret_qs(curcpu());
		return NULL;
	}
	crypto_put_crp_ret_qs(curcpu());

	krp = pool_cache_get(cryptkop_cache, prflags);
	if (krp == NULL) {
		return NULL;
	}
	memset(krp, 0, sizeof(struct cryptkop));

	return krp;
}

/*
 * Invoke the callback on behalf of the driver.
 */
void
crypto_done(struct cryptop *crp)
{
	int wasempty;
	struct crypto_crp_ret_qs *qs;
	struct crypto_crp_ret_q *crp_ret_q;

	KASSERT(crp != NULL);

	if (crp->crp_etype != 0)
		cryptostats.cs_errs++;
#ifdef CRYPTO_TIMING
	if (crypto_timing)
		crypto_tstat(&cryptostats.cs_done, &crp->crp_tstamp);
#endif
	DPRINTF("lid[%u]: crp %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);

	qs = crypto_get_crp_ret_qs(crp->reqcpu);
	crp_ret_q = &qs->crp_ret_q;
	wasempty = TAILQ_EMPTY(crp_ret_q);
	DPRINTF("lid[%u]: queueing %p\n", CRYPTO_SESID2LID(crp->crp_sid), crp);
	crp->crp_flags |= CRYPTO_F_ONRETQ;
	TAILQ_INSERT_TAIL(crp_ret_q, crp, crp_next);
	qs->crp_ret_q_len++;
	if (wasempty && !qs->crp_ret_q_exit_flag) {
		DPRINTF("lid[%u]: waking cryptoret, crp %p hit empty queue\n.",
		    CRYPTO_SESID2LID(crp->crp_sid), crp);
		softint_schedule_cpu(crypto_ret_si, crp->reqcpu);
	}
	crypto_put_crp_ret_qs(crp->reqcpu);
}

/*
 * Invoke the callback on behalf of the driver.
 */
void
crypto_kdone(struct cryptkop *krp)
{
	int wasempty;
	struct crypto_crp_ret_qs *qs;
	struct crypto_crp_ret_kq *crp_ret_kq;

	KASSERT(krp != NULL);

	if (krp->krp_status != 0)
		cryptostats.cs_kerrs++;

	qs = crypto_get_crp_ret_qs(krp->reqcpu);
	crp_ret_kq = &qs->crp_ret_kq;

	wasempty = TAILQ_EMPTY(crp_ret_kq);
	krp->krp_flags |= CRYPTO_F_ONRETQ;
	TAILQ_INSERT_TAIL(crp_ret_kq, krp, krp_next);
	qs->crp_ret_kq_len++;
	if (wasempty && !qs->crp_ret_q_exit_flag)
		softint_schedule_cpu(crypto_ret_si, krp->reqcpu);
	crypto_put_crp_ret_qs(krp->reqcpu);
}

int
crypto_getfeat(int *featp)
{

	if (crypto_userasymcrypto == 0) {
		*featp = 0;
		return 0;
	}

	mutex_enter(&crypto_drv_mtx);

	int feat = 0;
	for (int hid = 0; hid < crypto_drivers_num; hid++) {
		struct cryptocap *cap;
		cap = crypto_checkdriver(hid);
		if (cap == NULL)
			continue;

		crypto_driver_lock(cap);

		if ((cap->cc_flags & CRYPTOCAP_F_SOFTWARE) &&
		    crypto_devallowsoft == 0)
			goto unlock;

		if (cap->cc_kprocess == NULL)
			goto unlock;

		for (int kalg = 0; kalg < CRK_ALGORITHM_MAX; kalg++)
			if ((cap->cc_kalg[kalg] &
			    CRYPTO_ALG_FLAG_SUPPORTED) != 0)
				feat |=  1 << kalg;

unlock:		crypto_driver_unlock(cap);
	}

	mutex_exit(&crypto_drv_mtx);
	*featp = feat;
	return (0);
}

/*
 * Software interrupt thread to dispatch crypto requests.
 */
static void
cryptointr(void *arg __unused)
{
	struct cryptop *crp, *submit, *cnext;
	struct cryptkop *krp, *knext;
	struct cryptocap *cap;
	struct crypto_crp_qs *crp_qs;
	struct crypto_crp_q *crp_q;
	struct crypto_crp_kq *crp_kq;
	int result, hint, s;

	cryptostats.cs_intrs++;
	crp_qs = crypto_get_crp_qs(&s);
	crp_q = crp_qs->crp_q;
	crp_kq = crp_qs->crp_kq;
	do {
		/*
		 * Find the first element in the queue that can be
		 * processed and look-ahead to see if multiple ops
		 * are ready for the same driver.
		 */
		submit = NULL;
		hint = 0;
		TAILQ_FOREACH_SAFE(crp, crp_q, crp_next, cnext) {
			u_int32_t hid = CRYPTO_SESID2HID(crp->crp_sid);
			cap = crypto_checkdriver_lock(hid);
			if (cap == NULL || cap->cc_process == NULL) {
				if (cap != NULL)
					crypto_driver_unlock(cap);
				/* Op needs to be migrated, process it. */
				submit = crp;
				break;
			}

			/*
			 * skip blocked crp regardless of CRYPTO_F_BATCH
			 */
			if (cap->cc_qblocked != 0) {
				crypto_driver_unlock(cap);
				continue;
			}
			crypto_driver_unlock(cap);

			/*
			 * skip batch crp until the end of crp_q
			 */
			if ((crp->crp_flags & CRYPTO_F_BATCH) != 0) {
				if (submit == NULL) {
					submit = crp;
				} else {
					if (CRYPTO_SESID2HID(submit->crp_sid)
					    == hid)
						hint = CRYPTO_HINT_MORE;
				}

				continue;
			}

			/*
			 * found first crp which is neither blocked nor batch.
			 */
			submit = crp;
			/*
			 * batch crp can be processed much later, so clear hint.
			 */
			hint = 0;
			break;
		}
		if (submit != NULL) {
			TAILQ_REMOVE(crp_q, submit, crp_next);
			result = crypto_invoke(submit, hint);
			KASSERTMSG(result == 0 || result == ERESTART,
			    "result=%d", result);
			/* we must take here as the TAILQ op or kinvoke
			   may need this mutex below.  sigh. */
			if (result == ERESTART) {
				/*
				 * The driver ran out of resources, mark the
				 * driver ``blocked'' for cryptop's and put
				 * the request back in the queue.  It would
				 * best to put the request back where we got
				 * it but that's hard so for now we put it
				 * at the front.  This should be ok; putting
				 * it at the end does not work.
				 */
				/* validate sid again */
				cap = crypto_checkdriver_lock(CRYPTO_SESID2HID(submit->crp_sid));
				if (cap == NULL) {
					/* migrate again, sigh... */
					TAILQ_INSERT_TAIL(crp_q, submit, crp_next);
				} else {
					cap->cc_qblocked = 1;
					crypto_driver_unlock(cap);
					TAILQ_INSERT_HEAD(crp_q, submit, crp_next);
					cryptostats.cs_blocks++;
				}
			}
		}

		/* As above, but for key ops */
		TAILQ_FOREACH_SAFE(krp, crp_kq, krp_next, knext) {
			cap = crypto_checkdriver_lock(krp->krp_hid);
			if (cap == NULL || cap->cc_kprocess == NULL) {
				if (cap != NULL)
					crypto_driver_unlock(cap);
				/* Op needs to be migrated, process it. */
				break;
			}
			if (!cap->cc_kqblocked) {
				crypto_driver_unlock(cap);
				break;
			}
			crypto_driver_unlock(cap);
		}
		if (krp != NULL) {
			TAILQ_REMOVE(crp_kq, krp, krp_next);
			result = crypto_kinvoke(krp, 0);
			KASSERTMSG(result == 0 || result == ERESTART,
			    "result=%d", result);
			/* the next iteration will want the mutex. :-/ */
			if (result == ERESTART) {
				/*
				 * The driver ran out of resources, mark the
				 * driver ``blocked'' for cryptkop's and put
				 * the request back in the queue.  It would
				 * best to put the request back where we got
				 * it but that's hard so for now we put it
				 * at the front.  This should be ok; putting
				 * it at the end does not work.
				 */
				/* validate sid again */
				cap = crypto_checkdriver_lock(krp->krp_hid);
				if (cap == NULL) {
					/* migrate again, sigh... */
					TAILQ_INSERT_TAIL(crp_kq, krp, krp_next);
				} else {
					cap->cc_kqblocked = 1;
					crypto_driver_unlock(cap);
					TAILQ_INSERT_HEAD(crp_kq, krp, krp_next);
					cryptostats.cs_kblocks++;
				}
			}
		}
	} while (submit != NULL || krp != NULL);
	crypto_put_crp_qs(&s);
}

/*
 * softint handler to do callbacks.
 */
static void
cryptoret_softint(void *arg __unused)
{
	struct crypto_crp_ret_qs *qs;
	struct crypto_crp_ret_q *crp_ret_q;
	struct crypto_crp_ret_kq *crp_ret_kq;

	qs = crypto_get_crp_ret_qs(curcpu());
	crp_ret_q = &qs->crp_ret_q;
	crp_ret_kq = &qs->crp_ret_kq;
	for (;;) {
		struct cryptop *crp;
		struct cryptkop *krp;

		crp = TAILQ_FIRST(crp_ret_q);
		if (crp != NULL) {
			TAILQ_REMOVE(crp_ret_q, crp, crp_next);
			qs->crp_ret_q_len--;
			crp->crp_flags &= ~CRYPTO_F_ONRETQ;
		}
		krp = TAILQ_FIRST(crp_ret_kq);
		if (krp != NULL) {
			TAILQ_REMOVE(crp_ret_kq, krp, krp_next);
			qs->crp_ret_q_len--;
			krp->krp_flags &= ~CRYPTO_F_ONRETQ;
		}

		/* drop before calling any callbacks. */
		if (crp == NULL && krp == NULL)
			break;

		mutex_spin_exit(&qs->crp_ret_q_mtx);
		if (crp != NULL) {
#ifdef CRYPTO_TIMING
			if (crypto_timing) {
				/*
				 * NB: We must copy the timestamp before
				 * doing the callback as the cryptop is
				 * likely to be reclaimed.
				 */
				struct timespec t = crp->crp_tstamp;
				crypto_tstat(&cryptostats.cs_cb, &t);
				crp->crp_callback(crp);
				crypto_tstat(&cryptostats.cs_finis, &t);
			} else
#endif
			{
				crp->crp_callback(crp);
			}
		}
		if (krp != NULL)
			krp->krp_callback(krp);

		mutex_spin_enter(&qs->crp_ret_q_mtx);
	}
	crypto_put_crp_ret_qs(curcpu());
}

/* NetBSD module interface */

MODULE(MODULE_CLASS_MISC, opencrypto, NULL);

static int
opencrypto_modcmd(modcmd_t cmd, void *opaque)
{
	int error = 0;

	switch (cmd) {
	case MODULE_CMD_INIT:
#ifdef _MODULE
		error = crypto_init();
#endif
		break;
	case MODULE_CMD_FINI:
#ifdef _MODULE
		error = crypto_destroy(true);
#endif
		break;
	default:
		error = ENOTTY;
	}
	return error;
}