xref: /dragonfly/sys/bus/cam/scsi/scsi_target.c (revision 8a7bdfea)
1 /*
2  * Generic SCSI Target Kernel Mode Driver
3  *
4  * Copyright (c) 2002 Nate Lawson.
5  * Copyright (c) 1998, 1999, 2001, 2002 Justin T. Gibbs.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD: src/sys/cam/scsi/scsi_target.c,v 1.22.2.7 2003/02/18 22:07:10 njl Exp $
30  * $DragonFly: src/sys/bus/cam/scsi/scsi_target.c,v 1.18 2007/11/17 20:28:46 pavalos Exp $
31  */
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/conf.h>
37 #include <sys/device.h>
38 #include <sys/malloc.h>
39 #include <sys/poll.h>
40 #include <sys/vnode.h>
41 #include <sys/devicestat.h>
42 #include <sys/thread2.h>
43 
44 #include "../cam.h"
45 #include "../cam_ccb.h"
46 #include "../cam_periph.h"
47 #include "../cam_xpt_periph.h"
48 #include "scsi_targetio.h"
49 
50 /* Transaction information attached to each CCB sent by the user */
51 struct targ_cmd_descr {
52 	struct cam_periph_map_info  mapinfo;
53 	TAILQ_ENTRY(targ_cmd_descr) tqe;
54 	union ccb *user_ccb;
55 	int	   priority;
56 	int	   func_code;
57 };
58 
59 /* Offset into the private CCB area for storing our descriptor */
60 #define targ_descr	periph_priv.entries[1].ptr
61 
62 TAILQ_HEAD(descr_queue, targ_cmd_descr);
63 
64 typedef enum {
65 	TARG_STATE_RESV		= 0x00, /* Invalid state */
66 	TARG_STATE_OPENED	= 0x01, /* Device opened, softc initialized */
67 	TARG_STATE_LUN_ENABLED	= 0x02  /* Device enabled for a path */
68 } targ_state;
69 
70 /* Per-instance device software context */
71 struct targ_softc {
72 	/* CCBs (CTIOs, ATIOs, INOTs) pending on the controller */
73 	struct ccb_queue	 pending_ccb_queue;
74 
75 	/* Command descriptors awaiting CTIO resources from the XPT */
76 	struct descr_queue	 work_queue;
77 
78 	/* Command descriptors that have been aborted back to the user. */
79 	struct descr_queue	 abort_queue;
80 
81 	/*
82 	 * Queue of CCBs that have been copied out to userland, but our
83 	 * userland daemon has not yet seen.
84 	 */
85 	struct ccb_queue	 user_ccb_queue;
86 
87 	struct cam_periph	*periph;
88 	struct cam_path		*path;
89 	targ_state		 state;
90 	struct selinfo		 read_select;
91 	struct devstat		 device_stats;
92 };
93 
94 static d_open_t		targopen;
95 static d_close_t	targclose;
96 static d_read_t		targread;
97 static d_write_t	targwrite;
98 static d_ioctl_t	targioctl;
99 static d_poll_t		targpoll;
100 static d_kqfilter_t	targkqfilter;
101 static void		targreadfiltdetach(struct knote *kn);
102 static int		targreadfilt(struct knote *kn, long hint);
103 static struct filterops targread_filtops =
104 	{ 1, NULL, targreadfiltdetach, targreadfilt };
105 
106 #define TARG_CDEV_MAJOR 65
107 static struct dev_ops targ_ops = {
108 	{ "targ", TARG_CDEV_MAJOR, D_KQFILTER },
109 	.d_open = targopen,
110 	.d_close = targclose,
111 	.d_read = targread,
112 	.d_write = targwrite,
113 	.d_ioctl = targioctl,
114 	.d_poll = targpoll,
115 	.d_kqfilter = targkqfilter
116 };
117 
118 static cam_status	targendislun(struct cam_path *path, int enable,
119 				     int grp6_len, int grp7_len);
120 static cam_status	targenable(struct targ_softc *softc,
121 				   struct cam_path *path,
122 				   int grp6_len, int grp7_len);
123 static cam_status	targdisable(struct targ_softc *softc);
124 static periph_ctor_t    targctor;
125 static periph_dtor_t    targdtor;
126 static periph_start_t   targstart;
127 static int		targusermerge(struct targ_softc *softc,
128 				      struct targ_cmd_descr *descr,
129 				      union ccb *ccb);
130 static int		targsendccb(struct targ_softc *softc, union ccb *ccb,
131 				    struct targ_cmd_descr *descr);
132 static void		targdone(struct cam_periph *periph,
133 				 union  ccb *done_ccb);
134 static int		targreturnccb(struct targ_softc *softc,
135 				      union  ccb *ccb);
136 static union ccb *	targgetccb(struct targ_softc *softc, xpt_opcode type,
137 				   int priority);
138 static void		targfreeccb(struct targ_softc *softc, union ccb *ccb);
139 static struct targ_cmd_descr *
140 			targgetdescr(struct targ_softc *softc);
141 static periph_init_t	targinit;
142 static void		targasync(void *callback_arg, u_int32_t code,
143 				  struct cam_path *path, void *arg);
144 static void		abort_all_pending(struct targ_softc *softc);
145 static void		notify_user(struct targ_softc *softc);
146 static int		targcamstatus(cam_status status);
147 static size_t		targccblen(xpt_opcode func_code);
148 
149 static struct periph_driver targdriver =
150 {
151 	targinit, "targ",
152 	TAILQ_HEAD_INITIALIZER(targdriver.units), /* generation */ 0
153 };
154 PERIPHDRIVER_DECLARE(targ, targdriver);
155 
156 static MALLOC_DEFINE(M_TARG, "TARG", "TARG data");
157 
158 /* Create softc and initialize it. Only one proc can open each targ device. */
159 static int
160 targopen(struct dev_open_args *ap)
161 {
162 	cdev_t dev = ap->a_head.a_dev;
163 	struct targ_softc *softc;
164 
165 	if (dev->si_drv1 != 0) {
166 		return (EBUSY);
167 	}
168 
169 	/* Mark device busy before any potentially blocking operations */
170 	dev->si_drv1 = (void *)~0;
171 	reference_dev(dev);		/* save ref for later destroy_dev() */
172 
173 	/* Create the targ device, allocate its softc, initialize it */
174 	make_dev(&targ_ops, minor(dev), UID_ROOT, GID_WHEEL, 0600,
175 			 "targ%d", lminor(dev));
176 	MALLOC(softc, struct targ_softc *, sizeof(*softc), M_TARG,
177 	       M_INTWAIT | M_ZERO);
178 	dev->si_drv1 = softc;
179 	softc->state = TARG_STATE_OPENED;
180 	softc->periph = NULL;
181 	softc->path = NULL;
182 
183 	TAILQ_INIT(&softc->pending_ccb_queue);
184 	TAILQ_INIT(&softc->work_queue);
185 	TAILQ_INIT(&softc->abort_queue);
186 	TAILQ_INIT(&softc->user_ccb_queue);
187 
188 	return (0);
189 }
190 
191 /* Disable LUN if enabled and teardown softc */
192 static int
193 targclose(struct dev_close_args *ap)
194 {
195 	cdev_t dev = ap->a_head.a_dev;
196 	struct targ_softc     *softc;
197 	int    error;
198 
199 	softc = (struct targ_softc *)dev->si_drv1;
200 	error = targdisable(softc);
201 	if (error == CAM_REQ_CMP) {
202 		dev->si_drv1 = 0;
203 		if (softc->periph != NULL) {
204 			cam_periph_invalidate(softc->periph);
205 			softc->periph = NULL;
206 		}
207 		destroy_dev(dev);	/* eats the open ref */
208 		FREE(softc, M_TARG);
209 	} else {
210 		release_dev(dev);
211 	}
212 	return (error);
213 }
214 
215 /* Enable/disable LUNs, set debugging level */
216 static int
217 targioctl(struct dev_ioctl_args *ap)
218 {
219 	struct targ_softc *softc;
220 	cam_status	   status;
221 
222 	softc = (struct targ_softc *)ap->a_head.a_dev->si_drv1;
223 
224 	switch (ap->a_cmd) {
225 	case TARGIOCENABLE:
226 	{
227 		struct ioc_enable_lun	*new_lun;
228 		struct cam_path		*path;
229 
230 		new_lun = (struct ioc_enable_lun *)ap->a_data;
231 		status = xpt_create_path(&path, /*periph*/NULL,
232 					 new_lun->path_id,
233 					 new_lun->target_id,
234 					 new_lun->lun_id);
235 		if (status != CAM_REQ_CMP) {
236 			kprintf("Couldn't create path, status %#x\n", status);
237 			break;
238 		}
239 		status = targenable(softc, path, new_lun->grp6_len,
240 				    new_lun->grp7_len);
241 		xpt_free_path(path);
242 		break;
243 	}
244 	case TARGIOCDISABLE:
245 		status = targdisable(softc);
246 		break;
247 	case TARGIOCDEBUG:
248 	{
249 #ifdef	CAMDEBUG
250 		struct ccb_debug cdbg;
251 
252 		bzero(&cdbg, sizeof cdbg);
253 		if (*((int *)ap->a_data) != 0)
254 			cdbg.flags = CAM_DEBUG_PERIPH;
255 		else
256 			cdbg.flags = CAM_DEBUG_NONE;
257 		xpt_setup_ccb(&cdbg.ccb_h, softc->path, /*priority*/0);
258 		cdbg.ccb_h.func_code = XPT_DEBUG;
259 		cdbg.ccb_h.cbfcnp = targdone;
260 
261 		/* If no periph available, disallow debugging changes */
262 		if ((softc->state & TARG_STATE_LUN_ENABLED) == 0) {
263 			status = CAM_DEV_NOT_THERE;
264 			break;
265 		}
266 		xpt_action((union ccb *)&cdbg);
267 		status = cdbg.ccb_h.status & CAM_STATUS_MASK;
268 #else
269 		status = CAM_FUNC_NOTAVAIL;
270 #endif
271 		break;
272 	}
273 	default:
274 		status = CAM_PROVIDE_FAIL;
275 		break;
276 	}
277 
278 	return (targcamstatus(status));
279 }
280 
281 /* Writes are always ready, reads wait for user_ccb_queue or abort_queue */
282 static int
283 targpoll(struct dev_poll_args *ap)
284 {
285 	struct targ_softc *softc;
286 	int	revents;
287 
288 	softc = (struct targ_softc *)ap->a_head.a_dev->si_drv1;
289 
290 	/* Poll for write() is always ok. */
291 	revents = ap->a_events & (POLLOUT | POLLWRNORM);
292 	if ((ap->a_events & (POLLIN | POLLRDNORM)) != 0) {
293 		crit_enter();
294 		/* Poll for read() depends on user and abort queues. */
295 		if (!TAILQ_EMPTY(&softc->user_ccb_queue) ||
296 		    !TAILQ_EMPTY(&softc->abort_queue)) {
297 			revents |= ap->a_events & (POLLIN | POLLRDNORM);
298 		}
299 		/* Only sleep if the user didn't poll for write. */
300 		if (revents == 0)
301 			selrecord(curthread, &softc->read_select);
302 		crit_exit();
303 	}
304 	ap->a_events = revents;
305 	return (0);
306 }
307 
308 static int
309 targkqfilter(struct dev_kqfilter_args *ap)
310 {
311 	struct	knote *kn = ap->a_kn;
312 	struct  targ_softc *softc;
313 
314 	softc = (struct targ_softc *)ap->a_head.a_dev->si_drv1;
315 	kn->kn_hook = (caddr_t)softc;
316 	kn->kn_fop = &targread_filtops;
317 	crit_enter();
318 	SLIST_INSERT_HEAD(&softc->read_select.si_note, kn, kn_selnext);
319 	crit_exit();
320 	return (0);
321 }
322 
323 static void
324 targreadfiltdetach(struct knote *kn)
325 {
326 	struct  targ_softc *softc;
327 
328 	softc = (struct targ_softc *)kn->kn_hook;
329 	crit_enter();
330 	SLIST_REMOVE(&softc->read_select.si_note, kn, knote, kn_selnext);
331 	crit_exit();
332 }
333 
334 /* Notify the user's kqueue when the user queue or abort queue gets a CCB */
335 static int
336 targreadfilt(struct knote *kn, long hint)
337 {
338 	struct targ_softc *softc;
339 	int	retval;
340 
341 	softc = (struct targ_softc *)kn->kn_hook;
342 	crit_enter();
343 	retval = !TAILQ_EMPTY(&softc->user_ccb_queue) ||
344 		 !TAILQ_EMPTY(&softc->abort_queue);
345 	crit_exit();
346 	return (retval);
347 }
348 
349 /* Send the HBA the enable/disable message */
350 static cam_status
351 targendislun(struct cam_path *path, int enable, int grp6_len, int grp7_len)
352 {
353 	struct ccb_en_lun en_ccb;
354 	cam_status	  status;
355 
356 	/* Tell the lun to begin answering selects */
357 	xpt_setup_ccb(&en_ccb.ccb_h, path, /*priority*/1);
358 	en_ccb.ccb_h.func_code = XPT_EN_LUN;
359 	/* Don't need support for any vendor specific commands */
360 	en_ccb.grp6_len = grp6_len;
361 	en_ccb.grp7_len = grp7_len;
362 	en_ccb.enable = enable ? 1 : 0;
363 	xpt_action((union ccb *)&en_ccb);
364 	status = en_ccb.ccb_h.status & CAM_STATUS_MASK;
365 	if (status != CAM_REQ_CMP) {
366 		xpt_print_path(path);
367 		kprintf("%sable lun CCB rejected, status %#x\n",
368 		       enable ? "en" : "dis", status);
369 	}
370 	return (status);
371 }
372 
373 /* Enable target mode on a LUN, given its path */
374 static cam_status
375 targenable(struct targ_softc *softc, struct cam_path *path, int grp6_len,
376 	   int grp7_len)
377 {
378 	struct cam_periph *periph;
379 	struct ccb_pathinq cpi;
380 	cam_status	   status;
381 
382 	if ((softc->state & TARG_STATE_LUN_ENABLED) != 0)
383 		return (CAM_LUN_ALRDY_ENA);
384 
385 	/* Make sure SIM supports target mode */
386 	xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
387 	cpi.ccb_h.func_code = XPT_PATH_INQ;
388 	xpt_action((union ccb *)&cpi);
389 	status = cpi.ccb_h.status & CAM_STATUS_MASK;
390 	if (status != CAM_REQ_CMP) {
391 		kprintf("pathinq failed, status %#x\n", status);
392 		goto enable_fail;
393 	}
394 	if ((cpi.target_sprt & PIT_PROCESSOR) == 0) {
395 		kprintf("controller does not support target mode\n");
396 		status = CAM_FUNC_NOTAVAIL;
397 		goto enable_fail;
398 	}
399 
400 	/* Destroy any periph on our path if it is disabled */
401 	periph = cam_periph_find(path, "targ");
402 	if (periph != NULL) {
403 		struct targ_softc *del_softc;
404 
405 		del_softc = (struct targ_softc *)periph->softc;
406 		if ((del_softc->state & TARG_STATE_LUN_ENABLED) == 0) {
407 			cam_periph_invalidate(del_softc->periph);
408 			del_softc->periph = NULL;
409 		} else {
410 			kprintf("Requested path still in use by targ%d\n",
411 			       periph->unit_number);
412 			status = CAM_LUN_ALRDY_ENA;
413 			goto enable_fail;
414 		}
415 	}
416 
417 	/* Create a periph instance attached to this path */
418 	status = cam_periph_alloc(targctor, NULL, targdtor, targstart,
419 			"targ", CAM_PERIPH_BIO, path, targasync, 0, softc);
420 	if (status != CAM_REQ_CMP) {
421 		kprintf("cam_periph_alloc failed, status %#x\n", status);
422 		goto enable_fail;
423 	}
424 
425 	/* Ensure that the periph now exists. */
426 	if (cam_periph_find(path, "targ") == NULL) {
427 		panic("targenable: succeeded but no periph?");
428 		/* NOTREACHED */
429 	}
430 
431 	/* Send the enable lun message */
432 	status = targendislun(path, /*enable*/1, grp6_len, grp7_len);
433 	if (status != CAM_REQ_CMP) {
434 		kprintf("enable lun failed, status %#x\n", status);
435 		goto enable_fail;
436 	}
437 	softc->state |= TARG_STATE_LUN_ENABLED;
438 
439 enable_fail:
440 	return (status);
441 }
442 
443 /* Disable this softc's target instance if enabled */
444 static cam_status
445 targdisable(struct targ_softc *softc)
446 {
447 	cam_status status;
448 
449 	if ((softc->state & TARG_STATE_LUN_ENABLED) == 0)
450 		return (CAM_REQ_CMP);
451 
452 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH, ("targdisable\n"));
453 
454 	/* Abort any ccbs pending on the controller */
455 	crit_enter();
456 	abort_all_pending(softc);
457 	crit_exit();
458 
459 	/* Disable this lun */
460 	status = targendislun(softc->path, /*enable*/0,
461 			      /*grp6_len*/0, /*grp7_len*/0);
462 	if (status == CAM_REQ_CMP)
463 		softc->state &= ~TARG_STATE_LUN_ENABLED;
464 	else
465 		kprintf("Disable lun failed, status %#x\n", status);
466 
467 	return (status);
468 }
469 
470 /* Initialize a periph (called from cam_periph_alloc) */
471 static cam_status
472 targctor(struct cam_periph *periph, void *arg)
473 {
474 	struct targ_softc *softc;
475 
476 	/* Store pointer to softc for periph-driven routines */
477 	softc = (struct targ_softc *)arg;
478 	periph->softc = softc;
479 	softc->periph = periph;
480 	softc->path = periph->path;
481 	return (CAM_REQ_CMP);
482 }
483 
484 static void
485 targdtor(struct cam_periph *periph)
486 {
487 	struct targ_softc     *softc;
488 	struct ccb_hdr	      *ccb_h;
489 	struct targ_cmd_descr *descr;
490 
491 	softc = (struct targ_softc *)periph->softc;
492 
493 	/*
494 	 * targdisable() aborts CCBs back to the user and leaves them
495 	 * on user_ccb_queue and abort_queue in case the user is still
496 	 * interested in them.  We free them now.
497 	 */
498 	while ((ccb_h = TAILQ_FIRST(&softc->user_ccb_queue)) != NULL) {
499 		TAILQ_REMOVE(&softc->user_ccb_queue, ccb_h, periph_links.tqe);
500 		targfreeccb(softc, (union ccb *)ccb_h);
501 	}
502 	while ((descr = TAILQ_FIRST(&softc->abort_queue)) != NULL) {
503 		TAILQ_REMOVE(&softc->abort_queue, descr, tqe);
504 		FREE(descr, M_TARG);
505 	}
506 
507 	softc->periph = NULL;
508 	softc->path = NULL;
509 	periph->softc = NULL;
510 }
511 
512 /* Receive CCBs from user mode proc and send them to the HBA */
513 static int
514 targwrite(struct dev_write_args *ap)
515 {
516 	struct uio *uio = ap->a_uio;
517 	union ccb *user_ccb;
518 	struct targ_softc *softc;
519 	struct targ_cmd_descr *descr;
520 	int write_len, error;
521 	int func_code, priority;
522 
523 	softc = (struct targ_softc *)ap->a_head.a_dev->si_drv1;
524 	write_len = error = 0;
525 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
526 		  ("write - uio_resid %d\n", uio->uio_resid));
527 	while (uio->uio_resid >= sizeof(user_ccb) && error == 0) {
528 		union ccb *ccb;
529 
530 		error = uiomove((caddr_t)&user_ccb, sizeof(user_ccb), uio);
531 		if (error != 0) {
532 			CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
533 				  ("write - uiomove failed (%d)\n", error));
534 			break;
535 		}
536 		priority = fuword(&user_ccb->ccb_h.pinfo.priority);
537 		if (priority == -1) {
538 			error = EINVAL;
539 			break;
540 		}
541 		func_code = fuword(&user_ccb->ccb_h.func_code);
542 		switch (func_code) {
543 		case XPT_ACCEPT_TARGET_IO:
544 		case XPT_IMMED_NOTIFY:
545 			ccb = targgetccb(softc, func_code, priority);
546 			descr = (struct targ_cmd_descr *)ccb->ccb_h.targ_descr;
547 			descr->user_ccb = user_ccb;
548 			descr->func_code = func_code;
549 			CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
550 				  ("Sent ATIO/INOT (%p)\n", user_ccb));
551 			xpt_action(ccb);
552 			crit_enter();
553 			TAILQ_INSERT_TAIL(&softc->pending_ccb_queue,
554 					  &ccb->ccb_h,
555 					  periph_links.tqe);
556 			crit_exit();
557 			break;
558 		default:
559 			if ((func_code & XPT_FC_QUEUED) != 0) {
560 				CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
561 					  ("Sending queued ccb %#x (%p)\n",
562 					  func_code, user_ccb));
563 				descr = targgetdescr(softc);
564 				descr->user_ccb = user_ccb;
565 				descr->priority = priority;
566 				descr->func_code = func_code;
567 				crit_enter();
568 				TAILQ_INSERT_TAIL(&softc->work_queue,
569 						  descr, tqe);
570 				crit_exit();
571 				xpt_schedule(softc->periph, priority);
572 			} else {
573 				CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
574 					  ("Sending inline ccb %#x (%p)\n",
575 					  func_code, user_ccb));
576 				ccb = targgetccb(softc, func_code, priority);
577 				descr = (struct targ_cmd_descr *)
578 					 ccb->ccb_h.targ_descr;
579 				descr->user_ccb = user_ccb;
580 				descr->priority = priority;
581 				descr->func_code = func_code;
582 				if (targusermerge(softc, descr, ccb) != EFAULT)
583 					targsendccb(softc, ccb, descr);
584 				targreturnccb(softc, ccb);
585 			}
586 			break;
587 		}
588 		write_len += sizeof(user_ccb);
589 	}
590 
591 	/*
592 	 * If we've successfully taken in some amount of
593 	 * data, return success for that data first.  If
594 	 * an error is persistent, it will be reported
595 	 * on the next write.
596 	 */
597 	if (error != 0 && write_len == 0)
598 		return (error);
599 	if (write_len == 0 && uio->uio_resid != 0)
600 		return (ENOSPC);
601 	return (0);
602 }
603 
604 /* Process requests (descrs) via the periph-supplied CCBs */
605 static void
606 targstart(struct cam_periph *periph, union ccb *start_ccb)
607 {
608 	struct targ_softc *softc;
609 	struct targ_cmd_descr *descr, *next_descr;
610 	int error;
611 
612 	softc = (struct targ_softc *)periph->softc;
613 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH, ("targstart %p\n", start_ccb));
614 
615 	crit_enter();
616 	descr = TAILQ_FIRST(&softc->work_queue);
617 	if (descr == NULL) {
618 		crit_exit();
619 		xpt_release_ccb(start_ccb);
620 	} else {
621 		TAILQ_REMOVE(&softc->work_queue, descr, tqe);
622 		next_descr = TAILQ_FIRST(&softc->work_queue);
623 		crit_exit();
624 
625 		/* Initiate a transaction using the descr and supplied CCB */
626 		error = targusermerge(softc, descr, start_ccb);
627 		if (error == 0)
628 			error = targsendccb(softc, start_ccb, descr);
629 		if (error != 0) {
630 			xpt_print_path(periph->path);
631 			kprintf("targsendccb failed, err %d\n", error);
632 			xpt_release_ccb(start_ccb);
633 			suword(&descr->user_ccb->ccb_h.status,
634 			       CAM_REQ_CMP_ERR);
635 			crit_enter();
636 			TAILQ_INSERT_TAIL(&softc->abort_queue, descr, tqe);
637 			crit_exit();
638 			notify_user(softc);
639 		}
640 
641 		/* If we have more work to do, stay scheduled */
642 		if (next_descr != NULL)
643 			xpt_schedule(periph, next_descr->priority);
644 	}
645 }
646 
647 static int
648 targusermerge(struct targ_softc *softc, struct targ_cmd_descr *descr,
649 	      union ccb *ccb)
650 {
651 	struct ccb_hdr *u_ccbh, *k_ccbh;
652 	size_t ccb_len;
653 	int error;
654 
655 	u_ccbh = &descr->user_ccb->ccb_h;
656 	k_ccbh = &ccb->ccb_h;
657 
658 	/*
659 	 * There are some fields in the CCB header that need to be
660 	 * preserved, the rest we get from the user ccb. (See xpt_merge_ccb)
661 	 */
662 	xpt_setup_ccb(k_ccbh, softc->path, descr->priority);
663 	k_ccbh->retry_count = fuword(&u_ccbh->retry_count);
664 	k_ccbh->func_code = descr->func_code;
665 	k_ccbh->flags = fuword(&u_ccbh->flags);
666 	k_ccbh->timeout = fuword(&u_ccbh->timeout);
667 	ccb_len = targccblen(k_ccbh->func_code) - sizeof(struct ccb_hdr);
668 	error = copyin(u_ccbh + 1, k_ccbh + 1, ccb_len);
669 	if (error != 0) {
670 		k_ccbh->status = CAM_REQ_CMP_ERR;
671 		return (error);
672 	}
673 
674 	/* Translate usermode abort_ccb pointer to its kernel counterpart */
675 	if (k_ccbh->func_code == XPT_ABORT) {
676 		struct ccb_abort *cab;
677 		struct ccb_hdr *ccb_h;
678 
679 		cab = (struct ccb_abort *)ccb;
680 		crit_enter();
681 		TAILQ_FOREACH(ccb_h, &softc->pending_ccb_queue,
682 		    periph_links.tqe) {
683 			struct targ_cmd_descr *ab_descr;
684 
685 			ab_descr = (struct targ_cmd_descr *)ccb_h->targ_descr;
686 			if (ab_descr->user_ccb == cab->abort_ccb) {
687 				CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
688 					  ("Changing abort for %p to %p\n",
689 					  cab->abort_ccb, ccb_h));
690 				cab->abort_ccb = (union ccb *)ccb_h;
691 				break;
692 			}
693 		}
694 		crit_exit();
695 		/* CCB not found, set appropriate status */
696 		if (ccb_h == NULL) {
697 			k_ccbh->status = CAM_PATH_INVALID;
698 			error = ESRCH;
699 		}
700 	}
701 
702 	return (error);
703 }
704 
705 /* Build and send a kernel CCB formed from descr->user_ccb */
706 static int
707 targsendccb(struct targ_softc *softc, union ccb *ccb,
708 	    struct targ_cmd_descr *descr)
709 {
710 	struct cam_periph_map_info *mapinfo;
711 	struct ccb_hdr *ccb_h;
712 	int error;
713 
714 	ccb_h = &ccb->ccb_h;
715 	mapinfo = &descr->mapinfo;
716 	mapinfo->num_bufs_used = 0;
717 
718 	/*
719 	 * There's no way for the user to have a completion
720 	 * function, so we put our own completion function in here.
721 	 * We also stash in a reference to our descriptor so targreturnccb()
722 	 * can find our mapping info.
723 	 */
724 	ccb_h->cbfcnp = targdone;
725 	ccb_h->targ_descr = descr;
726 
727 	/*
728 	 * We only attempt to map the user memory into kernel space
729 	 * if they haven't passed in a physical memory pointer,
730 	 * and if there is actually an I/O operation to perform.
731 	 * Right now cam_periph_mapmem() only supports SCSI and device
732 	 * match CCBs.  For the SCSI CCBs, we only pass the CCB in if
733 	 * there's actually data to map.  cam_periph_mapmem() will do the
734 	 * right thing, even if there isn't data to map, but since CCBs
735 	 * without data are a reasonably common occurance (e.g. test unit
736 	 * ready), it will save a few cycles if we check for it here.
737 	 */
738 	if (((ccb_h->flags & CAM_DATA_PHYS) == 0)
739 	 && (((ccb_h->func_code == XPT_CONT_TARGET_IO)
740 	    && ((ccb_h->flags & CAM_DIR_MASK) != CAM_DIR_NONE))
741 	  || (ccb_h->func_code == XPT_DEV_MATCH))) {
742 
743 		error = cam_periph_mapmem(ccb, mapinfo);
744 
745 		/*
746 		 * cam_periph_mapmem returned an error, we can't continue.
747 		 * Return the error to the user.
748 		 */
749 		if (error) {
750 			ccb_h->status = CAM_REQ_CMP_ERR;
751 			mapinfo->num_bufs_used = 0;
752 			return (error);
753 		}
754 	}
755 
756 	/*
757 	 * Once queued on the pending CCB list, this CCB will be protected
758 	 * by our error recovery handler.
759 	 */
760 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH, ("sendccb %p\n", ccb));
761 	if (XPT_FC_IS_QUEUED(ccb)) {
762 		crit_enter();
763 		TAILQ_INSERT_TAIL(&softc->pending_ccb_queue, ccb_h,
764 				  periph_links.tqe);
765 		crit_exit();
766 	}
767 	xpt_action(ccb);
768 
769 	return (0);
770 }
771 
772 /* Completion routine for CCBs (called in a critical section) */
773 static void
774 targdone(struct cam_periph *periph, union ccb *done_ccb)
775 {
776 	struct targ_softc *softc;
777 	cam_status status;
778 
779 	CAM_DEBUG(periph->path, CAM_DEBUG_PERIPH, ("targdone %p\n", done_ccb));
780 	softc = (struct targ_softc *)periph->softc;
781 	TAILQ_REMOVE(&softc->pending_ccb_queue, &done_ccb->ccb_h,
782 		     periph_links.tqe);
783 	status = done_ccb->ccb_h.status & CAM_STATUS_MASK;
784 
785 	/* If we're no longer enabled, throw away CCB */
786 	if ((softc->state & TARG_STATE_LUN_ENABLED) == 0) {
787 		targfreeccb(softc, done_ccb);
788 		return;
789 	}
790 	/* abort_all_pending() waits for pending queue to be empty */
791 	if (TAILQ_EMPTY(&softc->pending_ccb_queue))
792 		wakeup(&softc->pending_ccb_queue);
793 
794 	switch (done_ccb->ccb_h.func_code) {
795 	/* All FC_*_QUEUED CCBs go back to userland */
796 	case XPT_IMMED_NOTIFY:
797 	case XPT_ACCEPT_TARGET_IO:
798 	case XPT_CONT_TARGET_IO:
799 		TAILQ_INSERT_TAIL(&softc->user_ccb_queue, &done_ccb->ccb_h,
800 				  periph_links.tqe);
801 		notify_user(softc);
802 		break;
803 	default:
804 		panic("targdone: impossible xpt opcode %#x",
805 		      done_ccb->ccb_h.func_code);
806 		/* NOTREACHED */
807 	}
808 }
809 
810 /* Return CCBs to the user from the user queue and abort queue */
811 static int
812 targread(struct dev_read_args *ap)
813 {
814 	struct uio *uio = ap->a_uio;
815 	struct descr_queue	*abort_queue;
816 	struct targ_cmd_descr	*user_descr;
817 	struct targ_softc	*softc;
818 	struct ccb_queue  *user_queue;
819 	struct ccb_hdr	  *ccb_h;
820 	union  ccb	  *user_ccb;
821 	int		   read_len, error;
822 
823 	error = 0;
824 	read_len = 0;
825 	softc = (struct targ_softc *)ap->a_head.a_dev->si_drv1;
826 	user_queue = &softc->user_ccb_queue;
827 	abort_queue = &softc->abort_queue;
828 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH, ("targread\n"));
829 
830 	/* If no data is available, wait or return immediately */
831 	crit_enter();
832 	ccb_h = TAILQ_FIRST(user_queue);
833 	user_descr = TAILQ_FIRST(abort_queue);
834 	while (ccb_h == NULL && user_descr == NULL) {
835 		if ((ap->a_ioflag & IO_NDELAY) == 0) {
836 			error = tsleep(user_queue, PCATCH, "targrd", 0);
837 			ccb_h = TAILQ_FIRST(user_queue);
838 			user_descr = TAILQ_FIRST(abort_queue);
839 			if (error != 0) {
840 				if (error == ERESTART) {
841 					continue;
842 				} else {
843 					crit_exit();
844 					goto read_fail;
845 				}
846 			}
847 		} else {
848 			crit_exit();
849 			return (EAGAIN);
850 		}
851 	}
852 
853 	/* Data is available so fill the user's buffer */
854 	while (ccb_h != NULL) {
855 		struct targ_cmd_descr *descr;
856 
857 		if (uio->uio_resid < sizeof(user_ccb))
858 			break;
859 		TAILQ_REMOVE(user_queue, ccb_h, periph_links.tqe);
860 		crit_exit();
861 		descr = (struct targ_cmd_descr *)ccb_h->targ_descr;
862 		user_ccb = descr->user_ccb;
863 		CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
864 			  ("targread ccb %p (%p)\n", ccb_h, user_ccb));
865 		error = targreturnccb(softc, (union ccb *)ccb_h);
866 		if (error != 0)
867 			goto read_fail;
868 		error = uiomove((caddr_t)&user_ccb, sizeof(user_ccb), uio);
869 		if (error != 0)
870 			goto read_fail;
871 		read_len += sizeof(user_ccb);
872 
873 		crit_enter();
874 		ccb_h = TAILQ_FIRST(user_queue);
875 	}
876 
877 	/* Flush out any aborted descriptors */
878 	while (user_descr != NULL) {
879 		if (uio->uio_resid < sizeof(user_ccb))
880 			break;
881 		TAILQ_REMOVE(abort_queue, user_descr, tqe);
882 		crit_exit();
883 		user_ccb = user_descr->user_ccb;
884 		CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
885 			  ("targread aborted descr %p (%p)\n",
886 			  user_descr, user_ccb));
887 		suword(&user_ccb->ccb_h.status, CAM_REQ_ABORTED);
888 		error = uiomove((caddr_t)&user_ccb, sizeof(user_ccb), uio);
889 		if (error != 0)
890 			goto read_fail;
891 		read_len += sizeof(user_ccb);
892 
893 		crit_enter();
894 		user_descr = TAILQ_FIRST(abort_queue);
895 	}
896 	crit_exit();
897 
898 	/*
899 	 * If we've successfully read some amount of data, don't report an
900 	 * error.  If the error is persistent, it will be reported on the
901 	 * next read().
902 	 */
903 	if (read_len == 0 && uio->uio_resid != 0)
904 		error = ENOSPC;
905 
906 read_fail:
907 	return (error);
908 }
909 
910 /* Copy completed ccb back to the user */
911 static int
912 targreturnccb(struct targ_softc *softc, union ccb *ccb)
913 {
914 	struct targ_cmd_descr *descr;
915 	struct ccb_hdr *u_ccbh;
916 	size_t ccb_len;
917 	int error;
918 
919 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH, ("targreturnccb %p\n", ccb));
920 	descr = (struct targ_cmd_descr *)ccb->ccb_h.targ_descr;
921 	u_ccbh = &descr->user_ccb->ccb_h;
922 
923 	/* Copy out the central portion of the ccb_hdr */
924 	copyout(&ccb->ccb_h.retry_count, &u_ccbh->retry_count,
925 		offsetof(struct ccb_hdr, periph_priv) -
926 		offsetof(struct ccb_hdr, retry_count));
927 
928 	/* Copy out the rest of the ccb (after the ccb_hdr) */
929 	ccb_len = targccblen(ccb->ccb_h.func_code) - sizeof(struct ccb_hdr);
930 	if (descr->mapinfo.num_bufs_used != 0)
931 		cam_periph_unmapmem(ccb, &descr->mapinfo);
932 	error = copyout(&ccb->ccb_h + 1, u_ccbh + 1, ccb_len);
933 	if (error != 0) {
934 		xpt_print_path(softc->path);
935 		kprintf("targreturnccb - CCB copyout failed (%d)\n",
936 		       error);
937 	}
938 	/* Free CCB or send back to devq. */
939 	targfreeccb(softc, ccb);
940 
941 	return (error);
942 }
943 
944 static union ccb *
945 targgetccb(struct targ_softc *softc, xpt_opcode type, int priority)
946 {
947 	union ccb *ccb;
948 	int ccb_len;
949 
950 	ccb_len = targccblen(type);
951 	MALLOC(ccb, union ccb *, ccb_len, M_TARG, M_INTWAIT);
952 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH, ("getccb %p\n", ccb));
953 
954 	xpt_setup_ccb(&ccb->ccb_h, softc->path, priority);
955 	ccb->ccb_h.func_code = type;
956 	ccb->ccb_h.cbfcnp = targdone;
957 	ccb->ccb_h.targ_descr = targgetdescr(softc);
958 	return (ccb);
959 }
960 
961 static void
962 targfreeccb(struct targ_softc *softc, union ccb *ccb)
963 {
964 	CAM_DEBUG_PRINT(CAM_DEBUG_PERIPH, ("targfreeccb descr %p and\n",
965 			ccb->ccb_h.targ_descr));
966 	FREE(ccb->ccb_h.targ_descr, M_TARG);
967 
968 	switch (ccb->ccb_h.func_code) {
969 	case XPT_ACCEPT_TARGET_IO:
970 	case XPT_IMMED_NOTIFY:
971 		CAM_DEBUG_PRINT(CAM_DEBUG_PERIPH, ("freeing ccb %p\n", ccb));
972 		FREE(ccb, M_TARG);
973 		break;
974 	default:
975 		/* Send back CCB if we got it from the periph */
976 		if (XPT_FC_IS_QUEUED(ccb)) {
977 			CAM_DEBUG_PRINT(CAM_DEBUG_PERIPH,
978 					("returning queued ccb %p\n", ccb));
979 			xpt_release_ccb(ccb);
980 		} else {
981 			CAM_DEBUG_PRINT(CAM_DEBUG_PERIPH,
982 					("freeing ccb %p\n", ccb));
983 			FREE(ccb, M_TARG);
984 		}
985 		break;
986 	}
987 }
988 
989 static struct targ_cmd_descr *
990 targgetdescr(struct targ_softc *softc)
991 {
992 	struct targ_cmd_descr *descr;
993 
994 	MALLOC(descr, struct targ_cmd_descr *, sizeof(*descr),
995 		M_TARG, M_INTWAIT);
996 	descr->mapinfo.num_bufs_used = 0;
997 	return (descr);
998 }
999 
1000 static void
1001 targinit(void)
1002 {
1003 	dev_ops_add(&targ_ops, 0, 0);
1004 }
1005 
1006 static void
1007 targasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg)
1008 {
1009 	/* All events are handled in usermode by INOTs */
1010 	panic("targasync() called, should be an INOT instead");
1011 }
1012 
1013 /* Cancel all pending requests and CCBs awaiting work. */
1014 static void
1015 abort_all_pending(struct targ_softc *softc)
1016 {
1017 	struct targ_cmd_descr   *descr;
1018 	struct ccb_abort	 cab;
1019 	struct ccb_hdr		*ccb_h;
1020 
1021 	CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH, ("abort_all_pending\n"));
1022 
1023 	/* First abort the descriptors awaiting resources */
1024 	while ((descr = TAILQ_FIRST(&softc->work_queue)) != NULL) {
1025 		CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
1026 			  ("Aborting descr from workq %p\n", descr));
1027 		TAILQ_REMOVE(&softc->work_queue, descr, tqe);
1028 		TAILQ_INSERT_TAIL(&softc->abort_queue, descr, tqe);
1029 	}
1030 
1031 	/*
1032 	 * Then abort all pending CCBs.
1033 	 * targdone() will return the aborted CCB via user_ccb_queue
1034 	 */
1035 	xpt_setup_ccb(&cab.ccb_h, softc->path, /*priority*/0);
1036 	cab.ccb_h.func_code = XPT_ABORT;
1037 	cab.ccb_h.status = CAM_REQ_CMP_ERR;
1038 	TAILQ_FOREACH(ccb_h, &softc->pending_ccb_queue, periph_links.tqe) {
1039 		CAM_DEBUG(softc->path, CAM_DEBUG_PERIPH,
1040 			  ("Aborting pending CCB %p\n", ccb_h));
1041 		cab.abort_ccb = (union ccb *)ccb_h;
1042 		xpt_action((union ccb *)&cab);
1043 		if (cab.ccb_h.status != CAM_REQ_CMP) {
1044 			xpt_print_path(cab.ccb_h.path);
1045 			kprintf("Unable to abort CCB, status %#x\n",
1046 			       cab.ccb_h.status);
1047 		}
1048 	}
1049 
1050 	/* If we aborted at least one pending CCB ok, wait for it. */
1051 	if (cab.ccb_h.status == CAM_REQ_CMP) {
1052 		tsleep(&softc->pending_ccb_queue, PCATCH, "tgabrt", 0);
1053 	}
1054 
1055 	/* If we aborted anything from the work queue, wakeup user. */
1056 	if (!TAILQ_EMPTY(&softc->user_ccb_queue)
1057 	 || !TAILQ_EMPTY(&softc->abort_queue))
1058 		notify_user(softc);
1059 }
1060 
1061 /* Notify the user that data is ready */
1062 static void
1063 notify_user(struct targ_softc *softc)
1064 {
1065 	/*
1066 	 * Notify users sleeping via poll(), kqueue(), and
1067 	 * blocking read().
1068 	 */
1069 	selwakeup(&softc->read_select);
1070 	KNOTE(&softc->read_select.si_note, 0);
1071 	wakeup(&softc->user_ccb_queue);
1072 }
1073 
1074 /* Convert CAM status to errno values */
1075 static int
1076 targcamstatus(cam_status status)
1077 {
1078 	switch (status & CAM_STATUS_MASK) {
1079 	case CAM_REQ_CMP:	/* CCB request completed without error */
1080 		return (0);
1081 	case CAM_REQ_INPROG:	/* CCB request is in progress */
1082 		return (EINPROGRESS);
1083 	case CAM_REQ_CMP_ERR:	/* CCB request completed with an error */
1084 		return (EIO);
1085 	case CAM_PROVIDE_FAIL:	/* Unable to provide requested capability */
1086 		return (ENOTTY);
1087 	case CAM_FUNC_NOTAVAIL:	/* The requested function is not available */
1088 		return (ENOTSUP);
1089 	case CAM_LUN_ALRDY_ENA:	/* LUN is already enabled for target mode */
1090 		return (EADDRINUSE);
1091 	case CAM_PATH_INVALID:	/* Supplied Path ID is invalid */
1092 	case CAM_DEV_NOT_THERE:	/* SCSI Device Not Installed/there */
1093 		return (ENOENT);
1094 	case CAM_REQ_ABORTED:	/* CCB request aborted by the host */
1095 		return (ECANCELED);
1096 	case CAM_CMD_TIMEOUT:	/* Command timeout */
1097 		return (ETIMEDOUT);
1098 	case CAM_REQUEUE_REQ:	/* Requeue to preserve transaction ordering */
1099 		return (EAGAIN);
1100 	case CAM_REQ_INVALID:	/* CCB request was invalid */
1101 		return (EINVAL);
1102 	case CAM_RESRC_UNAVAIL:	/* Resource Unavailable */
1103 		return (ENOMEM);
1104 	case CAM_BUSY:		/* CAM subsytem is busy */
1105 	case CAM_UA_ABORT:	/* Unable to abort CCB request */
1106 		return (EBUSY);
1107 	default:
1108 		return (ENXIO);
1109 	}
1110 }
1111 
1112 static size_t
1113 targccblen(xpt_opcode func_code)
1114 {
1115 	int len;
1116 
1117 	/* Codes we expect to see as a target */
1118 	switch (func_code) {
1119 	case XPT_CONT_TARGET_IO:
1120 	case XPT_SCSI_IO:
1121 		len = sizeof(struct ccb_scsiio);
1122 		break;
1123 	case XPT_ACCEPT_TARGET_IO:
1124 		len = sizeof(struct ccb_accept_tio);
1125 		break;
1126 	case XPT_IMMED_NOTIFY:
1127 		len = sizeof(struct ccb_immed_notify);
1128 		break;
1129 	case XPT_REL_SIMQ:
1130 		len = sizeof(struct ccb_relsim);
1131 		break;
1132 	case XPT_PATH_INQ:
1133 		len = sizeof(struct ccb_pathinq);
1134 		break;
1135 	case XPT_DEBUG:
1136 		len = sizeof(struct ccb_debug);
1137 		break;
1138 	case XPT_ABORT:
1139 		len = sizeof(struct ccb_abort);
1140 		break;
1141 	case XPT_EN_LUN:
1142 		len = sizeof(struct ccb_en_lun);
1143 		break;
1144 	default:
1145 		len = sizeof(union ccb);
1146 		break;
1147 	}
1148 
1149 	return (len);
1150 }
1151