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