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