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