summaryrefslogtreecommitdiffstats
path: root/sys/cam/scsi/scsi_ch.c
blob: 2923ab201f5d128c52ddec345b29c98abe240f26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
/*
 * Copyright (c) 1997 Justin T. Gibbs.
 * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
 * 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.
 *
 * $FreeBSD$
 */
/*
 * Derived from the NetBSD SCSI changer driver.
 *
 *	$NetBSD: ch.c,v 1.32 1998/01/12 09:49:12 thorpej Exp $
 *
 */
/*
 * Copyright (c) 1996, 1997 Jason R. Thorpe <thorpej@and.com>
 * All rights reserved.
 *
 * Partially based on an autochanger driver written by Stefan Grefen
 * and on an autochanger driver written by the Systems Programming Group
 * at the University of Utah Computer Science Department.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgements:
 *	This product includes software developed by Jason R. Thorpe
 *	for And Communications, http://www.and.com/
 * 4. 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 ``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 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.
 */

#include <sys/param.h>
#include <sys/queue.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/types.h>
#include <sys/malloc.h>
#include <sys/fcntl.h>
#include <sys/conf.h>
#include <sys/chio.h>
#include <sys/errno.h>
#include <sys/devicestat.h>

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

#include <cam/scsi/scsi_all.h>
#include <cam/scsi/scsi_message.h>
#include <cam/scsi/scsi_ch.h>

/*
 * Timeout definitions for various changer related commands.  They may
 * be too short for some devices (especially the timeout for INITIALIZE
 * ELEMENT STATUS).
 */

static const u_int32_t	CH_TIMEOUT_MODE_SENSE                = 6000;
static const u_int32_t	CH_TIMEOUT_MOVE_MEDIUM               = 100000;
static const u_int32_t	CH_TIMEOUT_EXCHANGE_MEDIUM           = 100000;
static const u_int32_t	CH_TIMEOUT_POSITION_TO_ELEMENT       = 100000;
static const u_int32_t	CH_TIMEOUT_READ_ELEMENT_STATUS       = 10000;
static const u_int32_t	CH_TIMEOUT_SEND_VOLTAG		     = 10000;
static const u_int32_t	CH_TIMEOUT_INITIALIZE_ELEMENT_STATUS = 500000;

typedef enum {
	CH_FLAG_INVALID		= 0x001,
	CH_FLAG_OPEN		= 0x002
} ch_flags;

typedef enum {
	CH_STATE_PROBE,
	CH_STATE_NORMAL
} ch_state;

typedef enum {
	CH_CCB_PROBE,
	CH_CCB_WAITING
} ch_ccb_types;

typedef enum {
	CH_Q_NONE	= 0x00,
	CH_Q_NO_DBD	= 0x01
} ch_quirks;

#define ccb_state	ppriv_field0
#define ccb_bp		ppriv_ptr1

struct scsi_mode_sense_data {
	struct scsi_mode_header_6 header;
	struct scsi_mode_blk_desc blk_desc;
	union {
		struct page_element_address_assignment ea;
		struct page_transport_geometry_parameters tg;
		struct page_device_capabilities cap;
	} pages;
};

struct ch_softc {
	ch_flags	flags;
	ch_state	state;
	ch_quirks	quirks;
	union ccb	saved_ccb;
	struct devstat	device_stats;
	dev_t		dev;

	int		sc_picker;	/* current picker */

	/*
	 * The following information is obtained from the
	 * element address assignment page.
	 */
	int		sc_firsts[4];	/* firsts, indexed by CHET_* */
	int		sc_counts[4];	/* counts, indexed by CHET_* */

	/*
	 * The following mask defines the legal combinations
	 * of elements for the MOVE MEDIUM command.
	 */
	u_int8_t	sc_movemask[4];

	/*
	 * As above, but for EXCHANGE MEDIUM.
	 */
	u_int8_t	sc_exchangemask[4];

	/*
	 * Quirks; see below.  XXX KDM not implemented yet
	 */
	int		sc_settledelay;	/* delay for settle */
};

#define CHUNIT(x)       (minor((x)))
#define CH_CDEV_MAJOR	17

static	d_open_t	chopen;
static	d_close_t	chclose;
static	d_ioctl_t	chioctl;
static	periph_init_t	chinit;
static  periph_ctor_t	chregister;
static	periph_oninv_t	choninvalidate;
static  periph_dtor_t   chcleanup;
static  periph_start_t  chstart;
static	void		chasync(void *callback_arg, u_int32_t code,
				struct cam_path *path, void *arg);
static	void		chdone(struct cam_periph *periph,
			       union ccb *done_ccb);
static	int		cherror(union ccb *ccb, u_int32_t cam_flags,
				u_int32_t sense_flags);
static	int		chmove(struct cam_periph *periph,
			       struct changer_move *cm);
static	int		chexchange(struct cam_periph *periph,
				   struct changer_exchange *ce);
static	int		chposition(struct cam_periph *periph,
				   struct changer_position *cp);
static	int		chgetelemstatus(struct cam_periph *periph,
				struct changer_element_status_request *csr);
static	int		chsetvoltag(struct cam_periph *periph,
				    struct changer_set_voltag_request *csvr);
static	int		chielem(struct cam_periph *periph, 
				unsigned int timeout);
static	int		chgetparams(struct cam_periph *periph);

static struct periph_driver chdriver =
{
	chinit, "ch",
	TAILQ_HEAD_INITIALIZER(chdriver.units), /* generation */ 0
};

PERIPHDRIVER_DECLARE(ch, chdriver);

static struct cdevsw ch_cdevsw = {
	/* open */	chopen,
	/* close */	chclose,
	/* read */	noread,
	/* write */	nowrite,
	/* ioctl */	chioctl,
	/* poll */	nopoll,
	/* mmap */	nommap,
	/* strategy */	nostrategy,
	/* name */	"ch",
	/* maj */	CH_CDEV_MAJOR,
	/* dump */	nodump,
	/* psize */	nopsize,
	/* flags */	0,
	/* bmaj */	-1
};

static struct extend_array *chperiphs;

void
chinit(void)
{
	cam_status status;
	struct cam_path *path;

	/*
	 * Create our extend array for storing the devices we attach to.
	 */
	chperiphs = cam_extend_new();
	if (chperiphs == NULL) {
		printf("ch: Failed to alloc extend array!\n");
		return;
	}

	/*
	 * Install a global async callback.  This callback will
	 * receive async callbacks like "new device found".
	 */
	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);

	if (status == CAM_REQ_CMP) {
		struct ccb_setasync csa;

                xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
                csa.ccb_h.func_code = XPT_SASYNC_CB;
                csa.event_enable = AC_FOUND_DEVICE;
                csa.callback = chasync;
                csa.callback_arg = NULL;
                xpt_action((union ccb *)&csa);
		status = csa.ccb_h.status;
                xpt_free_path(path);
        }

	if (status != CAM_REQ_CMP) {
		printf("ch: Failed to attach master async callback "
		       "due to status 0x%x!\n", status);
	}
}

static void
choninvalidate(struct cam_periph *periph)
{
	struct ch_softc *softc;
	struct ccb_setasync csa;

	softc = (struct ch_softc *)periph->softc;

	/*
	 * De-register any async callbacks.
	 */
	xpt_setup_ccb(&csa.ccb_h, periph->path,
		      /* priority */ 5);
	csa.ccb_h.func_code = XPT_SASYNC_CB;
	csa.event_enable = 0;
	csa.callback = chasync;
	csa.callback_arg = periph;
	xpt_action((union ccb *)&csa);

	softc->flags |= CH_FLAG_INVALID;

	xpt_print_path(periph->path);
	printf("lost device\n");

}

static void
chcleanup(struct cam_periph *periph)
{
	struct ch_softc *softc;

	softc = (struct ch_softc *)periph->softc;

	devstat_remove_entry(&softc->device_stats);
	destroy_dev(softc->dev);
	cam_extend_release(chperiphs, periph->unit_number);
	xpt_print_path(periph->path);
	printf("removing device entry\n");
	free(softc, M_DEVBUF);
}

static void
chasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg)
{
	struct cam_periph *periph;

	periph = (struct cam_periph *)callback_arg;

	switch(code) {
	case AC_FOUND_DEVICE:
	{
		struct ccb_getdev *cgd;
		cam_status status;

		cgd = (struct ccb_getdev *)arg;

		if (SID_TYPE(&cgd->inq_data)!= T_CHANGER)
			break;

		/*
		 * Allocate a peripheral instance for
		 * this device and start the probe
		 * process.
		 */
		status = cam_periph_alloc(chregister, choninvalidate,
					  chcleanup, chstart, "ch",
					  CAM_PERIPH_BIO, cgd->ccb_h.path,
					  chasync, AC_FOUND_DEVICE, cgd);

		if (status != CAM_REQ_CMP
		 && status != CAM_REQ_INPROG)
			printf("chasync: Unable to probe new device "
			       "due to status 0x%x\n", status);

		break;

	}
	default:
		cam_periph_async(periph, code, path, arg);
		break;
	}
}

static cam_status
chregister(struct cam_periph *periph, void *arg)
{
	struct ch_softc *softc;
	struct ccb_setasync csa;
	struct ccb_getdev *cgd;

	cgd = (struct ccb_getdev *)arg;
	if (periph == NULL) {
		printf("chregister: periph was NULL!!\n");
		return(CAM_REQ_CMP_ERR);
	}

	if (cgd == NULL) {
		printf("chregister: no getdev CCB, can't register device\n");
		return(CAM_REQ_CMP_ERR);
	}

	softc = (struct ch_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);

	if (softc == NULL) {
		printf("chregister: Unable to probe new device. "
		       "Unable to allocate softc\n");				
		return(CAM_REQ_CMP_ERR);
	}

	bzero(softc, sizeof(*softc));
	softc->state = CH_STATE_PROBE;
	periph->softc = softc;
	cam_extend_set(chperiphs, periph->unit_number, periph);
	softc->quirks = CH_Q_NONE;

	/*
	 * Changers don't have a blocksize, and obviously don't support
	 * tagged queueing.
	 */
	devstat_add_entry(&softc->device_stats, "ch",
			  periph->unit_number, 0,
			  DEVSTAT_NO_BLOCKSIZE | DEVSTAT_NO_ORDERED_TAGS,
			  SID_TYPE(&cgd->inq_data)| DEVSTAT_TYPE_IF_SCSI,
			  DEVSTAT_PRIORITY_OTHER);

	/* Register the device */
	softc->dev = make_dev(&ch_cdevsw, periph->unit_number, UID_ROOT,
			      GID_OPERATOR, 0600, "%s%d", periph->periph_name,
			      periph->unit_number);

	/*
	 * Add an async callback so that we get
	 * notified if this device goes away.
	 */
	xpt_setup_ccb(&csa.ccb_h, periph->path, /* priority */ 5);
	csa.ccb_h.func_code = XPT_SASYNC_CB;
	csa.event_enable = AC_LOST_DEVICE;
	csa.callback = chasync;
	csa.callback_arg = periph;
	xpt_action((union ccb *)&csa);

	/*
	 * Lock this peripheral until we are setup.
	 * This first call can't block
	 */
	(void)cam_periph_lock(periph, PRIBIO);
	xpt_schedule(periph, /*priority*/5);

	return(CAM_REQ_CMP);
}

static int
chopen(dev_t dev, int flags, int fmt, struct proc *p)
{
	struct cam_periph *periph;
	struct ch_softc *softc;
	int unit, error;
	int s;

	unit = CHUNIT(dev);
	periph = cam_extend_get(chperiphs, unit);

	if (periph == NULL)
		return(ENXIO);

	softc = (struct ch_softc *)periph->softc;

	s = splsoftcam();
	if (softc->flags & CH_FLAG_INVALID) {
		splx(s);
		return(ENXIO);
	}

	if ((error = cam_periph_lock(periph, PRIBIO | PCATCH)) != 0) {
		splx(s);
		return (error);
	}
	
	splx(s);

	if ((softc->flags & CH_FLAG_OPEN) == 0) {
		if (cam_periph_acquire(periph) != CAM_REQ_CMP)
			return(ENXIO);
		softc->flags |= CH_FLAG_OPEN;
	}

	/*
	 * Load information about this changer device into the softc.
	 */
	if ((error = chgetparams(periph)) != 0) {
		softc->flags &= ~CH_FLAG_OPEN;
		cam_periph_unlock(periph);
		cam_periph_release(periph);
		return(error);
	}

	cam_periph_unlock(periph);

	return(error);
}

static int
chclose(dev_t dev, int flag, int fmt, struct proc *p)
{
	struct	cam_periph *periph;
	struct	ch_softc *softc;
	int	unit, error;

	error = 0;

	unit = CHUNIT(dev);
	periph = cam_extend_get(chperiphs, unit);
	if (periph == NULL)
		return(ENXIO);

	softc = (struct ch_softc *)periph->softc;

	if ((error = cam_periph_lock(periph, PRIBIO)) != 0)
		return(error);

	softc->flags &= ~CH_FLAG_OPEN;

	cam_periph_unlock(periph);
	cam_periph_release(periph);

	return(0);
}

static void
chstart(struct cam_periph *periph, union ccb *start_ccb)
{
	struct ch_softc *softc;
	int s;

	softc = (struct ch_softc *)periph->softc;

	switch (softc->state) {
	case CH_STATE_NORMAL:
	{
		s = splbio();
		if (periph->immediate_priority <= periph->pinfo.priority){
			start_ccb->ccb_h.ccb_state = CH_CCB_WAITING;

			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
					  periph_links.sle);
			periph->immediate_priority = CAM_PRIORITY_NONE;
			splx(s);
			wakeup(&periph->ccb_list);
		} else
			splx(s);
		break;
	}
	case CH_STATE_PROBE:
	{
		int mode_buffer_len;
		void *mode_buffer;

		/*
		 * Include the block descriptor when calculating the mode
		 * buffer length,
		 */
		mode_buffer_len = sizeof(struct scsi_mode_header_6) +
				  sizeof(struct scsi_mode_blk_desc) +
				 sizeof(struct page_element_address_assignment);

		mode_buffer = malloc(mode_buffer_len, M_TEMP, M_NOWAIT);

		if (mode_buffer == NULL) {
			printf("chstart: couldn't malloc mode sense data\n");
			break;
		}
		bzero(mode_buffer, mode_buffer_len);

		/*
		 * Get the element address assignment page.
		 */
		scsi_mode_sense(&start_ccb->csio,
				/* retries */ 1,
				/* cbfcnp */ chdone,
				/* tag_action */ MSG_SIMPLE_Q_TAG,
				/* dbd */ (softc->quirks & CH_Q_NO_DBD) ?
					FALSE : TRUE,
				/* page_code */ SMS_PAGE_CTRL_CURRENT,
				/* page */ CH_ELEMENT_ADDR_ASSIGN_PAGE,
				/* param_buf */ (u_int8_t *)mode_buffer,
				/* param_len */ mode_buffer_len,
				/* sense_len */ SSD_FULL_SIZE,
				/* timeout */ CH_TIMEOUT_MODE_SENSE);

		start_ccb->ccb_h.ccb_bp = NULL;
		start_ccb->ccb_h.ccb_state = CH_CCB_PROBE;
		xpt_action(start_ccb);
		break;
	}
	}
}

static void
chdone(struct cam_periph *periph, union ccb *done_ccb)
{
	struct ch_softc *softc;
	struct ccb_scsiio *csio;

	softc = (struct ch_softc *)periph->softc;
	csio = &done_ccb->csio;

	switch(done_ccb->ccb_h.ccb_state) {
	case CH_CCB_PROBE:
	{
		struct scsi_mode_header_6 *mode_header;
		struct page_element_address_assignment *ea;
		char announce_buf[80];


		mode_header = (struct scsi_mode_header_6 *)csio->data_ptr;

		ea = (struct page_element_address_assignment *)
			find_mode_page_6(mode_header);

		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP){
			
			softc->sc_firsts[CHET_MT] = scsi_2btoul(ea->mtea);
			softc->sc_counts[CHET_MT] = scsi_2btoul(ea->nmte);
			softc->sc_firsts[CHET_ST] = scsi_2btoul(ea->fsea);
			softc->sc_counts[CHET_ST] = scsi_2btoul(ea->nse);
			softc->sc_firsts[CHET_IE] = scsi_2btoul(ea->fieea);
			softc->sc_counts[CHET_IE] = scsi_2btoul(ea->niee);
			softc->sc_firsts[CHET_DT] = scsi_2btoul(ea->fdtea);
			softc->sc_counts[CHET_DT] = scsi_2btoul(ea->ndte);
			softc->sc_picker = softc->sc_firsts[CHET_MT];

#define PLURAL(c)	(c) == 1 ? "" : "s"
			snprintf(announce_buf, sizeof(announce_buf),
				"%d slot%s, %d drive%s, "
				"%d picker%s, %d portal%s",
		    		softc->sc_counts[CHET_ST],
				PLURAL(softc->sc_counts[CHET_ST]),
		    		softc->sc_counts[CHET_DT],
				PLURAL(softc->sc_counts[CHET_DT]),
		    		softc->sc_counts[CHET_MT],
				PLURAL(softc->sc_counts[CHET_MT]),
		    		softc->sc_counts[CHET_IE],
				PLURAL(softc->sc_counts[CHET_IE]));
#undef PLURAL
		} else {
			int error;

			error = cherror(done_ccb, 0, SF_RETRY_UA |
					SF_NO_PRINT | SF_RETRY_SELTO);
			/*
			 * Retry any UNIT ATTENTION type errors.  They
			 * are expected at boot.
			 */
			if (error == ERESTART) {
				/*
				 * A retry was scheuled, so
				 * just return.
				 */
				return;
			} else if (error != 0) {
				int retry_scheduled;
				struct scsi_mode_sense_6 *sms;

				sms = (struct scsi_mode_sense_6 *)
					done_ccb->csio.cdb_io.cdb_bytes;

				/*
				 * Check to see if block descriptors were
				 * disabled.  Some devices don't like that.
				 * We're taking advantage of the fact that
				 * the first few bytes of the 6 and 10 byte
				 * mode sense commands are the same.  If
				 * block descriptors were disabled, enable
				 * them and re-send the command.
				 */
				if (sms->byte2 & SMS_DBD) {
					sms->byte2 &= ~SMS_DBD;
					xpt_action(done_ccb);
					softc->quirks |= CH_Q_NO_DBD;
					retry_scheduled = 1;
				} else
					retry_scheduled = 0;

				/* Don't wedge this device's queue */
				cam_release_devq(done_ccb->ccb_h.path,
						 /*relsim_flags*/0,
						 /*reduction*/0,
						 /*timeout*/0,
						 /*getcount_only*/0);

				if (retry_scheduled)
					return;

				if ((done_ccb->ccb_h.status & CAM_STATUS_MASK)
				    == CAM_SCSI_STATUS_ERROR) 
					scsi_sense_print(&done_ccb->csio);
				else {
					xpt_print_path(periph->path);
					printf("got CAM status %#x\n",
					       done_ccb->ccb_h.status);
				}
				xpt_print_path(periph->path);
				printf("fatal error, failed to attach to"
				       " device\n");

				cam_periph_invalidate(periph);

				announce_buf[0] = '\0';
			}
		}
		if (announce_buf[0] != '\0')
			xpt_announce_periph(periph, announce_buf);
		softc->state = CH_STATE_NORMAL;
		free(mode_header, M_TEMP);
		/*
		 * Since our peripheral may be invalidated by an error
		 * above or an external event, we must release our CCB
		 * before releasing the probe lock on the peripheral.
		 * The peripheral will only go away once the last lock
		 * is removed, and we need it around for the CCB release
		 * operation.
		 */
		xpt_release_ccb(done_ccb);
		cam_periph_unlock(periph);
		return;
	}
	case CH_CCB_WAITING:
	{
		/* Caller will release the CCB */
		wakeup(&done_ccb->ccb_h.cbfcnp);
		return;
	}
	default:
		break;
	}
	xpt_release_ccb(done_ccb);
}

static int
cherror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
{
	struct ch_softc *softc;
	struct cam_periph *periph;

	periph = xpt_path_periph(ccb->ccb_h.path);
	softc = (struct ch_softc *)periph->softc;

	return (cam_periph_error(ccb, cam_flags, sense_flags,
				 &softc->saved_ccb));
}

static int
chioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
{
	struct cam_periph *periph;
	struct ch_softc *softc;
	u_int8_t unit;
	int error;

	unit = CHUNIT(dev);

	periph = cam_extend_get(chperiphs, unit);
	if (periph == NULL)
		return(ENXIO);

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering chioctl\n"));

	softc = (struct ch_softc *)periph->softc;

	error = 0;

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, 
		  ("trying to do ioctl %#lx\n", cmd));

	/*
	 * If this command can change the device's state, we must
	 * have the device open for writing.
	 */
	switch (cmd) {
	case CHIOGPICKER:
	case CHIOGPARAMS:
	case CHIOGSTATUS:
		break;

	default:
		if ((flag & FWRITE) == 0)
			return (EBADF);
	}

	switch (cmd) {
	case CHIOMOVE:
		error = chmove(periph, (struct changer_move *)addr);
		break;

	case CHIOEXCHANGE:
		error = chexchange(periph, (struct changer_exchange *)addr);
		break;

	case CHIOPOSITION:
		error = chposition(periph, (struct changer_position *)addr);
		break;

	case CHIOGPICKER:
		*(int *)addr = softc->sc_picker - softc->sc_firsts[CHET_MT];
		break;

	case CHIOSPICKER:
	{
		int new_picker = *(int *)addr;

		if (new_picker > (softc->sc_counts[CHET_MT] - 1))
			return (EINVAL);
		softc->sc_picker = softc->sc_firsts[CHET_MT] + new_picker;
		break;
	}
	case CHIOGPARAMS:
	{
		struct changer_params *cp = (struct changer_params *)addr;

		cp->cp_npickers = softc->sc_counts[CHET_MT];
		cp->cp_nslots = softc->sc_counts[CHET_ST];
		cp->cp_nportals = softc->sc_counts[CHET_IE];
		cp->cp_ndrives = softc->sc_counts[CHET_DT];
		break;
	}
	case CHIOIELEM:
		error = chielem(periph, *(unsigned int *)addr);
		break;

	case CHIOGSTATUS:
	{
		error = chgetelemstatus(periph,
			       (struct changer_element_status_request *) addr);
		break;
	}

	case CHIOSETVOLTAG:
	{
		error = chsetvoltag(periph,
				    (struct changer_set_voltag_request *) addr);
		break;
	}

	/* Implement prevent/allow? */

	default:
		error = cam_periph_ioctl(periph, cmd, addr, cherror);
		break;
	}

	return (error);
}

static int
chmove(struct cam_periph *periph, struct changer_move *cm)
{
	struct ch_softc *softc;
	u_int16_t fromelem, toelem;
	union ccb *ccb;
	int error;

	error = 0;
	softc = (struct ch_softc *)periph->softc;

	/*
	 * Check arguments.
	 */
	if ((cm->cm_fromtype > CHET_DT) || (cm->cm_totype > CHET_DT))
		return (EINVAL);
	if ((cm->cm_fromunit > (softc->sc_counts[cm->cm_fromtype] - 1)) ||
	    (cm->cm_tounit > (softc->sc_counts[cm->cm_totype] - 1)))
		return (ENODEV);

	/*
	 * Check the request against the changer's capabilities.
	 */
	if ((softc->sc_movemask[cm->cm_fromtype] & (1 << cm->cm_totype)) == 0)
		return (ENODEV);

	/*
	 * Calculate the source and destination elements.
	 */
	fromelem = softc->sc_firsts[cm->cm_fromtype] + cm->cm_fromunit;
	toelem = softc->sc_firsts[cm->cm_totype] + cm->cm_tounit;

	ccb = cam_periph_getccb(periph, /*priority*/ 1);

	scsi_move_medium(&ccb->csio,
			 /* retries */ 1,
			 /* cbfcnp */ chdone,
			 /* tag_action */ MSG_SIMPLE_Q_TAG,
			 /* tea */ softc->sc_picker,
			 /* src */ fromelem,
			 /* dst */ toelem,
			 /* invert */ (cm->cm_flags & CM_INVERT) ? TRUE : FALSE,
			 /* sense_len */ SSD_FULL_SIZE,
			 /* timeout */ CH_TIMEOUT_MOVE_MEDIUM);

	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/0,
				  /*sense_flags*/ SF_RETRY_UA | SF_RETRY_SELTO,
				  &softc->device_stats);

	xpt_release_ccb(ccb);

	return(error);
}

static int
chexchange(struct cam_periph *periph, struct changer_exchange *ce)
{
	struct ch_softc *softc;
	u_int16_t src, dst1, dst2;
	union ccb *ccb;
	int error;

	error = 0;
	softc = (struct ch_softc *)periph->softc;
	/*
	 * Check arguments.
	 */
	if ((ce->ce_srctype > CHET_DT) || (ce->ce_fdsttype > CHET_DT) ||
	    (ce->ce_sdsttype > CHET_DT))
		return (EINVAL);
	if ((ce->ce_srcunit > (softc->sc_counts[ce->ce_srctype] - 1)) ||
	    (ce->ce_fdstunit > (softc->sc_counts[ce->ce_fdsttype] - 1)) ||
	    (ce->ce_sdstunit > (softc->sc_counts[ce->ce_sdsttype] - 1)))
		return (ENODEV);

	/*
	 * Check the request against the changer's capabilities.
	 */
	if (((softc->sc_exchangemask[ce->ce_srctype] &
	     (1 << ce->ce_fdsttype)) == 0) ||
	    ((softc->sc_exchangemask[ce->ce_fdsttype] &
	     (1 << ce->ce_sdsttype)) == 0))
		return (ENODEV);

	/*
	 * Calculate the source and destination elements.
	 */
	src = softc->sc_firsts[ce->ce_srctype] + ce->ce_srcunit;
	dst1 = softc->sc_firsts[ce->ce_fdsttype] + ce->ce_fdstunit;
	dst2 = softc->sc_firsts[ce->ce_sdsttype] + ce->ce_sdstunit;

	ccb = cam_periph_getccb(periph, /*priority*/ 1);

	scsi_exchange_medium(&ccb->csio,
			     /* retries */ 1,
			     /* cbfcnp */ chdone,
			     /* tag_action */ MSG_SIMPLE_Q_TAG,
			     /* tea */ softc->sc_picker,
			     /* src */ src,
			     /* dst1 */ dst1,
			     /* dst2 */ dst2,
			     /* invert1 */ (ce->ce_flags & CE_INVERT1) ?
			                   TRUE : FALSE,
			     /* invert2 */ (ce->ce_flags & CE_INVERT2) ?
			                   TRUE : FALSE,
			     /* sense_len */ SSD_FULL_SIZE,
			     /* timeout */ CH_TIMEOUT_EXCHANGE_MEDIUM);

	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/0,
				  /*sense_flags*/ SF_RETRY_UA | SF_RETRY_SELTO,
				  &softc->device_stats);

	xpt_release_ccb(ccb);

	return(error);
}

static int
chposition(struct cam_periph *periph, struct changer_position *cp)
{
	struct ch_softc *softc;
	u_int16_t dst;
	union ccb *ccb;
	int error;

	error = 0;
	softc = (struct ch_softc *)periph->softc;

	/*
	 * Check arguments.
	 */
	if (cp->cp_type > CHET_DT)
		return (EINVAL);
	if (cp->cp_unit > (softc->sc_counts[cp->cp_type] - 1))
		return (ENODEV);

	/*
	 * Calculate the destination element.
	 */
	dst = softc->sc_firsts[cp->cp_type] + cp->cp_unit;

	ccb = cam_periph_getccb(periph, /*priority*/ 1);

	scsi_position_to_element(&ccb->csio,
				 /* retries */ 1,
				 /* cbfcnp */ chdone,
				 /* tag_action */ MSG_SIMPLE_Q_TAG,
				 /* tea */ softc->sc_picker,
				 /* dst */ dst,
				 /* invert */ (cp->cp_flags & CP_INVERT) ?
					      TRUE : FALSE,
				 /* sense_len */ SSD_FULL_SIZE,
				 /* timeout */ CH_TIMEOUT_POSITION_TO_ELEMENT);

	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  /*sense_flags*/ SF_RETRY_UA | SF_RETRY_SELTO,
				  &softc->device_stats);

	xpt_release_ccb(ccb);

	return(error);
}

/*
 * Copy a volume tag to a volume_tag struct, converting SCSI byte order
 * to host native byte order in the volume serial number.  The volume
 * label as returned by the changer is transferred to user mode as
 * nul-terminated string.  Volume labels are truncated at the first
 * space, as suggested by SCSI-2.
 */
static	void
copy_voltag(struct changer_voltag *uvoltag, struct volume_tag *voltag)
{
	int i;
	for (i=0; i<CH_VOLTAG_MAXLEN; i++) {
		char c = voltag->vif[i];
		if (c && c != ' ')
			uvoltag->cv_volid[i] = c;
	        else
			break;
	}
	uvoltag->cv_serial = scsi_2btoul(voltag->vsn);
}

/*
 * Copy an an element status descriptor to a user-mode
 * changer_element_status structure.
 */

static	void
copy_element_status(struct ch_softc *softc,
		    u_int16_t flags,
		    struct read_element_status_descriptor *desc,
		    struct changer_element_status *ces)
{
	u_int16_t eaddr = scsi_2btoul(desc->eaddr);
	u_int16_t et;

	ces->ces_int_addr = eaddr;
	/* set up logical address in element status */
	for (et = CHET_MT; et <= CHET_DT; et++) {
		if ((softc->sc_firsts[et] <= eaddr)
		    && ((softc->sc_firsts[et] + softc->sc_counts[et])
			> eaddr)) {
			ces->ces_addr = eaddr - softc->sc_firsts[et];
			ces->ces_type = et;
			break;
		}
	}

	ces->ces_flags = desc->flags1;

	ces->ces_sensecode = desc->sense_code;
	ces->ces_sensequal = desc->sense_qual;

	if (desc->flags2 & READ_ELEMENT_STATUS_INVERT)
		ces->ces_flags |= CES_INVERT;

	if (desc->flags2 & READ_ELEMENT_STATUS_SVALID) {

		eaddr = scsi_2btoul(desc->ssea);

		/* convert source address to logical format */
		for (et = CHET_MT; et <= CHET_DT; et++) {
			if ((softc->sc_firsts[et] <= eaddr)
			    && ((softc->sc_firsts[et] + softc->sc_counts[et])
				> eaddr)) {
				ces->ces_source_addr = 
					eaddr - softc->sc_firsts[et];
				ces->ces_source_type = et;
				ces->ces_flags |= CES_SOURCE_VALID;
				break;
			}
		}

		if (!(ces->ces_flags & CES_SOURCE_VALID))
			printf("ch: warning: could not map element source "
			       "address %ud to a valid element type\n",
			       eaddr);
	}
			

	if (flags & READ_ELEMENT_STATUS_PVOLTAG)
		copy_voltag(&(ces->ces_pvoltag), &(desc->pvoltag));
	if (flags & READ_ELEMENT_STATUS_AVOLTAG)
		copy_voltag(&(ces->ces_avoltag), &(desc->avoltag));

	if (desc->dt_scsi_flags & READ_ELEMENT_STATUS_DT_IDVALID) {
		ces->ces_flags |= CES_SCSIID_VALID;
		ces->ces_scsi_id = desc->dt_scsi_addr;
	}

	if (desc->dt_scsi_addr & READ_ELEMENT_STATUS_DT_LUVALID) {
		ces->ces_flags |= CES_LUN_VALID;
		ces->ces_scsi_lun = 
			desc->dt_scsi_flags & READ_ELEMENT_STATUS_DT_LUNMASK;
	}
}

static int
chgetelemstatus(struct cam_periph *periph, 
		struct changer_element_status_request *cesr)
{
	struct read_element_status_header *st_hdr;
	struct read_element_status_page_header *pg_hdr;
	struct read_element_status_descriptor *desc;
	caddr_t data = NULL;
	size_t size, desclen;
	int avail, i, error = 0;
	struct changer_element_status *user_data = NULL;
	struct ch_softc *softc;
	union ccb *ccb;
	int chet = cesr->cesr_element_type;
	int want_voltags = (cesr->cesr_flags & CESR_VOLTAGS) ? 1 : 0;

	softc = (struct ch_softc *)periph->softc;

	/* perform argument checking */

	/*
	 * Perform a range check on the cesr_element_{base,count}
	 * request argument fields.
	 */
	if ((softc->sc_counts[chet] - cesr->cesr_element_base) <= 0
	    || (cesr->cesr_element_base + cesr->cesr_element_count)
	        > softc->sc_counts[chet])
		return (EINVAL);

	/*
	 * Request one descriptor for the given element type.  This
	 * is used to determine the size of the descriptor so that
	 * we can allocate enough storage for all of them.  We assume
	 * that the first one can fit into 1k.
	 */
	data = (caddr_t)malloc(1024, M_DEVBUF, M_WAITOK);

	ccb = cam_periph_getccb(periph, /*priority*/ 1);

	scsi_read_element_status(&ccb->csio,
				 /* retries */ 1,
				 /* cbfcnp */ chdone,
				 /* tag_action */ MSG_SIMPLE_Q_TAG,
				 /* voltag */ want_voltags,
				 /* sea */ softc->sc_firsts[chet],
				 /* count */ 1,
				 /* data_ptr */ data,
				 /* dxfer_len */ 1024,
				 /* sense_len */ SSD_FULL_SIZE,
				 /* timeout */ CH_TIMEOUT_READ_ELEMENT_STATUS);

	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  /*sense_flags*/ SF_RETRY_UA | SF_RETRY_SELTO,
				  &softc->device_stats);

	if (error)
		goto done;

	st_hdr = (struct read_element_status_header *)data;
	pg_hdr = (struct read_element_status_page_header *)((uintptr_t)st_hdr +
		  sizeof(struct read_element_status_header));
	desclen = scsi_2btoul(pg_hdr->edl);

	size = sizeof(struct read_element_status_header) +
	       sizeof(struct read_element_status_page_header) +
	       (desclen * cesr->cesr_element_count);

	/*
	 * Reallocate storage for descriptors and get them from the
	 * device.
	 */
	free(data, M_DEVBUF);
	data = (caddr_t)malloc(size, M_DEVBUF, M_WAITOK);

	scsi_read_element_status(&ccb->csio,
				 /* retries */ 1,
				 /* cbfcnp */ chdone,
				 /* tag_action */ MSG_SIMPLE_Q_TAG,
				 /* voltag */ want_voltags,
				 /* sea */ softc->sc_firsts[chet]
				 + cesr->cesr_element_base,
				 /* count */ cesr->cesr_element_count,
				 /* data_ptr */ data,
				 /* dxfer_len */ size,
				 /* sense_len */ SSD_FULL_SIZE,
				 /* timeout */ CH_TIMEOUT_READ_ELEMENT_STATUS);
	
	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  /*sense_flags*/ SF_RETRY_UA | SF_RETRY_SELTO,
				  &softc->device_stats);

	if (error)
		goto done;

	/*
	 * Fill in the user status array.
	 */
	st_hdr = (struct read_element_status_header *)data;
	avail = scsi_2btoul(st_hdr->count);

	if (avail != cesr->cesr_element_count) {
		xpt_print_path(periph->path);
		printf("warning, READ ELEMENT STATUS avail != count\n");
	}

	user_data = (struct changer_element_status *)
		malloc(avail * sizeof(struct changer_element_status),
		       M_DEVBUF, M_WAITOK | M_ZERO);

	desc = (struct read_element_status_descriptor *)((uintptr_t)data +
		sizeof(struct read_element_status_header) +
		sizeof(struct read_element_status_page_header));
	/*
	 * Set up the individual element status structures
	 */
	for (i = 0; i < avail; ++i) {
		struct changer_element_status *ces = &(user_data[i]);

		copy_element_status(softc, pg_hdr->flags, desc, ces);

		desc = (struct read_element_status_descriptor *)
		       ((uintptr_t)desc + desclen);
	}

	/* Copy element status structures out to userspace. */
	error = copyout(user_data,
			cesr->cesr_element_status,
			avail * sizeof(struct changer_element_status));

 done:
	xpt_release_ccb(ccb);

	if (data != NULL)
		free(data, M_DEVBUF);
	if (user_data != NULL)
		free(user_data, M_DEVBUF);

	return (error);
}

static int
chielem(struct cam_periph *periph,
	unsigned int timeout)
{
	union ccb *ccb;
	struct ch_softc *softc;
	int error;

	if (!timeout) {
		timeout = CH_TIMEOUT_INITIALIZE_ELEMENT_STATUS;
	} else {
		timeout *= 1000;
	}

	error = 0;
	softc = (struct ch_softc *)periph->softc;

	ccb = cam_periph_getccb(periph, /*priority*/ 1);

	scsi_initialize_element_status(&ccb->csio,
				      /* retries */ 1,
				      /* cbfcnp */ chdone,
				      /* tag_action */ MSG_SIMPLE_Q_TAG,
				      /* sense_len */ SSD_FULL_SIZE,
				      /* timeout */ timeout);

	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  /*sense_flags*/ SF_RETRY_UA | SF_RETRY_SELTO,
				  &softc->device_stats);

	xpt_release_ccb(ccb);

	return(error);
}

static int
chsetvoltag(struct cam_periph *periph,
	    struct changer_set_voltag_request *csvr)
{
	union ccb *ccb;
	struct ch_softc *softc;
	u_int16_t ea;
	u_int8_t sac;
	struct scsi_send_volume_tag_parameters ssvtp;
	int error;
	int i;

	error = 0;
	softc = (struct ch_softc *)periph->softc;

	bzero(&ssvtp, sizeof(ssvtp));
	for (i=0; i<sizeof(ssvtp.vitf); i++) {
		ssvtp.vitf[i] = ' ';
	}

	/*
	 * Check arguments.
	 */
	if (csvr->csvr_type > CHET_DT)
		return EINVAL;
	if (csvr->csvr_addr > (softc->sc_counts[csvr->csvr_type] - 1))
		return ENODEV;

	ea = softc->sc_firsts[csvr->csvr_type] + csvr->csvr_addr;

	if (csvr->csvr_flags & CSVR_ALTERNATE) {
		switch (csvr->csvr_flags & CSVR_MODE_MASK) {
		case CSVR_MODE_SET:
			sac = SEND_VOLUME_TAG_ASSERT_ALTERNATE;
			break;
		case CSVR_MODE_REPLACE:
			sac = SEND_VOLUME_TAG_REPLACE_ALTERNATE;
			break;
		case CSVR_MODE_CLEAR:
			sac = SEND_VOLUME_TAG_UNDEFINED_ALTERNATE;
			break;
		default:
			error = EINVAL;
			goto out;
		}
	} else {
		switch (csvr->csvr_flags & CSVR_MODE_MASK) {
		case CSVR_MODE_SET:
			sac = SEND_VOLUME_TAG_ASSERT_PRIMARY;
			break;
		case CSVR_MODE_REPLACE:
			sac = SEND_VOLUME_TAG_REPLACE_PRIMARY;
			break;
		case CSVR_MODE_CLEAR:
			sac = SEND_VOLUME_TAG_UNDEFINED_PRIMARY;
			break;
		default:
			error = EINVAL;
			goto out;
		}
	}

	memcpy(ssvtp.vitf, csvr->csvr_voltag.cv_volid,
	       min(strlen(csvr->csvr_voltag.cv_volid), sizeof(ssvtp.vitf)));
	scsi_ulto2b(csvr->csvr_voltag.cv_serial, ssvtp.minvsn);

	ccb = cam_periph_getccb(periph, /*priority*/ 1);

	scsi_send_volume_tag(&ccb->csio,
			     /* retries */ 1,
			     /* cbfcnp */ chdone,
			     /* tag_action */ MSG_SIMPLE_Q_TAG,
			     /* element_address */ ea,
			     /* send_action_code */ sac,
			     /* parameters */ &ssvtp,
			     /* sense_len */ SSD_FULL_SIZE,
			     /* timeout */ CH_TIMEOUT_SEND_VOLTAG);
	
	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  /*sense_flags*/ SF_RETRY_UA | SF_RETRY_SELTO,
				  &softc->device_stats);

	xpt_release_ccb(ccb);

 out:
	return error;
}

static int
chgetparams(struct cam_periph *periph)
{
	union ccb *ccb;
	struct ch_softc *softc;
	void *mode_buffer;
	int mode_buffer_len;
	struct page_element_address_assignment *ea;
	struct page_device_capabilities *cap;
	int error, from, dbd;
	u_int8_t *moves, *exchanges;

	error = 0;

	softc = (struct ch_softc *)periph->softc;

	ccb = cam_periph_getccb(periph, /*priority*/ 1);

	/*
	 * The scsi_mode_sense_data structure is just a convenience
	 * structure that allows us to easily calculate the worst-case
	 * storage size of the mode sense buffer.
	 */
	mode_buffer_len = sizeof(struct scsi_mode_sense_data);

	mode_buffer = malloc(mode_buffer_len, M_TEMP, M_NOWAIT);

	if (mode_buffer == NULL) {
		printf("chgetparams: couldn't malloc mode sense data\n");
		return(ENOSPC);
	}

	bzero(mode_buffer, mode_buffer_len);

	if (softc->quirks & CH_Q_NO_DBD)
		dbd = FALSE;
	else
		dbd = TRUE;

	/*
	 * Get the element address assignment page.
	 */
	scsi_mode_sense(&ccb->csio,
			/* retries */ 1,
			/* cbfcnp */ chdone,
			/* tag_action */ MSG_SIMPLE_Q_TAG,
			/* dbd */ dbd,
			/* page_code */ SMS_PAGE_CTRL_CURRENT,
			/* page */ CH_ELEMENT_ADDR_ASSIGN_PAGE,
			/* param_buf */ (u_int8_t *)mode_buffer,
			/* param_len */ mode_buffer_len,
			/* sense_len */ SSD_FULL_SIZE,
			/* timeout */ CH_TIMEOUT_MODE_SENSE);

	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  /* sense_flags */ SF_RETRY_UA |
				  SF_NO_PRINT | SF_RETRY_SELTO,
				  &softc->device_stats);

	if (error) {
		if (dbd) {
			struct scsi_mode_sense_6 *sms;

			sms = (struct scsi_mode_sense_6 *)
				ccb->csio.cdb_io.cdb_bytes;

			sms->byte2 &= ~SMS_DBD;
			error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  		  /*sense_flags*/ SF_RETRY_UA |
						  SF_RETRY_SELTO,
						  &softc->device_stats);
		} else {
			/*
			 * Since we disabled sense printing above, print
			 * out the sense here since we got an error.
			 */
			scsi_sense_print(&ccb->csio);
		}

		if (error) {
			xpt_print_path(periph->path);
			printf("chgetparams: error getting element "
			       "address page\n");
			xpt_release_ccb(ccb);
			free(mode_buffer, M_TEMP);
			return(error);
		}
	}

	ea = (struct page_element_address_assignment *)
		find_mode_page_6((struct scsi_mode_header_6 *)mode_buffer);

	softc->sc_firsts[CHET_MT] = scsi_2btoul(ea->mtea);
	softc->sc_counts[CHET_MT] = scsi_2btoul(ea->nmte);
	softc->sc_firsts[CHET_ST] = scsi_2btoul(ea->fsea);
	softc->sc_counts[CHET_ST] = scsi_2btoul(ea->nse);
	softc->sc_firsts[CHET_IE] = scsi_2btoul(ea->fieea);
	softc->sc_counts[CHET_IE] = scsi_2btoul(ea->niee);
	softc->sc_firsts[CHET_DT] = scsi_2btoul(ea->fdtea);
	softc->sc_counts[CHET_DT] = scsi_2btoul(ea->ndte);

	bzero(mode_buffer, mode_buffer_len);

	/*
	 * Now get the device capabilities page.
	 */
	scsi_mode_sense(&ccb->csio,
			/* retries */ 1,
			/* cbfcnp */ chdone,
			/* tag_action */ MSG_SIMPLE_Q_TAG,
			/* dbd */ dbd,
			/* page_code */ SMS_PAGE_CTRL_CURRENT,
			/* page */ CH_DEVICE_CAP_PAGE,
			/* param_buf */ (u_int8_t *)mode_buffer,
			/* param_len */ mode_buffer_len,
			/* sense_len */ SSD_FULL_SIZE,
			/* timeout */ CH_TIMEOUT_MODE_SENSE);
	
	error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  /* sense_flags */ SF_RETRY_UA | SF_NO_PRINT |
				  SF_RETRY_SELTO, &softc->device_stats);

	if (error) {
		if (dbd) {
			struct scsi_mode_sense_6 *sms;

			sms = (struct scsi_mode_sense_6 *)
				ccb->csio.cdb_io.cdb_bytes;

			sms->byte2 &= ~SMS_DBD;
			error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ 0,
				  		  /*sense_flags*/ SF_RETRY_UA |
						  SF_RETRY_SELTO,
						  &softc->device_stats);
		} else {
			/*
			 * Since we disabled sense printing above, print
			 * out the sense here since we got an error.
			 */
			scsi_sense_print(&ccb->csio);
		}

		if (error) {
			xpt_print_path(periph->path);
			printf("chgetparams: error getting device "
			       "capabilities page\n");
			xpt_release_ccb(ccb);
			free(mode_buffer, M_TEMP);
			return(error);
		}
	}

	xpt_release_ccb(ccb);

	cap = (struct page_device_capabilities *)
		find_mode_page_6((struct scsi_mode_header_6 *)mode_buffer);

	bzero(softc->sc_movemask, sizeof(softc->sc_movemask));
	bzero(softc->sc_exchangemask, sizeof(softc->sc_exchangemask));
	moves = &cap->move_from_mt;
	exchanges = &cap->exchange_with_mt;
	for (from = CHET_MT; from <= CHET_DT; ++from) {
		softc->sc_movemask[from] = moves[from];
		softc->sc_exchangemask[from] = exchanges[from];
	}

	free(mode_buffer, M_TEMP);

	return(error);
}

void
scsi_move_medium(struct ccb_scsiio *csio, u_int32_t retries,
		 void (*cbfcnp)(struct cam_periph *, union ccb *),
		 u_int8_t tag_action, u_int32_t tea, u_int32_t src,
		 u_int32_t dst, int invert, u_int8_t sense_len,
		 u_int32_t timeout)
{
	struct scsi_move_medium *scsi_cmd;

	scsi_cmd = (struct scsi_move_medium *)&csio->cdb_io.cdb_bytes;
	bzero(scsi_cmd, sizeof(*scsi_cmd));

	scsi_cmd->opcode = MOVE_MEDIUM;

	scsi_ulto2b(tea, scsi_cmd->tea);
	scsi_ulto2b(src, scsi_cmd->src);
	scsi_ulto2b(dst, scsi_cmd->dst);

	if (invert)
		scsi_cmd->invert |= MOVE_MEDIUM_INVERT;

	cam_fill_csio(csio,
		      retries,
		      cbfcnp,
		      /*flags*/ CAM_DIR_NONE,
		      tag_action,
		      /*data_ptr*/ NULL,
		      /*dxfer_len*/ 0,
		      sense_len,
		      sizeof(*scsi_cmd),
		      timeout);
}

void
scsi_exchange_medium(struct ccb_scsiio *csio, u_int32_t retries,
		     void (*cbfcnp)(struct cam_periph *, union ccb *),
		     u_int8_t tag_action, u_int32_t tea, u_int32_t src,
		     u_int32_t dst1, u_int32_t dst2, int invert1,
		     int invert2, u_int8_t sense_len, u_int32_t timeout)
{
	struct scsi_exchange_medium *scsi_cmd;

	scsi_cmd = (struct scsi_exchange_medium *)&csio->cdb_io.cdb_bytes;
	bzero(scsi_cmd, sizeof(*scsi_cmd));

	scsi_cmd->opcode = EXCHANGE_MEDIUM;

	scsi_ulto2b(tea, scsi_cmd->tea);
	scsi_ulto2b(src, scsi_cmd->src);
	scsi_ulto2b(dst1, scsi_cmd->fdst);
	scsi_ulto2b(dst2, scsi_cmd->sdst);

	if (invert1)
		scsi_cmd->invert |= EXCHANGE_MEDIUM_INV1;

	if (invert2)
		scsi_cmd->invert |= EXCHANGE_MEDIUM_INV2;

	cam_fill_csio(csio,
		      retries,
		      cbfcnp,
		      /*flags*/ CAM_DIR_NONE,
		      tag_action,
		      /*data_ptr*/ NULL,
		      /*dxfer_len*/ 0,
		      sense_len,
		      sizeof(*scsi_cmd),
		      timeout);
}

void
scsi_position_to_element(struct ccb_scsiio *csio, u_int32_t retries,
			 void (*cbfcnp)(struct cam_periph *, union ccb *),
			 u_int8_t tag_action, u_int32_t tea, u_int32_t dst,
			 int invert, u_int8_t sense_len, u_int32_t timeout)
{
	struct scsi_position_to_element *scsi_cmd;

	scsi_cmd = (struct scsi_position_to_element *)&csio->cdb_io.cdb_bytes;
	bzero(scsi_cmd, sizeof(*scsi_cmd));

	scsi_cmd->opcode = POSITION_TO_ELEMENT;

	scsi_ulto2b(tea, scsi_cmd->tea);
	scsi_ulto2b(dst, scsi_cmd->dst);

	if (invert)
		scsi_cmd->invert |= POSITION_TO_ELEMENT_INVERT;

	cam_fill_csio(csio,
		      retries,
		      cbfcnp,
		      /*flags*/ CAM_DIR_NONE,
		      tag_action,
		      /*data_ptr*/ NULL,
		      /*dxfer_len*/ 0,
		      sense_len,
		      sizeof(*scsi_cmd),
		      timeout);
}

void
scsi_read_element_status(struct ccb_scsiio *csio, u_int32_t retries,
			 void (*cbfcnp)(struct cam_periph *, union ccb *),
			 u_int8_t tag_action, int voltag, u_int32_t sea,
			 u_int32_t count, u_int8_t *data_ptr,
			 u_int32_t dxfer_len, u_int8_t sense_len,
			 u_int32_t timeout)
{
	struct scsi_read_element_status *scsi_cmd;

	scsi_cmd = (struct scsi_read_element_status *)&csio->cdb_io.cdb_bytes;
	bzero(scsi_cmd, sizeof(*scsi_cmd));

	scsi_cmd->opcode = READ_ELEMENT_STATUS;

	scsi_ulto2b(sea, scsi_cmd->sea);
	scsi_ulto2b(count, scsi_cmd->count);
	scsi_ulto3b(dxfer_len, scsi_cmd->len);

	if (voltag)
		scsi_cmd->byte2 |= READ_ELEMENT_STATUS_VOLTAG;

	cam_fill_csio(csio,
		      retries,
		      cbfcnp,
		      /*flags*/ CAM_DIR_IN,
		      tag_action,
		      data_ptr,
		      dxfer_len,
		      sense_len,
		      sizeof(*scsi_cmd),
		      timeout);
}

void
scsi_initialize_element_status(struct ccb_scsiio *csio, u_int32_t retries,
			       void (*cbfcnp)(struct cam_periph *, union ccb *),
			       u_int8_t tag_action, u_int8_t sense_len,
			       u_int32_t timeout)
{
	struct scsi_initialize_element_status *scsi_cmd;

	scsi_cmd = (struct scsi_initialize_element_status *)
		    &csio->cdb_io.cdb_bytes;
	bzero(scsi_cmd, sizeof(*scsi_cmd));

	scsi_cmd->opcode = INITIALIZE_ELEMENT_STATUS;

	cam_fill_csio(csio,
		      retries,
		      cbfcnp,
		      /*flags*/ CAM_DIR_NONE,
		      tag_action,
		      /* data_ptr */ NULL,
		      /* dxfer_len */ 0,
		      sense_len,
		      sizeof(*scsi_cmd),
		      timeout);
}

void
scsi_send_volume_tag(struct ccb_scsiio *csio, u_int32_t retries,
		     void (*cbfcnp)(struct cam_periph *, union ccb *),
		     u_int8_t tag_action, 
		     u_int16_t element_address,
		     u_int8_t send_action_code,
		     struct scsi_send_volume_tag_parameters *parameters,
		     u_int8_t sense_len, u_int32_t timeout)
{
	struct scsi_send_volume_tag *scsi_cmd;

	scsi_cmd = (struct scsi_send_volume_tag *) &csio->cdb_io.cdb_bytes;
	bzero(scsi_cmd, sizeof(*scsi_cmd));

	scsi_cmd->opcode = SEND_VOLUME_TAG;
	scsi_ulto2b(element_address, scsi_cmd->ea);
	scsi_cmd->sac = send_action_code;
	scsi_ulto2b(sizeof(*parameters), scsi_cmd->pll);

	cam_fill_csio(csio,
		      retries,
		      cbfcnp,
		      /*flags*/ CAM_DIR_OUT,
		      tag_action,
		      /* data_ptr */ (u_int8_t *) parameters,
		      sizeof(*parameters),
		      sense_len,
		      sizeof(*scsi_cmd),
		      timeout);
}
OpenPOWER on IntegriCloud