xref: /freebsd/sys/cam/scsi/scsi_sg.c (revision aa64588d28258aef88cc33b8043112e8856948d0)
1 /*-
2  * Copyright (c) 2007 Scott Long
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * scsi_sg peripheral driver.  This driver is meant to implement the Linux
29  * SG passthrough interface for SCSI.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/types.h>
39 #include <sys/bio.h>
40 #include <sys/malloc.h>
41 #include <sys/fcntl.h>
42 #include <sys/ioccom.h>
43 #include <sys/conf.h>
44 #include <sys/errno.h>
45 #include <sys/devicestat.h>
46 #include <sys/proc.h>
47 #include <sys/uio.h>
48 
49 #include <cam/cam.h>
50 #include <cam/cam_ccb.h>
51 #include <cam/cam_periph.h>
52 #include <cam/cam_queue.h>
53 #include <cam/cam_xpt_periph.h>
54 #include <cam/cam_debug.h>
55 #include <cam/cam_sim.h>
56 
57 #include <cam/scsi/scsi_all.h>
58 #include <cam/scsi/scsi_message.h>
59 #include <cam/scsi/scsi_sg.h>
60 
61 #include <compat/linux/linux_ioctl.h>
62 
63 typedef enum {
64 	SG_FLAG_OPEN		= 0x01,
65 	SG_FLAG_LOCKED		= 0x02,
66 	SG_FLAG_INVALID		= 0x04
67 } sg_flags;
68 
69 typedef enum {
70 	SG_STATE_NORMAL
71 } sg_state;
72 
73 typedef enum {
74 	SG_RDWR_FREE,
75 	SG_RDWR_INPROG,
76 	SG_RDWR_DONE
77 } sg_rdwr_state;
78 
79 typedef enum {
80 	SG_CCB_RDWR_IO,
81 	SG_CCB_WAITING
82 } sg_ccb_types;
83 
84 #define ccb_type	ppriv_field0
85 #define ccb_rdwr	ppriv_ptr1
86 
87 struct sg_rdwr {
88 	TAILQ_ENTRY(sg_rdwr)	rdwr_link;
89 	int			tag;
90 	int			state;
91 	int			buf_len;
92 	char			*buf;
93 	union ccb		*ccb;
94 	union {
95 		struct sg_header hdr;
96 		struct sg_io_hdr io_hdr;
97 	} hdr;
98 };
99 
100 struct sg_softc {
101 	sg_state		state;
102 	sg_flags		flags;
103 	struct devstat		*device_stats;
104 	TAILQ_HEAD(, sg_rdwr)	rdwr_done;
105 	struct cdev		*dev;
106 	int			sg_timeout;
107 	int			sg_user_timeout;
108 	uint8_t			pd_type;
109 	union ccb		saved_ccb;
110 };
111 
112 static d_open_t		sgopen;
113 static d_close_t	sgclose;
114 static d_ioctl_t	sgioctl;
115 static d_write_t	sgwrite;
116 static d_read_t		sgread;
117 
118 static periph_init_t	sginit;
119 static periph_ctor_t	sgregister;
120 static periph_oninv_t	sgoninvalidate;
121 static periph_dtor_t	sgcleanup;
122 static periph_start_t	sgstart;
123 static void		sgasync(void *callback_arg, uint32_t code,
124 				struct cam_path *path, void *arg);
125 static void		sgdone(struct cam_periph *periph, union ccb *done_ccb);
126 static int		sgsendccb(struct cam_periph *periph, union ccb *ccb);
127 static int		sgsendrdwr(struct cam_periph *periph, union ccb *ccb);
128 static int		sgerror(union ccb *ccb, uint32_t cam_flags,
129 				uint32_t sense_flags);
130 static void		sg_scsiio_status(struct ccb_scsiio *csio,
131 					 u_short *hoststat, u_short *drvstat);
132 
133 static int		scsi_group_len(u_char cmd);
134 
135 static struct periph_driver sgdriver =
136 {
137 	sginit, "sg",
138 	TAILQ_HEAD_INITIALIZER(sgdriver.units), /* gen */ 0
139 };
140 PERIPHDRIVER_DECLARE(sg, sgdriver);
141 
142 static struct cdevsw sg_cdevsw = {
143 	.d_version =	D_VERSION,
144 	.d_flags =	D_NEEDGIANT,
145 	.d_open =	sgopen,
146 	.d_close =	sgclose,
147 	.d_ioctl =	sgioctl,
148 	.d_write =	sgwrite,
149 	.d_read =	sgread,
150 	.d_name =	"sg",
151 };
152 
153 static int sg_version = 30125;
154 
155 static void
156 sginit(void)
157 {
158 	cam_status status;
159 
160 	/*
161 	 * Install a global async callback.  This callback will receive aync
162 	 * callbacks like "new device found".
163 	 */
164 	status = xpt_register_async(AC_FOUND_DEVICE, sgasync, NULL, NULL);
165 
166 	if (status != CAM_REQ_CMP) {
167 		printf("sg: Failed to attach master async callbac "
168 			"due to status 0x%x!\n", status);
169 	}
170 }
171 
172 static void
173 sgoninvalidate(struct cam_periph *periph)
174 {
175 	struct sg_softc *softc;
176 
177 	softc = (struct sg_softc *)periph->softc;
178 
179 	/*
180 	 * Deregister any async callbacks.
181 	 */
182 	xpt_register_async(0, sgasync, periph, periph->path);
183 
184 	softc->flags |= SG_FLAG_INVALID;
185 
186 	/*
187 	 * XXX Return all queued I/O with ENXIO.
188 	 * XXX Handle any transactions queued to the card
189 	 *     with XPT_ABORT_CCB.
190 	 */
191 
192 	if (bootverbose) {
193 		xpt_print(periph->path, "lost device\n");
194 	}
195 }
196 
197 static void
198 sgcleanup(struct cam_periph *periph)
199 {
200 	struct sg_softc *softc;
201 
202 	softc = (struct sg_softc *)periph->softc;
203 	if (bootverbose)
204 		xpt_print(periph->path, "removing device entry\n");
205 	devstat_remove_entry(softc->device_stats);
206 	cam_periph_unlock(periph);
207 	destroy_dev(softc->dev);
208 	cam_periph_lock(periph);
209 	free(softc, M_DEVBUF);
210 }
211 
212 static void
213 sgasync(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
214 {
215 	struct cam_periph *periph;
216 
217 	periph = (struct cam_periph *)callback_arg;
218 
219 	switch (code) {
220 	case AC_FOUND_DEVICE:
221 	{
222 		struct ccb_getdev *cgd;
223 		cam_status status;
224 
225 		cgd = (struct ccb_getdev *)arg;
226 		if (cgd == NULL)
227 			break;
228 
229 		if (cgd->protocol != PROTO_SCSI)
230 			break;
231 
232 		/*
233 		 * Allocate a peripheral instance for this device and
234 		 * start the probe process.
235 		 */
236 		status = cam_periph_alloc(sgregister, sgoninvalidate,
237 					  sgcleanup, sgstart, "sg",
238 					  CAM_PERIPH_BIO, cgd->ccb_h.path,
239 					  sgasync, AC_FOUND_DEVICE, cgd);
240 		if ((status != CAM_REQ_CMP) && (status != CAM_REQ_INPROG)) {
241 			const struct cam_status_entry *entry;
242 
243 			entry = cam_fetch_status_entry(status);
244 			printf("sgasync: Unable to attach new device "
245 				"due to status %#x: %s\n", status, entry ?
246 				entry->status_text : "Unknown");
247 		}
248 		break;
249 	}
250 	default:
251 		cam_periph_async(periph, code, path, arg);
252 		break;
253 	}
254 }
255 
256 static cam_status
257 sgregister(struct cam_periph *periph, void *arg)
258 {
259 	struct sg_softc *softc;
260 	struct ccb_getdev *cgd;
261 	int no_tags;
262 
263 	cgd = (struct ccb_getdev *)arg;
264 	if (periph == NULL) {
265 		printf("sgregister: periph was NULL!!\n");
266 		return (CAM_REQ_CMP_ERR);
267 	}
268 
269 	if (cgd == NULL) {
270 		printf("sgregister: no getdev CCB, can't register device\n");
271 		return (CAM_REQ_CMP_ERR);
272 	}
273 
274 	softc = malloc(sizeof(*softc), M_DEVBUF, M_ZERO | M_NOWAIT);
275 	if (softc == NULL) {
276 		printf("sgregister: Unable to allocate softc\n");
277 		return (CAM_REQ_CMP_ERR);
278 	}
279 
280 	softc->state = SG_STATE_NORMAL;
281 	softc->pd_type = SID_TYPE(&cgd->inq_data);
282 	softc->sg_timeout = SG_DEFAULT_TIMEOUT / SG_DEFAULT_HZ * hz;
283 	softc->sg_user_timeout = SG_DEFAULT_TIMEOUT;
284 	TAILQ_INIT(&softc->rdwr_done);
285 	periph->softc = softc;
286 
287 	/*
288 	 * We pass in 0 for all blocksize, since we don't know what the
289 	 * blocksize of the device is, if it even has a blocksize.
290 	 */
291 	cam_periph_unlock(periph);
292 	no_tags = (cgd->inq_data.flags & SID_CmdQue) == 0;
293 	softc->device_stats = devstat_new_entry("sg",
294 			periph->unit_number, 0,
295 			DEVSTAT_NO_BLOCKSIZE
296 			| (no_tags ? DEVSTAT_NO_ORDERED_TAGS : 0),
297 			softc->pd_type |
298 			DEVSTAT_TYPE_IF_SCSI |
299 			DEVSTAT_TYPE_PASS,
300 			DEVSTAT_PRIORITY_PASS);
301 
302 	/* Register the device */
303 	softc->dev = make_dev(&sg_cdevsw, periph->unit_number,
304 			      UID_ROOT, GID_OPERATOR, 0600, "%s%d",
305 			      periph->periph_name, periph->unit_number);
306 	if (periph->unit_number < 26) {
307 		(void)make_dev_alias(softc->dev, "sg%c",
308 		    periph->unit_number + 'a');
309 	} else {
310 		(void)make_dev_alias(softc->dev, "sg%c%c",
311 		    ((periph->unit_number / 26) - 1) + 'a',
312 		    (periph->unit_number % 26) + 'a');
313 	}
314 	cam_periph_lock(periph);
315 	softc->dev->si_drv1 = periph;
316 
317 	/*
318 	 * Add as async callback so that we get
319 	 * notified if this device goes away.
320 	 */
321 	xpt_register_async(AC_LOST_DEVICE, sgasync, periph, periph->path);
322 
323 	if (bootverbose)
324 		xpt_announce_periph(periph, NULL);
325 
326 	return (CAM_REQ_CMP);
327 }
328 
329 static void
330 sgstart(struct cam_periph *periph, union ccb *start_ccb)
331 {
332 	struct sg_softc *softc;
333 
334 	softc = (struct sg_softc *)periph->softc;
335 
336 	switch (softc->state) {
337 	case SG_STATE_NORMAL:
338 		start_ccb->ccb_h.ccb_type = SG_CCB_WAITING;
339 		SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
340 				  periph_links.sle);
341 		periph->immediate_priority = CAM_PRIORITY_NONE;
342 		wakeup(&periph->ccb_list);
343 		break;
344 	}
345 }
346 
347 static void
348 sgdone(struct cam_periph *periph, union ccb *done_ccb)
349 {
350 	struct sg_softc *softc;
351 	struct ccb_scsiio *csio;
352 
353 	softc = (struct sg_softc *)periph->softc;
354 	csio = &done_ccb->csio;
355 	switch (csio->ccb_h.ccb_type) {
356 	case SG_CCB_WAITING:
357 		/* Caller will release the CCB */
358 		wakeup(&done_ccb->ccb_h.cbfcnp);
359 		return;
360 	case SG_CCB_RDWR_IO:
361 	{
362 		struct sg_rdwr *rdwr;
363 		int state;
364 
365 		devstat_end_transaction(softc->device_stats,
366 					csio->dxfer_len,
367 					csio->tag_action & 0xf,
368 					((csio->ccb_h.flags & CAM_DIR_MASK) ==
369 					CAM_DIR_NONE) ? DEVSTAT_NO_DATA :
370 					(csio->ccb_h.flags & CAM_DIR_OUT) ?
371 					DEVSTAT_WRITE : DEVSTAT_READ,
372 					NULL, NULL);
373 
374 		rdwr = done_ccb->ccb_h.ccb_rdwr;
375 		state = rdwr->state;
376 		rdwr->state = SG_RDWR_DONE;
377 		wakeup(rdwr);
378 		break;
379 	}
380 	default:
381 		panic("unknown sg CCB type");
382 	}
383 }
384 
385 static int
386 sgopen(struct cdev *dev, int flags, int fmt, struct thread *td)
387 {
388 	struct cam_periph *periph;
389 	struct sg_softc *softc;
390 	int error = 0;
391 
392 	periph = (struct cam_periph *)dev->si_drv1;
393 	if (periph == NULL)
394 		return (ENXIO);
395 
396 	/*
397 	 * Don't allow access when we're running at a high securelevel.
398 	 */
399 	error = securelevel_gt(td->td_ucred, 1);
400 	if (error)
401 		return (error);
402 
403 	cam_periph_lock(periph);
404 
405 	softc = (struct sg_softc *)periph->softc;
406 	if (softc->flags & SG_FLAG_INVALID) {
407 		cam_periph_unlock(periph);
408 		return (ENXIO);
409 	}
410 
411 	if ((softc->flags & SG_FLAG_OPEN) == 0) {
412 		softc->flags |= SG_FLAG_OPEN;
413 		cam_periph_unlock(periph);
414 	} else {
415 		/* Device closes aren't symmetrical, fix up the refcount. */
416 		cam_periph_unlock(periph);
417 		cam_periph_release(periph);
418 	}
419 
420 	return (error);
421 }
422 
423 static int
424 sgclose(struct cdev *dev, int flag, int fmt, struct thread *td)
425 {
426 	struct cam_periph *periph;
427 	struct sg_softc *softc;
428 
429 	periph = (struct cam_periph *)dev->si_drv1;
430 	if (periph == NULL)
431 		return (ENXIO);
432 
433 	cam_periph_lock(periph);
434 
435 	softc = (struct sg_softc *)periph->softc;
436 	softc->flags &= ~SG_FLAG_OPEN;
437 
438 	cam_periph_unlock(periph);
439 	cam_periph_release(periph);
440 
441 	return (0);
442 }
443 
444 static int
445 sgioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td)
446 {
447 	union ccb *ccb;
448 	struct ccb_scsiio *csio;
449 	struct cam_periph *periph;
450 	struct sg_softc *softc;
451 	struct sg_io_hdr req;
452 	int dir, error;
453 
454 	periph = (struct cam_periph *)dev->si_drv1;
455 	if (periph == NULL)
456 		return (ENXIO);
457 
458 	cam_periph_lock(periph);
459 
460 	softc = (struct sg_softc *)periph->softc;
461 	error = 0;
462 
463 	switch (cmd) {
464 	case LINUX_SCSI_GET_BUS_NUMBER: {
465 		int busno;
466 
467 		busno = xpt_path_path_id(periph->path);
468 		error = copyout(&busno, arg, sizeof(busno));
469 		break;
470 	}
471 	case LINUX_SCSI_GET_IDLUN: {
472 		struct scsi_idlun idlun;
473 		struct cam_sim *sim;
474 
475 		idlun.dev_id = xpt_path_target_id(periph->path);
476 		sim = xpt_path_sim(periph->path);
477 		idlun.host_unique_id = sim->unit_number;
478 		error = copyout(&idlun, arg, sizeof(idlun));
479 		break;
480 	}
481 	case SG_GET_VERSION_NUM:
482 	case LINUX_SG_GET_VERSION_NUM:
483 		error = copyout(&sg_version, arg, sizeof(sg_version));
484 		break;
485 	case SG_SET_TIMEOUT:
486 	case LINUX_SG_SET_TIMEOUT: {
487 		u_int user_timeout;
488 
489 		error = copyin(arg, &user_timeout, sizeof(u_int));
490 		if (error == 0) {
491 			softc->sg_user_timeout = user_timeout;
492 			softc->sg_timeout = user_timeout / SG_DEFAULT_HZ * hz;
493 		}
494 		break;
495 	}
496 	case SG_GET_TIMEOUT:
497 	case LINUX_SG_GET_TIMEOUT:
498 		/*
499 		 * The value is returned directly to the syscall.
500 		 */
501 		td->td_retval[0] = softc->sg_user_timeout;
502 		error = 0;
503 		break;
504 	case SG_IO:
505 	case LINUX_SG_IO:
506 		error = copyin(arg, &req, sizeof(req));
507 		if (error)
508 			break;
509 
510 		if (req.cmd_len > IOCDBLEN) {
511 			error = EINVAL;
512 			break;
513 		}
514 
515 		if (req.iovec_count != 0) {
516 			error = EOPNOTSUPP;
517 			break;
518 		}
519 
520 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
521 		csio = &ccb->csio;
522 
523 		error = copyin(req.cmdp, &csio->cdb_io.cdb_bytes,
524 		    req.cmd_len);
525 		if (error) {
526 			xpt_release_ccb(ccb);
527 			break;
528 		}
529 
530 		switch(req.dxfer_direction) {
531 		case SG_DXFER_TO_DEV:
532 			dir = CAM_DIR_OUT;
533 			break;
534 		case SG_DXFER_FROM_DEV:
535 			dir = CAM_DIR_IN;
536 			break;
537 		case SG_DXFER_TO_FROM_DEV:
538 			dir = CAM_DIR_IN | CAM_DIR_OUT;
539 			break;
540 		case SG_DXFER_NONE:
541 		default:
542 			dir = CAM_DIR_NONE;
543 			break;
544 		}
545 
546 		cam_fill_csio(csio,
547 			      /*retries*/1,
548 			      sgdone,
549 			      dir|CAM_DEV_QFRZDIS,
550 			      MSG_SIMPLE_Q_TAG,
551 			      req.dxferp,
552 			      req.dxfer_len,
553 			      req.mx_sb_len,
554 			      req.cmd_len,
555 			      req.timeout);
556 
557 		error = sgsendccb(periph, ccb);
558 		if (error) {
559 			req.host_status = DID_ERROR;
560 			req.driver_status = DRIVER_INVALID;
561 			xpt_release_ccb(ccb);
562 			break;
563 		}
564 
565 		req.status = csio->scsi_status;
566 		req.masked_status = (csio->scsi_status >> 1) & 0x7f;
567 		sg_scsiio_status(csio, &req.host_status, &req.driver_status);
568 		req.resid = csio->resid;
569 		req.duration = csio->ccb_h.timeout;
570 		req.info = 0;
571 
572 		error = copyout(&req, arg, sizeof(req));
573 		if ((error == 0) && (csio->ccb_h.status & CAM_AUTOSNS_VALID)
574 		    && (req.sbp != NULL)) {
575 			req.sb_len_wr = req.mx_sb_len - csio->sense_resid;
576 			error = copyout(&csio->sense_data, req.sbp,
577 					req.sb_len_wr);
578 		}
579 
580 		xpt_release_ccb(ccb);
581 		break;
582 
583 	case SG_GET_RESERVED_SIZE:
584 	case LINUX_SG_GET_RESERVED_SIZE: {
585 		int size = 32768;
586 
587 		error = copyout(&size, arg, sizeof(size));
588 		break;
589 	}
590 
591 	case SG_GET_SCSI_ID:
592 	case LINUX_SG_GET_SCSI_ID:
593 	{
594 		struct sg_scsi_id id;
595 
596 		id.host_no = cam_sim_path(xpt_path_sim(periph->path));
597 		id.channel = xpt_path_path_id(periph->path);
598 		id.scsi_id = xpt_path_target_id(periph->path);
599 		id.lun = xpt_path_lun_id(periph->path);
600 		id.scsi_type = softc->pd_type;
601 		id.h_cmd_per_lun = 1;
602 		id.d_queue_depth = 1;
603 		id.unused[0] = 0;
604 		id.unused[1] = 0;
605 
606 		error = copyout(&id, arg, sizeof(id));
607 		break;
608 	}
609 
610 	case SG_EMULATED_HOST:
611 	case SG_SET_TRANSFORM:
612 	case SG_GET_TRANSFORM:
613 	case SG_GET_NUM_WAITING:
614 	case SG_SCSI_RESET:
615 	case SG_GET_REQUEST_TABLE:
616 	case SG_SET_KEEP_ORPHAN:
617 	case SG_GET_KEEP_ORPHAN:
618 	case SG_GET_ACCESS_COUNT:
619 	case SG_SET_FORCE_LOW_DMA:
620 	case SG_GET_LOW_DMA:
621 	case SG_GET_SG_TABLESIZE:
622 	case SG_SET_FORCE_PACK_ID:
623 	case SG_GET_PACK_ID:
624 	case SG_SET_RESERVED_SIZE:
625 	case SG_GET_COMMAND_Q:
626 	case SG_SET_COMMAND_Q:
627 	case SG_SET_DEBUG:
628 	case SG_NEXT_CMD_LEN:
629 	case LINUX_SG_EMULATED_HOST:
630 	case LINUX_SG_SET_TRANSFORM:
631 	case LINUX_SG_GET_TRANSFORM:
632 	case LINUX_SG_GET_NUM_WAITING:
633 	case LINUX_SG_SCSI_RESET:
634 	case LINUX_SG_GET_REQUEST_TABLE:
635 	case LINUX_SG_SET_KEEP_ORPHAN:
636 	case LINUX_SG_GET_KEEP_ORPHAN:
637 	case LINUX_SG_GET_ACCESS_COUNT:
638 	case LINUX_SG_SET_FORCE_LOW_DMA:
639 	case LINUX_SG_GET_LOW_DMA:
640 	case LINUX_SG_GET_SG_TABLESIZE:
641 	case LINUX_SG_SET_FORCE_PACK_ID:
642 	case LINUX_SG_GET_PACK_ID:
643 	case LINUX_SG_SET_RESERVED_SIZE:
644 	case LINUX_SG_GET_COMMAND_Q:
645 	case LINUX_SG_SET_COMMAND_Q:
646 	case LINUX_SG_SET_DEBUG:
647 	case LINUX_SG_NEXT_CMD_LEN:
648 	default:
649 #ifdef CAMDEBUG
650 		printf("sgioctl: rejecting cmd 0x%lx\n", cmd);
651 #endif
652 		error = ENODEV;
653 		break;
654 	}
655 
656 	cam_periph_unlock(periph);
657 	return (error);
658 }
659 
660 static int
661 sgwrite(struct cdev *dev, struct uio *uio, int ioflag)
662 {
663 	union ccb *ccb;
664 	struct cam_periph *periph;
665 	struct ccb_scsiio *csio;
666 	struct sg_softc *sc;
667 	struct sg_header *hdr;
668 	struct sg_rdwr *rdwr;
669 	u_char cdb_cmd;
670 	char *buf;
671 	int error = 0, cdb_len, buf_len, dir;
672 
673 	periph = dev->si_drv1;
674 	rdwr = malloc(sizeof(*rdwr), M_DEVBUF, M_WAITOK | M_ZERO);
675 	hdr = &rdwr->hdr.hdr;
676 
677 	/* Copy in the header block and sanity check it */
678 	if (uio->uio_resid < sizeof(*hdr)) {
679 		error = EINVAL;
680 		goto out_hdr;
681 	}
682 	error = uiomove(hdr, sizeof(*hdr), uio);
683 	if (error)
684 		goto out_hdr;
685 
686 	ccb = xpt_alloc_ccb();
687 	if (ccb == NULL) {
688 		error = ENOMEM;
689 		goto out_hdr;
690 	}
691 	csio = &ccb->csio;
692 
693 	/*
694 	 * Copy in the CDB block.  The designers of the interface didn't
695 	 * bother to provide a size for this in the header, so we have to
696 	 * figure it out ourselves.
697 	 */
698 	if (uio->uio_resid < 1)
699 		goto out_ccb;
700 	error = uiomove(&cdb_cmd, 1, uio);
701 	if (error)
702 		goto out_ccb;
703 	if (hdr->twelve_byte)
704 		cdb_len = 12;
705 	else
706 		cdb_len = scsi_group_len(cdb_cmd);
707 	/*
708 	 * We've already read the first byte of the CDB and advanced the uio
709 	 * pointer.  Just read the rest.
710 	 */
711 	csio->cdb_io.cdb_bytes[0] = cdb_cmd;
712 	error = uiomove(&csio->cdb_io.cdb_bytes[1], cdb_len - 1, uio);
713 	if (error)
714 		goto out_ccb;
715 
716 	/*
717 	 * Now set up the data block.  Again, the designers didn't bother
718 	 * to make this reliable.
719 	 */
720 	buf_len = uio->uio_resid;
721 	if (buf_len != 0) {
722 		buf = malloc(buf_len, M_DEVBUF, M_WAITOK | M_ZERO);
723 		error = uiomove(buf, buf_len, uio);
724 		if (error)
725 			goto out_buf;
726 		dir = CAM_DIR_OUT;
727 	} else if (hdr->reply_len != 0) {
728 		buf = malloc(hdr->reply_len, M_DEVBUF, M_WAITOK | M_ZERO);
729 		buf_len = hdr->reply_len;
730 		dir = CAM_DIR_IN;
731 	} else {
732 		buf = NULL;
733 		buf_len = 0;
734 		dir = CAM_DIR_NONE;
735 	}
736 
737 	cam_periph_lock(periph);
738 	sc = periph->softc;
739 	xpt_setup_ccb(&ccb->ccb_h, periph->path, CAM_PRIORITY_NORMAL);
740 	cam_fill_csio(csio,
741 		      /*retries*/1,
742 		      sgdone,
743 		      dir|CAM_DEV_QFRZDIS,
744 		      MSG_SIMPLE_Q_TAG,
745 		      buf,
746 		      buf_len,
747 		      SG_MAX_SENSE,
748 		      cdb_len,
749 		      sc->sg_timeout);
750 
751 	/*
752 	 * Send off the command and hope that it works. This path does not
753 	 * go through sgstart because the I/O is supposed to be asynchronous.
754 	 */
755 	rdwr->buf = buf;
756 	rdwr->buf_len = buf_len;
757 	rdwr->tag = hdr->pack_id;
758 	rdwr->ccb = ccb;
759 	rdwr->state = SG_RDWR_INPROG;
760 	ccb->ccb_h.ccb_rdwr = rdwr;
761 	ccb->ccb_h.ccb_type = SG_CCB_RDWR_IO;
762 	TAILQ_INSERT_TAIL(&sc->rdwr_done, rdwr, rdwr_link);
763 	error = sgsendrdwr(periph, ccb);
764 	cam_periph_unlock(periph);
765 	return (error);
766 
767 out_buf:
768 	free(buf, M_DEVBUF);
769 out_ccb:
770 	xpt_free_ccb(ccb);
771 out_hdr:
772 	free(rdwr, M_DEVBUF);
773 	return (error);
774 }
775 
776 static int
777 sgread(struct cdev *dev, struct uio *uio, int ioflag)
778 {
779 	struct ccb_scsiio *csio;
780 	struct cam_periph *periph;
781 	struct sg_softc *sc;
782 	struct sg_header *hdr;
783 	struct sg_rdwr *rdwr;
784 	u_short hstat, dstat;
785 	int error, pack_len, reply_len, pack_id;
786 
787 	periph = dev->si_drv1;
788 
789 	/* XXX The pack len field needs to be updated and written out instead
790 	 * of discarded.  Not sure how to do that.
791 	 */
792 	uio->uio_rw = UIO_WRITE;
793 	if ((error = uiomove(&pack_len, 4, uio)) != 0)
794 		return (error);
795 	if ((error = uiomove(&reply_len, 4, uio)) != 0)
796 		return (error);
797 	if ((error = uiomove(&pack_id, 4, uio)) != 0)
798 		return (error);
799 	uio->uio_rw = UIO_READ;
800 
801 	cam_periph_lock(periph);
802 	sc = periph->softc;
803 search:
804 	TAILQ_FOREACH(rdwr, &sc->rdwr_done, rdwr_link) {
805 		if (rdwr->tag == pack_id)
806 			break;
807 	}
808 	if ((rdwr == NULL) || (rdwr->state != SG_RDWR_DONE)) {
809 		if (msleep(rdwr, periph->sim->mtx, PCATCH, "sgread", 0) == ERESTART)
810 			return (EAGAIN);
811 		goto search;
812 	}
813 	TAILQ_REMOVE(&sc->rdwr_done, rdwr, rdwr_link);
814 	cam_periph_unlock(periph);
815 
816 	hdr = &rdwr->hdr.hdr;
817 	csio = &rdwr->ccb->csio;
818 	sg_scsiio_status(csio, &hstat, &dstat);
819 	hdr->host_status = hstat;
820 	hdr->driver_status = dstat;
821 	hdr->target_status = csio->scsi_status >> 1;
822 
823 	switch (hstat) {
824 	case DID_OK:
825 	case DID_PASSTHROUGH:
826 	case DID_SOFT_ERROR:
827 		hdr->result = 0;
828 		break;
829 	case DID_NO_CONNECT:
830 	case DID_BUS_BUSY:
831 	case DID_TIME_OUT:
832 		hdr->result = EBUSY;
833 		break;
834 	case DID_BAD_TARGET:
835 	case DID_ABORT:
836 	case DID_PARITY:
837 	case DID_RESET:
838 	case DID_BAD_INTR:
839 	case DID_ERROR:
840 	default:
841 		hdr->result = EIO;
842 		break;
843 	}
844 
845 	if (dstat == DRIVER_SENSE) {
846 		bcopy(&csio->sense_data, hdr->sense_buffer,
847 		      min(csio->sense_len, SG_MAX_SENSE));
848 #ifdef CAMDEBUG
849 		scsi_sense_print(csio);
850 #endif
851 	}
852 
853 	error = uiomove(&hdr->result, sizeof(*hdr) -
854 			offsetof(struct sg_header, result), uio);
855 	if ((error == 0) && (hdr->result == 0))
856 		error = uiomove(rdwr->buf, rdwr->buf_len, uio);
857 
858 	cam_periph_lock(periph);
859 	xpt_free_ccb(rdwr->ccb);
860 	cam_periph_unlock(periph);
861 	free(rdwr->buf, M_DEVBUF);
862 	free(rdwr, M_DEVBUF);
863 	return (error);
864 }
865 
866 static int
867 sgsendccb(struct cam_periph *periph, union ccb *ccb)
868 {
869 	struct sg_softc *softc;
870 	struct cam_periph_map_info mapinfo;
871 	int error, need_unmap = 0;
872 
873 	softc = periph->softc;
874 	if (((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE)
875 	    && (ccb->csio.data_ptr != NULL)) {
876 		bzero(&mapinfo, sizeof(mapinfo));
877 
878 		/*
879 		 * cam_periph_mapmem calls into proc and vm functions that can
880 		 * sleep as well as trigger I/O, so we can't hold the lock.
881 		 * Dropping it here is reasonably safe.
882 		 */
883 		cam_periph_unlock(periph);
884 		error = cam_periph_mapmem(ccb, &mapinfo);
885 		cam_periph_lock(periph);
886 		if (error)
887 			return (error);
888 		need_unmap = 1;
889 	}
890 
891 	error = cam_periph_runccb(ccb,
892 				  sgerror,
893 				  CAM_RETRY_SELTO,
894 				  SF_RETRY_UA,
895 				  softc->device_stats);
896 
897 	if (need_unmap)
898 		cam_periph_unmapmem(ccb, &mapinfo);
899 
900 	return (error);
901 }
902 
903 static int
904 sgsendrdwr(struct cam_periph *periph, union ccb *ccb)
905 {
906 	struct sg_softc *softc;
907 
908 	softc = periph->softc;
909 	devstat_start_transaction(softc->device_stats, NULL);
910 	xpt_action(ccb);
911 	return (0);
912 }
913 
914 static int
915 sgerror(union ccb *ccb, uint32_t cam_flags, uint32_t sense_flags)
916 {
917 	struct cam_periph *periph;
918 	struct sg_softc *softc;
919 
920 	periph = xpt_path_periph(ccb->ccb_h.path);
921 	softc = (struct sg_softc *)periph->softc;
922 
923 	return (cam_periph_error(ccb, cam_flags, sense_flags,
924 				 &softc->saved_ccb));
925 }
926 
927 static void
928 sg_scsiio_status(struct ccb_scsiio *csio, u_short *hoststat, u_short *drvstat)
929 {
930 	int status;
931 
932 	status = csio->ccb_h.status;
933 
934 	switch (status & CAM_STATUS_MASK) {
935 	case CAM_REQ_CMP:
936 		*hoststat = DID_OK;
937 		*drvstat = 0;
938 		break;
939 	case CAM_REQ_CMP_ERR:
940 		*hoststat = DID_ERROR;
941 		*drvstat = 0;
942 		break;
943 	case CAM_REQ_ABORTED:
944 		*hoststat = DID_ABORT;
945 		*drvstat = 0;
946 		break;
947 	case CAM_REQ_INVALID:
948 		*hoststat = DID_ERROR;
949 		*drvstat = DRIVER_INVALID;
950 		break;
951 	case CAM_DEV_NOT_THERE:
952 		*hoststat = DID_BAD_TARGET;
953 		*drvstat = 0;
954 		break;
955 	case CAM_SEL_TIMEOUT:
956 		*hoststat = DID_NO_CONNECT;
957 		*drvstat = 0;
958 		break;
959 	case CAM_CMD_TIMEOUT:
960 		*hoststat = DID_TIME_OUT;
961 		*drvstat = 0;
962 		break;
963 	case CAM_SCSI_STATUS_ERROR:
964 		*hoststat = DID_ERROR;
965 		*drvstat = 0;
966 		break;
967 	case CAM_SCSI_BUS_RESET:
968 		*hoststat = DID_RESET;
969 		*drvstat = 0;
970 		break;
971 	case CAM_UNCOR_PARITY:
972 		*hoststat = DID_PARITY;
973 		*drvstat = 0;
974 		break;
975 	case CAM_SCSI_BUSY:
976 		*hoststat = DID_BUS_BUSY;
977 		*drvstat = 0;
978 		break;
979 	default:
980 		*hoststat = DID_ERROR;
981 		*drvstat = DRIVER_ERROR;
982 	}
983 
984 	if (status & CAM_AUTOSNS_VALID)
985 		*drvstat = DRIVER_SENSE;
986 }
987 
988 static int
989 scsi_group_len(u_char cmd)
990 {
991 	int len[] = {6, 10, 10, 12, 12, 12, 10, 10};
992 	int group;
993 
994 	group = (cmd >> 5) & 0x7;
995 	return (len[group]);
996 }
997 
998