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