]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/scsi/scsi_enc.c
libfdt: Update to 1.4.6, switch to using libfdt for overlay support
[FreeBSD/FreeBSD.git] / sys / cam / scsi / scsi_enc.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2000 Matthew Jacob
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33
34 #include <sys/conf.h>
35 #include <sys/errno.h>
36 #include <sys/fcntl.h>
37 #include <sys/kernel.h>
38 #include <sys/kthread.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/queue.h>
43 #include <sys/sbuf.h>
44 #include <sys/sx.h>
45 #include <sys/systm.h>
46 #include <sys/sysctl.h>
47 #include <sys/types.h>
48
49 #include <machine/stdarg.h>
50
51 #include <cam/cam.h>
52 #include <cam/cam_ccb.h>
53 #include <cam/cam_debug.h>
54 #include <cam/cam_periph.h>
55 #include <cam/cam_xpt_periph.h>
56
57 #include <cam/scsi/scsi_all.h>
58 #include <cam/scsi/scsi_message.h>
59 #include <cam/scsi/scsi_enc.h>
60 #include <cam/scsi/scsi_enc_internal.h>
61
62 #include "opt_ses.h"
63
64 MALLOC_DEFINE(M_SCSIENC, "SCSI ENC", "SCSI ENC buffers");
65
66 /* Enclosure type independent driver */
67
68 static  d_open_t        enc_open;
69 static  d_close_t       enc_close;
70 static  d_ioctl_t       enc_ioctl;
71 static  periph_init_t   enc_init;
72 static  periph_ctor_t   enc_ctor;
73 static  periph_oninv_t  enc_oninvalidate;
74 static  periph_dtor_t   enc_dtor;
75
76 static void enc_async(void *, uint32_t, struct cam_path *, void *);
77 static enctyp enc_type(struct ccb_getdev *);
78
79 SYSCTL_NODE(_kern_cam, OID_AUTO, enc, CTLFLAG_RD, 0,
80             "CAM Enclosure Services driver");
81
82 static struct periph_driver encdriver = {
83         enc_init, "ses",
84         TAILQ_HEAD_INITIALIZER(encdriver.units), /* generation */ 0
85 };
86
87 PERIPHDRIVER_DECLARE(enc, encdriver);
88
89 static struct cdevsw enc_cdevsw = {
90         .d_version =    D_VERSION,
91         .d_open =       enc_open,
92         .d_close =      enc_close,
93         .d_ioctl =      enc_ioctl,
94         .d_name =       "ses",
95         .d_flags =      D_TRACKCLOSE,
96 };
97
98 static void
99 enc_init(void)
100 {
101         cam_status status;
102
103         /*
104          * Install a global async callback.  This callback will
105          * receive async callbacks like "new device found".
106          */
107         status = xpt_register_async(AC_FOUND_DEVICE, enc_async, NULL, NULL);
108
109         if (status != CAM_REQ_CMP) {
110                 printf("enc: Failed to attach master async callback "
111                        "due to status 0x%x!\n", status);
112         }
113 }
114
115 static void
116 enc_devgonecb(void *arg)
117 {
118         struct cam_periph *periph;
119         struct enc_softc  *enc;
120         struct mtx *mtx;
121         int i;
122
123         periph = (struct cam_periph *)arg;
124         mtx = cam_periph_mtx(periph);
125         mtx_lock(mtx);
126         enc = (struct enc_softc *)periph->softc;
127
128         /*
129          * When we get this callback, we will get no more close calls from
130          * devfs.  So if we have any dangling opens, we need to release the
131          * reference held for that particular context.
132          */
133         for (i = 0; i < enc->open_count; i++)
134                 cam_periph_release_locked(periph);
135
136         enc->open_count = 0;
137
138         /*
139          * Release the reference held for the device node, it is gone now.
140          */
141         cam_periph_release_locked(periph);
142
143         /*
144          * We reference the lock directly here, instead of using
145          * cam_periph_unlock().  The reason is that the final call to
146          * cam_periph_release_locked() above could result in the periph
147          * getting freed.  If that is the case, dereferencing the periph
148          * with a cam_periph_unlock() call would cause a page fault.
149          */
150         mtx_unlock(mtx);
151 }
152
153 static void
154 enc_oninvalidate(struct cam_periph *periph)
155 {
156         struct enc_softc *enc;
157
158         enc = periph->softc;
159
160         enc->enc_flags |= ENC_FLAG_INVALID;
161
162         /* If the sub-driver has an invalidate routine, call it */
163         if (enc->enc_vec.softc_invalidate != NULL)
164                 enc->enc_vec.softc_invalidate(enc);
165
166         /*
167          * Unregister any async callbacks.
168          */
169         xpt_register_async(0, enc_async, periph, periph->path);
170
171         /*
172          * Shutdown our daemon.
173          */
174         enc->enc_flags |= ENC_FLAG_SHUTDOWN;
175         if (enc->enc_daemon != NULL) {
176                 /* Signal the ses daemon to terminate. */
177                 wakeup(enc->enc_daemon);
178         }
179         callout_drain(&enc->status_updater);
180
181         destroy_dev_sched_cb(enc->enc_dev, enc_devgonecb, periph);
182 }
183
184 static void
185 enc_dtor(struct cam_periph *periph)
186 {
187         struct enc_softc *enc;
188
189         enc = periph->softc;
190
191         /* If the sub-driver has a cleanup routine, call it */
192         if (enc->enc_vec.softc_cleanup != NULL)
193                 enc->enc_vec.softc_cleanup(enc);
194
195         if (enc->enc_boot_hold_ch.ich_func != NULL) {
196                 config_intrhook_disestablish(&enc->enc_boot_hold_ch);
197                 enc->enc_boot_hold_ch.ich_func = NULL;
198         }
199
200         ENC_FREE(enc);
201 }
202
203 static void
204 enc_async(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
205 {
206         struct cam_periph *periph;
207
208         periph = (struct cam_periph *)callback_arg;
209
210         switch(code) {
211         case AC_FOUND_DEVICE:
212         {
213                 struct ccb_getdev *cgd;
214                 cam_status status;
215                 path_id_t path_id;
216
217                 cgd = (struct ccb_getdev *)arg;
218                 if (arg == NULL) {
219                         break;
220                 }
221
222                 if (enc_type(cgd) == ENC_NONE) {
223                         /*
224                          * Schedule announcement of the ENC bindings for
225                          * this device if it is managed by a SEP.
226                          */
227                         path_id = xpt_path_path_id(path);
228                         xpt_lock_buses();
229                         TAILQ_FOREACH(periph, &encdriver.units, unit_links) {
230                                 struct enc_softc *softc;
231
232                                 softc = (struct enc_softc *)periph->softc;
233                                 if (xpt_path_path_id(periph->path) != path_id
234                                  || softc == NULL
235                                  || (softc->enc_flags & ENC_FLAG_INITIALIZED)
236                                   == 0
237                                  || softc->enc_vec.device_found == NULL)
238                                         continue;
239
240                                 softc->enc_vec.device_found(softc);
241                         }
242                         xpt_unlock_buses();
243                         return;
244                 }
245
246                 status = cam_periph_alloc(enc_ctor, enc_oninvalidate,
247                     enc_dtor, NULL, "ses", CAM_PERIPH_BIO,
248                     path, enc_async, AC_FOUND_DEVICE, cgd);
249
250                 if (status != CAM_REQ_CMP && status != CAM_REQ_INPROG) {
251                         printf("enc_async: Unable to probe new device due to "
252                             "status 0x%x\n", status);
253                 }
254                 break;
255         }
256         default:
257                 cam_periph_async(periph, code, path, arg);
258                 break;
259         }
260 }
261
262 static int
263 enc_open(struct cdev *dev, int flags, int fmt, struct thread *td)
264 {
265         struct cam_periph *periph;
266         struct enc_softc *softc;
267         int error = 0;
268
269         periph = (struct cam_periph *)dev->si_drv1;
270         if (cam_periph_acquire(periph) != CAM_REQ_CMP)
271                 return (ENXIO);
272
273         cam_periph_lock(periph);
274
275         softc = (struct enc_softc *)periph->softc;
276
277         if ((softc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
278                 error = ENXIO;
279                 goto out;
280         }
281         if (softc->enc_flags & ENC_FLAG_INVALID) {
282                 error = ENXIO;
283                 goto out;
284         }
285 out:
286         if (error != 0)
287                 cam_periph_release_locked(periph);
288         else
289                 softc->open_count++;
290
291         cam_periph_unlock(periph);
292
293         return (error);
294 }
295
296 static int
297 enc_close(struct cdev *dev, int flag, int fmt, struct thread *td)
298 {
299         struct cam_periph *periph;
300         struct enc_softc  *enc;
301         struct mtx *mtx;
302
303         periph = (struct cam_periph *)dev->si_drv1;
304         mtx = cam_periph_mtx(periph);
305         mtx_lock(mtx);
306
307         enc = periph->softc;
308         enc->open_count--;
309
310         cam_periph_release_locked(periph);
311
312         /*
313          * We reference the lock directly here, instead of using
314          * cam_periph_unlock().  The reason is that the call to
315          * cam_periph_release_locked() above could result in the periph
316          * getting freed.  If that is the case, dereferencing the periph
317          * with a cam_periph_unlock() call would cause a page fault.
318          *
319          * cam_periph_release() avoids this problem using the same method,
320          * but we're manually acquiring and dropping the lock here to
321          * protect the open count and avoid another lock acquisition and
322          * release.
323          */
324         mtx_unlock(mtx);
325
326         return (0);
327 }
328
329 int
330 enc_error(union ccb *ccb, uint32_t cflags, uint32_t sflags)
331 {
332         struct enc_softc *softc;
333         struct cam_periph *periph;
334
335         periph = xpt_path_periph(ccb->ccb_h.path);
336         softc = (struct enc_softc *)periph->softc;
337
338         return (cam_periph_error(ccb, cflags, sflags));
339 }
340
341 static int
342 enc_ioctl(struct cdev *dev, u_long cmd, caddr_t arg_addr, int flag,
343          struct thread *td)
344 {
345         struct cam_periph *periph;
346         encioc_enc_status_t tmp;
347         encioc_string_t sstr;
348         encioc_elm_status_t elms;
349         encioc_elm_desc_t elmd;
350         encioc_elm_devnames_t elmdn;
351         encioc_element_t *uelm;
352         enc_softc_t *enc;
353         enc_cache_t *cache;
354         void *addr;
355         int error, i;
356
357
358         if (arg_addr)
359                 addr = *((caddr_t *) arg_addr);
360         else
361                 addr = NULL;
362
363         periph = (struct cam_periph *)dev->si_drv1;
364         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering encioctl\n"));
365
366         cam_periph_lock(periph);
367         enc = (struct enc_softc *)periph->softc;
368         cache = &enc->enc_cache;
369
370         /*
371          * Now check to see whether we're initialized or not.
372          * This actually should never fail as we're not supposed
373          * to get past enc_open w/o successfully initializing
374          * things.
375          */
376         if ((enc->enc_flags & ENC_FLAG_INITIALIZED) == 0) {
377                 cam_periph_unlock(periph);
378                 return (ENXIO);
379         }
380         cam_periph_unlock(periph);
381
382         error = 0;
383
384         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
385             ("trying to do ioctl %#lx\n", cmd));
386
387         /*
388          * If this command can change the device's state,
389          * we must have the device open for writing.
390          *
391          * For commands that get information about the
392          * device- we don't need to lock the peripheral
393          * if we aren't running a command.  The periph
394          * also can't go away while a user process has
395          * it open.
396          */
397         switch (cmd) {
398         case ENCIOC_GETNELM:
399         case ENCIOC_GETELMMAP:
400         case ENCIOC_GETENCSTAT:
401         case ENCIOC_GETELMSTAT:
402         case ENCIOC_GETELMDESC:
403         case ENCIOC_GETELMDEVNAMES:
404         case ENCIOC_GETENCNAME:
405         case ENCIOC_GETENCID:
406                 break;
407         default:
408                 if ((flag & FWRITE) == 0) {
409                         return (EBADF);
410                 }
411         }
412  
413         /*
414          * XXX The values read here are only valid for the current
415          *     configuration generation.  We need these ioctls
416          *     to also pass in/out a generation number.
417          */
418         sx_slock(&enc->enc_cache_lock);
419         switch (cmd) {
420         case ENCIOC_GETNELM:
421                 error = copyout(&cache->nelms, addr, sizeof (cache->nelms));
422                 break;
423                 
424         case ENCIOC_GETELMMAP:
425                 for (uelm = addr, i = 0; i != cache->nelms; i++) {
426                         encioc_element_t kelm;
427                         kelm.elm_idx = i;
428                         kelm.elm_subenc_id = cache->elm_map[i].subenclosure;
429                         kelm.elm_type = cache->elm_map[i].enctype;
430                         error = copyout(&kelm, &uelm[i], sizeof(kelm));
431                         if (error)
432                                 break;
433                 }
434                 break;
435
436         case ENCIOC_GETENCSTAT:
437                 cam_periph_lock(periph);
438                 error = enc->enc_vec.get_enc_status(enc, 1);
439                 if (error) {
440                         cam_periph_unlock(periph);
441                         break;
442                 }
443                 tmp = cache->enc_status;
444                 cam_periph_unlock(periph);
445                 error = copyout(&tmp, addr, sizeof(tmp));
446                 cache->enc_status = tmp;
447                 break;
448
449         case ENCIOC_SETENCSTAT:
450                 error = copyin(addr, &tmp, sizeof(tmp));
451                 if (error)
452                         break;
453                 cam_periph_lock(periph);
454                 error = enc->enc_vec.set_enc_status(enc, tmp, 1);
455                 cam_periph_unlock(periph);
456                 break;
457
458         case ENCIOC_GETSTRING:
459         case ENCIOC_SETSTRING:
460         case ENCIOC_GETENCNAME:
461         case ENCIOC_GETENCID:
462                 if (enc->enc_vec.handle_string == NULL) {
463                         error = EINVAL;
464                         break;
465                 }
466                 error = copyin(addr, &sstr, sizeof(sstr));
467                 if (error)
468                         break;
469                 cam_periph_lock(periph);
470                 error = enc->enc_vec.handle_string(enc, &sstr, cmd);
471                 cam_periph_unlock(periph);
472                 break;
473
474         case ENCIOC_GETELMSTAT:
475                 error = copyin(addr, &elms, sizeof(elms));
476                 if (error)
477                         break;
478                 if (elms.elm_idx >= cache->nelms) {
479                         error = EINVAL;
480                         break;
481                 }
482                 cam_periph_lock(periph);
483                 error = enc->enc_vec.get_elm_status(enc, &elms, 1);
484                 cam_periph_unlock(periph);
485                 if (error)
486                         break;
487                 error = copyout(&elms, addr, sizeof(elms));
488                 break;
489
490         case ENCIOC_GETELMDESC:
491                 error = copyin(addr, &elmd, sizeof(elmd));
492                 if (error)
493                         break;
494                 if (elmd.elm_idx >= cache->nelms) {
495                         error = EINVAL;
496                         break;
497                 }
498                 if (enc->enc_vec.get_elm_desc != NULL) {
499                         error = enc->enc_vec.get_elm_desc(enc, &elmd);
500                         if (error)
501                                 break;
502                 } else
503                         elmd.elm_desc_len = 0;
504                 error = copyout(&elmd, addr, sizeof(elmd));
505                 break;
506
507         case ENCIOC_GETELMDEVNAMES:
508                 if (enc->enc_vec.get_elm_devnames == NULL) {
509                         error = EINVAL;
510                         break;
511                 }
512                 error = copyin(addr, &elmdn, sizeof(elmdn));
513                 if (error)
514                         break;
515                 if (elmdn.elm_idx >= cache->nelms) {
516                         error = EINVAL;
517                         break;
518                 }
519                 cam_periph_lock(periph);
520                 error = (*enc->enc_vec.get_elm_devnames)(enc, &elmdn);
521                 cam_periph_unlock(periph);
522                 if (error)
523                         break;
524                 error = copyout(&elmdn, addr, sizeof(elmdn));
525                 break;
526
527         case ENCIOC_SETELMSTAT:
528                 error = copyin(addr, &elms, sizeof(elms));
529                 if (error)
530                         break;
531
532                 if (elms.elm_idx >= cache->nelms) {
533                         error = EINVAL;
534                         break;
535                 }
536                 cam_periph_lock(periph);
537                 error = enc->enc_vec.set_elm_status(enc, &elms, 1);
538                 cam_periph_unlock(periph);
539
540                 break;
541
542         case ENCIOC_INIT:
543
544                 cam_periph_lock(periph);
545                 error = enc->enc_vec.init_enc(enc);
546                 cam_periph_unlock(periph);
547                 break;
548
549         default:
550                 cam_periph_lock(periph);
551                 error = cam_periph_ioctl(periph, cmd, arg_addr, enc_error);
552                 cam_periph_unlock(periph);
553                 break;
554         }
555         sx_sunlock(&enc->enc_cache_lock);
556         return (error);
557 }
558
559 int
560 enc_runcmd(struct enc_softc *enc, char *cdb, int cdbl, char *dptr, int *dlenp)
561 {
562         int error, dlen, tdlen;
563         ccb_flags ddf;
564         union ccb *ccb;
565
566         CAM_DEBUG(enc->periph->path, CAM_DEBUG_TRACE,
567             ("entering enc_runcmd\n"));
568         if (dptr) {
569                 if ((dlen = *dlenp) < 0) {
570                         dlen = -dlen;
571                         ddf = CAM_DIR_OUT;
572                 } else {
573                         ddf = CAM_DIR_IN;
574                 }
575         } else {
576                 dlen = 0;
577                 ddf = CAM_DIR_NONE;
578         }
579
580         if (cdbl > IOCDBLEN) {
581                 cdbl = IOCDBLEN;
582         }
583
584         ccb = cam_periph_getccb(enc->periph, CAM_PRIORITY_NORMAL);
585         if (enc->enc_type == ENC_SEMB_SES || enc->enc_type == ENC_SEMB_SAFT) {
586                 tdlen = min(dlen, 1020);
587                 tdlen = (tdlen + 3) & ~3;
588                 cam_fill_ataio(&ccb->ataio, 0, NULL, ddf, 0, dptr, tdlen,
589                     30 * 1000);
590                 if (cdb[0] == RECEIVE_DIAGNOSTIC)
591                         ata_28bit_cmd(&ccb->ataio,
592                             ATA_SEP_ATTN, cdb[2], 0x02, tdlen / 4);
593                 else if (cdb[0] == SEND_DIAGNOSTIC)
594                         ata_28bit_cmd(&ccb->ataio,
595                             ATA_SEP_ATTN, dlen > 0 ? dptr[0] : 0,
596                             0x82, tdlen / 4);
597                 else if (cdb[0] == READ_BUFFER)
598                         ata_28bit_cmd(&ccb->ataio,
599                             ATA_SEP_ATTN, cdb[2], 0x00, tdlen / 4);
600                 else
601                         ata_28bit_cmd(&ccb->ataio,
602                             ATA_SEP_ATTN, dlen > 0 ? dptr[0] : 0,
603                             0x80, tdlen / 4);
604         } else {
605                 tdlen = dlen;
606                 cam_fill_csio(&ccb->csio, 0, NULL, ddf, MSG_SIMPLE_Q_TAG,
607                     dptr, dlen, sizeof (struct scsi_sense_data), cdbl,
608                     60 * 1000);
609                 bcopy(cdb, ccb->csio.cdb_io.cdb_bytes, cdbl);
610         }
611
612         error = cam_periph_runccb(ccb, enc_error, ENC_CFLAGS, ENC_FLAGS, NULL);
613         if (error) {
614                 if (dptr) {
615                         *dlenp = dlen;
616                 }
617         } else {
618                 if (dptr) {
619                         if (ccb->ccb_h.func_code == XPT_ATA_IO)
620                                 *dlenp = ccb->ataio.resid;
621                         else
622                                 *dlenp = ccb->csio.resid;
623                         *dlenp += tdlen - dlen;
624                 }
625         }
626         xpt_release_ccb(ccb);
627         CAM_DEBUG(enc->periph->path, CAM_DEBUG_SUBTRACE,
628             ("exiting enc_runcmd: *dlenp = %d\n", *dlenp));
629         return (error);
630 }
631
632 void
633 enc_log(struct enc_softc *enc, const char *fmt, ...)
634 {
635         va_list ap;
636
637         printf("%s%d: ", enc->periph->periph_name, enc->periph->unit_number);
638         va_start(ap, fmt);
639         vprintf(fmt, ap);
640         va_end(ap);
641 }
642
643 /*
644  * The code after this point runs on many platforms,
645  * so forgive the slightly awkward and nonconforming
646  * appearance.
647  */
648
649 /*
650  * Is this a device that supports enclosure services?
651  *
652  * It's a pretty simple ruleset- if it is device type
653  * 0x0D (13), it's an ENCLOSURE device.
654  */
655
656 #define SAFTE_START     44
657 #define SAFTE_END       50
658 #define SAFTE_LEN       SAFTE_END-SAFTE_START
659
660 static enctyp
661 enc_type(struct ccb_getdev *cgd)
662 {
663         int buflen;
664         unsigned char *iqd;
665
666         if (cgd->protocol == PROTO_SEMB) {
667                 iqd = (unsigned char *)&cgd->ident_data;
668                 if (STRNCMP(iqd + 43, "S-E-S", 5) == 0)
669                         return (ENC_SEMB_SES);
670                 else if (STRNCMP(iqd + 43, "SAF-TE", 6) == 0)
671                         return (ENC_SEMB_SAFT);
672                 return (ENC_NONE);
673
674         } else if (cgd->protocol != PROTO_SCSI)
675                 return (ENC_NONE);
676
677         iqd = (unsigned char *)&cgd->inq_data;
678         buflen = min(sizeof(cgd->inq_data),
679             SID_ADDITIONAL_LENGTH(&cgd->inq_data));
680
681         if ((iqd[0] & 0x1f) == T_ENCLOSURE) {
682                 if ((iqd[2] & 0x7) > 2) {
683                         return (ENC_SES);
684                 } else {
685                         return (ENC_SES_SCSI2);
686                 }
687                 return (ENC_NONE);
688         }
689
690 #ifdef  SES_ENABLE_PASSTHROUGH
691         if ((iqd[6] & 0x40) && (iqd[2] & 0x7) >= 2) {
692                 /*
693                  * PassThrough Device.
694                  */
695                 return (ENC_SES_PASSTHROUGH);
696         }
697 #endif
698
699         /*
700          * The comparison is short for a reason-
701          * some vendors were chopping it short.
702          */
703
704         if (buflen < SAFTE_END - 2) {
705                 return (ENC_NONE);
706         }
707
708         if (STRNCMP((char *)&iqd[SAFTE_START], "SAF-TE", SAFTE_LEN - 2) == 0) {
709                 return (ENC_SAFT);
710         }
711         return (ENC_NONE);
712 }
713
714 /*================== Enclosure Monitoring/Processing Daemon ==================*/
715 /**
716  * \brief Queue an update request for a given action, if needed.
717  *
718  * \param enc           SES softc to queue the request for.
719  * \param action        Action requested.
720  */
721 void
722 enc_update_request(enc_softc_t *enc, uint32_t action)
723 {
724         if ((enc->pending_actions & (0x1 << action)) == 0) {
725                 enc->pending_actions |= (0x1 << action);
726                 ENC_DLOG(enc, "%s: queing requested action %d\n",
727                     __func__, action);
728                 if (enc->current_action == ENC_UPDATE_NONE)
729                         wakeup(enc->enc_daemon);
730         } else {
731                 ENC_DLOG(enc, "%s: ignoring requested action %d - "
732                     "Already queued\n", __func__, action);
733         }
734 }
735
736 /**
737  * \brief Invoke the handler of the highest priority pending
738  *        state in the SES state machine.
739  *
740  * \param enc  The SES instance invoking the state machine.
741  */
742 static void
743 enc_fsm_step(enc_softc_t *enc)
744 {
745         union ccb            *ccb;
746         uint8_t              *buf;
747         struct enc_fsm_state *cur_state;
748         int                   error;
749         uint32_t              xfer_len;
750         
751         ENC_DLOG(enc, "%s enter %p\n", __func__, enc);
752
753         enc->current_action   = ffs(enc->pending_actions) - 1;
754         enc->pending_actions &= ~(0x1 << enc->current_action);
755
756         cur_state = &enc->enc_fsm_states[enc->current_action];
757
758         buf = NULL;
759         if (cur_state->buf_size != 0) {
760                 cam_periph_unlock(enc->periph);
761                 buf = malloc(cur_state->buf_size, M_SCSIENC, M_WAITOK|M_ZERO);
762                 cam_periph_lock(enc->periph);
763         }
764
765         error = 0;
766         ccb   = NULL;
767         if (cur_state->fill != NULL) {
768                 ccb = cam_periph_getccb(enc->periph, CAM_PRIORITY_NORMAL);
769
770                 error = cur_state->fill(enc, cur_state, ccb, buf);
771                 if (error != 0)
772                         goto done;
773
774                 error = cam_periph_runccb(ccb, cur_state->error,
775                                           ENC_CFLAGS,
776                                           ENC_FLAGS|SF_QUIET_IR, NULL);
777         }
778
779         if (ccb != NULL) {
780                 if (ccb->ccb_h.func_code == XPT_ATA_IO)
781                         xfer_len = ccb->ataio.dxfer_len - ccb->ataio.resid;
782                 else
783                         xfer_len = ccb->csio.dxfer_len - ccb->csio.resid;
784         } else
785                 xfer_len = 0;
786
787         cam_periph_unlock(enc->periph);
788         cur_state->done(enc, cur_state, ccb, &buf, error, xfer_len);
789         cam_periph_lock(enc->periph);
790
791 done:
792         ENC_DLOG(enc, "%s exit - result %d\n", __func__, error);
793         ENC_FREE_AND_NULL(buf);
794         if (ccb != NULL)
795                 xpt_release_ccb(ccb);
796 }
797
798 /**
799  * \invariant Called with cam_periph mutex held.
800  */
801 static void
802 enc_status_updater(void *arg)
803 {
804         enc_softc_t *enc;
805
806         enc = arg;
807         if (enc->enc_vec.poll_status != NULL)
808                 enc->enc_vec.poll_status(enc);
809 }
810
811 static void
812 enc_daemon(void *arg)
813 {
814         enc_softc_t *enc;
815
816         enc = arg;
817
818         cam_periph_lock(enc->periph);
819         while ((enc->enc_flags & ENC_FLAG_SHUTDOWN) == 0) {
820                 if (enc->pending_actions == 0) {
821                         struct intr_config_hook *hook;
822
823                         /*
824                          * Reset callout and msleep, or
825                          * issue timed task completion
826                          * status command.
827                          */
828                         enc->current_action = ENC_UPDATE_NONE;
829
830                         /*
831                          * We've been through our state machine at least
832                          * once.  Allow the transition to userland.
833                          */
834                         hook = &enc->enc_boot_hold_ch;
835                         if (hook->ich_func != NULL) {
836                                 config_intrhook_disestablish(hook);
837                                 hook->ich_func = NULL;
838                         }
839
840                         callout_reset(&enc->status_updater, 60*hz,
841                                       enc_status_updater, enc);
842
843                         cam_periph_sleep(enc->periph, enc->enc_daemon,
844                                          PUSER, "idle", 0);
845                 } else {
846                         enc_fsm_step(enc);
847                 }
848         }
849         enc->enc_daemon = NULL;
850         cam_periph_unlock(enc->periph);
851         cam_periph_release(enc->periph);
852         kproc_exit(0);
853 }
854
855 static int
856 enc_kproc_init(enc_softc_t *enc)
857 {
858         int result;
859
860         callout_init_mtx(&enc->status_updater, cam_periph_mtx(enc->periph), 0);
861
862         if (cam_periph_acquire(enc->periph) != CAM_REQ_CMP)
863                 return (ENXIO);
864
865         result = kproc_create(enc_daemon, enc, &enc->enc_daemon, /*flags*/0,
866                               /*stackpgs*/0, "enc_daemon%d",
867                               enc->periph->unit_number);
868         if (result == 0) {
869                 /* Do an initial load of all page data. */
870                 cam_periph_lock(enc->periph);
871                 enc->enc_vec.poll_status(enc);
872                 cam_periph_unlock(enc->periph);
873         } else
874                 cam_periph_release(enc->periph);
875         return (result);
876 }
877  
878 /**
879  * \brief Interrupt configuration hook callback associated with
880  *        enc_boot_hold_ch.
881  *
882  * Since interrupts are always functional at the time of enclosure
883  * configuration, there is nothing to be done when the callback occurs.
884  * This hook is only registered to hold up boot processing while initial
885  * eclosure processing occurs.
886  * 
887  * \param arg  The enclosure softc, but currently unused in this callback.
888  */
889 static void
890 enc_nop_confighook_cb(void *arg __unused)
891 {
892 }
893
894 static cam_status
895 enc_ctor(struct cam_periph *periph, void *arg)
896 {
897         cam_status status = CAM_REQ_CMP_ERR;
898         int err;
899         enc_softc_t *enc;
900         struct ccb_getdev *cgd;
901         char *tname;
902         struct make_dev_args args;
903         struct sbuf sb;
904
905         cgd = (struct ccb_getdev *)arg;
906         if (cgd == NULL) {
907                 printf("enc_ctor: no getdev CCB, can't register device\n");
908                 goto out;
909         }
910
911         enc = ENC_MALLOCZ(sizeof(*enc));
912         if (enc == NULL) {
913                 printf("enc_ctor: Unable to probe new device. "
914                        "Unable to allocate enc\n");                             
915                 goto out;
916         }
917         enc->periph = periph;
918         enc->current_action = ENC_UPDATE_INVALID;
919
920         enc->enc_type = enc_type(cgd);
921         sx_init(&enc->enc_cache_lock, "enccache");
922
923         switch (enc->enc_type) {
924         case ENC_SES:
925         case ENC_SES_SCSI2:
926         case ENC_SES_PASSTHROUGH:
927         case ENC_SEMB_SES:
928                 err = ses_softc_init(enc);
929                 break;
930         case ENC_SAFT:
931         case ENC_SEMB_SAFT:
932                 err = safte_softc_init(enc);
933                 break;
934         case ENC_NONE:
935         default:
936                 ENC_FREE(enc);
937                 return (CAM_REQ_CMP_ERR);
938         }
939
940         if (err) {
941                 xpt_print(periph->path, "error %d initializing\n", err);
942                 goto out;
943         }
944
945         /*
946          * Hold off userland until we have made at least one pass
947          * through our state machine so that physical path data is
948          * present.
949          */
950         if (enc->enc_vec.poll_status != NULL) {
951                 enc->enc_boot_hold_ch.ich_func = enc_nop_confighook_cb;
952                 enc->enc_boot_hold_ch.ich_arg = enc;
953                 config_intrhook_establish(&enc->enc_boot_hold_ch);
954         }
955
956         /*
957          * The softc field is set only once the enc is fully initialized
958          * so that we can rely on this field to detect partially
959          * initialized periph objects in the AC_FOUND_DEVICE handler.
960          */
961         periph->softc = enc;
962
963         cam_periph_unlock(periph);
964         if (enc->enc_vec.poll_status != NULL) {
965                 err = enc_kproc_init(enc);
966                 if (err) {
967                         xpt_print(periph->path,
968                                   "error %d starting enc_daemon\n", err);
969                         goto out;
970                 }
971         }
972
973         /*
974          * Acquire a reference to the periph before we create the devfs
975          * instance for it.  We'll release this reference once the devfs
976          * instance has been freed.
977          */
978         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
979                 xpt_print(periph->path, "%s: lost periph during "
980                           "registration!\n", __func__);
981                 cam_periph_lock(periph);
982
983                 return (CAM_REQ_CMP_ERR);
984         }
985
986         make_dev_args_init(&args);
987         args.mda_devsw = &enc_cdevsw;
988         args.mda_unit = periph->unit_number;
989         args.mda_uid = UID_ROOT;
990         args.mda_gid = GID_OPERATOR;
991         args.mda_mode = 0600;
992         args.mda_si_drv1 = periph;
993         err = make_dev_s(&args, &enc->enc_dev, "%s%d", periph->periph_name,
994             periph->unit_number);
995         cam_periph_lock(periph);
996         if (err != 0) {
997                 cam_periph_release_locked(periph);
998                 return (CAM_REQ_CMP_ERR);
999         }
1000
1001         enc->enc_flags |= ENC_FLAG_INITIALIZED;
1002
1003         /*
1004          * Add an async callback so that we get notified if this
1005          * device goes away.
1006          */
1007         xpt_register_async(AC_LOST_DEVICE, enc_async, periph, periph->path);
1008
1009         switch (enc->enc_type) {
1010         default:
1011         case ENC_NONE:
1012                 tname = "No ENC device";
1013                 break;
1014         case ENC_SES_SCSI2:
1015                 tname = "SCSI-2 ENC Device";
1016                 break;
1017         case ENC_SES:
1018                 tname = "SCSI-3 ENC Device";
1019                 break;
1020         case ENC_SES_PASSTHROUGH:
1021                 tname = "ENC Passthrough Device";
1022                 break;
1023         case ENC_SAFT:
1024                 tname = "SAF-TE Compliant Device";
1025                 break;
1026         case ENC_SEMB_SES:
1027                 tname = "SEMB SES Device";
1028                 break;
1029         case ENC_SEMB_SAFT:
1030                 tname = "SEMB SAF-TE Device";
1031                 break;
1032         }
1033
1034         sbuf_new(&sb, enc->announce_buf, ENC_ANNOUNCE_SZ, SBUF_FIXEDLEN);
1035         xpt_announce_periph_sbuf(periph, &sb, tname);
1036         sbuf_finish(&sb);
1037         sbuf_putbuf(&sb);
1038
1039         status = CAM_REQ_CMP;
1040
1041 out:
1042         if (status != CAM_REQ_CMP)
1043                 enc_dtor(periph);
1044         return (status);
1045 }
1046