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