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