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