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