kernel - Make filters able to be marked MPSAFE
[dragonfly.git] / sys / dev / misc / tw / tw.c
1 /*-
2  * Copyright (c) 1992, 1993, 1995 Eugene W. Stark
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Eugene W. Stark.
16  * 4. 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 EUGENE W. STARK (THE AUTHOR) ``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 BE LIABLE FOR ANY DIRECT,
23  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25  * 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  * $FreeBSD: src/sys/i386/isa/tw.c,v 1.38 2000/01/29 16:00:32 peter Exp $
32  * $DragonFly: src/sys/dev/misc/tw/tw.c,v 1.19 2008/08/02 01:14:42 dillon Exp $
33  *
34  */
35
36 #include "use_tw.h"
37
38 /*
39  * Driver configuration parameters
40  */
41
42 /*
43  * Time for 1/2 of a power line cycle, in microseconds.
44  * Change this to 10000 for 50Hz power.  Phil Sampson
45  * (vk2jnt@gw.vk2jnt.ampr.org OR sampson@gidday.enet.dec.com)
46  * reports that this works (at least in Australia) using a
47  * TW7223 module (a local version of the TW523).
48  */
49 #define HALFCYCLE 8333                  /* 1/2 cycle = 8333us at 60Hz */
50
51 /*
52  * Undefine the following if you don't have the high-resolution "microtime"
53  * routines (leave defined for FreeBSD, which has them).
54  */
55 #define HIRESTIME
56
57 /*
58  * End of driver configuration parameters
59  */
60
61 /*
62  * FreeBSD Device Driver for X-10 POWERHOUSE (tm)
63  * Two-Way Power Line Interface, Model #TW523
64  *
65  * written by Eugene W. Stark (stark@cs.sunysb.edu)
66  * December 2, 1992
67  *
68  * NOTES:
69  *
70  * The TW523 is a carrier-current modem for home control/automation purposes.
71  * It is made by:
72  *
73  *      X-10 Inc.
74  *      185A LeGrand Ave.
75  *      Northvale, NJ 07647
76  *      USA
77  *      (201) 784-9700 or 1-800-526-0027
78  *
79  *      X-10 Home Controls Inc.
80  *      1200 Aerowood Drive, Unit 20
81  *      Mississauga, Ontario
82  *      (416) 624-4446 or 1-800-387-3346
83  *
84  * The TW523 is designed for communications using the X-10 protocol,
85  * which is compatible with a number of home control systems, including
86  * Radio Shack "Plug 'n Power(tm)" and Stanley "Lightmaker(tm)."
87  * I bought my TW523 from:
88  *
89  *      Home Control Concepts
90  *      9353-C Activity Road
91  *      San Diego, CA 92126
92  *      (619) 693-8887
93  *
94  * They supplied me with the TW523 (which has an RJ-11 four-wire modular
95  * telephone connector), a modular cable, an RJ-11 to DB-25 connector with
96  * internal wiring, documentation from X-10 on the TW523 (very good),
97  * an instruction manual by Home Control Concepts (not very informative),
98  * and a floppy disk containing binary object code of some demonstration/test
99  * programs and of a C function library suitable for controlling the TW523
100  * by an IBM PC under MS-DOS (not useful to me other than to verify that
101  * the unit worked).  I suggest saving money and buying the bare TW523
102  * rather than the TW523 development kit (what I bought), because if you
103  * are running FreeBSD you don't really care about the DOS binaries.
104  *
105  * The interface to the TW-523 consists of four wires on the RJ-11 connector,
106  * which are jumpered to somewhat more wires on the DB-25 connector, which
107  * in turn is intended to plug into the PC parallel printer port.  I dismantled
108  * the DB-25 connector to find out what they had done:
109  *
110  *      Signal          RJ-11 pin       DB-25 pin(s)    Parallel Port
111  *      Transmit TX       4 (Y)         2, 4, 6, 8      Data out
112  *      Receive RX        3 (G)         10, 14          -ACK, -AutoFeed
113  *      Common            2 (R)         25              Common
114  *      Zero crossing     1 (B)         17 or 12        -Select or +PaperEnd
115  *
116  * NOTE: In the original cable I have (which I am still using, May, 1997)
117  * the Zero crossing signal goes to pin 17 (-Select) on the parallel port.
118  * In retrospect, this doesn't make a whole lot of sense, given that the
119  * -Select signal propagates the other direction.  Indeed, some people have
120  * reported problems with this, and have had success using pin 12 (+PaperEnd)
121  * instead.  This driver searches for the zero crossing signal on either
122  * pin 17 or pin 12, so it should work with either cable configuration.
123  * My suggestion would be to start by making the cable so that the zero
124  * crossing signal goes to pin 12 on the parallel port.
125  *
126  * The zero crossing signal is used to synchronize transmission to the
127  * zero crossings of the AC line, as detailed in the X-10 documentation.
128  * It would be nice if one could generate interrupts with this signal,
129  * however one needs interrupts on both the rising and falling edges,
130  * and the -ACK signal to the parallel port interrupts only on the falling
131  * edge, so it can't be done without additional hardware.
132  *
133  * In this driver, the transmit function is performed in a non-interrupt-driven
134  * fashion, by polling the zero crossing signal to determine when a transition
135  * has occurred.  This wastes CPU time during transmission, but it seems like
136  * the best that can be done without additional hardware.  One problem with
137  * the scheme is that preemption of the CPU during transmission can cause loss
138  * of sync.  The driver tries to catch this, by noticing that a long delay
139  * loop has somehow become foreshortened, and the transmission is aborted with
140  * an error return.  It is up to the user level software to handle this
141  * situation (most likely by retrying the transmission).
142  */
143
144 #include <sys/param.h>
145 #include <sys/systm.h>
146 #include <sys/conf.h>
147 #include <sys/device.h>
148 #include <sys/kernel.h>
149 #include <sys/uio.h>
150 #include <sys/syslog.h>
151 #include <sys/event.h>
152 #include <sys/thread2.h>
153
154 #ifdef HIRESTIME
155 #include <sys/time.h>
156 #endif /* HIRESTIME */
157
158 #include <bus/isa/isa_device.h>
159
160 /*
161  * Transmission is done by calling write() to send three byte packets of data.
162  * The first byte contains a four bit house code (0=A to 15=P).
163  * The second byte contains five bit unit/key code (0=unit 1 to 15=unit 16,
164  * 16=All Units Off to 31 = Status Request).  The third byte specifies
165  * the number of times the packet is to be transmitted without any
166  * gaps between successive transmissions.  Normally this is 2, as per
167  * the X-10 documentation, but sometimes (e.g. for bright and dim codes)
168  * it can be another value.  Each call to write can specify an arbitrary
169  * number of data bytes.  An incomplete packet is buffered until a subsequent
170  * call to write() provides data to complete it.  At most one packet will
171  * actually be processed in any call to write().  Successive calls to write()
172  * leave a three-cycle gap between transmissions, per the X-10 documentation.
173  *
174  * Reception is done using read().
175  * The driver produces a series of three-character packets.
176  * In each packet, the first character consists of flags,
177  * the second character is a four bit house code (0-15),
178  * and the third character is a five bit key/function code (0-31).
179  * The flags are the following:
180  */
181
182 #define TW_RCV_LOCAL    1  /* The packet arrived during a local transmission */
183 #define TW_RCV_ERROR    2  /* An invalid/corrupted packet was received */
184
185 /*
186  * IBM PC parallel port definitions relevant to TW523
187  */
188
189 #define tw_data 0                       /* Data to tw523 (R/W) */
190
191 #define tw_status 1                     /* Status of tw523 (R) */
192 #define TWS_RDATA               0x40    /* tw523 receive data */
193 #define TWS_OUT                 0x20    /* pin 12, out of paper */
194
195 #define tw_control 2                    /* Control tw523 (R/W) */
196 #define TWC_SYNC                0x08    /* tw523 sync (pin 17) */
197 #define TWC_ENA                 0x10    /* tw523 interrupt enable */
198
199 /*
200  * Miscellaneous defines
201  */
202
203 #define TWUNIT(dev)     (minor(dev))    /* Extract unit number from device */
204
205 static int twprobe(struct isa_device *idp);
206 static int twattach(struct isa_device *idp);
207
208 struct isa_driver twdriver = {
209   twprobe, twattach, "tw"
210 };
211
212 static  d_open_t        twopen;
213 static  d_close_t       twclose;
214 static  d_read_t        twread;
215 static  d_write_t       twwrite;
216 static  d_kqfilter_t    twkqfilter;
217
218 static void twfilter_detach(struct knote *);
219 static int twfilter_read(struct knote *, long);
220 static int twfilter_write(struct knote *, long);
221
222 #define CDEV_MAJOR 19
223 static struct dev_ops tw_ops = {
224         { "tw", CDEV_MAJOR, 0 },
225         .d_open =       twopen,
226         .d_close =      twclose,
227         .d_read =       twread,
228         .d_write =      twwrite,
229         .d_kqfilter =   twkqfilter
230 };
231
232 /*
233  * Software control structure for TW523
234  */
235
236 #define TWS_XMITTING     1      /* Transmission in progress */
237 #define TWS_RCVING       2      /* Reception in progress */
238 #define TWS_WANT         4      /* A process wants received data */
239 #define TWS_OPEN         8      /* Is it currently open? */
240
241 #define TW_SIZE         3*60    /* Enough for about 10 sec. of input */
242 #define TW_MIN_DELAY    1500    /* Ignore interrupts of lesser latency */
243
244 static struct tw_sc {
245   u_int sc_port;                /* I/O Port */
246   u_int sc_state;               /* Current software control state */
247   struct kqinfo sc_kqp;         /* Information for select()/poll()/kq() */
248   u_char sc_xphase;             /* Current state of sync (for transmitter) */
249   u_char sc_rphase;             /* Current state of sync (for receiver) */
250   u_char sc_flags;              /* Flags for current reception */
251   short sc_rcount;              /* Number of bits received so far */
252   int sc_bits;                  /* Bits received so far */
253   u_char sc_pkt[3];             /* Packet not yet transmitted */
254   short sc_pktsize;             /* How many bytes in the packet? */
255   u_char sc_buf[TW_SIZE];       /* We buffer our own input */
256   int sc_nextin;                /* Next free slot in circular buffer */
257   int sc_nextout;               /* First used slot in circular buffer */
258                                 /* Callout for canceling our abortrcv timeout */
259   struct callout abortrcv_ch;
260 #ifdef HIRESTIME
261   int sc_xtimes[22];            /* Times for bits in current xmit packet */
262   int sc_rtimes[22];            /* Times for bits in current rcv packet */
263   int sc_no_rcv;                /* number of interrupts received */
264 #define SC_RCV_TIME_LEN 128
265   int sc_rcv_time[SC_RCV_TIME_LEN]; /* usec time stamp on interrupt */
266 #endif /* HIRESTIME */
267 } tw_sc[NTW];
268
269 static int tw_zcport;           /* offset of port for zero crossing signal */
270 static int tw_zcmask;           /* mask for the zero crossing signal */
271
272 static void twdelay25(void);
273 static void twdelayn(int n);
274 static void twsetuptimes(int *a);
275 static int wait_for_zero(struct tw_sc *sc);
276 static int twputpkt(struct tw_sc *sc, u_char *p);
277 static void twintr(void *);
278 static int twgetbytes(struct tw_sc *sc, u_char *p, int cnt);
279 static timeout_t twabortrcv;
280 static int twsend(struct tw_sc *sc, int h, int k, int cnt);
281 static int next_zero(struct tw_sc *sc);
282 static int twchecktime(int target, int tol);
283 static void twdebugtimes(struct tw_sc *sc);
284
285 /*
286  * Counter value for delay loop.
287  * It is adjusted by twprobe so that the delay loop takes about 25us.
288  */
289
290 #define TWDELAYCOUNT 161                /* Works on my 486DX/33 */
291 static int twdelaycount;
292
293 /*
294  * Twdelay25 is used for very short delays of about 25us.
295  * It is implemented with a calibrated delay loop, and should be
296  * fairly accurate ... unless we are preempted by an interrupt.
297  *
298  * We use this to wait for zero crossings because the X-10 specs say we
299  * are supposed to assert carrier within 25us when one happens.
300  * I don't really believe we can do this, but the X-10 devices seem to be
301  * fairly forgiving.
302  */
303
304 static void
305 twdelay25(void)
306 {
307   int cnt;
308   for(cnt = twdelaycount; cnt; cnt--);  /* Should take about 25us */
309 }
310
311 /*
312  * Twdelayn is used to time the length of the 1ms carrier pulse.
313  * This is not very critical, but if we have high-resolution time-of-day
314  * we check it every apparent 200us to make sure we don't get too far off
315  * if we happen to be interrupted during the delay.
316  */
317
318 static void
319 twdelayn(int n)
320 {
321 #ifdef HIRESTIME
322   int t, d;
323   struct timeval tv;
324   microtime(&tv);
325   t = tv.tv_usec;
326   t += n;
327 #endif /* HIRESTIME */
328   while(n > 0) {
329     twdelay25();
330     n -= 25;
331 #ifdef HIRESTIME
332     if((n & 0x7) == 0) {
333       microtime(&tv);
334       d = tv.tv_usec - t;
335       if(d >= 0 && d < 1000000) return;
336     }
337 #endif /* HIRESTIME */
338   }
339 }
340
341 static int
342 twprobe(struct isa_device *idp)
343 {
344   struct tw_sc sc;
345   int d;
346   int tries;
347
348   sc.sc_port = idp->id_iobase;
349   /* Search for the zero crossing signal at ports, bit combinations. */
350   tw_zcport = tw_control;
351   tw_zcmask = TWC_SYNC;
352   sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
353   if(wait_for_zero(&sc) < 0) {
354     tw_zcport = tw_status;
355     tw_zcmask = TWS_OUT;
356     sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
357   }
358   if(wait_for_zero(&sc) < 0)
359     return(0);
360   /*
361    * Iteratively check the timing of a few sync transitions, and adjust
362    * the loop delay counter, if necessary, to bring the timing reported
363    * by wait_for_zero() close to HALFCYCLE.  Give up if anything
364    * ridiculous happens.
365    */
366   if(twdelaycount == 0) {  /* Only adjust timing for first unit */
367     twdelaycount = TWDELAYCOUNT;
368     for(tries = 0; tries < 10; tries++) {
369       sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
370       if(wait_for_zero(&sc) >= 0) {
371         d = wait_for_zero(&sc);
372         if(d <= HALFCYCLE/100 || d >= HALFCYCLE*100) {
373           twdelaycount = 0;
374           return(0);
375         }
376         twdelaycount = (twdelaycount * d)/HALFCYCLE;
377       }
378     }
379   }
380   /*
381    * Now do a final check, just to make sure
382    */
383   sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
384   if(wait_for_zero(&sc) >= 0) {
385     d = wait_for_zero(&sc);
386     if(d <= (HALFCYCLE * 110)/100 && d >= (HALFCYCLE * 90)/100) return(8);
387   }
388   return(0);
389 }
390
391 static int
392 twattach(struct isa_device *idp)
393 {
394   struct tw_sc *sc;
395   int   unit;
396
397   idp->id_intr = (inthand2_t *)twintr;
398   sc = &tw_sc[unit = idp->id_unit];
399   sc->sc_port = idp->id_iobase;
400   sc->sc_state = 0;
401   sc->sc_rcount = 0;
402   callout_init(&sc->abortrcv_ch);
403   make_dev(&tw_ops, unit, 0, 0, 0600, "tw%d", unit);
404   return (1);
405 }
406
407 int
408 twopen(struct dev_open_args *ap)
409 {
410   cdev_t dev = ap->a_head.a_dev;
411   struct tw_sc *sc = &tw_sc[TWUNIT(dev)];
412
413   crit_enter();
414   if(sc->sc_state == 0) {
415     sc->sc_state = TWS_OPEN;
416     sc->sc_nextin = sc->sc_nextout = 0;
417     sc->sc_pktsize = 0;
418     outb(sc->sc_port+tw_control, TWC_ENA);
419   }
420   crit_exit();
421   return(0);
422 }
423
424 int
425 twclose(struct dev_close_args *ap)
426 {
427   cdev_t dev = ap->a_head.a_dev;
428   struct tw_sc *sc = &tw_sc[TWUNIT(dev)];
429
430   crit_enter();
431   sc->sc_state = 0;
432   outb(sc->sc_port+tw_control, 0);
433   crit_exit();
434   return(0);
435 }
436
437 int
438 twread(struct dev_read_args *ap)
439 {
440   cdev_t dev = ap->a_head.a_dev;
441   struct uio *uio = ap->a_uio;
442   u_char buf[3];
443   struct tw_sc *sc = &tw_sc[TWUNIT(dev)];
444   int error, cnt;
445
446   crit_enter();
447   cnt = MIN(uio->uio_resid, 3);
448   if((error = twgetbytes(sc, buf, cnt)) == 0) {
449     error = uiomove(buf, cnt, uio);
450   }
451   crit_exit();
452   return(error);
453 }
454
455 int
456 twwrite(struct dev_write_args *ap)
457 {
458   cdev_t dev = ap->a_head.a_dev;
459   struct uio *uio = ap->a_uio;
460   struct tw_sc *sc;
461   int house, key, reps;
462   int error;
463   int cnt;
464
465   sc = &tw_sc[TWUNIT(dev)];
466   /*
467    * Note: Although I had intended to allow concurrent transmitters,
468    * there is a potential problem here if two processes both write
469    * into the sc_pkt buffer at the same time.  The following code
470    * is an additional critical section that needs to be synchronized.
471    */
472   crit_enter();
473   cnt = MIN(3 - sc->sc_pktsize, uio->uio_resid);
474   error = uiomove(&(sc->sc_pkt[sc->sc_pktsize]), cnt, uio);
475   if(error) {
476     crit_exit();
477     return(error);
478   }
479   sc->sc_pktsize += cnt;
480   if(sc->sc_pktsize < 3) {  /* Only transmit 3-byte packets */
481     crit_exit();
482     return(0);
483   }
484   sc->sc_pktsize = 0;
485   /*
486    * Collect house code, key code, and rep count, and check for sanity.
487    */
488   house = sc->sc_pkt[0];
489   key = sc->sc_pkt[1];
490   reps = sc->sc_pkt[2];
491   if(house >= 16 || key >= 32) {
492     crit_exit();
493     return(ENODEV);
494   }
495   /*
496    * Synchronize with the receiver operating in the bottom half, and
497    * also with concurrent transmitters.
498    * We don't want to interfere with a packet currently being received,
499    * and we would like the receiver to recognize when a packet has
500    * originated locally.
501    */
502   while(sc->sc_state & (TWS_RCVING | TWS_XMITTING)) {
503     error = tsleep((caddr_t)sc, PCATCH, "twwrite", 0);
504     if(error) {
505       crit_exit();
506       return(error);
507     }
508   }
509   sc->sc_state |= TWS_XMITTING;
510   /*
511    * Everything looks OK, let's do the transmission.
512    */
513   crit_exit(); /* Enable interrupts because this takes a LONG time */
514   error = twsend(sc, house, key, reps);
515   crit_enter();
516   sc->sc_state &= ~TWS_XMITTING;
517   wakeup((caddr_t)sc);
518   crit_exit();
519   if(error) return(EIO);
520   else return(0);
521 }
522
523 /*
524  * Determine if there is data available for reading
525  */
526
527 static struct filterops twfiltops_read =
528         { FILTEROP_ISFD, NULL, twfilter_detach, twfilter_read };
529 static struct filterops twfiltops_write =
530         { FILTEROP_ISFD, NULL, twfilter_detach, twfilter_write };
531
532 static int
533 twkqfilter(struct dev_kqfilter_args *ap)
534 {
535   cdev_t dev = ap->a_head.a_dev;
536   struct knote *kn = ap->a_kn;
537   struct klist *klist;
538   struct tw_sc *sc;
539
540   ap->a_result = 0;
541
542   switch (kn->kn_filter) {
543   case EVFILT_READ:
544     sc = &tw_sc[TWUNIT(dev)];
545     kn->kn_fop = &twfiltops_read;
546     kn->kn_hook = (caddr_t)sc;
547     break;
548   case EVFILT_WRITE:
549     sc = &tw_sc[TWUNIT(dev)];
550     kn->kn_fop = &twfiltops_write;
551     kn->kn_hook = (caddr_t)sc;
552     break;
553   default:
554     ap->a_result = EOPNOTSUPP;
555     return (0);
556   }
557
558   klist = &sc->sc_kqp.ki_note;
559   knote_insert(klist, kn);
560
561   return (0);
562 }
563
564 static void
565 twfilter_detach(struct knote *kn)
566 {
567   struct tw_sc *sc = (struct tw_sc *)kn->kn_hook;
568   struct klist *klist;
569
570   klist = &sc->sc_kqp.ki_note;
571   knote_remove(klist, kn);
572 }
573
574 static int
575 twfilter_read(struct knote *kn, long hint)
576 {
577   struct tw_sc *sc = (struct tw_sc *)kn->kn_hook;
578   int ready = 0;
579
580   crit_enter();
581   if(sc->sc_nextin != sc->sc_nextout)
582     ready = 1;
583   crit_exit();
584
585   return (ready);
586 }
587
588 static int
589 twfilter_write(struct knote *kn, long hint)
590 {
591   /* write() is always OK */
592   return (1);
593 }
594
595 /*
596  * X-10 Protocol
597  */
598
599 #define X10_START_LENGTH 4
600 static char X10_START[] = { 1, 1, 1, 0 };
601
602 /*
603  * Each bit of the 4-bit house code and 5-bit key code
604  * is transmitted twice, once in true form, and then in
605  * complemented form.  This is already taken into account
606  * in the following tables.
607  */
608
609 #define X10_HOUSE_LENGTH 8
610 static char X10_HOUSE[16][8] = {
611         { 0, 1, 1, 0, 1, 0, 0, 1 },             /* A = 0110 */
612         { 1, 0, 1, 0, 1, 0, 0, 1 },             /* B = 1110 */
613         { 0, 1, 0, 1, 1, 0, 0, 1 },             /* C = 0010 */
614         { 1, 0, 0, 1, 1, 0, 0, 1 },             /* D = 1010 */
615         { 0, 1, 0, 1, 0, 1, 1, 0 },             /* E = 0001 */
616         { 1, 0, 0, 1, 0, 1, 1, 0 },             /* F = 1001 */
617         { 0, 1, 1, 0, 0, 1, 1, 0 },             /* G = 0101 */
618         { 1, 0, 1, 0, 0, 1, 1, 0 },             /* H = 1101 */
619         { 0, 1, 1, 0, 1, 0, 1, 0 },             /* I = 0111 */
620         { 1, 0, 1, 0, 1, 0, 1, 0 },             /* J = 1111 */
621         { 0, 1, 0, 1, 1, 0, 1, 0 },             /* K = 0011 */
622         { 1, 0, 0, 1, 1, 0, 1, 0 },             /* L = 1011 */
623         { 0, 1, 0, 1, 0, 1, 0, 1 },             /* M = 0000 */
624         { 1, 0, 0, 1, 0, 1, 0, 1 },             /* N = 1000 */
625         { 0, 1, 1, 0, 0, 1, 0, 1 },             /* O = 0100 */
626         { 1, 0, 1, 0, 0, 1, 0, 1 }              /* P = 1100 */
627 };
628
629 #define X10_KEY_LENGTH 10
630 static char X10_KEY[32][10] = {
631         { 0, 1, 1, 0, 1, 0, 0, 1, 0, 1 },       /* 01100 => 1 */
632         { 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 },       /* 11100 => 2 */
633         { 0, 1, 0, 1, 1, 0, 0, 1, 0, 1 },       /* 00100 => 3 */
634         { 1, 0, 0, 1, 1, 0, 0, 1, 0, 1 },       /* 10100 => 4 */
635         { 0, 1, 0, 1, 0, 1, 1, 0, 0, 1 },       /* 00010 => 5 */
636         { 1, 0, 0, 1, 0, 1, 1, 0, 0, 1 },       /* 10010 => 6 */
637         { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1 },       /* 01010 => 7 */
638         { 1, 0, 1, 0, 0, 1, 1, 0, 0, 1 },       /* 11010 => 8 */
639         { 0, 1, 1, 0, 1, 0, 1, 0, 0, 1 },       /* 01110 => 9 */
640         { 1, 0, 1, 0, 1, 0, 1, 0, 0, 1 },       /* 11110 => 10 */
641         { 0, 1, 0, 1, 1, 0, 1, 0, 0, 1 },       /* 00110 => 11 */
642         { 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 },       /* 10110 => 12 */
643         { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 },       /* 00000 => 13 */
644         { 1, 0, 0, 1, 0, 1, 0, 1, 0, 1 },       /* 10000 => 14 */
645         { 0, 1, 1, 0, 0, 1, 0, 1, 0, 1 },       /* 01000 => 15 */
646         { 1, 0, 1, 0, 0, 1, 0, 1, 0, 1 },       /* 11000 => 16 */
647         { 0, 1, 0, 1, 0, 1, 0, 1, 1, 0 },       /* 00001 => All Units Off */
648         { 0, 1, 0, 1, 0, 1, 1, 0, 1, 0 },       /* 00011 => All Units On */
649         { 0, 1, 0, 1, 1, 0, 0, 1, 1, 0 },       /* 00101 => On */
650         { 0, 1, 0, 1, 1, 0, 1, 0, 1, 0 },       /* 00111 => Off */
651         { 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 },       /* 01001 => Dim */
652         { 0, 1, 1, 0, 0, 1, 1, 0, 1, 0 },       /* 01011 => Bright */
653         { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0 },       /* 01101 => All LIGHTS Off */
654         { 0, 1, 1, 0, 1, 0, 1, 0, 1, 0 },       /* 01111 => Extended Code */
655         { 1, 0, 0, 1, 0, 1, 0, 1, 1, 0 },       /* 10001 => Hail Request */
656         { 1, 0, 0, 1, 0, 1, 1, 0, 1, 0 },       /* 10011 => Hail Acknowledge */
657         { 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 },       /* 10101 => Preset Dim 0 */
658         { 1, 0, 0, 1, 1, 0, 1, 0, 1, 0 },       /* 10111 => Preset Dim 1 */
659         { 1, 0, 1, 0, 0, 1, 0, 1, 0, 1 },       /* 11000 => Extended Data (analog) */
660         { 1, 0, 1, 0, 0, 1, 1, 0, 1, 0 },       /* 11011 => Status = on */
661         { 1, 0, 1, 0, 1, 0, 0, 1, 1, 0 },       /* 11101 => Status = off */
662         { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }        /* 11111 => Status request */
663 };
664
665 /*
666  * Tables for mapping received X-10 code back to house/key number.
667  */
668
669 static short X10_HOUSE_INV[16] = {
670       12,  4,  2, 10, 14,  6,  0,  8,
671       13,  5,  3, 11, 15,  7,  1,  9
672 };
673
674 static short X10_KEY_INV[32] = { 
675       12, 16,  4, 17,  2, 18, 10, 19,
676       14, 20,  6, 21,  0, 22,  8, 23,
677       13, 24,  5, 25,  3, 26, 11, 27,
678       15, 28,  7, 29,  1, 30,  9, 31
679 };
680
681 static char *X10_KEY_LABEL[32] = {
682  "1",
683  "2",
684  "3",
685  "4",
686  "5",
687  "6",
688  "7",
689  "8",
690  "9",
691  "10",
692  "11",
693  "12",
694  "13",
695  "14",
696  "15",
697  "16",
698  "All Units Off",
699  "All Units On",
700  "On",
701  "Off",
702  "Dim",
703  "Bright",
704  "All LIGHTS Off",
705  "Extended Code",
706  "Hail Request",
707  "Hail Acknowledge",
708  "Preset Dim 0",
709  "Preset Dim 1",
710  "Extended Data (analog)",
711  "Status = on",
712  "Status = off",
713  "Status request"
714 };
715 /*
716  * Transmit a packet containing house code h and key code k
717  */
718
719 #define TWRETRY         10              /* Try 10 times to sync with AC line */
720
721 static int
722 twsend(struct tw_sc *sc, int h, int k, int cnt)
723 {
724   int i;
725   int port = sc->sc_port;
726
727   /*
728    * Make sure we get a reliable sync with a power line zero crossing
729    */
730   for(i = 0; i < TWRETRY; i++) {
731     if(wait_for_zero(sc) > 100) goto insync;
732   }
733   log(LOG_ERR, "TWXMIT: failed to sync.\n");
734   return(-1);
735
736  insync:
737   /*
738    * Be sure to leave 3 cycles space between transmissions
739    */
740   for(i = 6; i > 0; i--)
741         if(next_zero(sc) < 0) return(-1);
742   /*
743    * The packet is transmitted cnt times, with no gaps.
744    */
745   while(cnt--) {
746     /*
747      * Transmit the start code
748      */
749     for(i = 0; i < X10_START_LENGTH; i++) {
750       outb(port+tw_data, X10_START[i] ? 0xff : 0x00);  /* Waste no time! */
751 #ifdef HIRESTIME
752       if(i == 0) twsetuptimes(sc->sc_xtimes);
753       if(twchecktime(sc->sc_xtimes[i], HALFCYCLE/20) == 0) {
754         outb(port+tw_data, 0);
755         return(-1);
756       }
757 #endif /* HIRESTIME */
758       twdelayn(1000);   /* 1ms pulse width */
759       outb(port+tw_data, 0);
760       if(next_zero(sc) < 0) return(-1);
761     }
762     /*
763      * Transmit the house code
764      */
765     for(i = 0; i < X10_HOUSE_LENGTH; i++) {
766       outb(port+tw_data, X10_HOUSE[h][i] ? 0xff : 0x00);  /* Waste no time! */
767 #ifdef HIRESTIME
768       if(twchecktime(sc->sc_xtimes[i+X10_START_LENGTH], HALFCYCLE/20) == 0) {
769         outb(port+tw_data, 0);
770         return(-1);
771       }
772 #endif /* HIRESTIME */
773       twdelayn(1000);   /* 1ms pulse width */
774       outb(port+tw_data, 0);
775       if(next_zero(sc) < 0) return(-1);
776     }
777     /*
778      * Transmit the unit/key code
779      */
780     for(i = 0; i < X10_KEY_LENGTH; i++) {
781       outb(port+tw_data, X10_KEY[k][i] ? 0xff : 0x00);
782 #ifdef HIRESTIME
783       if(twchecktime(sc->sc_xtimes[i+X10_START_LENGTH+X10_HOUSE_LENGTH],
784                         HALFCYCLE/20) == 0) {
785         outb(port+tw_data, 0);
786         return(-1);
787       }
788 #endif /* HIRESTIME */
789       twdelayn(1000);   /* 1ms pulse width */
790       outb(port+tw_data, 0);
791       if(next_zero(sc) < 0) return(-1);
792     }
793   }
794   return(0);
795 }
796
797 /*
798  * Waste CPU cycles to get in sync with a power line zero crossing.
799  * The value returned is roughly how many microseconds we wasted before
800  * seeing the transition.  To avoid wasting time forever, we give up after
801  * waiting patiently for 1/4 sec (15 power line cycles at 60 Hz),
802  * which is more than the 11 cycles it takes to transmit a full
803  * X-10 packet.
804  */
805
806 static int
807 wait_for_zero(struct tw_sc *sc)
808 {
809   int i, old, new, max;
810   int port = sc->sc_port + tw_zcport;
811
812   old = sc->sc_xphase;
813   max = 10000;          /* 10000 * 25us = 0.25 sec */
814   i = 0;
815   while(max--) {
816     new = inb(port) & tw_zcmask;
817     if(new != old) {
818       sc->sc_xphase = new;
819       return(i*25);
820     }
821     i++;
822     twdelay25();
823   }
824   return(-1);
825 }
826
827 /*
828  * Wait for the next zero crossing transition, and if we don't have
829  * high-resolution time-of-day, check to see that the zero crossing
830  * appears to be arriving on schedule.
831  * We expect to be waiting almost a full half-cycle (8.333ms-1ms = 7.333ms).
832  * If we don't seem to wait very long, something is wrong (like we got
833  * preempted!) and we should abort the transmission because
834  * there's no telling how long it's really been since the
835  * last bit was transmitted.
836  */
837
838 static int
839 next_zero(struct tw_sc *sc)
840 {
841   int d;
842 #ifdef HIRESTIME
843   if((d = wait_for_zero(sc)) < 0) {
844 #else
845   if((d = wait_for_zero(sc)) < 6000 || d > 8500) {
846         /* No less than 6.0ms, no more than 8.5ms */
847 #endif /* HIRESTIME */
848     log(LOG_ERR, "TWXMIT framing error: %d\n", d);
849     return(-1);
850   }
851   return(0);
852 }
853
854 /*
855  * Put a three-byte packet into the circular buffer
856  * Should be called from a critical section.
857  */
858
859 static int
860 twputpkt(struct tw_sc *sc, u_char *p)
861 {
862   int i, next;
863
864   for(i = 0; i < 3; i++) {
865     next = sc->sc_nextin+1;
866     if(next >= TW_SIZE) next = 0;
867     if(next == sc->sc_nextout) {  /* Buffer full */
868 /*
869       log(LOG_ERR, "TWRCV: Buffer overrun\n");
870  */
871       return(1);
872     }
873     sc->sc_buf[sc->sc_nextin] = *p++;
874     sc->sc_nextin = next;
875   }
876   if(sc->sc_state & TWS_WANT) {
877     sc->sc_state &= ~TWS_WANT;
878     wakeup((caddr_t)(&sc->sc_buf));
879   }
880   KNOTE(&sc->sc_kqp.ki_note, 0);
881   return(0);
882 }
883
884 /*
885  * Get bytes from the circular buffer
886  * Should be called from a critical section.
887  */
888
889 static int
890 twgetbytes(struct tw_sc *sc, u_char *p, int cnt)
891 {
892   int error;
893
894   while(cnt--) {
895     while(sc->sc_nextin == sc->sc_nextout) {  /* Buffer empty */
896       sc->sc_state |= TWS_WANT;
897       error = tsleep((caddr_t)(&sc->sc_buf), PCATCH, "twread", 0);
898       if(error) {
899         return(error);
900       }
901     }
902     *p++ = sc->sc_buf[sc->sc_nextout++];
903     if(sc->sc_nextout >= TW_SIZE) sc->sc_nextout = 0;
904   }
905   return(0);
906 }
907
908 /*
909  * Abort reception that has failed to complete in the required time.
910  */
911
912 static void
913 twabortrcv(void *arg)
914 {
915   struct tw_sc *sc = arg;
916   u_char pkt[3];
917
918   crit_enter();
919   sc->sc_state &= ~TWS_RCVING;
920   /* simply ignore single isolated interrupts. */
921   if (sc->sc_no_rcv > 1) {
922       sc->sc_flags |= TW_RCV_ERROR;
923       pkt[0] = sc->sc_flags;
924       pkt[1] = pkt[2] = 0;
925       twputpkt(sc, pkt);
926       log(LOG_ERR, "TWRCV: aborting (%x, %d)\n", sc->sc_bits, sc->sc_rcount);
927       twdebugtimes(sc);
928   }
929   wakeup((caddr_t)sc);
930   crit_exit();
931 }
932
933 static int
934 tw_is_within(int value, int expected, int tolerance)
935 {
936   int diff;
937   diff = value - expected;
938   if (diff < 0)
939     diff *= -1;
940   if (diff < tolerance)
941     return 1;
942   return 0;
943 }
944
945 /*
946  * This routine handles interrupts that occur when there is a falling
947  * transition on the RX input.  There isn't going to be a transition
948  * on every bit (some are zero), but if we are smart and keep track of
949  * how long it's been since the last interrupt (via the zero crossing
950  * detect line and/or high-resolution time-of-day routine), we can
951  * reconstruct the transmission without having to poll.
952  */
953
954 static void
955 twintr(void *arg)
956 {
957   int unit = (int)arg;
958   struct tw_sc *sc = &tw_sc[unit];
959   int port;
960   int newphase;
961   u_char pkt[3];
962   int delay = 0;
963   struct timeval tv;
964
965   port = sc->sc_port;
966   /*
967    * Ignore any interrupts that occur if the device is not open.
968    */
969   if(sc->sc_state == 0) return;
970   newphase = inb(port + tw_zcport) & tw_zcmask;
971   microtime(&tv);
972
973   /*
974    * NEW PACKET:
975    * If we aren't currently receiving a packet, set up a new packet
976    * and put in the first "1" bit that has just arrived.
977    * Arrange for the reception to be aborted if too much time goes by.
978    */
979   if((sc->sc_state & TWS_RCVING) == 0) {
980 #ifdef HIRESTIME
981     twsetuptimes(sc->sc_rtimes);
982 #endif /* HIRESTIME */
983     sc->sc_state |= TWS_RCVING;
984     sc->sc_rcount = 1;
985     if(sc->sc_state & TWS_XMITTING) sc->sc_flags = TW_RCV_LOCAL;
986     else sc->sc_flags = 0;
987     sc->sc_bits = 0;
988     sc->sc_rphase = newphase;
989     /* 3 cycles of silence = 3/60 = 1/20 = 50 msec */
990     callout_reset(&sc->abortrcv_ch, hz / 20, twabortrcv, sc);
991     sc->sc_rcv_time[0] = tv.tv_usec;
992     sc->sc_no_rcv = 1;
993     return;
994   }
995   callout_reset(&sc->abortrcv_ch, hz / 20, twabortrcv, sc);
996   newphase = inb(port + tw_zcport) & tw_zcmask;
997
998   /* enforce a minimum delay since the last interrupt */
999   delay = tv.tv_usec - sc->sc_rcv_time[sc->sc_no_rcv - 1];
1000   if (delay < 0)
1001     delay += 1000000;
1002   if (delay < TW_MIN_DELAY)
1003     return;
1004
1005   sc->sc_rcv_time[sc->sc_no_rcv] = tv.tv_usec;
1006   if (sc->sc_rcv_time[sc->sc_no_rcv] < sc->sc_rcv_time[0])
1007     sc->sc_rcv_time[sc->sc_no_rcv] += 1000000;
1008   sc->sc_no_rcv++;
1009
1010   /*
1011    * START CODE:
1012    * The second and third bits are a special case.
1013    */
1014   if (sc->sc_rcount < 3) {
1015     if (
1016 #ifdef HIRESTIME
1017         tw_is_within(delay, HALFCYCLE, HALFCYCLE / 6)
1018 #else
1019         newphase != sc->sc_rphase
1020 #endif
1021         ) {
1022       sc->sc_rcount++;
1023     } else {
1024       /*
1025        * Invalid start code -- abort reception.
1026        */
1027       sc->sc_state &= ~TWS_RCVING;
1028       sc->sc_flags |= TW_RCV_ERROR;
1029       callout_stop(&sc->abortrcv_ch);
1030       log(LOG_ERR, "TWRCV: Invalid start code\n");
1031       twdebugtimes(sc);
1032       sc->sc_no_rcv = 0;
1033       return;
1034     }
1035     if(sc->sc_rcount == 3) {
1036       /*
1037        * We've gotten three "1" bits in a row.  The start code
1038        * is really 1110, but this might be followed by a zero
1039        * bit from the house code, so if we wait any longer we
1040        * might be confused about the first house code bit.
1041        * So, we guess that the start code is correct and insert
1042        * the trailing zero without actually having seen it.
1043        * We don't change sc_rphase in this case, because two
1044        * bit arrivals in a row preserve parity.
1045        */
1046       sc->sc_rcount++;
1047       return;
1048     }
1049     /*
1050      * Update sc_rphase to the current phase before returning.
1051      */
1052     sc->sc_rphase = newphase;
1053     return;
1054   }
1055   /*
1056    * GENERAL CASE:
1057    * Now figure out what the current bit is that just arrived.
1058    * The X-10 protocol transmits each data bit twice: once in
1059    * true form and once in complemented form on the next half
1060    * cycle.  So, there will be at least one interrupt per bit.
1061    * By comparing the phase we see at the time of the interrupt
1062    * with the saved sc_rphase, we can tell on which half cycle
1063    * the interrupt occrred.  This assumes, of course, that the
1064    * packet is well-formed.  We do the best we can at trying to
1065    * catch errors by aborting if too much time has gone by, and
1066    * by tossing out a packet if too many bits arrive, but the
1067    * whole scheme is probably not as robust as if we had a nice
1068    * interrupt on every half cycle of the power line.
1069    * If we have high-resolution time-of-day routines, then we
1070    * can do a bit more sanity checking.
1071    */
1072
1073   /*
1074    * A complete packet is 22 half cycles.
1075    */
1076   if(sc->sc_rcount <= 20) {
1077 #ifdef HIRESTIME
1078     int bit = 0, last_bit;
1079     if (sc->sc_rcount == 4)
1080       last_bit = 1;             /* Start (1110) ends in 10, a 'one' code. */
1081     else
1082       last_bit = sc->sc_bits & 0x1;
1083     if (   (   (last_bit == 1)
1084             && (tw_is_within(delay, HALFCYCLE * 2, HALFCYCLE / 6)))
1085         || (   (last_bit == 0)
1086             && (tw_is_within(delay, HALFCYCLE * 1, HALFCYCLE / 6))))
1087       bit = 1;
1088     else if (   (   (last_bit == 1)
1089                  && (tw_is_within(delay, HALFCYCLE * 3, HALFCYCLE / 6)))
1090              || (   (last_bit == 0)
1091                  && (tw_is_within(delay, HALFCYCLE * 2, HALFCYCLE / 6))))
1092       bit = 0;
1093     else {
1094       sc->sc_flags |= TW_RCV_ERROR;
1095       log(LOG_ERR, "TWRCV: %d cycle after %d bit, delay %d%%\n",
1096           sc->sc_rcount, last_bit, 100 * delay / HALFCYCLE);
1097     }
1098     sc->sc_bits = (sc->sc_bits << 1) | bit;
1099 #else
1100     sc->sc_bits = (sc->sc_bits << 1)
1101       | ((newphase == sc->sc_rphase) ? 0x0 : 0x1);
1102 #endif /* HIRESTIME */
1103     sc->sc_rcount += 2;
1104   }
1105   if(sc->sc_rcount >= 22 || sc->sc_flags & TW_RCV_ERROR) {
1106     if(sc->sc_rcount != 22) {
1107       sc->sc_flags |= TW_RCV_ERROR;
1108       pkt[0] = sc->sc_flags;
1109       pkt[1] = pkt[2] = 0;
1110     } else {
1111       pkt[0] = sc->sc_flags;
1112       pkt[1] = X10_HOUSE_INV[(sc->sc_bits & 0x1e0) >> 5];
1113       pkt[2] = X10_KEY_INV[sc->sc_bits & 0x1f];
1114     }
1115     sc->sc_state &= ~TWS_RCVING;
1116     twputpkt(sc, pkt);
1117     callout_stop(&sc->abortrcv_ch);
1118     if(sc->sc_flags & TW_RCV_ERROR) {
1119       log(LOG_ERR, "TWRCV: invalid packet: (%d, %x) %c %s\n",
1120           sc->sc_rcount, sc->sc_bits, 'A' + pkt[1], X10_KEY_LABEL[pkt[2]]);
1121       twdebugtimes(sc);
1122     } else {
1123 /*      log(LOG_ERR, "TWRCV: valid packet: (%d, %x) %c %s\n",
1124           sc->sc_rcount, sc->sc_bits, 'A' + pkt[1], X10_KEY_LABEL[pkt[2]]); */
1125     }
1126     sc->sc_rcount = 0;
1127     wakeup((caddr_t)sc);
1128   }
1129 }
1130
1131 static void
1132 twdebugtimes(struct tw_sc *sc)
1133 {
1134     int i;
1135     for (i = 0; (i < sc->sc_no_rcv) && (i < SC_RCV_TIME_LEN); i++)
1136         log(LOG_ERR, "TWRCV: interrupt %2d: %d\t%d%%\n", i, sc->sc_rcv_time[i],
1137             (sc->sc_rcv_time[i] - sc->sc_rcv_time[(i?i-1:0)])*100/HALFCYCLE);
1138 }
1139
1140 #ifdef HIRESTIME
1141 /*
1142  * Initialize an array of 22 times, starting from the current
1143  * microtime and continuing for the next 21 half cycles.
1144  * We use the times as a reference to make sure transmission
1145  * or reception is on schedule.
1146  */
1147
1148 static void
1149 twsetuptimes(int *a)
1150 {
1151   struct timeval tv;
1152   int i, t;
1153
1154   microtime(&tv);
1155   t = tv.tv_usec;
1156   for(i = 0; i < 22; i++) {
1157     *a++ = t;
1158     t += HALFCYCLE;
1159     if(t >= 1000000) t -= 1000000;
1160   }
1161 }
1162
1163 /*
1164  * Check the current time against a slot in a previously set up
1165  * timing array, and make sure that it looks like we are still
1166  * on schedule.
1167  */
1168
1169 static int
1170 twchecktime(int target, int tol)
1171 {
1172   struct timeval tv;
1173   int t, d;
1174
1175   microtime(&tv);
1176   t = tv.tv_usec;
1177   d = (target - t) >= 0 ? (target - t) : (t - target);
1178   if(d > 500000) d = 1000000-d;
1179   if(d <= tol && d >= -tol) {
1180     return(1);
1181   } else {
1182     return(0);
1183   }
1184 }
1185 #endif /* HIRESTIME */