summaryrefslogtreecommitdiff
path: root/usr/netlink.c
blob: 22cad8344b0e38b8d507f47f4745fab0558ce32d (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
/*
 * iSCSI Netlink/Linux Interface
 *
 * Copyright (C) 2004 Dmitry Yusupov, Alex Aizman
 * Copyright (C) 2006 Mike Christie
 * Copyright (C) 2006 Red Hat, Inc. All rights reserved.
 * maintained by open-iscsi@googlegroups.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * See the file COPYING included with this distribution for more details.
 */

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <time.h>
#include <inttypes.h>
#include <asm/types.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <poll.h>
#include <linux/netlink.h>

#include "types.h"
#include "iscsi_if.h"
#include "log.h"
#include "iscsi_ipc.h"
#include "initiator.h"
#include "iscsi_sysfs.h"
#include "transport.h"
#include "iscsi_netlink.h"
#include "iscsi_err.h"
#include "iscsi_timer.h"

static int ctrl_fd;
static struct sockaddr_nl src_addr, dest_addr;
static void *xmitbuf = NULL;
static int xmitlen = 0;
static void *recvbuf = NULL;
static int recvlen = 0;
static void *nlm_sendbuf;
static void *nlm_recvbuf;
static void *pdu_sendbuf;
static void *setparam_buf;
static struct iscsi_ipc_ev_clbk *ipc_ev_clbk;

static int ctldev_handle(void);

#define NLM_BUF_DEFAULT_MAX (NLMSG_SPACE(ISCSI_DEF_MAX_RECV_SEG_LEN +	\
					sizeof(struct iscsi_uevent) +	\
					sizeof(struct iscsi_hdr)))

#define PDU_SENDBUF_DEFAULT_MAX	(ISCSI_DEF_MAX_RECV_SEG_LEN +		\
					sizeof(struct iscsi_uevent) +	\
					sizeof(struct iscsi_hdr))

#define NLM_SETPARAM_DEFAULT_MAX (NI_MAXHOST + 1 + sizeof(struct iscsi_uevent))

struct iscsi_ping_event {
	uint32_t host_no;
	uint32_t pid;
	int32_t status;
	int active;
};

struct iscsi_ping_event ping_event;

struct nlattr *iscsi_nla_alloc(uint16_t type, uint16_t len)
{
	struct nlattr *attr;

	attr = calloc(1, ISCSI_NLA_TOTAL_LEN(len));
	if (!attr)
		return NULL; 

	attr->nla_len = ISCSI_NLA_LEN(len);
	attr->nla_type = type;
	return attr;
}

static int
kread(char *data, int count)
{
	log_debug(7, "in %s %u %u %p %p", __FUNCTION__, recvlen, count,
		  data, recvbuf);

	memcpy(data, recvbuf + recvlen, count);
	recvlen += count;
	return count;
}

static int
nl_read(int ctrl_fd, char *data, int size, int flags)
{
	int rc;
	struct iovec iov;
	struct msghdr msg;

	log_debug(7, "in %s", __FUNCTION__);

	iov.iov_base = data;
	iov.iov_len = size;

	memset(&msg, 0, sizeof(msg));
	msg.msg_name= (void*)&src_addr;
	msg.msg_namelen = sizeof(src_addr);
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;

	rc = recvmsg(ctrl_fd, &msg, flags);

	return rc;
}

static int
nlpayload_read(int ctrl_fd, char *data, int count, int flags)
{
	int rc;
	struct iovec iov;
	struct msghdr msg;

	log_debug(7, "in %s", __FUNCTION__);

	iov.iov_base = nlm_recvbuf;
	iov.iov_len = NLMSG_SPACE(count);

	if (iov.iov_len > NLM_BUF_DEFAULT_MAX) {
		log_error("Cannot read %zu bytes. nlm_recvbuf too small.",
			  iov.iov_len);
		return -1;
	}
	memset(iov.iov_base, 0, iov.iov_len);

	memset(&msg, 0, sizeof(msg));
	msg.msg_name= (void*)&src_addr;
	msg.msg_namelen = sizeof(src_addr);
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;

	/*
	 * Netlink recvmsg call path:
	 *
	 *  - transport api callback
	 *  - iscsi_control_conn_error (should succeed)
	 *  - iscsi_unicast_skb (must succeed)
	 *  - netlink_unicast (must succeed)
	 *  - netlink_data_ready (must succeed)
	 *  - netlink_sendskb (must succeed)
	 *  - netlink_recvmsg (must succeed)
	 *  - sock_recvmsg (must succeed)
	 *  - sys_recvmsg (must succeed)
	 *  - sys_socketcall (must succeed)
	 *  - syscall_call (must succeed)
	 *
	 *  Note1: "must succeed" means succeed unless bug in daemon.
	 *        It also means - no sleep and memory allocation on
	 *        the path.
	 *
	 *  Note2: "should succeed" means will succeed in most of cases
	 *        because of mempool preallocation.
	 *
	 *  FIXME: if "Note2" than interface should generate iSCSI error
	 *        level 0 on its own. Interface must always succeed on this.
	 */
	rc = recvmsg(ctrl_fd, &msg, flags);

	if (data)
		memcpy(data, NLMSG_DATA(iov.iov_base), count);

	return rc;
}

static int
kwritev(enum iscsi_uevent_e type, struct iovec *iovp, int count)
{
	int i, rc;
	struct nlmsghdr *nlh;
	struct msghdr msg;
	int datalen = 0;

	log_debug(7, "in %s", __FUNCTION__);

	for (i = 0; i < count; i++) {
		datalen += iovp[i].iov_len;
	}

	if (xmitbuf && type != ISCSI_UEVENT_SEND_PDU) {
		for (i = 0; i < count; i++) {
			memcpy(xmitbuf + xmitlen,
			       iovp[i].iov_base, iovp[i].iov_len);
			xmitlen += iovp[i].iov_len;
		}
		return datalen;
	}

	nlh = nlm_sendbuf;
	memset(nlh, 0, NLMSG_SPACE(0));

	datalen = 0;
	for (i = 1; i < count; i++)
		datalen += iovp[i].iov_len;

	nlh->nlmsg_len = datalen + sizeof(*nlh);
	nlh->nlmsg_pid = getpid();
	nlh->nlmsg_flags = 0;
	nlh->nlmsg_type = type;

	iovp[0].iov_base = (void *)nlh;
	iovp[0].iov_len = sizeof(*nlh);

	memset(&msg, 0, sizeof(msg));
	msg.msg_name= (void*)&dest_addr;
	msg.msg_namelen = sizeof(dest_addr);
	msg.msg_iov = iovp;
	msg.msg_iovlen = count;

	do {
		/*
		 * Netlink down call path:
		 *
		 *  - transport api call
		 *  - iscsi_if_recv_msg (must succeed)
		 *  - iscsi_if_rx (must succeed)
		 *  - netlink_data_ready (must succeed)
		 *  - netlink_sendskb (must succeed)
		 *  - netlink_sendmsg (alloc_skb() might fail)
		 *  - sock_sendmsg (must succeed)
		 *  - sys_sendmsg (must succeed)
		 *  - sys_socketcall (must succeed)
		 *  - syscall_call (must succeed)
		 *
		 *  Note1: "must succeed" means succeed unless bug in daemon.
		 *        It also means - no sleep and memory allocation on
		 *        the path.
		 *
		 *  Note2: netlink_sendmsg() might fail because of OOM. Since
		 *         we are in user-space, we will sleep until we succeed.
		 */

		rc = sendmsg(ctrl_fd, &msg, 0);
		if (rc == -ENOMEM) {
			log_debug(1, "sendmsg: alloc_skb() failed");
			sleep(1);
		} else if (rc < 0) {
			log_error("sendmsg: bug? ctrl_fd %d", ctrl_fd);
			exit(rc);
		}
	} while (rc < 0);

	return rc;
}

/*
 * __kipc_call() should never block. Therefore
 * Netlink's xmit logic is serialized. This means we do not allocate on
 * xmit path. Instead we reuse nlm_sendbuf buffer.
 *
 * Transport must assure non-blocking operations for:
 *
 *	- session_create()
 *	- conn_create()
 *	- conn_bind()
 *	_ set_param()
 *	- conn_start()
 *	- conn_stop()
 *
 * Its OK to block for cleanup for short period of time in operatations for:
 *
 *	- conn_destroy()
 *	- session_destroy()
 *
 * FIXME: interface needs to be extended to allow longer blocking on
 *        cleanup. (Dima)
 */
static int
__kipc_call(struct iovec *iovp, int count)
{
	int rc, iferr;
	struct iscsi_uevent *ev = iovp[1].iov_base;
	enum iscsi_uevent_e type = ev->type;

	log_debug(7, "in %s", __FUNCTION__);

	rc = kwritev(type, iovp, count);

	do {
		if ((rc = nlpayload_read(ctrl_fd, (void*)ev,
					 sizeof(*ev), MSG_PEEK)) < 0) {
			return rc;
		}
		if (ev->type != type) {
			log_debug(1, "expecting event %d, got %d, handling...",
				  type, ev->type);
			if (ev->type == ISCSI_KEVENT_IF_ERROR) {
				if ((rc = nlpayload_read(ctrl_fd, (void*)ev,
							 sizeof(*ev), 0)) < 0) {
					return rc;
				}
				/*
				 * iferror is u32, but the kernel returns
				 * negative errno values for errors.
				 */
				iferr = ev->iferror;

				if (iferr == -ENOSYS)
					/* not fatal so let caller handle log */
					log_debug(1, "Received iferror %d: %s.",
						  iferr, strerror(-iferr));
				else if (iferr < 0)
					log_error("Received iferror %d: %s.",
						   iferr, strerror(-iferr));
				else
					log_error("Received iferror %d.",
						   iferr);
				return ev->iferror;
			}
			/*
			 * receive and queue async. event which as of
			 * today could be:
			 *	- CONN_ERROR
			 *	- RECV_PDU
			 */
			ctldev_handle();
		} else if (ev->type == ISCSI_UEVENT_GET_STATS) {
			/* kget_stats() will read */
			return 0;
		} else if (ev->type == ISCSI_UEVENT_GET_CHAP) {
			/* kget_chap() will read */
			return 0;
		} else if (ev->type == ISCSI_UEVENT_GET_HOST_STATS) {
			/* kget_host_stats() will read */
			return 0;

		} else {
			if ((rc = nlpayload_read(ctrl_fd, (void*)ev,
						 sizeof(*ev), 0)) < 0) {
				return rc;
			}
			break;
		}
	} while (ev->type != type);

	return rc;
}

static int
ksendtargets(uint64_t transport_handle, uint32_t host_no, struct sockaddr *addr)
{
	int rc, addrlen;
	struct iscsi_uevent *ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX);
	ev = (struct iscsi_uevent *)setparam_buf;
	ev->type = ISCSI_UEVENT_TGT_DSCVR;
	ev->transport_handle = transport_handle;
	ev->u.tgt_dscvr.type = ISCSI_TGT_DSCVR_SEND_TARGETS;
	ev->u.tgt_dscvr.host_no = host_no;

	if (addr->sa_family == PF_INET)
		addrlen = sizeof(struct sockaddr_in);
	else if (addr->sa_family == PF_INET6)
		addrlen = sizeof(struct sockaddr_in6);
	else {
		log_error("%s unknown addr family %d",
			  __FUNCTION__, addr->sa_family);
		return -EINVAL;
	}
	memcpy(setparam_buf + sizeof(*ev), addr, addrlen);

	iov[1].iov_base = ev;
	iov[1].iov_len = sizeof(*ev) + addrlen;
	rc = __kipc_call(iov, 2);
	if (rc < 0) {
		log_error("sendtargets failed rc%d", rc);
		return rc;
	}
	return 0;
}

static int
kcreate_session(uint64_t transport_handle, uint64_t ep_handle,
		uint32_t initial_cmdsn, uint16_t cmds_max, uint16_t qdepth,
		uint32_t *out_sid, uint32_t *hostno)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	if (ep_handle == 0) {
		ev.type = ISCSI_UEVENT_CREATE_SESSION;
		ev.transport_handle = transport_handle;
		ev.u.c_session.initial_cmdsn = initial_cmdsn;
		ev.u.c_session.cmds_max = cmds_max;
		ev.u.c_session.queue_depth = qdepth;
	} else {
		ev.type = ISCSI_UEVENT_CREATE_BOUND_SESSION;
		ev.transport_handle = transport_handle;
		ev.u.c_bound_session.initial_cmdsn = initial_cmdsn;
		ev.u.c_bound_session.cmds_max = cmds_max;
		ev.u.c_bound_session.queue_depth = qdepth;
		ev.u.c_bound_session.ep_handle = ep_handle;
	}

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	*hostno = ev.r.c_session_ret.host_no;
	*out_sid = ev.r.c_session_ret.sid;

	return 0;
}

static int
kdestroy_session(uint64_t transport_handle, uint32_t sid)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_DESTROY_SESSION;
	ev.transport_handle = transport_handle;
	ev.u.d_session.sid = sid;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
kunbind_session(uint64_t transport_handle, uint32_t sid)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_UNBIND_SESSION;
	ev.transport_handle = transport_handle;
	ev.u.d_session.sid = sid;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
kcreate_conn(uint64_t transport_handle, uint32_t sid,
	    uint32_t cid, uint32_t *out_cid)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_CREATE_CONN;
	ev.transport_handle = transport_handle;
	ev.u.c_conn.cid = cid;
	ev.u.c_conn.sid = sid;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0) {
		log_debug(7, "returned %d", rc);
		return rc;
	}

	if ((int)ev.r.c_conn_ret.cid == -1)
		return -EIO;

	*out_cid = ev.r.c_conn_ret.cid;
	return 0;
}

static int
kdestroy_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_DESTROY_CONN;
	ev.transport_handle = transport_handle;
	ev.u.d_conn.sid = sid;
	ev.u.d_conn.cid = cid;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
kbind_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid,
	  uint64_t transport_eph, int is_leading, int *retcode)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_BIND_CONN;
	ev.transport_handle = transport_handle;
	ev.u.b_conn.sid = sid;
	ev.u.b_conn.cid = cid;
	ev.u.b_conn.transport_eph = transport_eph;
	ev.u.b_conn.is_leading = is_leading;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	*retcode = ev.r.retcode;

	return 0;
}

static void
ksend_pdu_begin(uint64_t transport_handle, uint32_t sid, uint32_t cid,
			int hdr_size, int data_size)
{
	struct iscsi_uevent *ev;
	int total_xmitlen = sizeof(*ev) + hdr_size + data_size;

	log_debug(7, "in %s", __FUNCTION__);

	if (xmitbuf) {
		log_error("send's begin state machine bug?");
		exit(-EIO);
	}

	if (total_xmitlen > (int)PDU_SENDBUF_DEFAULT_MAX) {
		log_error("BUG: Cannot send %d bytes.", total_xmitlen);
		exit(-EINVAL);
	}

	xmitbuf = pdu_sendbuf;
	memset(xmitbuf, 0, total_xmitlen);
	xmitlen = sizeof(*ev);
	ev = xmitbuf;
	memset(ev, 0, sizeof(*ev));
	ev->type = ISCSI_UEVENT_SEND_PDU;
	ev->transport_handle = transport_handle;
	ev->u.send_pdu.sid = sid;
	ev->u.send_pdu.cid = cid;
	ev->u.send_pdu.hdr_size = hdr_size;
	ev->u.send_pdu.data_size = data_size;

	log_debug(3, "send PDU began for hdr %d bytes and data %d bytes",
		hdr_size, data_size);
}

static int
ksend_pdu_end(__attribute__((unused))uint64_t transport_handle,
	      uint32_t sid, uint32_t cid, int *retcode)
{
	int rc;
	struct iscsi_uevent *ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	if (!xmitbuf) {
		log_error("send's end state machine bug?");
		exit(-EIO);
	}
	ev = xmitbuf;
	if (ev->u.send_pdu.sid != sid || ev->u.send_pdu.cid != cid) {
		log_error("send's end state machine corruption?");
		exit(-EIO);
	}

	iov[1].iov_base = xmitbuf;
	iov[1].iov_len = xmitlen;

	rc = __kipc_call(iov, 2);
	if (rc < 0)
		goto err;
	if (ev->r.retcode) {
		*retcode = ev->r.retcode;
		goto err;
	}
	if (ev->type != ISCSI_UEVENT_SEND_PDU) {
		log_error("bad event: bug on send_pdu_end?");
		exit(-EIO);
	}

	log_debug(3, "send PDU finished for conn %d:%d",
		  sid, cid);

	xmitbuf = NULL;
	return 0;

err:
	xmitbuf = NULL;
	xmitlen = 0;
	return rc;
}

static int
kset_host_param(uint64_t transport_handle, uint32_t host_no,
		enum iscsi_host_param param, void *value, int type)
{
	struct iscsi_uevent *ev;
	char *param_str;
	int rc, len;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX);
	ev = (struct iscsi_uevent *)setparam_buf;
	ev->type = ISCSI_UEVENT_SET_HOST_PARAM;
	ev->transport_handle = transport_handle;
	ev->u.set_host_param.host_no = host_no;
	ev->u.set_host_param.param = param;

	param_str = setparam_buf + sizeof(*ev);
	switch (type) {
	case ISCSI_INT:
		sprintf(param_str, "%d", *((int *)value));
		break;
	case ISCSI_STRING:
		if (!strlen(value))
			return 0;
		sprintf(param_str, "%s", (char *)value);
		break;
	default:
		log_error("invalid type %d", type);
		return -EINVAL;
	}
	ev->u.set_host_param.len = len = strlen(param_str) + 1;

	iov[1].iov_base = ev;
	iov[1].iov_len = sizeof(*ev) + len;
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
kset_param(uint64_t transport_handle, uint32_t sid, uint32_t cid,
	   enum iscsi_param param, void *value, int type)
{
	struct iscsi_uevent *ev;
	char *param_str;
	int rc, len;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX);
	ev = (struct iscsi_uevent *)setparam_buf;
	ev->type = ISCSI_UEVENT_SET_PARAM;
	ev->transport_handle = transport_handle;
	ev->u.set_param.sid = sid;
	ev->u.set_param.cid = cid;
	ev->u.set_param.param = param;

	param_str = setparam_buf + sizeof(*ev);
	switch (type) {
	case ISCSI_INT:
		sprintf(param_str, "%d", *((int *)value));
		break;
	case ISCSI_UINT:
		sprintf(param_str, "%u", *((unsigned int *)value));
		break;
	case ISCSI_STRING:
		if (!strlen(value))
			return 0;
		sprintf(param_str, "%s", (char *)value);
		break;
	default:
		log_error("invalid type %d", type);
		return -EINVAL;
	}
	ev->u.set_param.len = len = strlen(param_str) + 1;

	iov[1].iov_base = ev;
	iov[1].iov_len = sizeof(*ev) + len;
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
kstop_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid, int flag)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_STOP_CONN;
	ev.transport_handle = transport_handle;
	ev.u.stop_conn.sid = sid;
	ev.u.stop_conn.cid = cid;
	ev.u.stop_conn.flag = flag;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
kstart_conn(uint64_t transport_handle, uint32_t sid, uint32_t cid,
	    int *retcode)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_START_CONN;
	ev.transport_handle = transport_handle;
	ev.u.start_conn.sid = sid;
	ev.u.start_conn.cid = cid;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	*retcode = ev.r.retcode;
	return 0;
}

static int
krecv_pdu_begin(struct iscsi_conn *conn)
{
	int rc;

	log_debug(7, "in %s", __FUNCTION__);

	if (recvbuf) {
		log_error("recv's begin state machine bug?");
		return -EIO;
	}

	if (!conn->recv_context) {
		rc = ipc->ctldev_handle();
		if (rc == -ENXIO)
			/* event for some other conn */
			return -EAGAIN;
		else if (rc < 0)
			/* fatal handling error or conn error */
			return rc;
		/*
		 * Session create/destroy event for another conn
		 */
		if (!conn->recv_context)
			return -EAGAIN;
	}

	recvbuf = conn->recv_context->data + sizeof(struct iscsi_uevent);
	recvlen = 0;

	log_debug(3, "recv PDU began, pdu handle %p", recvbuf);
	return 0;
}

static int
krecv_pdu_end(struct iscsi_conn *conn)
{
	log_debug(7, "in %s", __FUNCTION__);

	if (!recvbuf) {
		log_error("recv's end state machine bug?");
		return -EIO;
	}

	log_debug(3, "recv PDU finished for pdu handle 0x%p",
		  recvbuf);

	ipc_ev_clbk->put_ev_context(conn->recv_context);
	conn->recv_context = NULL;
	recvbuf = NULL;
	return 0;
}

int
ktransport_ep_connect(iscsi_conn_t *conn, int non_blocking)
{
	int rc, addrlen;
	struct iscsi_uevent *ev;
	struct sockaddr *dst_addr = (struct sockaddr *)&conn->saddr;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX);
	ev = (struct iscsi_uevent *)setparam_buf;
	ev->transport_handle = conn->session->t->handle;

	if (conn->bind_ep) {
		ev->type = ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST;
		ev->u.ep_connect_through_host.non_blocking = non_blocking;
		ev->u.ep_connect_through_host.host_no = conn->session->hostno;
	} else {
		ev->type = ISCSI_UEVENT_TRANSPORT_EP_CONNECT;
		ev->u.ep_connect.non_blocking = non_blocking;
	}

	if (dst_addr->sa_family == PF_INET)
		addrlen = sizeof(struct sockaddr_in);
	else if (dst_addr->sa_family == PF_INET6)
		addrlen = sizeof(struct sockaddr_in6);
	else {
		log_error("%s unknown addr family %d",
			 __FUNCTION__, dst_addr->sa_family);
		return -EINVAL;
	}
	memcpy(setparam_buf + sizeof(*ev), dst_addr, addrlen);

	iov[1].iov_base = ev;
	iov[1].iov_len = sizeof(*ev) + addrlen;
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	if (!ev->r.ep_connect_ret.handle)
		return -EIO;

	conn->transport_ep_handle = ev->r.ep_connect_ret.handle;

	log_debug(6, "%s got handle %llx",
		__FUNCTION__, (unsigned long long)conn->transport_ep_handle);
	return 0;
}

int
ktransport_ep_poll(iscsi_conn_t *conn, int timeout_ms)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_TRANSPORT_EP_POLL;
	ev.transport_handle = conn->session->t->handle;
	ev.u.ep_poll.ep_handle  = conn->transport_ep_handle;
	ev.u.ep_poll.timeout_ms = timeout_ms;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return ev.r.retcode;
}

void
ktransport_ep_disconnect(iscsi_conn_t *conn)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	if (conn->transport_ep_handle == (uint64_t)-1)
		return;

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT;
	ev.transport_handle = conn->session->t->handle;
	ev.u.ep_disconnect.ep_handle = conn->transport_ep_handle;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0) {
		log_error("connection %d:%d transport disconnect failed for "
			  "ep %" PRIu64 " with error %d.", conn->session->id,
			  conn->id, conn->transport_ep_handle, rc);
	} else
		conn->transport_ep_handle = -1;
}

static int
kget_stats(uint64_t transport_handle, uint32_t sid, uint32_t cid,
	   char *statsbuf, int statsbuf_max)
{
	int rc;
	int ev_size;
	struct iscsi_uevent ev;
	char nlm_ev[NLMSG_SPACE(sizeof(struct iscsi_uevent))];
	struct nlmsghdr *nlh;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_GET_STATS;
	ev.transport_handle = transport_handle;
	ev.u.get_stats.sid = sid;
	ev.u.get_stats.cid = cid;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	if ((rc = nl_read(ctrl_fd, nlm_ev,
		NLMSG_SPACE(sizeof(struct iscsi_uevent)), MSG_PEEK)) < 0) {
		log_error("can not read nlm_ev, error %d", rc);
		return rc;
	}
	nlh = (struct nlmsghdr *)nlm_ev;
	ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));

	log_debug(6, "message real length is %d bytes", nlh->nlmsg_len);

	if (ev_size > statsbuf_max) {
		log_error("destanation buffer for statistics is "
			"not big enough to fit %d bytes", statsbuf_max);
		ev_size = statsbuf_max;
	}

	if ((rc = nlpayload_read(ctrl_fd, (void*)statsbuf, ev_size, 0)) < 0) {
		log_error("can not read from NL socket, error %d", rc);
		return rc;
	}

	return 0;
}

static int
kset_net_config(uint64_t transport_handle, uint32_t host_no,
		struct iovec *iovs, uint32_t param_count)
{
	struct iscsi_uevent ev;
	int rc, ev_len;
	struct iovec *iov = iovs + 1;

	log_debug(8, "in %s", __FUNCTION__);

	ev_len = sizeof(ev);
	ev.type = ISCSI_UEVENT_SET_IFACE_PARAMS;
	ev.transport_handle = transport_handle;
	ev.u.set_iface_params.host_no = host_no;
	/* first two iovs for nlmsg hdr and ev */
	ev.u.set_iface_params.count = param_count - 2;

	iov->iov_base = &ev;
	iov->iov_len = ev_len;
	rc = __kipc_call(iovs, param_count);
	if (rc < 0)
		return rc;

	return 0;
}

static int krecv_conn_state(struct iscsi_conn *conn, uint32_t *state)
{
	int rc;

	rc = ipc->ctldev_handle();
	if (rc == -ENXIO) {
		/* event for some other conn */
		rc = -EAGAIN;
		goto exit;
	} else if (rc < 0)
		/* fatal handling error or conn error */
		goto exit;

        /* unexpected event without a receive context */
        if (!conn->recv_context)
                return -EAGAIN;

	*state = *(enum iscsi_conn_state *)conn->recv_context->data;

	ipc_ev_clbk->put_ev_context(conn->recv_context);
	conn->recv_context = NULL;

exit:
	return rc;
}




static int
ksend_ping(uint64_t transport_handle, uint32_t host_no, struct sockaddr *addr,
	   uint32_t iface_num, uint32_t iface_type, uint32_t pid, uint32_t size)
{
	int rc, addrlen;
	struct iscsi_uevent *ev;
	struct iovec iov[2];

	log_debug(8, "in %s", __FUNCTION__);

	memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX);
	ev = (struct iscsi_uevent *)setparam_buf;
	ev->type = ISCSI_UEVENT_PING;
	ev->transport_handle = transport_handle;
	ev->u.iscsi_ping.host_no = host_no;
	ev->u.iscsi_ping.iface_num = iface_num;
	ev->u.iscsi_ping.iface_type = iface_type;
	ev->u.iscsi_ping.payload_size = size;
	ev->u.iscsi_ping.pid = pid;

	if (addr->sa_family == PF_INET)
		addrlen = sizeof(struct sockaddr_in);
	else if (addr->sa_family == PF_INET6)
		addrlen = sizeof(struct sockaddr_in6);
	else {
		log_error("%s unknown addr family %d",
			  __FUNCTION__, addr->sa_family);
		return -EINVAL;
	}
	memcpy(setparam_buf + sizeof(*ev), addr, addrlen);

	iov[1].iov_base = ev;
	iov[1].iov_len = sizeof(*ev) + addrlen;
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int kexec_ping(uint64_t transport_handle, uint32_t host_no,
		      struct sockaddr *addr, uint32_t iface_num,
		      uint32_t iface_type, uint32_t size, uint32_t *status)
{
	struct pollfd pfd;
	struct timeval ping_timer;
	int timeout, fd, rc;
	uint32_t pid;

	*status = 0;

	fd = ipc->ctldev_open();
	if (fd < 0) {
		log_error("Could not open netlink socket.");
		return ISCSI_ERR;
	}

	/* prepare to poll */
	memset(&pfd, 0, sizeof(pfd));
	pfd.fd = fd;
	pfd.events = POLLIN | POLLPRI;

	/* get unique ping id */
	pid = rand();

	rc = ksend_ping(transport_handle, host_no, addr, iface_num,
			iface_type, pid, size);
	if (rc != 0) {
		switch (rc) {
		case -ENOSYS:
			rc = ISCSI_ERR_OP_NOT_SUPP;
			break;
		case -EINVAL:
			rc = ISCSI_ERR_INVAL;
			break;
		default:
			rc = ISCSI_ERR;
		}
		goto close_nl;
	}

	ping_event.host_no = -1;
	ping_event.pid = -1;
	ping_event.status = -1;
	ping_event.active = -1;

	iscsi_timer_set(&ping_timer, 30);

	timeout = iscsi_timer_msecs_until(&ping_timer);

	while (1) {
		pfd.revents = 0;
		rc = poll(&pfd, 1, timeout);

		if (iscsi_timer_expired(&ping_timer)) {
			rc = ISCSI_ERR_TRANS_TIMEOUT;
			break;
		}

		if (rc > 0) {
			if (pfd.revents & (POLLIN | POLLPRI)) {
				timeout = iscsi_timer_msecs_until(&ping_timer);
				rc = ipc->ctldev_handle();

				if (ping_event.active != 1)
					continue;

				if (pid != ping_event.pid)
					continue;

				rc = 0;
				*status = ping_event.status;
				break;
			}

			if (pfd.revents & POLLHUP) {
				rc = ISCSI_ERR_TRANS;
				break;
			}

			if (pfd.revents & POLLNVAL) {
				rc = ISCSI_ERR_INTERNAL;
				break;
			}

			if (pfd.revents & POLLERR) {
				rc = ISCSI_ERR_INTERNAL;
				break;
			}
		} else if (rc < 0) {
			rc = ISCSI_ERR_INTERNAL;
			break;
		}
	}

close_nl:
	ipc->ctldev_close();
	return rc;
}

static int kget_chap(uint64_t transport_handle, uint32_t host_no,
		     uint16_t chap_tbl_idx, uint32_t num_entries,
		     char *chap_buf, uint32_t *valid_chap_entries)
{
	int rc = 0;
	int ev_size;
	struct iscsi_uevent ev;
	struct iovec iov[2];
	char nlm_ev[NLMSG_SPACE(sizeof(struct iscsi_uevent))];
	struct nlmsghdr *nlh;

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_GET_CHAP;
	ev.transport_handle = transport_handle;
	ev.u.get_chap.host_no = host_no;
	ev.u.get_chap.chap_tbl_idx = chap_tbl_idx;
	ev.u.get_chap.num_entries = num_entries;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	if ((rc = nl_read(ctrl_fd, nlm_ev,
			  NLMSG_SPACE(sizeof(struct iscsi_uevent)),
			  MSG_PEEK)) < 0) {
		log_error("can not read nlm_ev, error %d", rc);
		return rc;
	}

	nlh = (struct nlmsghdr *)nlm_ev;
	ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));

	if ((rc = nlpayload_read(ctrl_fd, (void *)chap_buf, ev_size, 0)) < 0) {
		log_error("can not read from NL socket, error %d", rc);
		return rc;
	}

	*valid_chap_entries = ev.u.get_chap.num_entries;

	return rc;
}

static int kset_chap(uint64_t transport_handle, uint32_t host_no,
			struct iovec *iovs, uint32_t param_count)
{
	int rc;
	struct iscsi_uevent ev;
	struct iovec *iov = iovs + 1;

	log_debug(8, "in %s", __func__);

	ev.type = ISCSI_UEVENT_SET_CHAP;
	ev.transport_handle = transport_handle;
	ev.u.set_path.host_no = host_no;

	iov->iov_base = &ev;
	iov->iov_len = sizeof(ev);

	rc = __kipc_call(iovs, param_count);
	if (rc < 0)
		return rc;

	return 0;
}

static int kdelete_chap(uint64_t transport_handle, uint32_t host_no,
			uint16_t chap_tbl_idx)
{
	int rc = 0;
	struct iscsi_uevent ev;
	struct iovec iov[2];

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_DELETE_CHAP;
	ev.transport_handle = transport_handle;
	ev.u.delete_chap.host_no = host_no;
	ev.u.delete_chap.chap_tbl_idx = chap_tbl_idx;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);

	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return rc;
}

static int
kset_flashnode_params(uint64_t transport_handle, uint32_t host_no,
		      uint32_t flashnode_idx, struct iovec *iovs,
		      uint32_t param_count)
{
	struct iscsi_uevent ev;
	int rc, ev_len;
	struct iovec *iov = iovs + 1;

	log_debug(8, "in %s", __FUNCTION__);

	ev_len = sizeof(ev);
	ev.type = ISCSI_UEVENT_SET_FLASHNODE_PARAMS;
	ev.transport_handle = transport_handle;
	ev.u.set_flashnode.host_no = host_no;
	ev.u.set_flashnode.flashnode_idx = flashnode_idx;
	/* first two iovs for nlmsg hdr and ev */
	ev.u.set_flashnode.count = param_count - 2;

	iov->iov_base = &ev;
	iov->iov_len = ev_len;
	rc = __kipc_call(iovs, param_count);
	if (rc < 0)
		return rc;

	return 0;
}

static int
knew_flashnode(uint64_t transport_handle, uint32_t host_no, void *value,
	       uint32_t *flashnode_idx)
{
	struct iscsi_uevent *ev;
	char *param_str;
	int rc, len;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(setparam_buf, 0, NLM_SETPARAM_DEFAULT_MAX);
	ev = (struct iscsi_uevent *)setparam_buf;
	ev->type = ISCSI_UEVENT_NEW_FLASHNODE;
	ev->transport_handle = transport_handle;
	ev->u.new_flashnode.host_no = host_no;

	param_str = setparam_buf + sizeof(*ev);
	if (!strlen(value))
		return 0;
	sprintf(param_str, "%s", (char *)value);
	len = strlen(param_str) + 1;
	ev->u.new_flashnode.len = len;


	iov[1].iov_base = ev;
	iov[1].iov_len = sizeof(*ev) + len;
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	*flashnode_idx = ev->r.new_flashnode_ret.flashnode_idx;
	return 0;
}

static int
kdel_flashnode(uint64_t transport_handle, uint32_t host_no,
	       uint32_t flashnode_idx)
{
	struct iscsi_uevent ev;
	int rc;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));
	ev.type = ISCSI_UEVENT_DEL_FLASHNODE;
	ev.transport_handle = transport_handle;
	ev.u.del_flashnode.host_no = host_no;
	ev.u.del_flashnode.flashnode_idx = flashnode_idx;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
klogin_flashnode(uint64_t transport_handle, uint32_t host_no,
		 uint32_t flashnode_idx)
{
	struct iscsi_uevent ev;
	int rc;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));
	ev.type = ISCSI_UEVENT_LOGIN_FLASHNODE;
	ev.transport_handle = transport_handle;
	ev.u.login_flashnode.host_no = host_no;
	ev.u.login_flashnode.flashnode_idx = flashnode_idx;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
klogout_flashnode(uint64_t transport_handle, uint32_t host_no,
		  uint32_t flashnode_idx)
{
	struct iscsi_uevent ev;
	int rc;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));
	ev.type = ISCSI_UEVENT_LOGOUT_FLASHNODE;
	ev.transport_handle = transport_handle;
	ev.u.logout_flashnode.host_no = host_no;
	ev.u.logout_flashnode.flashnode_idx = flashnode_idx;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int
klogout_flashnode_sid(uint64_t transport_handle, uint32_t host_no,
		      uint32_t sid)
{
	struct iscsi_uevent ev;
	int rc;
	struct iovec iov[2];

	log_debug(7, "in %s", __FUNCTION__);

	memset(&ev, 0, sizeof(struct iscsi_uevent));
	ev.type = ISCSI_UEVENT_LOGOUT_FLASHNODE_SID;
	ev.transport_handle = transport_handle;
	ev.u.logout_flashnode_sid.host_no = host_no;
	ev.u.logout_flashnode_sid.sid = sid;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	return 0;
}

static int kget_host_stats(uint64_t transport_handle, uint32_t host_no,
		     char *host_stats)
{
	int rc = 0;
	int ev_size;
	struct iscsi_uevent ev;
	struct iovec iov[2];
	char nlm_ev[NLMSG_SPACE(sizeof(struct iscsi_uevent))];
	struct nlmsghdr *nlh;

	memset(&ev, 0, sizeof(struct iscsi_uevent));

	ev.type = ISCSI_UEVENT_GET_HOST_STATS;
	ev.transport_handle = transport_handle;
	ev.u.get_host_stats.host_no = host_no;

	iov[1].iov_base = &ev;
	iov[1].iov_len = sizeof(ev);
	rc = __kipc_call(iov, 2);
	if (rc < 0)
		return rc;

	if ((rc = nl_read(ctrl_fd, nlm_ev,
			  NLMSG_SPACE(sizeof(struct iscsi_uevent)),
			  MSG_PEEK)) < 0) {
		log_error("can not read nlm_ev, error %d", rc);
		return rc;
	}

	nlh = (struct nlmsghdr *)nlm_ev;
	ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));

	if ((rc = nlpayload_read(ctrl_fd, (void *)host_stats,
				 ev_size, 0)) < 0) {
		log_error("can not read from NL socket, error %d", rc);
		return rc;
	}

	return rc;
}


static void drop_data(struct nlmsghdr *nlh)
{
	int ev_size;

	ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));
	nlpayload_read(ctrl_fd, NULL, ev_size, 0);
}

static int ctldev_handle(void)
{
	int rc, ev_size;
	struct iscsi_uevent *ev;
	iscsi_session_t *session = NULL;
	iscsi_conn_t *conn = NULL;
	char nlm_ev[NLMSG_SPACE(sizeof(struct iscsi_uevent))];
	struct nlmsghdr *nlh;
	struct iscsi_ev_context *ev_context;
	uint32_t sid = 0, cid = 0;

	log_debug(7, "in %s", __FUNCTION__);

	if ((rc = nl_read(ctrl_fd, nlm_ev,
		NLMSG_SPACE(sizeof(struct iscsi_uevent)), MSG_PEEK)) < 0) {
		log_error("can not read nlm_ev, error %d", rc);
		return rc;
	}
	nlh = (struct nlmsghdr *)nlm_ev;
	ev = (struct iscsi_uevent *)NLMSG_DATA(nlm_ev);

	log_debug(7, "%s got event type %u", __FUNCTION__, ev->type);
	/* drivers like qla4xxx can be inserted after iscsid is started */
	switch (ev->type) {
	case ISCSI_KEVENT_CREATE_SESSION:
	/* old kernels sent ISCSI_UEVENT_CREATE_SESSION on creation */
	case ISCSI_UEVENT_CREATE_SESSION:
		drop_data(nlh);
		if (!ipc_ev_clbk)
			return 0;

		if (ipc_ev_clbk->create_session)
			ipc_ev_clbk->create_session(ev->r.c_session_ret.host_no,
						    ev->r.c_session_ret.sid);
		return 0;
	case ISCSI_KEVENT_DESTROY_SESSION:
		drop_data(nlh);
		if (!ipc_ev_clbk)
			return 0;

		if (ipc_ev_clbk->destroy_session)
			ipc_ev_clbk->destroy_session(ev->r.d_session.host_no,
						     ev->r.d_session.sid);
		return 0;
	case ISCSI_KEVENT_RECV_PDU:
		sid = ev->r.recv_req.sid;
		cid = ev->r.recv_req.cid;
		break;
	case ISCSI_KEVENT_CONN_ERROR:
		sid = ev->r.connerror.sid;
		cid = ev->r.connerror.cid;
		break;
	case ISCSI_KEVENT_CONN_LOGIN_STATE:
		sid = ev->r.conn_login.sid;
		cid = ev->r.conn_login.cid;
		break;
	case ISCSI_KEVENT_UNBIND_SESSION:
		sid = ev->r.unbind_session.sid;
		/* session wide event so cid is 0 */
		cid = 0;
		break;
	case ISCSI_KEVENT_HOST_EVENT:
		switch (ev->r.host_event.code) {
		case ISCSI_EVENT_LINKUP:
			log_warning("Host%u: Link Up.",
				    ev->r.host_event.host_no);
			break;
		case ISCSI_EVENT_LINKDOWN:
			log_warning("Host%u: Link Down.",
				    ev->r.host_event.host_no);
			break;
		default:
			log_debug(7, "Host%u: Unknown host event: %u.",
				  ev->r.host_event.host_no,
				  ev->r.host_event.code);
		}

		drop_data(nlh);
		return 0;
	case ISCSI_KEVENT_PING_COMP:
		ping_event.host_no = ev->r.ping_comp.host_no;
		ping_event.pid = ev->r.ping_comp.pid;
		ping_event.status = ev->r.ping_comp.status;
		ping_event.active = 1;

		drop_data(nlh);
		return 0;
	default:
		if ((ev->type > ISCSI_UEVENT_MAX && ev->type < KEVENT_BASE) ||
		    (ev->type > ISCSI_KEVENT_MAX))
			log_error("Unknown kernel event %d. You may want to "
				  " upgrade your iscsi tools.", ev->type);
		else
			/*
			 * If another app is using the interface we might
			 * see their
			 * stuff. Just drop it.
			 */
			log_debug(7, "Got unknown event %d. Dropping.",
				  ev->type);
		drop_data(nlh);
		return 0;
	}

	/* verify connection */
	session = session_find_by_sid(sid);
	if (!session) {
		/*
		 * this can happen normally when other apps are using the
		 * nl interface.
		 */
		log_debug(1, "Could not verify connection %d:%d. Dropping "
			   "event.", sid, cid);
		drop_data(nlh);
		return -ENXIO;
	}
	conn = &session->conn[0];

	ev_size = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));

	ev_context = ipc_ev_clbk->get_ev_context(conn, ev_size);
	if (!ev_context) {
		log_error("Can not allocate memory for receive context.");
		drop_data(nlh);
		return -ENOMEM;
	}

	log_debug(6, "message real length is %d bytes, recv_handle %p",
		nlh->nlmsg_len, ev_context->data);

	if ((rc = nlpayload_read(ctrl_fd, ev_context->data,
				ev_size, 0)) < 0) {
		ipc_ev_clbk->put_ev_context(ev_context);
		log_error("can not read from NL socket, error %d", rc);
		/* retry later */
		return rc;
	}

	/*
	 * we sched these events because the handlers could call back
	 * into ctldev_handle
	 */
	switch (ev->type) {
	case ISCSI_KEVENT_RECV_PDU:
		rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0,
						   EV_CONN_RECV_PDU);
		break;
	case ISCSI_KEVENT_CONN_ERROR:
		memcpy(ev_context->data, &ev->r.connerror.error,
			sizeof(ev->r.connerror.error));
		rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0,
						   EV_CONN_ERROR);
		break;
	case ISCSI_KEVENT_CONN_LOGIN_STATE:
		memcpy(ev_context->data, &ev->r.conn_login.state,
			sizeof(ev->r.conn_login.state));
		rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0,
						   EV_CONN_LOGIN);
		break;
	case ISCSI_KEVENT_UNBIND_SESSION:
		rc = ipc_ev_clbk->sched_ev_context(ev_context, conn, 0,
						   EV_CONN_STOP);
		break;
	default:
		ipc_ev_clbk->put_ev_context(ev_context);
		log_error("unknown kernel event %d", ev->type);
		return -EEXIST;
	}

	if (rc)
		ipc_ev_clbk->put_ev_context(ev_context);
	return rc;
}

static int
ctldev_open(void)
{
	log_debug(7, "in %s", __FUNCTION__);

	nlm_sendbuf = calloc(1, NLM_BUF_DEFAULT_MAX);
	if (!nlm_sendbuf) {
		log_error("can not allocate nlm_sendbuf");
		return -1;
	}

	nlm_recvbuf = calloc(1, NLM_BUF_DEFAULT_MAX);
	if (!nlm_recvbuf) {
		log_error("can not allocate nlm_recvbuf");
		goto free_nlm_sendbuf;
	}

	pdu_sendbuf = calloc(1, PDU_SENDBUF_DEFAULT_MAX);
	if (!pdu_sendbuf) {
		log_error("can not allocate nlm_sendbuf");
		goto free_nlm_recvbuf;
	}

	setparam_buf = calloc(1, NLM_SETPARAM_DEFAULT_MAX);
	if (!setparam_buf) {
		log_error("can not allocate setparam_buf");
		goto free_pdu_sendbuf;
	}

	ctrl_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ISCSI);
	if (ctrl_fd < 0) {
		log_error("can not create NETLINK_ISCSI socket [%s]",
		          strerror(errno));
		goto free_setparam_buf;
	}

	memset(&src_addr, 0, sizeof(src_addr));
	src_addr.nl_family = AF_NETLINK;
	src_addr.nl_pid = getpid();
	src_addr.nl_groups = 1;
	if (bind(ctrl_fd, (struct sockaddr *)&src_addr, sizeof(src_addr))) {
		log_error("can not bind NETLINK_ISCSI socket [%s]",
		          strerror(errno));
		goto close_socket;
	}

	memset(&dest_addr, 0, sizeof(dest_addr));
	dest_addr.nl_family = AF_NETLINK;
	dest_addr.nl_pid = 0; /* kernel */
	dest_addr.nl_groups = 0; /* unicast */

	log_debug(7, "created NETLINK_ISCSI socket...");

	return ctrl_fd;

close_socket:
	close(ctrl_fd);
free_setparam_buf:
	free(setparam_buf);
free_pdu_sendbuf:
	free(pdu_sendbuf);
free_nlm_recvbuf:
	free(nlm_recvbuf);
free_nlm_sendbuf:
	free(nlm_sendbuf);
	return -1;
}

static void
ctldev_close(void)
{
	log_debug(7, "in %s", __FUNCTION__);

	if (ctrl_fd >= 0)
		close(ctrl_fd);
	free(setparam_buf);
	free(pdu_sendbuf);
	free(nlm_recvbuf);
	free(nlm_sendbuf);
}

struct iscsi_ipc nl_ipc = {
	.name                   = "Open-iSCSI Kernel IPC/NETLINK v.1",
	.ctldev_bufmax		= NLM_BUF_DEFAULT_MAX,
	.ctldev_open		= ctldev_open,
	.ctldev_close		= ctldev_close,
	.ctldev_handle		= ctldev_handle,
	.sendtargets		= ksendtargets,
	.create_session         = kcreate_session,
	.destroy_session        = kdestroy_session,
	.unbind_session		= kunbind_session,
	.create_conn            = kcreate_conn,
	.destroy_conn           = kdestroy_conn,
	.bind_conn              = kbind_conn,
	.set_param              = kset_param,
	.set_host_param		= kset_host_param,
	.get_param              = NULL,
	.start_conn             = kstart_conn,
	.stop_conn              = kstop_conn,
	.get_stats		= kget_stats,
	.writev			= kwritev,
	.send_pdu_begin         = ksend_pdu_begin,
	.send_pdu_end           = ksend_pdu_end,
	.read			= kread,
	.recv_pdu_begin         = krecv_pdu_begin,
	.recv_pdu_end           = krecv_pdu_end,
	.set_net_config         = kset_net_config,
	.recv_conn_state        = krecv_conn_state,
	.exec_ping		= kexec_ping,
	.get_chap		= kget_chap,
	.set_chap		= kset_chap,
	.delete_chap		= kdelete_chap,
	.set_flash_node_params	= kset_flashnode_params,
	.new_flash_node		= knew_flashnode,
	.del_flash_node		= kdel_flashnode,
	.login_flash_node	= klogin_flashnode,
	.logout_flash_node	= klogout_flashnode,
	.logout_flash_node_sid	= klogout_flashnode_sid,
	.get_host_stats		= kget_host_stats,
};
struct iscsi_ipc *ipc = &nl_ipc;

void ipc_register_ev_callback(struct iscsi_ipc_ev_clbk *ev_clbk)
{
	ipc_ev_clbk = ev_clbk;
}