summaryrefslogtreecommitdiffstats
path: root/src/server/iscsi.c
blob: 892172e097a4289eb9610755c475c78bbd1e2cd3 (plain) (blame)
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
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
/*
 * This file is part of the Distributed Network Block Device 3
 *
 * Copyright(c) 2025 Sebastian Vater <sebastian.vater@rz.uni-freiburg.de>
 *
 * This file may be licensed under the terms of the
 * GNU General Public License Version 2 (the ``GPL'').
 *
 * Software distributed under the License is distributed
 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
 * express or implied. See the GPL for the specific language
 * governing rights and limitations.
 *
 * You should have received a copy of the GPL along with this
 * program. If not, go to http://www.gnu.org/licenses/gpl.html
 * or write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <dnbd3/config.h>
#include <dnbd3/shared/log.h>
#include <dnbd3/shared/sockhelper.h>
#include <dnbd3/types.h>
#include <pthread.h>
#include <unistd.h>

#include "sendfile.h"
#include "globals.h"
#include "helper.h"
#include "image.h"
#include "iscsi.h"
#include "uplink.h"
#include "reference.h"

#define ISCSI_DEFAULT_LUN 0
#define ISCSI_DEFAULT_PROTOCOL_ID 1
#define ISCSI_DEFAULT_DEVICE_ID 1
#define ISCSI_DEFAULT_QUEUE_DEPTH 16

#include <dnbd3/afl.h>

/**
 * @file iscsi.c
 * @author Sebastian Vater
 * @date 16 Jul 2025
 * @brief iSCSI implementation for DNBD3.
 *
 * This file contains the iSCSI implementation according to
 * RFC7143 for dnbd3-server.\n
 * All server-side network sending and client-side network
 * receiving code is done here.\n
 * @see https://www.rfc-editor.org/rfc/rfc7143
 */

//#define malloc(x) (rand() % 100 == 0 ? NULL : malloc(x))

// Use for stack-allocated iscsi_pdu
#define CLEANUP_PDU __attribute__((cleanup(iscsi_connection_pdu_destroy)))

static int iscsi_scsi_emu_block_process(iscsi_scsi_task *scsi_task);

static int iscsi_scsi_emu_primary_process(iscsi_scsi_task *scsi_task);


static void iscsi_scsi_task_init(iscsi_scsi_task *scsi_task); // Initializes a SCSI task

static void iscsi_scsi_task_xfer_complete(iscsi_connection *conn, iscsi_scsi_task *scsi_task, iscsi_pdu *request_pdu); // Callback function when an iSCSI SCSI task completed the data transfer

static void iscsi_scsi_task_lun_process_none(iscsi_scsi_task *scsi_task); // Processes a iSCSI SCSI task with no LUN identifier


static uint64_t iscsi_scsi_lun_get_from_scsi(const int lun_id); // Converts an internal representation of a LUN identifier to an iSCSI LUN required for packet data
static int iscsi_scsi_lun_get_from_iscsi(const uint64_t lun); // Converts an iSCSI LUN from packet data to internal SCSI LUN identifier

static int iscsi_scsi_emu_io_blocks_read(iscsi_scsi_task *scsi_task,  dnbd3_image_t *image, const uint64_t offset_blocks, const uint64_t num_blocks); // Reads a number of blocks from a block offset of a DNBD3 image to a specified buffer

static void iscsi_strcpy_pad(char *dst, const char *src, const size_t size, const int pad); // Copies a string with additional padding character to fill in a specified size

static iscsi_task *iscsi_task_create(iscsi_connection *conn); // Allocates and initializes an iSCSI task structure
static void iscsi_task_destroy(iscsi_task *task); // Deallocates resources acquired by iscsi_task_create

static uint64_t iscsi_target_node_wwn_get(const uint8_t *name); // Calculates the WWN using 64-bit IEEE Extended NAA for a name

static iscsi_session *iscsi_session_create(const int type); // Creates and initializes an iSCSI session
static void iscsi_session_destroy(iscsi_session *session); // Deallocates all resources acquired by iscsi_session_create


static iscsi_connection *iscsi_connection_create(dnbd3_client_t *client); // Creates data structure for an iSCSI connection from iSCSI portal and TCP/IP socket
static void iscsi_connection_destroy(iscsi_connection *conn); // Deallocates all resources acquired by iscsi_connection_create

static void iscsi_connection_login_response_reject(iscsi_pdu *login_response_pdu, const iscsi_pdu *pdu); // Initializes a rejecting login response packet
static bool iscsi_connection_pdu_init(iscsi_pdu *pdu, const uint32_t ds_len, bool no_ds_alloc);
static void iscsi_connection_pdu_destroy(iscsi_pdu *pdu);

static iscsi_bhs_packet *iscsi_connection_pdu_resize(iscsi_pdu *pdu, const uint ahs_len,  const uint32_t ds_len); // Appends packet data to an iSCSI PDU structure used by connections

static bool iscsi_connection_pdu_write(iscsi_connection *conn, iscsi_pdu *pdu);

static int iscsi_connection_handle_reject(iscsi_connection *conn, iscsi_pdu *pdu, int reason_code);


/**
 * @brief Copies a string with additional padding character to fill in a specified size.
 *
 * This function does NOT pad, but truncates
 * instead if the string length equals or is
 * larger than the maximum allowed size.
 *
 * @param[in] dst Pointer to destination string to copy
 * with padding and may NOT be NULL, so be
 * careful.
 * @param[in] src Pointer to string for copying. NULL
 * is NOT allowed here, take caution.
 * @param[in] size Total size in bytes for padding.
 * @param[in] pad Padding character to use.
 */
static void iscsi_strcpy_pad(char *dst, const char *src, const size_t size, const int pad)
{
	const size_t len = strlen( src );

	if ( len < size ) {
		memcpy( dst, src, len );
		memset( (dst + len), pad, (size - len) );
	} else {
		memcpy( dst, src, size );
	}
}

/**
 * @brief Parses a string representation of an integer and assigns the result to
 * the provided destination variable, ensuring it is within valid range.
 *
 * This function checks for duplicate entries, empty strings, non-numeric
 * characters, and out-of-range values. Logs debug messages for invalid or
 * duplicate inputs and ensures values are clamped between 0 and INT_MAX.
 *
 * @param[in] name The name of the key associated with the integer value.
 * Used for logging purposes.
 * @param[in, out] dest Pointer to the destination integer variable where the
 * parsed value will be stored. Must not be NULL. If the pointed
 * value is -1, the parsed value will be assigned; otherwise,
 * the function considers it a duplicate and does not update it.
 * @param[in] src Pointer to the string containing the numeric representation
 * of the value to parse. Must not be NULL or empty.
 */
static void iscsi_copy_kvp_int(const char *name, int *dest, const char *src)
{
	long long res = 0;
	const char *end = NULL;

	if ( *dest != -1 ) {
		logadd( LOG_DEBUG1, "Received duplicate entry for key '%s', ignoring (new: %s, old: %d)", name, src, *dest );
		return;
	}

	if ( *src == '\0' ) {
		logadd( LOG_DEBUG1, "Empty value for numeric option '%s', ignoring", name );
		return;
	}
	res = strtoll( src, (char **)&end, 10 ); // WTF why is the second arg not const char **

	if ( end == NULL ) {
		logadd( LOG_DEBUG1, "base 10 not valid! O.o" );
		return;
	}
	if ( *end != '\0' ) {
		logadd( LOG_DEBUG1, "Invalid non-numeric character in value for '%s': '%c' (0x%02x), ignoring option",
				name, (int)*end, (int)*end );
		return;
	}
	if ( res < 0 ) {
		res = 0;
	} else if ( res > INT_MAX ) {
		res = INT_MAX;
	}
	*dest = (int)res;
}

/**
 * @brief Copies a key-value pair string to the destination if it hasn't been copied already.
 *
 * This function ensures that a key has a single corresponding value by
 * checking if the destination pointer has already been assigned. If assigned,
 * a debug log entry is created, and the new value is ignored.
 *
 * @param[in] name The name of the key being assigned. Used for logging.
 * @param[in,out] dest Pointer to the destination where the string is to be copied.
 * If the destination is already assigned, the function will log and return.
 * @param[in] src Pointer to the source string to be assigned to the destination.
 */
static void iscsi_copy_kvp_str(const char *name, const char **dest, const char *src)
{
	if ( *dest != NULL ) {
		logadd( LOG_DEBUG1, "Received duplicate entry for key '%s', ignoring (new: %s, old: %s)", name, src, *dest );
		return;
	}
	*dest = src;
}

/**
 * @brief Extracts a single text key / value pairs out of an iSCSI packet into a hash map.
 *
 * Parses and extracts a specific key and value pair out of an iSCSI packet
 * data stream amd puts the extracted data into a hash map to be used by
 * the iSCSI implementation.
 *
 * @param[in] key_value_pairs Pointer to hash map containing all related keys and pairs.
 * May NOT be NULL, so take caution.
 * @param[in] packet_data Pointer to key / value pair to be parsed. NULL is
 * an illegal value, so be careful.
 * @param[in] len Length of the remaining packet data.
 * @return Number of bytes used by the extracted key / vair pair or
 * a negative value in case of an error. This can be used for
 * incrementing the offset to the next key / value pair.
 */
static int iscsi_parse_text_key_value_pair(iscsi_negotiation_kvp *key_value_pairs, const char *packet_data, const uint32_t len)
{
	int key_val_len = (int) strnlen( packet_data, len );
	const char *key_end = memchr( packet_data, '=', key_val_len );

	if ( key_val_len == (int)len ) {
		logadd( LOG_DEBUG1, "iscsi_parse_text_key_value_pair: Final key/value pair not null-terminated, not spec compliant, aborting" );
		return -1;
	}
	// Account for the trailing nullchar (for return value), which we also consumed
	key_val_len++;

	if ( key_end == NULL ) {
		logadd( LOG_DEBUG1, "iscsi_parse_text_key_value_pair: Key/value separator '=' not found, ignoring" );
		return key_val_len;
	}

	const uint key_len = (uint) (key_end - packet_data);
	const uint val_len = (uint) (key_val_len - key_len - 1);

	if ( key_len == 0U ) {
		logadd( LOG_DEBUG1, "iscsi_parse_text_key_value_pair: Empty key, not allowed according to iSCSI specs, ignoring" );
		return key_val_len;
	}

	if ( key_len > ISCSI_TEXT_KEY_MAX_LEN ) {
		logadd( LOG_DEBUG1, "iscsi_parse_text_key_value_pair: Key is too long (max %d bytes), ignoring", ISCSI_TEXT_KEY_MAX_LEN );
		return key_val_len;
	}

	if ( val_len > ISCSI_TEXT_VALUE_MAX_LEN ) {
		logadd( LOG_DEBUG1, "iscsi_parse_text_key_value_pair: Value for '%.*s' is too long (max %d bytes), ignoring",
				(int)key_len, packet_data, ISCSI_TEXT_VALUE_MAX_LEN );
		return key_val_len;
	}

#define COPY_KVP(type, key) \
	else if ( strncmp( packet_data, #key, key_len ) == 0 ) iscsi_copy_kvp_ ## type ( #key, &key_value_pairs->key, key_end + 1 )

	if ( 0 ) {}
	COPY_KVP( int, MaxRecvDataSegmentLength );
	COPY_KVP( int, MaxBurstLength );
	COPY_KVP( int, FirstBurstLength );
	COPY_KVP( int, MaxConnections );
	COPY_KVP( int, ErrorRecoveryLevel );
	COPY_KVP( str, SessionType );
	COPY_KVP( str, AuthMethod );
	COPY_KVP( str, SendTargets );
	COPY_KVP( str, HeaderDigest );
	COPY_KVP( str, DataDigest );
	COPY_KVP( str, InitiatorName );
	COPY_KVP( str, TargetName );
	else {
		logadd( LOG_DEBUG1, "iscsi_parse_text_key_value_pair: Unknown option: '%.*s'", (int)key_len, packet_data );
	}

#undef COPY_KVP

	return (int)key_val_len;
}

/**
 * @brief Extracts all text key / value pairs out of an iSCSI packet into a hash map.
 *
 * Parses and extracts all key and value pairs out of iSCSI packet
 * data amd puts the extracted data into a hash map to be used by
 * the iSCSI implementation.
 *
 * @param[in] pairs struct to write all key-value-pair options from packet to
 * extracted keys and pairs. May NOT be NULL, so take caution.
 * @param[in] packet_data Pointer to first key and value pair to
 * be parsed. NULL is an illegal value here, so be careful.
 * @param[in] len Length of the remaining packet data.
 * @retval -1 An error occured during parsing key.
 * @retval 0 Key and value pair was parsed successfully and was added to
 * kvp struct.
 */
static int iscsi_parse_login_key_value_pairs(iscsi_negotiation_kvp *pairs, const uint8_t *packet_data, uint len)
{
	memset( pairs, -1 , sizeof(*pairs) );
	pairs->SessionType = NULL;
	pairs->AuthMethod = NULL;
	pairs->SendTargets = NULL;
	pairs->HeaderDigest = NULL;
	pairs->DataDigest = NULL;
	pairs->InitiatorName = NULL;
	pairs->TargetName = NULL;

	if ( len == 0U )
		return 0; // iSCSI specs don't allow zero length

	int offset = 0;

	while ( ((uint) offset < len) && (packet_data[offset] != '\0') ) {
		const int rc = iscsi_parse_text_key_value_pair( pairs, (const char *)(packet_data + offset), (len - offset) );

		if ( rc <= 0 )
			return -1;

		offset += rc;
	}

	return 0;
}

/**
 * @brief Allocates and initializes an iSCSI task structure.
 *
 * This function also initializes the underlying
 * SCSI task structure with the transfer complete
 * callback function.\n
 * If a parent task is specified, SCSI data
 * is copied over from it.
 *
 * @param[in] conn Pointer to iSCSI connection to associate
 * the task with. May NOT be NULL, so take
 * caution.
 * @return Pointer to iSCSI task structure or NULL
 * in case of an error (memory exhaustion).
 */
static iscsi_task *iscsi_task_create(iscsi_connection *conn)
{
	iscsi_task *task = malloc( sizeof(struct iscsi_task) );

	if ( task == NULL ) {
		logadd( LOG_ERROR, "iscsi_task_create: Out of memory while allocating iSCSI task" );

		return NULL;
	}

	task->len               = 0UL;
	task->lun_id            = 0;
	task->init_task_tag     = 0UL;
	task->target_xfer_tag   = 0UL;

	iscsi_scsi_task_init( &task->scsi_task );
	task->scsi_task.connection = conn;

	return task;
}

/**
 * @brief Deallocates resources acquired by iscsi_task_create.
 *
 * This function also frees the embedded SCSI task.
 *
 * @param[in] task Pointer to iSCSI task to deallocate. If
 * set to NULL, this function does nothing.
 */
static void iscsi_task_destroy(iscsi_task *task)
{
	if ( task == NULL )
		return;

	if ( task->scsi_task.must_free ) {
		free( task->scsi_task.buf );
	}
	free( task->scsi_task.sense_data );
	free( task );
}

/**
 * @brief Sends a single iSCSI SCSI Data In packet to the client.
 *
 * This function reads the data from the
 * associated DNBD3 image as well and sends
 * it to the initiator.
 *
 * @param[in] conn Pointer to iSCSI connection for which the
 * packet should be sent for. May NOT be
 * NULL, so be careful.
 * @param[in] task Pointer to iSCSI task which handles the
 * actual SCSI packet data. NULL is NOT
 * allowed here, so take caution.
 * @param[in] pos Offset of data to be sent in bytes.
 * @param[in] len Length of data to be sent in bytes
 * @param[in] res_cnt Residual Count.
 * @param[in] data_sn Data Sequence Number (DataSN).
 * @param[in] flags Flags for this data packet.
 * @param[in] immediate whether immediate bit was set in this request
 * @return true success, false error
 */
static bool iscsi_scsi_data_in_send(iscsi_connection *conn, iscsi_task *task,
	const uint32_t pos, const uint32_t len, const uint32_t res_cnt, const uint32_t data_sn, const int8_t flags, bool immediate)
{
	iscsi_pdu CLEANUP_PDU response_pdu;
	if ( !iscsi_connection_pdu_init( &response_pdu, len, true ) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	iscsi_scsi_data_in_response_packet *scsi_data_in_pkt = (iscsi_scsi_data_in_response_packet *) response_pdu.bhs_pkt;

	scsi_data_in_pkt->opcode   = ISCSI_OPCODE_SERVER_SCSI_DATA_IN;
	scsi_data_in_pkt->flags    = (flags & ~(ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_RES_UNDERFLOW | ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_RES_OVERFLOW));
	scsi_data_in_pkt->reserved = 0U;

	if ( (flags & ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_STATUS) != 0 ) {
		if ( (flags & ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_FINAL) != 0 ) {
			scsi_data_in_pkt->flags |= (flags & (ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_RES_UNDERFLOW | ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_RES_OVERFLOW));

			if ( !immediate ) {
				conn->session->max_cmd_sn++;
			}

			iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->res_cnt, res_cnt );
		} else {
			scsi_data_in_pkt->res_cnt = 0UL;
		}

		scsi_data_in_pkt->status = task->scsi_task.status;
		iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->stat_sn, conn->stat_sn++ );
	} else {
		scsi_data_in_pkt->status  = 0U;
		scsi_data_in_pkt->stat_sn = 0UL;
		scsi_data_in_pkt->res_cnt = 0UL;
	}

	iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->total_ahs_len, len ); // TotalAHSLength is always 0 and DataSegmentLength is 24-bit, so write in one step.
	scsi_data_in_pkt->lun             = 0ULL;
	iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->init_task_tag, task->init_task_tag );
	scsi_data_in_pkt->target_xfer_tag = 0xFFFFFFFFUL; // Minus one does not require endianess conversion
	iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->exp_cmd_sn, conn->session->exp_cmd_sn );
	iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->max_cmd_sn, conn->session->max_cmd_sn );
	iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->data_sn, data_sn );

	iscsi_put_be32( (uint8_t *) &scsi_data_in_pkt->buf_offset, pos );

	iscsi_connection_pdu_write( conn, &response_pdu );

	if ( task->scsi_task.buf != NULL ) {
		if ( !sock_sendAll( conn->client->sock, (task->scsi_task.buf + pos), len, ISCSI_CONNECT_SOCKET_WRITE_RETRIES ) )
			return false;
		const size_t padding = ISCSI_ALIGN( len, ISCSI_ALIGN_SIZE ) - len;
		if ( padding != 0 ) {
			if ( !sock_sendPadding( conn->client->sock, padding ) )
				return false;
		}
	} else {
		const uint64_t off = task->scsi_task.file_offset + pos;
		size_t padding = 0;
		size_t realBytes = len;
		if ( off >= conn->client->image->realFilesize ) {
			padding = len;
			realBytes = 0;
		} else if ( off + len > conn->client->image->realFilesize ) {
			padding = ( off + len ) - conn->client->image->realFilesize;
			realBytes -= padding;
		}
		bool ret = sendfile_all( conn->client->image->readFd, conn->client->sock,
			(off_t)off, realBytes );
		if ( !ret )
			return false;
		if ( padding > 0 ) {
			if ( !sock_sendPadding( conn->client->sock, padding ) )
				return false;
		}
	}

	return true;
}

/**
 * @brief Handles iSCSI task read (incoming) data.
 *
 * This function handles iSCSI incoming data
 * read buffer for both processed and
 * unprocessed tasks.
 *
 * @param[in] conn Pointer to iSCSI connection of which the
 * incoming data should be handled, may NOT be
 * NULL, so be careful.
 * @param[in] task Pointer to iSCSI task for handling
 * the incoming data. NULL is NOT allowed here,
 * take caution.
 * @param immediate
 * @return 0 on successful incoming transfer handling,
 * a negative error code otherwise.
 */
static int iscsi_task_xfer_scsi_data_in(iscsi_connection *conn, iscsi_task *task, bool immediate)
{
	if ( task->scsi_task.status != ISCSI_SCSI_STATUS_GOOD )
		return 0;

	const uint32_t expected_len = task->scsi_task.exp_xfer_len;
	uint32_t xfer_len           = task->scsi_task.len;
	uint32_t res_cnt            = 0UL;
	int8_t flags                = 0;

	if ( expected_len < xfer_len ) {
		res_cnt  = (xfer_len - expected_len);
		xfer_len = expected_len;
		flags   |= ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_RES_OVERFLOW;
	} else if ( expected_len > xfer_len ) {
		res_cnt  = (expected_len - xfer_len);
		flags   |= ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_RES_UNDERFLOW;
	}
	if ( xfer_len == 0UL )
		return 0;

	uint32_t data_sn                 = 0;
	uint32_t max_burst_offset        = 0UL;
	// Max burst length = total length of payload in all PDUs
	const uint32_t max_burst_len     = conn->session->opts.MaxBurstLength;
	// Max recv segment length = total length of one individual PDU
	const uint32_t seg_len      = conn->session->opts.MaxRecvDataSegmentLength;
	const uint32_t data_in_seq_count = ((xfer_len - 1) / max_burst_len) + 1;
	int8_t status                    = 0;

	for ( uint32_t i = 0UL; i < data_in_seq_count; i++ ) {
		uint32_t seq_end = (max_burst_offset + max_burst_len);

		if ( seq_end > xfer_len )
			seq_end = xfer_len;

		for ( uint32_t offset = max_burst_offset; offset < seq_end; offset += seg_len ) {
			uint32_t len = (seq_end - offset);

			if ( len > seg_len )
				len = seg_len;

			flags &= (int8_t) ~(ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_STATUS | ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_FINAL);

			if ( (offset + len) == seq_end ) {
				flags |= (int8_t) ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_FINAL;

				if ( (task->scsi_task.sense_data_len == 0U) && ((offset + len) == xfer_len) ) {
					flags  |= (int8_t) ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_STATUS;
					status |= flags;
				}
			}

			if ( !iscsi_scsi_data_in_send( conn, task, offset, len, res_cnt, data_sn, flags, immediate ) )
				return -1;

			data_sn++;
		}

		max_burst_offset += max_burst_len;
	}

	return (status & ISCSI_SCSI_DATA_IN_RESPONSE_FLAGS_STATUS);
}

/**
 * @brief Initializes a SCSI task.
 *
 * @param[in] scsi_task Pointer to SCSI task. This
 * may NOT be NULL, so be careful.
 */
static void iscsi_scsi_task_init(iscsi_scsi_task *scsi_task)
{
	scsi_task->cdb                    = NULL;
	scsi_task->sense_data             = NULL;
	scsi_task->buf                    = NULL;
	scsi_task->must_free              = true;
	scsi_task->len                    = 0UL;
	scsi_task->id                     = 0ULL;
	scsi_task->is_read                = false;
	scsi_task->is_write               = false;
	scsi_task->exp_xfer_len           = 0UL;
	scsi_task->sense_data_len         = 0U;
	scsi_task->status                 = ISCSI_SCSI_STATUS_GOOD;
}

/**
 * @brief Callback function when an iSCSI SCSI task completed the data transfer.
 *
 * This function post-processes a task upon
 * finish of data transfer.
 *
 * @param[in] scsi_task Pointer to iSCSI SCSI task which finished
 * the data transfer and may NOT be NULL,
 * so be careful.
 * @param request_pdu
 */
static void iscsi_scsi_task_xfer_complete(iscsi_connection *conn, iscsi_scsi_task *scsi_task, iscsi_pdu *request_pdu)
{
	iscsi_task *task = container_of( scsi_task, iscsi_task, scsi_task );

	iscsi_scsi_cmd_packet *scsi_cmd_pkt = (iscsi_scsi_cmd_packet *) request_pdu->bhs_pkt;

	if ( (scsi_cmd_pkt->flags_task & ISCSI_SCSI_CMD_FLAGS_TASK_READ) != 0 ) {
		const int rc = iscsi_task_xfer_scsi_data_in( conn, task, (scsi_cmd_pkt->opcode & ISCSI_OPCODE_FLAGS_IMMEDIATE) != 0 );

		if ( rc > 0 )
			return;
	}

	const uint32_t ds_len   = (scsi_task->sense_data_len != 0U)
		? (scsi_task->sense_data_len + offsetof(struct iscsi_scsi_ds_cmd_data, sense_data))
		: 0UL;

	iscsi_pdu CLEANUP_PDU response_pdu;
	if ( !iscsi_connection_pdu_init( &response_pdu, ds_len, false ) )
		return;

	iscsi_scsi_response_packet *scsi_response_pkt = (iscsi_scsi_response_packet *) response_pdu.bhs_pkt;

	if ( scsi_task->sense_data_len != 0U ) {
		iscsi_scsi_ds_cmd_data *ds_cmd_data_pkt = response_pdu.ds_cmd_data;

		iscsi_put_be16( (uint8_t *) &ds_cmd_data_pkt->len, scsi_task->sense_data_len );
		memcpy( ds_cmd_data_pkt->sense_data, scsi_task->sense_data, scsi_task->sense_data_len );

		iscsi_put_be32( (uint8_t *) &scsi_response_pkt->total_ahs_len, ds_len ); // TotalAHSLength is always 0 and DataSegmentLength is 24-bit, so write in one step.
	} else {
		*(uint32_t *) &scsi_response_pkt->total_ahs_len = 0UL; // TotalAHSLength and DataSegmentLength are always 0, so write in one step.
	}

	scsi_response_pkt->opcode   = ISCSI_OPCODE_SERVER_SCSI_RESPONSE;
	scsi_response_pkt->flags    = -0x80;
	scsi_response_pkt->response = ISCSI_SCSI_RESPONSE_CODE_OK;
	const uint32_t exp_xfer_len             = scsi_task->exp_xfer_len;

	if ( (exp_xfer_len != 0UL) && (scsi_task->status == ISCSI_SCSI_STATUS_GOOD) ) {
		const uint32_t resp_len             = ds_len;

		if ( resp_len < exp_xfer_len ) {
			const uint32_t res_cnt = (exp_xfer_len - resp_len);

			scsi_response_pkt->flags |= ISCSI_SCSI_RESPONSE_FLAGS_RES_UNDERFLOW;
			iscsi_put_be32( (uint8_t *) &scsi_response_pkt->res_cnt, res_cnt );
		} else if ( resp_len > exp_xfer_len ) {
			const uint32_t res_cnt = (resp_len - exp_xfer_len);

			scsi_response_pkt->flags |= ISCSI_SCSI_RESPONSE_FLAGS_RES_OVERFLOW;
			iscsi_put_be32( (uint8_t *) &scsi_response_pkt->res_cnt, res_cnt );
		} else {
			scsi_response_pkt->res_cnt = 0UL;
		}
	} else {
		scsi_response_pkt->res_cnt = 0UL;
	}

	scsi_response_pkt->status    = scsi_task->status;
	scsi_response_pkt->reserved  = 0ULL;
	iscsi_put_be32( (uint8_t *) &scsi_response_pkt->init_task_tag, task->init_task_tag );
	scsi_response_pkt->snack_tag = 0UL;
	iscsi_put_be32( (uint8_t *) &scsi_response_pkt->stat_sn, conn->stat_sn++ );

	if ( (scsi_cmd_pkt->opcode & ISCSI_OPCODE_FLAGS_IMMEDIATE) == 0 )
		conn->session->max_cmd_sn++;

	iscsi_put_be32( (uint8_t *) &scsi_response_pkt->exp_cmd_sn, conn->session->exp_cmd_sn );
	iscsi_put_be32( (uint8_t *) &scsi_response_pkt->max_cmd_sn, conn->session->max_cmd_sn );
	scsi_response_pkt->exp_data_sn       = 0UL;
	scsi_response_pkt->bidi_read_res_cnt = 0UL;

	iscsi_connection_pdu_write( conn, &response_pdu );
}

/**
 * @brief Allocates, if necessary and initializes SCSI sense data for check condition status code.
 *
 * This function is invoked whenever additional
 * SCSI sense data for check condition status
 * code is required for sending to the
 * initiator.
 *
 * @param[in] scsi_task Pointer to iSCSI SCSI task to allocate
 * and assign the SCSI check condition status
 * code sense data for. May NOT be NULL, so
 * be careful.
 * @param[in] sense_key Sense Key (SK).
 * @param[in] asc Additional Sense Code (ASC).
 * @param[in] ascq Additional Sense Code Qualifier (ASCQ).
 */
static void iscsi_scsi_task_sense_data_build(iscsi_scsi_task *scsi_task, const uint8_t sense_key, const uint8_t asc, const uint8_t ascq)
{
	iscsi_scsi_sense_data_check_cond_packet *sense_data = (iscsi_scsi_sense_data_check_cond_packet *) scsi_task->sense_data;

	if ( sense_data == NULL ) {
		sense_data = malloc( sizeof(struct iscsi_scsi_sense_data_check_cond_packet) );

		if ( sense_data == NULL ) {
			logadd( LOG_ERROR, "iscsi_scsi_task_sense_data_build: Out of memory allocating iSCSI SCSI conidtion check status code sense data" );

			return;
		}

		scsi_task->sense_data = (iscsi_scsi_sense_data_packet *) sense_data;
	}

	sense_data->sense_data.response_code   = (int8_t) (ISCSI_SCSI_SENSE_DATA_PUT_RESPONSE_CODE(ISCSI_SCSI_SENSE_DATA_RESPONSE_CODE_CURRENT_FMT) | ISCSI_SCSI_SENSE_DATA_RESPONSE_CODE_VALID);
	sense_data->sense_data.reserved        = 0U;
	sense_data->sense_data.sense_key_flags = ISCSI_SCSI_SENSE_DATA_PUT_SENSE_KEY(sense_key);
	sense_data->sense_data.info            = 0UL; // Zero does not require endianess conversion
	sense_data->sense_data.add_len         = (sizeof(struct iscsi_scsi_sense_data_check_cond_packet) - sizeof(struct iscsi_scsi_sense_data_packet));

	sense_data->cmd_spec_info        = 0UL; // Zero does not require endianess conversion
	sense_data->asc                  = asc;
	sense_data->ascq                 = ascq;
	sense_data->field_rep_unit_code  = 0UL;
	sense_data->sense_key_spec_flags = 0U;
	sense_data->sense_key_spec       = 0U; // Zero does not require endianess conversion

	scsi_task->sense_data_len = sizeof(struct iscsi_scsi_sense_data_check_cond_packet);
}

/**
 * @brief Sets an iSCSI SCSI task status code with optional additional details.
 *
 * Sense Key (SK), Additional Sense Code (ASC)
 * and Additional Sense Code Qualifier (ASCQ)
 * are only generated on check condition SCSI
 * status code.
 *
 * @param[in] scsi_task Pointer to iSCSI SCSI task to set the
 * SCSI status and additional details for. May
 * NOT be NULL, so be careful.
 * @param[in] status SCSI status code to be set.
 * @param[in] sense_key Sense Key (SK).
 * @param[in] asc Additional Sense Code (ASC).
 * @param[in] ascq Additional Sense Code Qualifier (ASCQ).
 */
static void iscsi_scsi_task_status_set(iscsi_scsi_task *scsi_task, const uint8_t status, const uint8_t sense_key, const uint8_t asc, const uint8_t ascq)
{
	if ( status == ISCSI_SCSI_STATUS_CHECK_COND )
		iscsi_scsi_task_sense_data_build( scsi_task, sense_key, asc, ascq );

	scsi_task->status = status;
}

/**
 * @brief Processes a iSCSI SCSI task with no LUN identifier.
 *
 * This function only generates a SCSI response
 * if the SCSI command is INQUIRY, otherwise
 * a SCSI error will be generated as specified
 * by the SCSI standard.
 *
 * @param[in] scsi_task Pointer to iSCSI SCSI task to process
 * the task with no LUN identifier for. May NOT
 * be NULL, so be careful.
 */
static void iscsi_scsi_task_lun_process_none(iscsi_scsi_task *scsi_task)
{
	iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ,
		ISCSI_SCSI_ASC_LU_NOT_SUPPORTED, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );
}

/**
 * @brief Converts an internal representation of a LUN identifier to an iSCSI LUN required for packet data.
 *
 * This function needs to be called prior
 * storing the internal SCSI identifier
 * representation in the iSCSI packet.
 *
 * @param[in] lun_id Internal SCSI presentation of LUN
 * identifier to be converted to iSCSI packet data
 * representation.
 * @return iSCSI packet data representation of LUN or
 * 0 in case of an invalid LUN.
 */
static uint64_t iscsi_scsi_lun_get_from_scsi(const int lun_id)
{
	uint64_t iscsi_scsi_lun;

	if ( lun_id < 0x100 )
		iscsi_scsi_lun = (uint64_t) (lun_id & 0xFF) << 48ULL;
	else if ( lun_id < 0x4000 )
		iscsi_scsi_lun = (1ULL << 62ULL) | (uint64_t) (lun_id & 0x3FFF) << 48ULL;
	else
		iscsi_scsi_lun = 0ULL;

	return iscsi_scsi_lun;
}

/**
 * @brief Converts an iSCSI LUN from packet data to internal SCSI LUN identifier.
 *
 * This function needs to be called prior
 * storing the iSCSI packet data
 * representation in the structures
 * requiring an internal SCSI  identifier.
 *
 * @param[in] lun iSCSI packet data LUN to be converted
 * to the internal SCSI LUN identifier
 * representation.
 * @return SCSI identifier representation of iSCSI
 * packet data LUN or 0xFFFF in case of
 * an error.
 */
static int iscsi_scsi_lun_get_from_iscsi(const uint64_t lun)
{
	int lun_id = (int) (lun >> 62ULL) & 0x03;

	if ( lun_id == 0x00 )
		lun_id = (int) (lun >> 48ULL) & 0xFF;
	else if ( lun_id == 0x01 )
		lun_id = (int) (lun >> 48ULL) & 0x3FFF;
	else
		lun_id = 0xFFFF;

	return lun_id;
}

/**
 * @brief Retrieves the number of total logical blocks for a DNBD3 image.
 *
 * This function depends on DNBD3 image
 * properties.
 *
 * @param[in] image Pointer to DNBD3 image to retrieve
 * the logical size from. May NOT be NULL,
 * so be careful.
 * @return The number of total logical blocks.
 */
static inline uint64_t iscsi_scsi_emu_block_get_count(const dnbd3_image_t *image)
{
	return (image->virtualFilesize / ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE);
}


/**
 * @brief Converts offset and length specified by a block size to offset and length in bytes.
 *
 * This function uses bit shifting if
 * the block size is a power of two.
 *
 * @param[out] offset_bytes Pointer where to store the block
 * in bytes. May NOT be NULL, so be
 * careful.
 * @param[in] offset_blocks Offset in blocks.
 * @param[in] num_blocks Number of blocks.
 * @return Number of blocks in bytes.
 */
static uint64_t iscsi_scsi_emu_blocks_to_bytes(uint64_t *offset_bytes, const uint64_t offset_blocks, const uint64_t num_blocks)
{
	*offset_bytes = (offset_blocks * ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE);

	return (num_blocks * ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE);
}

/**
 * @brief Called when data requested via an uplink server has arrived.
 *
 * This function is used to retrieve
 * block data which is NOT locally
 * available.
 *
 * @param[in] data Pointer to related scsi_task. May NOT
 * be NULL, so be careful.
 * @param[in] handle Pointer to destination buffer, as passed to
 * iscsi_scsi_emu_io_block_read().
 * @param[in] start Start of range in bytes.
 * @param[in] length Length of range in bytes, as passed to
 * uplink_request().
 * @param[in] buffer Data for requested range.
 */
static void iscsi_uplink_callback(void *data, uint64_t handle UNUSED, uint64_t start UNUSED, uint32_t length, const char *buffer)
{
	iscsi_scsi_task *scsi_task = (iscsi_scsi_task *) data;

	memcpy( scsi_task->buf, buffer, length );

	pthread_mutex_lock( &scsi_task->uplink_mutex );
	pthread_cond_signal( &scsi_task->uplink_cond );
	pthread_mutex_unlock( &scsi_task->uplink_mutex );
}

/**
 * @brief Reads a number of blocks from a block offset of a DNBD3 image to a specified buffer.
 *
 * This function enqueues the I/O read
 * process which invokes a callback
 * function when the read operation has
 * been finished.
 *
 * @param[in] scsi_task Pointer to iSCSI SCSI task which
 * executes the I/O read operation, may
 * NOT be NULL, so be careful.
 * @param[in] image Pointer to DNBD3 image to read
 * data from and may NOT be NULL, so
 * be careful.
 * @param[in] offset_blocks Offset in blocks to start reading from.
 * @param[in] num_blocks Number of blocks to read.
 * @return 0 on successful operation, a negative
 * error code otherwise.
 */
static int iscsi_scsi_emu_io_blocks_read(iscsi_scsi_task *scsi_task,  dnbd3_image_t *image, const uint64_t offset_blocks, const uint64_t num_blocks)
{
	int rc = 0;
	uint64_t offset_bytes;
	const uint64_t num_bytes = iscsi_scsi_emu_blocks_to_bytes( &offset_bytes, offset_blocks, num_blocks );

	if ( offset_bytes + num_bytes > image->virtualFilesize )
		return -ERANGE;

	scsi_task->file_offset = offset_bytes;
	scsi_task->len = (uint32_t)num_bytes;

	dnbd3_cache_map_t *cache = ref_get_cachemap( image );

	if ( cache != NULL ) {
		// This is a proxyed image, check if we need to relay the request...
		const uint64_t start = (offset_bytes & ~(uint64_t)(DNBD3_BLOCK_SIZE - 1));
		const uint64_t end   = ((offset_bytes + num_bytes + DNBD3_BLOCK_SIZE - 1) & ~(uint64_t) (DNBD3_BLOCK_SIZE - 1));
		bool readFromFile = image_isRangeCachedUnsafe( cache, start, end );

		ref_put( &cache->reference );

		if ( !readFromFile ) {
			// Not cached, request via uplink
			scsi_task->buf = malloc( num_bytes );
			if ( scsi_task->buf == NULL ) {
				return -ENOMEM;
			}
			pthread_mutex_init( &scsi_task->uplink_mutex, NULL );
			pthread_cond_init( &scsi_task->uplink_cond, NULL );
			pthread_mutex_lock( &scsi_task->uplink_mutex );

			if ( !uplink_request( image, scsi_task, iscsi_uplink_callback, 0, offset_bytes, (uint32_t)num_bytes ) ) {
				pthread_mutex_unlock( &scsi_task->uplink_mutex );

				logadd( LOG_DEBUG1, "Could not relay uncached request to upstream proxy for image %s:%d",
						image->name, image->rid );

				rc = -EIO;
			} else {
				// Wait sync (Maybe use pthread_cond_timedwait to detect unavailable uplink instead of hanging...)
				pthread_cond_wait( &scsi_task->uplink_cond, &scsi_task->uplink_mutex );
				pthread_mutex_unlock( &scsi_task->uplink_mutex );
				scsi_task->file_offset = (size_t)-1;
			}
			pthread_cond_destroy( &scsi_task->uplink_cond );
			pthread_mutex_destroy( &scsi_task->uplink_mutex );
		}
	}

	return rc;
}

/**
 * @brief Executes a read operation on a DNBD3 image.
 *
 * This function also sets the SCSI
 * status result code accordingly.
 *
 * @param[in] image Pointer to DNBD3 image to read from
 * @param[in] scsi_task Pointer to iSCSI SCSI task
 * responsible for this read or write
 * task. NULL is NOT allowed here, take
 * caution.
 * @param[in] lba Logical Block Address (LBA) to start
 * reading from or writing to.
 * @param[in] xfer_len Transfer length in logical blocks.
 * @return 0 on successful operation, a negative
 * error code otherwise.
 */
static int iscsi_scsi_emu_block_read(dnbd3_image_t *image, iscsi_scsi_task *scsi_task, const uint64_t lba, const uint32_t xfer_len)
{
	if ( xfer_len == 0UL ) {
		scsi_task->status   = ISCSI_SCSI_STATUS_GOOD;

		return ISCSI_SCSI_TASK_RUN_COMPLETE;
	}

	const uint32_t max_xfer_len = ISCSI_MAX_DS_SIZE / ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE;

	if ( xfer_len > max_xfer_len || !scsi_task->is_read || scsi_task->is_write ) {
		iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ,
			ISCSI_SCSI_ASC_INVALID_FIELD_IN_CDB, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

		return ISCSI_SCSI_TASK_RUN_COMPLETE;
	}

	int rc = iscsi_scsi_emu_io_blocks_read( scsi_task, image, lba, xfer_len );

	if ( rc == 0 )
		return ISCSI_SCSI_TASK_RUN_COMPLETE;

	if ( rc == -ENOMEM ) {
		iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_HARDWARE_ERR,
			ISCSI_SCSI_ASC_INTERNAL_TARGET_FAIL, ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE );

		return ISCSI_SCSI_TASK_RUN_COMPLETE;
	}

	if ( rc == -ERANGE ) {
		iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ,
			ISCSI_SCSI_ASC_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

		return ISCSI_SCSI_TASK_RUN_COMPLETE;
	}

	iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE,
		ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

	return ISCSI_SCSI_TASK_RUN_COMPLETE;
}

/**
 * @brief Executes SCSI block emulation on a DNBD3 image.
 *
 * This function determines the block
 * based SCSI opcode and executes it.
 *
 * @param[in] scsi_task Pointer to iSCSI SCSI task
 * to process the SCSI block operation
 * for and may NOT be NULL, be careful.
 * @return 0 on successful operation, a negative
 * error code otherwise.
 */
static int iscsi_scsi_emu_block_process(iscsi_scsi_task *scsi_task)
{
	uint64_t lba;
	uint32_t xfer_len;
	dnbd3_image_t *image = scsi_task->connection->client->image;

	switch ( scsi_task->cdb->opcode ) {
		case ISCSI_SCSI_OPCODE_READ6 : {
			const iscsi_scsi_cdb_read_write_6 *cdb_read_write_6 = (iscsi_scsi_cdb_read_write_6 *) scsi_task->cdb;

			lba      = iscsi_get_be24(cdb_read_write_6->lba);
			xfer_len = cdb_read_write_6->xfer_len;

			if ( xfer_len == 0UL )
				xfer_len = 256UL;

			return iscsi_scsi_emu_block_read( image, scsi_task, lba, xfer_len );
		}
		case ISCSI_SCSI_OPCODE_READ10 : {
			const iscsi_scsi_cdb_read_write_10 *cdb_read_write_10 = (iscsi_scsi_cdb_read_write_10 *) scsi_task->cdb;

			lba      = iscsi_get_be32(cdb_read_write_10->lba);
			xfer_len = iscsi_get_be16(cdb_read_write_10->xfer_len);

			return iscsi_scsi_emu_block_read( image, scsi_task, lba, xfer_len );
		}
		case ISCSI_SCSI_OPCODE_READ12 : {
			const iscsi_scsi_cdb_read_write_12 *cdb_read_write_12 = (iscsi_scsi_cdb_read_write_12 *) scsi_task->cdb;

			lba      = iscsi_get_be32(cdb_read_write_12->lba);
			xfer_len = iscsi_get_be32(cdb_read_write_12->xfer_len);

			return iscsi_scsi_emu_block_read( image, scsi_task, lba, xfer_len );
		}
		case ISCSI_SCSI_OPCODE_READ16 : {
			const iscsi_scsi_cdb_read_write_16 *cdb_read_write_16 = (iscsi_scsi_cdb_read_write_16 *) scsi_task->cdb;

			lba      = iscsi_get_be64(cdb_read_write_16->lba);
			xfer_len = iscsi_get_be32(cdb_read_write_16->xfer_len);

			return iscsi_scsi_emu_block_read( image, scsi_task, lba, xfer_len );
		}
		case ISCSI_SCSI_OPCODE_READCAPACITY10 : {
			iscsi_scsi_read_capacity_10_parameter_data_packet *buf = malloc( sizeof(struct iscsi_scsi_read_capacity_10_parameter_data_packet) );

			if ( buf == NULL ) {
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NOT_READY, ISCSI_SCSI_ASC_LOGICAL_UNIT_NOT_READY, ISCSI_SCSI_ASCQ_BECOMING_READY );

				return ISCSI_SCSI_TASK_RUN_COMPLETE;
			}

			lba = iscsi_scsi_emu_block_get_count( image ) - 1ULL;

			if ( lba > 0xFFFFFFFFULL )
				buf->lba = 0xFFFFFFFFUL; // Minus one does not require endianess conversion
			else
				iscsi_put_be32( (uint8_t *) &buf->lba, (uint32_t) lba );

			iscsi_put_be32( (uint8_t *) &buf->block_len, ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE );

			scsi_task->buf      = (uint8_t *) buf;
			scsi_task->len      = sizeof(*buf);
			scsi_task->status   = ISCSI_SCSI_STATUS_GOOD;

			break;
		}
		case ISCSI_SCSI_OPCODE_SERVICE_ACTION_IN_16 : {
			const iscsi_scsi_cdb_service_action_in_16 *cdb_servce_in_action_16 = (iscsi_scsi_cdb_service_action_in_16 *) scsi_task->cdb;

			if ( ISCSI_SCSI_CDB_SERVICE_ACTION_IN_16_GET_ACTION(cdb_servce_in_action_16->action)
						!= ISCSI_SCSI_CDB_SERVICE_ACTION_IN_16_ACTION_READ_CAPACITY_16 ) {
				return ISCSI_SCSI_TASK_RUN_UNKNOWN;
			}
			iscsi_scsi_service_action_in_16_parameter_data_packet *buf = malloc( sizeof(struct iscsi_scsi_service_action_in_16_parameter_data_packet) );

			if ( buf == NULL ) {
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NOT_READY,
					ISCSI_SCSI_ASC_LOGICAL_UNIT_NOT_READY, ISCSI_SCSI_ASCQ_BECOMING_READY );

				return ISCSI_SCSI_TASK_RUN_COMPLETE;
			}

			lba = iscsi_scsi_emu_block_get_count( image ) - 1ULL;

			iscsi_put_be64( (uint8_t *) &buf->lba, lba );
			iscsi_put_be32( (uint8_t *) &buf->block_len, ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE );

			buf->flags = 0;

			const uint8_t exponent = ISCSI_SCSI_EMU_BLOCK_DIFF_SHIFT;

			buf->exponents = ISCSI_SCSI_SERVICE_ACTION_IN_16_PARAM_DATA_PUT_LBPPB_EXPONENT((exponent <= ISCSI_SCSI_SERVICE_ACTION_IN_16_PARAM_DATA_LBPPB_EXPONENT_MASK) ? exponent : 0U);

			buf->lbp_lalba = 0U;
			buf->reserved[0] = 0ULL;
			buf->reserved[1] = 0ULL;

			uint len = cdb_servce_in_action_16->alloc_len;

			if ( len > sizeof(struct iscsi_scsi_service_action_in_16_parameter_data_packet) ) {
				len = sizeof(struct iscsi_scsi_service_action_in_16_parameter_data_packet); // TODO: Check whether scatter data is required
			}

			scsi_task->buf      = (uint8_t *) buf;
			scsi_task->len      = len;
			scsi_task->status   = ISCSI_SCSI_STATUS_GOOD;

			break;
		}
		case ISCSI_SCSI_OPCODE_WRITE6 :
		case ISCSI_SCSI_OPCODE_WRITE10 :
		case ISCSI_SCSI_OPCODE_WRITE12 :
		case ISCSI_SCSI_OPCODE_WRITE16 :
		case ISCSI_SCSI_OPCODE_UNMAP :
		case ISCSI_SCSI_OPCODE_SYNCHRONIZECACHE10 :
		case ISCSI_SCSI_OPCODE_SYNCHRONIZECACHE16 : {
			iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE, ISCSI_SCSI_ASC_WRITE_PROTECTED, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

			break;
		}
		default : {
			return ISCSI_SCSI_TASK_RUN_UNKNOWN;

			break;
		}
	}

	return ISCSI_SCSI_TASK_RUN_COMPLETE;
}

/**
 * @brief Calculates the 64-bit IEEE Extended NAA for a name.
 *
 * @param[out] buf Pointer to 64-bit output buffer for
 * storing the IEEE Extended NAA. May
 * NOT be NULL, so be careful.
 * @param[in] name Pointer to string containing the
 * name to calculate the IEEE Extended
 * NAA for. NULL is NOT allowed here, so
 * take caution.
 */
static inline void iscsi_scsi_emu_naa_ieee_ext_set(uint64_t *buf, const uint8_t *name)
{
	const uint64_t wwn = iscsi_target_node_wwn_get( name );

	iscsi_put_be64( (uint8_t *) buf, wwn );
}

/**
 * @brief Copies a SCSI name string and zero pads until total string length is aligned to DWORD boundary.
 *
 * @param[out] buf Pointer to copy the aligned SCSI
 * string to. May NOT be NULL, so be
 * careful.
 * @param[in] name Pointer to string containing the
 * SCSI name to be copied. NULL is NOT
 * allowed here, so take caution.
 * @return The aligned string length in bytes.
 */
static size_t iscsi_scsi_emu_pad_scsi_name(uint8_t *buf, const uint8_t *name)
{
	size_t len = strlen( (char *) name );

	memcpy( buf, name, len );

	do {
		buf[len++] = '\0';
	} while ( (len & (ISCSI_ALIGN_SIZE - 1)) != 0 );

	return len;
}

/**
 * @brief Executes an inquiry operation on a DNBD3 image.
 *
 * This function also sets the SCSI
 * status result code accordingly.
 *
 * @param[in] image Pointer to DNBD3 image to get
 * the inquiry data from. May NOT be
 * NULL, so be careful.
 * @param[in] scsi_task Pointer to iSCSI SCSI task
 * responsible for this inqueiry
 * request. NULL is NOT allowed here,
 * take caution.
 * @param[in] cdb_inquiry Pointer to Command Descriptor
 * Block (CDB) and may NOT be NULL, be
 * careful.
 * @param[in] std_inquiry_data_pkt Pointer to standard inquiry
 * data packet to fill the inquiry
 * data with.
 * @param[in] len Length of inquiry result buffer
 * in bytes.
 * @return length of data on successful operation, a negative
 * error code otherwise.
 */
static int iscsi_scsi_emu_primary_inquiry(dnbd3_image_t *image, iscsi_scsi_task *scsi_task, const iscsi_scsi_cdb_inquiry *cdb_inquiry, iscsi_scsi_std_inquiry_data_packet *std_inquiry_data_pkt, const uint len)
{
	if ( len < sizeof(struct iscsi_scsi_std_inquiry_data_packet) ) {
		iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE,
			ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

		return -1;
	}

	const int evpd = (cdb_inquiry->lun_flags & ISCSI_SCSI_CDB_INQUIRY_FLAGS_EVPD);
	const uint pc  = cdb_inquiry->page_code;

	if ( (evpd == 0) && (pc != 0U) ) {
		iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ,
			ISCSI_SCSI_ASC_INVALID_FIELD_IN_CDB, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

		return -1;
	}

	if ( evpd != 0 ) {
		// VPD requested
		iscsi_scsi_vpd_page_inquiry_data_packet *vpd_page_inquiry_data_pkt = (iscsi_scsi_vpd_page_inquiry_data_packet *) std_inquiry_data_pkt;
		uint alloc_len;
		const uint8_t pti = ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PUT_PERIPHERAL_TYPE(ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PERIPHERAL_TYPE_DIRECT) | ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PUT_PERIPHERAL_ID(ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PERIPHERAL_ID_POSSIBLE);

		vpd_page_inquiry_data_pkt->peripheral_type_id        = pti;
		vpd_page_inquiry_data_pkt->page_code                 = (uint8_t) pc;

		switch ( pc ) {
			case ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_SUPPORTED_VPD_PAGES : {
				vpd_page_inquiry_data_pkt->params[0] = ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_SUPPORTED_VPD_PAGES;
				vpd_page_inquiry_data_pkt->params[1] = ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_UNIT_SERIAL_NUMBER;
				vpd_page_inquiry_data_pkt->params[2] = ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_DEVICE_ID;
				vpd_page_inquiry_data_pkt->params[3] = ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_EXTENDED_INQUIRY_DATA;
				vpd_page_inquiry_data_pkt->params[4] = ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_BLOCK_LIMITS;
				vpd_page_inquiry_data_pkt->params[5] = ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_BLOCK_DEV_CHARS;

				alloc_len = 6U;

				iscsi_put_be16( (uint8_t *) &vpd_page_inquiry_data_pkt->alloc_len, (uint16_t) alloc_len );

				break;
			}
			case ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_UNIT_SERIAL_NUMBER : {
				const char *name = image->name;

				alloc_len = (uint) strlen( name );

				if ( alloc_len >= (len - sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet)) )
					alloc_len = (uint) ((len - sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet)) - 1U);

				memcpy( vpd_page_inquiry_data_pkt->params, name, alloc_len );
				memset( (vpd_page_inquiry_data_pkt->params + alloc_len), '\0', (len - alloc_len - sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet)) );

				alloc_len++;

				iscsi_put_be16( (uint8_t *) &vpd_page_inquiry_data_pkt->alloc_len, (uint16_t) alloc_len );

				break;
			}
			case ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_DEVICE_ID : {
				const char *port_name = "Horst";
				const uint dev_name_len  = (uint) (strlen( image->name ) + 1U);
				const uint port_name_len = (uint) (strlen( port_name ) + 1U);

				alloc_len  = (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_ieee_naa_ext_inquiry_data_packet)); // 64-bit IEEE NAA Extended
				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_t10_vendor_id_inquiry_data_packet)); // T10 Vendor ID
				alloc_len += (uint) (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + ISCSI_ALIGN(dev_name_len, ISCSI_ALIGN_SIZE)); // SCSI Device Name
				alloc_len += (uint) (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + ISCSI_ALIGN(port_name_len, ISCSI_ALIGN_SIZE)); // SCSI Target Port Name
				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_rel_target_port_inquiry_data_packet)); // Relative Target Port
				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_target_port_group_inquiry_data_packet)); // Target Port Group
				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_logical_unit_group_inquiry_data_packet)); // Logical Unit Group

				if ( len < (alloc_len + sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet)) ) {
					iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ, ISCSI_SCSI_ASC_INVALID_FIELD_IN_CDB, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

					return -1;
				}

				iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *vpd_page_design_desc_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *) vpd_page_inquiry_data_pkt->params;

				vpd_page_design_desc_inquiry_data_pkt->protocol_id_code_set = ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_CODE_SET(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_CODE_SET_BINARY) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_PROTOCOL_ID(ISCSI_DEFAULT_PROTOCOL_ID);
				vpd_page_design_desc_inquiry_data_pkt->flags                = (int8_t) (ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_TYPE(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_TYPE_NAA) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_ASSOC(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_ASSOC_LOGICAL_UNIT) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PIV);
				vpd_page_design_desc_inquiry_data_pkt->reserved             = 0U;
				vpd_page_design_desc_inquiry_data_pkt->len                  = sizeof(struct iscsi_scsi_vpd_page_design_desc_ieee_naa_ext_inquiry_data_packet);

				iscsi_scsi_emu_naa_ieee_ext_set( (uint64_t *) vpd_page_design_desc_inquiry_data_pkt->desc, (uint8_t *) image->name );

				alloc_len = (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_ieee_naa_ext_inquiry_data_packet));

				vpd_page_design_desc_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *) (((uint8_t *) vpd_page_design_desc_inquiry_data_pkt) + alloc_len);
				vpd_page_design_desc_inquiry_data_pkt->protocol_id_code_set = ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_CODE_SET(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_CODE_SET_ASCII) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_PROTOCOL_ID(ISCSI_DEFAULT_PROTOCOL_ID);
				vpd_page_design_desc_inquiry_data_pkt->flags                = (int8_t) (ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_TYPE(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_TYPE_T10_VENDOR_ID) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_ASSOC(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_ASSOC_LOGICAL_UNIT) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PIV);
				vpd_page_design_desc_inquiry_data_pkt->reserved             = 0U;
				vpd_page_design_desc_inquiry_data_pkt->len                  = sizeof(struct iscsi_scsi_vpd_page_design_desc_t10_vendor_id_inquiry_data_packet);

				iscsi_scsi_vpd_page_design_desc_t10_vendor_id_inquiry_data_packet *vpd_page_design_desc_t10_vendor_id_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_t10_vendor_id_inquiry_data_packet *) vpd_page_design_desc_inquiry_data_pkt->desc;

				iscsi_strcpy_pad( (char *) vpd_page_design_desc_t10_vendor_id_inquiry_data_pkt->vendor_id, ISCSI_SCSI_STD_INQUIRY_DATA_DISK_VENDOR_ID, sizeof(vpd_page_design_desc_t10_vendor_id_inquiry_data_pkt->vendor_id), ' ' );
				iscsi_strcpy_pad( (char *) vpd_page_design_desc_t10_vendor_id_inquiry_data_pkt->product_id, image->name, sizeof(vpd_page_design_desc_t10_vendor_id_inquiry_data_pkt->product_id), ' ' );
				iscsi_strcpy_pad( (char *) vpd_page_design_desc_t10_vendor_id_inquiry_data_pkt->unit_serial_num, image->name, sizeof(vpd_page_design_desc_t10_vendor_id_inquiry_data_pkt->unit_serial_num), ' ' );

				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_t10_vendor_id_inquiry_data_packet));

				vpd_page_design_desc_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *) (((uint8_t *) vpd_page_design_desc_inquiry_data_pkt) + (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_t10_vendor_id_inquiry_data_packet)));
				vpd_page_design_desc_inquiry_data_pkt->protocol_id_code_set = ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_CODE_SET(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_CODE_SET_UTF8) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_PROTOCOL_ID(ISCSI_DEFAULT_PROTOCOL_ID);
				vpd_page_design_desc_inquiry_data_pkt->flags                = (int8_t) (ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_TYPE(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_TYPE_SCSI_NAME) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_ASSOC(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_ASSOC_TARGET_DEVICE) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PIV);
				vpd_page_design_desc_inquiry_data_pkt->reserved             = 0U;
				vpd_page_design_desc_inquiry_data_pkt->len                  = (uint8_t) iscsi_scsi_emu_pad_scsi_name( vpd_page_design_desc_inquiry_data_pkt->desc, (const uint8_t*)image->name );

				alloc_len += (uint) (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + vpd_page_design_desc_inquiry_data_pkt->len);

				vpd_page_design_desc_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *) (((uint8_t *) vpd_page_design_desc_inquiry_data_pkt) + (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + vpd_page_design_desc_inquiry_data_pkt->len));
				vpd_page_design_desc_inquiry_data_pkt->protocol_id_code_set = ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_CODE_SET(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_CODE_SET_UTF8) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_PROTOCOL_ID(ISCSI_DEFAULT_PROTOCOL_ID);
				vpd_page_design_desc_inquiry_data_pkt->flags                = (int8_t) (ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_TYPE(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_TYPE_SCSI_NAME) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_ASSOC(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_ASSOC_TARGET_PORT) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PIV);
				vpd_page_design_desc_inquiry_data_pkt->reserved             = 0U;
				vpd_page_design_desc_inquiry_data_pkt->len                  = (uint8_t) iscsi_scsi_emu_pad_scsi_name( vpd_page_design_desc_inquiry_data_pkt->desc, (const uint8_t*)port_name );

				alloc_len += (uint) (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + vpd_page_design_desc_inquiry_data_pkt->len);

				vpd_page_design_desc_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *) (((uint8_t *) vpd_page_design_desc_inquiry_data_pkt) + (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + vpd_page_design_desc_inquiry_data_pkt->len));
				vpd_page_design_desc_inquiry_data_pkt->protocol_id_code_set = ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_CODE_SET(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_CODE_SET_BINARY) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_PROTOCOL_ID(ISCSI_DEFAULT_PROTOCOL_ID);
				vpd_page_design_desc_inquiry_data_pkt->flags                = (int8_t) (ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_TYPE(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_TYPE_REL_TARGET_PORT) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_ASSOC(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_ASSOC_TARGET_PORT) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PIV);
				vpd_page_design_desc_inquiry_data_pkt->reserved             = 0U;
				vpd_page_design_desc_inquiry_data_pkt->len                  = sizeof(struct iscsi_scsi_vpd_page_design_desc_rel_target_port_inquiry_data_packet);

				iscsi_scsi_vpd_page_design_desc_rel_target_port_inquiry_data_packet *vpd_page_design_desc_rel_target_port_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_rel_target_port_inquiry_data_packet *) vpd_page_design_desc_inquiry_data_pkt->desc;

				vpd_page_design_desc_rel_target_port_inquiry_data_pkt->reserved = 0U;
				iscsi_put_be16( (uint8_t *) &vpd_page_design_desc_rel_target_port_inquiry_data_pkt->index, 1 );

				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_rel_target_port_inquiry_data_packet));

				vpd_page_design_desc_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *) (((uint8_t *) vpd_page_design_desc_inquiry_data_pkt) +  (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_rel_target_port_inquiry_data_packet)));
				vpd_page_design_desc_inquiry_data_pkt->protocol_id_code_set = ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_CODE_SET(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_CODE_SET_BINARY) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_PROTOCOL_ID(ISCSI_DEFAULT_PROTOCOL_ID);
				vpd_page_design_desc_inquiry_data_pkt->flags                = (int8_t) (ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_TYPE(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_TYPE_TARGET_PORT_GROUP) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_ASSOC(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_ASSOC_TARGET_PORT) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PIV);
				vpd_page_design_desc_inquiry_data_pkt->reserved             = 0U;
				vpd_page_design_desc_inquiry_data_pkt->len                  = sizeof(struct iscsi_scsi_vpd_page_design_desc_target_port_group_inquiry_data_packet);

				iscsi_scsi_vpd_page_design_desc_target_port_group_inquiry_data_packet *vpd_page_design_desc_target_port_group_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_target_port_group_inquiry_data_packet *) vpd_page_design_desc_inquiry_data_pkt->desc;

				vpd_page_design_desc_target_port_group_inquiry_data_pkt->reserved = 0U;
				vpd_page_design_desc_target_port_group_inquiry_data_pkt->index    = 0U;

				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_target_port_group_inquiry_data_packet));

				vpd_page_design_desc_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_inquiry_data_packet *) (((uint8_t *) vpd_page_design_desc_inquiry_data_pkt) +  (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_target_port_group_inquiry_data_packet)));
				vpd_page_design_desc_inquiry_data_pkt->protocol_id_code_set = ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_CODE_SET(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_CODE_SET_BINARY) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_PUT_PROTOCOL_ID(ISCSI_DEFAULT_PROTOCOL_ID);
				vpd_page_design_desc_inquiry_data_pkt->flags                = (int8_t) (ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_TYPE(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_TYPE_LOGICAL_UNIT_GROUP) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PUT_ASSOC(ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_ASSOC_LOGICAL_UNIT) | ISCSI_SCSI_VPD_PAGE_DESIGN_DESC_INQUIRY_DATA_FLAGS_PIV);
				vpd_page_design_desc_inquiry_data_pkt->reserved             = 0U;
				vpd_page_design_desc_inquiry_data_pkt->len                  = sizeof(struct iscsi_scsi_vpd_page_design_desc_logical_unit_group_inquiry_data_packet);

				iscsi_scsi_vpd_page_design_desc_logical_unit_group_inquiry_data_packet *vpd_page_design_desc_logical_unit_group_inquiry_data_pkt = (iscsi_scsi_vpd_page_design_desc_logical_unit_group_inquiry_data_packet*)vpd_page_design_desc_inquiry_data_pkt->desc;

				vpd_page_design_desc_logical_unit_group_inquiry_data_pkt->reserved = 0U;
				iscsi_put_be16( (uint8_t *) &vpd_page_design_desc_logical_unit_group_inquiry_data_pkt->id, (uint16_t) ISCSI_DEFAULT_DEVICE_ID );

				alloc_len += (sizeof(struct iscsi_scsi_vpd_page_design_desc_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_design_desc_logical_unit_group_inquiry_data_packet));

				iscsi_put_be16( (uint8_t *) &vpd_page_inquiry_data_pkt->alloc_len, (uint16_t) alloc_len );

				break;
			}
			case ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_EXTENDED_INQUIRY_DATA : {
				iscsi_scsi_vpd_page_ext_inquiry_data_packet *vpd_page_ext_inquiry_data_pkt = (iscsi_scsi_vpd_page_ext_inquiry_data_packet *) vpd_page_inquiry_data_pkt;

				alloc_len = (sizeof(iscsi_scsi_vpd_page_ext_inquiry_data_packet) - sizeof(iscsi_scsi_vpd_page_inquiry_data_packet));

				if ( len < (alloc_len + sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet)) ) {
					iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ, ISCSI_SCSI_ASC_INVALID_FIELD_IN_CDB, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

					return -1;
				}

				vpd_page_ext_inquiry_data_pkt->reserved        = 0U;
				vpd_page_ext_inquiry_data_pkt->page_len        = (uint8_t) alloc_len;
				vpd_page_ext_inquiry_data_pkt->check_flags     = 0;
				vpd_page_ext_inquiry_data_pkt->support_flags   = (ISCSI_SCSI_VPD_PAGE_EXT_INQUIRY_DATA_SUPPORT_FLAGS_SIMPSUP | ISCSI_SCSI_VPD_PAGE_EXT_INQUIRY_DATA_SUPPORT_FLAGS_HEADSUP);
				vpd_page_ext_inquiry_data_pkt->support_flags_2 = 0;
				vpd_page_ext_inquiry_data_pkt->luiclr          = 0U;
				vpd_page_ext_inquiry_data_pkt->cbcs            = 0U;
				vpd_page_ext_inquiry_data_pkt->micro_dl        = 0U;
				vpd_page_ext_inquiry_data_pkt->reserved2[0]    = 0ULL;
				vpd_page_ext_inquiry_data_pkt->reserved2[1]    = 0ULL;
				vpd_page_ext_inquiry_data_pkt->reserved2[2]    = 0ULL;
				vpd_page_ext_inquiry_data_pkt->reserved2[3]    = 0ULL;
				vpd_page_ext_inquiry_data_pkt->reserved2[4]    = 0ULL;
				vpd_page_ext_inquiry_data_pkt->reserved2[5]    = 0ULL;
				vpd_page_ext_inquiry_data_pkt->reserved3       = 0UL;
				vpd_page_ext_inquiry_data_pkt->reserved4       = 0U;

				iscsi_put_be16( (uint8_t *) &vpd_page_inquiry_data_pkt->alloc_len, (uint16_t) alloc_len );

				break;
			}
			case ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_BLOCK_LIMITS : {
				iscsi_scsi_vpd_page_block_limits_inquiry_data_packet *vpd_page_block_limits_inquiry_data_pkt = (iscsi_scsi_vpd_page_block_limits_inquiry_data_packet *) vpd_page_inquiry_data_pkt->params;

				if ( len < (sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_block_limits_inquiry_data_packet)) ) {
					iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ, ISCSI_SCSI_ASC_INVALID_FIELD_IN_CDB, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

					return -1;
				}

				alloc_len = sizeof(struct iscsi_scsi_vpd_page_block_limits_inquiry_data_packet);

				vpd_page_block_limits_inquiry_data_pkt->flags = 0;

				// Calculate maximum number of logical blocks that would fit into a maximum-size transfer (16MiB),
				// but make sure it is a multiple of the physical block size
				const uint32_t blocks = ((ISCSI_MAX_DS_SIZE  / ISCSI_SCSI_EMU_PHYSICAL_BLOCK_SIZE)
					* ISCSI_SCSI_EMU_PHYSICAL_BLOCK_SIZE) / ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE;

				vpd_page_block_limits_inquiry_data_pkt->max_cmp_write_len = (uint8_t) blocks;

				iscsi_put_be16( (uint8_t *) &vpd_page_block_limits_inquiry_data_pkt->optimal_granularity_xfer_len,
					(uint16_t) ISCSI_SCSI_EMU_PHYSICAL_BLOCK_SIZE / ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE );
				iscsi_put_be32( (uint8_t *) &vpd_page_block_limits_inquiry_data_pkt->max_xfer_len, blocks );
				iscsi_put_be32( (uint8_t *) &vpd_page_block_limits_inquiry_data_pkt->optimal_xfer_len, blocks );
				vpd_page_block_limits_inquiry_data_pkt->max_prefetch_len = 0UL;

				vpd_page_block_limits_inquiry_data_pkt->max_unmap_lba_cnt = 0UL;
				vpd_page_block_limits_inquiry_data_pkt->max_unmap_block_desc_cnt = 0UL;

				vpd_page_block_limits_inquiry_data_pkt->optimal_unmap_granularity        = 0UL;
				vpd_page_block_limits_inquiry_data_pkt->unmap_granularity_align_ugavalid = 0UL;
				iscsi_put_be64( (uint8_t *) &vpd_page_block_limits_inquiry_data_pkt->max_write_same_len, blocks );
				vpd_page_block_limits_inquiry_data_pkt->reserved[0]                      = 0ULL;
				vpd_page_block_limits_inquiry_data_pkt->reserved[1]                      = 0ULL;
				vpd_page_block_limits_inquiry_data_pkt->reserved2                        = 0UL;

				iscsi_put_be16( (uint8_t *) &vpd_page_inquiry_data_pkt->alloc_len, (uint16_t) alloc_len );

				break;
			}
			case ISCSI_SCSI_VPD_PAGE_INQUIRY_DATA_PAGE_CODE_BLOCK_DEV_CHARS : {
				iscsi_scsi_vpd_page_block_dev_chars_inquiry_data_packet *vpd_page_block_dev_chars_inquiry_data_pkt = (iscsi_scsi_vpd_page_block_dev_chars_inquiry_data_packet *) vpd_page_inquiry_data_pkt->params;

				if ( len < (sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet) + sizeof(struct iscsi_scsi_vpd_page_block_dev_chars_inquiry_data_packet)) ) {
					iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ, ISCSI_SCSI_ASC_INVALID_FIELD_IN_CDB, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

					return -1;
				}

				alloc_len = sizeof(struct iscsi_scsi_vpd_page_block_dev_chars_inquiry_data_packet);

				vpd_page_block_dev_chars_inquiry_data_pkt->medium_rotation_rate = ISCSI_SCSI_VPD_PAGE_BLOCK_DEV_CHARS_INQUIRY_DATA_MEDIUM_ROTATION_RATE_NONE;
				vpd_page_block_dev_chars_inquiry_data_pkt->product_type         = ISCSI_SCSI_VPD_PAGE_BLOCK_DEV_CHARS_INQUIRY_DATA_PRODUCT_TYPE_NOT_INDICATED;
				vpd_page_block_dev_chars_inquiry_data_pkt->flags                = ISCSI_SCSI_VPD_PAGE_BLOCK_DEV_CHARS_INQUIRY_DATA_FLAGS_PUT_NOMINAL_FORM_FACTOR(ISCSI_SCSI_VPD_PAGE_BLOCK_DEV_CHARS_INQUIRY_DATA_FLAGS_NOMINAL_FORM_FACTOR_NOT_REPORTED);
				vpd_page_block_dev_chars_inquiry_data_pkt->support_flags        = 0U;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved[0]          = 0ULL;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved[1]          = 0ULL;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved[2]          = 0ULL;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved[3]          = 0ULL;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved[4]          = 0ULL;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved[5]          = 0ULL;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved2            = 0UL;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved3            = 0U;
				vpd_page_block_dev_chars_inquiry_data_pkt->reserved4            = 0U;

				iscsi_put_be16( (uint8_t *) &vpd_page_inquiry_data_pkt->alloc_len, (uint16_t) alloc_len );

				break;
			}
			default : {
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE, ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

				return -1;

				break;
			}
		}

		return (int) (alloc_len + sizeof(struct iscsi_scsi_vpd_page_inquiry_data_packet));
	}

	// Normal INQUIRY, no VPD

	const uint8_t pti = ISCSI_SCSI_BASIC_INQUIRY_DATA_PUT_PERIPHERAL_TYPE(ISCSI_SCSI_BASIC_INQUIRY_DATA_PERIPHERAL_TYPE_DIRECT) | ISCSI_SCSI_BASIC_INQUIRY_DATA_PUT_PERIPHERAL_ID(ISCSI_SCSI_BASIC_INQUIRY_DATA_PERIPHERAL_ID_POSSIBLE);

	std_inquiry_data_pkt->basic_inquiry.peripheral_type_id        = pti;
	std_inquiry_data_pkt->basic_inquiry.peripheral_type_mod_flags = 0;
	std_inquiry_data_pkt->basic_inquiry.version                   = ISCSI_SCSI_BASIC_INQUIRY_DATA_PUT_VERSION_ANSI(ISCSI_SCSI_BASIC_INQUIRY_DATA_VERSION_ANSI_SPC3);
	std_inquiry_data_pkt->basic_inquiry.response_data_fmt_flags   = ISCSI_SCSI_BASIC_INQUIRY_DATA_PUT_RESPONSE_DATA_FMT_FLAGS(ISCSI_SCSI_BASIC_INQUIRY_DATA_RESPONSE_DATA_FMT_FLAGS_SCSI_2) | ISCSI_SCSI_BASIC_INQUIRY_DATA_RESPONSE_DATA_FMT_FLAGS_HISUP;

	std_inquiry_data_pkt->tpgs_flags     = 0U;
	std_inquiry_data_pkt->services_flags = ISCSI_SCSI_STD_INQUIRY_DATA_SERVICES_FLAGS_MULTIP;
	std_inquiry_data_pkt->flags          = ISCSI_SCSI_STD_INQUIRY_DATA_FLAGS_COMMAND_QUEUE;

	iscsi_strcpy_pad( (char *) std_inquiry_data_pkt->vendor_id, ISCSI_SCSI_STD_INQUIRY_DATA_DISK_VENDOR_ID, sizeof(std_inquiry_data_pkt->vendor_id), ' ' );
	iscsi_strcpy_pad( (char *) std_inquiry_data_pkt->product_id, image->name, sizeof(std_inquiry_data_pkt->product_id), ' ' );

	char image_rev[sizeof(std_inquiry_data_pkt->product_rev_level) + 1];

	sprintf( image_rev, "%04" PRIX16, image->rid );
	iscsi_strcpy_pad( (char *) std_inquiry_data_pkt->product_rev_level, image_rev, sizeof(std_inquiry_data_pkt->product_rev_level), ' ' );

	uint add_len = (sizeof(struct iscsi_scsi_std_inquiry_data_packet) - sizeof(struct iscsi_scsi_basic_inquiry_data_packet));
	iscsi_scsi_ext_inquiry_data_packet *ext_inquiry_data_pkt = (iscsi_scsi_ext_inquiry_data_packet *) std_inquiry_data_pkt;

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, vendor_spec) ) {
		iscsi_strcpy_pad( (char *) ext_inquiry_data_pkt->vendor_spec, ISCSI_SCSI_EXT_INQUIRY_DATA_VENDOR_SPEC_ID, sizeof(ext_inquiry_data_pkt->vendor_spec), ' ' );

		add_len += sizeof(ext_inquiry_data_pkt->vendor_spec);
	}

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, flags) ) {
		ext_inquiry_data_pkt->flags = 0;

		add_len += sizeof(ext_inquiry_data_pkt->flags);
	}

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, reserved) ) {
		ext_inquiry_data_pkt->reserved = 0U;

		add_len += sizeof(ext_inquiry_data_pkt->reserved);
	}

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, version_desc[0]) ) {
		iscsi_put_be16( (uint8_t *) &ext_inquiry_data_pkt->version_desc[0], ISCSI_SCSI_EXT_INQUIRY_DATA_VERSION_DESC_ISCSI_NO_VERSION );

		add_len += sizeof(ext_inquiry_data_pkt->version_desc[0]);
	}

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, version_desc[1]) ) {
		iscsi_put_be16( (uint8_t *) &ext_inquiry_data_pkt->version_desc[1], ISCSI_SCSI_EXT_INQUIRY_DATA_VERSION_DESC_SPC3_NO_VERSION );

		add_len += sizeof(ext_inquiry_data_pkt->version_desc[1]);
	}

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, version_desc[2]) ) {
		iscsi_put_be16( (uint8_t *) &ext_inquiry_data_pkt->version_desc[2], ISCSI_SCSI_EXT_INQUIRY_DATA_VERSION_DESC_SBC2_NO_VERSION );

		add_len += sizeof(ext_inquiry_data_pkt->version_desc[2]);
	}

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, version_desc[3]) ) {
		iscsi_put_be16( (uint8_t *) &ext_inquiry_data_pkt->version_desc[3], ISCSI_SCSI_EXT_INQUIRY_DATA_VERSION_DESC_SAM2_NO_VERSION );

		add_len += sizeof(ext_inquiry_data_pkt->version_desc[3]);
	}

	if ( len >= ISCSI_NEXT_OFFSET(iscsi_scsi_ext_inquiry_data_packet, version_desc[4]) ) {
		uint alloc_len = (uint) (len - offsetof(iscsi_scsi_ext_inquiry_data_packet, version_desc[4]));

		if ( alloc_len > (sizeof(struct iscsi_scsi_ext_inquiry_data_packet) - offsetof(iscsi_scsi_ext_inquiry_data_packet, version_desc[4])) )
			alloc_len = (sizeof(struct iscsi_scsi_ext_inquiry_data_packet) - offsetof(iscsi_scsi_ext_inquiry_data_packet, version_desc[4]));

		memset( &ext_inquiry_data_pkt->version_desc[4], 0, alloc_len );
		add_len += alloc_len;
	}

	std_inquiry_data_pkt->basic_inquiry.add_len = (uint8_t) add_len;

	return (int) (add_len + sizeof(struct iscsi_scsi_basic_inquiry_data_packet));
}

/**
 * @brief Executes a report LUNs operation on a DNBD3 image.
 *
 * This function also sets the SCSI
 * status result code accordingly.
 *
 * @param[in] report_luns_parameter_data_pkt Pointer to report LUNS
 * parameter data packet to fill the
 * LUN data data with.
 * @param[in] len Length of LUN reporting result buffer
 * in bytes.
 * @param[in] select_report Selected report.
 * @return Total length of LUN data on successful
 * operation, a negative error code
 * otherwise.
 */
static int iscsi_scsi_emu_primary_report_luns( iscsi_scsi_report_luns_parameter_data_lun_list_packet *report_luns_parameter_data_pkt, const uint len, const uint select_report)
{
	const uint64_t lun = iscsi_scsi_lun_get_from_scsi( ISCSI_DEFAULT_LUN );

	if ( len < sizeof(struct iscsi_scsi_report_luns_parameter_data_lun_list_packet) + sizeof(lun) )
		return -1;

	switch ( select_report ) {
		case ISCSI_SCSI_CDB_REPORT_LUNS_SELECT_REPORT_LU_ADDR_METHOD :
		case ISCSI_SCSI_CDB_REPORT_LUNS_SELECT_REPORT_LU_KNOWN :
		case ISCSI_SCSI_CDB_REPORT_LUNS_SELECT_REPORT_LU_ALL : {
			break;
		}
		default : {
			return -1;
		}
	}

	report_luns_parameter_data_pkt->reserved     = 0UL;
	iscsi_put_be32( (uint8_t *) &report_luns_parameter_data_pkt->lun_list_len, sizeof(lun) );
	iscsi_put_be64( (uint8_t *) (report_luns_parameter_data_pkt + 1), lun );

	return (int) (sizeof(lun) + sizeof(struct iscsi_scsi_report_luns_parameter_data_lun_list_packet));
}

/**
 * @brief Initializes a mode sense page or sub page and zero fills the parameter data.
 *
 * This function also sets the correct
 * page length and flags either for
 * the page or sub page. If a sub page
 * is initialized, the sub page code
 * will also be set.
 *
 * @param[in] buffer Pointer to mode sense parameter
 * mode page or sub page data packet
 * to initialize. If this is NULL,
 * this function does nothing.
 * @param[in] len Length in bytes to initialize. Any padding will be zeroed.
 * @param[in] page Page code.
 * @param[in] sub_page Sub page code.
 */
static void iscsi_scsi_emu_primary_mode_sense_page_init(uint8_t *buffer, const uint len, const uint page, const uint sub_page)
{
	if ( buffer == NULL )
		return;

	if ( sub_page == 0U ) {
		iscsi_scsi_mode_sense_mode_page_data_header *mode_sense_mode_page_pkt = (iscsi_scsi_mode_sense_mode_page_data_header *) buffer;
		mode_sense_mode_page_pkt->page_code_flags = (uint8_t) ISCSI_SCSI_MODE_SENSE_MODE_PAGE_PUT_PAGE_CODE(page);
		mode_sense_mode_page_pkt->page_len        = (uint8_t) (len - sizeof(*mode_sense_mode_page_pkt));

		memset( mode_sense_mode_page_pkt + 1, 0, (len - sizeof(*mode_sense_mode_page_pkt)) );
	} else {
		iscsi_scsi_mode_sense_mode_sub_page_data_header *mode_sense_mode_sub_page_pkt = (iscsi_scsi_mode_sense_mode_sub_page_data_header *) buffer;

		mode_sense_mode_sub_page_pkt->page_code_flags = (uint8_t) (ISCSI_SCSI_MODE_SENSE_MODE_PAGE_PUT_PAGE_CODE(page) | ISCSI_SCSI_MODE_SENSE_MODE_PAGE_FLAGS_SPF);
		mode_sense_mode_sub_page_pkt->sub_page_code   = (uint8_t) sub_page;
		iscsi_put_be16( (uint8_t *) &mode_sense_mode_sub_page_pkt->page_len, (uint16_t) (len - sizeof(*mode_sense_mode_sub_page_pkt)) );

		memset( mode_sense_mode_sub_page_pkt + 1, 0, (len - sizeof(*mode_sense_mode_sub_page_pkt)) );
	}
}

/**
 * @brief Handles a specific mode sense page or sub page.
 *
 * This function also sets the SCSI
 * status result code accordingly.
 *
 * @param[in] image Pointer to DNBD3 image to get
 * the mode sense data from. May NOT be
 * NULL, so be careful.
 * @param[in] scsi_task Pointer to iSCSI SCSI task
 * responsible for this mode sense
 * task. NULL is NOT allowed here,
 * take caution.
 * @param[in] buffer Pointer to mode sense parameter
 * mode page or sub page data packet
 * to process. If this is NULL, only
 * the length of page is calculated.
 * @param[in] pc Page control (PC).
 * @param[in] page Page code.
 * @param[in] sub_page Sub page code.
 * @return Number of bytes occupied or a
 * negative error code otherwise.
 */
static int iscsi_scsi_emu_primary_mode_sense_page(dnbd3_image_t *image, iscsi_scsi_task *scsi_task, uint8_t *buffer, const uint pc, const uint page, const uint sub_page)
{
	uint page_len;
	uint len = 0;
	int tmplen;

	switch ( pc ) {
		case ISCSI_SCSI_CDB_MODE_SENSE_6_PAGE_CONTROL_CURRENT_VALUES :
		case ISCSI_SCSI_CDB_MODE_SENSE_6_PAGE_CONTROL_CHG_VALUES :
		case ISCSI_SCSI_CDB_MODE_SENSE_6_PAGE_CONTROL_DEFAULT_VALUES : {
			break;
		}
		default : {
			iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ,
				ISCSI_SCSI_ASC_SAVING_PARAMETERS_NOT_SUPPORTED, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

			return -1;

			break;
		}
	}

	switch ( page ) {
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_FORMAT_DEVICE :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RIGID_DISK_GEOMETRY :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RIGID_DISK_GEOMETRY_2 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_OBSELETE :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_MEDIUM_TYPES_SUPPORTED :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_NOTCH_AND_PARTITION :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_OBSELETE_2 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_2 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_3 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_4 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_5 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_6 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_ENCLOSURE_SERVICES_MGMT :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_7 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_8 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_9 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_PROTOCOL_SPEC_LUN :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_PROTOCOL_SPEC_PORT :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_10 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_11 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_12 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_RESERVED_13 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_2 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_3 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_4 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_5 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_6 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_7 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_8 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_9 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_10 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_11 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_12 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_13 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_14 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_15 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_16 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_17 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_18 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_19 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_20 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_21 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_22 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_23 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_24 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_25 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_26 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_27 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_28 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_29 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_30 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_31 :
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC_32 : {
			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_READ_WRITE_ERR_RECOVERY : {
			if ( sub_page != 0U )
				break;

			page_len = sizeof(iscsi_scsi_mode_sense_read_write_err_recovery_mode_page_data_packet);

			iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

			len += page_len;

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_DISCONNECT_RECONNECT : {
			if ( sub_page != 0U )
				break;

			page_len = sizeof(iscsi_scsi_mode_sense_disconnect_reconnect_mode_page_data_packet);

			iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

			len += page_len;

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VERIFY_ERR_RECOVERY : {
			if ( sub_page != 0U )
				break;

			page_len = sizeof(iscsi_scsi_mode_sense_verify_err_recovery_mode_page_data_packet);

			iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

			len += page_len;

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_CACHING : {
			if ( sub_page != 0U )
				break;

			iscsi_scsi_mode_sense_caching_mode_page_data_packet *mode_sense_caching_mode_page_pkt = (iscsi_scsi_mode_sense_caching_mode_page_data_packet *) buffer;

			page_len = sizeof(iscsi_scsi_mode_sense_caching_mode_page_data_packet);

			iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

			if ( (buffer != NULL) && (pc != ISCSI_SCSI_CDB_MODE_SENSE_6_PAGE_CONTROL_CHG_VALUES) )
				mode_sense_caching_mode_page_pkt->flags |= ISCSI_SCSI_MODE_SENSE_CACHING_MODE_PAGE_FLAGS_RCD;

			len += page_len;

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_CONTROL : {
			switch ( sub_page ) {
				case ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_CONTROL : {
					page_len = sizeof(iscsi_scsi_mode_sense_control_mode_page_data_packet);

					iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

					len += page_len;

					break;
				}
				case ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_CONTROL_EXT : {
					/* Control Extension */

					page_len = sizeof(struct iscsi_scsi_mode_sense_control_ext_mode_page_data_packet);

					iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

					len += page_len;

					break;
				}
				case ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_CONTROL_ALL : {
					tmplen = iscsi_scsi_emu_primary_mode_sense_page( image, scsi_task, ((buffer != NULL) ? (buffer + len) : NULL), pc, page, ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_CONTROL );
					if ( tmplen == -1 )
						return -1;
					len += tmplen;
					tmplen = iscsi_scsi_emu_primary_mode_sense_page( image, scsi_task, ((buffer != NULL) ? (buffer + len) : NULL), pc, page, ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_CONTROL_EXT );
					if ( tmplen == -1 )
						return -1;
					len += tmplen;

					break;
				}
				default : {
					break;
				}
			}

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_XOR_CONTROL : {
			if ( sub_page != 0U )
				break;

			page_len = sizeof(struct iscsi_scsi_mode_sense_xor_ext_mode_page_data_packet);

			iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

			len += page_len;

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_POWER_COND : {
			if ( sub_page != 0U )
				break;

			page_len = sizeof(struct iscsi_scsi_mode_sense_power_cond_mode_page_data_packet);

			iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

			len += page_len;

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_INFO_EXCEPTIOS_CONTROL : {
			if ( sub_page != 0U )
				break;

			page_len = sizeof(struct iscsi_scsi_mode_sense_info_exceptions_control_mode_page_data_packet);

			iscsi_scsi_emu_primary_mode_sense_page_init( buffer, page_len, page, sub_page );

			len += page_len;

			break;
		}
		case ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_REPORT_ALL_MODE_PAGES : {
			switch ( sub_page ) {
				case ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_REPORT_ALL_MODE_PAGES : {
					for ( uint i = ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC; i < ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_REPORT_ALL_MODE_PAGES; i++ ) {
						tmplen = iscsi_scsi_emu_primary_mode_sense_page( image, scsi_task, ((buffer != NULL) ? (buffer + len) : NULL), pc, i, ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_REPORT_ALL_MODE_PAGES );
						if ( tmplen == -1 )
							return -1;
						len += tmplen;
					}

					break;
				}
				case ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_REPORT_ALL_MODE_SUB_PAGES : {
					for ( uint i = ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC; i < ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_REPORT_ALL_MODE_PAGES; i++ ) {
						tmplen = iscsi_scsi_emu_primary_mode_sense_page( image, scsi_task, ((buffer != NULL) ? (buffer + len) : NULL), pc, i, ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_REPORT_ALL_MODE_PAGES );
						if ( tmplen == -1 )
							return -1;
						len += tmplen;
					}

					for ( uint i = ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_VENDOR_SPEC; i < ISCSI_SCSI_MODE_SENSE_MODE_PAGE_CODE_REPORT_ALL_MODE_PAGES; i++ ) {
						tmplen = iscsi_scsi_emu_primary_mode_sense_page( image, scsi_task, ((buffer != NULL) ? (buffer + len) : NULL), pc, i, ISCSI_SCSI_MODE_SENSE_MODE_SUB_PAGE_CODE_REPORT_ALL_MODE_SUB_PAGES );
						if ( tmplen == -1 )
							return -1;
						len += tmplen;
					}

					break;
				}
				default : {
					break;
				}
			}

			break;
		}
		default : {
			break;
		}
	}

	return (int)len;
}

/**
 * @brief Executes a mode sense operation on a DNBD3 image.
 *
 * This function also sets the SCSI
 * status result code accordingly.
 *
 * @param[in] image Pointer to DNBD3 image to get
 * the mode sense data from. May
 * NOT be NULL, so be careful.
 * @param[in] scsi_task Pointer to iSCSI SCSI task
 * responsible for this mode sense
 * task. NULL is NOT allowed here,
 * take caution.
 * @param[in] buffer Pointer to mode sense parameter
 * header data packet to fill the
 * mode sense data with. If this is
 * NULL, only the length of sense
 * data is calculated.
 * @param[in] hdr_len Length of parameter header in bytes.
 * @param[in] block_desc_len Length of LBA parameter block
 * descriptor in bytes.
 * @param[in] long_lba Long Logical Block Address (LONG_LBA) bit.
 * @param[in] pc Page control (PC).
 * @param[in] page_code Page code.
 * @param[in] sub_page_code Sub page code.
 * @return Total length of sense data on successful
 * operation, a negative error code
 * otherwise.
 */
static int iscsi_scsi_emu_primary_mode_sense(dnbd3_image_t *image, iscsi_scsi_task *scsi_task, uint8_t *buffer,
		const uint hdr_len, const uint block_desc_len, const uint long_lba, const uint pc, const uint page_code, const uint sub_page_code)
{
	// Pointer to right after header and LBA block description; where the pages go
	uint8_t *mode_sense_payload = (buffer != NULL) ? (buffer + hdr_len + block_desc_len) : NULL;
	const int page_len = iscsi_scsi_emu_primary_mode_sense_page( image, scsi_task, mode_sense_payload, pc, page_code, sub_page_code );

	if ( page_len < 0 )
		return -1;

	const uint alloc_len = (hdr_len + block_desc_len + page_len);

	if ( buffer == NULL )
		return (int)alloc_len;

	if ( hdr_len == sizeof(iscsi_scsi_mode_sense_6_parameter_header_data_packet) ) {
		iscsi_scsi_mode_sense_6_parameter_header_data_packet *mode_sense_6_parameter_hdr_data_pkt = (iscsi_scsi_mode_sense_6_parameter_header_data_packet *) buffer;
		mode_sense_6_parameter_hdr_data_pkt->mode_data_len  = (uint8_t) (alloc_len - sizeof(uint8_t));
		mode_sense_6_parameter_hdr_data_pkt->medium_type    = 0U;
		mode_sense_6_parameter_hdr_data_pkt->flags          = ISCSI_SCSI_MODE_SENSE_6_PARAM_HDR_DATA_FLAGS_WP;
		mode_sense_6_parameter_hdr_data_pkt->block_desc_len = (uint8_t) block_desc_len;
	} else if ( hdr_len == sizeof(iscsi_scsi_mode_sense_10_parameter_header_data_packet) ) {
		iscsi_scsi_mode_sense_10_parameter_header_data_packet *mode_sense_10_parameter_hdr_data_pkt = (iscsi_scsi_mode_sense_10_parameter_header_data_packet *) buffer;

		iscsi_put_be16( (uint8_t *) &mode_sense_10_parameter_hdr_data_pkt->mode_data_len, (uint16_t) (alloc_len - sizeof(uint16_t)) );
		mode_sense_10_parameter_hdr_data_pkt->medium_type    = 0U;
		mode_sense_10_parameter_hdr_data_pkt->flags          = ISCSI_SCSI_MODE_SENSE_10_PARAM_HDR_DATA_FLAGS_WP;
		mode_sense_10_parameter_hdr_data_pkt->long_lba       = (uint8_t) long_lba;
		mode_sense_10_parameter_hdr_data_pkt->reserved       = 0U;
		iscsi_put_be16( (uint8_t *) &mode_sense_10_parameter_hdr_data_pkt->block_desc_len, (uint16_t) block_desc_len );
	} else {
		logadd( LOG_DEBUG1, "iscsi_scsi_emu_primary_mode_sense: invalid parameter header length %u", hdr_len );
		return -1;
	}

	const uint64_t num_blocks = iscsi_scsi_emu_block_get_count( image );
	const uint32_t block_size = ISCSI_SCSI_EMU_LOGICAL_BLOCK_SIZE;

	if ( block_desc_len == sizeof(iscsi_scsi_mode_sense_lba_parameter_block_desc_data_packet) ) {
		iscsi_scsi_mode_sense_lba_parameter_block_desc_data_packet *lba_parameter_block_desc = (iscsi_scsi_mode_sense_lba_parameter_block_desc_data_packet *) (buffer + hdr_len);

		if ( num_blocks > 0xFFFFFFFFULL )
			lba_parameter_block_desc->num_blocks = 0xFFFFFFFFUL; // Minus one does not require endianess conversion
		else
			iscsi_put_be32( (uint8_t *) &lba_parameter_block_desc->num_blocks, (uint32_t) num_blocks );

		lba_parameter_block_desc->reserved = 0U;
		iscsi_put_be24( (uint8_t *) &lba_parameter_block_desc->block_len, block_size );
	} else if ( block_desc_len == sizeof(iscsi_scsi_mode_sense_long_lba_parameter_block_desc_data_packet) ) {
		iscsi_scsi_mode_sense_long_lba_parameter_block_desc_data_packet *long_lba_parameter_block_desc = (iscsi_scsi_mode_sense_long_lba_parameter_block_desc_data_packet *) (buffer + hdr_len);

		iscsi_put_be64( (uint8_t *) &long_lba_parameter_block_desc->num_blocks, num_blocks );
		long_lba_parameter_block_desc->reserved = 0UL;
		iscsi_put_be32( (uint8_t *) &long_lba_parameter_block_desc->block_len, block_size );
	}

	return (int)alloc_len;
}

/**
 * @brief Determines the temporary allocation size for a SCSI reply.
 *
 * This function calculates the temporary allocation size to be used for SCSI
 * commands based on the requested allocation size. It ensures the allocation
 * size has a minimum size, to simplify buffer-filling. The response can then
 * later be truncated if it's larger than the alloc_size.
 * If the requested size exceeds the default maximum allowed size, a SCSI task
 * status with an error condition is set, and the allocation size is returned
 * as zero.
 *
 * @param[in] scsi_task Pointer to the SCSI task, used to set error status.
 * @param[in] alloc_size The client-requested allocation size in bytes.
 *
 * @return The determined temporary allocation size. Returns 0 if the size
 * exceeds the maximum allowed limit; otherwise, the size is either adjusted
 * to the default size or remains the requested size.
 */
static uint32_t iscsi_get_temporary_allocation_size(iscsi_scsi_task *scsi_task, uint32_t alloc_size)
{
	if ( alloc_size > ISCSI_DEFAULT_RECV_DS_LEN ) {
		// Don't allocate gigabytes of memory just because the client says so
		iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE,
					ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );

		return 0;
	}
	if ( alloc_size < ISCSI_DEFAULT_RECV_DS_LEN )
		return ISCSI_DEFAULT_RECV_DS_LEN;

	return alloc_size;
}

/**
 * @brief Executes SCSI non-block emulation on a DNBD3 image.
 *
 * This function determines the
 * non-block based SCSI opcode and
 * executes it.
 *
 * @param[in] scsi_task Pointer to iSCSI SCSI task
 * to process the SCSI non-block
 * operation for and may NOT be NULL,
 * be careful.
 * @return 0 on successful operation, a negative
 * error code otherwise.
 */
static int iscsi_scsi_emu_primary_process(iscsi_scsi_task *scsi_task)
{
	uint len;
	int rc;

	switch ( scsi_task->cdb->opcode ) {
		case ISCSI_SCSI_OPCODE_INQUIRY : {
			const iscsi_scsi_cdb_inquiry *cdb_inquiry = (iscsi_scsi_cdb_inquiry *) scsi_task->cdb;
			const uint alloc_len = iscsi_get_be16(cdb_inquiry->alloc_len);

			len = iscsi_get_temporary_allocation_size( scsi_task, alloc_len );
			if ( len == 0 )
				break;

			iscsi_scsi_std_inquiry_data_packet *std_inquiry_data_pkt = malloc( len );

			if ( std_inquiry_data_pkt == NULL ) {
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NOT_READY,
					ISCSI_SCSI_ASC_LOGICAL_UNIT_NOT_READY, ISCSI_SCSI_ASCQ_BECOMING_READY );

				break;
			}

			rc = iscsi_scsi_emu_primary_inquiry( scsi_task->connection->client->image, scsi_task, cdb_inquiry, std_inquiry_data_pkt, len );

			if ( rc >= 0 ) {
				scsi_task->buf    = (uint8_t *) std_inquiry_data_pkt;
				scsi_task->len    = MIN( (uint)rc, alloc_len );
				scsi_task->status = ISCSI_SCSI_STATUS_GOOD;
			} else {
				free( std_inquiry_data_pkt );
			}

			break;
		}
		case ISCSI_SCSI_OPCODE_REPORTLUNS : {
			const iscsi_scsi_cdb_report_luns *cdb_report_luns = (iscsi_scsi_cdb_report_luns *) scsi_task->cdb;
			const uint alloc_len = iscsi_get_be32(cdb_report_luns->alloc_len);

			len = iscsi_get_temporary_allocation_size( scsi_task, alloc_len );
			if ( len == 0 )
				break;

			iscsi_scsi_report_luns_parameter_data_lun_list_packet *report_luns_parameter_data_pkt = malloc( len );

			if ( report_luns_parameter_data_pkt == NULL ) {
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NOT_READY,
					ISCSI_SCSI_ASC_LOGICAL_UNIT_NOT_READY, ISCSI_SCSI_ASCQ_BECOMING_READY );

				break;
			}

			rc = iscsi_scsi_emu_primary_report_luns( report_luns_parameter_data_pkt, len, cdb_report_luns->select_report );

			if ( rc >= 0 ) {
				scsi_task->buf    = (uint8_t *) report_luns_parameter_data_pkt;
				scsi_task->len    = MIN( (uint)rc, alloc_len );
				scsi_task->status = ISCSI_SCSI_STATUS_GOOD;
			} else {
				free( report_luns_parameter_data_pkt );
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE,
					ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );
			}

			break;
		}
		case ISCSI_SCSI_OPCODE_MODESENSE6 : {
			const iscsi_scsi_cdb_mode_sense_6 *cdb_mode_sense_6 = (iscsi_scsi_cdb_mode_sense_6 *) scsi_task->cdb;
			const uint alloc_len = cdb_mode_sense_6->alloc_len;

			const uint block_desc_len = ((cdb_mode_sense_6->flags & ISCSI_SCSI_CDB_MODE_SENSE_6_FLAGS_DBD) == 0) ? sizeof(struct iscsi_scsi_mode_sense_lba_parameter_block_desc_data_packet) : 0U;
			const uint pc             = ISCSI_SCSI_CDB_MODE_SENSE_6_GET_PAGE_CONTROL(cdb_mode_sense_6->page_code_control);
			const uint page           = ISCSI_SCSI_CDB_MODE_SENSE_6_GET_PAGE_CODE(cdb_mode_sense_6->page_code_control);
			const uint sub_page       = cdb_mode_sense_6->sub_page_code;

			rc = iscsi_scsi_emu_primary_mode_sense( scsi_task->connection->client->image, scsi_task, NULL, sizeof(struct iscsi_scsi_mode_sense_6_parameter_header_data_packet), block_desc_len, 0U, pc, page, sub_page );

			if ( rc < 0 )
				break;

			len = rc;

			uint8_t *mode_sense_6_parameter_hdr_data_pkt = malloc( len );

			if ( mode_sense_6_parameter_hdr_data_pkt == NULL ) {
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NOT_READY, ISCSI_SCSI_ASC_LOGICAL_UNIT_NOT_READY, ISCSI_SCSI_ASCQ_BECOMING_READY );

				break;
			}

			rc = iscsi_scsi_emu_primary_mode_sense( scsi_task->connection->client->image, scsi_task, mode_sense_6_parameter_hdr_data_pkt, sizeof(struct iscsi_scsi_mode_sense_6_parameter_header_data_packet), block_desc_len, 0U, pc, page, sub_page );

			if ( rc >= 0 ) {
				scsi_task->buf    = mode_sense_6_parameter_hdr_data_pkt;
				scsi_task->len    = MIN( (uint)rc, alloc_len );
				scsi_task->status = ISCSI_SCSI_STATUS_GOOD;
			} else {
				free( mode_sense_6_parameter_hdr_data_pkt );
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE,
					ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );
			}

			break;
		}
		case ISCSI_SCSI_OPCODE_MODESENSE10 : {
			const iscsi_scsi_cdb_mode_sense_10 *cdb_mode_sense_10 = (iscsi_scsi_cdb_mode_sense_10 *) scsi_task->cdb;
			const uint alloc_len = iscsi_get_be16(cdb_mode_sense_10->alloc_len);

			const uint long_lba       = (((cdb_mode_sense_10->flags & ISCSI_SCSI_CDB_MODE_SENSE_10_FLAGS_LLBAA) != 0) ? ISCSI_SCSI_MODE_SENSE_10_PARAM_HDR_DATA_LONGLBA : 0U);
			const uint block_desc_len = (((cdb_mode_sense_10->flags & ISCSI_SCSI_CDB_MODE_SENSE_10_FLAGS_DBD) == 0) ? ((long_lba != 0) ? sizeof(struct iscsi_scsi_mode_sense_long_lba_parameter_block_desc_data_packet) : sizeof(struct iscsi_scsi_mode_sense_lba_parameter_block_desc_data_packet)) : 0U);
			const uint pc10           = ISCSI_SCSI_CDB_MODE_SENSE_10_GET_PAGE_CONTROL(cdb_mode_sense_10->page_code_control);
			const uint page10         = ISCSI_SCSI_CDB_MODE_SENSE_10_GET_PAGE_CODE(cdb_mode_sense_10->page_code_control);
			const uint sub_page10     = cdb_mode_sense_10->sub_page_code;

			rc = iscsi_scsi_emu_primary_mode_sense( scsi_task->connection->client->image, scsi_task, NULL, sizeof(iscsi_scsi_mode_sense_10_parameter_header_data_packet), block_desc_len, long_lba, pc10, page10, sub_page10 );

			if ( rc < 0 )
				break;

			len = rc;

			uint8_t *mode_sense_10_parameter_hdr_data_pkt = malloc( len );

			if ( mode_sense_10_parameter_hdr_data_pkt == NULL ) {
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NOT_READY, ISCSI_SCSI_ASC_LOGICAL_UNIT_NOT_READY, ISCSI_SCSI_ASCQ_BECOMING_READY );

				break;
			}

			rc = iscsi_scsi_emu_primary_mode_sense( scsi_task->connection->client->image, scsi_task, mode_sense_10_parameter_hdr_data_pkt, sizeof(struct iscsi_scsi_mode_sense_10_parameter_header_data_packet), block_desc_len, long_lba, pc10, page10, sub_page10 );

			if ( rc >= 0 ) {
				scsi_task->buf    = mode_sense_10_parameter_hdr_data_pkt;
				scsi_task->len    = MIN( (uint)rc, alloc_len );
				scsi_task->status = ISCSI_SCSI_STATUS_GOOD;
			} else {
				free( mode_sense_10_parameter_hdr_data_pkt );
				iscsi_scsi_task_status_set( scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_NO_SENSE,
					ISCSI_SCSI_ASC_NO_ADDITIONAL_SENSE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );
			}

			break;
		}
		case ISCSI_SCSI_OPCODE_TESTUNITREADY :
		case ISCSI_SCSI_OPCODE_STARTSTOPUNIT : {
			scsi_task->status   = ISCSI_SCSI_STATUS_GOOD;

			break;
		}
		default : {
			return ISCSI_SCSI_TASK_RUN_UNKNOWN;

			break;
		}
	}

	return ISCSI_SCSI_TASK_RUN_COMPLETE;
}

/**
 * @brief Calculates the WWN using 64-bit IEEE Extended NAA for a name.
 *
 * @param[in] name Pointer to string containing the
 * name to calculate the IEEE Extended
 * NAA for. NULL is NOT allowed here, so
 * take caution.
 * @return A 64-bit unsigned integer for
 * storing the IEEE Extended NAA.
 */
static uint64_t iscsi_target_node_wwn_get(const uint8_t *name)
{
	uint64_t value      = 0ULL;
	int i               = 0;

	while ( name[i] != '\0' ) {
		value = (value * 131ULL) + name[i++];
	}

	const uint64_t id_a = ((value & 0xFFF000000ULL) << 24ULL);

	return ((value & 0xFFFFFFULL) | 0x2000000347000000ULL | id_a);
}

/**
 * @brief Creates and initializes an iSCSI session.
 *
 * This function creates and initializes all relevant
 * data structures of an ISCSI session.\n
 * Default key and value pairs are created and
 * assigned before they are negotiated at the
 * login phase.
 *
 * @param[in] conn Pointer to iSCSI connection to associate with the session.
 * @param[in] type Session type to initialize the session with.
 * @return Pointer to initialized iSCSI session or NULL in case an error
 * occured (usually due to memory exhaustion).
 */
static iscsi_session *iscsi_session_create(const int type)
{
	iscsi_session *session = malloc( sizeof(struct iscsi_session) );

	if ( session == NULL ) {
		logadd( LOG_ERROR, "iscsi_session_create: Out of memory allocating iSCSI session" );

		return NULL;
	}

	session->tsih                       = 0ULL;
	session->type                       = type;
	session->exp_cmd_sn                 = 0UL;
	session->max_cmd_sn                 = 0UL;

	return session;
}

/**
 * @brief Deallocates all resources acquired by iscsi_session_create.
 *
 * This function also frees the associated key and value pairs,
 * the attached connections as well as frees the initiator
 * port.
 *
 * @param[in] session Pointer to iSCSI session to be freed.
 * May be NULL in which case this function does nothing at all.
 */
static void iscsi_session_destroy(iscsi_session *session)
{
	free( session );
}

/**
 * @brief Creates data structure for an iSCSI connection from iSCSI portal and TCP/IP socket.
 *
 * Creates a data structure for incoming iSCSI connection
 * requests from iSCSI packet data.
 *
 * @param[in] client dnbd3 client to associate the connection with.
 * @return Pointer to initialized iSCSI connection structure or NULL in
 * case of an error (invalid iSCSI packet data or memory exhaustion).
 */
static iscsi_connection *iscsi_connection_create(dnbd3_client_t *client)
{
	iscsi_connection *conn = malloc( sizeof(struct iscsi_connection) );

	if ( conn == NULL ) {
		logadd( LOG_ERROR, "iscsi_create_connection: Out of memory while allocating iSCSI connection" );

		return NULL;
	}

	conn->session                  = NULL;
	conn->id                       = 0;
	conn->client                   = client;
	conn->flags                    = 0;
	conn->state                    = ISCSI_CONNECT_STATE_NEW;
	conn->login_phase              = ISCSI_LOGIN_RESPONSE_FLAGS_NEXT_STAGE_SECURITY_NEGOTIATION;
	conn->tsih                     = 0U;
	conn->cid                      = 0U;
	conn->state_negotiated         = 0U;
	conn->session_state_negotiated = 0UL;
	conn->init_task_tag            = 0UL;
	conn->target_xfer_tag          = 0UL;
	conn->stat_sn                  = 0UL;

	return conn;
}

/**
 * @brief Deallocates all resources acquired by iscsi_connection_create.
 *
 * Deallocates a data structure of an iSCSI connection
 * request and all allocated hash maps which don't
 * require closing of external resources like closing
 * TCP/IP socket connections.
 *
 * @param[in] conn Pointer to iSCSI connection structure to be
 * deallocated, TCP/IP connections are NOT closed by this
 * function, use iscsi_connection_close for this. This may be
 * NULL in which case this function does nothing.
 */
static void iscsi_connection_destroy(iscsi_connection *conn)
{
	if ( conn != NULL ) {
		iscsi_session_destroy( conn->session );
		free( conn );
	}
}

/**
 * @brief Appends a key and value pair to DataSegment packet data.
 *
 * This function adds any non-declarative key
 * and value pair to an output DataSegment
 * buffer and truncates if necessary.
 *
 * @param[in] number true = int, false = char*
 * @param[in] key Pointer to key to be written to output
 * buffer. NULL is NOT allowed, take caution.
 * @param[in] value Pointer to value of the key that should
 * be written to output buffer which may
 * NOT be NULL, so take caution.
 * @param[in] buf Pointer to output buffer to write the
 * key and value pair to. NULL is
 * prohibited, so be careful.
 * @param[in] pos Position of buffer in bytes to start
 * writing to.
 * @param[in] buflen Total length of buffer in bytes.
 * @return -1 if buffer is already full, otherwise the number
 * of bytes that are written or would have been written to
 * the buffer.
 */
static int iscsi_append_key_value_pair_packet(const bool number, const char *key, const char *value, char *buf, const uint32_t pos, const uint32_t buflen)
{
	if ( pos >= buflen )
		return -1;

	const ssize_t maxlen = buflen - pos;
	if ( number ) {
		return (int)snprintf( (buf + pos), maxlen, "%s=%d", key, (const int)(const size_t)value ) + 1;
	}
	return (int)snprintf( (buf + pos), maxlen, "%s=%s", key, value ) + 1;
}


#define CLAMP(val, min, max) ((val) < (min) ? (min) : ((val) > (max) ? (max) : (val)))

/**
 * @brief Updates iSCSI connection and session values after being retrieved from the client.
 *
 * This function copies the key and value pairs into the
 * internal connection and session structure and checks
 * them for consistency.\n
 * The TCP receive buffer will be adjusted to the new
 * updated value but is never lower than 4KiB and never
 * higher than 8KiB plus header overhead and a factor of
 * 16 for receiving 16 packets at once.
 *
 * @param[in] conn Pointer to ISCSI connection which should
 * be updated.
 * @retval -1 An error occured, e.g. socket is already closed.
 * @retval 0 All values have been updated successfully and
 * the socket is still alive.
 */
static void iscsi_connection_update_key_value_pairs(iscsi_connection *conn, iscsi_negotiation_kvp *pairs)
{
	conn->session->opts.MaxBurstLength = CLAMP(pairs->MaxBurstLength, 512, ISCSI_MAX_DS_SIZE);
	conn->session->opts.FirstBurstLength = CLAMP(pairs->FirstBurstLength, 512, pairs->MaxBurstLength);
	conn->session->opts.MaxRecvDataSegmentLength = CLAMP(pairs->MaxRecvDataSegmentLength, 512, ISCSI_MAX_DS_SIZE);
}

/**
 * @brief Prepares an iSCSI login response PDU and sends it via TCP/IP.
 *
 * This function constructs the login response PDU
 * to be sent via TCP/IP.
 *
 * @param[in] conn Pointer to ISCSI connection to send the TCP/IP
 * packet with. May NOT be NULL, so be
 * careful.
 * @param[in] resp_pdu Pointer to login response PDU to
 * be sent via TCP/IP. NULL is NOT
 * allowed here, take caution.
 * @return 0 if the login response has been sent
 * successfully, a negative error code otherwise.
 */
static int iscsi_send_login_response_pdu(iscsi_connection *conn, iscsi_pdu *resp_pdu)
{
	iscsi_login_response_packet *login_response_pkt =
		(iscsi_login_response_packet *) iscsi_connection_pdu_resize( resp_pdu, resp_pdu->ahs_len, resp_pdu->ds_write_pos );

	login_response_pkt->version_max    = ISCSI_VERSION_MAX;
	login_response_pkt->version_active = ISCSI_VERSION_MAX;

	iscsi_put_be32( (uint8_t *) &login_response_pkt->total_ahs_len, resp_pdu->ds_len ); // TotalAHSLength is always 0 and DataSegmentLength is 24-bit, so write in one step.
	iscsi_put_be32( (uint8_t *) &login_response_pkt->stat_sn, conn->stat_sn++ );

	if ( conn->session != NULL ) { // TODO: Needed? MC/S?
		iscsi_put_be32( (uint8_t *) &login_response_pkt->exp_cmd_sn, conn->session->exp_cmd_sn );
		iscsi_put_be32( (uint8_t *) &login_response_pkt->max_cmd_sn, conn->session->max_cmd_sn );
	} else {
		iscsi_put_be32( (uint8_t *) &login_response_pkt->exp_cmd_sn, resp_pdu->cmd_sn );
		iscsi_put_be32( (uint8_t *) &login_response_pkt->max_cmd_sn, resp_pdu->cmd_sn );
	}

	if ( login_response_pkt->status_class != ISCSI_LOGIN_RESPONSE_STATUS_CLASS_SUCCESS ) {
		login_response_pkt->flags &= (int8_t) ~(ISCSI_LOGIN_RESPONSE_FLAGS_TRANSIT | ISCSI_LOGIN_RESPONSE_FLAGS_CURRENT_STAGE_MASK | ISCSI_LOGIN_RESPONSE_FLAGS_NEXT_STAGE_MASK );
	}

	return iscsi_connection_pdu_write( conn, resp_pdu ) ? 0 : -1;
}

/**
 * @brief Initializes an iSCSI login response PDU structure.
 *
 * This function initializes the internal login
 * response data structure which is part of the iSCSI
 * login procedure.
 *
 * @param[in] login_response_pdu Pointer to login response PDU, NULL
 * is not an allowed value here, so take caution.
 * @param[in] pdu Pointer to login request PDU from client,
 * may NOT be NULL, so be careful.
 * @return 0 if initialization was successful, a negative error
 * code otherwise.
 */
static int iscsi_connection_pdu_login_response_init(iscsi_pdu *login_response_pdu, const iscsi_pdu *pdu)
{
	iscsi_login_req_packet *login_req_pkt = (iscsi_login_req_packet *) pdu->bhs_pkt;
	iscsi_login_response_packet *login_response_pkt = (iscsi_login_response_packet *) login_response_pdu->bhs_pkt;

	login_response_pkt->opcode = ISCSI_OPCODE_SERVER_LOGIN_RES;
	login_response_pkt->flags  = (int8_t) (login_req_pkt->flags & (ISCSI_LOGIN_REQ_FLAGS_TRANSIT | ISCSI_LOGIN_REQ_FLAGS_CONTINUE | ISCSI_LOGIN_REQ_FLAGS_CURRENT_STAGE_MASK));

	if ( (login_response_pkt->flags & ISCSI_LOGIN_RESPONSE_FLAGS_TRANSIT) != 0 )
		login_response_pkt->flags |= (login_req_pkt->flags & ISCSI_LOGIN_REQ_FLAGS_NEXT_STAGE_MASK);

	login_response_pkt->isid          = login_req_pkt->isid;
	login_response_pkt->tsih          = 0;
	login_response_pkt->init_task_tag = login_req_pkt->init_task_tag; // Copying over doesn't change endianess.
	login_response_pkt->reserved      = 0UL;
	login_response_pdu->cmd_sn        = iscsi_get_be32(login_req_pkt->cmd_sn);
	login_response_pkt->stat_sn       = 0UL;
	login_response_pkt->reserved2     = 0U;
	login_response_pkt->reserved3     = 0ULL;

	if ( login_req_pkt->tsih != 0 ) {
		// Session resumption, not supported
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_SESSION_NO_EXIST;
	} else if ( ((login_response_pkt->flags & ISCSI_LOGIN_RESPONSE_FLAGS_TRANSIT) != 0) && ((login_response_pkt->flags & ISCSI_LOGIN_RESPONSE_FLAGS_CONTINUE) != 0) ) {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_MISC;
	} else if ( (ISCSI_VERSION_MAX < login_req_pkt->version_min) || (ISCSI_VERSION_MIN > login_req_pkt->version_max) ) {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_WRONG_VERSION;
	} else if ( (ISCSI_LOGIN_RESPONSE_FLAGS_GET_NEXT_STAGE(login_response_pkt->flags) == ISCSI_LOGIN_RESPONSE_FLAGS_NEXT_STAGE_RESERVED) && ((login_response_pkt->flags & ISCSI_LOGIN_RESPONSE_FLAGS_TRANSIT) != 0) ) {
		login_response_pkt->flags        &= (int8_t) ~(ISCSI_LOGIN_RESPONSE_FLAGS_NEXT_STAGE_MASK | ISCSI_LOGIN_RESPONSE_FLAGS_TRANSIT | ISCSI_LOGIN_RESPONSE_FLAGS_CURRENT_STAGE_MASK);
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_MISC;
	} else {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_SUCCESS;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_SUCCESS;

		return ISCSI_CONNECT_PDU_READ_OK;
	}

	return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
}

/**
 * @brief Determines the session type of login.
 *
 * This function is used to retrieve the
 * login session type and checks the
 * relevant key and value pair for
 * errors.
 *
 * @param[in] login_response_pdu Pointer to login response PDU,
 * NULL is not allowed, so take caution.
 * @param[in] type_str Pointer to key and value pairs which
 * contain the session type parameter to be evaluated,
 * which may NOT be NULL, so take caution.
 * @return 0 on successful operation, a negative error code
 * otherwise. The output session 'type' is unchanged, if
 * an invalid session type value was retrieved.
 */
static int iscsi_login_parse_session_type(iscsi_pdu *login_response_pdu, const char *type_str, int *type)
{
	iscsi_login_response_packet *login_response_pkt = (iscsi_login_response_packet *) login_response_pdu->bhs_pkt;

	if ( type_str != NULL && strcasecmp( type_str, "Normal" ) == 0 ) {
		*type = ISCSI_SESSION_TYPE_NORMAL;
		return ISCSI_CONNECT_PDU_READ_OK;
	}

	*type = ISCSI_SESSION_TYPE_INVALID;
	logadd( LOG_DEBUG1, "Unsupported session type: %s", type_str );
	login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
	login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_MISSING_PARAMETER;

	return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
}

/**
 * @brief Checks the target node info and sets login response PDU accordingly.
 *
 * This function also checks if the target node is
 * redirected and if so, sets the response to the
 * client response to the temporarily redirection
 * URL.\n
 * THe accessibility of the target node is
 * also checked.
 *
 * @param[in] conn Pointer to iSCSI connection which may NOT be
 * NULL, so be careful.
 * @param[in] login_response_pdu Pointer to login response PDU
 * to set the parameters for. NULL is NOT allowed
 * here, so take caution.
 * @param[in] target_name Pointer to target node name and may
 * NOT be NULL, be careful.
 * @return 0 if the check was successful or a negative
 * error code otherwise.
 */
static int iscsi_image_from_target(iscsi_connection *conn, iscsi_pdu *login_response_pdu, const char *target_name)
{
	iscsi_login_response_packet *login_response_pkt = (iscsi_login_response_packet *) login_response_pdu->bhs_pkt;

	char *image_rev        = NULL;
	char *tmpbuf           = strdup( target_name );
	char *image_name       = tmpbuf;
	char *tmp              = strchr( tmpbuf, ':' );

	if ( tmpbuf == NULL ) {
		logadd( LOG_ERROR, "iscsi_target_node_image_get: Out of memory while allocating DNBD3 image name for iSCSI target node" );
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_SERVER_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_SERVER_ERR_OUT_OF_RESOURCES;

		return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
	}

	while ( tmp != NULL ) {
		*tmp++ = '\0';
		if ( image_rev != NULL ) {
			image_name = image_rev;
		}
		image_rev  = tmp;
		tmp        = strchr( tmp, ':' );
	}

	uint16_t rev   = 0;
	if ( image_rev != NULL ) {
		char *end = NULL;
		long rid = strtol( image_rev, &end, 10 );
		if ( end == NULL || *end != '\0' || rid < 0 || rid > 0xFFFF ) {
			logadd( LOG_DEBUG1, "iscsi_image_from_target: Invalid revision number (%s) in iSCSI target node name: '%s'", image_rev, target_name );
		} else {
			rev = (uint16_t)rid;
		}
	}
	dnbd3_image_t *image = image_getOrLoad( image_name, rev );

	if ( image == NULL && image_rev != NULL ) {
		image = image_getOrLoad( image_rev, rev );
	}

	if ( image == NULL && strncasecmp( image_name, ISCSI_TARGET_NODE_WWN_NAME_PREFIX, ISCSI_STRLEN(ISCSI_TARGET_NODE_WWN_NAME_PREFIX) ) == 0 ) {
		uint64_t wwn = strtoull( (image_name + ISCSI_STRLEN(ISCSI_TARGET_NODE_WWN_NAME_PREFIX)), NULL, 16 );

		image = image_getByWwn( wwn, rev, true );

		if ( image == NULL ) {
			wwn   = strtoull( (tmp + ISCSI_STRLEN(ISCSI_TARGET_NODE_WWN_NAME_PREFIX)), NULL, 16 );
			image = image_getByWwn( wwn, rev, true );
		}
	}

	free( tmpbuf );

	if ( image == NULL ) {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_NOT_FOUND;

		return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
	}
	conn->client->image = image;

	return ISCSI_CONNECT_PDU_READ_OK;
}

/**
 * @brief Initializes a rejecting login response packet.
 *
 * The login response structure has status detail
 * invalid login request type set.
 *
 * @param[in] login_response_pdu Pointer to iSCSI login response PDU,
 * NULL is an invalid value here, so take caution.
 * @param[in] pdu Pointer to iSCSI login request PDU, may NOT
 * be NULL, so be careful.
 */
static void iscsi_connection_login_response_reject(iscsi_pdu *login_response_pdu, const iscsi_pdu *pdu)
{
	iscsi_login_response_packet *login_response_pkt = (iscsi_login_response_packet *) login_response_pdu->bhs_pkt;

	login_response_pkt->opcode                       = ISCSI_OPCODE_SERVER_LOGIN_RES;
	login_response_pkt->flags                        = 0;
	login_response_pkt->version_max                  = ISCSI_VERSION_MAX;
	login_response_pkt->version_active               = ISCSI_VERSION_MAX;
	*(uint32_t *) &login_response_pkt->total_ahs_len = 0UL; // TotalAHSLength and DataSegmentLength are always 0, so write in one step.
	login_response_pkt->tsih                         = 0U;
	login_response_pkt->init_task_tag                = ((iscsi_login_req_packet *) pdu->bhs_pkt)->init_task_tag;
	login_response_pkt->reserved                     = 0UL;
	login_response_pkt->stat_sn                      = 0UL;
	login_response_pkt->exp_cmd_sn                   = 0UL;
	login_response_pkt->max_cmd_sn                   = 0UL;
	login_response_pkt->status_class                 = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
	login_response_pkt->status_detail                = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_INVALID_LOGIN_REQ_TYPE;
	login_response_pkt->reserved2                    = 0U;
	login_response_pkt->reserved3                    = 0ULL;
}

/**
 * @brief Initializes an iSCSI Protocol Data Unit (PDU) object for use in iSCSI communication.
 *
 * Allocates and assigns the required memory for the Basic Header Segment (BHS) packet
 * and optionally for the aligned data segment (DS). Resets and initializes various fields
 * within the given PDU structure. Ensures proper memory alignment for data segment if
 * applicable, and zeroes out unused buffer regions.
 *
 * @param[in,out] pdu Pointer to the iSCSI PDU structure to initialize. Must not be NULL.
 * @param[in] ds_len Length of the Data Segment (DS) in bytes. Must not exceed ISCSI_MAX_DS_SIZE.
 * @param[in] no_ds_alloc If true, the Data Segment memory allocation is skipped.
 *
 * @retval true if initialization is successful.
 * @retval false if memory allocation for the BHS packet fails or ds_len exceeds the maximum allowed size.
 */
static bool iscsi_connection_pdu_init(iscsi_pdu *pdu, const uint32_t ds_len, bool no_ds_alloc)
{
	// Always set this pointer to NULL before any sanity checks,
	// so the attribute-cleanup magic won't screw up if init fails
	pdu->big_alloc = NULL;

	if ( ds_len > ISCSI_MAX_DS_SIZE ) {
		logadd( LOG_ERROR, "iscsi_pdu_init: Invalid DS length" );
		return false;
	}

	const uint32_t pkt_ds_len = no_ds_alloc ? 0 : ISCSI_ALIGN( ds_len, ISCSI_ALIGN_SIZE );
	const uint32_t alloc_len        = (uint32_t) ( sizeof(struct iscsi_bhs_packet) + pkt_ds_len );

	if ( alloc_len > ISCSI_INTERNAL_BUFFER_SIZE ) {
		pdu->bhs_pkt = pdu->big_alloc = malloc( alloc_len );
		if ( pdu->bhs_pkt == NULL ) {
			logadd( LOG_ERROR, "iscsi_pdu_init: Out of memory while allocating iSCSI BHS packet" );
			return false;
		}
	} else {
		pdu->bhs_pkt = (iscsi_bhs_packet *)pdu->internal_buffer;
	}

	pdu->ahs_pkt                 = NULL;
	pdu->ds_cmd_data             = (pkt_ds_len != 0UL)
		? (iscsi_scsi_ds_cmd_data *) (((uint8_t *) pdu->bhs_pkt) + sizeof(struct iscsi_bhs_packet))
		: NULL;
	pdu->flags                   = 0;
	pdu->bhs_pos                 = 0U;
	pdu->ahs_len                 = 0;
	pdu->ds_len                  = ds_len;
	pdu->ds_write_pos            = 0;
	pdu->cmd_sn                  = 0UL;

	if ( pkt_ds_len > ds_len ) {
		memset( (((uint8_t *) pdu->ds_cmd_data) + ds_len), 0, (pkt_ds_len - ds_len) );
	}

	return true;
}

/**
 * @brief Frees resources associated with an iSCSI PDU (Protocol Data Unit).
 *
 * This function releases memory allocated for certain members of the iSCSI
 * PDU structure. It ensures that the allocated resources are properly freed.
 * If the provided PDU pointer is NULL, the function returns immediately without
 * performing any operations.
 *
 * @param[in] pdu Pointer to the iSCSI PDU structure to be destroyed.
 * If NULL, the function has no effect.
 */
static void iscsi_connection_pdu_destroy(iscsi_pdu *pdu)
{
	if ( pdu == NULL )
		return;
	free( pdu->big_alloc );
}

/**
 * @brief Appends packet data to an iSCSI PDU structure used by connections.
 *
 * This function adjusts the pointers if
 * the packet data size needs to be
 * extended.
 *
 * @param[in] pdu Pointer to iSCSI PDU where to append
 * the packet data to. May NOT be NULL, so
 * be careful.
 * @param[in] ahs_len Length of AHS packet data to be appended.
 * @param[in] ds_len Length of DataSegment packet data to be appended.
 * May not exceed 16MiB - 1 (16777215 bytes).
 * @return Pointer to allocated and zero filled PDU or NULL
 * in case of an error (usually memory exhaustion).
 */
static iscsi_bhs_packet *iscsi_connection_pdu_resize(iscsi_pdu *pdu, const uint ahs_len,  const uint32_t ds_len)
{
	if ( (ahs_len != pdu->ahs_len) || (ds_len != pdu->ds_len) ) {
		if ( (ahs_len > ISCSI_MAX_AHS_SIZE) || (ds_len > ISCSI_MAX_DS_SIZE) || (ahs_len % ISCSI_ALIGN_SIZE != 0) ) {
			logadd( LOG_ERROR, "iscsi_connection_pdu_resize: Invalid AHS or DataSegment packet size" );
			return NULL;
		}
		if ( pdu->ds_len != 0 && pdu->ds_cmd_data == NULL ) {
			// If you really ever need this, handle it properly below (old_len, no copying, etc.)
			logadd( LOG_ERROR, "iscsi_connection_pdu_resize: Cannot resize PDU with virtual DS" );
			return NULL;
		}
		if ( pdu->ds_len != 0 && pdu->ahs_len != ahs_len && ds_len != 0 ) {
			// Cannot resize the AHS of a PDU that already has a DS and should keep the DS - we'd need to move the data
			// around. Implement this when needed (and make sure it works).
			logadd( LOG_ERROR, "iscsi_connection_pdu_resize: Cannot resize PDU's AHS that also has a DS" );
			return NULL;
		}

		iscsi_bhs_packet *bhs_pkt;
		const uint32_t pkt_ds_len = ISCSI_ALIGN(ds_len, ISCSI_ALIGN_SIZE);
		const size_t old_len      = (sizeof(struct iscsi_bhs_packet) + (uint32_t) pdu->ahs_len + ISCSI_ALIGN(pdu->ds_len, ISCSI_ALIGN_SIZE));
		const size_t new_len      = (sizeof(struct iscsi_bhs_packet) + (uint32_t) ahs_len + pkt_ds_len);
		const bool old_alloced    = pdu->big_alloc != NULL;
		const bool new_alloced    = new_len > ISCSI_INTERNAL_BUFFER_SIZE;

		if ( new_len == old_len ) {
			// Nothing changed
			bhs_pkt = pdu->bhs_pkt;
		} else {
			if ( new_alloced ) {
				// New block doesn't fit in internal buffer - (re)allocate big buffer
				bhs_pkt = realloc( pdu->big_alloc, new_len );
				if ( bhs_pkt == NULL ) {
					logadd( LOG_ERROR, "iscsi_connection_pdu_resize: Out of memory while reallocating iSCSI PDU packet data" );
					return NULL;
				}
				if ( !old_alloced ) {
					// Old was in internal buffer, copy contents
					memcpy( bhs_pkt, pdu->internal_buffer, MIN(new_len, old_len) );
				}
				// Update PDU's BHS pointer
				pdu->big_alloc = bhs_pkt;
				pdu->bhs_pkt = bhs_pkt;
			} else {
				// New block fits into internal buffer - ignore for now and keep in big buffer
				// to avoid needless overhead - PDUs are short-lived anyways.
				// Keep using old BHS pointer
				bhs_pkt = pdu->bhs_pkt;
			}
		}

		pdu->ahs_pkt            = (ahs_len != 0U) ? (iscsi_ahs_packet *) (((uint8_t *) bhs_pkt) + sizeof(struct iscsi_bhs_packet)) : NULL;
		pdu->ds_cmd_data        = (pkt_ds_len != 0UL) ? (iscsi_scsi_ds_cmd_data *) (((uint8_t *) bhs_pkt) + sizeof(struct iscsi_bhs_packet) + ahs_len) : NULL;
		pdu->ahs_len            = ahs_len;
		pdu->ds_len             = ds_len;

		if ( pkt_ds_len != 0UL ) {
			memset( (((uint8_t *) pdu->ds_cmd_data) + ds_len), 0, (pkt_ds_len - ds_len) );
		}
	}

	return pdu->bhs_pkt;
}

/**
 * @brief Writes and sends a response PDU to the client.
 *
 * This function sends a response PDU to the
 * client after being processed by the server.\n
 * If a header or data digest (CRC32C) needs to
 * be calculated, this is done as well.
 *
 * @param[in] conn Pointer to iSCSI connection to handle. May
 * NOT be NULL, so take caution. Will be freed after sending,
 * so don't access afterwards.
 * @param[in] pdu Pointer to iSCSI server response PDU to send.
 * May NOT be NULL, so be careful.
 */
static bool iscsi_connection_pdu_write(iscsi_connection *conn, iscsi_pdu *pdu)
{
	if ( conn->state >= ISCSI_CONNECT_STATE_EXITING ) {
		return false;
	}

	// During allocation we already round up to ISCSI_ALIGN_SIZE, but store the requested size in the ds_len
	// member, so it's safe to round up here before sending, the accessed memory will be valid and zeroed
	const size_t len = (sizeof(struct iscsi_bhs_packet) + pdu->ahs_len
		+ (pdu->ds_cmd_data == NULL ? 0 : ISCSI_ALIGN(pdu->ds_len, ISCSI_ALIGN_SIZE)));
	const ssize_t rc = sock_sendAll( conn->client->sock, pdu->bhs_pkt, len, ISCSI_CONNECT_SOCKET_WRITE_RETRIES );

	if ( rc != (ssize_t)len ) {
		conn->state = ISCSI_CONNECT_STATE_EXITING;
		return false;
	}
	return true;
}

/**
 * @brief Compares if the first iSCSI 32-bit sequence numbers is smaller than the second one.
 *
 * This function almost does the same as an
 * unsigned compare but with special
 * handling for "negative" numbers.
 *
 * @param[in] seq_num First iSCSI sequence number to be compared.
 * @param[in] seq_num_2 Second iSCSI sequence number to be compared.
 * @retval true if first sequence number is smaller than
 * the second one.
 * @retval false if first sequence number is equal or
 * larger than the second one.
 */
static inline int iscsi_seq_num_cmp_lt(const uint32_t seq_num, const uint32_t seq_num_2)
{
	return (seq_num != seq_num_2) && (((seq_num < seq_num_2) && ((seq_num_2 - seq_num) < 2147483648UL)) || ((seq_num > seq_num_2) && ((seq_num - seq_num_2)) > 2147483648UL));
}

/**
 * @brief Compares if the first iSCSI 32-bit sequence numbers is larger than the second one.
 *
 * This function almost does the same as an
 * unsigned compare but with special
 * handling for "negative" numbers.
 *
 * @param[in] seq_num First iSCSI sequence number to be compared.
 * @param[in] seq_num_2 Second iSCSI sequence number to be compared.
 * @retval true if first sequence number is larger than
 * the second one.
 * @retval false if first sequence number is equal or
 * smaller than the second one.
 */
static inline int iscsi_seq_num_cmp_gt(const uint32_t seq_num, const uint32_t seq_num_2)
{
	return (seq_num != seq_num_2) && (((seq_num < seq_num_2) && ((seq_num_2 - seq_num) > 2147483648UL)) || ((seq_num > seq_num_2) && ((seq_num - seq_num_2)) < 2147483648UL));
}

/**
 * @brief Constructs and sends an iSCSI reject response to the client.
 *
 * This function constructs an reject response PDU with its
 * packet data.\n
 * The original rejected packet data is appended as DataSegment
 * according by iSCSI standard specification.
 *
 * @param[in] conn Pointer to iSCSI connection for reject packet construction.
 * @param[in] pdu Pointer to iSCSI source PDU which contains the rejected packet data.
 * @param[in] reason_code Reason code for rejected packet data.
 * @retval -1 An error ocurred during reject packet generation,
 * currently only happens on memory exhaustion.
 * @retval 0 Reject packet and PDU constructed and sent successfully to the client.
 */
static int iscsi_connection_handle_reject(iscsi_connection *conn, iscsi_pdu *pdu, const int reason_code)
{
	const uint32_t ds_len   = (uint32_t) sizeof(struct iscsi_bhs_packet) + (uint32_t) (pdu->bhs_pkt->total_ahs_len * ISCSI_ALIGN_SIZE);
	iscsi_pdu CLEANUP_PDU response_pdu;
	if ( !iscsi_connection_pdu_init( &response_pdu, ds_len, false ) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	iscsi_reject_packet *reject_pkt = (iscsi_reject_packet *) response_pdu.bhs_pkt;

	reject_pkt->opcode    = ISCSI_OPCODE_SERVER_REJECT;
	reject_pkt->flags     = -0x80;
	reject_pkt->reason    = (uint8_t) reason_code;
	reject_pkt->reserved  = 0U;
	iscsi_put_be32( (uint8_t *) &reject_pkt->total_ahs_len, ds_len ); // TotalAHSLength is always 0 and DataSegmentLength is 24-bit, so write in one step.
	reject_pkt->reserved2 = 0ULL;
	reject_pkt->tag       = 0xFFFFFFFFUL; // Minus one does not require endianess conversion
	reject_pkt->reserved3 = 0UL;
	iscsi_put_be32( (uint8_t *) &reject_pkt->stat_sn, conn->stat_sn++ );

	if ( conn->session != NULL ) {
		iscsi_put_be32( (uint8_t *) &reject_pkt->exp_cmd_sn, conn->session->exp_cmd_sn );
		iscsi_put_be32( (uint8_t *) &reject_pkt->max_cmd_sn, conn->session->max_cmd_sn );
	} else {
		iscsi_put_be32( (uint8_t *) &reject_pkt->exp_cmd_sn, 1UL );
		iscsi_put_be32( (uint8_t *) &reject_pkt->max_cmd_sn, 1UL );
	}

	reject_pkt->reserved4 = 0ULL;

	memcpy( response_pdu.ds_cmd_data, pdu->bhs_pkt, ds_len );

	iscsi_connection_pdu_write( conn, &response_pdu );

	return ISCSI_CONNECT_PDU_READ_OK;
}

/**
 * @brief Updates the expected command sequence number (ExpCmdSN) and validates sequence number bounds.
 *
 * This function extracts the CmdSN and checks whether it fits within the session's
 * expected command sequence range, considering session type and iSCSI operation types.
 * Also updates session-related sequence numbers as needed based on the received command.
 *
 * @param[in] conn Pointer to the iSCSI connection. Must not be NULL, and its session pointer should also be valid.
 * @param[in] request_pdu Pointer to the iSCSI PDU (Protocol Data Unit) containing command information. Must not be NULL.
 *
 * @return Returns `ISCSI_CONNECT_PDU_READ_OK` (0) on success or
 *         `ISCSI_CONNECT_PDU_READ_ERR_FATAL` (-1) if sequence numbers or other data are invalid.
 */
static int iscsi_connection_handle_cmd_sn(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	iscsi_session *session = conn->session;

	if ( session == NULL )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	iscsi_scsi_cmd_packet *scsi_cmd_pkt = (iscsi_scsi_cmd_packet *) request_pdu->bhs_pkt;
	const int opcode = ISCSI_GET_OPCODE(scsi_cmd_pkt->opcode);

	request_pdu->cmd_sn = iscsi_get_be32(scsi_cmd_pkt->cmd_sn);

	if ( (scsi_cmd_pkt->opcode & ISCSI_OPCODE_FLAGS_IMMEDIATE) == 0 ) {
		if ( (iscsi_seq_num_cmp_lt( request_pdu->cmd_sn, session->exp_cmd_sn )
				|| iscsi_seq_num_cmp_gt( request_pdu->cmd_sn, session->max_cmd_sn ))
				&& ((session->type == ISCSI_SESSION_TYPE_NORMAL) && (opcode != ISCSI_OPCODE_CLIENT_SCSI_DATA_OUT)) ) {
			logadd( LOG_WARNING, "Seqnum messup. Is: %u, want >= %u, < %u",
				request_pdu->cmd_sn, session->exp_cmd_sn, session->max_cmd_sn );
			return ISCSI_CONNECT_PDU_READ_ERR_FATAL;
		}
	} else if ( (request_pdu->cmd_sn != session->exp_cmd_sn) && (opcode != ISCSI_OPCODE_CLIENT_NOP_OUT) ) {
		logadd( LOG_WARNING, "Seqnum messup. Is: %u, want: %u",
			request_pdu->cmd_sn, session->exp_cmd_sn );
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;
	}

	if ( ((scsi_cmd_pkt->opcode & ISCSI_OPCODE_FLAGS_IMMEDIATE) == 0) && (opcode != ISCSI_OPCODE_CLIENT_SCSI_DATA_OUT) )
		session->exp_cmd_sn++;

	return ISCSI_CONNECT_PDU_READ_OK;
}

/**
 * @brief Handles an incoming iSCSI header logout request PDU.
 *
 * This function handles logout request header
 * data sent by the client.\n
 * If a response needs to be sent, this will
 * be done as well.
 *
 * @param[in] conn Pointer to iSCSI connection to handle. May
 * NOT be NULL, so take caution.
 * @param[in] request_pdu Pointer to iSCSI client request PDU to handle.
 * May be NULL in which case an error is returned.
 * @return 0 on success. A negative value indicates
 * an error. A positive value a warning.
 */
static int iscsi_connection_handle_logout_req(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	iscsi_logout_req_packet *logout_req_pkt = (iscsi_logout_req_packet *) request_pdu->bhs_pkt;

	if ( (conn->session != NULL) && (conn->session->type == ISCSI_SESSION_TYPE_DISCOVERY) && (logout_req_pkt->reason_code != ISCSI_LOGOUT_REQ_REASON_CODE_CLOSE_SESSION) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	iscsi_pdu CLEANUP_PDU response_pdu;
	if ( !iscsi_connection_pdu_init( &response_pdu, 0, false ) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	iscsi_logout_response_packet *logout_response_pkt = (iscsi_logout_response_packet *) response_pdu.bhs_pkt;

	logout_response_pkt->opcode = ISCSI_OPCODE_SERVER_LOGOUT_RES;
	logout_response_pkt->flags  = -0x80;

	const uint16_t cid = iscsi_get_be16(logout_req_pkt->cid);

	if ( cid == conn->cid ) {
		logout_response_pkt->response = ISCSI_LOGOUT_RESPONSE_CLOSED_SUCCESSFULLY;
	} else {
		logout_response_pkt->response = ISCSI_LOGOUT_RESPONSE_CID_NOT_FOUND;
	}

	logout_response_pkt->reserved                     = 0U;
	*(uint32_t *) &logout_response_pkt->total_ahs_len = 0UL; // TotalAHSLength and DataSegmentLength are always 0, so write in one step.
	logout_response_pkt->reserved2                    = 0ULL;
	logout_response_pkt->init_task_tag                = logout_req_pkt->init_task_tag; // Copying over doesn't change endianess.
	logout_response_pkt->reserved3                    = 0UL;
	iscsi_put_be32( (uint8_t *) &logout_response_pkt->stat_sn, conn->stat_sn++ );

	if ( conn->session != NULL ) {
		conn->session->max_cmd_sn++;

		iscsi_put_be32( (uint8_t *) &logout_response_pkt->exp_cmd_sn, conn->session->exp_cmd_sn );
		iscsi_put_be32( (uint8_t *) &logout_response_pkt->max_cmd_sn, conn->session->max_cmd_sn );
	} else {
		iscsi_put_be32( (uint8_t *) &logout_response_pkt->exp_cmd_sn, request_pdu->cmd_sn );
		iscsi_put_be32( (uint8_t *) &logout_response_pkt->max_cmd_sn, request_pdu->cmd_sn );
	}

	logout_response_pkt->reserved4   = 0UL;
	logout_response_pkt->time_wait   = 0U;
	logout_response_pkt->time_retain = 0U;
	logout_response_pkt->reserved5   = 0UL;

	bool ret = iscsi_connection_pdu_write( conn, &response_pdu );

	if ( cid == conn->cid ) {
		conn->state = ISCSI_CONNECT_STATE_EXITING;
	}

	return ret ? ISCSI_CONNECT_PDU_READ_OK : ISCSI_CONNECT_PDU_READ_ERR_FATAL;
}

/**
 * @brief Handles an iSCSI task management function request and generates an appropriate response.
 *
 * This function processes an incoming iSCSI task management function request PDU,
 * constructs a corresponding response PDU, and sends it back to the initiator.
 *
 * @param[in] conn Pointer to the iSCSI connection structure. Must not be NULL.
 * This represents the connection for which the request is being handled.
 * @param[in] request_pdu Pointer to the incoming iSCSI task management function
 * request PDU. Must not be NULL.
 *
 * @return 0 on successful PDU write, or -1 on failure.
 */
static int iscsi_connection_handle_task_func_req(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	iscsi_pdu CLEANUP_PDU response_pdu;
	if ( !iscsi_connection_pdu_init( &response_pdu, 0, false ) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;
	iscsi_task_mgmt_func_response_packet *mgmt_resp = (iscsi_task_mgmt_func_response_packet *) response_pdu.bhs_pkt;
	iscsi_task_mgmt_func_req_packet *mgmt_req = (iscsi_task_mgmt_func_req_packet *) request_pdu->bhs_pkt;

	mgmt_resp->opcode        = ISCSI_OPCODE_SERVER_TASK_FUNC_RES;
	mgmt_resp->response      = ISCSI_TASK_MGMT_FUNC_RESPONSE_FUNC_COMPLETE;
	mgmt_resp->flags         = 0x80;
	mgmt_resp->init_task_tag = mgmt_req->init_task_tag; // Copying over doesn't change endianess.
	iscsi_put_be32( (uint8_t *) &mgmt_resp->stat_sn, conn->stat_sn++ );
	iscsi_put_be32( (uint8_t *) &mgmt_resp->exp_cmd_sn, conn->session->exp_cmd_sn );
	iscsi_put_be32( (uint8_t *) &mgmt_resp->max_cmd_sn, conn->session->max_cmd_sn );

	return iscsi_connection_pdu_write( conn, &response_pdu ) ? 0 : -1;
}

/**
 * @brief Handles an incoming iSCSI payload data NOP-Out request PDU.
 *
 * This function handles NOP-Out request payload
 * data sent by the client.\n
 * If a response needs to be sent, this will
 * be done as well.
 *
 * @param[in] conn Pointer to iSCSI connection to handle. May
 * NOT be NULL, so take caution.
 * @param[in] request_pdu Pointer to iSCSI client request PDU to handle.
 * May be NULL in which case an error is returned.
 * @param response_pdu
 * @return 0 on success. A negative value indicates
 * an error. A positive value a warning.
 */
static int iscsi_connection_handle_nop_out(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	if ( conn->session->type == ISCSI_SESSION_TYPE_DISCOVERY )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	if ( request_pdu->ds_len > ISCSI_DEFAULT_MAX_RECV_DS_LEN )
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_PROTOCOL_ERR );

	iscsi_nop_out_packet *nop_out_pkt = (iscsi_nop_out_packet *) request_pdu->bhs_pkt;
	const uint32_t target_xfer_tag    = iscsi_get_be32(nop_out_pkt->target_xfer_tag);
	uint32_t ds_len                   = request_pdu->ds_len;
	const uint64_t lun                = iscsi_get_be64(nop_out_pkt->lun);

	if ( nop_out_pkt->init_task_tag == 0xFFFFFFFFUL ) // Was response to a NOP by us - do not reply
		return ISCSI_CONNECT_PDU_READ_OK;

	if ( (target_xfer_tag != 0xFFFFFFFFUL) && (target_xfer_tag != (uint32_t) conn->id) )
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_INVALID_PDU_FIELD ); // TODO: Check if this is the correct error code.

	if ( (nop_out_pkt->init_task_tag == 0xFFFFFFFFUL) && (nop_out_pkt->opcode & ISCSI_OPCODE_FLAGS_IMMEDIATE) == 0 )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	if ( ds_len > (uint32_t)conn->session->opts.MaxRecvDataSegmentLength )
		ds_len = conn->session->opts.MaxRecvDataSegmentLength;

	iscsi_pdu CLEANUP_PDU response_pdu;
	if ( !iscsi_connection_pdu_init( &response_pdu, ds_len, false ) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	iscsi_nop_in_packet *nop_in_pkt = (iscsi_nop_in_packet *) response_pdu.bhs_pkt;

	nop_in_pkt->opcode          = ISCSI_OPCODE_SERVER_NOP_IN;
	nop_in_pkt->flags           = -0x80;
	nop_in_pkt->reserved        = 0U;
	iscsi_put_be32( (uint8_t *) &nop_in_pkt->total_ahs_len, ds_len ); // TotalAHSLength is always 0 and DataSegmentLength is 24-bit, so write in one step.
	iscsi_put_be64( (uint8_t *) &nop_in_pkt->lun, lun );
	nop_in_pkt->target_xfer_tag = 0xFFFFFFFFUL; // Minus one does not require endianess conversion
	nop_in_pkt->init_task_tag = nop_out_pkt->init_task_tag; // Copyed from request packet, no endian conversion required
	iscsi_put_be32( (uint8_t *) &nop_in_pkt->stat_sn, conn->stat_sn++ );

	if ( (nop_out_pkt->opcode & ISCSI_OPCODE_FLAGS_IMMEDIATE) == 0 )
		conn->session->max_cmd_sn++;

	iscsi_put_be32( (uint8_t *) &nop_in_pkt->exp_cmd_sn, conn->session->exp_cmd_sn );
	iscsi_put_be32( (uint8_t *) &nop_in_pkt->max_cmd_sn, conn->session->max_cmd_sn );
	nop_in_pkt->reserved2 = 0UL;
	nop_in_pkt->reserved3 = 0ULL;

	if ( ds_len != 0UL ) {
		memcpy( response_pdu.ds_cmd_data, request_pdu->ds_cmd_data, ds_len );
	}

	iscsi_connection_pdu_write( conn, &response_pdu );

	return ISCSI_CONNECT_PDU_READ_OK;
}

/**
 * @brief Handles an incoming iSCSI payload data SCSI command request PDU.
 *
 * This function handles SCSI command request payload
 * data sent by the client.\n
 * If a response needs to be sent, this will
 * be done as well.
 *
 * @param[in] conn Pointer to iSCSI connection to handle. May
 * NOT be NULL, so take caution.
 * @param[in] request_pdu Pointer to iSCSI client request PDU to handle.
 * May be NULL in which case an error is returned.
 * @return 0 on success. A negative value indicates
 * an error. A positive value a warning.
 */
static int iscsi_connection_handle_scsi_cmd(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	iscsi_scsi_cmd_packet *scsi_cmd_pkt = (iscsi_scsi_cmd_packet *) request_pdu->bhs_pkt;

	if ( (scsi_cmd_pkt->flags_task & ISCSI_SCSI_CMD_FLAGS_TASK_WRITE) != 0 ) { // Bidirectional transfer is not supported
		logadd( LOG_DEBUG1, "Received SCSI write command from %s", conn->client->hostName );
		// Should really return a write protect error on SCSI layer, but a well-behaving client shouldn't ever
		// send a write command anyways, since we declare the device read only.
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_COMMAND_NOT_SUPPORTED );
	}

	iscsi_task *task = iscsi_task_create( conn );

	if ( task == NULL ) {
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_OUT_OF_RESOURCES );
	}

	uint32_t exp_xfer_len = iscsi_get_be32(scsi_cmd_pkt->exp_xfer_len);

	task->scsi_task.cdb          = &scsi_cmd_pkt->scsi_cdb;
	task->scsi_task.exp_xfer_len = exp_xfer_len;
	task->init_task_tag          = iscsi_get_be32(scsi_cmd_pkt->init_task_tag);

	const uint64_t lun = iscsi_get_be64(scsi_cmd_pkt->lun);
	task->lun_id       = iscsi_scsi_lun_get_from_iscsi( lun );

	if ( (scsi_cmd_pkt->flags_task & ISCSI_SCSI_CMD_FLAGS_TASK_READ) == 0 ) {
		if ( exp_xfer_len != 0UL ) {
			// Not a read request, but expecting data - not valid
			iscsi_scsi_task_status_set( &task->scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ, ISCSI_SCSI_ASC_INVALID_FIELD_IN_CDB, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );
			iscsi_task_destroy( task );

			return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_INVALID_PDU_FIELD );
		}
	} else {
		task->scsi_task.is_read = true;
	}
	task->scsi_task.is_write = (scsi_cmd_pkt->flags_task & ISCSI_SCSI_CMD_FLAGS_TASK_WRITE) != 0;

	int rc;

	if ( task->lun_id != ISCSI_DEFAULT_LUN ) {
		logadd( LOG_WARNING, "Received SCSI command for unknown LUN %d", task->lun_id );
		iscsi_scsi_task_lun_process_none( &task->scsi_task );
		rc = ISCSI_CONNECT_PDU_READ_OK;
	} else {
		task->scsi_task.status = ISCSI_SCSI_STATUS_GOOD;

		rc = iscsi_scsi_emu_block_process( &task->scsi_task );

		if ( rc == ISCSI_SCSI_TASK_RUN_UNKNOWN ) {
			rc = iscsi_scsi_emu_primary_process( &task->scsi_task );

			if ( rc == ISCSI_SCSI_TASK_RUN_UNKNOWN ) {
				iscsi_scsi_task_status_set( &task->scsi_task, ISCSI_SCSI_STATUS_CHECK_COND, ISCSI_SCSI_SENSE_KEY_ILLEGAL_REQ, ISCSI_SCSI_ASC_INVALID_COMMAND_OPERATION_CODE, ISCSI_SCSI_ASCQ_CAUSE_NOT_REPORTABLE );
				rc = ISCSI_SCSI_TASK_RUN_COMPLETE;
			}
		}
	}

	if ( rc == ISCSI_SCSI_TASK_RUN_COMPLETE ) {
		iscsi_scsi_task_xfer_complete( conn, &task->scsi_task, request_pdu );
	}

	iscsi_task_destroy( task );

	return ISCSI_CONNECT_PDU_READ_OK;
}

/**
 * @brief Handles iSCSI connection login phase none.
 *
 * This function negotiates the login phase
 * without a session.
 *
 * @param[in] conn Pointer to iSCSI connection,
 * may NOT be NULL, so be careful.
 * @param[in] login_response_pdu Pointer to login response PDU.
 * NULL is not allowed here, so take caution.
 * @param[in] kvpairs Pointer to key and value pairs.
 * which may NOT be NULL, so take caution.
 * @return 0 on success, a negative error code otherwise.
 */
static int iscsi_connection_handle_login_phase_none(iscsi_connection *conn, iscsi_pdu *login_response_pdu, iscsi_negotiation_kvp *kvpairs)
{
	int type, rc;
	iscsi_login_response_packet *login_response_pkt = (iscsi_login_response_packet *) login_response_pdu->bhs_pkt;

	rc = iscsi_login_parse_session_type( login_response_pdu, kvpairs->SessionType, &type );

	if ( rc < 0 )
		return rc;

	if ( type != ISCSI_SESSION_TYPE_NORMAL ) {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_SESSION_NO_SUPPORT;
		rc = ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
	} else if ( kvpairs->TargetName != NULL ) {
		rc = iscsi_image_from_target( conn, login_response_pdu, kvpairs->TargetName );
	} else {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_MISSING_PARAMETER;
		rc = ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
	}

	if ( rc < 0 )
		return rc;

	if ( conn->session == NULL ) {
		conn->session = iscsi_session_create( type );

		if ( conn->session == NULL ) {
			login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_SERVER_ERR;
			login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_SERVER_ERR_OUT_OF_RESOURCES;

			return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
		}

		conn->stat_sn            = iscsi_get_be32(login_response_pkt->stat_sn);

		conn->session->exp_cmd_sn  = login_response_pdu->cmd_sn;
		conn->session->max_cmd_sn  = (uint32_t) (login_response_pdu->cmd_sn + ISCSI_DEFAULT_QUEUE_DEPTH - 1UL);
	}

	return ISCSI_CONNECT_PDU_READ_OK;
}

/**
 * @brief Writes login options to a PDU (Protocol Data Unit).
 *
 * This function processes key-value pairs of login negotiation options and
 * appends them to the specified PDU. The function ensures the payload of the
 * response PDU does not exceed its designated length.
 *
 * @param[in] conn Pointer to the iSCSI connection structure containing session
 * options and other connection-specific information.
 * @param[in] pairs Pointer to the iSCSI negotiation key-value pairs structure
 * that holds applicable key-value options for the login phase.
 * @param[in,out] response_pdu Pointer to the PDU where the login options should
 * be added. The PDU's fields, such as data segment and payload length, are
 * updated within the function.
 *
 * @return The updated payload length of the response PDU if successful.
 * Returns -1 if an error occurs during key-value pair appending.
 */
static int iscsi_write_login_options_to_pdu( iscsi_connection *conn, iscsi_negotiation_kvp *pairs, iscsi_pdu *response_pdu )
{
	uint payload_len = response_pdu->ds_write_pos;

#	define ADD_KV_INTERNAL(num, key, value) do { \
int rc = iscsi_append_key_value_pair_packet( num, key, value, (char *)response_pdu->ds_cmd_data, payload_len, response_pdu->ds_len ); \
if ( rc < 0 ) return -1; \
payload_len += rc; \
} while (0)
#	define ADD_KV_OPTION_INT(key) do { \
if ( pairs->key != -1 ) ADD_KV_INTERNAL( true, #key, (const char *)(size_t)conn->session->opts.key ); \
} while (0)
#	define ADD_KV_OPTION_STR(key) do { \
if ( pairs->key != NULL ) ADD_KV_INTERNAL( false, #key, conn->session->opts.key ); \
} while (0)
#	define ADD_KV_PLAIN_INT(key, value) do { \
if ( pairs->key != -1 ) ADD_KV_INTERNAL( true, #key, (const char *)(size_t)(value) ); \
} while (0)
#	define ADD_KV_PLAIN_STR(key, value) do { \
if ( pairs->key != NULL ) ADD_KV_INTERNAL( false, #key, value ); \
} while (0)
	ADD_KV_OPTION_INT( MaxRecvDataSegmentLength );
	ADD_KV_OPTION_INT( MaxBurstLength );
	ADD_KV_OPTION_INT( FirstBurstLength );
	ADD_KV_PLAIN_INT( MaxConnections, 1 );
	ADD_KV_PLAIN_INT( ErrorRecoveryLevel, 0 );
	ADD_KV_PLAIN_STR( HeaderDigest, "None" );
	ADD_KV_PLAIN_STR( DataDigest, "None" );
#	undef ADD_KV_PLAIN
#	undef ADD_KV_OPTION_INT
#	undef ADD_KV_OPTION_STR

	if ( payload_len <= response_pdu->ds_len ) {
		response_pdu->ds_write_pos = payload_len;
	} else {
		response_pdu->ds_write_pos = response_pdu->ds_len;
	}
	return (int)payload_len;
}

/**
 * @brief Handles iSCSI connection login response.
 *
 * This function negotiates the login parameters
 * and determines the authentication method.
 *
 * @param[in] conn Pointer to iSCSI connection,
 * may NOT be NULL, so be careful.
 * @param[in] login_response_pdu Pointer to login response PDU.
 * NULL is not allowed here, so take caution.
 * @return 0 on success, a negative error code otherwise.
 */
static int iscsi_connecction_handle_login_response(iscsi_connection *conn, iscsi_pdu *login_response_pdu,  iscsi_negotiation_kvp *pairs)
{
	if ( iscsi_connection_pdu_resize( login_response_pdu, 0, ISCSI_DEFAULT_RECV_DS_LEN ) == NULL ) {
		return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
	}
	iscsi_login_response_packet *login_response_pkt = (iscsi_login_response_packet *) login_response_pdu->bhs_pkt;

	// Handle current stage (CSG bits)
	switch ( ISCSI_LOGIN_RESPONSE_FLAGS_GET_CURRENT_STAGE(login_response_pkt->flags) ) {
	case ISCSI_LOGIN_RESPONSE_FLAGS_CURRENT_STAGE_SECURITY_NEGOTIATION : {
		logadd( LOG_DEBUG1, "security nego" );
		if ( pairs->AuthMethod == NULL || strcasecmp( pairs->AuthMethod, "None" ) != 0 ) {
			// Only "None" supported
			login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
			login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_AUTH_ERR;

			return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
		}

		break;
	}
	case ISCSI_LOGIN_RESPONSE_FLAGS_CURRENT_STAGE_LOGIN_OPERATIONAL_NEGOTIATION : {
		// Nothing to do, expect client to request transition to full feature phase
		break;
	}
	case ISCSI_LOGIN_RESPONSE_FLAGS_CURRENT_STAGE_FULL_FEATURE_PHASE :
	default : {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_MISC;

		return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
	}
	}

	if ( (login_response_pkt->flags & ISCSI_LOGIN_RESPONSE_FLAGS_TRANSIT) != 0 ) {
		// Client set the transition bit - requests to move on to next stage
		switch ( ISCSI_LOGIN_RESPONSE_FLAGS_GET_NEXT_STAGE(login_response_pkt->flags) ) {
		case ISCSI_LOGIN_RESPONSE_FLAGS_NEXT_STAGE_FULL_FEATURE_PHASE : {
			conn->login_phase = ISCSI_LOGIN_RESPONSE_FLAGS_NEXT_STAGE_FULL_FEATURE_PHASE;

			iscsi_put_be16( (uint8_t *) &login_response_pkt->tsih, 42 );

			conn->state = ISCSI_CONNECT_STATE_NORMAL_SESSION;

			iscsi_connection_update_key_value_pairs( conn, pairs );
			int payload_len = iscsi_write_login_options_to_pdu( conn, pairs, login_response_pdu );

			if ( payload_len < 0 || (uint32_t)payload_len > login_response_pdu->ds_len ) {
				logadd( LOG_DEBUG1, "iscsi_connecction_handle_login_response: Invalid payload length %d, ds_len: %u, write_pos: %u",
					payload_len, login_response_pdu->ds_len, login_response_pdu->ds_write_pos );
				login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_SERVER_ERR;
				login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_SERVER_ERR_OUT_OF_RESOURCES;

				return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
			}

			break;
		}
		default : {
			login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
			login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_MISC;

			return ISCSI_CONNECT_PDU_READ_ERR_LOGIN_RESPONSE;
		}
		}
	}

	return ISCSI_CONNECT_PDU_READ_OK;
}

/**
 * @brief Handles an incoming iSCSI payload data login request PDU.
 *
 * This function handles login request payload
 * data sent by the client.\n
 * If a response needs to be sent, this will
 * be done as well.
 *
 * @param[in] conn Pointer to iSCSI connection to handle. May
 * NOT be NULL, so take caution.
 * @param[in] request_pdu Pointer to iSCSI client request PDU to handle.
 * May be NULL in which case an error is returned.
 * @param login_response_pdu
 * @return 0 on success. A negative value indicates
 * an error. A positive value a warning.
 */
static int iscsi_connection_handle_login_req(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	int rc;

	if ( request_pdu->ds_len > ISCSI_DEFAULT_RECV_DS_LEN || conn->state != ISCSI_CONNECT_STATE_NEW )
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_PROTOCOL_ERR );

	const iscsi_login_req_packet *login_req_pkt = (iscsi_login_req_packet *) request_pdu->bhs_pkt;

	request_pdu->cmd_sn = iscsi_get_be32(login_req_pkt->cmd_sn);

	iscsi_pdu CLEANUP_PDU login_response_pdu;
	if ( !iscsi_connection_pdu_init( &login_response_pdu, 0, false ) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	rc = iscsi_connection_pdu_login_response_init( &login_response_pdu, request_pdu );

	if ( rc < 0 ) {
		// response_init set an error code in the response pdu, send it right away and bail out
		return iscsi_send_login_response_pdu( conn, &login_response_pdu );
	}

	iscsi_negotiation_kvp pairs;
	iscsi_login_response_packet *login_response_pkt = (iscsi_login_response_packet *) login_response_pdu.bhs_pkt;
	rc = iscsi_parse_login_key_value_pairs( &pairs, (uint8_t *) request_pdu->ds_cmd_data, request_pdu->ds_len );

	if ( rc < 0 ) {
		login_response_pkt->status_class  = ISCSI_LOGIN_RESPONSE_STATUS_CLASS_CLIENT_ERR;
		login_response_pkt->status_detail = ISCSI_LOGIN_RESPONSE_STATUS_DETAILS_CLIENT_ERR_AUTH_ERR;

		return iscsi_send_login_response_pdu( conn, &login_response_pdu );
	}

	rc = iscsi_connection_handle_login_phase_none( conn, &login_response_pdu, &pairs );

	if ( rc != ISCSI_CONNECT_PDU_READ_OK ) {
		return iscsi_send_login_response_pdu( conn, &login_response_pdu );
	}

	iscsi_connecction_handle_login_response( conn, &login_response_pdu, &pairs );
	return iscsi_send_login_response_pdu( conn, &login_response_pdu );
}

/**
 * @brief Handles an incoming iSCSI payload data text request PDU.
 *
 * This function handles text request payload
 * data sent by the client.\n
 * If a response needs to be sent, this will
 * be done as well.
 *
 * @param[in] conn Pointer to iSCSI connection to handle. May
 * NOT be NULL, so take caution.
 * @param[in] request_pdu Pointer to iSCSI client request PDU to handle.
 * May be NULL in which case an error is returned.
 * @return 0 on success. A negative value indicates
 * an error. A positive value a warning.
 */
static int iscsi_connection_handle_text_req(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	iscsi_text_req_packet *text_req_pkt = (iscsi_text_req_packet *) request_pdu->bhs_pkt;

	if ( request_pdu->ds_len > ISCSI_MAX_DS_SIZE )
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_PROTOCOL_ERR );

	if ( (text_req_pkt->flags & (ISCSI_TEXT_REQ_FLAGS_CONTINUE | ISCSI_TEXT_REQ_FLAGS_FINAL))
			== (ISCSI_TEXT_REQ_FLAGS_CONTINUE | ISCSI_TEXT_REQ_FLAGS_FINAL) ) {
		// Continue and Final at the same time is invalid
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_PROTOCOL_ERR );
	}
	if ( (text_req_pkt->flags & ISCSI_TEXT_REQ_FLAGS_FINAL) == 0 ) {
		// Text request spread across multiple PDUs not supported
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_COMMAND_NOT_SUPPORTED );
	}
	if ( text_req_pkt->target_xfer_tag != 0xFFFFFFFFUL ) {
		// Initial request must have this set to all 1
		return iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_PROTOCOL_ERR );
	}

	const uint32_t exp_stat_sn   = iscsi_get_be32(text_req_pkt->exp_stat_sn);
	if ( exp_stat_sn != conn->stat_sn ) {
		conn->stat_sn = exp_stat_sn;
	}

	iscsi_negotiation_kvp pairs;
	int rc = iscsi_parse_login_key_value_pairs( &pairs, (uint8_t *) request_pdu->ds_cmd_data, request_pdu->ds_len );

	if ( rc < 0 ) {
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;
	}

	iscsi_pdu CLEANUP_PDU response_pdu;
	if ( !iscsi_connection_pdu_init( &response_pdu, MIN( 8192, conn->session->opts.MaxRecvDataSegmentLength ), false ) )
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;

	iscsi_connection_update_key_value_pairs( conn, &pairs );

	// TODO: Handle SendTargets
	int payload_len = iscsi_write_login_options_to_pdu( conn, &pairs, &response_pdu );

	if ( payload_len < 0 || (uint32_t)payload_len > response_pdu.ds_len ) {
		return ISCSI_CONNECT_PDU_READ_ERR_FATAL;
	}

	iscsi_text_response_packet *text_response_pkt =
		(iscsi_text_response_packet *) iscsi_connection_pdu_resize( &response_pdu, 0, response_pdu.ds_write_pos );

	text_response_pkt->opcode = ISCSI_OPCODE_SERVER_TEXT_RES;
	text_response_pkt->flags  = (int8_t) ISCSI_TEXT_RESPONSE_FLAGS_FINAL;

	text_response_pkt->reserved = 0;

	// TotalAHSLength is always 0 and DataSegmentLength is 24-bit, so write in one step.
	iscsi_put_be32( (uint8_t *) &text_response_pkt->total_ahs_len, response_pdu.ds_write_pos );
	text_response_pkt->lun             = text_req_pkt->lun; // Copying over doesn't change endianess.
	text_response_pkt->init_task_tag   = text_req_pkt->init_task_tag; // Copying over doesn't change endianess.
	text_response_pkt->target_xfer_tag = 0xFFFFFFFFUL; // Minus one does not require endianess conversion

	iscsi_put_be32( (uint8_t *) &text_response_pkt->stat_sn, conn->stat_sn++ );

	conn->session->max_cmd_sn++;

	iscsi_put_be32( (uint8_t *) &text_response_pkt->exp_cmd_sn, conn->session->exp_cmd_sn );
	iscsi_put_be32( (uint8_t *) &text_response_pkt->max_cmd_sn, conn->session->max_cmd_sn );
	text_response_pkt->reserved2[0] = 0ULL;
	text_response_pkt->reserved2[1] = 0ULL;

	return iscsi_connection_pdu_write( conn, &response_pdu ) ? ISCSI_CONNECT_PDU_READ_OK : ISCSI_CONNECT_PDU_READ_ERR_FATAL;
}

/**
 * @brief Handles an incoming iSCSI PDU.
 *
 * If a response needs to be sent, this will
 * be done as well.
 *
 * @param[in] conn Pointer to iSCSI connection to handle. May
 * NOT be NULL, so take caution.
 * @param[in] request_pdu Pointer to iSCSI client request PDU to handle.
 * May be NULL in which case an error is returned.
 * @return 0 on success. A negative value indicates
 * an error. A positive value a warning.
 */
static int iscsi_connection_pdu_handle(iscsi_connection *conn, iscsi_pdu *request_pdu)
{
	int rc = 0;

	const uint8_t opcode = ISCSI_GET_OPCODE(request_pdu->bhs_pkt->opcode);

	if ( conn->state == ISCSI_CONNECT_STATE_NEW ) {
		// Fresh connection, not logged in yet - we only support LOGIN in this state
		if ( opcode == ISCSI_OPCODE_CLIENT_LOGIN_REQ ) {
			rc = iscsi_connection_handle_login_req( conn, request_pdu );
		} else {
			rc = iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_PROTOCOL_ERR );
		}
	} else if ( conn->state == ISCSI_CONNECT_STATE_EXITING ) {
		// Exiting, nothing to do
		rc = ISCSI_CONNECT_PDU_READ_OK;
	} else if ( conn->state == ISCSI_CONNECT_STATE_NORMAL_SESSION ) {
		// Normal operation
		rc = iscsi_connection_handle_cmd_sn( conn, request_pdu );
		if ( rc != 0 )
			return rc;

		switch ( opcode ) {
			case ISCSI_OPCODE_CLIENT_NOP_OUT : {
				rc = iscsi_connection_handle_nop_out( conn, request_pdu );

				break;
			}
			case ISCSI_OPCODE_CLIENT_SCSI_CMD : {
				rc = iscsi_connection_handle_scsi_cmd( conn, request_pdu );

				break;
			}
			case ISCSI_OPCODE_CLIENT_TEXT_REQ : {
				rc = iscsi_connection_handle_text_req( conn, request_pdu );

				break;
			}
			case ISCSI_OPCODE_CLIENT_LOGOUT_REQ : {
				rc = iscsi_connection_handle_logout_req( conn, request_pdu );

				break;
			}
			case ISCSI_OPCODE_CLIENT_TASK_FUNC_REQ : {
				rc = iscsi_connection_handle_task_func_req( conn, request_pdu );

				break;
			}
			default : {
				rc = iscsi_connection_handle_reject( conn, request_pdu, ISCSI_REJECT_REASON_PROTOCOL_ERR );

				break;
			}
		}
	}

	if ( rc < 0 ) {
		logadd( LOG_ERROR, "Fatal error during payload handler (opcode 0x%02x) detected for client %s", (int) opcode, conn->client->hostName );
	}

	return rc;
}

/**
 * @brief Reads and processes incoming iSCSI connection PDUs in a loop.
 *
 * This function continuously reads Protocol Data Units (PDUs) on an iSCSI
 * connection and performs operations based on the type and content of the
 * received data. The function processes Basic Header Segment (BHS), Additional
 * Header Segment (AHS), and Data Segment (DS) as part of the PDU handling. If
 * any errors occur during the process, the function gracefully exits the loop.
 *
 * @param[in] conn Pointer to the iSCSI connection object. Must not be NULL and
 * contains the state and data required for processing the iSCSI connection.
 * @param[in] request Pointer to the initial received data for the PDU. This
 * serves as the partially received data of the BHS. Must not be NULL.
 * @param[in] len Length of the already received portion of the BHS in bytes.
 */
static void iscsi_connection_pdu_read_loop(iscsi_connection *conn, const dnbd3_request_t *request, const int len)
{
	iscsi_pdu CLEANUP_PDU request_pdu;

	if ( !iscsi_connection_pdu_init( &request_pdu, 0, false ) )
		return;

	// 1) Receive BHS (partially already received, in "request", merge and finish)
	memcpy( request_pdu.bhs_pkt, request, len );
	if ( sock_recv( conn->client->sock, ((uint8_t *)request_pdu.bhs_pkt) + len, sizeof(iscsi_bhs_packet) - len )
			!= sizeof(iscsi_bhs_packet) - len ) {
		logadd( LOG_INFO, "Cannot receive first BHS for client %s", conn->client->hostName );
		return;
	}

	do {
		// 2) Evaluate BHS regarding length of AHS and DS
		iscsi_bhs_packet *bhs_pkt = request_pdu.bhs_pkt;
		const uint ahs_len        = ((uint) bhs_pkt->total_ahs_len * ISCSI_ALIGN_SIZE);
		const uint32_t ds_len     = iscsi_get_be24(bhs_pkt->ds_len);

		bhs_pkt = iscsi_connection_pdu_resize( &request_pdu, ahs_len, ds_len );

		if ( bhs_pkt == NULL ) {
			logadd( LOG_WARNING, "Cannot resize PDU for client %s", conn->client->hostName );
			break;
		}

		// 3) Receive the optional AHS
		if ( ahs_len != 0 && sock_recv( conn->client->sock, request_pdu.ahs_pkt, ahs_len ) != ahs_len ) {
			logadd( LOG_DEBUG1, "Could not receive AHS for client %s", conn->client->hostName );
			break;
		}

		// 4) Receive the optional DS
		if ( request_pdu.ds_len != 0U ) {
			const uint32_t padded_ds_len = ISCSI_ALIGN( request_pdu.ds_len, ISCSI_ALIGN_SIZE );

			if ( sock_recv( conn->client->sock, request_pdu.ds_cmd_data, padded_ds_len ) != padded_ds_len ) {
				logadd( LOG_DEBUG1, "Could not receive DS for client %s", conn->client->hostName );
				break;
			}
		}

		// 5) Handle PDU
		if ( iscsi_connection_pdu_handle( conn, &request_pdu ) != ISCSI_CONNECT_PDU_READ_OK
				|| conn->state == ISCSI_CONNECT_STATE_EXITING ) {
			break;
		}

		// In case we needed an extra buffer, reset
		if ( request_pdu.big_alloc != NULL ) {
			iscsi_connection_pdu_destroy( &request_pdu );
			if ( !iscsi_connection_pdu_init( &request_pdu, 0, false ) ) {
				logadd( LOG_WARNING, "Cannot re-initialize PDU for client %s", conn->client->hostName );
				break;
			}
		}

		// Move first part of next iteration last in this loop, as we completed the first, partial
		// header before the loop - this saves us from accounting for this within the mainloop

		// 1) Receive entire BHS
		if ( sock_recv( conn->client->sock, request_pdu.bhs_pkt, sizeof(iscsi_bhs_packet) ) != sizeof(iscsi_bhs_packet) ) {
			logadd( LOG_INFO, "Cannot receive BHS for client %s", conn->client->hostName );
			break;
		}
	} while ( !_shutdown );
}

/**
 * @brief Handles an iSCSI connection until connection is closed.
 *
 * This function creates an iSCSI portal group
 * and iSCSI portal with connection data
 * delivered from the DNBD3 client and
 * request data.
 *
 * @param[in] client Pointer to DNBD3 client structure,
 * may NOT be NULL, so be careful.
 * @param[in] request Pointer to DNBD3 request packet data.
 * NULL is not allowed here, take caution.
 * @param[in] len Length of already read DNBD3 request data.
 */
void iscsi_connection_handle(dnbd3_client_t *client, const dnbd3_request_t *request, const int len)
{
	_Static_assert( sizeof(dnbd3_request_t) <= sizeof(struct iscsi_bhs_packet),
		"DNBD3 request size larger than iSCSI BHS packet data size - Manual intervention required!" );
	sock_setTimeout( client->sock, 1000L * 3600L ); // TODO: Remove after finishing iSCSI implementation

	iscsi_connection *conn = iscsi_connection_create( client );

	if ( conn == NULL ) {
		logadd( LOG_ERROR, "iscsi_connection_handle: Out of memory while allocating iSCSI connection" );

		return;
	}

	static atomic_int CONN_ID = 0;
	conn->id = ++CONN_ID;

	iscsi_connection_pdu_read_loop( conn, request, len );

	// Wait for the client to receive any pending outgoing PDUs
	shutdown( client->sock, SHUT_WR );
	sock_setTimeout( client->sock, 100 );
	while ( recv( client->sock, (void *)request, len, 0 ) > 0 ) {}

	iscsi_connection_destroy( conn );
}