ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / sbus / char / envctrl.c
1 /* $Id: envctrl.c,v 1.25 2002/01/15 09:01:26 davem Exp $
2  * envctrl.c: Temperature and Fan monitoring on Machines providing it.
3  *
4  * Copyright (C) 1998  Eddie C. Dost  (ecd@skynet.be)
5  * Copyright (C) 2000  Vinh Truong    (vinh.truong@eng.sun.com)
6  * VT - The implementation is to support Sun Microelectronics (SME) platform
7  *      environment monitoring.  SME platforms use pcf8584 as the i2c bus 
8  *      controller to access pcf8591 (8-bit A/D and D/A converter) and 
9  *      pcf8571 (256 x 8-bit static low-voltage RAM with I2C-bus interface).
10  *      At board level, it follows SME Firmware I2C Specification. Reference:
11  *      http://www-eu2.semiconductors.com/pip/PCF8584P
12  *      http://www-eu2.semiconductors.com/pip/PCF8574AP
13  *      http://www-eu2.semiconductors.com/pip/PCF8591P
14  *
15  * EB - Added support for CP1500 Global Address and PS/Voltage monitoring.
16  *              Eric Brower <ebrower@usa.net>
17  *
18  * DB - Audit every copy_to_user in envctrl_read.
19  *              Daniele Bellucci <bellucda@tiscali.it>
20  */
21
22 #include <linux/config.h>
23 #include <linux/module.h>
24 #include <linux/sched.h>
25 #include <linux/errno.h>
26 #include <linux/delay.h>
27 #include <linux/ioport.h>
28 #include <linux/init.h>
29 #include <linux/miscdevice.h>
30 #include <linux/mm.h>
31 #include <linux/slab.h>
32 #include <linux/kernel.h>
33
34 #include <asm/ebus.h>
35 #include <asm/uaccess.h>
36 #include <asm/envctrl.h>
37
38 #define __KERNEL_SYSCALLS__
39 static int errno;
40 #include <asm/unistd.h>
41
42 #define ENVCTRL_MINOR   162
43
44 #define PCF8584_ADDRESS 0x55
45
46 #define CONTROL_PIN     0x80
47 #define CONTROL_ES0     0x40
48 #define CONTROL_ES1     0x20
49 #define CONTROL_ES2     0x10
50 #define CONTROL_ENI     0x08
51 #define CONTROL_STA     0x04
52 #define CONTROL_STO     0x02
53 #define CONTROL_ACK     0x01
54
55 #define STATUS_PIN      0x80
56 #define STATUS_STS      0x20
57 #define STATUS_BER      0x10
58 #define STATUS_LRB      0x08
59 #define STATUS_AD0      0x08
60 #define STATUS_AAB      0x04
61 #define STATUS_LAB      0x02
62 #define STATUS_BB       0x01
63
64 /*
65  * CLK Mode Register.
66  */
67 #define BUS_CLK_90      0x00
68 #define BUS_CLK_45      0x01
69 #define BUS_CLK_11      0x02
70 #define BUS_CLK_1_5     0x03
71
72 #define CLK_3           0x00
73 #define CLK_4_43        0x10
74 #define CLK_6           0x14
75 #define CLK_8           0x18
76 #define CLK_12          0x1c
77
78 #define OBD_SEND_START  0xc5    /* value to generate I2c_bus START condition */
79 #define OBD_SEND_STOP   0xc3    /* value to generate I2c_bus STOP condition */
80
81 /* Monitor type of i2c child device.
82  * Firmware definitions.
83  */
84 #define PCF8584_MAX_CHANNELS            8
85 #define PCF8584_GLOBALADDR_TYPE                 6  /* global address monitor */
86 #define PCF8584_FANSTAT_TYPE            3  /* fan status monitor */
87 #define PCF8584_VOLTAGE_TYPE            2  /* voltage monitor    */
88 #define PCF8584_TEMP_TYPE                       1  /* temperature monitor*/
89
90 /* Monitor type of i2c child device.
91  * Driver definitions.
92  */
93 #define ENVCTRL_NOMON                           0
94 #define ENVCTRL_CPUTEMP_MON                     1    /* cpu temperature monitor */
95 #define ENVCTRL_CPUVOLTAGE_MON          2    /* voltage monitor         */
96 #define ENVCTRL_FANSTAT_MON             3    /* fan status monitor      */
97 #define ENVCTRL_ETHERTEMP_MON           4    /* ethernet temperarture */
98                                              /* monitor                     */
99 #define ENVCTRL_VOLTAGESTAT_MON         5    /* voltage status monitor  */
100 #define ENVCTRL_MTHRBDTEMP_MON          6    /* motherboard temperature */
101 #define ENVCTRL_SCSITEMP_MON            7    /* scsi temperarture */
102 #define ENVCTRL_GLOBALADDR_MON          8    /* global address */
103
104 /* Child device type.
105  * Driver definitions.
106  */
107 #define I2C_ADC                         0    /* pcf8591 */
108 #define I2C_GPIO                        1    /* pcf8571 */
109
110 /* Data read from child device may need to decode
111  * through a data table and a scale.
112  * Translation type as defined by firmware.
113  */
114 #define ENVCTRL_TRANSLATE_NO            0
115 #define ENVCTRL_TRANSLATE_PARTIAL       1
116 #define ENVCTRL_TRANSLATE_COMBINED      2
117 #define ENVCTRL_TRANSLATE_FULL          3     /* table[data] */
118 #define ENVCTRL_TRANSLATE_SCALE         4     /* table[data]/scale */
119
120 /* Driver miscellaneous definitions. */
121 #define ENVCTRL_MAX_CPU                 4
122 #define CHANNEL_DESC_SZ                 256
123
124 /* Mask values for combined GlobalAddress/PowerStatus node */
125 #define ENVCTRL_GLOBALADDR_ADDR_MASK    0x1F
126 #define ENVCTRL_GLOBALADDR_PSTAT_MASK   0x60
127
128 /* Node 0x70 ignored on CompactPCI CP1400/1500 platforms 
129  * (see envctrl_init_i2c_child)
130  */
131 #define ENVCTRL_CPCI_IGNORED_NODE               0x70
132
133 struct pcf8584_reg {
134          unsigned char data;
135          unsigned char csr;
136 };
137
138 /* Each child device can be monitored by up to PCF8584_MAX_CHANNELS.
139  * Property of a port or channel as defined by the firmware.
140  */
141 struct pcf8584_channel {
142         unsigned char chnl_no;
143         unsigned char io_direction;
144         unsigned char type;
145         unsigned char last;
146 };
147
148 /* Each child device may have one or more tables of bytes to help decode
149  * data. Table property as defined by the firmware.
150  */ 
151 struct pcf8584_tblprop {
152         unsigned int type;
153         unsigned int scale;  
154         unsigned int offset; /* offset from the beginning of the table */
155         unsigned int size;
156 };
157
158 /* i2c child */
159 struct i2c_child_t {
160         /* Either ADC or GPIO. */
161         unsigned char i2ctype;
162         unsigned long addr;    
163         struct pcf8584_channel chnl_array[PCF8584_MAX_CHANNELS];
164
165         /* Channel info. */ 
166         unsigned int total_chnls;       /* Number of monitor channels. */
167         unsigned char fan_mask;         /* Byte mask for fan status channels. */
168         unsigned char voltage_mask;     /* Byte mask for voltage status channels. */
169         struct pcf8584_tblprop tblprop_array[PCF8584_MAX_CHANNELS];
170
171         /* Properties of all monitor channels. */
172         unsigned int total_tbls;        /* Number of monitor tables. */
173         char *tables;                   /* Pointer to table(s). */
174         char chnls_desc[CHANNEL_DESC_SZ]; /* Channel description. */
175         char mon_type[PCF8584_MAX_CHANNELS];
176 };
177
178 volatile static struct pcf8584_reg *i2c = NULL;
179 static struct i2c_child_t i2c_childlist[ENVCTRL_MAX_CPU*2];
180 static unsigned char chnls_mask[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
181 static unsigned int warning_temperature = 0;
182 static unsigned int shutdown_temperature = 0;
183 static char read_cpu;
184
185 /* Forward declarations. */
186 static struct i2c_child_t *envctrl_get_i2c_child(unsigned char);
187
188 /* Function description: Read a byte from an i2c controller register.
189  * Return: A byte from the passed in address.
190  */
191 static inline unsigned char envctrl_readb(volatile unsigned char *p)
192 {
193         return readb(p);
194 }
195
196 /* Function description: Write a byte to an i2c controller register.
197  * Return: Nothing.
198  */
199 static inline void envctrl_writeb(unsigned char val, volatile unsigned char *p)
200 {
201         writeb(val, p);
202 }
203
204 /* Function Description: Test the PIN bit (Pending Interrupt Not) 
205  *                       to test when serial transmission is completed .
206  * Return : None.
207  */
208 static void envtrl_i2c_test_pin(void)
209 {
210         int limit = 1000000;
211
212         while (--limit > 0) {
213                 if (!(envctrl_readb(&i2c->csr) & STATUS_PIN)) 
214                         break;
215                 udelay(1);
216         } 
217
218         if (limit <= 0)
219                 printk(KERN_INFO "envctrl: Pin status will not clear.\n");
220 }
221
222 /* Function Description: Test busy bit.
223  * Return : None.
224  */
225 static void envctrl_i2c_test_bb(void)
226 {
227         int limit = 1000000;
228
229         while (--limit > 0) {
230                 /* Busy bit 0 means busy. */
231                 if (envctrl_readb(&i2c->csr) & STATUS_BB)
232                         break;
233                 udelay(1);
234         } 
235
236         if (limit <= 0)
237                 printk(KERN_INFO "envctrl: Busy bit will not clear.\n");
238 }
239
240 /* Function Description: Send the address for a read access.
241  * Return : 0 if not acknowledged, otherwise acknowledged.
242  */
243 static int envctrl_i2c_read_addr(unsigned char addr)
244 {
245         envctrl_i2c_test_bb();
246
247         /* Load address. */
248         envctrl_writeb(addr + 1, &i2c->data);
249
250         envctrl_i2c_test_bb();
251
252         envctrl_writeb(OBD_SEND_START, &i2c->csr);
253
254         /* Wait for PIN. */
255         envtrl_i2c_test_pin();
256
257         /* CSR 0 means acknowledged. */
258         if (!(envctrl_readb(&i2c->csr) & STATUS_LRB)) {
259                 return envctrl_readb(&i2c->data);
260         } else {
261                 envctrl_writeb(OBD_SEND_STOP, &i2c->csr);
262                 return 0;
263         }
264 }
265
266 /* Function Description: Send the address for write mode.  
267  * Return : None.
268  */
269 static void envctrl_i2c_write_addr(unsigned char addr)
270 {
271         envctrl_i2c_test_bb();
272         envctrl_writeb(addr, &i2c->data);
273
274         /* Generate Start condition. */
275         envctrl_writeb(OBD_SEND_START, &i2c->csr);
276 }
277
278 /* Function Description: Read 1 byte of data from addr 
279  *                       set by envctrl_i2c_read_addr() 
280  * Return : Data from address set by envctrl_i2c_read_addr().
281  */
282 static unsigned char envctrl_i2c_read_data(void)
283 {
284         envtrl_i2c_test_pin();
285         envctrl_writeb(CONTROL_ES0, &i2c->csr);  /* Send neg ack. */
286         return envctrl_readb(&i2c->data);
287 }
288
289 /* Function Description: Instruct the device which port to read data from.  
290  * Return : None.
291  */
292 static void envctrl_i2c_write_data(unsigned char port)
293 {
294         envtrl_i2c_test_pin();
295         envctrl_writeb(port, &i2c->data);
296 }
297
298 /* Function Description: Generate Stop condition after last byte is sent.
299  * Return : None.
300  */
301 static void envctrl_i2c_stop(void)
302 {
303         envtrl_i2c_test_pin();
304         envctrl_writeb(OBD_SEND_STOP, &i2c->csr);
305 }
306
307 /* Function Description: Read adc device.
308  * Return : Data at address and port.
309  */
310 static unsigned char envctrl_i2c_read_8591(unsigned char addr, unsigned char port)
311 {
312         /* Send address. */
313         envctrl_i2c_write_addr(addr);
314
315         /* Setup port to read. */
316         envctrl_i2c_write_data(port);
317         envctrl_i2c_stop();
318
319         /* Read port. */
320         envctrl_i2c_read_addr(addr);
321
322         /* Do a single byte read and send stop. */
323         envctrl_i2c_read_data();
324         envctrl_i2c_stop();
325
326         return envctrl_readb(&i2c->data);
327 }
328
329 /* Function Description: Read gpio device.
330  * Return : Data at address.
331  */
332 static unsigned char envctrl_i2c_read_8574(unsigned char addr)
333 {
334         unsigned char rd;
335
336         envctrl_i2c_read_addr(addr);
337
338         /* Do a single byte read and send stop. */
339         rd = envctrl_i2c_read_data();
340         envctrl_i2c_stop();
341         return rd;
342 }
343
344 /* Function Description: Decode data read from an adc device using firmware
345  *                       table.
346  * Return: Number of read bytes. Data is stored in bufdata in ascii format.
347  */
348 static int envctrl_i2c_data_translate(unsigned char data, int translate_type,
349                                       int scale, char *tbl, char *bufdata)
350 {
351         int len = 0;
352
353         switch (translate_type) {
354         case ENVCTRL_TRANSLATE_NO:
355                 /* No decode necessary. */
356                 len = 1;
357                 bufdata[0] = data;
358                 break;
359
360         case ENVCTRL_TRANSLATE_FULL:
361                 /* Decode this way: data = table[data]. */
362                 len = 1;
363                 bufdata[0] = tbl[data];
364                 break;
365
366         case ENVCTRL_TRANSLATE_SCALE:
367                 /* Decode this way: data = table[data]/scale */
368                 sprintf(bufdata,"%d ", (tbl[data] * 10) / (scale));
369                 len = strlen(bufdata);
370                 bufdata[len - 1] = bufdata[len - 2];
371                 bufdata[len - 2] = '.';
372                 break;
373
374         default:
375                 break;
376         };
377
378         return len;
379 }
380
381 /* Function Description: Read cpu-related data such as cpu temperature, voltage.
382  * Return: Number of read bytes. Data is stored in bufdata in ascii format.
383  */
384 static int envctrl_read_cpu_info(int cpu, struct i2c_child_t *pchild,
385                                  char mon_type, unsigned char *bufdata)
386 {
387         unsigned char data;
388         int i;
389         char *tbl, j = -1;
390
391         /* Find the right monitor type and channel. */
392         for (i = 0; i < PCF8584_MAX_CHANNELS; i++) {
393                 if (pchild->mon_type[i] == mon_type) {
394                         if (++j == cpu) {
395                                 break;
396                         }
397                 }
398         }
399
400         if (j != cpu)
401                 return 0;
402
403         /* Read data from address and port. */
404         data = envctrl_i2c_read_8591((unsigned char)pchild->addr,
405                                      (unsigned char)pchild->chnl_array[i].chnl_no);
406
407         /* Find decoding table. */
408         tbl = pchild->tables + pchild->tblprop_array[i].offset;
409
410         return envctrl_i2c_data_translate(data, pchild->tblprop_array[i].type,
411                                           pchild->tblprop_array[i].scale,
412                                           tbl, bufdata);
413 }
414
415 /* Function Description: Read noncpu-related data such as motherboard 
416  *                       temperature.
417  * Return: Number of read bytes. Data is stored in bufdata in ascii format.
418  */
419 static int envctrl_read_noncpu_info(struct i2c_child_t *pchild,
420                                     char mon_type, unsigned char *bufdata)
421 {
422         unsigned char data;
423         int i;
424         char *tbl = NULL;
425
426         for (i = 0; i < PCF8584_MAX_CHANNELS; i++) {
427                 if (pchild->mon_type[i] == mon_type)
428                         break;
429         }
430
431         if (i >= PCF8584_MAX_CHANNELS)
432                 return 0;
433
434         /* Read data from address and port. */
435         data = envctrl_i2c_read_8591((unsigned char)pchild->addr,
436                                      (unsigned char)pchild->chnl_array[i].chnl_no);
437
438         /* Find decoding table. */
439         tbl = pchild->tables + pchild->tblprop_array[i].offset;
440
441         return envctrl_i2c_data_translate(data, pchild->tblprop_array[i].type,
442                                           pchild->tblprop_array[i].scale,
443                                           tbl, bufdata);
444 }
445
446 /* Function Description: Read fan status.
447  * Return : Always 1 byte. Status stored in bufdata.
448  */
449 static int envctrl_i2c_fan_status(struct i2c_child_t *pchild,
450                                   unsigned char data,
451                                   char *bufdata)
452 {
453         unsigned char tmp, ret = 0;
454         int i, j = 0;
455
456         tmp = data & pchild->fan_mask;
457
458         if (tmp == pchild->fan_mask) {
459                 /* All bits are on. All fans are functioning. */
460                 ret = ENVCTRL_ALL_FANS_GOOD;
461         } else if (tmp == 0) {
462                 /* No bits are on. No fans are functioning. */
463                 ret = ENVCTRL_ALL_FANS_BAD;
464         } else {
465                 /* Go through all channels, mark 'on' the matched bits.
466                  * Notice that fan_mask may have discontiguous bits but
467                  * return mask are always contiguous. For example if we
468                  * monitor 4 fans at channels 0,1,2,4, the return mask
469                  * should be 00010000 if only fan at channel 4 is working.
470                  */
471                 for (i = 0; i < PCF8584_MAX_CHANNELS;i++) {
472                         if (pchild->fan_mask & chnls_mask[i]) {
473                                 if (!(chnls_mask[i] & tmp))
474                                         ret |= chnls_mask[j];
475
476                                 j++;
477                         }
478                 }
479         }
480
481         bufdata[0] = ret;
482         return 1;
483 }
484
485 /* Function Description: Read global addressing line.
486  * Return : Always 1 byte. Status stored in bufdata.
487  */
488 static int envctrl_i2c_globaladdr(struct i2c_child_t *pchild,
489                                   unsigned char data,
490                                   char *bufdata)
491 {
492         /* Translatation table is not necessary, as global
493          * addr is the integer value of the GA# bits.
494          *
495          * NOTE: MSB is documented as zero, but I see it as '1' always....
496          *
497          * -----------------------------------------------
498          * | 0 | FAL | DEG | GA4 | GA3 | GA2 | GA1 | GA0 |
499          * -----------------------------------------------
500          * GA0 - GA4    integer value of Global Address (backplane slot#)
501          * DEG                  0 = cPCI Power supply output is starting to degrade
502          *                              1 = cPCI Power supply output is OK
503          * FAL                  0 = cPCI Power supply has failed
504          *                              1 = cPCI Power supply output is OK
505          */
506         bufdata[0] = (data & ENVCTRL_GLOBALADDR_ADDR_MASK);
507         return 1;
508 }
509
510 /* Function Description: Read standard voltage and power supply status.
511  * Return : Always 1 byte. Status stored in bufdata.
512  */
513 static unsigned char envctrl_i2c_voltage_status(struct i2c_child_t *pchild,
514                                                 unsigned char data,
515                                                 char *bufdata)
516 {
517         unsigned char tmp, ret = 0;
518         int i, j = 0;
519
520         tmp = data & pchild->voltage_mask;
521
522         /* Two channels are used to monitor voltage and power supply. */
523         if (tmp == pchild->voltage_mask) {
524                 /* All bits are on. Voltage and power supply are okay. */
525                 ret = ENVCTRL_VOLTAGE_POWERSUPPLY_GOOD;
526         } else if (tmp == 0) {
527                 /* All bits are off. Voltage and power supply are bad */
528                 ret = ENVCTRL_VOLTAGE_POWERSUPPLY_BAD;
529         } else {
530                 /* Either voltage or power supply has problem. */
531                 for (i = 0; i < PCF8584_MAX_CHANNELS; i++) {
532                         if (pchild->voltage_mask & chnls_mask[i]) {
533                                 j++;
534
535                                 /* Break out when there is a mismatch. */
536                                 if (!(chnls_mask[i] & tmp))
537                                         break; 
538                         }
539                 }
540
541                 /* Make a wish that hardware will always use the
542                  * first channel for voltage and the second for
543                  * power supply.
544                  */
545                 if (j == 1)
546                         ret = ENVCTRL_VOLTAGE_BAD;
547                 else
548                         ret = ENVCTRL_POWERSUPPLY_BAD;
549         }
550
551         bufdata[0] = ret;
552         return 1;
553 }
554
555 /* Function Description: Read a byte from /dev/envctrl. Mapped to user read().
556  * Return: Number of read bytes. 0 for error.
557  */
558 static ssize_t
559 envctrl_read(struct file *file, char *buf, size_t count, loff_t *ppos)
560 {
561         struct i2c_child_t *pchild;
562         unsigned char data[10];
563         int ret = 0;
564
565         /* Get the type of read as decided in ioctl() call.
566          * Find the appropriate i2c child.
567          * Get the data and put back to the user buffer.
568          */
569
570         switch ((int)(long)file->private_data) {
571         case ENVCTRL_RD_WARNING_TEMPERATURE:
572                 if (warning_temperature == 0)
573                         return 0;
574
575                 data[0] = (unsigned char)(warning_temperature);
576                 ret = 1;
577                 if (copy_to_user((unsigned char *)buf, data, ret))
578                         ret = -EFAULT;
579                 break;
580
581         case ENVCTRL_RD_SHUTDOWN_TEMPERATURE:
582                 if (shutdown_temperature == 0)
583                         return 0;
584
585                 data[0] = (unsigned char)(shutdown_temperature);
586                 ret = 1;
587                 if (copy_to_user((unsigned char *)buf, data, ret))
588                         ret = -EFAULT;
589                 break;
590
591         case ENVCTRL_RD_MTHRBD_TEMPERATURE:
592                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_MTHRBDTEMP_MON)))
593                         return 0;
594                 ret = envctrl_read_noncpu_info(pchild, ENVCTRL_MTHRBDTEMP_MON, data);
595                 if (copy_to_user((unsigned char *)buf, data, ret))
596                         ret = -EFAULT;
597                 break;
598
599         case ENVCTRL_RD_CPU_TEMPERATURE:
600                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_CPUTEMP_MON)))
601                         return 0;
602                 ret = envctrl_read_cpu_info(read_cpu, pchild, ENVCTRL_CPUTEMP_MON, data);
603
604                 /* Reset cpu to the default cpu0. */
605                 if (copy_to_user((unsigned char *)buf, data, ret))
606                         ret = -EFAULT;
607                 break;
608
609         case ENVCTRL_RD_CPU_VOLTAGE:
610                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_CPUVOLTAGE_MON)))
611                         return 0;
612                 ret = envctrl_read_cpu_info(read_cpu, pchild, ENVCTRL_CPUVOLTAGE_MON, data);
613
614                 /* Reset cpu to the default cpu0. */
615                 if (copy_to_user((unsigned char *)buf, data, ret))
616                         ret = -EFAULT;
617                 break;
618
619         case ENVCTRL_RD_SCSI_TEMPERATURE:
620                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_SCSITEMP_MON)))
621                         return 0;
622                 ret = envctrl_read_noncpu_info(pchild, ENVCTRL_SCSITEMP_MON, data);
623                 if (copy_to_user((unsigned char *)buf, data, ret))
624                         ret = -EFAULT;
625                 break;
626
627         case ENVCTRL_RD_ETHERNET_TEMPERATURE:
628                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_ETHERTEMP_MON)))
629                         return 0;
630                 ret = envctrl_read_noncpu_info(pchild, ENVCTRL_ETHERTEMP_MON, data);
631                 if (copy_to_user((unsigned char *)buf, data, ret))
632                         ret = -EFAULT;
633                 break;
634
635         case ENVCTRL_RD_FAN_STATUS:
636                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_FANSTAT_MON)))
637                         return 0;
638                 data[0] = envctrl_i2c_read_8574(pchild->addr);
639                 ret = envctrl_i2c_fan_status(pchild,data[0], data);
640                 if (copy_to_user((unsigned char *)buf, data, ret))
641                         ret = -EFAULT;
642                 break;
643         
644         case ENVCTRL_RD_GLOBALADDRESS:
645                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_GLOBALADDR_MON)))
646                         return 0;
647                 data[0] = envctrl_i2c_read_8574(pchild->addr);
648                 ret = envctrl_i2c_globaladdr(pchild, data[0], data);
649                 if (copy_to_user((unsigned char *)buf, data, ret))
650                         ret = -EFAULT;
651                 break;
652
653         case ENVCTRL_RD_VOLTAGE_STATUS:
654                 if (!(pchild = envctrl_get_i2c_child(ENVCTRL_VOLTAGESTAT_MON)))
655                         /* If voltage monitor not present, check for CPCI equivalent */
656                         if (!(pchild = envctrl_get_i2c_child(ENVCTRL_GLOBALADDR_MON)))
657                                 return 0;
658                 data[0] = envctrl_i2c_read_8574(pchild->addr);
659                 ret = envctrl_i2c_voltage_status(pchild, data[0], data);
660                 if (copy_to_user((unsigned char *)buf, data, ret))
661                         ret = -EFAULT;
662                 break;
663
664         default:
665                 break;
666
667         };
668
669         return ret;
670 }
671
672 /* Function Description: Command what to read.  Mapped to user ioctl().
673  * Return: Gives 0 for implemented commands, -EINVAL otherwise.
674  */
675 static int
676 envctrl_ioctl(struct inode *inode, struct file *file,
677               unsigned int cmd, unsigned long arg)
678 {
679         char *infobuf;
680
681         switch (cmd) {
682         case ENVCTRL_RD_WARNING_TEMPERATURE:
683         case ENVCTRL_RD_SHUTDOWN_TEMPERATURE:
684         case ENVCTRL_RD_MTHRBD_TEMPERATURE:
685         case ENVCTRL_RD_FAN_STATUS:
686         case ENVCTRL_RD_VOLTAGE_STATUS:
687         case ENVCTRL_RD_ETHERNET_TEMPERATURE:
688         case ENVCTRL_RD_SCSI_TEMPERATURE:
689         case ENVCTRL_RD_GLOBALADDRESS:
690                 file->private_data = (void *)(long)cmd;
691                 break;
692
693         case ENVCTRL_RD_CPU_TEMPERATURE:
694         case ENVCTRL_RD_CPU_VOLTAGE:
695                 /* Check to see if application passes in any cpu number,
696                  * the default is cpu0.
697                  */
698                 infobuf = (char *) arg;
699                 if (infobuf == NULL) {
700                         read_cpu = 0;
701                 }else {
702                         get_user(read_cpu, infobuf);
703                 }
704
705                 /* Save the command for use when reading. */
706                 file->private_data = (void *)(long)cmd;
707                 break;
708
709         default:
710                 return -EINVAL;
711         };
712
713         return 0;
714 }
715
716 /* Function Description: open device. Mapped to user open().
717  * Return: Always 0.
718  */
719 static int
720 envctrl_open(struct inode *inode, struct file *file)
721 {
722         file->private_data = 0;
723         return 0;
724 }
725
726 /* Function Description: Open device. Mapped to user close().
727  * Return: Always 0.
728  */
729 static int
730 envctrl_release(struct inode *inode, struct file *file)
731 {
732         return 0;
733 }
734
735 static struct file_operations envctrl_fops = {
736         .owner =        THIS_MODULE,
737         .read =         envctrl_read,
738         .ioctl =        envctrl_ioctl,
739         .open =         envctrl_open,
740         .release =      envctrl_release,
741 };      
742
743 static struct miscdevice envctrl_dev = {
744         ENVCTRL_MINOR,
745         "envctrl",
746         &envctrl_fops
747 };
748
749 /* Function Description: Set monitor type based on firmware description.
750  * Return: None.
751  */
752 static void envctrl_set_mon(struct i2c_child_t *pchild,
753                             char *chnl_desc,
754                             int chnl_no)
755 {
756         /* Firmware only has temperature type.  It does not distinguish
757          * different kinds of temperatures.  We use channel description
758          * to disinguish them.
759          */
760         if (!(strcmp(chnl_desc,"temp,cpu")) ||
761             !(strcmp(chnl_desc,"temp,cpu0")) ||
762             !(strcmp(chnl_desc,"temp,cpu1")) ||
763             !(strcmp(chnl_desc,"temp,cpu2")) ||
764             !(strcmp(chnl_desc,"temp,cpu3")))
765                 pchild->mon_type[chnl_no] = ENVCTRL_CPUTEMP_MON;
766
767         if (!(strcmp(chnl_desc,"vddcore,cpu0")) ||
768             !(strcmp(chnl_desc,"vddcore,cpu1")) ||
769             !(strcmp(chnl_desc,"vddcore,cpu2")) ||
770             !(strcmp(chnl_desc,"vddcore,cpu3")))
771                 pchild->mon_type[chnl_no] = ENVCTRL_CPUVOLTAGE_MON;
772
773         if (!(strcmp(chnl_desc,"temp,motherboard")))
774                 pchild->mon_type[chnl_no] = ENVCTRL_MTHRBDTEMP_MON;
775
776         if (!(strcmp(chnl_desc,"temp,scsi")))
777                 pchild->mon_type[chnl_no] = ENVCTRL_SCSITEMP_MON;
778
779         if (!(strcmp(chnl_desc,"temp,ethernet")))
780                 pchild->mon_type[chnl_no] = ENVCTRL_ETHERTEMP_MON;
781 }
782
783 /* Function Description: Initialize monitor channel with channel desc,
784  *                       decoding tables, monitor type, optional properties.
785  * Return: None.
786  */
787 static void envctrl_init_adc(struct i2c_child_t *pchild, int node)
788 {
789         char chnls_desc[CHANNEL_DESC_SZ];
790         int i = 0, len;
791         char *pos = chnls_desc;
792
793         /* Firmware describe channels into a stream separated by a '\0'. */
794         len = prom_getproperty(node, "channels-description", chnls_desc,
795                                CHANNEL_DESC_SZ);
796         chnls_desc[CHANNEL_DESC_SZ - 1] = '\0';
797
798         while (len > 0) {
799                 int l = strlen(pos) + 1;
800                 envctrl_set_mon(pchild, pos, i++);
801                 len -= l;
802                 pos += l;
803         }
804
805         /* Get optional properties. */
806         len = prom_getproperty(node, "warning-temp", (char *)&warning_temperature,
807                                sizeof(warning_temperature));
808         len = prom_getproperty(node, "shutdown-temp", (char *)&shutdown_temperature,
809                                sizeof(shutdown_temperature));
810 }
811
812 /* Function Description: Initialize child device monitoring fan status.
813  * Return: None.
814  */
815 static void envctrl_init_fanstat(struct i2c_child_t *pchild)
816 {
817         int i;
818
819         /* Go through all channels and set up the mask. */
820         for (i = 0; i < pchild->total_chnls; i++)
821                 pchild->fan_mask |= chnls_mask[(pchild->chnl_array[i]).chnl_no];
822
823         /* We only need to know if this child has fan status monitored.
824          * We don't care which channels since we have the mask already.
825          */
826         pchild->mon_type[0] = ENVCTRL_FANSTAT_MON;
827 }
828
829 /* Function Description: Initialize child device for global addressing line.
830  * Return: None.
831  */
832 static void envctrl_init_globaladdr(struct i2c_child_t *pchild)
833 {
834         int i;
835
836         /* Voltage/PowerSupply monitoring is piggybacked 
837          * with Global Address on CompactPCI.  See comments
838          * within envctrl_i2c_globaladdr for bit assignments.
839          *
840          * The mask is created here by assigning mask bits to each
841          * bit position that represents PCF8584_VOLTAGE_TYPE data.
842          * Channel numbers are not consecutive within the globaladdr
843          * node (why?), so we use the actual counter value as chnls_mask
844          * index instead of the chnl_array[x].chnl_no value.
845          *
846          * NOTE: This loop could be replaced with a constant representing
847          * a mask of bits 5&6 (ENVCTRL_GLOBALADDR_PSTAT_MASK).
848          */
849         for (i = 0; i < pchild->total_chnls; i++) {
850                 if (PCF8584_VOLTAGE_TYPE == pchild->chnl_array[i].type) {
851                         pchild->voltage_mask |= chnls_mask[i];
852                 }
853         }
854
855         /* We only need to know if this child has global addressing 
856          * line monitored.  We don't care which channels since we know 
857          * the mask already (ENVCTRL_GLOBALADDR_ADDR_MASK).
858          */
859         pchild->mon_type[0] = ENVCTRL_GLOBALADDR_MON;
860 }
861
862 /* Initialize child device monitoring voltage status. */
863 static void envctrl_init_voltage_status(struct i2c_child_t *pchild)
864 {
865         int i;
866
867         /* Go through all channels and set up the mask. */
868         for (i = 0; i < pchild->total_chnls; i++)
869                 pchild->voltage_mask |= chnls_mask[(pchild->chnl_array[i]).chnl_no];
870
871         /* We only need to know if this child has voltage status monitored.
872          * We don't care which channels since we have the mask already.
873          */
874         pchild->mon_type[0] = ENVCTRL_VOLTAGESTAT_MON;
875 }
876
877 /* Function Description: Initialize i2c child device.
878  * Return: None.
879  */
880 static void envctrl_init_i2c_child(struct linux_ebus_child *edev_child,
881                                    struct i2c_child_t *pchild)
882 {
883         int node, len, i, tbls_size = 0;
884
885         node = edev_child->prom_node;
886
887         /* Get device address. */
888         len = prom_getproperty(node, "reg",
889                                (char *) &(pchild->addr),
890                                sizeof(pchild->addr));
891
892         /* Get tables property.  Read firmware temperature tables. */
893         len = prom_getproperty(node, "translation",
894                                (char *) pchild->tblprop_array,
895                                (PCF8584_MAX_CHANNELS *
896                                 sizeof(struct pcf8584_tblprop)));
897         if (len > 0) {
898                 pchild->total_tbls = len / sizeof(struct pcf8584_tblprop);
899                 for (i = 0; i < pchild->total_tbls; i++) {
900                         if ((pchild->tblprop_array[i].size + pchild->tblprop_array[i].offset) > tbls_size) {
901                                 tbls_size = pchild->tblprop_array[i].size + pchild->tblprop_array[i].offset;
902                         }
903                 }
904
905                 pchild->tables = kmalloc(tbls_size, GFP_KERNEL);
906                 if (pchild->tables == NULL){
907                         printk("envctrl: Failed to allocate table.\n");
908                         return;
909                 }
910                 len = prom_getproperty(node, "tables",
911                                        (char *) pchild->tables, tbls_size);
912                 if (len <= 0) {
913                         printk("envctrl: Failed to get table.\n");
914                         return;
915                 }
916         }
917
918         /* SPARCengine ASM Reference Manual (ref. SMI doc 805-7581-04)
919          * sections 2.5, 3.5, 4.5 state node 0x70 for CP1400/1500 is
920          * "For Factory Use Only."
921          *
922          * We ignore the node on these platforms by assigning the
923          * 'NULL' monitor type.
924          */
925         if (ENVCTRL_CPCI_IGNORED_NODE == pchild->addr) {
926                 int len;
927                 char prop[56];
928
929                 len = prom_getproperty(prom_root_node, "name", prop, sizeof(prop));
930                 if (0 < len && (0 == strncmp(prop, "SUNW,UltraSPARC-IIi-cEngine", len)))
931                 {
932                         for (len = 0; len < PCF8584_MAX_CHANNELS; ++len) {
933                                 pchild->mon_type[len] = ENVCTRL_NOMON;
934                         }
935                         return;
936                 }
937         }
938
939         /* Get the monitor channels. */
940         len = prom_getproperty(node, "channels-in-use",
941                                (char *) pchild->chnl_array,
942                                (PCF8584_MAX_CHANNELS *
943                                 sizeof(struct pcf8584_channel)));
944         pchild->total_chnls = len / sizeof(struct pcf8584_channel);
945
946         for (i = 0; i < pchild->total_chnls; i++) {
947                 switch (pchild->chnl_array[i].type) {
948                 case PCF8584_TEMP_TYPE:
949                         envctrl_init_adc(pchild, node);
950                         break;
951
952                 case PCF8584_GLOBALADDR_TYPE:
953                         envctrl_init_globaladdr(pchild);
954                         i = pchild->total_chnls;
955                         break;
956
957                 case PCF8584_FANSTAT_TYPE:
958                         envctrl_init_fanstat(pchild);
959                         i = pchild->total_chnls;
960                         break;
961
962                 case PCF8584_VOLTAGE_TYPE:
963                         if (pchild->i2ctype == I2C_ADC) {
964                                 envctrl_init_adc(pchild,node);
965                         } else {
966                                 envctrl_init_voltage_status(pchild);
967                         }
968                         i = pchild->total_chnls;
969                         break;
970
971                 default:
972                         break;
973                 };
974         }
975 }
976
977 /* Function Description: Search the child device list for a device.
978  * Return : The i2c child if found. NULL otherwise.
979  */
980 static struct i2c_child_t *envctrl_get_i2c_child(unsigned char mon_type)
981 {
982         int i, j;
983
984         for (i = 0; i < ENVCTRL_MAX_CPU*2; i++) {
985                 for (j = 0; j < PCF8584_MAX_CHANNELS; j++) {
986                         if (i2c_childlist[i].mon_type[j] == mon_type) {
987                                 return (struct i2c_child_t *)(&(i2c_childlist[i]));
988                         }
989                 }
990         }
991         return NULL;
992 }
993
994 static void envctrl_do_shutdown(void)
995 {
996         static int inprog = 0;
997         static char *envp[] = { 
998                 "HOME=/", "TERM=linux", "PATH=/sbin:/usr/sbin:/bin:/usr/bin", NULL };
999         char *argv[] = { 
1000                 "/sbin/shutdown", "-h", "now", NULL };  
1001
1002         if (inprog != 0)
1003                 return;
1004
1005         inprog = 1;
1006         printk(KERN_CRIT "kenvctrld: WARNING: Shutting down the system now.\n");
1007         if (0 > execve("/sbin/shutdown", argv, envp)) {
1008                 printk(KERN_CRIT "kenvctrld: WARNING: system shutdown failed!\n"); 
1009                 inprog = 0;  /* unlikely to succeed, but we could try again */
1010         }
1011 }
1012
1013 static struct task_struct *kenvctrld_task;
1014
1015 static int kenvctrld(void *__unused)
1016 {
1017         int poll_interval;
1018         int whichcpu;
1019         char tempbuf[10];
1020         struct i2c_child_t *cputemp;
1021
1022         if (NULL == (cputemp = envctrl_get_i2c_child(ENVCTRL_CPUTEMP_MON))) {
1023                 printk(KERN_ERR 
1024                        "envctrl: kenvctrld unable to monitor CPU temp-- exiting\n");
1025                 return -ENODEV;
1026         }
1027
1028         poll_interval = 5 * HZ; /* TODO env_mon_interval */
1029
1030         daemonize("kenvctrld");
1031         allow_signal(SIGKILL);
1032
1033         kenvctrld_task = current;
1034
1035         printk(KERN_INFO "envctrl: %s starting...\n", current->comm);
1036         for (;;) {
1037                 current->state = TASK_INTERRUPTIBLE;
1038                 schedule_timeout(poll_interval);
1039
1040                 if(signal_pending(current))
1041                         break;
1042
1043                 for (whichcpu = 0; whichcpu < ENVCTRL_MAX_CPU; ++whichcpu) {
1044                         if (0 < envctrl_read_cpu_info(whichcpu, cputemp,
1045                                                       ENVCTRL_CPUTEMP_MON,
1046                                                       tempbuf)) {
1047                                 if (tempbuf[0] >= shutdown_temperature) {
1048                                         printk(KERN_CRIT 
1049                                                 "%s: WARNING: CPU%i temperature %i C meets or exceeds "\
1050                                                 "shutdown threshold %i C\n", 
1051                                                 current->comm, whichcpu, 
1052                                                 tempbuf[0], shutdown_temperature);
1053                                         envctrl_do_shutdown();
1054                                 }
1055                         }
1056                 }
1057         }
1058         printk(KERN_INFO "envctrl: %s exiting...\n", current->comm);
1059         return 0;
1060 }
1061
1062 static int __init envctrl_init(void)
1063 {
1064 #ifdef CONFIG_PCI
1065         struct linux_ebus *ebus = NULL;
1066         struct linux_ebus_device *edev = NULL;
1067         struct linux_ebus_child *edev_child = NULL;
1068         int err, i = 0;
1069
1070         for_each_ebus(ebus) {
1071                 for_each_ebusdev(edev, ebus) {
1072                         if (!strcmp(edev->prom_name, "bbc")) {
1073                                 /* If we find a boot-bus controller node,
1074                                  * then this envctrl driver is not for us.
1075                                  */
1076                                 return -ENODEV;
1077                         }
1078                 }
1079         }
1080
1081         /* Traverse through ebus and ebus device list for i2c device and
1082          * adc and gpio nodes.
1083          */
1084         for_each_ebus(ebus) {
1085                 for_each_ebusdev(edev, ebus) {
1086                         if (!strcmp(edev->prom_name, "i2c")) {
1087                                 i2c = ioremap(  edev->resource[0].start, 
1088                                                                 sizeof(struct pcf8584_reg));
1089                                 for_each_edevchild(edev, edev_child) {
1090                                         if (!strcmp("gpio", edev_child->prom_name)) {
1091                                                 i2c_childlist[i].i2ctype = I2C_GPIO;
1092                                                 envctrl_init_i2c_child(edev_child, &(i2c_childlist[i++]));
1093                                         }
1094                                         if (!strcmp("adc", edev_child->prom_name)) {
1095                                                 i2c_childlist[i].i2ctype = I2C_ADC;
1096                                                 envctrl_init_i2c_child(edev_child, &(i2c_childlist[i++]));
1097                                         }
1098                                 }
1099                                 goto done;
1100                         }
1101                 }
1102         }
1103
1104 done:
1105         if (!edev) {
1106                 printk("envctrl: I2C device not found.\n");
1107                 return -ENODEV;
1108         }
1109
1110         /* Set device address. */
1111         envctrl_writeb(CONTROL_PIN, &i2c->csr);
1112         envctrl_writeb(PCF8584_ADDRESS, &i2c->data);
1113
1114         /* Set system clock and SCL frequencies. */ 
1115         envctrl_writeb(CONTROL_PIN | CONTROL_ES1, &i2c->csr);
1116         envctrl_writeb(CLK_4_43 | BUS_CLK_90, &i2c->data);
1117
1118         /* Enable serial interface. */
1119         envctrl_writeb(CONTROL_PIN | CONTROL_ES0 | CONTROL_ACK, &i2c->csr);
1120         udelay(200);
1121
1122         /* Register the device as a minor miscellaneous device. */
1123         err = misc_register(&envctrl_dev);
1124         if (err) {
1125                 printk("envctrl: Unable to get misc minor %d\n",
1126                        envctrl_dev.minor);
1127                 goto out_iounmap;
1128         }
1129
1130         /* Note above traversal routine post-incremented 'i' to accommodate 
1131          * a next child device, so we decrement before reverse-traversal of
1132          * child devices.
1133          */
1134         printk("envctrl: initialized ");
1135         for (--i; i >= 0; --i) {
1136                 printk("[%s 0x%lx]%s", 
1137                         (I2C_ADC == i2c_childlist[i].i2ctype) ? ("adc") : 
1138                         ((I2C_GPIO == i2c_childlist[i].i2ctype) ? ("gpio") : ("unknown")), 
1139                         i2c_childlist[i].addr, (0 == i) ? ("\n") : (" "));
1140         }
1141
1142         err = kernel_thread(kenvctrld, NULL, CLONE_FS | CLONE_FILES);
1143         if (err < 0)
1144                 goto out_deregister;
1145
1146         return 0;
1147
1148 out_deregister:
1149         misc_deregister(&envctrl_dev);
1150 out_iounmap:
1151         iounmap(i2c);
1152         for (i = 0; i < ENVCTRL_MAX_CPU * 2; i++) {
1153                 if (i2c_childlist[i].tables)
1154                         kfree(i2c_childlist[i].tables);
1155         }
1156         return err;
1157 #else
1158         return -ENODEV;
1159 #endif
1160 }
1161
1162 static void __exit envctrl_cleanup(void)
1163 {
1164         int i;
1165
1166         if (NULL != kenvctrld_task) {
1167                 force_sig(SIGKILL, kenvctrld_task);
1168                 for (;;) {
1169                         struct task_struct *p;
1170                         int found = 0;
1171
1172                         read_lock(&tasklist_lock);
1173                         for_each_process(p) {
1174                                 if (p == kenvctrld_task) {
1175                                         found = 1;
1176                                         break;
1177                                 }
1178                         }
1179                         read_unlock(&tasklist_lock);
1180
1181                         if (!found)
1182                                 break;
1183
1184                         current->state = TASK_INTERRUPTIBLE;
1185                         schedule_timeout(HZ);
1186                 }
1187                 kenvctrld_task = NULL;
1188         }
1189
1190         iounmap(i2c);
1191         misc_deregister(&envctrl_dev);
1192
1193         for (i = 0; i < ENVCTRL_MAX_CPU * 2; i++) {
1194                 if (i2c_childlist[i].tables)
1195                         kfree(i2c_childlist[i].tables);
1196         }
1197 }
1198
1199 module_init(envctrl_init);
1200 module_exit(envctrl_cleanup);
1201 MODULE_LICENSE("GPL");