aboutsummaryrefslogtreecommitdiff
path: root/sys/cam/scsi/scsi_enc_ses.c
blob: e122e0d0e0d9a1ba9fe65444c350881e30142c23 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2000 Matthew Jacob
 * Copyright (c) 2010 Spectra Logic Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification, immediately at the beginning of the file.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/**
 * \file scsi_enc_ses.c
 *
 * Structures and routines specific && private to SES only
 */

#include <sys/param.h>

#include <sys/ctype.h>
#include <sys/errno.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/mutex.h>
#include <sys/queue.h>
#include <sys/sbuf.h>
#include <sys/sx.h>
#include <sys/systm.h>
#include <sys/types.h>

#include <cam/cam.h>
#include <cam/cam_ccb.h>
#include <cam/cam_xpt_periph.h>
#include <cam/cam_periph.h>

#include <cam/scsi/scsi_message.h>
#include <cam/scsi/scsi_enc.h>
#include <cam/scsi/scsi_enc_internal.h>

/* SES Native Type Device Support */

/* SES Diagnostic Page Codes */
typedef enum {
	SesSupportedPages	= 0x0,
	SesConfigPage		= 0x1,
	SesControlPage		= 0x2,
	SesStatusPage		= SesControlPage,
	SesHelpTxt		= 0x3,
	SesStringOut		= 0x4,
	SesStringIn		= SesStringOut,
	SesThresholdOut		= 0x5,
	SesThresholdIn		= SesThresholdOut,
	SesArrayControl		= 0x6,	/* Obsolete in SES v2 */
	SesArrayStatus		= SesArrayControl,
	SesElementDescriptor	= 0x7,
	SesShortStatus		= 0x8,
	SesEnclosureBusy	= 0x9,
	SesAddlElementStatus	= 0xa
} SesDiagPageCodes;

typedef struct ses_type {
	const struct ses_elm_type_desc  *hdr;
	const char			*text;
} ses_type_t;

typedef struct ses_comstat {
	uint8_t	comstatus;
	uint8_t	comstat[3];
} ses_comstat_t;

typedef union ses_addl_data {
	struct ses_elm_sas_device_phy *sasdev_phys;
	struct ses_elm_sas_expander_phy *sasexp_phys;
	struct ses_elm_sas_port_phy *sasport_phys;
	struct ses_fcobj_port *fc_ports;
} ses_add_data_t;

typedef struct ses_addl_status {
	struct ses_elm_addlstatus_base_hdr *hdr;
	union {
		union ses_fcobj_hdr *fc;
		union ses_elm_sas_hdr *sas;
		struct ses_elm_ata_hdr *ata;
	} proto_hdr;
	union ses_addl_data proto_data;	/* array sizes stored in header */
} ses_add_status_t;

typedef struct ses_element {
	uint8_t eip;			/* eip bit is set */
	uint16_t descr_len;		/* length of the descriptor */
	const char *descr;		/* descriptor for this object */
	struct ses_addl_status addl;	/* additional status info */
} ses_element_t;

typedef struct ses_control_request {
	int	      elm_idx;
	ses_comstat_t elm_stat;
	int	      result;
	TAILQ_ENTRY(ses_control_request) links;
} ses_control_request_t;
TAILQ_HEAD(ses_control_reqlist, ses_control_request);
typedef struct ses_control_reqlist ses_control_reqlist_t;
enum {
	SES_SETSTATUS_ENC_IDX = -1
};

static void
ses_terminate_control_requests(ses_control_reqlist_t *reqlist, int result)
{
	ses_control_request_t *req;

	while ((req = TAILQ_FIRST(reqlist)) != NULL) {
		TAILQ_REMOVE(reqlist, req, links);
		req->result = result;
		wakeup(req);
	}
}

enum ses_iter_index_values {
	/**
	 * \brief  Value of an initialized but invalid index
	 *         in a ses_iterator object.
	 *
	 * This value is used for the  individual_element_index of
	 * overal status elements and for all index types when
	 * an iterator is first initialized.
	 */
	ITERATOR_INDEX_INVALID = -1,

	/**
	 * \brief  Value of an index in a ses_iterator object
	 *	   when the iterator has traversed past the last
	 *	   valid element..
	 */
	ITERATOR_INDEX_END     = INT_MAX
};

/**
 * \brief Structure encapsulating all data necessary to traverse the
 *        elements of a SES configuration.
 *
 * The ses_iterator object simplifies the task of iterating through all
 * elements detected via the SES configuration page by tracking the numerous
 * element indexes that, instead of memoizing in the softc, we calculate
 * on the fly during the traversal of the element objects.  The various
 * indexes are necessary due to the varying needs of matching objects in
 * the different SES pages.  Some pages (e.g. Status/Control) contain all
 * elements, while others (e.g. Additional Element Status) only contain
 * individual elements (no overal status elements) of particular types.
 *
 * To use an iterator, initialize it with ses_iter_init(), and then
 * use ses_iter_next() to traverse the elements (including the first) in
 * the configuration.  Once an iterator is initiailized with ses_iter_init(),
 * you may also seek to any particular element by either it's global or
 * individual element index via the ses_iter_seek_to() function.  You may
 * also return an iterator to the position just before the first element
 * (i.e. the same state as after an ses_iter_init()), with ses_iter_reset().
 */
struct ses_iterator {
	/**
	 * \brief Backlink to the overal software configuration structure.
	 *
	 * This is included for convenience so the iteration functions
	 * need only take a single, struct ses_iterator *, argument.
	 */
	enc_softc_t *enc;

	enc_cache_t *cache;

	/**
	 * \brief Index of the type of the current element within the
	 *        ses_cache's ses_types array.
	 */
	int	          type_index;

	/**
	 * \brief The position (0 based) of this element relative to all other
	 *        elements of this type.
	 *
	 * This index resets to zero every time the iterator transitions
	 * to elements of a new type in the configuration.
	 */
	int	          type_element_index;

	/**
	 * \brief The position (0 based) of this element relative to all
	 *        other individual status elements in the configuration.
	 *
	 * This index ranges from 0 through the number of individual
	 * elements in the configuration.  When the iterator returns
	 * an overall status element, individual_element_index is
	 * set to ITERATOR_INDEX_INVALID, to indicate that it does
	 * not apply to the current element.
	 */
	int	          individual_element_index;

	/**
	 * \brief The position (0 based) of this element relative to
	 *        all elements in the configration.
	 *
	 * This index is appropriate for indexing into enc->ses_elm_map.
	 */
	int	          global_element_index;

	/**
	 * \brief The last valid individual element index of this
	 *        iterator.
	 *
	 * When an iterator traverses an overal status element, the
	 * individual element index is reset to ITERATOR_INDEX_INVALID
	 * to prevent unintential use of the individual_element_index
	 * field.  The saved_individual_element_index allows the iterator
	 * to restore it's position in the individual elements upon
	 * reaching the next individual element.
	 */
	int	          saved_individual_element_index;
};

typedef enum {
	SES_UPDATE_NONE,
	SES_UPDATE_PAGES,
	SES_UPDATE_GETCONFIG,
	SES_UPDATE_GETSTATUS,
	SES_UPDATE_GETELMDESCS,
	SES_UPDATE_GETELMADDLSTATUS,
	SES_PROCESS_CONTROL_REQS,
	SES_PUBLISH_PHYSPATHS,
	SES_PUBLISH_CACHE,
	SES_NUM_UPDATE_STATES
} ses_update_action;

static enc_softc_cleanup_t ses_softc_cleanup;

#define	SCSZ	0x8000

static fsm_fill_handler_t ses_fill_rcv_diag_io;
static fsm_fill_handler_t ses_fill_control_request;
static fsm_done_handler_t ses_process_pages;
static fsm_done_handler_t ses_process_config;
static fsm_done_handler_t ses_process_status;
static fsm_done_handler_t ses_process_elm_descs;
static fsm_done_handler_t ses_process_elm_addlstatus;
static fsm_done_handler_t ses_process_control_request;
static fsm_done_handler_t ses_publish_physpaths;
static fsm_done_handler_t ses_publish_cache;

static struct enc_fsm_state enc_fsm_states[SES_NUM_UPDATE_STATES] =
{
	{ "SES_UPDATE_NONE", 0, 0, 0, NULL, NULL, NULL },
	{
		"SES_UPDATE_PAGES",
		SesSupportedPages,
		SCSZ,
		60 * 1000,
		ses_fill_rcv_diag_io,
		ses_process_pages,
		enc_error
	},
	{
		"SES_UPDATE_GETCONFIG",
		SesConfigPage,
		SCSZ,
		60 * 1000,
		ses_fill_rcv_diag_io,
		ses_process_config,
		enc_error
	},
	{
		"SES_UPDATE_GETSTATUS",
		SesStatusPage,
		SCSZ,
		60 * 1000,
		ses_fill_rcv_diag_io,
		ses_process_status,
		enc_error
	},
	{
		"SES_UPDATE_GETELMDESCS",
		SesElementDescriptor,
		SCSZ,
		60 * 1000,
		ses_fill_rcv_diag_io,
		ses_process_elm_descs,
		enc_error
	},
	{
		"SES_UPDATE_GETELMADDLSTATUS",
		SesAddlElementStatus,
		SCSZ,
		60 * 1000,
		ses_fill_rcv_diag_io,
		ses_process_elm_addlstatus,
		enc_error
	},
	{
		"SES_PROCESS_CONTROL_REQS",
		SesControlPage,
		SCSZ,
		60 * 1000,
		ses_fill_control_request,
		ses_process_control_request,
		enc_error
	},
	{
		"SES_PUBLISH_PHYSPATHS",
		0,
		0,
		0,
		NULL,
		ses_publish_physpaths,
		NULL
	},
	{
		"SES_PUBLISH_CACHE",
		0,
		0,
		0,
		NULL,
		ses_publish_cache,
		NULL
	}
};

typedef struct ses_cache {
	/* Source for all the configuration data pointers */
	const struct ses_cfg_page		*cfg_page;

	/* References into the config page. */
	int					 ses_nsubencs;
	const struct ses_enc_desc * const	*subencs;
	int					 ses_ntypes;
	const ses_type_t			*ses_types;

	/* Source for all the status pointers */
	const struct ses_status_page		*status_page;

	/* Source for all the object descriptor pointers */
	const struct ses_elem_descr_page	*elm_descs_page;

	/* Source for all the additional object status pointers */
	const struct ses_addl_elem_status_page  *elm_addlstatus_page;

} ses_cache_t;

typedef struct ses_softc {
	uint32_t		ses_flags;
#define	SES_FLAG_TIMEDCOMP	0x01
#define	SES_FLAG_ADDLSTATUS	0x02
#define	SES_FLAG_DESC		0x04

	ses_control_reqlist_t	ses_requests;
	ses_control_reqlist_t	ses_pending_requests;
} ses_softc_t;

static int ses_search_globally = 0;
SYSCTL_INT(_kern_cam_enc, OID_AUTO, search_globally, CTLFLAG_RWTUN,
           &ses_search_globally, 0, "Search for disks on other buses");

/**
 * \brief Reset a SES iterator to just before the first element
 *        in the configuration.
 *
 * \param iter  The iterator object to reset.
 *
 * The indexes within a reset iterator are invalid and will only
 * become valid upon completion of a ses_iter_seek_to() or a
 * ses_iter_next().
 */
static void
ses_iter_reset(struct ses_iterator *iter)
{
	/*
	 * Set our indexes to just before the first valid element
	 * of the first type (ITERATOR_INDEX_INVALID == -1).  This
	 * simplifies the implementation of ses_iter_next().
	 */
	iter->type_index                     = 0;
	iter->type_element_index             = ITERATOR_INDEX_INVALID;
	iter->global_element_index           = ITERATOR_INDEX_INVALID;
	iter->individual_element_index       = ITERATOR_INDEX_INVALID;
	iter->saved_individual_element_index = ITERATOR_INDEX_INVALID;
}

/**
 * \brief Initialize the storage of a SES iterator and reset it to
 *        the position just before the first element of the
 *        configuration.
 *
 * \param enc	The SES softc for the SES instance whose configuration
 *              will be enumerated by this iterator.
 * \param iter  The iterator object to initialize.
 */
static void
ses_iter_init(enc_softc_t *enc, enc_cache_t *cache, struct ses_iterator *iter)
{
	iter->enc = enc;
	iter->cache = cache;
	ses_iter_reset(iter);
}

/**
 * \brief Traverse the provided SES iterator to the next element
 *        within the configuration.
 *
 * \param iter  The iterator to move.
 *
 * \return  If a valid next element exists, a pointer to it's enc_element_t.
 *          Otherwise NULL.
 */
static enc_element_t *
ses_iter_next(struct ses_iterator *iter)
{
	ses_cache_t	 *ses_cache;
	const ses_type_t *element_type;

	ses_cache = iter->cache->private;

	/*
	 * Note: Treat nelms as signed, so we will hit this case
	 *       and immediately terminate the iteration if the
	 *	 configuration has 0 objects.
	 */
	if (iter->global_element_index >= (int)iter->cache->nelms - 1) {
		/* Elements exhausted. */
		iter->type_index	       = ITERATOR_INDEX_END;
		iter->type_element_index       = ITERATOR_INDEX_END;
		iter->global_element_index     = ITERATOR_INDEX_END;
		iter->individual_element_index = ITERATOR_INDEX_END;
		iter->saved_individual_element_index = ITERATOR_INDEX_END;
		return (NULL);
	}

	KASSERT((iter->type_index < ses_cache->ses_ntypes),
		("Corrupted element iterator. %d not less than %d",
		 iter->type_index, ses_cache->ses_ntypes));

	element_type = &ses_cache->ses_types[iter->type_index];
	iter->global_element_index++;
	iter->type_element_index++;

	/*
	 * There is an object for overal type status in addition
	 * to one for each allowed element, but only if the element
	 * count is non-zero.
	 */
	if (iter->type_element_index > element_type->hdr->etype_maxelt) {
		/*
		 * We've exhausted the elements of this type.
		 * This next element belongs to the next type.
		 */
		iter->type_index++;
		iter->type_element_index = 0;
		iter->individual_element_index = ITERATOR_INDEX_INVALID;
	}

	if (iter->type_element_index > 0) {
		iter->individual_element_index =
		    ++iter->saved_individual_element_index;
	}

	return (&iter->cache->elm_map[iter->global_element_index]);
}

/**
 * Element index types tracked by a SES iterator.
 */
typedef enum {
	/**
	 * Index relative to all elements (overall and individual)
	 * in the system.
	 */
	SES_ELEM_INDEX_GLOBAL,

	/**
	 * \brief Index relative to all individual elements in the system.
	 *
	 * This index counts only individual elements, skipping overall
	 * status elements.  This is the index space of the additional
	 * element status page (page 0xa).
	 */
	SES_ELEM_INDEX_INDIVIDUAL
} ses_elem_index_type_t;

/**
 * \brief Move the provided iterator forwards or backwards to the object 
 *        having the give index.
 *
 * \param iter           The iterator on which to perform the seek.
 * \param element_index  The index of the element to find.
 * \param index_type     The type (global or individual) of element_index.
 *
 * \return  If the element is found, a pointer to it's enc_element_t.
 *          Otherwise NULL.
 */
static enc_element_t *
ses_iter_seek_to(struct ses_iterator *iter, int element_index,
		 ses_elem_index_type_t index_type)
{
	enc_element_t	*element;
	int		*cur_index;

	if (index_type == SES_ELEM_INDEX_GLOBAL)
		cur_index = &iter->global_element_index;
	else
		cur_index = &iter->individual_element_index;

	if (*cur_index == element_index) {
		/* Already there. */
		return (&iter->cache->elm_map[iter->global_element_index]);
	}

	ses_iter_reset(iter);
	while ((element = ses_iter_next(iter)) != NULL
	    && *cur_index != element_index)
		;

	if (*cur_index != element_index)
		return (NULL);

	return (element);
}

#if 0
static int ses_encode(enc_softc_t *, uint8_t *, int, int,
    struct ses_comstat *);
#endif
static int ses_set_timed_completion(enc_softc_t *, uint8_t);
#if 0
static int ses_putstatus(enc_softc_t *, int, struct ses_comstat *);
#endif

static void ses_poll_status(enc_softc_t *);
static void ses_print_addl_data(enc_softc_t *, enc_element_t *);

/*=========================== SES cleanup routines ===========================*/

static void
ses_cache_free_elm_addlstatus(enc_softc_t *enc, enc_cache_t *cache)
{
	ses_cache_t   *ses_cache;
	ses_cache_t   *other_ses_cache;
	enc_element_t *cur_elm;
	enc_element_t *last_elm;

	ENC_DLOG(enc, "%s: enter\n", __func__);
	ses_cache = cache->private;
	if (ses_cache->elm_addlstatus_page == NULL)
		return;

	for (cur_elm = cache->elm_map,
	     last_elm = &cache->elm_map[cache->nelms];
	     cur_elm != last_elm; cur_elm++) {
		ses_element_t *elmpriv;

		elmpriv = cur_elm->elm_private;

		/* Clear references to the additional status page. */
		bzero(&elmpriv->addl, sizeof(elmpriv->addl));
	}

	other_ses_cache = enc_other_cache(enc, cache)->private;
	if (other_ses_cache->elm_addlstatus_page
	 != ses_cache->elm_addlstatus_page)
		ENC_FREE(ses_cache->elm_addlstatus_page);
	ses_cache->elm_addlstatus_page = NULL;
}

static void
ses_cache_free_elm_descs(enc_softc_t *enc, enc_cache_t *cache)
{
	ses_cache_t   *ses_cache;
	ses_cache_t   *other_ses_cache;
	enc_element_t *cur_elm;
	enc_element_t *last_elm;

	ENC_DLOG(enc, "%s: enter\n", __func__);
	ses_cache = cache->private;
	if (ses_cache->elm_descs_page == NULL)
		return;

	for (cur_elm = cache->elm_map,
	     last_elm = &cache->elm_map[cache->nelms];
	     cur_elm != last_elm; cur_elm++) {
		ses_element_t *elmpriv;

		elmpriv = cur_elm->elm_private;
		elmpriv->descr_len = 0;
		elmpriv->descr = NULL;
	}

	other_ses_cache = enc_other_cache(enc, cache)->private;
	if (other_ses_cache->elm_descs_page
	 != ses_cache->elm_descs_page)
		ENC_FREE(ses_cache->elm_descs_page);
	ses_cache->elm_descs_page = NULL;
}

static void
ses_cache_free_status(enc_softc_t *enc, enc_cache_t *cache)
{
	ses_cache_t *ses_cache;
	ses_cache_t *other_ses_cache;

	ENC_DLOG(enc, "%s: enter\n", __func__);
	ses_cache   = cache->private;
	if (ses_cache->status_page == NULL)
		return;

	other_ses_cache = enc_other_cache(enc, cache)->private;
	if (other_ses_cache->status_page != ses_cache->status_page)
		ENC_FREE(ses_cache->status_page);
	ses_cache->status_page = NULL;
}

static void
ses_cache_free_elm_map(enc_softc_t *enc, enc_cache_t *cache)
{
	enc_element_t *cur_elm;
	enc_element_t *last_elm;

	ENC_DLOG(enc, "%s: enter\n", __func__);
	if (cache->elm_map == NULL)
		return;

	ses_cache_free_elm_descs(enc, cache);
	ses_cache_free_elm_addlstatus(enc, cache);
	for (cur_elm = cache->elm_map,
	     last_elm = &cache->elm_map[cache->nelms];
	     cur_elm != last_elm; cur_elm++) {
		ENC_FREE_AND_NULL(cur_elm->elm_private);
	}
	ENC_FREE_AND_NULL(cache->elm_map);
	cache->nelms = 0;
	ENC_DLOG(enc, "%s: exit\n", __func__);
}

static void
ses_cache_free(enc_softc_t *enc, enc_cache_t *cache)
{
	ses_cache_t *other_ses_cache;
	ses_cache_t *ses_cache;

	ENC_DLOG(enc, "%s: enter\n", __func__);
	ses_cache_free_elm_addlstatus(enc, cache);
	ses_cache_free_status(enc, cache);
	ses_cache_free_elm_map(enc, cache);

	ses_cache = cache->private;
	ses_cache->ses_ntypes = 0;

	other_ses_cache = enc_other_cache(enc, cache)->private;
	if (other_ses_cache->subencs != ses_cache->subencs)
		ENC_FREE(ses_cache->subencs);
	ses_cache->subencs = NULL;

	if (other_ses_cache->ses_types != ses_cache->ses_types)
		ENC_FREE(ses_cache->ses_types);
	ses_cache->ses_types = NULL;

	if (other_ses_cache->cfg_page != ses_cache->cfg_page)
		ENC_FREE(ses_cache->cfg_page);
	ses_cache->cfg_page = NULL;

	ENC_DLOG(enc, "%s: exit\n", __func__);
}

static void
ses_cache_clone(enc_softc_t *enc, enc_cache_t *src, enc_cache_t *dst)
{
	ses_cache_t   *dst_ses_cache;
	ses_cache_t   *src_ses_cache;
	enc_element_t *src_elm;
	enc_element_t *dst_elm;
	enc_element_t *last_elm;

	ses_cache_free(enc, dst);
	src_ses_cache = src->private;
	dst_ses_cache = dst->private;

	/*
	 * The cloned enclosure cache and ses specific cache are
	 * mostly identical to the source.
	 */
	*dst = *src;
	*dst_ses_cache = *src_ses_cache;

	/*
	 * But the ses cache storage is still independent.  Restore
	 * the pointer that was clobbered by the structure copy above.
	 */
	dst->private = dst_ses_cache;

	/*
	 * The element map is independent even though it starts out
	 * pointing to the same constant page data.
	 */
	dst->elm_map = malloc(dst->nelms * sizeof(enc_element_t),
	    M_SCSIENC, M_WAITOK);
	memcpy(dst->elm_map, src->elm_map, dst->nelms * sizeof(enc_element_t));
	for (dst_elm = dst->elm_map, src_elm = src->elm_map,
	     last_elm = &src->elm_map[src->nelms];
	     src_elm != last_elm; src_elm++, dst_elm++) {
		dst_elm->elm_private = malloc(sizeof(ses_element_t),
		    M_SCSIENC, M_WAITOK);
		memcpy(dst_elm->elm_private, src_elm->elm_private,
		       sizeof(ses_element_t));
	}
}

/* Structure accessors.  These are strongly typed to avoid errors. */

int
ses_elm_sas_descr_type(union ses_elm_sas_hdr *obj)
{
	return ((obj)->base_hdr.byte1 >> 6);
}
int
ses_elm_addlstatus_proto(struct ses_elm_addlstatus_base_hdr *hdr)
{
	return ((hdr)->byte0 & 0xf);
}
int
ses_elm_addlstatus_eip(struct ses_elm_addlstatus_base_hdr *hdr)
{
	return ((hdr)->byte0 >> 4 & 0x1);
}
int
ses_elm_addlstatus_invalid(struct ses_elm_addlstatus_base_hdr *hdr)
{
	return ((hdr)->byte0 >> 7);
}
int
ses_elm_sas_type0_not_all_phys(union ses_elm_sas_hdr *hdr)
{
	return ((hdr)->type0_noneip.byte1 & 0x1);
}
int
ses_elm_sas_dev_phy_sata_dev(struct ses_elm_sas_device_phy *phy)
{
	return ((phy)->target_ports & 0x1);
}
int
ses_elm_sas_dev_phy_sata_port(struct ses_elm_sas_device_phy *phy)
{
	return ((phy)->target_ports >> 7);
}
int
ses_elm_sas_dev_phy_dev_type(struct ses_elm_sas_device_phy *phy)
{
	return (((phy)->byte0 >> 4) & 0x7);
}

/**
 * \brief Verify that the cached configuration data in our softc
 *        is valid for processing the page data corresponding to
 *        the provided page header.
 *
 * \param ses_cache The SES cache to validate.
 * \param gen_code  The 4 byte generation code from a SES diagnostic
 *		    page header.
 *
 * \return  non-zero if true, 0 if false.
 */
static int
ses_config_cache_valid(ses_cache_t *ses_cache, const uint8_t *gen_code)
{
	uint32_t cache_gc;
	uint32_t cur_gc;

	if (ses_cache->cfg_page == NULL)
		return (0);

	cache_gc = scsi_4btoul(ses_cache->cfg_page->hdr.gen_code);
	cur_gc   = scsi_4btoul(gen_code);
	return (cache_gc == cur_gc);
}

/**
 * Function signature for consumers of the ses_devids_iter() interface.
 */
typedef void ses_devid_callback_t(enc_softc_t *, enc_element_t *,
				  struct scsi_vpd_id_descriptor *, void *);

/**
 * \brief Iterate over and create vpd device id records from the
 *        additional element status data for elm, passing that data
 *        to the provided callback.
 *
 * \param enc	        SES instance containing elm
 * \param elm	        Element for which to extract device ID data.
 * \param callback      The callback function to invoke on each generated
 *                      device id descriptor for elm.
 * \param callback_arg  Argument passed through to callback on each invocation.
 */
static void
ses_devids_iter(enc_softc_t *enc, enc_element_t *elm,
		ses_devid_callback_t *callback, void *callback_arg)
{
	ses_element_t           *elmpriv;
	struct ses_addl_status *addl;
	u_int                   i;
	size_t			devid_record_size;

	elmpriv = elm->elm_private;
	addl = &(elmpriv->addl);

	devid_record_size = SVPD_DEVICE_ID_DESC_HDR_LEN
			  + sizeof(struct scsi_vpd_id_naa_ieee_reg);
	for (i = 0; i < addl->proto_hdr.sas->base_hdr.num_phys; i++) {
		uint8_t			       devid_buf[devid_record_size];
		struct scsi_vpd_id_descriptor *devid;
		uint8_t			      *phy_addr;

		devid = (struct scsi_vpd_id_descriptor *)devid_buf;
		phy_addr = addl->proto_data.sasdev_phys[i].phy_addr;
		devid->proto_codeset = (SCSI_PROTO_SAS << SVPD_ID_PROTO_SHIFT)
				     | SVPD_ID_CODESET_BINARY;
		devid->id_type       = SVPD_ID_PIV
				     | SVPD_ID_ASSOC_PORT
				     | SVPD_ID_TYPE_NAA;
		devid->reserved	     = 0;
		devid->length	     = sizeof(struct scsi_vpd_id_naa_ieee_reg);
		memcpy(devid->identifier, phy_addr, devid->length);

		callback(enc, elm, devid, callback_arg);
	}
}

/**
 * Function signature for consumers of the ses_paths_iter() interface.
 */
typedef void ses_path_callback_t(enc_softc_t *, enc_element_t *,
				 struct cam_path *, void *);

/**
 * Argument package passed through ses_devids_iter() by
 * ses_paths_iter() to ses_path_iter_devid_callback().
 */
typedef struct ses_path_iter_args {
	ses_path_callback_t *callback;
	void		    *callback_arg;
} ses_path_iter_args_t;

/**
 * ses_devids_iter() callback function used by ses_paths_iter()
 * to map device ids to peripheral driver instances.
 *
 * \param enc	  SES instance containing elm
 * \param elm	  Element on which device ID matching is active.
 * \param periph  A device ID corresponding to elm.
 * \param arg     Argument passed through to callback on each invocation.
 */
static void
ses_path_iter_devid_callback(enc_softc_t *enc, enc_element_t *elem,
			       struct scsi_vpd_id_descriptor *devid,
			       void *arg)
{
	struct ccb_dev_match         cdm;
	struct dev_match_pattern     match_pattern;
	struct dev_match_result      match_result;
	struct device_match_result  *device_match;
	struct device_match_pattern *device_pattern;
	ses_path_iter_args_t	    *args;
	struct cam_path		    *path;

	args = (ses_path_iter_args_t *)arg;
	match_pattern.type = DEV_MATCH_DEVICE;
	device_pattern = &match_pattern.pattern.device_pattern;
	device_pattern->flags = DEV_MATCH_DEVID;
	device_pattern->data.devid_pat.id_len = 
	    offsetof(struct scsi_vpd_id_descriptor, identifier)
	  + devid->length;
	memcpy(device_pattern->data.devid_pat.id, devid,
	       device_pattern->data.devid_pat.id_len);
	if (!ses_search_globally) {
		device_pattern->flags |= DEV_MATCH_PATH;
		device_pattern->path_id = xpt_path_path_id(enc->periph->path);
	}

	memset(&cdm, 0, sizeof(cdm));
	if (xpt_create_path(&cdm.ccb_h.path, /*periph*/NULL,
			     CAM_XPT_PATH_ID,
			     CAM_TARGET_WILDCARD,
			     CAM_LUN_WILDCARD) != CAM_REQ_CMP)
		return;

	cdm.ccb_h.func_code = XPT_DEV_MATCH;
	cdm.num_patterns    = 1;
	cdm.patterns        = &match_pattern;
	cdm.pattern_buf_len = sizeof(match_pattern);
	cdm.match_buf_len   = sizeof(match_result);
	cdm.matches         = &match_result;

	do {
		xpt_action((union ccb *)&cdm);

		if ((cdm.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP ||
		    (cdm.status != CAM_DEV_MATCH_LAST &&
		     cdm.status != CAM_DEV_MATCH_MORE) ||
		    cdm.num_matches == 0)
			break;

		device_match = &match_result.result.device_result;
		if (xpt_create_path(&path, /*periph*/NULL,
				    device_match->path_id,
				    device_match->target_id,
				    device_match->target_lun) == CAM_REQ_CMP) {
			args->callback(enc, elem, path, args->callback_arg);

			xpt_free_path(path);
		}
	} while (cdm.status == CAM_DEV_MATCH_MORE);

	xpt_free_path(cdm.ccb_h.path);
}

/**
 * \brief Iterate over and find the matching periph objects for the
 *        specified element.
 *
 * \param enc	        SES instance containing elm
 * \param elm	        Element for which to perform periph object matching.
 * \param callback      The callback function to invoke with each matching
 *                      periph object.
 * \param callback_arg  Argument passed through to callback on each invocation.
 */
static void
ses_paths_iter(enc_softc_t *enc, enc_element_t *elm,
	       ses_path_callback_t *callback, void *callback_arg)
{
	ses_element_t *elmpriv;
	struct ses_addl_status *addl;

	elmpriv = elm->elm_private;
	addl = &(elmpriv->addl);

	if (addl->hdr == NULL)
		return;

	switch(ses_elm_addlstatus_proto(addl->hdr)) {
	case SPSP_PROTO_SAS:
		if (addl->proto_hdr.sas != NULL &&
		    addl->proto_data.sasdev_phys != NULL) {
			ses_path_iter_args_t args;

			args.callback     = callback;
			args.callback_arg = callback_arg;
			ses_devids_iter(enc, elm, ses_path_iter_devid_callback,
			    &args);
		}
		break;
	case SPSP_PROTO_ATA:
		if (addl->proto_hdr.ata != NULL) {
			struct cam_path *path;
			struct ccb_getdev cgd;

			if (xpt_create_path(&path, /*periph*/NULL,
			    scsi_4btoul(addl->proto_hdr.ata->bus),
			    scsi_4btoul(addl->proto_hdr.ata->target), 0)
			     != CAM_REQ_CMP)
				return;

			memset(&cgd, 0, sizeof(cgd));
			xpt_setup_ccb(&cgd.ccb_h, path, CAM_PRIORITY_NORMAL);
			cgd.ccb_h.func_code = XPT_GDEV_TYPE;
			xpt_action((union ccb *)&cgd);
			if (cam_ccb_success((union ccb *)&cgd))
				callback(enc, elm, path, callback_arg);

			xpt_free_path(path);
		}
		break;
	}
}

/**
 * ses_paths_iter() callback function used by ses_get_elmdevname()
 * to record periph driver instance strings corresponding to a SES
 * element.
 *
 * \param enc	  SES instance containing elm
 * \param elm	  Element on which periph matching is active.
 * \param periph  A periph instance that matches elm.
 * \param arg     Argument passed through to callback on each invocation.
 */
static void
ses_elmdevname_callback(enc_softc_t *enc, enc_element_t *elem,
			struct cam_path *path, void *arg)
{
	struct sbuf *sb;

	sb = (struct sbuf *)arg;
	cam_periph_list(path, sb);
}

/**
 * Argument package passed through ses_paths_iter() to
 * ses_getcampath_callback.
 */
typedef struct ses_setphyspath_callback_args {
	struct sbuf *physpath;
	int          num_set;
} ses_setphyspath_callback_args_t;

/**
 * \brief ses_paths_iter() callback to set the physical path on the
 *        CAM EDT entries corresponding to a given SES element.
 *
 * \param enc	  SES instance containing elm
 * \param elm	  Element on which periph matching is active.
 * \param periph  A periph instance that matches elm.
 * \param arg     Argument passed through to callback on each invocation.
 */
static void
ses_setphyspath_callback(enc_softc_t *enc, enc_element_t *elm,
			 struct cam_path *path, void *arg)
{
	struct ccb_dev_advinfo cdai;
	ses_setphyspath_callback_args_t *args;
	char *old_physpath;

	args = (ses_setphyspath_callback_args_t *)arg;
	old_physpath = malloc(MAXPATHLEN, M_SCSIENC, M_WAITOK|M_ZERO);
	xpt_path_lock(path);
	memset(&cdai, 0, sizeof(cdai));
	xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
	cdai.buftype = CDAI_TYPE_PHYS_PATH;
	cdai.flags = CDAI_FLAG_NONE;
	cdai.bufsiz = MAXPATHLEN;
	cdai.buf = old_physpath;
	xpt_action((union ccb *)&cdai);
	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);

	if (strcmp(old_physpath, sbuf_data(args->physpath)) != 0) {
		xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
		cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
		cdai.buftype = CDAI_TYPE_PHYS_PATH;
		cdai.flags = CDAI_FLAG_STORE;
		cdai.bufsiz = sbuf_len(args->physpath);
		cdai.buf = sbuf_data(args->physpath);
		xpt_action((union ccb *)&cdai);
		if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
			cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
		if (cam_ccb_success((union ccb *)&cdai))
			args->num_set++;
	}
	xpt_path_unlock(path);
	free(old_physpath, M_SCSIENC);
}

/**
 * \brief Set a device's physical path string in CAM XPT.
 *
 * \param enc	SES instance containing elm
 * \param elm	Element to publish physical path string for
 * \param iter	Iterator whose state corresponds to elm
 *
 * \return	0 on success, errno otherwise.
 */
static int
ses_set_physpath(enc_softc_t *enc, enc_element_t *elm,
		 struct ses_iterator *iter)
{
	struct ccb_dev_advinfo cdai;
	ses_setphyspath_callback_args_t args;
	int i, ret;
	struct sbuf sb;
	struct scsi_vpd_id_descriptor *idd;
	uint8_t *devid;
	ses_element_t *elmpriv;
	const char *c;

	ret = EIO;
	devid = NULL;

	elmpriv = elm->elm_private;
	if (elmpriv->addl.hdr == NULL)
		goto out;

	/*
	 * Assemble the components of the physical path starting with
	 * the device ID of the enclosure itself.
	 */
	memset(&cdai, 0, sizeof(cdai));
	xpt_setup_ccb(&cdai.ccb_h, enc->periph->path, CAM_PRIORITY_NORMAL);
	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
	cdai.flags = CDAI_FLAG_NONE;
	cdai.buftype = CDAI_TYPE_SCSI_DEVID;
	cdai.bufsiz = CAM_SCSI_DEVID_MAXLEN;
	cdai.buf = devid = malloc(cdai.bufsiz, M_SCSIENC, M_WAITOK|M_ZERO);
	cam_periph_lock(enc->periph);
	xpt_action((union ccb *)&cdai);
	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
	cam_periph_unlock(enc->periph);
	if (cdai.ccb_h.status != CAM_REQ_CMP)
		goto out;

	idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
	    cdai.provsiz, scsi_devid_is_naa_ieee_reg);
	if (idd == NULL)
		goto out;

	if (sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND) == NULL) {
		ret = ENOMEM;
		goto out;
	}
	/* Next, generate the physical path string */
	sbuf_printf(&sb, "id1,enc@n%jx/type@%x/slot@%x",
	    scsi_8btou64(idd->identifier), iter->type_index,
	    iter->type_element_index);
	/* Append the element descriptor if one exists */
	if (elmpriv->descr != NULL && elmpriv->descr_len > 0) {
		sbuf_cat(&sb, "/elmdesc@");
		for (i = 0, c = elmpriv->descr; i < elmpriv->descr_len;
		    i++, c++) {
			if (!isprint(*c) || isspace(*c) || *c == '/')
				sbuf_putc(&sb, '_');
			else
				sbuf_putc(&sb, *c);
		}
	}
	sbuf_finish(&sb);

	/*
	 * Set this physical path on any CAM devices with a device ID
	 * descriptor that matches one created from the SES additional
	 * status data for this element.
	 */
	args.physpath= &sb;
	args.num_set = 0;
	ses_paths_iter(enc, elm, ses_setphyspath_callback, &args);
	sbuf_delete(&sb);

	ret = args.num_set == 0 ? ENOENT : 0;

out:
	if (devid != NULL)
		ENC_FREE(devid);
	return (ret);
}

/**
 * \brief Helper to set the CDB fields appropriately.
 *
 * \param cdb		Buffer containing the cdb.
 * \param pagenum	SES diagnostic page to query for.
 * \param dir		Direction of query.
 */
static void
ses_page_cdb(char *cdb, int bufsiz, SesDiagPageCodes pagenum, int dir)
{

	/* Ref: SPC-4 r25 Section 6.20 Table 223 */
	if (dir == CAM_DIR_IN) {
		cdb[0] = RECEIVE_DIAGNOSTIC;
		cdb[1] = 1; /* Set page code valid bit */
		cdb[2] = pagenum;
	} else {
		cdb[0] = SEND_DIAGNOSTIC;
		cdb[1] = 0x10;
		cdb[2] = pagenum;
	}
	cdb[3] = bufsiz >> 8;	/* high bits */
	cdb[4] = bufsiz & 0xff;	/* low bits */
	cdb[5] = 0;
}

/**
 * \brief Discover whether this instance supports timed completion of a
 * 	  RECEIVE DIAGNOSTIC RESULTS command requesting the Enclosure Status
 * 	  page, and store the result in the softc, updating if necessary.
 *
 * \param enc	SES instance to query and update.
 * \param tc_en	Value of timed completion to set (see \return).
 *
 * \return	1 if timed completion enabled, 0 otherwise.
 */
static int
ses_set_timed_completion(enc_softc_t *enc, uint8_t tc_en)
{
	union ccb *ccb;
	struct cam_periph *periph;
	struct ses_mgmt_mode_page *mgmt;
	uint8_t *mode_buf;
	size_t mode_buf_len;
	ses_softc_t *ses;

	periph = enc->periph;
	ses = enc->enc_private;
	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);

	mode_buf_len = sizeof(struct ses_mgmt_mode_page);
	mode_buf = ENC_MALLOCZ(mode_buf_len);
	if (mode_buf == NULL)
		goto out;

	scsi_mode_sense(&ccb->csio, /*retries*/4, NULL, MSG_SIMPLE_Q_TAG,
	    /*dbd*/FALSE, SMS_PAGE_CTRL_CURRENT, SES_MGMT_MODE_PAGE_CODE,
	    mode_buf, mode_buf_len, SSD_FULL_SIZE, /*timeout*/60 * 1000);

	/*
	 * Ignore illegal request errors, as they are quite common and we
	 * will print something out in that case anyway.
	 */
	cam_periph_runccb(ccb, enc_error, ENC_CFLAGS,
	    ENC_FLAGS|SF_QUIET_IR, NULL);
	if (ccb->ccb_h.status != CAM_REQ_CMP) {
		ENC_VLOG(enc, "Timed Completion Unsupported\n");
		goto release;
	}

	/* Skip the mode select if the desired value is already set */
	mgmt = (struct ses_mgmt_mode_page *)mode_buf;
	if ((mgmt->byte5 & SES_MGMT_TIMED_COMP_EN) == tc_en)
		goto done;

	/* Value is not what we wanted, set it */
	if (tc_en)
		mgmt->byte5 |= SES_MGMT_TIMED_COMP_EN;
	else
		mgmt->byte5 &= ~SES_MGMT_TIMED_COMP_EN;
	/* SES2r20: a completion time of zero means as long as possible */
	bzero(&mgmt->max_comp_time, sizeof(mgmt->max_comp_time));

	scsi_mode_select(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG,
	    /*page_fmt*/FALSE, /*save_pages*/TRUE, mode_buf, mode_buf_len,
	    SSD_FULL_SIZE, /*timeout*/60 * 1000);

	cam_periph_runccb(ccb, enc_error, ENC_CFLAGS, ENC_FLAGS, NULL);
	if (ccb->ccb_h.status != CAM_REQ_CMP) {
		ENC_VLOG(enc, "Timed Completion Set Failed\n");
		goto release;
	}

done:
	if ((mgmt->byte5 & SES_MGMT_TIMED_COMP_EN) != 0) {
		ENC_LOG(enc, "Timed Completion Enabled\n");
		ses->ses_flags |= SES_FLAG_TIMEDCOMP;
	} else {
		ENC_LOG(enc, "Timed Completion Disabled\n");
		ses->ses_flags &= ~SES_FLAG_TIMEDCOMP;
	}
release:
	ENC_FREE(mode_buf);
	xpt_release_ccb(ccb);
out:
	return (ses->ses_flags & SES_FLAG_TIMEDCOMP);
}

/**
 * \brief Process the list of supported pages and update flags.
 *
 * \param enc       SES device to query.
 * \param buf       Buffer containing the config page.
 * \param xfer_len  Length of the config page in the buffer.
 *
 * \return  0 on success, errno otherwise.
 */
static int
ses_process_pages(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{
	ses_softc_t *ses;
	struct scsi_diag_page *page;
	int err, i, length;

	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
	    ("entering %s(%p, %d)\n", __func__, bufp, xfer_len));
	ses = enc->enc_private;
	err = -1;

	if (error != 0) {
		err = error;
		goto out;
	}
	if (xfer_len < sizeof(*page)) {
		ENC_VLOG(enc, "Unable to parse Diag Pages List Header\n");
		err = EIO;
		goto out;
	}
	page = (struct scsi_diag_page *)*bufp;
	length = scsi_2btoul(page->length);
	if (length + offsetof(struct scsi_diag_page, params) > xfer_len) {
		ENC_VLOG(enc, "Diag Pages List Too Long\n");
		goto out;
	}
	ENC_DLOG(enc, "%s: page length %d, xfer_len %d\n",
		 __func__, length, xfer_len);

	err = 0;
	for (i = 0; i < length; i++) {
		if (page->params[i] == SesElementDescriptor)
			ses->ses_flags |= SES_FLAG_DESC;
		else if (page->params[i] == SesAddlElementStatus)
			ses->ses_flags |= SES_FLAG_ADDLSTATUS;
	}

out:
	ENC_DLOG(enc, "%s: exiting with err %d\n", __func__, err);
	return (err);
}

/**
 * \brief Process the config page and update associated structures.
 *
 * \param enc       SES device to query.
 * \param buf       Buffer containing the config page.
 * \param xfer_len  Length of the config page in the buffer.
 *
 * \return  0 on success, errno otherwise.
 */
static int
ses_process_config(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{
	struct ses_iterator iter;
	enc_cache_t *enc_cache;
	ses_cache_t *ses_cache;
	uint8_t *buf;
	int length;
	int err;
	int nelm;
	int ntype;
	struct ses_cfg_page *cfg_page;
	struct ses_enc_desc *buf_subenc;
	const struct ses_enc_desc **subencs;
	const struct ses_enc_desc **cur_subenc;
	const struct ses_enc_desc **last_subenc;
	ses_type_t *ses_types;
	ses_type_t *sestype;
	const struct ses_elm_type_desc *cur_buf_type;
	const struct ses_elm_type_desc *last_buf_type;
	uint8_t *last_valid_byte;
	enc_element_t *element;
	const char *type_text;

	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
	    ("entering %s(%p, %d)\n", __func__, bufp, xfer_len));
	enc_cache = &enc->enc_daemon_cache;
	ses_cache = enc_cache->private;
	buf = *bufp;
	err = -1;

	if (error != 0) {
		err = error;
		goto out;
	}
	if (xfer_len < sizeof(cfg_page->hdr)) {
		ENC_VLOG(enc, "Unable to parse SES Config Header\n");
		err = EIO;
		goto out;
	}

	cfg_page = (struct ses_cfg_page *)buf;
	length = ses_page_length(&cfg_page->hdr);
	if (length > xfer_len) {
		ENC_VLOG(enc, "Enclosure Config Page Too Long\n");
		goto out;
	}
	last_valid_byte = &buf[length - 1];

	ENC_DLOG(enc, "%s: total page length %d, xfer_len %d\n",
		 __func__, length, xfer_len);

	err = 0;
	if (ses_config_cache_valid(ses_cache, cfg_page->hdr.gen_code)) {
		/* Our cache is still valid.  Proceed to fetching status. */
		goto out;
	}

	/* Cache is no longer valid.  Free old data to make way for new. */
	ses_cache_free(enc, enc_cache);
	ENC_VLOG(enc, "Generation Code 0x%x has %d SubEnclosures\n",
	    scsi_4btoul(cfg_page->hdr.gen_code),
	    ses_cfg_page_get_num_subenc(cfg_page));

	/* Take ownership of the buffer. */
	ses_cache->cfg_page = cfg_page;
	*bufp = NULL;

	/*
	 * Now waltz through all the subenclosures summing the number of
	 * types available in each.
	 */
	subencs = malloc(ses_cfg_page_get_num_subenc(cfg_page)
	    * sizeof(*subencs), M_SCSIENC, M_WAITOK|M_ZERO);
	/*
	 * Sub-enclosure data is const after construction (i.e. when
	 * accessed via our cache object.
	 *
	 * The cast here is not required in C++ but C99 is not so
	 * sophisticated (see C99 6.5.16.1(1)).
	 */
	ses_cache->ses_nsubencs = ses_cfg_page_get_num_subenc(cfg_page);
	ses_cache->subencs = subencs;

	buf_subenc = cfg_page->subencs;
	cur_subenc = subencs;
	last_subenc = &subencs[ses_cache->ses_nsubencs - 1];
	ntype = 0;
	while (cur_subenc <= last_subenc) {
		if (!ses_enc_desc_is_complete(buf_subenc, last_valid_byte)) {
			ENC_VLOG(enc, "Enclosure %d Beyond End of "
			    "Descriptors\n", cur_subenc - subencs);
			err = EIO;
			goto out;
		}

		ENC_VLOG(enc, " SubEnclosure ID %d, %d Types With this ID, "
		    "Descriptor Length %d, offset %d\n", buf_subenc->subenc_id,
		    buf_subenc->num_types, buf_subenc->length,
		    &buf_subenc->byte0 - buf);
		ENC_VLOG(enc, "WWN: %jx\n",
		    (uintmax_t)scsi_8btou64(buf_subenc->logical_id));

		ntype += buf_subenc->num_types;
		*cur_subenc = buf_subenc;
		cur_subenc++;
		buf_subenc = ses_enc_desc_next(buf_subenc);
	}

	/* Process the type headers. */
	ses_types = malloc(ntype * sizeof(*ses_types),
	    M_SCSIENC, M_WAITOK|M_ZERO);
	/*
	 * Type data is const after construction (i.e. when accessed via
	 * our cache object.
	 */
	ses_cache->ses_ntypes = ntype;
	ses_cache->ses_types = ses_types;

	cur_buf_type = (const struct ses_elm_type_desc *)
	    (&(*last_subenc)->length + (*last_subenc)->length + 1);
	last_buf_type = cur_buf_type + ntype - 1;
	type_text = (const uint8_t *)(last_buf_type + 1);
	nelm = 0;
	sestype = ses_types;
	while (cur_buf_type <= last_buf_type) {
		if (&cur_buf_type->etype_txt_len > last_valid_byte) {
			ENC_VLOG(enc, "Runt Enclosure Type Header %d\n",
			    sestype - ses_types);
			err = EIO;
			goto out;
		}
		sestype->hdr  = cur_buf_type;
		sestype->text = type_text;
		type_text += cur_buf_type->etype_txt_len;
		ENC_VLOG(enc, " Type Desc[%d]: Type 0x%x, MaxElt %d, In Subenc "
		    "%d, Text Length %d: %.*s\n", sestype - ses_types,
		    sestype->hdr->etype_elm_type, sestype->hdr->etype_maxelt,
		    sestype->hdr->etype_subenc, sestype->hdr->etype_txt_len,
		    sestype->hdr->etype_txt_len, sestype->text);

		nelm += sestype->hdr->etype_maxelt
		      + /*overall status element*/1;
		sestype++;
		cur_buf_type++;
	}

	/* Create the object map. */
	enc_cache->elm_map = malloc(nelm * sizeof(enc_element_t),
	    M_SCSIENC, M_WAITOK|M_ZERO);
	enc_cache->nelms = nelm;

	ses_iter_init(enc, enc_cache, &iter);
	while ((element = ses_iter_next(&iter)) != NULL) {
		const struct ses_elm_type_desc *thdr;

		ENC_DLOG(enc, "%s: checking obj %d(%d,%d)\n", __func__,
		    iter.global_element_index, iter.type_index, nelm,
		    iter.type_element_index);
		thdr = ses_cache->ses_types[iter.type_index].hdr;
		element->elm_idx = iter.global_element_index;
		element->elm_type = thdr->etype_elm_type;
		element->subenclosure = thdr->etype_subenc;
		element->type_elm_idx = iter.type_element_index;
		element->elm_private = malloc(sizeof(ses_element_t),
		    M_SCSIENC, M_WAITOK|M_ZERO);
		ENC_DLOG(enc, "%s: creating elmpriv %d(%d,%d) subenc %d "
		    "type 0x%x\n", __func__, iter.global_element_index,
		    iter.type_index, iter.type_element_index,
		    thdr->etype_subenc, thdr->etype_elm_type);
	}

	err = 0;

out:
	if (err)
		ses_cache_free(enc, enc_cache);
	else {
		ses_poll_status(enc);
		enc_update_request(enc, SES_PUBLISH_CACHE);
	}
	ENC_DLOG(enc, "%s: exiting with err %d\n", __func__, err);
	return (err);
}

/**
 * \brief Update the status page and associated structures.
 * 
 * \param enc   SES softc to update for.
 * \param buf   Buffer containing the status page.
 * \param bufsz	Amount of data in the buffer.
 *
 * \return	0 on success, errno otherwise.
 */
static int
ses_process_status(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{
	struct ses_iterator iter;
	enc_element_t *element;
	ses_softc_t *ses;
	enc_cache_t *enc_cache;
	ses_cache_t *ses_cache;
	uint8_t *buf;
	int err = -1;
	int length;
	struct ses_status_page *page;
	union ses_status_element *cur_stat;
	union ses_status_element *last_stat;

	ses = enc->enc_private;
	enc_cache = &enc->enc_daemon_cache;
	ses_cache = enc_cache->private;
	buf = *bufp;

	ENC_DLOG(enc, "%s: enter (%p, %p, %d)\n", __func__, enc, buf, xfer_len);
	page = (struct ses_status_page *)buf;
	length = ses_page_length(&page->hdr);

	if (error != 0) {
		err = error;
		goto out;
	}
	/*
	 * Make sure the length fits in the buffer.
	 *
	 * XXX all this means is that the page is larger than the space
	 * we allocated.  Since we use a statically sized buffer, this
	 * could happen... Need to use dynamic discovery of the size.
	 */
	if (length > xfer_len) {
		ENC_VLOG(enc, "Enclosure Status Page Too Long\n");
		goto out;
	}

	/* Check for simple enclosure reporting short enclosure status. */
	if (length >= 4 && page->hdr.page_code == SesShortStatus) {
		ENC_DLOG(enc, "Got Short Enclosure Status page\n");
		ses->ses_flags &= ~(SES_FLAG_ADDLSTATUS | SES_FLAG_DESC);
		ses_cache_free(enc, enc_cache);
		enc_cache->enc_status = page->hdr.page_specific_flags;
		enc_update_request(enc, SES_PUBLISH_CACHE);
		err = 0;
		goto out;
	}

	/* Make sure the length contains at least one header and status */
	if (length < (sizeof(*page) + sizeof(*page->elements))) {
		ENC_VLOG(enc, "Enclosure Status Page Too Short\n");
		goto out;
	}

	if (!ses_config_cache_valid(ses_cache, page->hdr.gen_code)) {
		ENC_DLOG(enc, "%s: Generation count change detected\n",
		    __func__);
		enc_update_request(enc, SES_UPDATE_GETCONFIG);
		goto out;
	}

	ses_cache_free_status(enc, enc_cache);
	ses_cache->status_page = page;
	*bufp = NULL;

	enc_cache->enc_status = page->hdr.page_specific_flags;

	/*
	 * Read in individual element status.  The element order
	 * matches the order reported in the config page (i.e. the
	 * order of an unfiltered iteration of the config objects)..
	 */
	ses_iter_init(enc, enc_cache, &iter);
	cur_stat  = page->elements;
	last_stat = (union ses_status_element *)
	    &buf[length - sizeof(*last_stat)];
	ENC_DLOG(enc, "%s: total page length %d, xfer_len %d\n",
		__func__, length, xfer_len);
	while (cur_stat <= last_stat
	    && (element = ses_iter_next(&iter)) != NULL) {
		ENC_DLOG(enc, "%s: obj %d(%d,%d) off=0x%tx status=%jx\n",
		    __func__, iter.global_element_index, iter.type_index,
		    iter.type_element_index, (uint8_t *)cur_stat - buf,
		    scsi_4btoul(cur_stat->bytes));

		memcpy(&element->encstat, cur_stat, sizeof(element->encstat));
		element->svalid = 1;
		cur_stat++;
	}

	if (ses_iter_next(&iter) != NULL) {
		ENC_VLOG(enc, "Status page, length insufficient for "
			"expected number of objects\n");
	} else {
		if (cur_stat <= last_stat)
			ENC_VLOG(enc, "Status page, exhausted objects before "
				"exhausing page\n");
		enc_update_request(enc, SES_PUBLISH_CACHE);
		err = 0;
	}
out:
	ENC_DLOG(enc, "%s: exiting with error %d\n", __func__, err);
	return (err);
}

typedef enum {
	/**
	 * The enclosure should not provide additional element
	 * status for this element type in page 0x0A.
	 *
	 * \note  This status is returned for any types not
	 *        listed SES3r02.  Further types added in a
	 *        future specification will be incorrectly
	 *        classified.
	 */
	TYPE_ADDLSTATUS_NONE,

	/**
	 * The element type provides additional element status
	 * in page 0x0A.
	 */
	TYPE_ADDLSTATUS_MANDATORY,

	/**
	 * The element type may provide additional element status
	 * in page 0x0A, but i
	 */
	TYPE_ADDLSTATUS_OPTIONAL
} ses_addlstatus_avail_t;

/**
 * \brief Check to see whether a given type (as obtained via type headers) is
 *	  supported by the additional status command.
 *
 * \param enc     SES softc to check.
 * \param typidx  Type index to check for.
 *
 * \return  An enumeration indicating if additional status is mandatory,
 *          optional, or not required for this type.
 */
static ses_addlstatus_avail_t
ses_typehasaddlstatus(enc_softc_t *enc, uint8_t typidx)
{
	enc_cache_t *enc_cache;
	ses_cache_t *ses_cache;

	enc_cache = &enc->enc_daemon_cache;
	ses_cache = enc_cache->private;
	switch(ses_cache->ses_types[typidx].hdr->etype_elm_type) {
	case ELMTYP_DEVICE:
	case ELMTYP_ARRAY_DEV:
	case ELMTYP_SAS_EXP:
		return (TYPE_ADDLSTATUS_MANDATORY);
	case ELMTYP_SCSI_INI:
	case ELMTYP_SCSI_TGT:
	case ELMTYP_ESCC:
		return (TYPE_ADDLSTATUS_OPTIONAL);
	default:
		/* No additional status information available. */
		break;
	}
	return (TYPE_ADDLSTATUS_NONE);
}

static int ses_get_elm_addlstatus_fc(enc_softc_t *, enc_cache_t *,
				     uint8_t *, int);
static int ses_get_elm_addlstatus_sas(enc_softc_t *, enc_cache_t *, uint8_t *,
				      int, int, int, int);
static int ses_get_elm_addlstatus_ata(enc_softc_t *, enc_cache_t *, uint8_t *,
				      int, int, int, int);

/**
 * \brief Parse the additional status element data for each object.
 *
 * \param enc       The SES softc to update.
 * \param buf       The buffer containing the additional status
 *                  element response.
 * \param xfer_len  Size of the buffer.
 *
 * \return  0 on success, errno otherwise.
 */
static int
ses_process_elm_addlstatus(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{
	struct ses_iterator iter, titer;
	int eip;
	int err;
	int length;
	int offset;
	enc_cache_t *enc_cache;
	ses_cache_t *ses_cache;
	uint8_t *buf;
	ses_element_t *elmpriv;
	const struct ses_page_hdr *hdr;
	enc_element_t *element, *telement;

	enc_cache = &enc->enc_daemon_cache;
	ses_cache = enc_cache->private;
	buf = *bufp;
	err = -1;

	if (error != 0) {
		err = error;
		goto out;
	}
	ses_cache_free_elm_addlstatus(enc, enc_cache);
	ses_cache->elm_addlstatus_page =
	    (struct ses_addl_elem_status_page *)buf;
	*bufp = NULL;

	/*
	 * The objects appear in the same order here as in Enclosure Status,
	 * which itself is ordered by the Type Descriptors from the Config
	 * page.  However, it is necessary to skip elements that are not
	 * supported by this page when counting them.
	 */
	hdr = &ses_cache->elm_addlstatus_page->hdr;
	length = ses_page_length(hdr);
	ENC_DLOG(enc, "Additional Element Status Page Length 0x%x\n", length);
	/* Make sure the length includes at least one header. */
	if (length < sizeof(*hdr)+sizeof(struct ses_elm_addlstatus_base_hdr)) {
		ENC_VLOG(enc, "Runt Additional Element Status Page\n");
		goto out;
	}
	if (length > xfer_len) {
		ENC_VLOG(enc, "Additional Element Status Page Too Long\n");
		goto out;
	}

	if (!ses_config_cache_valid(ses_cache, hdr->gen_code)) {
		ENC_DLOG(enc, "%s: Generation count change detected\n",
		    __func__);
		enc_update_request(enc, SES_UPDATE_GETCONFIG);
		goto out;
	}

	offset = sizeof(struct ses_page_hdr);
	ses_iter_init(enc, enc_cache, &iter);
	while (offset < length
	    && (element = ses_iter_next(&iter)) != NULL) {
		struct ses_elm_addlstatus_base_hdr *elm_hdr;
		int proto_info_len;
		ses_addlstatus_avail_t status_type;

		/*
		 * Additional element status is only provided for
		 * individual elements (i.e. overal status elements
		 * are excluded) and those of the types specified
		 * in the SES spec.
		 */
		status_type = ses_typehasaddlstatus(enc, iter.type_index);
		if (iter.individual_element_index == ITERATOR_INDEX_INVALID
		 || status_type == TYPE_ADDLSTATUS_NONE)
			continue;

		elm_hdr = (struct ses_elm_addlstatus_base_hdr *)&buf[offset];
		eip = ses_elm_addlstatus_eip(elm_hdr);
		if (eip) {
			struct ses_elm_addlstatus_eip_hdr *eip_hdr;
			int expected_index, index;
			ses_elem_index_type_t index_type;

			eip_hdr = (struct ses_elm_addlstatus_eip_hdr *)elm_hdr;
			if (SES_ADDL_EIP_EIIOE_EI_GLOB(eip_hdr->byte2)) {
				index_type = SES_ELEM_INDEX_GLOBAL;
				expected_index = iter.global_element_index;
			} else {
				index_type = SES_ELEM_INDEX_INDIVIDUAL;
				expected_index = iter.individual_element_index;
			}
			if (eip_hdr->element_index < expected_index) {
				ENC_VLOG(enc, "%s: provided %selement index "
				    "%d is lower then expected %d\n",
				    __func__, SES_ADDL_EIP_EIIOE_EI_GLOB(
				    eip_hdr->byte2) ? "global " : "",
				    eip_hdr->element_index, expected_index);
				goto badindex;
			}
			titer = iter;
			telement = ses_iter_seek_to(&titer,
			    eip_hdr->element_index, index_type);
			if (telement == NULL) {
				ENC_VLOG(enc, "%s: provided %selement index "
				    "%d does not exist\n", __func__,
				    SES_ADDL_EIP_EIIOE_EI_GLOB(eip_hdr->byte2) ?
				    "global " : "", eip_hdr->element_index);
				goto badindex;
			}
			if (ses_typehasaddlstatus(enc, titer.type_index) ==
			    TYPE_ADDLSTATUS_NONE) {
				ENC_VLOG(enc, "%s: provided %selement index "
				    "%d can't have additional status\n",
				    __func__,
				    SES_ADDL_EIP_EIIOE_EI_GLOB(eip_hdr->byte2) ?
				    "global " : "", eip_hdr->element_index);
badindex:
				/*
				 * If we expected mandatory element, we may
				 * guess it was just a wrong index and we may
				 * use the status.  If element was optional,
				 * then we have no idea where status belongs.
				 */
				if (status_type == TYPE_ADDLSTATUS_OPTIONAL)
					break;
			} else {
				iter = titer;
				element = telement;
			}

			if (SES_ADDL_EIP_EIIOE_EI_GLOB(eip_hdr->byte2))
				index = iter.global_element_index;
			else
				index = iter.individual_element_index;
			if (index > expected_index
			 && status_type == TYPE_ADDLSTATUS_MANDATORY) {
				ENC_VLOG(enc, "%s: provided %s element"
					"index %d skips mandatory status "
					" element at index %d\n",
					__func__, SES_ADDL_EIP_EIIOE_EI_GLOB(
					eip_hdr->byte2) ? "global " : "",
					index, expected_index);
			}
		}
		elmpriv = element->elm_private;
		ENC_DLOG(enc, "%s: global element index=%d, type index=%d "
		    "type element index=%d, offset=0x%x, "
		    "byte0=0x%x, length=0x%x\n", __func__,
		    iter.global_element_index, iter.type_index,
		    iter.type_element_index, offset, elm_hdr->byte0,
		    elm_hdr->length);

		/* Skip to after the length field */
		offset += sizeof(struct ses_elm_addlstatus_base_hdr);

		/* Make sure the descriptor is within bounds */
		if ((offset + elm_hdr->length) > length) {
			ENC_VLOG(enc, "Element %d Beyond End "
			    "of Additional Element Status Descriptors\n",
			    iter.global_element_index);
			break;
		}

		/* Skip elements marked as invalid. */
		if (ses_elm_addlstatus_invalid(elm_hdr)) {
			offset += elm_hdr->length;
			continue;
		}
		elmpriv->addl.hdr = elm_hdr;

		/* Advance to the protocol data, skipping eip bytes if needed */
		offset += (eip * SES_EIP_HDR_EXTRA_LEN);
		proto_info_len = elm_hdr->length
			       - (eip * SES_EIP_HDR_EXTRA_LEN);

		/* Errors in this block are ignored as they are non-fatal */
		switch(ses_elm_addlstatus_proto(elm_hdr)) {
		case SPSP_PROTO_FC:
			if (elm_hdr->length == 0)
				break;
			ses_get_elm_addlstatus_fc(enc, enc_cache,
						  &buf[offset], proto_info_len);
			break;
		case SPSP_PROTO_SAS:
			if (elm_hdr->length <= 2)
				break;
			ses_get_elm_addlstatus_sas(enc, enc_cache,
						   &buf[offset],
						   proto_info_len,
						   eip, iter.type_index,
						   iter.global_element_index);
			break;
		case SPSP_PROTO_ATA:
			ses_get_elm_addlstatus_ata(enc, enc_cache,
						   &buf[offset],
						   proto_info_len,
						   eip, iter.type_index,
						   iter.global_element_index);
			break;
		default:
			ENC_VLOG(enc, "Element %d: Unknown Additional Element "
			    "Protocol 0x%x\n", iter.global_element_index,
			    ses_elm_addlstatus_proto(elm_hdr));
			break;
		}

		offset += proto_info_len;
	}
	err = 0;
out:
	if (err)
		ses_cache_free_elm_addlstatus(enc, enc_cache);
	enc_update_request(enc, SES_PUBLISH_PHYSPATHS);
	enc_update_request(enc, SES_PUBLISH_CACHE);
	return (err);
}

static int
ses_process_control_request(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{
	ses_softc_t *ses;

	ses = enc->enc_private;
	/*
	 * Possible errors:
	 *  o Generation count wrong.
	 *  o Some SCSI status error.
	 */
	ses_terminate_control_requests(&ses->ses_pending_requests, error);
	ses_poll_status(enc);
	return (0);
}

static int
ses_publish_physpaths(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{
	struct ses_iterator iter;
	enc_cache_t *enc_cache;
	enc_element_t *element;

	enc_cache = &enc->enc_daemon_cache;

	ses_iter_init(enc, enc_cache, &iter);
	while ((element = ses_iter_next(&iter)) != NULL) {
		/*
		 * ses_set_physpath() returns success if we changed
		 * the physpath of any element.  This allows us to
		 * only announce devices once regardless of how
		 * many times we process additional element status.
		 */
		if (ses_set_physpath(enc, element, &iter) == 0)
			ses_print_addl_data(enc, element);
	}

	return (0);
}

static int
ses_publish_cache(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{

	sx_xlock(&enc->enc_cache_lock);
	ses_cache_clone(enc, /*src*/&enc->enc_daemon_cache,
			/*dst*/&enc->enc_cache);
	sx_xunlock(&enc->enc_cache_lock);

	return (0);
}

/*
 * \brief Sanitize an element descriptor
 *
 * The SES4r3 standard, sections 3.1.2 and 6.1.10, specifies that element
 * descriptors may only contain ASCII characters in the range 0x20 to 0x7e.
 * But some vendors violate that rule.  Ensure that we only expose compliant
 * descriptors to userland.
 *
 * \param desc		SES element descriptor as reported by the hardware
 * \param len		Length of desc in bytes, not necessarily including
 * 			trailing NUL.  It will be modified if desc is invalid.
 */
static const char*
ses_sanitize_elm_desc(const char *desc, uint16_t *len)
{
	const char *invalid = "<invalid>";
	int i;

	for (i = 0; i < *len; i++) {
		if (desc[i] == 0) {
			break;
		} else if (desc[i] < 0x20 || desc[i] > 0x7e) {
			*len = strlen(invalid);
			return (invalid);
		}
	}
	return (desc);
}

/**
 * \brief Parse the descriptors for each object.
 *
 * \param enc       The SES softc to update.
 * \param buf       The buffer containing the descriptor list response.
 * \param xfer_len  Size of the buffer.
 * 
 * \return	0 on success, errno otherwise.
 */
static int
ses_process_elm_descs(enc_softc_t *enc, struct enc_fsm_state *state,
    union ccb *ccb, uint8_t **bufp, int error, int xfer_len)
{
	ses_softc_t *ses;
	struct ses_iterator iter;
	enc_element_t *element;
	int err;
	int offset;
	u_long length, plength;
	enc_cache_t *enc_cache;
	ses_cache_t *ses_cache;
	uint8_t *buf;
	ses_element_t *elmpriv;
	const struct ses_page_hdr *phdr;
	const struct ses_elm_desc_hdr *hdr;

	ses = enc->enc_private;
	enc_cache = &enc->enc_daemon_cache;
	ses_cache = enc_cache->private;
	buf = *bufp;
	err = -1;

	if (error != 0) {
		err = error;
		goto out;
	}
	ses_cache_free_elm_descs(enc, enc_cache);
	ses_cache->elm_descs_page = (struct ses_elem_descr_page *)buf;
	*bufp = NULL;

	phdr = &ses_cache->elm_descs_page->hdr;
	plength = ses_page_length(phdr);
	if (xfer_len < sizeof(struct ses_page_hdr)) {
		ENC_VLOG(enc, "Runt Element Descriptor Page\n");
		goto out;
	}
	if (plength > xfer_len) {
		ENC_VLOG(enc, "Element Descriptor Page Too Long\n");
		goto out;
	}

	if (!ses_config_cache_valid(ses_cache, phdr->gen_code)) {
		ENC_VLOG(enc, "%s: Generation count change detected\n",
		    __func__);
		enc_update_request(enc, SES_UPDATE_GETCONFIG);
		goto out;
	}

	offset = sizeof(struct ses_page_hdr);

	ses_iter_init(enc, enc_cache, &iter);
	while (offset < plength
	    && (element = ses_iter_next(&iter)) != NULL) {
		if ((offset + sizeof(struct ses_elm_desc_hdr)) > plength) {
			ENC_VLOG(enc, "Element %d Descriptor Header Past "
			    "End of Buffer\n", iter.global_element_index);
			goto out;
		}
		hdr = (struct ses_elm_desc_hdr *)&buf[offset];
		length = scsi_2btoul(hdr->length);
		ENC_DLOG(enc, "%s: obj %d(%d,%d) length=%d off=%d\n", __func__,
		    iter.global_element_index, iter.type_index,
		    iter.type_element_index, length, offset);
		if ((offset + sizeof(*hdr) + length) > plength) {
			ENC_VLOG(enc, "Element%d Descriptor Past "
			    "End of Buffer\n", iter.global_element_index);
			goto out;
		}
		offset += sizeof(*hdr);

		if (length > 0) {
			elmpriv = element->elm_private;
			elmpriv->descr_len = length;
			elmpriv->descr = ses_sanitize_elm_desc(&buf[offset],
			    &elmpriv->descr_len);
		}

		/* skip over the descriptor itself */
		offset += length;
	}

	err = 0;
out:
	if (err == 0) {
		if (ses->ses_flags & SES_FLAG_ADDLSTATUS)
			enc_update_request(enc, SES_UPDATE_GETELMADDLSTATUS);
	}
	enc_update_request(enc, SES_PUBLISH_CACHE);
	return (err);
}

static int
ses_fill_rcv_diag_io(enc_softc_t *enc, struct enc_fsm_state *state,
		       union ccb *ccb, uint8_t *buf)
{

	if (enc->enc_type == ENC_SEMB_SES) {
		semb_receive_diagnostic_results(&ccb->ataio, /*retries*/5,
					NULL, MSG_SIMPLE_Q_TAG, /*pcv*/1,
					state->page_code, buf, state->buf_size,
					state->timeout);
	} else {
		scsi_receive_diagnostic_results(&ccb->csio, /*retries*/5,
					NULL, MSG_SIMPLE_Q_TAG, /*pcv*/1,
					state->page_code, buf, state->buf_size,
					SSD_FULL_SIZE, state->timeout);
	}
	return (0);
}

/**
 * \brief Encode the object status into the response buffer, which is
 *	  expected to contain the current enclosure status.  This function
 *	  turns off all the 'select' bits for the objects except for the
 *	  object specified, then sends it back to the enclosure.
 *
 * \param enc	SES enclosure the change is being applied to.
 * \param buf	Buffer containing the current enclosure status response.
 * \param amt	Length of the response in the buffer.
 * \param req	The control request to be applied to buf.
 *
 * \return	0 on success, errno otherwise.
 */
static int
ses_encode(enc_softc_t *enc, uint8_t *buf, int amt, ses_control_request_t *req)
{
	struct ses_iterator iter;
	enc_element_t *element;
	int offset;
	struct ses_control_page_hdr *hdr;

	ses_iter_init(enc, &enc->enc_cache, &iter);
	hdr = (struct ses_control_page_hdr *)buf;
	if (req->elm_idx == -1) {
		/* for enclosure status, at least 2 bytes are needed */
		if (amt < 2)
			return EIO;
		hdr->control_flags =
		    req->elm_stat.comstatus & SES_SET_STATUS_MASK;
		ENC_DLOG(enc, "Set EncStat %x\n", hdr->control_flags);
		return (0);
	}

	element = ses_iter_seek_to(&iter, req->elm_idx, SES_ELEM_INDEX_GLOBAL);
	if (element == NULL)
		return (ENXIO);

	/*
	 * Seek to the type set that corresponds to the requested object.
	 * The +1 is for the overall status element for the type.
	 */
	offset = sizeof(struct ses_control_page_hdr)
	       + (iter.global_element_index * sizeof(struct ses_comstat));

	/* Check for buffer overflow. */
	if (offset + sizeof(struct ses_comstat) > amt)
		return (EIO);

	/* Set the status. */
	memcpy(&buf[offset], &req->elm_stat, sizeof(struct ses_comstat));

	ENC_DLOG(enc, "Set Type 0x%x Obj 0x%x (offset %d) with %x %x %x %x\n",
	    iter.type_index, iter.global_element_index, offset,
	    req->elm_stat.comstatus, req->elm_stat.comstat[0],
	    req->elm_stat.comstat[1], req->elm_stat.comstat[2]);

	return (0);
}

static int
ses_fill_control_request(enc_softc_t *enc, struct enc_fsm_state *state,
			 union ccb *ccb, uint8_t *buf)
{
	ses_softc_t			*ses;
	enc_cache_t			*enc_cache;
	ses_cache_t			*ses_cache;
	struct ses_control_page_hdr	*hdr;
	ses_control_request_t		*req;
	size_t				 plength;
	size_t				 offset;

	ses = enc->enc_private;
	enc_cache = &enc->enc_daemon_cache;
	ses_cache = enc_cache->private;
	hdr = (struct ses_control_page_hdr *)buf;

	if (ses_cache->status_page == NULL) {
		ses_terminate_control_requests(&ses->ses_requests, EIO);
		return (EIO);
	}

	plength = ses_page_length(&ses_cache->status_page->hdr);
	memcpy(buf, ses_cache->status_page, plength);

	/* Disable the select bits in all status entries.  */
	offset = sizeof(struct ses_control_page_hdr);
	for (offset = sizeof(struct ses_control_page_hdr);
	     offset < plength; offset += sizeof(struct ses_comstat)) {
		buf[offset] &= ~SESCTL_CSEL;
	}

	/* And make sure the INVOP bit is clear.  */
	hdr->control_flags &= ~SES_ENCSTAT_INVOP;

	/* Apply incoming requests. */
	while ((req = TAILQ_FIRST(&ses->ses_requests)) != NULL) {
		TAILQ_REMOVE(&ses->ses_requests, req, links);
		req->result = ses_encode(enc, buf, plength, req);
		if (req->result != 0) {
			wakeup(req);
			continue;
		}
		TAILQ_INSERT_TAIL(&ses->ses_pending_requests, req, links);
	}

	if (TAILQ_EMPTY(&ses->ses_pending_requests) != 0)
		return (ENOENT);

	/* Fill out the ccb */
	if (enc->enc_type == ENC_SEMB_SES) {
		semb_send_diagnostic(&ccb->ataio, /*retries*/5, NULL,
			     MSG_SIMPLE_Q_TAG,
			     buf, ses_page_length(&ses_cache->status_page->hdr),
			     state->timeout);
	} else {
		scsi_send_diagnostic(&ccb->csio, /*retries*/5, NULL,
			     MSG_SIMPLE_Q_TAG, /*unit_offline*/0,
			     /*device_offline*/0, /*self_test*/0,
			     /*page_format*/1, /*self_test_code*/0,
			     buf, ses_page_length(&ses_cache->status_page->hdr),
			     SSD_FULL_SIZE, state->timeout);
	}
	return (0);
}

static int
ses_get_elm_addlstatus_fc(enc_softc_t *enc, enc_cache_t *enc_cache,
			  uint8_t *buf, int bufsiz)
{
	ENC_VLOG(enc, "FC Device Support Stubbed in Additional Status Page\n");
	return (ENODEV);
}

#define	SES_PRINT_PORTS(p, type) do {					\
	if (((p) & SES_SASOBJ_DEV_PHY_PROTOMASK) != 0) {		\
		sbuf_printf(sbp, " %s (", type);			\
		if ((p) & SES_SASOBJ_DEV_PHY_SMP)			\
			sbuf_printf(sbp, " SMP");			\
		if ((p) & SES_SASOBJ_DEV_PHY_STP)			\
			sbuf_printf(sbp, " STP");			\
		if ((p) & SES_SASOBJ_DEV_PHY_SSP)			\
			sbuf_printf(sbp, " SSP");			\
		sbuf_printf(sbp, " )");					\
	}								\
} while(0)

/**
 * \brief Print the additional element status data for this object, for SAS
 * 	  type 0 objects.  See SES2 r20 Section 6.1.13.3.2.
 *
 * \param sesname	SES device name associated with the object.
 * \param sbp		Sbuf to print to.
 * \param obj		The object to print the data for.
 */
static void
ses_print_addl_data_sas_type0(char *sesname, struct sbuf *sbp,
			      enc_element_t *obj)
{
	int i;
	ses_element_t *elmpriv;
	struct ses_addl_status *addl;
	struct ses_elm_sas_device_phy *phy;

	elmpriv = obj->elm_private;
	addl = &(elmpriv->addl);
	sbuf_printf(sbp, ", SAS Slot: %d%s phys",
	    addl->proto_hdr.sas->base_hdr.num_phys,
	    ses_elm_sas_type0_not_all_phys(addl->proto_hdr.sas) ? "+" : "");
	if (ses_elm_addlstatus_eip(addl->hdr))
		sbuf_printf(sbp, " at slot %d",
		    addl->proto_hdr.sas->type0_eip.dev_slot_num);
	sbuf_printf(sbp, "\n");
	if (addl->proto_data.sasdev_phys == NULL)
		return;
	for (i = 0;i < addl->proto_hdr.sas->base_hdr.num_phys;i++) {
		phy = &addl->proto_data.sasdev_phys[i];
		sbuf_printf(sbp, "%s:  phy %d:", sesname, i);
		if (ses_elm_sas_dev_phy_sata_dev(phy))
			/* Spec says all other fields are specific values */
			sbuf_printf(sbp, " SATA device\n");
		else {
			sbuf_printf(sbp, " SAS device type %d phy %d",
			    ses_elm_sas_dev_phy_dev_type(phy), phy->phy_id);
			SES_PRINT_PORTS(phy->initiator_ports, "Initiator");
			SES_PRINT_PORTS(phy->target_ports, "Target");
			sbuf_printf(sbp, "\n");
		}
		sbuf_printf(sbp, "%s:  phy %d: parent %jx addr %jx\n",
		    sesname, i,
		    (uintmax_t)scsi_8btou64(phy->parent_addr),
		    (uintmax_t)scsi_8btou64(phy->phy_addr));
	}
}
#undef SES_PRINT_PORTS

/**
 * \brief Print the additional element status data for this object, for SAS
 *	  type 1 objects.  See SES2 r20 Sections 6.1.13.3.3 and 6.1.13.3.4.
 *
 * \param sesname	SES device name associated with the object.
 * \param sbp		Sbuf to print to.
 * \param obj		The object to print the data for.
 */
static void
ses_print_addl_data_sas_type1(char *sesname, struct sbuf *sbp,
			      enc_element_t *obj)
{
	int i, num_phys;
	ses_element_t *elmpriv;
	struct ses_addl_status *addl;
	struct ses_elm_sas_expander_phy *exp_phy;
	struct ses_elm_sas_port_phy *port_phy;

	elmpriv = obj->elm_private;
	addl = &(elmpriv->addl);
	sbuf_printf(sbp, ", SAS ");
	if (obj->elm_type == ELMTYP_SAS_EXP) {
		num_phys = addl->proto_hdr.sas->base_hdr.num_phys;
		sbuf_printf(sbp, "Expander: %d phys", num_phys);
		if (addl->proto_data.sasexp_phys == NULL)
			return;
		for (i = 0;i < num_phys;i++) {
			exp_phy = &addl->proto_data.sasexp_phys[i];
			sbuf_printf(sbp, "%s:  phy %d: connector %d other %d\n",
			    sesname, i, exp_phy->connector_index,
			    exp_phy->other_index);
		}
	} else {
		num_phys = addl->proto_hdr.sas->base_hdr.num_phys;
		sbuf_printf(sbp, "Port: %d phys", num_phys);
		if (addl->proto_data.sasport_phys == NULL)
			return;
		for (i = 0;i < num_phys;i++) {
			port_phy = &addl->proto_data.sasport_phys[i];
			sbuf_printf(sbp,
			    "%s:  phy %d: id %d connector %d other %d\n",
			    sesname, i, port_phy->phy_id,
			    port_phy->connector_index, port_phy->other_index);
			sbuf_printf(sbp, "%s:  phy %d: addr %jx\n", sesname, i,
			    (uintmax_t)scsi_8btou64(port_phy->phy_addr));
		}
	}
}

/**
 * \brief Print the additional element status data for this object, for
 *	  ATA objects.
 *
 * \param sbp		Sbuf to print to.
 * \param obj		The object to print the data for.
 */
static void
ses_print_addl_data_ata(struct sbuf *sbp, enc_element_t *obj)
{
	ses_element_t *elmpriv = obj->elm_private;
	struct ses_addl_status *addl = &elmpriv->addl;
	struct ses_elm_ata_hdr *ata = addl->proto_hdr.ata;

	sbuf_printf(sbp, ", SATA Slot: scbus%d target %d\n",
	    scsi_4btoul(ata->bus), scsi_4btoul(ata->target));
}

/**
 * \brief Print the additional element status data for this object.
 *
 * \param enc		SES softc associated with the object.
 * \param obj		The object to print the data for.
 */
static void
ses_print_addl_data(enc_softc_t *enc, enc_element_t *obj)
{
	ses_element_t *elmpriv;
	struct ses_addl_status *addl;
	struct sbuf sesname, name, out;

	elmpriv = obj->elm_private;
	if (elmpriv == NULL)
		return;

	addl = &(elmpriv->addl);
	if (addl->hdr == NULL)
		return;

	sbuf_new(&sesname, NULL, 16, SBUF_AUTOEXTEND);
	sbuf_new(&name, NULL, 16, SBUF_AUTOEXTEND);
	sbuf_new(&out, NULL, 512, SBUF_AUTOEXTEND);
	ses_paths_iter(enc, obj, ses_elmdevname_callback, &name);
	if (sbuf_len(&name) == 0)
		sbuf_printf(&name, "(none)");
	sbuf_finish(&name);
	sbuf_printf(&sesname, "%s%d", enc->periph->periph_name,
	    enc->periph->unit_number);
	sbuf_finish(&sesname);
	sbuf_printf(&out, "%s: %s in ", sbuf_data(&sesname), sbuf_data(&name));
	if (elmpriv->descr != NULL)
		sbuf_printf(&out, "'%s'", elmpriv->descr);
	else {
		if (obj->elm_type <= ELMTYP_LAST)
			sbuf_cat(&out, elm_type_names[obj->elm_type]);
		else
			sbuf_printf(&out, "<Type 0x%02x>", obj->elm_type);
		sbuf_printf(&out, " %d", obj->type_elm_idx);
		if (obj->subenclosure != 0)
			sbuf_printf(&out, " of subenc %d", obj->subenclosure);
	}
	switch(ses_elm_addlstatus_proto(addl->hdr)) {
	case SPSP_PROTO_FC:
		goto noaddl;	/* stubbed for now */
	case SPSP_PROTO_SAS:
		if (addl->proto_hdr.sas == NULL)
			goto noaddl;
		switch(ses_elm_sas_descr_type(addl->proto_hdr.sas)) {
		case SES_SASOBJ_TYPE_SLOT:
			ses_print_addl_data_sas_type0(sbuf_data(&sesname),
			    &out, obj);
			break;
		case SES_SASOBJ_TYPE_OTHER:
			ses_print_addl_data_sas_type1(sbuf_data(&sesname),
			    &out, obj);
			break;
		default:
			goto noaddl;
		}
		break;
	case SPSP_PROTO_ATA:
		if (addl->proto_hdr.ata == NULL)
			goto noaddl;
		ses_print_addl_data_ata(&out, obj);
		break;
	default:
noaddl:
		sbuf_cat(&out, "\n");
		break;
	}
	sbuf_finish(&out);
	printf("%s", sbuf_data(&out));
	sbuf_delete(&out);
	sbuf_delete(&name);
	sbuf_delete(&sesname);
}

/**
 * \brief Update the softc with the additional element status data for this
 * 	  object, for SAS type 0 objects.
 *
 * \param enc		SES softc to be updated.
 * \param buf		The additional element status response buffer.
 * \param bufsiz	Size of the response buffer.
 * \param eip		The EIP bit value.
 * \param nobj		Number of objects attached to the SES softc.
 * 
 * \return		0 on success, errno otherwise.
 */
static int
ses_get_elm_addlstatus_sas_type0(enc_softc_t *enc, enc_cache_t *enc_cache,
				 uint8_t *buf, int bufsiz, int eip, int nobj)
{
	int err, offset, physz;
	enc_element_t *obj;
	ses_element_t *elmpriv;
	struct ses_addl_status *addl;

	err = offset = 0;

	/* basic object setup */
	obj = &(enc_cache->elm_map[nobj]);
	elmpriv = obj->elm_private;
	addl = &(elmpriv->addl);

	addl->proto_hdr.sas = (union ses_elm_sas_hdr *)&buf[offset];

	/* Don't assume this object has any phys */
	bzero(&addl->proto_data, sizeof(addl->proto_data));
	if (addl->proto_hdr.sas->base_hdr.num_phys == 0)
		goto out;

	/* Skip forward to the phy list */
	if (eip)
		offset += sizeof(struct ses_elm_sas_type0_eip_hdr);
	else
		offset += sizeof(struct ses_elm_sas_type0_base_hdr);

	/* Make sure the phy list fits in the buffer */
	physz = addl->proto_hdr.sas->base_hdr.num_phys;
	physz *= sizeof(struct ses_elm_sas_device_phy);
	if (physz > (bufsiz - offset + 4)) {
		ENC_VLOG(enc, "Element %d Device Phy List Beyond End Of Buffer\n",
		    nobj);
		err = EIO;
		goto out;
	}

	/* Point to the phy list */
	addl->proto_data.sasdev_phys =
	    (struct ses_elm_sas_device_phy *)&buf[offset];

out:
	return (err);
}

/**
 * \brief Update the softc with the additional element status data for this
 * 	  object, for SAS type 1 objects.
 *
 * \param enc		SES softc to be updated.
 * \param buf		The additional element status response buffer.
 * \param bufsiz	Size of the response buffer.
 * \param eip		The EIP bit value.
 * \param nobj		Number of objects attached to the SES softc.
 * 
 * \return		0 on success, errno otherwise.
 */
static int
ses_get_elm_addlstatus_sas_type1(enc_softc_t *enc, enc_cache_t *enc_cache,
			         uint8_t *buf, int bufsiz, int eip, int nobj)
{
	int err, offset, physz;
	enc_element_t *obj;
	ses_element_t *elmpriv;
	struct ses_addl_status *addl;

	err = offset = 0;

	/* basic object setup */
	obj = &(enc_cache->elm_map[nobj]);
	elmpriv = obj->elm_private;
	addl = &(elmpriv->addl);

	addl->proto_hdr.sas = (union ses_elm_sas_hdr *)&buf[offset];

	/* Don't assume this object has any phys */
	bzero(&addl->proto_data, sizeof(addl->proto_data));
	if (addl->proto_hdr.sas->base_hdr.num_phys == 0)
		goto out;

	/* Process expanders differently from other type1 cases */
	if (obj->elm_type == ELMTYP_SAS_EXP) {
		offset += sizeof(struct ses_elm_sas_type1_expander_hdr);
		physz = addl->proto_hdr.sas->base_hdr.num_phys *
		    sizeof(struct ses_elm_sas_expander_phy);
		if (physz > (bufsiz - offset)) {
			ENC_VLOG(enc, "Element %d: Expander Phy List Beyond "
			    "End Of Buffer\n", nobj);
			err = EIO;
			goto out;
		}
		addl->proto_data.sasexp_phys =
		    (struct ses_elm_sas_expander_phy *)&buf[offset];
	} else {
		offset += sizeof(struct ses_elm_sas_type1_nonexpander_hdr);
		physz = addl->proto_hdr.sas->base_hdr.num_phys *
		    sizeof(struct ses_elm_sas_port_phy);
		if (physz > (bufsiz - offset + 4)) {
			ENC_VLOG(enc, "Element %d: Port Phy List Beyond End "
			    "Of Buffer\n", nobj);
			err = EIO;
			goto out;
		}
		addl->proto_data.sasport_phys =
		    (struct ses_elm_sas_port_phy *)&buf[offset];
	}

out:
	return (err);
}

/**
 * \brief Update the softc with the additional element status data for this
 * 	  object, for SAS objects.
 *
 * \param enc		SES softc to be updated.
 * \param buf		The additional element status response buffer.
 * \param bufsiz	Size of the response buffer.
 * \param eip		The EIP bit value.
 * \param tidx		Type index for this object.
 * \param nobj		Number of objects attached to the SES softc.
 * 
 * \return		0 on success, errno otherwise.
 */
static int
ses_get_elm_addlstatus_sas(enc_softc_t *enc, enc_cache_t *enc_cache,
			   uint8_t *buf, int bufsiz, int eip, int tidx,
			   int nobj)
{
	int dtype, err;
	ses_cache_t *ses_cache;
	union ses_elm_sas_hdr *hdr;

	/* Need to be able to read the descriptor type! */
	if (bufsiz < sizeof(union ses_elm_sas_hdr)) {
		err = EIO;
		goto out;
	}

	ses_cache = enc_cache->private;

	hdr = (union ses_elm_sas_hdr *)buf;
	dtype = ses_elm_sas_descr_type(hdr);
	switch(dtype) {
	case SES_SASOBJ_TYPE_SLOT:
		switch(ses_cache->ses_types[tidx].hdr->etype_elm_type) {
		case ELMTYP_DEVICE:
		case ELMTYP_ARRAY_DEV:
			break;
		default:
			ENC_VLOG(enc, "Element %d has Additional Status type 0, "
			    "invalid for SES element type 0x%x\n", nobj,
			    ses_cache->ses_types[tidx].hdr->etype_elm_type);
			err = ENODEV;
			goto out;
		}
		err = ses_get_elm_addlstatus_sas_type0(enc, enc_cache,
						       buf, bufsiz, eip,
		    nobj);
		break;
	case SES_SASOBJ_TYPE_OTHER:
		switch(ses_cache->ses_types[tidx].hdr->etype_elm_type) {
		case ELMTYP_SAS_EXP:
		case ELMTYP_SCSI_INI:
		case ELMTYP_SCSI_TGT:
		case ELMTYP_ESCC:
			break;
		default:
			ENC_VLOG(enc, "Element %d has Additional Status type 1, "
			    "invalid for SES element type 0x%x\n", nobj,
			    ses_cache->ses_types[tidx].hdr->etype_elm_type);
			err = ENODEV;
			goto out;
		}
		err = ses_get_elm_addlstatus_sas_type1(enc, enc_cache, buf,
						       bufsiz, eip, nobj);
		break;
	default:
		ENC_VLOG(enc, "Element %d of type 0x%x has Additional Status "
		    "of unknown type 0x%x\n", nobj,
		    ses_cache->ses_types[tidx].hdr->etype_elm_type, dtype);
		err = ENODEV;
		break;
	}

out:
	return (err);
}

/**
 * \brief Update the softc with the additional element status data for this
 * 	  object, for ATA objects.
 *
 * \param enc		SES softc to be updated.
 * \param buf		The additional element status response buffer.
 * \param bufsiz	Size of the response buffer.
 * \param eip		The EIP bit value.
 * \param tidx		Type index for this object.
 * \param nobj		Number of objects attached to the SES softc.
 * 
 * \return		0 on success, errno otherwise.
 */
static int
ses_get_elm_addlstatus_ata(enc_softc_t *enc, enc_cache_t *enc_cache,
			   uint8_t *buf, int bufsiz, int eip, int tidx,
			   int nobj)
{
	int err;
	ses_cache_t *ses_cache;

	if (bufsiz < sizeof(struct ses_elm_ata_hdr)) {
		err = EIO;
		goto out;
	}

	ses_cache = enc_cache->private;
	switch(ses_cache->ses_types[tidx].hdr->etype_elm_type) {
	case ELMTYP_DEVICE:
	case ELMTYP_ARRAY_DEV:
		break;
	default:
		ENC_VLOG(enc, "Element %d has Additional Status, "
		    "invalid for SES element type 0x%x\n", nobj,
		    ses_cache->ses_types[tidx].hdr->etype_elm_type);
		err = ENODEV;
		goto out;
	}

	((ses_element_t *)enc_cache->elm_map[nobj].elm_private)
	    ->addl.proto_hdr.ata = (struct ses_elm_ata_hdr *)buf;
	err = 0;

out:
	return (err);
}

static void
ses_softc_invalidate(enc_softc_t *enc)
{
	ses_softc_t *ses;

	ses = enc->enc_private;
	ses_terminate_control_requests(&ses->ses_requests, ENXIO);
}

static void
ses_softc_cleanup(enc_softc_t *enc)
{

	ses_cache_free(enc, &enc->enc_cache);
	ses_cache_free(enc, &enc->enc_daemon_cache);
	ENC_FREE_AND_NULL(enc->enc_private);
	ENC_FREE_AND_NULL(enc->enc_cache.private);
	ENC_FREE_AND_NULL(enc->enc_daemon_cache.private);
}

static int
ses_init_enc(enc_softc_t *enc)
{
	return (0);
}

static int
ses_set_enc_status(enc_softc_t *enc, uint8_t encstat, int slpflag)
{
	ses_control_request_t req;
	ses_softc_t	     *ses;

	ses = enc->enc_private;
	req.elm_idx = SES_SETSTATUS_ENC_IDX;
	req.elm_stat.comstatus = encstat & 0xf;

	TAILQ_INSERT_TAIL(&ses->ses_requests, &req, links);
	enc_update_request(enc, SES_PROCESS_CONTROL_REQS);
	cam_periph_sleep(enc->periph, &req, PUSER, "encstat", 0);

	return (req.result);
}

static int
ses_get_elm_status(enc_softc_t *enc, encioc_elm_status_t *elms, int slpflag)
{
	unsigned int i = elms->elm_idx;

	memcpy(elms->cstat, &enc->enc_cache.elm_map[i].encstat, 4);
	return (0);
}

static int
ses_set_elm_status(enc_softc_t *enc, encioc_elm_status_t *elms, int slpflag)
{
	ses_control_request_t req;
	ses_softc_t	     *ses;

	/* If this is clear, we don't do diddly.  */
	if ((elms->cstat[0] & SESCTL_CSEL) == 0)
		return (0);

	ses = enc->enc_private;
	req.elm_idx = elms->elm_idx;
	memcpy(&req.elm_stat, elms->cstat, sizeof(req.elm_stat));

	TAILQ_INSERT_TAIL(&ses->ses_requests, &req, links);
	enc_update_request(enc, SES_PROCESS_CONTROL_REQS);
	cam_periph_sleep(enc->periph, &req, PUSER, "encstat", 0);

	return (req.result);
}

static int
ses_get_elm_desc(enc_softc_t *enc, encioc_elm_desc_t *elmd)
{
	int i = (int)elmd->elm_idx;
	ses_element_t *elmpriv;

	/* Assume caller has already checked obj_id validity */
	elmpriv = enc->enc_cache.elm_map[i].elm_private;
	/* object might not have a descriptor */
	if (elmpriv == NULL || elmpriv->descr == NULL) {
		elmd->elm_desc_len = 0;
		return (0);
	}
	if (elmd->elm_desc_len > elmpriv->descr_len)
		elmd->elm_desc_len = elmpriv->descr_len;
	copyout(elmpriv->descr, elmd->elm_desc_str, elmd->elm_desc_len);
	return (0);
}

/**
 * \brief Respond to ENCIOC_GETELMDEVNAME, providing a device name for the
 *	  given object id if one is available.
 *
 * \param enc	SES softc to examine.
 * \param objdn	ioctl structure to read/write device name info.
 *
 * \return	0 on success, errno otherwise.
 */
static int
ses_get_elm_devnames(enc_softc_t *enc, encioc_elm_devnames_t *elmdn)
{
	struct sbuf sb;
	int len;

	len = elmdn->elm_names_size;
	if (len < 0)
		return (EINVAL);

	cam_periph_unlock(enc->periph);
	sbuf_new(&sb, NULL, len, SBUF_FIXEDLEN);
	ses_paths_iter(enc, &enc->enc_cache.elm_map[elmdn->elm_idx],
	    ses_elmdevname_callback, &sb);
	sbuf_finish(&sb);
	elmdn->elm_names_len = sbuf_len(&sb);
	copyout(sbuf_data(&sb), elmdn->elm_devnames, elmdn->elm_names_len + 1);
	sbuf_delete(&sb);
	cam_periph_lock(enc->periph);
	return (elmdn->elm_names_len > 0 ? 0 : ENODEV);
}

/**
 * \brief Send a string to the primary subenclosure using the String Out
 * 	  SES diagnostic page.
 *
 * \param enc	SES enclosure to run the command on.
 * \param sstr	SES string structure to operate on
 * \param ioc	Ioctl being performed
 *
 * \return	0 on success, errno otherwise.
 */
static int
ses_handle_string(enc_softc_t *enc, encioc_string_t *sstr, unsigned long ioc)
{
	enc_cache_t *enc_cache;
	ses_cache_t *ses_cache;
	const struct ses_enc_desc *enc_desc;
	int amt, payload, ret;
	char cdb[6];
	char str[32];
	char vendor[9];
	char product[17];
	char rev[5];
	uint8_t *buf;
	size_t size, rsize;

	enc_cache = &enc->enc_daemon_cache;
	ses_cache = enc_cache->private;

	/* Implement SES2r20 6.1.6 */
	if (sstr->bufsiz > ENC_STRING_MAX)
		return (EINVAL); /* buffer size too large */

	switch (ioc) {
	case ENCIOC_SETSTRING:
		payload = sstr->bufsiz + 4; /* header for SEND DIAGNOSTIC */
		amt = 0 - payload;
		buf = ENC_MALLOC(payload);
		if (buf == NULL)
			return (ENOMEM);
		ses_page_cdb(cdb, payload, 0, CAM_DIR_OUT);
		/* Construct the page request */
		buf[0] = SesStringOut;
		buf[1] = 0;
		buf[2] = sstr->bufsiz >> 8;
		buf[3] = sstr->bufsiz & 0xff;
		ret = copyin(sstr->buf, &buf[4], sstr->bufsiz);
		if (ret != 0) {
			ENC_FREE(buf);
			return (ret);
		}
		break;
	case ENCIOC_GETSTRING:
		payload = sstr->bufsiz;
		amt = payload;
		buf = ENC_MALLOC(payload);
		if (buf == NULL)
			return (ENOMEM);
		ses_page_cdb(cdb, payload, SesStringIn, CAM_DIR_IN);
		break;
	case ENCIOC_GETENCNAME:
		if (ses_cache->ses_nsubencs < 1)
			return (ENODEV);
		enc_desc = ses_cache->subencs[0];
		cam_strvis(vendor, enc_desc->vendor_id,
		    sizeof(enc_desc->vendor_id), sizeof(vendor));
		cam_strvis(product, enc_desc->product_id,
		    sizeof(enc_desc->product_id), sizeof(product));
		cam_strvis(rev, enc_desc->product_rev,
		    sizeof(enc_desc->product_rev), sizeof(rev));
		rsize = snprintf(str, sizeof(str), "%s %s %s",
		    vendor, product, rev) + 1;
		if (rsize > sizeof(str))
			rsize = sizeof(str);
		size = rsize;
		if (size > sstr->bufsiz)
			size = sstr->bufsiz;
		copyout(str, sstr->buf, size);
		sstr->bufsiz = rsize;
		return (size == rsize ? 0 : ENOMEM);
	case ENCIOC_GETENCID:
		if (ses_cache->ses_nsubencs < 1)
			return (ENODEV);
		enc_desc = ses_cache->subencs[0];
		rsize = snprintf(str, sizeof(str), "%16jx",
		    scsi_8btou64(enc_desc->logical_id)) + 1;
		if (rsize > sizeof(str))
			rsize = sizeof(str);
		size = rsize;
		if (size > sstr->bufsiz)
			size = sstr->bufsiz;
		copyout(str, sstr->buf, size);
		sstr->bufsiz = rsize;
		return (size == rsize ? 0 : ENOMEM);
	default:
		return (EINVAL);
	}
	ret = enc_runcmd(enc, cdb, 6, buf, &amt);
	if (ret == 0 && ioc == ENCIOC_GETSTRING)
		ret = copyout(buf, sstr->buf, sstr->bufsiz);
	if (ioc == ENCIOC_SETSTRING || ioc == ENCIOC_GETSTRING)
		ENC_FREE(buf);
	return (ret);
}

/**
 * \invariant Called with cam_periph mutex held.
 */
static void
ses_poll_status(enc_softc_t *enc)
{
	ses_softc_t *ses;

	ses = enc->enc_private;
	enc_update_request(enc, SES_UPDATE_GETSTATUS);
	if (ses->ses_flags & SES_FLAG_DESC)
		enc_update_request(enc, SES_UPDATE_GETELMDESCS);
	if (ses->ses_flags & SES_FLAG_ADDLSTATUS)
		enc_update_request(enc, SES_UPDATE_GETELMADDLSTATUS);
}

/**
 * \brief Notification received when CAM detects a new device in the
 *        SCSI domain in which this SEP resides.
 *
 * \param enc	SES enclosure instance.
 */
static void
ses_device_found(enc_softc_t *enc)
{
	ses_poll_status(enc);
	enc_update_request(enc, SES_PUBLISH_PHYSPATHS);
}

static struct enc_vec ses_enc_vec =
{
	.softc_invalidate	= ses_softc_invalidate,
	.softc_cleanup		= ses_softc_cleanup,
	.init_enc		= ses_init_enc,
	.set_enc_status		= ses_set_enc_status,
	.get_elm_status		= ses_get_elm_status,
	.set_elm_status		= ses_set_elm_status,
	.get_elm_desc		= ses_get_elm_desc,
	.get_elm_devnames	= ses_get_elm_devnames,
	.handle_string		= ses_handle_string,
	.device_found		= ses_device_found,
	.poll_status		= ses_poll_status
};

/**
 * \brief Initialize a new SES instance.
 *
 * \param enc		SES softc structure to set up the instance in.
 * \param doinit	Do the initialization (see main driver).
 *
 * \return		0 on success, errno otherwise.
 */
int
ses_softc_init(enc_softc_t *enc)
{
	ses_softc_t *ses_softc;

	CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
	    ("entering enc_softc_init(%p)\n", enc));

	enc->enc_vec = ses_enc_vec;
	enc->enc_fsm_states = enc_fsm_states;

	if (enc->enc_private == NULL)
		enc->enc_private = ENC_MALLOCZ(sizeof(ses_softc_t));
	if (enc->enc_cache.private == NULL)
		enc->enc_cache.private = ENC_MALLOCZ(sizeof(ses_cache_t));
	if (enc->enc_daemon_cache.private == NULL)
		enc->enc_daemon_cache.private =
		     ENC_MALLOCZ(sizeof(ses_cache_t));

	if (enc->enc_private == NULL
	 || enc->enc_cache.private == NULL
	 || enc->enc_daemon_cache.private == NULL) {
		ENC_FREE_AND_NULL(enc->enc_private);
		ENC_FREE_AND_NULL(enc->enc_cache.private);
		ENC_FREE_AND_NULL(enc->enc_daemon_cache.private);
		return (ENOMEM);
	}

	ses_softc = enc->enc_private;
	TAILQ_INIT(&ses_softc->ses_requests);
	TAILQ_INIT(&ses_softc->ses_pending_requests);

	enc_update_request(enc, SES_UPDATE_PAGES);

	// XXX: Move this to the FSM so it doesn't hang init
	if (0) (void) ses_set_timed_completion(enc, 1);

	return (0);
}