aboutsummaryrefslogtreecommitdiff
path: root/sys/cam/ctl/ctl_backend_block.c
blob: eeddf1735bcedb40499aced7ca9fdadb26ced5c0 (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
/*-
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2003 Silicon Graphics International Corp.
 * Copyright (c) 2009-2011 Spectra Logic Corporation
 * Copyright (c) 2012 The FreeBSD Foundation
 * Copyright (c) 2014-2015 Alexander Motin <mav@FreeBSD.org>
 * All rights reserved.
 *
 * Portions of this software were developed by Edward Tomasz Napierala
 * under sponsorship from the FreeBSD Foundation.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl_backend_block.c#5 $
 */
/*
 * CAM Target Layer driver backend for block devices.
 *
 * Author: Ken Merry <ken@FreeBSD.org>
 */
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/types.h>
#include <sys/kthread.h>
#include <sys/bio.h>
#include <sys/fcntl.h>
#include <sys/limits.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/condvar.h>
#include <sys/malloc.h>
#include <sys/conf.h>
#include <sys/ioccom.h>
#include <sys/queue.h>
#include <sys/sbuf.h>
#include <sys/endian.h>
#include <sys/uio.h>
#include <sys/buf.h>
#include <sys/taskqueue.h>
#include <sys/vnode.h>
#include <sys/namei.h>
#include <sys/mount.h>
#include <sys/disk.h>
#include <sys/fcntl.h>
#include <sys/filedesc.h>
#include <sys/filio.h>
#include <sys/proc.h>
#include <sys/pcpu.h>
#include <sys/module.h>
#include <sys/sdt.h>
#include <sys/devicestat.h>
#include <sys/sysctl.h>
#include <sys/nv.h>
#include <sys/dnv.h>

#include <geom/geom.h>

#include <cam/cam.h>
#include <cam/scsi/scsi_all.h>
#include <cam/scsi/scsi_da.h>
#include <cam/ctl/ctl_io.h>
#include <cam/ctl/ctl.h>
#include <cam/ctl/ctl_backend.h>
#include <cam/ctl/ctl_ioctl.h>
#include <cam/ctl/ctl_ha.h>
#include <cam/ctl/ctl_scsi_all.h>
#include <cam/ctl/ctl_private.h>
#include <cam/ctl/ctl_error.h>

/*
 * The idea here is that we'll allocate enough S/G space to hold a 1MB
 * I/O.  If we get an I/O larger than that, we'll split it.
 */
#define	CTLBLK_HALF_IO_SIZE	(512 * 1024)
#define	CTLBLK_MAX_IO_SIZE	(CTLBLK_HALF_IO_SIZE * 2)
#define	CTLBLK_MAX_SEG		MAXPHYS
#define	CTLBLK_HALF_SEGS	MAX(CTLBLK_HALF_IO_SIZE / CTLBLK_MAX_SEG, 1)
#define	CTLBLK_MAX_SEGS		(CTLBLK_HALF_SEGS * 2)

#ifdef CTLBLK_DEBUG
#define DPRINTF(fmt, args...) \
    printf("cbb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args)
#else
#define DPRINTF(fmt, args...) do {} while(0)
#endif

#define PRIV(io)	\
    ((struct ctl_ptr_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_BACKEND])
#define ARGS(io)	\
    ((struct ctl_lba_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_LBA_LEN])

SDT_PROVIDER_DEFINE(cbb);

typedef enum {
	CTL_BE_BLOCK_LUN_UNCONFIGURED	= 0x01,
	CTL_BE_BLOCK_LUN_CONFIG_ERR	= 0x02,
	CTL_BE_BLOCK_LUN_WAITING	= 0x04,
} ctl_be_block_lun_flags;

typedef enum {
	CTL_BE_BLOCK_NONE,
	CTL_BE_BLOCK_DEV,
	CTL_BE_BLOCK_FILE
} ctl_be_block_type;

struct ctl_be_block_filedata {
	struct ucred *cred;
};

union ctl_be_block_bedata {
	struct ctl_be_block_filedata file;
};

struct ctl_be_block_io;
struct ctl_be_block_lun;

typedef void (*cbb_dispatch_t)(struct ctl_be_block_lun *be_lun,
			       struct ctl_be_block_io *beio);
typedef uint64_t (*cbb_getattr_t)(struct ctl_be_block_lun *be_lun,
				  const char *attrname);

/*
 * Backend LUN structure.  There is a 1:1 mapping between a block device
 * and a backend block LUN, and between a backend block LUN and a CTL LUN.
 */
struct ctl_be_block_lun {
	struct ctl_lun_create_params params;
	char lunname[32];
	char *dev_path;
	ctl_be_block_type dev_type;
	struct vnode *vn;
	union ctl_be_block_bedata backend;
	cbb_dispatch_t dispatch;
	cbb_dispatch_t lun_flush;
	cbb_dispatch_t unmap;
	cbb_dispatch_t get_lba_status;
	cbb_getattr_t getattr;
	uma_zone_t lun_zone;
	uint64_t size_blocks;
	uint64_t size_bytes;
	struct ctl_be_block_softc *softc;
	struct devstat *disk_stats;
	ctl_be_block_lun_flags flags;
	STAILQ_ENTRY(ctl_be_block_lun) links;
	struct ctl_be_lun cbe_lun;
	struct taskqueue *io_taskqueue;
	struct task io_task;
	int num_threads;
	STAILQ_HEAD(, ctl_io_hdr) input_queue;
	STAILQ_HEAD(, ctl_io_hdr) config_read_queue;
	STAILQ_HEAD(, ctl_io_hdr) config_write_queue;
	STAILQ_HEAD(, ctl_io_hdr) datamove_queue;
	struct mtx_padalign io_lock;
	struct mtx_padalign queue_lock;
};

/*
 * Overall softc structure for the block backend module.
 */
struct ctl_be_block_softc {
	struct mtx			 lock;
	uma_zone_t			 beio_zone;
	int				 num_luns;
	STAILQ_HEAD(, ctl_be_block_lun)	 lun_list;
};

static struct ctl_be_block_softc backend_block_softc;

/*
 * Per-I/O information.
 */
struct ctl_be_block_io {
	union ctl_io			*io;
	struct ctl_sg_entry		sg_segs[CTLBLK_MAX_SEGS];
	struct iovec			xiovecs[CTLBLK_MAX_SEGS];
	int				bio_cmd;
	int				num_segs;
	int				num_bios_sent;
	int				num_bios_done;
	int				send_complete;
	int				first_error;
	uint64_t			first_error_offset;
	struct bintime			ds_t0;
	devstat_tag_type		ds_tag_type;
	devstat_trans_flags		ds_trans_type;
	uint64_t			io_len;
	uint64_t			io_offset;
	int				io_arg;
	struct ctl_be_block_softc	*softc;
	struct ctl_be_block_lun		*lun;
	void (*beio_cont)(struct ctl_be_block_io *beio); /* to continue processing */
};

extern struct ctl_softc *control_softc;

static int cbb_num_threads = 14;
SYSCTL_NODE(_kern_cam_ctl, OID_AUTO, block, CTLFLAG_RD, 0,
	    "CAM Target Layer Block Backend");
SYSCTL_INT(_kern_cam_ctl_block, OID_AUTO, num_threads, CTLFLAG_RWTUN,
           &cbb_num_threads, 0, "Number of threads per backing file");

static struct ctl_be_block_io *ctl_alloc_beio(struct ctl_be_block_softc *softc);
static void ctl_free_beio(struct ctl_be_block_io *beio);
static void ctl_complete_beio(struct ctl_be_block_io *beio);
static int ctl_be_block_move_done(union ctl_io *io);
static void ctl_be_block_biodone(struct bio *bio);
static void ctl_be_block_flush_file(struct ctl_be_block_lun *be_lun,
				    struct ctl_be_block_io *beio);
static void ctl_be_block_dispatch_file(struct ctl_be_block_lun *be_lun,
				       struct ctl_be_block_io *beio);
static void ctl_be_block_gls_file(struct ctl_be_block_lun *be_lun,
				  struct ctl_be_block_io *beio);
static uint64_t ctl_be_block_getattr_file(struct ctl_be_block_lun *be_lun,
					 const char *attrname);
static void ctl_be_block_flush_dev(struct ctl_be_block_lun *be_lun,
				   struct ctl_be_block_io *beio);
static void ctl_be_block_unmap_dev(struct ctl_be_block_lun *be_lun,
				   struct ctl_be_block_io *beio);
static void ctl_be_block_dispatch_dev(struct ctl_be_block_lun *be_lun,
				      struct ctl_be_block_io *beio);
static uint64_t ctl_be_block_getattr_dev(struct ctl_be_block_lun *be_lun,
					 const char *attrname);
static void ctl_be_block_cr_dispatch(struct ctl_be_block_lun *be_lun,
				    union ctl_io *io);
static void ctl_be_block_cw_dispatch(struct ctl_be_block_lun *be_lun,
				    union ctl_io *io);
static void ctl_be_block_dispatch(struct ctl_be_block_lun *be_lun,
				  union ctl_io *io);
static void ctl_be_block_worker(void *context, int pending);
static int ctl_be_block_submit(union ctl_io *io);
static int ctl_be_block_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
				   int flag, struct thread *td);
static int ctl_be_block_open_file(struct ctl_be_block_lun *be_lun,
				  struct ctl_lun_req *req);
static int ctl_be_block_open_dev(struct ctl_be_block_lun *be_lun,
				 struct ctl_lun_req *req);
static int ctl_be_block_close(struct ctl_be_block_lun *be_lun);
static int ctl_be_block_open(struct ctl_be_block_lun *be_lun,
			     struct ctl_lun_req *req);
static int ctl_be_block_create(struct ctl_be_block_softc *softc,
			       struct ctl_lun_req *req);
static int ctl_be_block_rm(struct ctl_be_block_softc *softc,
			   struct ctl_lun_req *req);
static int ctl_be_block_modify(struct ctl_be_block_softc *softc,
			   struct ctl_lun_req *req);
static void ctl_be_block_lun_shutdown(void *be_lun);
static void ctl_be_block_lun_config_status(void *be_lun,
					   ctl_lun_config_status status);
static int ctl_be_block_config_write(union ctl_io *io);
static int ctl_be_block_config_read(union ctl_io *io);
static int ctl_be_block_lun_info(void *be_lun, struct sbuf *sb);
static uint64_t ctl_be_block_lun_attr(void *be_lun, const char *attrname);
static int ctl_be_block_init(void);
static int ctl_be_block_shutdown(void);

static struct ctl_backend_driver ctl_be_block_driver = 
{
	.name = "block",
	.flags = CTL_BE_FLAG_HAS_CONFIG,
	.init = ctl_be_block_init,
	.shutdown = ctl_be_block_shutdown,
	.data_submit = ctl_be_block_submit,
	.data_move_done = ctl_be_block_move_done,
	.config_read = ctl_be_block_config_read,
	.config_write = ctl_be_block_config_write,
	.ioctl = ctl_be_block_ioctl,
	.lun_info = ctl_be_block_lun_info,
	.lun_attr = ctl_be_block_lun_attr
};

MALLOC_DEFINE(M_CTLBLK, "ctlblk", "Memory used for CTL block backend");
CTL_BACKEND_DECLARE(cbb, ctl_be_block_driver);

static struct ctl_be_block_io *
ctl_alloc_beio(struct ctl_be_block_softc *softc)
{
	struct ctl_be_block_io *beio;

	beio = uma_zalloc(softc->beio_zone, M_WAITOK | M_ZERO);
	beio->softc = softc;
	return (beio);
}

static void
ctl_free_beio(struct ctl_be_block_io *beio)
{
	int duplicate_free;
	int i;

	duplicate_free = 0;

	for (i = 0; i < beio->num_segs; i++) {
		if (beio->sg_segs[i].addr == NULL)
			duplicate_free++;

		uma_zfree(beio->lun->lun_zone, beio->sg_segs[i].addr);
		beio->sg_segs[i].addr = NULL;

		/* For compare we had two equal S/G lists. */
		if (ARGS(beio->io)->flags & CTL_LLF_COMPARE) {
			uma_zfree(beio->lun->lun_zone,
			    beio->sg_segs[i + CTLBLK_HALF_SEGS].addr);
			beio->sg_segs[i + CTLBLK_HALF_SEGS].addr = NULL;
		}
	}

	if (duplicate_free > 0) {
		printf("%s: %d duplicate frees out of %d segments\n", __func__,
		       duplicate_free, beio->num_segs);
	}

	uma_zfree(beio->softc->beio_zone, beio);
}

static void
ctl_complete_beio(struct ctl_be_block_io *beio)
{
	union ctl_io *io = beio->io;

	if (beio->beio_cont != NULL) {
		beio->beio_cont(beio);
	} else {
		ctl_free_beio(beio);
		ctl_data_submit_done(io);
	}
}

static size_t
cmp(uint8_t *a, uint8_t *b, size_t size)
{
	size_t i;

	for (i = 0; i < size; i++) {
		if (a[i] != b[i])
			break;
	}
	return (i);
}

static void
ctl_be_block_compare(union ctl_io *io)
{
	struct ctl_be_block_io *beio;
	uint64_t off, res;
	int i;
	uint8_t info[8];

	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
	off = 0;
	for (i = 0; i < beio->num_segs; i++) {
		res = cmp(beio->sg_segs[i].addr,
		    beio->sg_segs[i + CTLBLK_HALF_SEGS].addr,
		    beio->sg_segs[i].len);
		off += res;
		if (res < beio->sg_segs[i].len)
			break;
	}
	if (i < beio->num_segs) {
		scsi_u64to8b(off, info);
		ctl_set_sense(&io->scsiio, /*current_error*/ 1,
		    /*sense_key*/ SSD_KEY_MISCOMPARE,
		    /*asc*/ 0x1D, /*ascq*/ 0x00,
		    /*type*/ SSD_ELEM_INFO,
		    /*size*/ sizeof(info), /*data*/ &info,
		    /*type*/ SSD_ELEM_NONE);
	} else
		ctl_set_success(&io->scsiio);
}

static int
ctl_be_block_move_done(union ctl_io *io)
{
	struct ctl_be_block_io *beio;
	struct ctl_be_block_lun *be_lun;
	struct ctl_lba_len_flags *lbalen;
#ifdef CTL_TIME_IO
	struct bintime cur_bt;
#endif

	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
	be_lun = beio->lun;

	DPRINTF("entered\n");

#ifdef CTL_TIME_IO
	getbinuptime(&cur_bt);
	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
#endif
	io->io_hdr.num_dmas++;
	io->scsiio.kern_rel_offset += io->scsiio.kern_data_len;

	/*
	 * We set status at this point for read commands, and write
	 * commands with errors.
	 */
	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
		;
	} else if ((io->io_hdr.port_status != 0) &&
	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
		    /*retry_count*/ io->io_hdr.port_status);
	} else if (io->scsiio.kern_data_resid != 0 &&
	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
		ctl_set_invalid_field_ciu(&io->scsiio);
	} else if ((io->io_hdr.port_status == 0) &&
	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)) {
		lbalen = ARGS(beio->io);
		if (lbalen->flags & CTL_LLF_READ) {
			ctl_set_success(&io->scsiio);
		} else if (lbalen->flags & CTL_LLF_COMPARE) {
			/* We have two data blocks ready for comparison. */
			ctl_be_block_compare(io);
		}
	}

	/*
	 * If this is a read, or a write with errors, it is done.
	 */
	if ((beio->bio_cmd == BIO_READ)
	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)
	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)) {
		ctl_complete_beio(beio);
		return (0);
	}

	/*
	 * At this point, we have a write and the DMA completed
	 * successfully.  We now have to queue it to the task queue to
	 * execute the backend I/O.  That is because we do blocking
	 * memory allocations, and in the file backing case, blocking I/O.
	 * This move done routine is generally called in the SIM's
	 * interrupt context, and therefore we cannot block.
	 */
	mtx_lock(&be_lun->queue_lock);
	STAILQ_INSERT_TAIL(&be_lun->datamove_queue, &io->io_hdr, links);
	mtx_unlock(&be_lun->queue_lock);
	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);

	return (0);
}

static void
ctl_be_block_biodone(struct bio *bio)
{
	struct ctl_be_block_io *beio;
	struct ctl_be_block_lun *be_lun;
	union ctl_io *io;
	int error;

	beio = bio->bio_caller1;
	be_lun = beio->lun;
	io = beio->io;

	DPRINTF("entered\n");

	error = bio->bio_error;
	mtx_lock(&be_lun->io_lock);
	if (error != 0 &&
	    (beio->first_error == 0 ||
	     bio->bio_offset < beio->first_error_offset)) {
		beio->first_error = error;
		beio->first_error_offset = bio->bio_offset;
	}

	beio->num_bios_done++;

	/*
	 * XXX KDM will this cause WITNESS to complain?  Holding a lock
	 * during the free might cause it to complain.
	 */
	g_destroy_bio(bio);

	/*
	 * If the send complete bit isn't set, or we aren't the last I/O to
	 * complete, then we're done.
	 */
	if ((beio->send_complete == 0)
	 || (beio->num_bios_done < beio->num_bios_sent)) {
		mtx_unlock(&be_lun->io_lock);
		return;
	}

	/*
	 * At this point, we've verified that we are the last I/O to
	 * complete, so it's safe to drop the lock.
	 */
	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
	    beio->ds_tag_type, beio->ds_trans_type,
	    /*now*/ NULL, /*then*/&beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	/*
	 * If there are any errors from the backing device, we fail the
	 * entire I/O with a medium error.
	 */
	error = beio->first_error;
	if (error != 0) {
		if (error == EOPNOTSUPP) {
			ctl_set_invalid_opcode(&io->scsiio);
		} else if (error == ENOSPC || error == EDQUOT) {
			ctl_set_space_alloc_fail(&io->scsiio);
		} else if (error == EROFS || error == EACCES) {
			ctl_set_hw_write_protected(&io->scsiio);
		} else if (beio->bio_cmd == BIO_FLUSH) {
			/* XXX KDM is there is a better error here? */
			ctl_set_internal_failure(&io->scsiio,
						 /*sks_valid*/ 1,
						 /*retry_count*/ 0xbad2);
		} else {
			ctl_set_medium_error(&io->scsiio,
			    beio->bio_cmd == BIO_READ);
		}
		ctl_complete_beio(beio);
		return;
	}

	/*
	 * If this is a write, a flush, a delete or verify, we're all done.
	 * If this is a read, we can now send the data to the user.
	 */
	if ((beio->bio_cmd == BIO_WRITE)
	 || (beio->bio_cmd == BIO_FLUSH)
	 || (beio->bio_cmd == BIO_DELETE)
	 || (ARGS(io)->flags & CTL_LLF_VERIFY)) {
		ctl_set_success(&io->scsiio);
		ctl_complete_beio(beio);
	} else {
		if ((ARGS(io)->flags & CTL_LLF_READ) &&
		    beio->beio_cont == NULL) {
			ctl_set_success(&io->scsiio);
			ctl_serseq_done(io);
		}
#ifdef CTL_TIME_IO
		getbinuptime(&io->io_hdr.dma_start_bt);
#endif
		ctl_datamove(io);
	}
}

static void
ctl_be_block_flush_file(struct ctl_be_block_lun *be_lun,
			struct ctl_be_block_io *beio)
{
	union ctl_io *io = beio->io;
	struct mount *mountpoint;
	int error, lock_flags;

	DPRINTF("entered\n");

	binuptime(&beio->ds_t0);
	mtx_lock(&be_lun->io_lock);
	devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	(void) vn_start_write(be_lun->vn, &mountpoint, V_WAIT);

	if (MNT_SHARED_WRITES(mountpoint) ||
	    ((mountpoint == NULL) && MNT_SHARED_WRITES(be_lun->vn->v_mount)))
		lock_flags = LK_SHARED;
	else
		lock_flags = LK_EXCLUSIVE;
	vn_lock(be_lun->vn, lock_flags | LK_RETRY);
	error = VOP_FSYNC(be_lun->vn, beio->io_arg ? MNT_NOWAIT : MNT_WAIT,
	    curthread);
	VOP_UNLOCK(be_lun->vn, 0);

	vn_finished_write(mountpoint);

	mtx_lock(&be_lun->io_lock);
	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
	    beio->ds_tag_type, beio->ds_trans_type,
	    /*now*/ NULL, /*then*/&beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	if (error == 0)
		ctl_set_success(&io->scsiio);
	else {
		/* XXX KDM is there is a better error here? */
		ctl_set_internal_failure(&io->scsiio,
					 /*sks_valid*/ 1,
					 /*retry_count*/ 0xbad1);
	}

	ctl_complete_beio(beio);
}

SDT_PROBE_DEFINE1(cbb, , read, file_start, "uint64_t");
SDT_PROBE_DEFINE1(cbb, , write, file_start, "uint64_t");
SDT_PROBE_DEFINE1(cbb, , read, file_done,"uint64_t");
SDT_PROBE_DEFINE1(cbb, , write, file_done, "uint64_t");

static void
ctl_be_block_dispatch_file(struct ctl_be_block_lun *be_lun,
			   struct ctl_be_block_io *beio)
{
	struct ctl_be_block_filedata *file_data;
	union ctl_io *io;
	struct uio xuio;
	struct iovec *xiovec;
	size_t s;
	int error, flags, i;

	DPRINTF("entered\n");

	file_data = &be_lun->backend.file;
	io = beio->io;
	flags = 0;
	if (ARGS(io)->flags & CTL_LLF_DPO)
		flags |= IO_DIRECT;
	if (beio->bio_cmd == BIO_WRITE && ARGS(io)->flags & CTL_LLF_FUA)
		flags |= IO_SYNC;

	bzero(&xuio, sizeof(xuio));
	if (beio->bio_cmd == BIO_READ) {
		SDT_PROBE0(cbb, , read, file_start);
		xuio.uio_rw = UIO_READ;
	} else {
		SDT_PROBE0(cbb, , write, file_start);
		xuio.uio_rw = UIO_WRITE;
	}
	xuio.uio_offset = beio->io_offset;
	xuio.uio_resid = beio->io_len;
	xuio.uio_segflg = UIO_SYSSPACE;
	xuio.uio_iov = beio->xiovecs;
	xuio.uio_iovcnt = beio->num_segs;
	xuio.uio_td = curthread;

	for (i = 0, xiovec = xuio.uio_iov; i < xuio.uio_iovcnt; i++, xiovec++) {
		xiovec->iov_base = beio->sg_segs[i].addr;
		xiovec->iov_len = beio->sg_segs[i].len;
	}

	binuptime(&beio->ds_t0);
	mtx_lock(&be_lun->io_lock);
	devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	if (beio->bio_cmd == BIO_READ) {
		vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);

		/*
		 * UFS pays attention to IO_DIRECT for reads.  If the
		 * DIRECTIO option is configured into the kernel, it calls
		 * ffs_rawread().  But that only works for single-segment
		 * uios with user space addresses.  In our case, with a
		 * kernel uio, it still reads into the buffer cache, but it
		 * will just try to release the buffer from the cache later
		 * on in ffs_read().
		 *
		 * ZFS does not pay attention to IO_DIRECT for reads.
		 *
		 * UFS does not pay attention to IO_SYNC for reads.
		 *
		 * ZFS pays attention to IO_SYNC (which translates into the
		 * Solaris define FRSYNC for zfs_read()) for reads.  It
		 * attempts to sync the file before reading.
		 */
		error = VOP_READ(be_lun->vn, &xuio, flags, file_data->cred);

		VOP_UNLOCK(be_lun->vn, 0);
		SDT_PROBE0(cbb, , read, file_done);
		if (error == 0 && xuio.uio_resid > 0) {
			/*
			 * If we red less then requested (EOF), then
			 * we should clean the rest of the buffer.
			 */
			s = beio->io_len - xuio.uio_resid;
			for (i = 0; i < beio->num_segs; i++) {
				if (s >= beio->sg_segs[i].len) {
					s -= beio->sg_segs[i].len;
					continue;
				}
				bzero((uint8_t *)beio->sg_segs[i].addr + s,
				    beio->sg_segs[i].len - s);
				s = 0;
			}
		}
	} else {
		struct mount *mountpoint;
		int lock_flags;

		(void)vn_start_write(be_lun->vn, &mountpoint, V_WAIT);

		if (MNT_SHARED_WRITES(mountpoint) || ((mountpoint == NULL)
		  && MNT_SHARED_WRITES(be_lun->vn->v_mount)))
			lock_flags = LK_SHARED;
		else
			lock_flags = LK_EXCLUSIVE;
		vn_lock(be_lun->vn, lock_flags | LK_RETRY);

		/*
		 * UFS pays attention to IO_DIRECT for writes.  The write
		 * is done asynchronously.  (Normally the write would just
		 * get put into cache.
		 *
		 * UFS pays attention to IO_SYNC for writes.  It will
		 * attempt to write the buffer out synchronously if that
		 * flag is set.
		 *
		 * ZFS does not pay attention to IO_DIRECT for writes.
		 *
		 * ZFS pays attention to IO_SYNC (a.k.a. FSYNC or FRSYNC)
		 * for writes.  It will flush the transaction from the
		 * cache before returning.
		 */
		error = VOP_WRITE(be_lun->vn, &xuio, flags, file_data->cred);
		VOP_UNLOCK(be_lun->vn, 0);

		vn_finished_write(mountpoint);
		SDT_PROBE0(cbb, , write, file_done);
        }

	mtx_lock(&be_lun->io_lock);
	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
	    beio->ds_tag_type, beio->ds_trans_type,
	    /*now*/ NULL, /*then*/&beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	/*
	 * If we got an error, set the sense data to "MEDIUM ERROR" and
	 * return the I/O to the user.
	 */
	if (error != 0) {
		if (error == ENOSPC || error == EDQUOT) {
			ctl_set_space_alloc_fail(&io->scsiio);
		} else if (error == EROFS || error == EACCES) {
			ctl_set_hw_write_protected(&io->scsiio);
		} else {
			ctl_set_medium_error(&io->scsiio,
			    beio->bio_cmd == BIO_READ);
		}
		ctl_complete_beio(beio);
		return;
	}

	/*
	 * If this is a write or a verify, we're all done.
	 * If this is a read, we can now send the data to the user.
	 */
	if ((beio->bio_cmd == BIO_WRITE) ||
	    (ARGS(io)->flags & CTL_LLF_VERIFY)) {
		ctl_set_success(&io->scsiio);
		ctl_complete_beio(beio);
	} else {
		if ((ARGS(io)->flags & CTL_LLF_READ) &&
		    beio->beio_cont == NULL) {
			ctl_set_success(&io->scsiio);
			ctl_serseq_done(io);
		}
#ifdef CTL_TIME_IO
		getbinuptime(&io->io_hdr.dma_start_bt);
#endif
		ctl_datamove(io);
	}
}

static void
ctl_be_block_gls_file(struct ctl_be_block_lun *be_lun,
			struct ctl_be_block_io *beio)
{
	union ctl_io *io = beio->io;
	struct ctl_lba_len_flags *lbalen = ARGS(io);
	struct scsi_get_lba_status_data *data;
	off_t roff, off;
	int error, status;

	DPRINTF("entered\n");

	off = roff = ((off_t)lbalen->lba) * be_lun->cbe_lun.blocksize;
	vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
	error = VOP_IOCTL(be_lun->vn, FIOSEEKHOLE, &off,
	    0, curthread->td_ucred, curthread);
	if (error == 0 && off > roff)
		status = 0;	/* mapped up to off */
	else {
		error = VOP_IOCTL(be_lun->vn, FIOSEEKDATA, &off,
		    0, curthread->td_ucred, curthread);
		if (error == 0 && off > roff)
			status = 1;	/* deallocated up to off */
		else {
			status = 0;	/* unknown up to the end */
			off = be_lun->size_bytes;
		}
	}
	VOP_UNLOCK(be_lun->vn, 0);

	data = (struct scsi_get_lba_status_data *)io->scsiio.kern_data_ptr;
	scsi_u64to8b(lbalen->lba, data->descr[0].addr);
	scsi_ulto4b(MIN(UINT32_MAX, off / be_lun->cbe_lun.blocksize -
	    lbalen->lba), data->descr[0].length);
	data->descr[0].status = status;

	ctl_complete_beio(beio);
}

static uint64_t
ctl_be_block_getattr_file(struct ctl_be_block_lun *be_lun, const char *attrname)
{
	struct vattr		vattr;
	struct statfs		statfs;
	uint64_t		val;
	int			error;

	val = UINT64_MAX;
	if (be_lun->vn == NULL)
		return (val);
	vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
	if (strcmp(attrname, "blocksused") == 0) {
		error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
		if (error == 0)
			val = vattr.va_bytes / be_lun->cbe_lun.blocksize;
	}
	if (strcmp(attrname, "blocksavail") == 0 &&
	    !VN_IS_DOOMED(be_lun->vn)) {
		error = VFS_STATFS(be_lun->vn->v_mount, &statfs);
		if (error == 0)
			val = statfs.f_bavail * statfs.f_bsize /
			    be_lun->cbe_lun.blocksize;
	}
	VOP_UNLOCK(be_lun->vn, 0);
	return (val);
}

static void
ctl_be_block_dispatch_zvol(struct ctl_be_block_lun *be_lun,
			   struct ctl_be_block_io *beio)
{
	union ctl_io *io;
	struct cdevsw *csw;
	struct cdev *dev;
	struct uio xuio;
	struct iovec *xiovec;
	int error, flags, i, ref;

	DPRINTF("entered\n");

	io = beio->io;
	flags = 0;
	if (ARGS(io)->flags & CTL_LLF_DPO)
		flags |= IO_DIRECT;
	if (beio->bio_cmd == BIO_WRITE && ARGS(io)->flags & CTL_LLF_FUA)
		flags |= IO_SYNC;

	bzero(&xuio, sizeof(xuio));
	if (beio->bio_cmd == BIO_READ) {
		SDT_PROBE0(cbb, , read, file_start);
		xuio.uio_rw = UIO_READ;
	} else {
		SDT_PROBE0(cbb, , write, file_start);
		xuio.uio_rw = UIO_WRITE;
	}
	xuio.uio_offset = beio->io_offset;
	xuio.uio_resid = beio->io_len;
	xuio.uio_segflg = UIO_SYSSPACE;
	xuio.uio_iov = beio->xiovecs;
	xuio.uio_iovcnt = beio->num_segs;
	xuio.uio_td = curthread;

	for (i = 0, xiovec = xuio.uio_iov; i < xuio.uio_iovcnt; i++, xiovec++) {
		xiovec->iov_base = beio->sg_segs[i].addr;
		xiovec->iov_len = beio->sg_segs[i].len;
	}

	binuptime(&beio->ds_t0);
	mtx_lock(&be_lun->io_lock);
	devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	csw = devvn_refthread(be_lun->vn, &dev, &ref);
	if (csw) {
		if (beio->bio_cmd == BIO_READ)
			error = csw->d_read(dev, &xuio, flags);
		else
			error = csw->d_write(dev, &xuio, flags);
		dev_relthread(dev, ref);
	} else
		error = ENXIO;

	if (beio->bio_cmd == BIO_READ)
		SDT_PROBE0(cbb, , read, file_done);
	else
		SDT_PROBE0(cbb, , write, file_done);

	mtx_lock(&be_lun->io_lock);
	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
	    beio->ds_tag_type, beio->ds_trans_type,
	    /*now*/ NULL, /*then*/&beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	/*
	 * If we got an error, set the sense data to "MEDIUM ERROR" and
	 * return the I/O to the user.
	 */
	if (error != 0) {
		if (error == ENOSPC || error == EDQUOT) {
			ctl_set_space_alloc_fail(&io->scsiio);
		} else if (error == EROFS || error == EACCES) {
			ctl_set_hw_write_protected(&io->scsiio);
		} else {
			ctl_set_medium_error(&io->scsiio,
			    beio->bio_cmd == BIO_READ);
		}
		ctl_complete_beio(beio);
		return;
	}

	/*
	 * If this is a write or a verify, we're all done.
	 * If this is a read, we can now send the data to the user.
	 */
	if ((beio->bio_cmd == BIO_WRITE) ||
	    (ARGS(io)->flags & CTL_LLF_VERIFY)) {
		ctl_set_success(&io->scsiio);
		ctl_complete_beio(beio);
	} else {
		if ((ARGS(io)->flags & CTL_LLF_READ) &&
		    beio->beio_cont == NULL) {
			ctl_set_success(&io->scsiio);
			ctl_serseq_done(io);
		}
#ifdef CTL_TIME_IO
		getbinuptime(&io->io_hdr.dma_start_bt);
#endif
		ctl_datamove(io);
	}
}

static void
ctl_be_block_gls_zvol(struct ctl_be_block_lun *be_lun,
			struct ctl_be_block_io *beio)
{
	union ctl_io *io = beio->io;
	struct cdevsw *csw;
	struct cdev *dev;
	struct ctl_lba_len_flags *lbalen = ARGS(io);
	struct scsi_get_lba_status_data *data;
	off_t roff, off;
	int error, ref, status;

	DPRINTF("entered\n");

	csw = devvn_refthread(be_lun->vn, &dev, &ref);
	if (csw == NULL) {
		status = 0;	/* unknown up to the end */
		off = be_lun->size_bytes;
		goto done;
	}
	off = roff = ((off_t)lbalen->lba) * be_lun->cbe_lun.blocksize;
	error = csw->d_ioctl(dev, FIOSEEKHOLE, (caddr_t)&off, FREAD,
	    curthread);
	if (error == 0 && off > roff)
		status = 0;	/* mapped up to off */
	else {
		error = csw->d_ioctl(dev, FIOSEEKDATA, (caddr_t)&off, FREAD,
		    curthread);
		if (error == 0 && off > roff)
			status = 1;	/* deallocated up to off */
		else {
			status = 0;	/* unknown up to the end */
			off = be_lun->size_bytes;
		}
	}
	dev_relthread(dev, ref);

done:
	data = (struct scsi_get_lba_status_data *)io->scsiio.kern_data_ptr;
	scsi_u64to8b(lbalen->lba, data->descr[0].addr);
	scsi_ulto4b(MIN(UINT32_MAX, off / be_lun->cbe_lun.blocksize -
	    lbalen->lba), data->descr[0].length);
	data->descr[0].status = status;

	ctl_complete_beio(beio);
}

static void
ctl_be_block_flush_dev(struct ctl_be_block_lun *be_lun,
		       struct ctl_be_block_io *beio)
{
	struct bio *bio;
	struct cdevsw *csw;
	struct cdev *dev;
	int ref;

	DPRINTF("entered\n");

	/* This can't fail, it's a blocking allocation. */
	bio = g_alloc_bio();

	bio->bio_cmd	    = BIO_FLUSH;
	bio->bio_offset	    = 0;
	bio->bio_data	    = 0;
	bio->bio_done	    = ctl_be_block_biodone;
	bio->bio_caller1    = beio;
	bio->bio_pblkno	    = 0;

	/*
	 * We don't need to acquire the LUN lock here, because we are only
	 * sending one bio, and so there is no other context to synchronize
	 * with.
	 */
	beio->num_bios_sent = 1;
	beio->send_complete = 1;

	binuptime(&beio->ds_t0);
	mtx_lock(&be_lun->io_lock);
	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	csw = devvn_refthread(be_lun->vn, &dev, &ref);
	if (csw) {
		bio->bio_dev = dev;
		csw->d_strategy(bio);
		dev_relthread(dev, ref);
	} else {
		bio->bio_error = ENXIO;
		ctl_be_block_biodone(bio);
	}
}

static void
ctl_be_block_unmap_dev_range(struct ctl_be_block_lun *be_lun,
		       struct ctl_be_block_io *beio,
		       uint64_t off, uint64_t len, int last)
{
	struct bio *bio;
	uint64_t maxlen;
	struct cdevsw *csw;
	struct cdev *dev;
	int ref;

	csw = devvn_refthread(be_lun->vn, &dev, &ref);
	maxlen = LONG_MAX - (LONG_MAX % be_lun->cbe_lun.blocksize);
	while (len > 0) {
		bio = g_alloc_bio();
		bio->bio_cmd	    = BIO_DELETE;
		bio->bio_dev	    = dev;
		bio->bio_offset	    = off;
		bio->bio_length	    = MIN(len, maxlen);
		bio->bio_data	    = 0;
		bio->bio_done	    = ctl_be_block_biodone;
		bio->bio_caller1    = beio;
		bio->bio_pblkno     = off / be_lun->cbe_lun.blocksize;

		off += bio->bio_length;
		len -= bio->bio_length;

		mtx_lock(&be_lun->io_lock);
		beio->num_bios_sent++;
		if (last && len == 0)
			beio->send_complete = 1;
		mtx_unlock(&be_lun->io_lock);

		if (csw) {
			csw->d_strategy(bio);
		} else {
			bio->bio_error = ENXIO;
			ctl_be_block_biodone(bio);
		}
	}
	if (csw)
		dev_relthread(dev, ref);
}

static void
ctl_be_block_unmap_dev(struct ctl_be_block_lun *be_lun,
		       struct ctl_be_block_io *beio)
{
	union ctl_io *io;
	struct ctl_ptr_len_flags *ptrlen;
	struct scsi_unmap_desc *buf, *end;
	uint64_t len;

	io = beio->io;

	DPRINTF("entered\n");

	binuptime(&beio->ds_t0);
	mtx_lock(&be_lun->io_lock);
	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
	mtx_unlock(&be_lun->io_lock);

	if (beio->io_offset == -1) {
		beio->io_len = 0;
		ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
		buf = (struct scsi_unmap_desc *)ptrlen->ptr;
		end = buf + ptrlen->len / sizeof(*buf);
		for (; buf < end; buf++) {
			len = (uint64_t)scsi_4btoul(buf->length) *
			    be_lun->cbe_lun.blocksize;
			beio->io_len += len;
			ctl_be_block_unmap_dev_range(be_lun, beio,
			    scsi_8btou64(buf->lba) * be_lun->cbe_lun.blocksize,
			    len, (end - buf < 2) ? TRUE : FALSE);
		}
	} else
		ctl_be_block_unmap_dev_range(be_lun, beio,
		    beio->io_offset, beio->io_len, TRUE);
}

static void
ctl_be_block_dispatch_dev(struct ctl_be_block_lun *be_lun,
			  struct ctl_be_block_io *beio)
{
	TAILQ_HEAD(, bio) queue = TAILQ_HEAD_INITIALIZER(queue);
	struct bio *bio;
	struct cdevsw *csw;
	struct cdev *dev;
	off_t cur_offset;
	int i, max_iosize, ref;

	DPRINTF("entered\n");
	csw = devvn_refthread(be_lun->vn, &dev, &ref);

	/*
	 * We have to limit our I/O size to the maximum supported by the
	 * backend device.  Hopefully it is MAXPHYS.  If the driver doesn't
	 * set it properly, use DFLTPHYS.
	 */
	if (csw) {
		max_iosize = dev->si_iosize_max;
		if (max_iosize < PAGE_SIZE)
			max_iosize = DFLTPHYS;
	} else
		max_iosize = DFLTPHYS;

	cur_offset = beio->io_offset;
	for (i = 0; i < beio->num_segs; i++) {
		size_t cur_size;
		uint8_t *cur_ptr;

		cur_size = beio->sg_segs[i].len;
		cur_ptr = beio->sg_segs[i].addr;

		while (cur_size > 0) {
			/* This can't fail, it's a blocking allocation. */
			bio = g_alloc_bio();

			KASSERT(bio != NULL, ("g_alloc_bio() failed!\n"));

			bio->bio_cmd = beio->bio_cmd;
			bio->bio_dev = dev;
			bio->bio_caller1 = beio;
			bio->bio_length = min(cur_size, max_iosize);
			bio->bio_offset = cur_offset;
			bio->bio_data = cur_ptr;
			bio->bio_done = ctl_be_block_biodone;
			bio->bio_pblkno = cur_offset / be_lun->cbe_lun.blocksize;

			cur_offset += bio->bio_length;
			cur_ptr += bio->bio_length;
			cur_size -= bio->bio_length;

			TAILQ_INSERT_TAIL(&queue, bio, bio_queue);
			beio->num_bios_sent++;
		}
	}
	binuptime(&beio->ds_t0);
	mtx_lock(&be_lun->io_lock);
	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
	beio->send_complete = 1;
	mtx_unlock(&be_lun->io_lock);

	/*
	 * Fire off all allocated requests!
	 */
	while ((bio = TAILQ_FIRST(&queue)) != NULL) {
		TAILQ_REMOVE(&queue, bio, bio_queue);
		if (csw)
			csw->d_strategy(bio);
		else {
			bio->bio_error = ENXIO;
			ctl_be_block_biodone(bio);
		}
	}
	if (csw)
		dev_relthread(dev, ref);
}

static uint64_t
ctl_be_block_getattr_dev(struct ctl_be_block_lun *be_lun, const char *attrname)
{
	struct diocgattr_arg	arg;
	struct cdevsw *csw;
	struct cdev *dev;
	int error, ref;

	csw = devvn_refthread(be_lun->vn, &dev, &ref);
	if (csw == NULL)
		return (UINT64_MAX);
	strlcpy(arg.name, attrname, sizeof(arg.name));
	arg.len = sizeof(arg.value.off);
	if (csw->d_ioctl) {
		error = csw->d_ioctl(dev, DIOCGATTR, (caddr_t)&arg, FREAD,
		    curthread);
	} else
		error = ENODEV;
	dev_relthread(dev, ref);
	if (error != 0)
		return (UINT64_MAX);
	return (arg.value.off);
}

static void
ctl_be_block_cw_dispatch_sync(struct ctl_be_block_lun *be_lun,
			    union ctl_io *io)
{
	struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
	struct ctl_be_block_io *beio;
	struct ctl_lba_len_flags *lbalen;

	DPRINTF("entered\n");
	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
	lbalen = (struct ctl_lba_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];

	beio->io_len = lbalen->len * cbe_lun->blocksize;
	beio->io_offset = lbalen->lba * cbe_lun->blocksize;
	beio->io_arg = (lbalen->flags & SSC_IMMED) != 0;
	beio->bio_cmd = BIO_FLUSH;
	beio->ds_trans_type = DEVSTAT_NO_DATA;
	DPRINTF("SYNC\n");
	be_lun->lun_flush(be_lun, beio);
}

static void
ctl_be_block_cw_done_ws(struct ctl_be_block_io *beio)
{
	union ctl_io *io;

	io = beio->io;
	ctl_free_beio(beio);
	if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
		ctl_config_write_done(io);
		return;
	}

	ctl_be_block_config_write(io);
}

static void
ctl_be_block_cw_dispatch_ws(struct ctl_be_block_lun *be_lun,
			    union ctl_io *io)
{
	struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
	struct ctl_be_block_io *beio;
	struct ctl_lba_len_flags *lbalen;
	uint64_t len_left, lba;
	uint32_t pb, pbo, adj;
	int i, seglen;
	uint8_t *buf, *end;

	DPRINTF("entered\n");

	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
	lbalen = ARGS(beio->io);

	if (lbalen->flags & ~(SWS_LBDATA | SWS_UNMAP | SWS_ANCHOR | SWS_NDOB) ||
	    (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR) && be_lun->unmap == NULL)) {
		ctl_free_beio(beio);
		ctl_set_invalid_field(&io->scsiio,
				      /*sks_valid*/ 1,
				      /*command*/ 1,
				      /*field*/ 1,
				      /*bit_valid*/ 0,
				      /*bit*/ 0);
		ctl_config_write_done(io);
		return;
	}

	if (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR)) {
		beio->io_offset = lbalen->lba * cbe_lun->blocksize;
		beio->io_len = (uint64_t)lbalen->len * cbe_lun->blocksize;
		beio->bio_cmd = BIO_DELETE;
		beio->ds_trans_type = DEVSTAT_FREE;

		be_lun->unmap(be_lun, beio);
		return;
	}

	beio->bio_cmd = BIO_WRITE;
	beio->ds_trans_type = DEVSTAT_WRITE;

	DPRINTF("WRITE SAME at LBA %jx len %u\n",
	       (uintmax_t)lbalen->lba, lbalen->len);

	pb = cbe_lun->blocksize << be_lun->cbe_lun.pblockexp;
	if (be_lun->cbe_lun.pblockoff > 0)
		pbo = pb - cbe_lun->blocksize * be_lun->cbe_lun.pblockoff;
	else
		pbo = 0;
	len_left = (uint64_t)lbalen->len * cbe_lun->blocksize;
	for (i = 0, lba = 0; i < CTLBLK_MAX_SEGS && len_left > 0; i++) {

		/*
		 * Setup the S/G entry for this chunk.
		 */
		seglen = MIN(CTLBLK_MAX_SEG, len_left);
		if (pb > cbe_lun->blocksize) {
			adj = ((lbalen->lba + lba) * cbe_lun->blocksize +
			    seglen - pbo) % pb;
			if (seglen > adj)
				seglen -= adj;
			else
				seglen -= seglen % cbe_lun->blocksize;
		} else
			seglen -= seglen % cbe_lun->blocksize;
		beio->sg_segs[i].len = seglen;
		beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);

		DPRINTF("segment %d addr %p len %zd\n", i,
			beio->sg_segs[i].addr, beio->sg_segs[i].len);

		beio->num_segs++;
		len_left -= seglen;

		buf = beio->sg_segs[i].addr;
		end = buf + seglen;
		for (; buf < end; buf += cbe_lun->blocksize) {
			if (lbalen->flags & SWS_NDOB) {
				memset(buf, 0, cbe_lun->blocksize);
			} else {
				memcpy(buf, io->scsiio.kern_data_ptr,
				    cbe_lun->blocksize);
			}
			if (lbalen->flags & SWS_LBDATA)
				scsi_ulto4b(lbalen->lba + lba, buf);
			lba++;
		}
	}

	beio->io_offset = lbalen->lba * cbe_lun->blocksize;
	beio->io_len = lba * cbe_lun->blocksize;

	/* We can not do all in one run. Correct and schedule rerun. */
	if (len_left > 0) {
		lbalen->lba += lba;
		lbalen->len -= lba;
		beio->beio_cont = ctl_be_block_cw_done_ws;
	}

	be_lun->dispatch(be_lun, beio);
}

static void
ctl_be_block_cw_dispatch_unmap(struct ctl_be_block_lun *be_lun,
			    union ctl_io *io)
{
	struct ctl_be_block_io *beio;
	struct ctl_ptr_len_flags *ptrlen;

	DPRINTF("entered\n");

	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
	ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];

	if ((ptrlen->flags & ~SU_ANCHOR) != 0 || be_lun->unmap == NULL) {
		ctl_free_beio(beio);
		ctl_set_invalid_field(&io->scsiio,
				      /*sks_valid*/ 0,
				      /*command*/ 1,
				      /*field*/ 0,
				      /*bit_valid*/ 0,
				      /*bit*/ 0);
		ctl_config_write_done(io);
		return;
	}

	beio->io_len = 0;
	beio->io_offset = -1;
	beio->bio_cmd = BIO_DELETE;
	beio->ds_trans_type = DEVSTAT_FREE;
	DPRINTF("UNMAP\n");
	be_lun->unmap(be_lun, beio);
}

static void
ctl_be_block_cr_done(struct ctl_be_block_io *beio)
{
	union ctl_io *io;

	io = beio->io;
	ctl_free_beio(beio);
	ctl_config_read_done(io);
}

static void
ctl_be_block_cr_dispatch(struct ctl_be_block_lun *be_lun,
			 union ctl_io *io)
{
	struct ctl_be_block_io *beio;
	struct ctl_be_block_softc *softc;

	DPRINTF("entered\n");

	softc = be_lun->softc;
	beio = ctl_alloc_beio(softc);
	beio->io = io;
	beio->lun = be_lun;
	beio->beio_cont = ctl_be_block_cr_done;
	PRIV(io)->ptr = (void *)beio;

	switch (io->scsiio.cdb[0]) {
	case SERVICE_ACTION_IN:		/* GET LBA STATUS */
		beio->bio_cmd = -1;
		beio->ds_trans_type = DEVSTAT_NO_DATA;
		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
		beio->io_len = 0;
		if (be_lun->get_lba_status)
			be_lun->get_lba_status(be_lun, beio);
		else
			ctl_be_block_cr_done(beio);
		break;
	default:
		panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
		break;
	}
}

static void
ctl_be_block_cw_done(struct ctl_be_block_io *beio)
{
	union ctl_io *io;

	io = beio->io;
	ctl_free_beio(beio);
	ctl_config_write_done(io);
}

static void
ctl_be_block_cw_dispatch(struct ctl_be_block_lun *be_lun,
			 union ctl_io *io)
{
	struct ctl_be_block_io *beio;
	struct ctl_be_block_softc *softc;

	DPRINTF("entered\n");

	softc = be_lun->softc;
	beio = ctl_alloc_beio(softc);
	beio->io = io;
	beio->lun = be_lun;
	beio->beio_cont = ctl_be_block_cw_done;
	switch (io->scsiio.tag_type) {
	case CTL_TAG_ORDERED:
		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
		break;
	case CTL_TAG_HEAD_OF_QUEUE:
		beio->ds_tag_type = DEVSTAT_TAG_HEAD;
		break;
	case CTL_TAG_UNTAGGED:
	case CTL_TAG_SIMPLE:
	case CTL_TAG_ACA:
	default:
		beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
		break;
	}
	PRIV(io)->ptr = (void *)beio;

	switch (io->scsiio.cdb[0]) {
	case SYNCHRONIZE_CACHE:
	case SYNCHRONIZE_CACHE_16:
		ctl_be_block_cw_dispatch_sync(be_lun, io);
		break;
	case WRITE_SAME_10:
	case WRITE_SAME_16:
		ctl_be_block_cw_dispatch_ws(be_lun, io);
		break;
	case UNMAP:
		ctl_be_block_cw_dispatch_unmap(be_lun, io);
		break;
	default:
		panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
		break;
	}
}

SDT_PROBE_DEFINE1(cbb, , read, start, "uint64_t");
SDT_PROBE_DEFINE1(cbb, , write, start, "uint64_t");
SDT_PROBE_DEFINE1(cbb, , read, alloc_done, "uint64_t");
SDT_PROBE_DEFINE1(cbb, , write, alloc_done, "uint64_t");

static void
ctl_be_block_next(struct ctl_be_block_io *beio)
{
	struct ctl_be_block_lun *be_lun;
	union ctl_io *io;

	io = beio->io;
	be_lun = beio->lun;
	ctl_free_beio(beio);
	if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
		ctl_data_submit_done(io);
		return;
	}

	io->io_hdr.status &= ~CTL_STATUS_MASK;
	io->io_hdr.status |= CTL_STATUS_NONE;

	mtx_lock(&be_lun->queue_lock);
	STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
	mtx_unlock(&be_lun->queue_lock);
	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
}

static void
ctl_be_block_dispatch(struct ctl_be_block_lun *be_lun,
			   union ctl_io *io)
{
	struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
	struct ctl_be_block_io *beio;
	struct ctl_be_block_softc *softc;
	struct ctl_lba_len_flags *lbalen;
	struct ctl_ptr_len_flags *bptrlen;
	uint64_t len_left, lbas;
	int i;

	softc = be_lun->softc;

	DPRINTF("entered\n");

	lbalen = ARGS(io);
	if (lbalen->flags & CTL_LLF_WRITE) {
		SDT_PROBE0(cbb, , write, start);
	} else {
		SDT_PROBE0(cbb, , read, start);
	}

	beio = ctl_alloc_beio(softc);
	beio->io = io;
	beio->lun = be_lun;
	bptrlen = PRIV(io);
	bptrlen->ptr = (void *)beio;

	switch (io->scsiio.tag_type) {
	case CTL_TAG_ORDERED:
		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
		break;
	case CTL_TAG_HEAD_OF_QUEUE:
		beio->ds_tag_type = DEVSTAT_TAG_HEAD;
		break;
	case CTL_TAG_UNTAGGED:
	case CTL_TAG_SIMPLE:
	case CTL_TAG_ACA:
	default:
		beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
		break;
	}

	if (lbalen->flags & CTL_LLF_WRITE) {
		beio->bio_cmd = BIO_WRITE;
		beio->ds_trans_type = DEVSTAT_WRITE;
	} else {
		beio->bio_cmd = BIO_READ;
		beio->ds_trans_type = DEVSTAT_READ;
	}

	DPRINTF("%s at LBA %jx len %u @%ju\n",
	       (beio->bio_cmd == BIO_READ) ? "READ" : "WRITE",
	       (uintmax_t)lbalen->lba, lbalen->len, bptrlen->len);
	if (lbalen->flags & CTL_LLF_COMPARE)
		lbas = CTLBLK_HALF_IO_SIZE;
	else
		lbas = CTLBLK_MAX_IO_SIZE;
	lbas = MIN(lbalen->len - bptrlen->len, lbas / cbe_lun->blocksize);
	beio->io_offset = (lbalen->lba + bptrlen->len) * cbe_lun->blocksize;
	beio->io_len = lbas * cbe_lun->blocksize;
	bptrlen->len += lbas;

	for (i = 0, len_left = beio->io_len; len_left > 0; i++) {
		KASSERT(i < CTLBLK_MAX_SEGS, ("Too many segs (%d >= %d)",
		    i, CTLBLK_MAX_SEGS));

		/*
		 * Setup the S/G entry for this chunk.
		 */
		beio->sg_segs[i].len = min(CTLBLK_MAX_SEG, len_left);
		beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);

		DPRINTF("segment %d addr %p len %zd\n", i,
			beio->sg_segs[i].addr, beio->sg_segs[i].len);

		/* Set up second segment for compare operation. */
		if (lbalen->flags & CTL_LLF_COMPARE) {
			beio->sg_segs[i + CTLBLK_HALF_SEGS].len =
			    beio->sg_segs[i].len;
			beio->sg_segs[i + CTLBLK_HALF_SEGS].addr =
			    uma_zalloc(be_lun->lun_zone, M_WAITOK);
		}

		beio->num_segs++;
		len_left -= beio->sg_segs[i].len;
	}
	if (bptrlen->len < lbalen->len)
		beio->beio_cont = ctl_be_block_next;
	io->scsiio.be_move_done = ctl_be_block_move_done;
	/* For compare we have separate S/G lists for read and datamove. */
	if (lbalen->flags & CTL_LLF_COMPARE)
		io->scsiio.kern_data_ptr = (uint8_t *)&beio->sg_segs[CTLBLK_HALF_SEGS];
	else
		io->scsiio.kern_data_ptr = (uint8_t *)beio->sg_segs;
	io->scsiio.kern_data_len = beio->io_len;
	io->scsiio.kern_sg_entries = beio->num_segs;
	io->io_hdr.flags |= CTL_FLAG_ALLOCATED;

	/*
	 * For the read case, we need to read the data into our buffers and
	 * then we can send it back to the user.  For the write case, we
	 * need to get the data from the user first.
	 */
	if (beio->bio_cmd == BIO_READ) {
		SDT_PROBE0(cbb, , read, alloc_done);
		be_lun->dispatch(be_lun, beio);
	} else {
		SDT_PROBE0(cbb, , write, alloc_done);
#ifdef CTL_TIME_IO
		getbinuptime(&io->io_hdr.dma_start_bt);
#endif
		ctl_datamove(io);
	}
}

static void
ctl_be_block_worker(void *context, int pending)
{
	struct ctl_be_block_lun *be_lun = (struct ctl_be_block_lun *)context;
	struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
	union ctl_io *io;
	struct ctl_be_block_io *beio;

	DPRINTF("entered\n");
	/*
	 * Fetch and process I/Os from all queues.  If we detect LUN
	 * CTL_LUN_FLAG_NO_MEDIA status here -- it is result of a race,
	 * so make response maximally opaque to not confuse initiator.
	 */
	for (;;) {
		mtx_lock(&be_lun->queue_lock);
		io = (union ctl_io *)STAILQ_FIRST(&be_lun->datamove_queue);
		if (io != NULL) {
			DPRINTF("datamove queue\n");
			STAILQ_REMOVE(&be_lun->datamove_queue, &io->io_hdr,
				      ctl_io_hdr, links);
			mtx_unlock(&be_lun->queue_lock);
			beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
			if (cbe_lun->flags & CTL_LUN_FLAG_NO_MEDIA) {
				ctl_set_busy(&io->scsiio);
				ctl_complete_beio(beio);
				return;
			}
			be_lun->dispatch(be_lun, beio);
			continue;
		}
		io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_write_queue);
		if (io != NULL) {
			DPRINTF("config write queue\n");
			STAILQ_REMOVE(&be_lun->config_write_queue, &io->io_hdr,
				      ctl_io_hdr, links);
			mtx_unlock(&be_lun->queue_lock);
			if (cbe_lun->flags & CTL_LUN_FLAG_NO_MEDIA) {
				ctl_set_busy(&io->scsiio);
				ctl_config_write_done(io);
				return;
			}
			ctl_be_block_cw_dispatch(be_lun, io);
			continue;
		}
		io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_read_queue);
		if (io != NULL) {
			DPRINTF("config read queue\n");
			STAILQ_REMOVE(&be_lun->config_read_queue, &io->io_hdr,
				      ctl_io_hdr, links);
			mtx_unlock(&be_lun->queue_lock);
			if (cbe_lun->flags & CTL_LUN_FLAG_NO_MEDIA) {
				ctl_set_busy(&io->scsiio);
				ctl_config_read_done(io);
				return;
			}
			ctl_be_block_cr_dispatch(be_lun, io);
			continue;
		}
		io = (union ctl_io *)STAILQ_FIRST(&be_lun->input_queue);
		if (io != NULL) {
			DPRINTF("input queue\n");
			STAILQ_REMOVE(&be_lun->input_queue, &io->io_hdr,
				      ctl_io_hdr, links);
			mtx_unlock(&be_lun->queue_lock);
			if (cbe_lun->flags & CTL_LUN_FLAG_NO_MEDIA) {
				ctl_set_busy(&io->scsiio);
				ctl_data_submit_done(io);
				return;
			}
			ctl_be_block_dispatch(be_lun, io);
			continue;
		}

		/*
		 * If we get here, there is no work left in the queues, so
		 * just break out and let the task queue go to sleep.
		 */
		mtx_unlock(&be_lun->queue_lock);
		break;
	}
}

/*
 * Entry point from CTL to the backend for I/O.  We queue everything to a
 * work thread, so this just puts the I/O on a queue and wakes up the
 * thread.
 */
static int
ctl_be_block_submit(union ctl_io *io)
{
	struct ctl_be_block_lun *be_lun;
	struct ctl_be_lun *cbe_lun;

	DPRINTF("entered\n");

	cbe_lun = CTL_BACKEND_LUN(io);
	be_lun = (struct ctl_be_block_lun *)cbe_lun->be_lun;

	/*
	 * Make sure we only get SCSI I/O.
	 */
	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI, ("Non-SCSI I/O (type "
		"%#x) encountered", io->io_hdr.io_type));

	PRIV(io)->len = 0;

	mtx_lock(&be_lun->queue_lock);
	STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
	mtx_unlock(&be_lun->queue_lock);
	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);

	return (CTL_RETVAL_COMPLETE);
}

static int
ctl_be_block_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
			int flag, struct thread *td)
{
	struct ctl_be_block_softc *softc;
	int error;

	softc = &backend_block_softc;

	error = 0;

	switch (cmd) {
	case CTL_LUN_REQ: {
		struct ctl_lun_req *lun_req;

		lun_req = (struct ctl_lun_req *)addr;

		switch (lun_req->reqtype) {
		case CTL_LUNREQ_CREATE:
			error = ctl_be_block_create(softc, lun_req);
			break;
		case CTL_LUNREQ_RM:
			error = ctl_be_block_rm(softc, lun_req);
			break;
		case CTL_LUNREQ_MODIFY:
			error = ctl_be_block_modify(softc, lun_req);
			break;
		default:
			lun_req->status = CTL_LUN_ERROR;
			snprintf(lun_req->error_str, sizeof(lun_req->error_str),
				 "invalid LUN request type %d",
				 lun_req->reqtype);
			break;
		}
		break;
	}
	default:
		error = ENOTTY;
		break;
	}

	return (error);
}

static int
ctl_be_block_open_file(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
{
	struct ctl_be_lun *cbe_lun;
	struct ctl_be_block_filedata *file_data;
	struct ctl_lun_create_params *params;
	const char		     *value;
	struct vattr		      vattr;
	off_t			      ps, pss, po, pos, us, uss, uo, uos;
	int			      error;

	cbe_lun = &be_lun->cbe_lun;
	file_data = &be_lun->backend.file;
	params = &be_lun->params;

	be_lun->dev_type = CTL_BE_BLOCK_FILE;
	be_lun->dispatch = ctl_be_block_dispatch_file;
	be_lun->lun_flush = ctl_be_block_flush_file;
	be_lun->get_lba_status = ctl_be_block_gls_file;
	be_lun->getattr = ctl_be_block_getattr_file;
	be_lun->unmap = NULL;
	cbe_lun->flags &= ~CTL_LUN_FLAG_UNMAP;

	error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
	if (error != 0) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "error calling VOP_GETATTR() for file %s",
			 be_lun->dev_path);
		return (error);
	}

	file_data->cred = crhold(curthread->td_ucred);
	if (params->lun_size_bytes != 0)
		be_lun->size_bytes = params->lun_size_bytes;
	else
		be_lun->size_bytes = vattr.va_size;

	/*
	 * For files we can use any logical block size.  Prefer 512 bytes
	 * for compatibility reasons.  If file's vattr.va_blocksize
	 * (preferred I/O block size) is bigger and multiple to chosen
	 * logical block size -- report it as physical block size.
	 */
	if (params->blocksize_bytes != 0)
		cbe_lun->blocksize = params->blocksize_bytes;
	else if (cbe_lun->lun_type == T_CDROM)
		cbe_lun->blocksize = 2048;
	else
		cbe_lun->blocksize = 512;
	be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
	cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
	    0 : (be_lun->size_blocks - 1);

	us = ps = vattr.va_blocksize;
	uo = po = 0;

	value = dnvlist_get_string(cbe_lun->options, "pblocksize", NULL);
	if (value != NULL)
		ctl_expand_number(value, &ps);
	value = dnvlist_get_string(cbe_lun->options, "pblockoffset", NULL);
	if (value != NULL)
		ctl_expand_number(value, &po);
	pss = ps / cbe_lun->blocksize;
	pos = po / cbe_lun->blocksize;
	if ((pss > 0) && (pss * cbe_lun->blocksize == ps) && (pss >= pos) &&
	    ((pss & (pss - 1)) == 0) && (pos * cbe_lun->blocksize == po)) {
		cbe_lun->pblockexp = fls(pss) - 1;
		cbe_lun->pblockoff = (pss - pos) % pss;
	}

	value = dnvlist_get_string(cbe_lun->options, "ublocksize", NULL);
	if (value != NULL)
		ctl_expand_number(value, &us);
	value = dnvlist_get_string(cbe_lun->options, "ublockoffset", NULL);
	if (value != NULL)
		ctl_expand_number(value, &uo);
	uss = us / cbe_lun->blocksize;
	uos = uo / cbe_lun->blocksize;
	if ((uss > 0) && (uss * cbe_lun->blocksize == us) && (uss >= uos) &&
	    ((uss & (uss - 1)) == 0) && (uos * cbe_lun->blocksize == uo)) {
		cbe_lun->ublockexp = fls(uss) - 1;
		cbe_lun->ublockoff = (uss - uos) % uss;
	}

	/*
	 * Sanity check.  The media size has to be at least one
	 * sector long.
	 */
	if (be_lun->size_bytes < cbe_lun->blocksize) {
		error = EINVAL;
		snprintf(req->error_str, sizeof(req->error_str),
			 "file %s size %ju < block size %u", be_lun->dev_path,
			 (uintmax_t)be_lun->size_bytes, cbe_lun->blocksize);
	}

	cbe_lun->opttxferlen = CTLBLK_MAX_IO_SIZE / cbe_lun->blocksize;
	return (error);
}

static int
ctl_be_block_open_dev(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
{
	struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
	struct ctl_lun_create_params *params;
	struct cdevsw		     *csw;
	struct cdev		     *dev;
	const char		     *value;
	int			      error, atomic, maxio, ref, unmap, tmp;
	off_t			      ps, pss, po, pos, us, uss, uo, uos, otmp;

	params = &be_lun->params;

	be_lun->dev_type = CTL_BE_BLOCK_DEV;
	csw = devvn_refthread(be_lun->vn, &dev, &ref);
	if (csw == NULL)
		return (ENXIO);
	if (strcmp(csw->d_name, "zvol") == 0) {
		be_lun->dispatch = ctl_be_block_dispatch_zvol;
		be_lun->get_lba_status = ctl_be_block_gls_zvol;
		atomic = maxio = CTLBLK_MAX_IO_SIZE;
	} else {
		be_lun->dispatch = ctl_be_block_dispatch_dev;
		be_lun->get_lba_status = NULL;
		atomic = 0;
		maxio = dev->si_iosize_max;
		if (maxio <= 0)
			maxio = DFLTPHYS;
		if (maxio > CTLBLK_MAX_IO_SIZE)
			maxio = CTLBLK_MAX_IO_SIZE;
	}
	be_lun->lun_flush = ctl_be_block_flush_dev;
	be_lun->getattr = ctl_be_block_getattr_dev;
	be_lun->unmap = ctl_be_block_unmap_dev;

	if (!csw->d_ioctl) {
		dev_relthread(dev, ref);
		snprintf(req->error_str, sizeof(req->error_str),
			 "no d_ioctl for device %s!", be_lun->dev_path);
		return (ENODEV);
	}

	error = csw->d_ioctl(dev, DIOCGSECTORSIZE, (caddr_t)&tmp, FREAD,
			       curthread);
	if (error) {
		dev_relthread(dev, ref);
		snprintf(req->error_str, sizeof(req->error_str),
			 "error %d returned for DIOCGSECTORSIZE ioctl "
			 "on %s!", error, be_lun->dev_path);
		return (error);
	}

	/*
	 * If the user has asked for a blocksize that is greater than the
	 * backing device's blocksize, we can do it only if the blocksize
	 * the user is asking for is an even multiple of the underlying 
	 * device's blocksize.
	 */
	if ((params->blocksize_bytes != 0) &&
	    (params->blocksize_bytes >= tmp)) {
		if (params->blocksize_bytes % tmp == 0) {
			cbe_lun->blocksize = params->blocksize_bytes;
		} else {
			dev_relthread(dev, ref);
			snprintf(req->error_str, sizeof(req->error_str),
				 "requested blocksize %u is not an even "
				 "multiple of backing device blocksize %u",
				 params->blocksize_bytes, tmp);
			return (EINVAL);
		}
	} else if (params->blocksize_bytes != 0) {
		dev_relthread(dev, ref);
		snprintf(req->error_str, sizeof(req->error_str),
			 "requested blocksize %u < backing device "
			 "blocksize %u", params->blocksize_bytes, tmp);
		return (EINVAL);
	} else if (cbe_lun->lun_type == T_CDROM)
		cbe_lun->blocksize = MAX(tmp, 2048);
	else
		cbe_lun->blocksize = tmp;

	error = csw->d_ioctl(dev, DIOCGMEDIASIZE, (caddr_t)&otmp, FREAD,
			     curthread);
	if (error) {
		dev_relthread(dev, ref);
		snprintf(req->error_str, sizeof(req->error_str),
			 "error %d returned for DIOCGMEDIASIZE "
			 " ioctl on %s!", error,
			 be_lun->dev_path);
		return (error);
	}

	if (params->lun_size_bytes != 0) {
		if (params->lun_size_bytes > otmp) {
			dev_relthread(dev, ref);
			snprintf(req->error_str, sizeof(req->error_str),
				 "requested LUN size %ju > backing device "
				 "size %ju",
				 (uintmax_t)params->lun_size_bytes,
				 (uintmax_t)otmp);
			return (EINVAL);
		}

		be_lun->size_bytes = params->lun_size_bytes;
	} else
		be_lun->size_bytes = otmp;
	be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
	cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
	    0 : (be_lun->size_blocks - 1);

	error = csw->d_ioctl(dev, DIOCGSTRIPESIZE, (caddr_t)&ps, FREAD,
	    curthread);
	if (error)
		ps = po = 0;
	else {
		error = csw->d_ioctl(dev, DIOCGSTRIPEOFFSET, (caddr_t)&po,
		    FREAD, curthread);
		if (error)
			po = 0;
	}
	us = ps;
	uo = po;

	value = dnvlist_get_string(cbe_lun->options, "pblocksize", NULL);
	if (value != NULL)
		ctl_expand_number(value, &ps);
	value = dnvlist_get_string(cbe_lun->options, "pblockoffset", NULL);
	if (value != NULL)
		ctl_expand_number(value, &po);
	pss = ps / cbe_lun->blocksize;
	pos = po / cbe_lun->blocksize;
	if ((pss > 0) && (pss * cbe_lun->blocksize == ps) && (pss >= pos) &&
	    ((pss & (pss - 1)) == 0) && (pos * cbe_lun->blocksize == po)) {
		cbe_lun->pblockexp = fls(pss) - 1;
		cbe_lun->pblockoff = (pss - pos) % pss;
	}

	value = dnvlist_get_string(cbe_lun->options, "ublocksize", NULL);
	if (value != NULL)
		ctl_expand_number(value, &us);
	value = dnvlist_get_string(cbe_lun->options, "ublockoffset", NULL);
	if (value != NULL)
		ctl_expand_number(value, &uo);
	uss = us / cbe_lun->blocksize;
	uos = uo / cbe_lun->blocksize;
	if ((uss > 0) && (uss * cbe_lun->blocksize == us) && (uss >= uos) &&
	    ((uss & (uss - 1)) == 0) && (uos * cbe_lun->blocksize == uo)) {
		cbe_lun->ublockexp = fls(uss) - 1;
		cbe_lun->ublockoff = (uss - uos) % uss;
	}

	cbe_lun->atomicblock = atomic / cbe_lun->blocksize;
	cbe_lun->opttxferlen = maxio / cbe_lun->blocksize;

	if (be_lun->dispatch == ctl_be_block_dispatch_zvol) {
		unmap = 1;
	} else {
		struct diocgattr_arg	arg;

		strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
		arg.len = sizeof(arg.value.i);
		error = csw->d_ioctl(dev, DIOCGATTR, (caddr_t)&arg, FREAD,
		    curthread);
		unmap = (error == 0) ? arg.value.i : 0;
	}
	value = dnvlist_get_string(cbe_lun->options, "unmap", NULL);
	if (value != NULL)
		unmap = (strcmp(value, "on") == 0);
	if (unmap)
		cbe_lun->flags |= CTL_LUN_FLAG_UNMAP;
	else
		cbe_lun->flags &= ~CTL_LUN_FLAG_UNMAP;

	dev_relthread(dev, ref);
	return (0);
}

static int
ctl_be_block_close(struct ctl_be_block_lun *be_lun)
{
	struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
	int flags;

	if (be_lun->vn) {
		flags = FREAD;
		if ((cbe_lun->flags & CTL_LUN_FLAG_READONLY) == 0)
			flags |= FWRITE;
		(void)vn_close(be_lun->vn, flags, NOCRED, curthread);
		be_lun->vn = NULL;

		switch (be_lun->dev_type) {
		case CTL_BE_BLOCK_DEV:
			break;
		case CTL_BE_BLOCK_FILE:
			if (be_lun->backend.file.cred != NULL) {
				crfree(be_lun->backend.file.cred);
				be_lun->backend.file.cred = NULL;
			}
			break;
		case CTL_BE_BLOCK_NONE:
			break;
		default:
			panic("Unexpected backend type %d", be_lun->dev_type);
			break;
		}
		be_lun->dev_type = CTL_BE_BLOCK_NONE;
	}
	return (0);
}

static int
ctl_be_block_open(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
{
	struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
	struct nameidata nd;
	const char	*value;
	int		 error, flags;

	error = 0;
	if (rootvnode == NULL) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "Root filesystem is not mounted");
		return (1);
	}
	pwd_ensure_dirs();

	value = dnvlist_get_string(cbe_lun->options, "file", NULL);
	if (value == NULL) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "no file argument specified");
		return (1);
	}
	free(be_lun->dev_path, M_CTLBLK);
	be_lun->dev_path = strdup(value, M_CTLBLK);

	flags = FREAD;
	value = dnvlist_get_string(cbe_lun->options, "readonly", NULL);
	if (value != NULL) {
		if (strcmp(value, "on") != 0)
			flags |= FWRITE;
	} else if (cbe_lun->lun_type == T_DIRECT)
		flags |= FWRITE;

again:
	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, be_lun->dev_path, curthread);
	error = vn_open(&nd, &flags, 0, NULL);
	if ((error == EROFS || error == EACCES) && (flags & FWRITE)) {
		flags &= ~FWRITE;
		goto again;
	}
	if (error) {
		/*
		 * This is the only reasonable guess we can make as far as
		 * path if the user doesn't give us a fully qualified path.
		 * If they want to specify a file, they need to specify the
		 * full path.
		 */
		if (be_lun->dev_path[0] != '/') {
			char *dev_name;

			asprintf(&dev_name, M_CTLBLK, "/dev/%s",
				be_lun->dev_path);
			free(be_lun->dev_path, M_CTLBLK);
			be_lun->dev_path = dev_name;
			goto again;
		}
		snprintf(req->error_str, sizeof(req->error_str),
		    "error opening %s: %d", be_lun->dev_path, error);
		return (error);
	}
	if (flags & FWRITE)
		cbe_lun->flags &= ~CTL_LUN_FLAG_READONLY;
	else
		cbe_lun->flags |= CTL_LUN_FLAG_READONLY;

	NDFREE(&nd, NDF_ONLY_PNBUF);
	be_lun->vn = nd.ni_vp;

	/* We only support disks and files. */
	if (vn_isdisk(be_lun->vn, &error)) {
		error = ctl_be_block_open_dev(be_lun, req);
	} else if (be_lun->vn->v_type == VREG) {
		error = ctl_be_block_open_file(be_lun, req);
	} else {
		error = EINVAL;
		snprintf(req->error_str, sizeof(req->error_str),
			 "%s is not a disk or plain file", be_lun->dev_path);
	}
	VOP_UNLOCK(be_lun->vn, 0);

	if (error != 0)
		ctl_be_block_close(be_lun);
	cbe_lun->serseq = CTL_LUN_SERSEQ_OFF;
	if (be_lun->dispatch != ctl_be_block_dispatch_dev)
		cbe_lun->serseq = CTL_LUN_SERSEQ_READ;
	value = dnvlist_get_string(cbe_lun->options, "serseq", NULL);
	if (value != NULL && strcmp(value, "on") == 0)
		cbe_lun->serseq = CTL_LUN_SERSEQ_ON;
	else if (value != NULL && strcmp(value, "read") == 0)
		cbe_lun->serseq = CTL_LUN_SERSEQ_READ;
	else if (value != NULL && strcmp(value, "off") == 0)
		cbe_lun->serseq = CTL_LUN_SERSEQ_OFF;
	return (0);
}

static int
ctl_be_block_create(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
{
	struct ctl_be_lun *cbe_lun;
	struct ctl_be_block_lun *be_lun;
	struct ctl_lun_create_params *params;
	char num_thread_str[16];
	char tmpstr[32];
	const char *value;
	int retval, num_threads;
	int tmp_num_threads;

	params = &req->reqdata.create;
	retval = 0;
	req->status = CTL_LUN_OK;

	be_lun = malloc(sizeof(*be_lun), M_CTLBLK, M_ZERO | M_WAITOK);
	cbe_lun = &be_lun->cbe_lun;
	cbe_lun->be_lun = be_lun;
	be_lun->params = req->reqdata.create;
	be_lun->softc = softc;
	STAILQ_INIT(&be_lun->input_queue);
	STAILQ_INIT(&be_lun->config_read_queue);
	STAILQ_INIT(&be_lun->config_write_queue);
	STAILQ_INIT(&be_lun->datamove_queue);
	sprintf(be_lun->lunname, "cblk%d", softc->num_luns);
	mtx_init(&be_lun->io_lock, "cblk io lock", NULL, MTX_DEF);
	mtx_init(&be_lun->queue_lock, "cblk queue lock", NULL, MTX_DEF);
	cbe_lun->options = nvlist_clone(req->args_nvl);
	be_lun->lun_zone = uma_zcreate(be_lun->lunname, CTLBLK_MAX_SEG,
	    NULL, NULL, NULL, NULL, /*align*/ 0, /*flags*/0);
	if (be_lun->lun_zone == NULL) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "error allocating UMA zone");
		goto bailout_error;
	}

	if (params->flags & CTL_LUN_FLAG_DEV_TYPE)
		cbe_lun->lun_type = params->device_type;
	else
		cbe_lun->lun_type = T_DIRECT;
	be_lun->flags = CTL_BE_BLOCK_LUN_UNCONFIGURED;
	cbe_lun->flags = 0;
	value = dnvlist_get_string(cbe_lun->options, "ha_role", NULL);
	if (value != NULL) {
		if (strcmp(value, "primary") == 0)
			cbe_lun->flags |= CTL_LUN_FLAG_PRIMARY;
	} else if (control_softc->flags & CTL_FLAG_ACTIVE_SHELF)
		cbe_lun->flags |= CTL_LUN_FLAG_PRIMARY;

	if (cbe_lun->lun_type == T_DIRECT ||
	    cbe_lun->lun_type == T_CDROM) {
		be_lun->size_bytes = params->lun_size_bytes;
		if (params->blocksize_bytes != 0)
			cbe_lun->blocksize = params->blocksize_bytes;
		else if (cbe_lun->lun_type == T_CDROM)
			cbe_lun->blocksize = 2048;
		else
			cbe_lun->blocksize = 512;
		be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
		cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
		    0 : (be_lun->size_blocks - 1);

		if ((cbe_lun->flags & CTL_LUN_FLAG_PRIMARY) ||
		    control_softc->ha_mode == CTL_HA_MODE_SER_ONLY) {
			retval = ctl_be_block_open(be_lun, req);
			if (retval != 0) {
				retval = 0;
				req->status = CTL_LUN_WARNING;
			}
		}
		num_threads = cbb_num_threads;
	} else {
		num_threads = 1;
	}

	value = dnvlist_get_string(cbe_lun->options, "num_threads", NULL);
	if (value != NULL) {
		tmp_num_threads = strtol(value, NULL, 0);

		/*
		 * We don't let the user specify less than one
		 * thread, but hope he's clueful enough not to
		 * specify 1000 threads.
		 */
		if (tmp_num_threads < 1) {
			snprintf(req->error_str, sizeof(req->error_str),
				 "invalid number of threads %s",
				 num_thread_str);
			goto bailout_error;
		}
		num_threads = tmp_num_threads;
	}

	if (be_lun->vn == NULL)
		cbe_lun->flags |= CTL_LUN_FLAG_NO_MEDIA;
	/* Tell the user the blocksize we ended up using */
	params->lun_size_bytes = be_lun->size_bytes;
	params->blocksize_bytes = cbe_lun->blocksize;
	if (params->flags & CTL_LUN_FLAG_ID_REQ) {
		cbe_lun->req_lun_id = params->req_lun_id;
		cbe_lun->flags |= CTL_LUN_FLAG_ID_REQ;
	} else
		cbe_lun->req_lun_id = 0;

	cbe_lun->lun_shutdown = ctl_be_block_lun_shutdown;
	cbe_lun->lun_config_status = ctl_be_block_lun_config_status;
	cbe_lun->be = &ctl_be_block_driver;

	if ((params->flags & CTL_LUN_FLAG_SERIAL_NUM) == 0) {
		snprintf(tmpstr, sizeof(tmpstr), "MYSERIAL%04d",
			 softc->num_luns);
		strncpy((char *)cbe_lun->serial_num, tmpstr,
			MIN(sizeof(cbe_lun->serial_num), sizeof(tmpstr)));

		/* Tell the user what we used for a serial number */
		strncpy((char *)params->serial_num, tmpstr,
			MIN(sizeof(params->serial_num), sizeof(tmpstr)));
	} else { 
		strncpy((char *)cbe_lun->serial_num, params->serial_num,
			MIN(sizeof(cbe_lun->serial_num),
			sizeof(params->serial_num)));
	}
	if ((params->flags & CTL_LUN_FLAG_DEVID) == 0) {
		snprintf(tmpstr, sizeof(tmpstr), "MYDEVID%04d", softc->num_luns);
		strncpy((char *)cbe_lun->device_id, tmpstr,
			MIN(sizeof(cbe_lun->device_id), sizeof(tmpstr)));

		/* Tell the user what we used for a device ID */
		strncpy((char *)params->device_id, tmpstr,
			MIN(sizeof(params->device_id), sizeof(tmpstr)));
	} else {
		strncpy((char *)cbe_lun->device_id, params->device_id,
			MIN(sizeof(cbe_lun->device_id),
			    sizeof(params->device_id)));
	}

	TASK_INIT(&be_lun->io_task, /*priority*/0, ctl_be_block_worker, be_lun);

	be_lun->io_taskqueue = taskqueue_create(be_lun->lunname, M_WAITOK,
	    taskqueue_thread_enqueue, /*context*/&be_lun->io_taskqueue);

	if (be_lun->io_taskqueue == NULL) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "unable to create taskqueue");
		goto bailout_error;
	}

	/*
	 * Note that we start the same number of threads by default for
	 * both the file case and the block device case.  For the file
	 * case, we need multiple threads to allow concurrency, because the
	 * vnode interface is designed to be a blocking interface.  For the
	 * block device case, ZFS zvols at least will block the caller's
	 * context in many instances, and so we need multiple threads to
	 * overcome that problem.  Other block devices don't need as many
	 * threads, but they shouldn't cause too many problems.
	 *
	 * If the user wants to just have a single thread for a block
	 * device, he can specify that when the LUN is created, or change
	 * the tunable/sysctl to alter the default number of threads.
	 */
	retval = taskqueue_start_threads(&be_lun->io_taskqueue,
					 /*num threads*/num_threads,
					 /*priority*/PUSER,
					 /*thread name*/
					 "%s taskq", be_lun->lunname);

	if (retval != 0)
		goto bailout_error;

	be_lun->num_threads = num_threads;

	mtx_lock(&softc->lock);
	softc->num_luns++;
	STAILQ_INSERT_TAIL(&softc->lun_list, be_lun, links);

	mtx_unlock(&softc->lock);

	retval = ctl_add_lun(&be_lun->cbe_lun);
	if (retval != 0) {
		mtx_lock(&softc->lock);
		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
			      links);
		softc->num_luns--;
		mtx_unlock(&softc->lock);
		snprintf(req->error_str, sizeof(req->error_str),
			 "ctl_add_lun() returned error %d, see dmesg for "
			 "details", retval);
		retval = 0;
		goto bailout_error;
	}

	mtx_lock(&softc->lock);

	/*
	 * Tell the config_status routine that we're waiting so it won't
	 * clean up the LUN in the event of an error.
	 */
	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;

	while (be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) {
		retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
		if (retval == EINTR)
			break;
	}
	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;

	if (be_lun->flags & CTL_BE_BLOCK_LUN_CONFIG_ERR) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "LUN configuration error, see dmesg for details");
		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
			      links);
		softc->num_luns--;
		mtx_unlock(&softc->lock);
		goto bailout_error;
	} else {
		params->req_lun_id = cbe_lun->lun_id;
	}

	mtx_unlock(&softc->lock);

	be_lun->disk_stats = devstat_new_entry("cbb", params->req_lun_id,
					       cbe_lun->blocksize,
					       DEVSTAT_ALL_SUPPORTED,
					       cbe_lun->lun_type
					       | DEVSTAT_TYPE_IF_OTHER,
					       DEVSTAT_PRIORITY_OTHER);

	return (retval);

bailout_error:
	req->status = CTL_LUN_ERROR;

	if (be_lun->io_taskqueue != NULL)
		taskqueue_free(be_lun->io_taskqueue);
	ctl_be_block_close(be_lun);
	if (be_lun->dev_path != NULL)
		free(be_lun->dev_path, M_CTLBLK);
	if (be_lun->lun_zone != NULL)
		uma_zdestroy(be_lun->lun_zone);
	nvlist_destroy(cbe_lun->options);
	mtx_destroy(&be_lun->queue_lock);
	mtx_destroy(&be_lun->io_lock);
	free(be_lun, M_CTLBLK);

	return (retval);
}

static int
ctl_be_block_rm(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
{
	struct ctl_lun_rm_params *params;
	struct ctl_be_block_lun *be_lun;
	struct ctl_be_lun *cbe_lun;
	int retval;

	params = &req->reqdata.rm;

	mtx_lock(&softc->lock);
	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
		if (be_lun->cbe_lun.lun_id == params->lun_id)
			break;
	}
	mtx_unlock(&softc->lock);
	if (be_lun == NULL) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "LUN %u is not managed by the block backend",
			 params->lun_id);
		goto bailout_error;
	}
	cbe_lun = &be_lun->cbe_lun;

	retval = ctl_disable_lun(cbe_lun);
	if (retval != 0) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "error %d returned from ctl_disable_lun() for "
			 "LUN %d", retval, params->lun_id);
		goto bailout_error;
	}

	if (be_lun->vn != NULL) {
		cbe_lun->flags |= CTL_LUN_FLAG_NO_MEDIA;
		ctl_lun_no_media(cbe_lun);
		taskqueue_drain_all(be_lun->io_taskqueue);
		ctl_be_block_close(be_lun);
	}

	retval = ctl_invalidate_lun(cbe_lun);
	if (retval != 0) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "error %d returned from ctl_invalidate_lun() for "
			 "LUN %d", retval, params->lun_id);
		goto bailout_error;
	}

	mtx_lock(&softc->lock);
	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
	while ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
                retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
                if (retval == EINTR)
                        break;
        }
	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;

	if ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "interrupted waiting for LUN to be freed");
		mtx_unlock(&softc->lock);
		goto bailout_error;
	}

	STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun, links);

	softc->num_luns--;
	mtx_unlock(&softc->lock);

	taskqueue_drain_all(be_lun->io_taskqueue);
	taskqueue_free(be_lun->io_taskqueue);

	if (be_lun->disk_stats != NULL)
		devstat_remove_entry(be_lun->disk_stats);

	uma_zdestroy(be_lun->lun_zone);

	nvlist_destroy(cbe_lun->options);
	free(be_lun->dev_path, M_CTLBLK);
	mtx_destroy(&be_lun->queue_lock);
	mtx_destroy(&be_lun->io_lock);
	free(be_lun, M_CTLBLK);

	req->status = CTL_LUN_OK;
	return (0);

bailout_error:
	req->status = CTL_LUN_ERROR;
	return (0);
}

static int
ctl_be_block_modify(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
{
	struct ctl_lun_modify_params *params;
	struct ctl_be_block_lun *be_lun;
	struct ctl_be_lun *cbe_lun;
	const char *value;
	uint64_t oldsize;
	int error, wasprim;

	params = &req->reqdata.modify;

	mtx_lock(&softc->lock);
	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
		if (be_lun->cbe_lun.lun_id == params->lun_id)
			break;
	}
	mtx_unlock(&softc->lock);
	if (be_lun == NULL) {
		snprintf(req->error_str, sizeof(req->error_str),
			 "LUN %u is not managed by the block backend",
			 params->lun_id);
		goto bailout_error;
	}
	cbe_lun = &be_lun->cbe_lun;

	if (params->lun_size_bytes != 0)
		be_lun->params.lun_size_bytes = params->lun_size_bytes;

	nvlist_destroy(cbe_lun->options);
	cbe_lun->options = nvlist_clone(req->args_nvl);

	wasprim = (cbe_lun->flags & CTL_LUN_FLAG_PRIMARY);
	value = dnvlist_get_string(cbe_lun->options, "ha_role", NULL);
	if (value != NULL) {
		if (strcmp(value, "primary") == 0)
			cbe_lun->flags |= CTL_LUN_FLAG_PRIMARY;
		else
			cbe_lun->flags &= ~CTL_LUN_FLAG_PRIMARY;
	} else if (control_softc->flags & CTL_FLAG_ACTIVE_SHELF)
		cbe_lun->flags |= CTL_LUN_FLAG_PRIMARY;
	else
		cbe_lun->flags &= ~CTL_LUN_FLAG_PRIMARY;
	if (wasprim != (cbe_lun->flags & CTL_LUN_FLAG_PRIMARY)) {
		if (cbe_lun->flags & CTL_LUN_FLAG_PRIMARY)
			ctl_lun_primary(cbe_lun);
		else
			ctl_lun_secondary(cbe_lun);
	}

	oldsize = be_lun->size_blocks;
	if ((cbe_lun->flags & CTL_LUN_FLAG_PRIMARY) ||
	    control_softc->ha_mode == CTL_HA_MODE_SER_ONLY) {
		if (be_lun->vn == NULL)
			error = ctl_be_block_open(be_lun, req);
		else if (vn_isdisk(be_lun->vn, &error))
			error = ctl_be_block_open_dev(be_lun, req);
		else if (be_lun->vn->v_type == VREG) {
			vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
			error = ctl_be_block_open_file(be_lun, req);
			VOP_UNLOCK(be_lun->vn, 0);
		} else
			error = EINVAL;
		if ((cbe_lun->flags & CTL_LUN_FLAG_NO_MEDIA) &&
		    be_lun->vn != NULL) {
			cbe_lun->flags &= ~CTL_LUN_FLAG_NO_MEDIA;
			ctl_lun_has_media(cbe_lun);
		} else if ((cbe_lun->flags & CTL_LUN_FLAG_NO_MEDIA) == 0 &&
		    be_lun->vn == NULL) {
			cbe_lun->flags |= CTL_LUN_FLAG_NO_MEDIA;
			ctl_lun_no_media(cbe_lun);
		}
		cbe_lun->flags &= ~CTL_LUN_FLAG_EJECTED;
	} else {
		if (be_lun->vn != NULL) {
			cbe_lun->flags |= CTL_LUN_FLAG_NO_MEDIA;
			ctl_lun_no_media(cbe_lun);
			taskqueue_drain_all(be_lun->io_taskqueue);
			error = ctl_be_block_close(be_lun);
		} else
			error = 0;
	}
	if (be_lun->size_blocks != oldsize)
		ctl_lun_capacity_changed(cbe_lun);

	/* Tell the user the exact size we ended up using */
	params->lun_size_bytes = be_lun->size_bytes;

	req->status = error ? CTL_LUN_WARNING : CTL_LUN_OK;
	return (0);

bailout_error:
	req->status = CTL_LUN_ERROR;
	return (0);
}

static void
ctl_be_block_lun_shutdown(void *be_lun)
{
	struct ctl_be_block_lun *lun = be_lun;
	struct ctl_be_block_softc *softc = lun->softc;

	mtx_lock(&softc->lock);
	lun->flags |= CTL_BE_BLOCK_LUN_UNCONFIGURED;
	if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
		wakeup(lun);
	mtx_unlock(&softc->lock);
}

static void
ctl_be_block_lun_config_status(void *be_lun, ctl_lun_config_status status)
{
	struct ctl_be_block_lun *lun;
	struct ctl_be_block_softc *softc;

	lun = (struct ctl_be_block_lun *)be_lun;
	softc = lun->softc;

	if (status == CTL_LUN_CONFIG_OK) {
		mtx_lock(&softc->lock);
		lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
		if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
			wakeup(lun);
		mtx_unlock(&softc->lock);

		/*
		 * We successfully added the LUN, attempt to enable it.
		 */
		if (ctl_enable_lun(&lun->cbe_lun) != 0) {
			printf("%s: ctl_enable_lun() failed!\n", __func__);
			if (ctl_invalidate_lun(&lun->cbe_lun) != 0) {
				printf("%s: ctl_invalidate_lun() failed!\n",
				       __func__);
			}
		}

		return;
	}


	mtx_lock(&softc->lock);
	lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
	lun->flags |= CTL_BE_BLOCK_LUN_CONFIG_ERR;
	wakeup(lun);
	mtx_unlock(&softc->lock);
}


static int
ctl_be_block_config_write(union ctl_io *io)
{
	struct ctl_be_block_lun *be_lun;
	struct ctl_be_lun *cbe_lun;
	int retval;

	DPRINTF("entered\n");

	cbe_lun = CTL_BACKEND_LUN(io);
	be_lun = (struct ctl_be_block_lun *)cbe_lun->be_lun;

	retval = 0;
	switch (io->scsiio.cdb[0]) {
	case SYNCHRONIZE_CACHE:
	case SYNCHRONIZE_CACHE_16:
	case WRITE_SAME_10:
	case WRITE_SAME_16:
	case UNMAP:
		/*
		 * The upper level CTL code will filter out any CDBs with
		 * the immediate bit set and return the proper error.
		 *
		 * We don't really need to worry about what LBA range the
		 * user asked to be synced out.  When they issue a sync
		 * cache command, we'll sync out the whole thing.
		 */
		mtx_lock(&be_lun->queue_lock);
		STAILQ_INSERT_TAIL(&be_lun->config_write_queue, &io->io_hdr,
				   links);
		mtx_unlock(&be_lun->queue_lock);
		taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
		break;
	case START_STOP_UNIT: {
		struct scsi_start_stop_unit *cdb;
		struct ctl_lun_req req;

		cdb = (struct scsi_start_stop_unit *)io->scsiio.cdb;
		if ((cdb->how & SSS_PC_MASK) != 0) {
			ctl_set_success(&io->scsiio);
			ctl_config_write_done(io);
			break;
		}
		if (cdb->how & SSS_START) {
			if ((cdb->how & SSS_LOEJ) && be_lun->vn == NULL) {
				retval = ctl_be_block_open(be_lun, &req);
				cbe_lun->flags &= ~CTL_LUN_FLAG_EJECTED;
				if (retval == 0) {
					cbe_lun->flags &= ~CTL_LUN_FLAG_NO_MEDIA;
					ctl_lun_has_media(cbe_lun);
				} else {
					cbe_lun->flags |= CTL_LUN_FLAG_NO_MEDIA;
					ctl_lun_no_media(cbe_lun);
				}
			}
			ctl_start_lun(cbe_lun);
		} else {
			ctl_stop_lun(cbe_lun);
			if (cdb->how & SSS_LOEJ) {
				cbe_lun->flags |= CTL_LUN_FLAG_NO_MEDIA;
				cbe_lun->flags |= CTL_LUN_FLAG_EJECTED;
				ctl_lun_ejected(cbe_lun);
				if (be_lun->vn != NULL)
					ctl_be_block_close(be_lun);
			}
		}

		ctl_set_success(&io->scsiio);
		ctl_config_write_done(io);
		break;
	}
	case PREVENT_ALLOW:
		ctl_set_success(&io->scsiio);
		ctl_config_write_done(io);
		break;
	default:
		ctl_set_invalid_opcode(&io->scsiio);
		ctl_config_write_done(io);
		retval = CTL_RETVAL_COMPLETE;
		break;
	}

	return (retval);
}

static int
ctl_be_block_config_read(union ctl_io *io)
{
	struct ctl_be_block_lun *be_lun;
	struct ctl_be_lun *cbe_lun;
	int retval = 0;

	DPRINTF("entered\n");

	cbe_lun = CTL_BACKEND_LUN(io);
	be_lun = (struct ctl_be_block_lun *)cbe_lun->be_lun;

	switch (io->scsiio.cdb[0]) {
	case SERVICE_ACTION_IN:
		if (io->scsiio.cdb[1] == SGLS_SERVICE_ACTION) {
			mtx_lock(&be_lun->queue_lock);
			STAILQ_INSERT_TAIL(&be_lun->config_read_queue,
			    &io->io_hdr, links);
			mtx_unlock(&be_lun->queue_lock);
			taskqueue_enqueue(be_lun->io_taskqueue,
			    &be_lun->io_task);
			retval = CTL_RETVAL_QUEUED;
			break;
		}
		ctl_set_invalid_field(&io->scsiio,
				      /*sks_valid*/ 1,
				      /*command*/ 1,
				      /*field*/ 1,
				      /*bit_valid*/ 1,
				      /*bit*/ 4);
		ctl_config_read_done(io);
		retval = CTL_RETVAL_COMPLETE;
		break;
	default:
		ctl_set_invalid_opcode(&io->scsiio);
		ctl_config_read_done(io);
		retval = CTL_RETVAL_COMPLETE;
		break;
	}

	return (retval);
}

static int
ctl_be_block_lun_info(void *be_lun, struct sbuf *sb)
{
	struct ctl_be_block_lun *lun;
	int retval;

	lun = (struct ctl_be_block_lun *)be_lun;

	retval = sbuf_printf(sb, "\t<num_threads>");
	if (retval != 0)
		goto bailout;
	retval = sbuf_printf(sb, "%d", lun->num_threads);
	if (retval != 0)
		goto bailout;
	retval = sbuf_printf(sb, "</num_threads>\n");

bailout:
	return (retval);
}

static uint64_t
ctl_be_block_lun_attr(void *be_lun, const char *attrname)
{
	struct ctl_be_block_lun *lun = (struct ctl_be_block_lun *)be_lun;

	if (lun->getattr == NULL)
		return (UINT64_MAX);
	return (lun->getattr(lun, attrname));
}

static int
ctl_be_block_init(void)
{
	struct ctl_be_block_softc *softc = &backend_block_softc;

	mtx_init(&softc->lock, "ctlblock", NULL, MTX_DEF);
	softc->beio_zone = uma_zcreate("beio", sizeof(struct ctl_be_block_io),
	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
	STAILQ_INIT(&softc->lun_list);
	return (0);
}


static int
ctl_be_block_shutdown(void)
{
	struct ctl_be_block_softc *softc = &backend_block_softc;
	struct ctl_be_block_lun *lun, *next_lun;

	mtx_lock(&softc->lock);
	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun) {
		/*
		 * Drop our lock here.  Since ctl_invalidate_lun() can call
		 * back into us, this could potentially lead to a recursive
		 * lock of the same mutex, which would cause a hang.
		 */
		mtx_unlock(&softc->lock);
		ctl_disable_lun(&lun->cbe_lun);
		ctl_invalidate_lun(&lun->cbe_lun);
		mtx_lock(&softc->lock);
	}
	mtx_unlock(&softc->lock);

	uma_zdestroy(softc->beio_zone);
	mtx_destroy(&softc->lock);
	return (0);
}