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