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