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