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