xref: /freebsd/sys/cam/scsi/scsi_sg.c (revision 830940567b49bb0c08dfaed40418999e76616909)
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 	(void)make_dev_alias(softc->dev, "sg%c", 'a' + periph->unit_number);
307 	cam_periph_lock(periph);
308 	softc->dev->si_drv1 = periph;
309 
310 	/*
311 	 * Add as async callback so that we get
312 	 * notified if this device goes away.
313 	 */
314 	xpt_register_async(AC_LOST_DEVICE, sgasync, periph, periph->path);
315 
316 	if (bootverbose)
317 		xpt_announce_periph(periph, NULL);
318 
319 	return (CAM_REQ_CMP);
320 }
321 
322 static void
323 sgstart(struct cam_periph *periph, union ccb *start_ccb)
324 {
325 	struct sg_softc *softc;
326 
327 	softc = (struct sg_softc *)periph->softc;
328 
329 	switch (softc->state) {
330 	case SG_STATE_NORMAL:
331 		start_ccb->ccb_h.ccb_type = SG_CCB_WAITING;
332 		SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
333 				  periph_links.sle);
334 		periph->immediate_priority = CAM_PRIORITY_NONE;
335 		wakeup(&periph->ccb_list);
336 		break;
337 	}
338 }
339 
340 static void
341 sgdone(struct cam_periph *periph, union ccb *done_ccb)
342 {
343 	struct sg_softc *softc;
344 	struct ccb_scsiio *csio;
345 
346 	softc = (struct sg_softc *)periph->softc;
347 	csio = &done_ccb->csio;
348 	switch (csio->ccb_h.ccb_type) {
349 	case SG_CCB_WAITING:
350 		/* Caller will release the CCB */
351 		wakeup(&done_ccb->ccb_h.cbfcnp);
352 		return;
353 	case SG_CCB_RDWR_IO:
354 	{
355 		struct sg_rdwr *rdwr;
356 		int state;
357 
358 		devstat_end_transaction(softc->device_stats,
359 					csio->dxfer_len,
360 					csio->tag_action & 0xf,
361 					((csio->ccb_h.flags & CAM_DIR_MASK) ==
362 					CAM_DIR_NONE) ? DEVSTAT_NO_DATA :
363 					(csio->ccb_h.flags & CAM_DIR_OUT) ?
364 					DEVSTAT_WRITE : DEVSTAT_READ,
365 					NULL, NULL);
366 
367 		rdwr = done_ccb->ccb_h.ccb_rdwr;
368 		state = rdwr->state;
369 		rdwr->state = SG_RDWR_DONE;
370 		wakeup(rdwr);
371 		break;
372 	}
373 	default:
374 		panic("unknown sg CCB type");
375 	}
376 }
377 
378 static int
379 sgopen(struct cdev *dev, int flags, int fmt, struct thread *td)
380 {
381 	struct cam_periph *periph;
382 	struct sg_softc *softc;
383 	int error = 0;
384 
385 	periph = (struct cam_periph *)dev->si_drv1;
386 	if (periph == NULL)
387 		return (ENXIO);
388 
389 	/*
390 	 * Don't allow access when we're running at a high securelevel.
391 	 */
392 	error = securelevel_gt(td->td_ucred, 1);
393 	if (error)
394 		return (error);
395 
396 	cam_periph_lock(periph);
397 
398 	softc = (struct sg_softc *)periph->softc;
399 	if (softc->flags & SG_FLAG_INVALID) {
400 		cam_periph_unlock(periph);
401 		return (ENXIO);
402 	}
403 
404 	if ((softc->flags & SG_FLAG_OPEN) == 0) {
405 		softc->flags |= SG_FLAG_OPEN;
406 		cam_periph_unlock(periph);
407 	} else {
408 		/* Device closes aren't symmetrical, fix up the refcount. */
409 		cam_periph_unlock(periph);
410 		cam_periph_release(periph);
411 	}
412 
413 	return (error);
414 }
415 
416 static int
417 sgclose(struct cdev *dev, int flag, int fmt, struct thread *td)
418 {
419 	struct cam_periph *periph;
420 	struct sg_softc *softc;
421 
422 	periph = (struct cam_periph *)dev->si_drv1;
423 	if (periph == NULL)
424 		return (ENXIO);
425 
426 	cam_periph_lock(periph);
427 
428 	softc = (struct sg_softc *)periph->softc;
429 	softc->flags &= ~SG_FLAG_OPEN;
430 
431 	cam_periph_unlock(periph);
432 	cam_periph_release(periph);
433 
434 	return (0);
435 }
436 
437 static int
438 sgioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td)
439 {
440 	union ccb *ccb;
441 	struct ccb_scsiio *csio;
442 	struct cam_periph *periph;
443 	struct sg_softc *softc;
444 	struct sg_io_hdr req;
445 	int dir, error;
446 
447 	periph = (struct cam_periph *)dev->si_drv1;
448 	if (periph == NULL)
449 		return (ENXIO);
450 
451 	cam_periph_lock(periph);
452 
453 	softc = (struct sg_softc *)periph->softc;
454 	error = 0;
455 
456 	switch (cmd) {
457 	case LINUX_SCSI_GET_BUS_NUMBER: {
458 		int busno;
459 
460 		busno = xpt_path_path_id(periph->path);
461 		error = copyout(&busno, arg, sizeof(busno));
462 		break;
463 	}
464 	case LINUX_SCSI_GET_IDLUN: {
465 		struct scsi_idlun idlun;
466 		struct cam_sim *sim;
467 
468 		idlun.dev_id = xpt_path_target_id(periph->path);
469 		sim = xpt_path_sim(periph->path);
470 		idlun.host_unique_id = sim->unit_number;
471 		error = copyout(&idlun, arg, sizeof(idlun));
472 		break;
473 	}
474 	case SG_GET_VERSION_NUM:
475 	case LINUX_SG_GET_VERSION_NUM:
476 		error = copyout(&sg_version, arg, sizeof(sg_version));
477 		break;
478 	case SG_SET_TIMEOUT:
479 	case LINUX_SG_SET_TIMEOUT: {
480 		u_int user_timeout;
481 
482 		error = copyin(arg, &user_timeout, sizeof(u_int));
483 		if (error == 0) {
484 			softc->sg_user_timeout = user_timeout;
485 			softc->sg_timeout = user_timeout / SG_DEFAULT_HZ * hz;
486 		}
487 		break;
488 	}
489 	case SG_GET_TIMEOUT:
490 	case LINUX_SG_GET_TIMEOUT:
491 		/*
492 		 * The value is returned directly to the syscall.
493 		 */
494 		td->td_retval[0] = softc->sg_user_timeout;
495 		error = 0;
496 		break;
497 	case SG_IO:
498 	case LINUX_SG_IO:
499 		error = copyin(arg, &req, sizeof(req));
500 		if (error)
501 			break;
502 
503 		if (req.cmd_len > IOCDBLEN) {
504 			error = EINVAL;
505 			break;
506 		}
507 
508 		if (req.iovec_count != 0) {
509 			error = EOPNOTSUPP;
510 			break;
511 		}
512 
513 		ccb = cam_periph_getccb(periph, /*priority*/5);
514 		csio = &ccb->csio;
515 
516 		error = copyin(req.cmdp, &csio->cdb_io.cdb_bytes,
517 		    req.cmd_len);
518 		if (error) {
519 			xpt_release_ccb(ccb);
520 			break;
521 		}
522 
523 		switch(req.dxfer_direction) {
524 		case SG_DXFER_TO_DEV:
525 			dir = CAM_DIR_OUT;
526 			break;
527 		case SG_DXFER_FROM_DEV:
528 			dir = CAM_DIR_IN;
529 			break;
530 		case SG_DXFER_TO_FROM_DEV:
531 			dir = CAM_DIR_IN | CAM_DIR_OUT;
532 			break;
533 		case SG_DXFER_NONE:
534 		default:
535 			dir = CAM_DIR_NONE;
536 			break;
537 		}
538 
539 		cam_fill_csio(csio,
540 			      /*retries*/1,
541 			      sgdone,
542 			      dir|CAM_DEV_QFRZDIS,
543 			      MSG_SIMPLE_Q_TAG,
544 			      req.dxferp,
545 			      req.dxfer_len,
546 			      req.mx_sb_len,
547 			      req.cmd_len,
548 			      req.timeout);
549 
550 		error = sgsendccb(periph, ccb);
551 		if (error) {
552 			req.host_status = DID_ERROR;
553 			req.driver_status = DRIVER_INVALID;
554 			xpt_release_ccb(ccb);
555 			break;
556 		}
557 
558 		req.status = csio->scsi_status;
559 		req.masked_status = (csio->scsi_status >> 1) & 0x7f;
560 		sg_scsiio_status(csio, &req.host_status, &req.driver_status);
561 		req.resid = csio->resid;
562 		req.duration = csio->ccb_h.timeout;
563 		req.info = 0;
564 
565 		error = copyout(&req, arg, sizeof(req));
566 		if ((error == 0) && (csio->ccb_h.status & CAM_AUTOSNS_VALID)
567 		    && (req.sbp != NULL)) {
568 			req.sb_len_wr = req.mx_sb_len - csio->sense_resid;
569 			error = copyout(&csio->sense_data, req.sbp,
570 					req.sb_len_wr);
571 		}
572 
573 		xpt_release_ccb(ccb);
574 		break;
575 
576 	case SG_GET_RESERVED_SIZE:
577 	case LINUX_SG_GET_RESERVED_SIZE: {
578 		int size = 32768;
579 
580 		error = copyout(&size, arg, sizeof(size));
581 		break;
582 	}
583 
584 	case SG_GET_SCSI_ID:
585 	case LINUX_SG_GET_SCSI_ID:
586 	{
587 		struct sg_scsi_id id;
588 
589 		id.host_no = 0; /* XXX */
590 		id.channel = xpt_path_path_id(periph->path);
591 		id.scsi_id = xpt_path_target_id(periph->path);
592 		id.lun = xpt_path_lun_id(periph->path);
593 		id.scsi_type = softc->pd_type;
594 		id.h_cmd_per_lun = 1;
595 		id.d_queue_depth = 1;
596 		id.unused[0] = 0;
597 		id.unused[1] = 0;
598 
599 		error = copyout(&id, arg, sizeof(id));
600 		break;
601 	}
602 
603 	case SG_EMULATED_HOST:
604 	case SG_SET_TRANSFORM:
605 	case SG_GET_TRANSFORM:
606 	case SG_GET_NUM_WAITING:
607 	case SG_SCSI_RESET:
608 	case SG_GET_REQUEST_TABLE:
609 	case SG_SET_KEEP_ORPHAN:
610 	case SG_GET_KEEP_ORPHAN:
611 	case SG_GET_ACCESS_COUNT:
612 	case SG_SET_FORCE_LOW_DMA:
613 	case SG_GET_LOW_DMA:
614 	case SG_GET_SG_TABLESIZE:
615 	case SG_SET_FORCE_PACK_ID:
616 	case SG_GET_PACK_ID:
617 	case SG_SET_RESERVED_SIZE:
618 	case SG_GET_COMMAND_Q:
619 	case SG_SET_COMMAND_Q:
620 	case SG_SET_DEBUG:
621 	case SG_NEXT_CMD_LEN:
622 	case LINUX_SG_EMULATED_HOST:
623 	case LINUX_SG_SET_TRANSFORM:
624 	case LINUX_SG_GET_TRANSFORM:
625 	case LINUX_SG_GET_NUM_WAITING:
626 	case LINUX_SG_SCSI_RESET:
627 	case LINUX_SG_GET_REQUEST_TABLE:
628 	case LINUX_SG_SET_KEEP_ORPHAN:
629 	case LINUX_SG_GET_KEEP_ORPHAN:
630 	case LINUX_SG_GET_ACCESS_COUNT:
631 	case LINUX_SG_SET_FORCE_LOW_DMA:
632 	case LINUX_SG_GET_LOW_DMA:
633 	case LINUX_SG_GET_SG_TABLESIZE:
634 	case LINUX_SG_SET_FORCE_PACK_ID:
635 	case LINUX_SG_GET_PACK_ID:
636 	case LINUX_SG_SET_RESERVED_SIZE:
637 	case LINUX_SG_GET_COMMAND_Q:
638 	case LINUX_SG_SET_COMMAND_Q:
639 	case LINUX_SG_SET_DEBUG:
640 	case LINUX_SG_NEXT_CMD_LEN:
641 	default:
642 #ifdef CAMDEBUG
643 		printf("sgioctl: rejecting cmd 0x%lx\n", cmd);
644 #endif
645 		error = ENODEV;
646 		break;
647 	}
648 
649 	cam_periph_unlock(periph);
650 	return (error);
651 }
652 
653 static int
654 sgwrite(struct cdev *dev, struct uio *uio, int ioflag)
655 {
656 	union ccb *ccb;
657 	struct cam_periph *periph;
658 	struct ccb_scsiio *csio;
659 	struct sg_softc *sc;
660 	struct sg_header *hdr;
661 	struct sg_rdwr *rdwr;
662 	u_char cdb_cmd;
663 	char *buf;
664 	int error = 0, cdb_len, buf_len, dir;
665 
666 	periph = dev->si_drv1;
667 	rdwr = malloc(sizeof(*rdwr), M_DEVBUF, M_WAITOK | M_ZERO);
668 	hdr = &rdwr->hdr.hdr;
669 
670 	/* Copy in the header block and sanity check it */
671 	if (uio->uio_resid < sizeof(*hdr)) {
672 		error = EINVAL;
673 		goto out_hdr;
674 	}
675 	error = uiomove(hdr, sizeof(*hdr), uio);
676 	if (error)
677 		goto out_hdr;
678 
679 	ccb = xpt_alloc_ccb();
680 	if (ccb == NULL) {
681 		error = ENOMEM;
682 		goto out_hdr;
683 	}
684 	csio = &ccb->csio;
685 
686 	/*
687 	 * Copy in the CDB block.  The designers of the interface didn't
688 	 * bother to provide a size for this in the header, so we have to
689 	 * figure it out ourselves.
690 	 */
691 	if (uio->uio_resid < 1)
692 		goto out_ccb;
693 	error = uiomove(&cdb_cmd, 1, uio);
694 	if (error)
695 		goto out_ccb;
696 	if (hdr->twelve_byte)
697 		cdb_len = 12;
698 	else
699 		cdb_len = scsi_group_len(cdb_cmd);
700 	/*
701 	 * We've already read the first byte of the CDB and advanced the uio
702 	 * pointer.  Just read the rest.
703 	 */
704 	csio->cdb_io.cdb_bytes[0] = cdb_cmd;
705 	error = uiomove(&csio->cdb_io.cdb_bytes[1], cdb_len - 1, uio);
706 	if (error)
707 		goto out_ccb;
708 
709 	/*
710 	 * Now set up the data block.  Again, the designers didn't bother
711 	 * to make this reliable.
712 	 */
713 	buf_len = uio->uio_resid;
714 	if (buf_len != 0) {
715 		buf = malloc(buf_len, M_DEVBUF, M_WAITOK | M_ZERO);
716 		error = uiomove(buf, buf_len, uio);
717 		if (error)
718 			goto out_buf;
719 		dir = CAM_DIR_OUT;
720 	} else if (hdr->reply_len != 0) {
721 		buf = malloc(hdr->reply_len, M_DEVBUF, M_WAITOK | M_ZERO);
722 		buf_len = hdr->reply_len;
723 		dir = CAM_DIR_IN;
724 	} else {
725 		buf = NULL;
726 		buf_len = 0;
727 		dir = CAM_DIR_NONE;
728 	}
729 
730 	cam_periph_lock(periph);
731 	sc = periph->softc;
732 	xpt_setup_ccb(&ccb->ccb_h, periph->path, /*priority*/5);
733 	cam_fill_csio(csio,
734 		      /*retries*/1,
735 		      sgdone,
736 		      dir|CAM_DEV_QFRZDIS,
737 		      MSG_SIMPLE_Q_TAG,
738 		      buf,
739 		      buf_len,
740 		      SG_MAX_SENSE,
741 		      cdb_len,
742 		      sc->sg_timeout);
743 
744 	/*
745 	 * Send off the command and hope that it works. This path does not
746 	 * go through sgstart because the I/O is supposed to be asynchronous.
747 	 */
748 	rdwr->buf = buf;
749 	rdwr->buf_len = buf_len;
750 	rdwr->tag = hdr->pack_id;
751 	rdwr->ccb = ccb;
752 	rdwr->state = SG_RDWR_INPROG;
753 	ccb->ccb_h.ccb_rdwr = rdwr;
754 	ccb->ccb_h.ccb_type = SG_CCB_RDWR_IO;
755 	TAILQ_INSERT_TAIL(&sc->rdwr_done, rdwr, rdwr_link);
756 	error = sgsendrdwr(periph, ccb);
757 	cam_periph_unlock(periph);
758 	return (error);
759 
760 out_buf:
761 	free(buf, M_DEVBUF);
762 out_ccb:
763 	xpt_free_ccb(ccb);
764 out_hdr:
765 	free(rdwr, M_DEVBUF);
766 	return (error);
767 }
768 
769 static int
770 sgread(struct cdev *dev, struct uio *uio, int ioflag)
771 {
772 	struct ccb_scsiio *csio;
773 	struct cam_periph *periph;
774 	struct sg_softc *sc;
775 	struct sg_header *hdr;
776 	struct sg_rdwr *rdwr;
777 	u_short hstat, dstat;
778 	int error, pack_len, reply_len, pack_id;
779 
780 	periph = dev->si_drv1;
781 
782 	/* XXX The pack len field needs to be updated and written out instead
783 	 * of discarded.  Not sure how to do that.
784 	 */
785 	uio->uio_rw = UIO_WRITE;
786 	if ((error = uiomove(&pack_len, 4, uio)) != 0)
787 		return (error);
788 	if ((error = uiomove(&reply_len, 4, uio)) != 0)
789 		return (error);
790 	if ((error = uiomove(&pack_id, 4, uio)) != 0)
791 		return (error);
792 	uio->uio_rw = UIO_READ;
793 
794 	cam_periph_lock(periph);
795 	sc = periph->softc;
796 search:
797 	TAILQ_FOREACH(rdwr, &sc->rdwr_done, rdwr_link) {
798 		if (rdwr->tag == pack_id)
799 			break;
800 	}
801 	if ((rdwr == NULL) || (rdwr->state != SG_RDWR_DONE)) {
802 		if (msleep(rdwr, periph->sim->mtx, PCATCH, "sgread", 0) == ERESTART)
803 			return (EAGAIN);
804 		goto search;
805 	}
806 	TAILQ_REMOVE(&sc->rdwr_done, rdwr, rdwr_link);
807 	cam_periph_unlock(periph);
808 
809 	hdr = &rdwr->hdr.hdr;
810 	csio = &rdwr->ccb->csio;
811 	sg_scsiio_status(csio, &hstat, &dstat);
812 	hdr->host_status = hstat;
813 	hdr->driver_status = dstat;
814 	hdr->target_status = csio->scsi_status >> 1;
815 
816 	switch (hstat) {
817 	case DID_OK:
818 	case DID_PASSTHROUGH:
819 	case DID_SOFT_ERROR:
820 		hdr->result = 0;
821 		break;
822 	case DID_NO_CONNECT:
823 	case DID_BUS_BUSY:
824 	case DID_TIME_OUT:
825 		hdr->result = EBUSY;
826 		break;
827 	case DID_BAD_TARGET:
828 	case DID_ABORT:
829 	case DID_PARITY:
830 	case DID_RESET:
831 	case DID_BAD_INTR:
832 	case DID_ERROR:
833 	default:
834 		hdr->result = EIO;
835 		break;
836 	}
837 
838 	if (dstat == DRIVER_SENSE) {
839 		bcopy(&csio->sense_data, hdr->sense_buffer,
840 		      min(csio->sense_len, SG_MAX_SENSE));
841 #ifdef CAMDEBUG
842 		scsi_sense_print(csio);
843 #endif
844 	}
845 
846 	error = uiomove(&hdr->result, sizeof(*hdr) -
847 			offsetof(struct sg_header, result), uio);
848 	if ((error == 0) && (hdr->result == 0))
849 		error = uiomove(rdwr->buf, rdwr->buf_len, uio);
850 
851 	cam_periph_lock(periph);
852 	xpt_free_ccb(rdwr->ccb);
853 	cam_periph_unlock(periph);
854 	free(rdwr->buf, M_DEVBUF);
855 	free(rdwr, M_DEVBUF);
856 	return (error);
857 }
858 
859 static int
860 sgsendccb(struct cam_periph *periph, union ccb *ccb)
861 {
862 	struct sg_softc *softc;
863 	struct cam_periph_map_info mapinfo;
864 	int error, need_unmap = 0;
865 
866 	softc = periph->softc;
867 	if (((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE)
868 	    && (ccb->csio.data_ptr != NULL)) {
869 		bzero(&mapinfo, sizeof(mapinfo));
870 
871 		/*
872 		 * cam_periph_mapmem calls into proc and vm functions that can
873 		 * sleep as well as trigger I/O, so we can't hold the lock.
874 		 * Dropping it here is reasonably safe.
875 		 */
876 		cam_periph_unlock(periph);
877 		error = cam_periph_mapmem(ccb, &mapinfo);
878 		cam_periph_lock(periph);
879 		if (error)
880 			return (error);
881 		need_unmap = 1;
882 	}
883 
884 	error = cam_periph_runccb(ccb,
885 				  sgerror,
886 				  CAM_RETRY_SELTO,
887 				  SF_RETRY_UA,
888 				  softc->device_stats);
889 
890 	if (need_unmap)
891 		cam_periph_unmapmem(ccb, &mapinfo);
892 
893 	return (error);
894 }
895 
896 static int
897 sgsendrdwr(struct cam_periph *periph, union ccb *ccb)
898 {
899 	struct sg_softc *softc;
900 
901 	softc = periph->softc;
902 	devstat_start_transaction(softc->device_stats, NULL);
903 	xpt_action(ccb);
904 	return (0);
905 }
906 
907 static int
908 sgerror(union ccb *ccb, uint32_t cam_flags, uint32_t sense_flags)
909 {
910 	struct cam_periph *periph;
911 	struct sg_softc *softc;
912 
913 	periph = xpt_path_periph(ccb->ccb_h.path);
914 	softc = (struct sg_softc *)periph->softc;
915 
916 	return (cam_periph_error(ccb, cam_flags, sense_flags,
917 				 &softc->saved_ccb));
918 }
919 
920 static void
921 sg_scsiio_status(struct ccb_scsiio *csio, u_short *hoststat, u_short *drvstat)
922 {
923 	int status;
924 
925 	status = csio->ccb_h.status;
926 
927 	switch (status & CAM_STATUS_MASK) {
928 	case CAM_REQ_CMP:
929 		*hoststat = DID_OK;
930 		*drvstat = 0;
931 		break;
932 	case CAM_REQ_CMP_ERR:
933 		*hoststat = DID_ERROR;
934 		*drvstat = 0;
935 		break;
936 	case CAM_REQ_ABORTED:
937 		*hoststat = DID_ABORT;
938 		*drvstat = 0;
939 		break;
940 	case CAM_REQ_INVALID:
941 		*hoststat = DID_ERROR;
942 		*drvstat = DRIVER_INVALID;
943 		break;
944 	case CAM_DEV_NOT_THERE:
945 		*hoststat = DID_BAD_TARGET;
946 		*drvstat = 0;
947 		break;
948 	case CAM_SEL_TIMEOUT:
949 		*hoststat = DID_NO_CONNECT;
950 		*drvstat = 0;
951 		break;
952 	case CAM_CMD_TIMEOUT:
953 		*hoststat = DID_TIME_OUT;
954 		*drvstat = 0;
955 		break;
956 	case CAM_SCSI_STATUS_ERROR:
957 		*hoststat = DID_ERROR;
958 		*drvstat = 0;
959 		break;
960 	case CAM_SCSI_BUS_RESET:
961 		*hoststat = DID_RESET;
962 		*drvstat = 0;
963 		break;
964 	case CAM_UNCOR_PARITY:
965 		*hoststat = DID_PARITY;
966 		*drvstat = 0;
967 		break;
968 	case CAM_SCSI_BUSY:
969 		*hoststat = DID_BUS_BUSY;
970 		*drvstat = 0;
971 		break;
972 	default:
973 		*hoststat = DID_ERROR;
974 		*drvstat = DRIVER_ERROR;
975 	}
976 
977 	if (status & CAM_AUTOSNS_VALID)
978 		*drvstat = DRIVER_SENSE;
979 }
980 
981 static int
982 scsi_group_len(u_char cmd)
983 {
984 	int len[] = {6, 10, 10, 12, 12, 12, 10, 10};
985 	int group;
986 
987 	group = (cmd >> 5) & 0x7;
988 	return (len[group]);
989 }
990 
991