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