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