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