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