vserver 1.9.5.x5
[linux-2.6.git] / drivers / macintosh / therm_pm72.c
1 /*
2  * Device driver for the thermostats & fan controller of  the
3  * Apple G5 "PowerMac7,2" desktop machines.
4  *
5  * (c) Copyright IBM Corp. 2003-2004
6  *
7  * Maintained by: Benjamin Herrenschmidt
8  *                <benh@kernel.crashing.org>
9  * 
10  *
11  * The algorithm used is the PID control algorithm, used the same
12  * way the published Darwin code does, using the same values that
13  * are present in the Darwin 7.0 snapshot property lists.
14  *
15  * As far as the CPUs control loops are concerned, I use the
16  * calibration & PID constants provided by the EEPROM,
17  * I do _not_ embed any value from the property lists, as the ones
18  * provided by Darwin 7.0 seem to always have an older version that
19  * what I've seen on the actual computers.
20  * It would be interesting to verify that though. Darwin has a
21  * version code of 1.0.0d11 for all control loops it seems, while
22  * so far, the machines EEPROMs contain a dataset versioned 1.0.0f
23  *
24  * Darwin doesn't provide source to all parts, some missing
25  * bits like the AppleFCU driver or the actual scale of some
26  * of the values returned by sensors had to be "guessed" some
27  * way... or based on what Open Firmware does.
28  *
29  * I didn't yet figure out how to get the slots power consumption
30  * out of the FCU, so that part has not been implemented yet and
31  * the slots fan is set to a fixed 50% PWM, hoping this value is
32  * safe enough ...
33  *
34  * Note: I have observed strange oscillations of the CPU control
35  * loop on a dual G5 here. When idle, the CPU exhaust fan tend to
36  * oscillates slowly (over several minutes) between the minimum
37  * of 300RPMs and approx. 1000 RPMs. I don't know what is causing
38  * this, it could be some incorrect constant or an error in the
39  * way I ported the algorithm, or it could be just normal. I
40  * don't have full understanding on the way Apple tweaked the PID
41  * algorithm for the CPU control, it is definitely not a standard
42  * implementation...
43  *
44  * TODO:  - Check MPU structure version/signature
45  *        - Add things like /sbin/overtemp for non-critical
46  *          overtemp conditions so userland can take some policy
47  *          decisions, like slewing down CPUs
48  *        - Deal with fan and i2c failures in a better way
49  *        - Maybe do a generic PID based on params used for
50  *          U3 and Drives ?
51  *        - Add RackMac3,1 support (XServe g5)
52  *
53  * History:
54  *
55  *  Nov. 13, 2003 : 0.5
56  *      - First release
57  *
58  *  Nov. 14, 2003 : 0.6
59  *      - Read fan speed from FCU, low level fan routines now deal
60  *        with errors & check fan status, though higher level don't
61  *        do much.
62  *      - Move a bunch of definitions to .h file
63  *
64  *  Nov. 18, 2003 : 0.7
65  *      - Fix build on ppc64 kernel
66  *      - Move back statics definitions to .c file
67  *      - Avoid calling schedule_timeout with a negative number
68  *
69  *  Dec. 18, 2003 : 0.8
70  *      - Fix typo when reading back fan speed on 2 CPU machines
71  *
72  *  Mar. 11, 2004 : 0.9
73  *      - Rework code accessing the ADC chips, make it more robust and
74  *        closer to the chip spec. Also make sure it is configured properly,
75  *        I've seen yet unexplained cases where on startup, I would have stale
76  *        values in the configuration register
77  *      - Switch back to use of target fan speed for PID, thus lowering
78  *        pressure on i2c
79  *
80  *  Oct. 20, 2004 : 1.1
81  *      - Add device-tree lookup for fan IDs, should detect liquid cooling
82  *        pumps when present
83  *      - Enable driver for PowerMac7,3 machines
84  *      - Split the U3/Backside cooling on U3 & U3H versions as Darwin does
85  *      - Add new CPU cooling algorithm for machines with liquid cooling
86  *      - Workaround for some PowerMac7,3 with empty "fan" node in the devtree
87  *      - Fix a signed/unsigned compare issue in some PID loops
88  */
89
90 #include <linux/config.h>
91 #include <linux/types.h>
92 #include <linux/module.h>
93 #include <linux/errno.h>
94 #include <linux/kernel.h>
95 #include <linux/delay.h>
96 #include <linux/sched.h>
97 #include <linux/i2c.h>
98 #include <linux/slab.h>
99 #include <linux/init.h>
100 #include <linux/spinlock.h>
101 #include <linux/smp_lock.h>
102 #include <linux/wait.h>
103 #include <linux/reboot.h>
104 #include <linux/kmod.h>
105 #include <linux/i2c.h>
106 #include <linux/i2c-dev.h>
107 #include <asm/prom.h>
108 #include <asm/machdep.h>
109 #include <asm/io.h>
110 #include <asm/system.h>
111 #include <asm/sections.h>
112 #include <asm/of_device.h>
113
114 #include "therm_pm72.h"
115
116 #define VERSION "1.1"
117
118 #undef DEBUG
119
120 #ifdef DEBUG
121 #define DBG(args...)    printk(args)
122 #else
123 #define DBG(args...)    do { } while(0)
124 #endif
125
126
127 /*
128  * Driver statics
129  */
130
131 static struct of_device *               of_dev;
132 static struct i2c_adapter *             u3_0;
133 static struct i2c_adapter *             u3_1;
134 static struct i2c_client *              fcu;
135 static struct cpu_pid_state             cpu_state[2];
136 static struct basckside_pid_params      backside_params;
137 static struct backside_pid_state        backside_state;
138 static struct drives_pid_state          drives_state;
139 static int                              state;
140 static int                              cpu_count;
141 static int                              cpu_pid_type;
142 static pid_t                            ctrl_task;
143 static struct completion                ctrl_complete;
144 static int                              critical_state;
145 static DECLARE_MUTEX(driver_lock);
146
147 /*
148  * We have 2 types of CPU PID control. One is "split" old style control
149  * for intake & exhaust fans, the other is "combined" control for both
150  * CPUs that also deals with the pumps when present. To be "compatible"
151  * with OS X at this point, we only use "COMBINED" on the machines that
152  * are identified as having the pumps (though that identification is at
153  * least dodgy). Ultimately, we could probably switch completely to this
154  * algorithm provided we hack it to deal with the UP case
155  */
156 #define CPU_PID_TYPE_SPLIT      0
157 #define CPU_PID_TYPE_COMBINED   1
158
159 /*
160  * This table describes all fans in the FCU. The "id" and "type" values
161  * are defaults valid for all earlier machines. Newer machines will
162  * eventually override the table content based on the device-tree
163  */
164 struct fcu_fan_table
165 {
166         char*   loc;    /* location code */
167         int     type;   /* 0 = rpm, 1 = pwm, 2 = pump */
168         int     id;     /* id or -1 */
169 };
170
171 #define FCU_FAN_RPM             0
172 #define FCU_FAN_PWM             1
173
174 #define FCU_FAN_ABSENT_ID       -1
175
176 #define FCU_FAN_COUNT           ARRAY_SIZE(fcu_fans)
177
178 struct fcu_fan_table    fcu_fans[] = {
179         [BACKSIDE_FAN_PWM_INDEX] = {
180                 .loc    = "BACKSIDE",
181                 .type   = FCU_FAN_PWM,
182                 .id     = BACKSIDE_FAN_PWM_DEFAULT_ID,
183         },
184         [DRIVES_FAN_RPM_INDEX] = {
185                 .loc    = "DRIVE BAY",
186                 .type   = FCU_FAN_RPM,
187                 .id     = DRIVES_FAN_RPM_DEFAULT_ID,
188         },
189         [SLOTS_FAN_PWM_INDEX] = {
190                 .loc    = "SLOT",
191                 .type   = FCU_FAN_PWM,
192                 .id     = SLOTS_FAN_PWM_DEFAULT_ID,
193         },
194         [CPUA_INTAKE_FAN_RPM_INDEX] = {
195                 .loc    = "CPU A INTAKE",
196                 .type   = FCU_FAN_RPM,
197                 .id     = CPUA_INTAKE_FAN_RPM_DEFAULT_ID,
198         },
199         [CPUA_EXHAUST_FAN_RPM_INDEX] = {
200                 .loc    = "CPU A EXHAUST",
201                 .type   = FCU_FAN_RPM,
202                 .id     = CPUA_EXHAUST_FAN_RPM_DEFAULT_ID,
203         },
204         [CPUB_INTAKE_FAN_RPM_INDEX] = {
205                 .loc    = "CPU B INTAKE",
206                 .type   = FCU_FAN_RPM,
207                 .id     = CPUB_INTAKE_FAN_RPM_DEFAULT_ID,
208         },
209         [CPUB_EXHAUST_FAN_RPM_INDEX] = {
210                 .loc    = "CPU B EXHAUST",
211                 .type   = FCU_FAN_RPM,
212                 .id     = CPUB_EXHAUST_FAN_RPM_DEFAULT_ID,
213         },
214         /* pumps aren't present by default, have to be looked up in the
215          * device-tree
216          */
217         [CPUA_PUMP_RPM_INDEX] = {
218                 .loc    = "CPU A PUMP",
219                 .type   = FCU_FAN_RPM,          
220                 .id     = FCU_FAN_ABSENT_ID,
221         },
222         [CPUB_PUMP_RPM_INDEX] = {
223                 .loc    = "CPU B PUMP",
224                 .type   = FCU_FAN_RPM,
225                 .id     = FCU_FAN_ABSENT_ID,
226         },
227 };
228
229 /*
230  * i2c_driver structure to attach to the host i2c controller
231  */
232
233 static int therm_pm72_attach(struct i2c_adapter *adapter);
234 static int therm_pm72_detach(struct i2c_adapter *adapter);
235
236 static struct i2c_driver therm_pm72_driver =
237 {
238         .owner          = THIS_MODULE,
239         .name           = "therm_pm72",
240         .flags          = I2C_DF_NOTIFY,
241         .attach_adapter = therm_pm72_attach,
242         .detach_adapter = therm_pm72_detach,
243 };
244
245 /*
246  * Utility function to create an i2c_client structure and
247  * attach it to one of u3 adapters
248  */
249 static struct i2c_client *attach_i2c_chip(int id, const char *name)
250 {
251         struct i2c_client *clt;
252         struct i2c_adapter *adap;
253
254         if (id & 0x100)
255                 adap = u3_1;
256         else
257                 adap = u3_0;
258         if (adap == NULL)
259                 return NULL;
260
261         clt = kmalloc(sizeof(struct i2c_client), GFP_KERNEL);
262         if (clt == NULL)
263                 return NULL;
264         memset(clt, 0, sizeof(struct i2c_client));
265
266         clt->addr = (id >> 1) & 0x7f;
267         clt->adapter = adap;
268         clt->driver = &therm_pm72_driver;
269         strncpy(clt->name, name, I2C_NAME_SIZE-1);
270
271         if (i2c_attach_client(clt)) {
272                 printk(KERN_ERR "therm_pm72: Failed to attach to i2c ID 0x%x\n", id);
273                 kfree(clt);
274                 return NULL;
275         }
276         return clt;
277 }
278
279 /*
280  * Utility function to get rid of the i2c_client structure
281  * (will also detach from the adapter hopepfully)
282  */
283 static void detach_i2c_chip(struct i2c_client *clt)
284 {
285         i2c_detach_client(clt);
286         kfree(clt);
287 }
288
289 /*
290  * Here are the i2c chip access wrappers
291  */
292
293 static void initialize_adc(struct cpu_pid_state *state)
294 {
295         int rc;
296         u8 buf[2];
297
298         /* Read ADC the configuration register and cache it. We
299          * also make sure Config2 contains proper values, I've seen
300          * cases where we got stale grabage in there, thus preventing
301          * proper reading of conv. values
302          */
303
304         /* Clear Config2 */
305         buf[0] = 5;
306         buf[1] = 0;
307         i2c_master_send(state->monitor, buf, 2);
308
309         /* Read & cache Config1 */
310         buf[0] = 1;
311         rc = i2c_master_send(state->monitor, buf, 1);
312         if (rc > 0) {
313                 rc = i2c_master_recv(state->monitor, buf, 1);
314                 if (rc > 0) {
315                         state->adc_config = buf[0];
316                         DBG("ADC config reg: %02x\n", state->adc_config);
317                         /* Disable shutdown mode */
318                         state->adc_config &= 0xfe;
319                         buf[0] = 1;
320                         buf[1] = state->adc_config;
321                         rc = i2c_master_send(state->monitor, buf, 2);
322                 }
323         }
324         if (rc <= 0)
325                 printk(KERN_ERR "therm_pm72: Error reading ADC config"
326                        " register !\n");
327 }
328
329 static int read_smon_adc(struct cpu_pid_state *state, int chan)
330 {
331         int rc, data, tries = 0;
332         u8 buf[2];
333
334         for (;;) {
335                 /* Set channel */
336                 buf[0] = 1;
337                 buf[1] = (state->adc_config & 0x1f) | (chan << 5);
338                 rc = i2c_master_send(state->monitor, buf, 2);
339                 if (rc <= 0)
340                         goto error;
341                 /* Wait for convertion */
342                 msleep(1);
343                 /* Switch to data register */
344                 buf[0] = 4;
345                 rc = i2c_master_send(state->monitor, buf, 1);
346                 if (rc <= 0)
347                         goto error;
348                 /* Read result */
349                 rc = i2c_master_recv(state->monitor, buf, 2);
350                 if (rc < 0)
351                         goto error;
352                 data = ((u16)buf[0]) << 8 | (u16)buf[1];
353                 return data >> 6;
354         error:
355                 DBG("Error reading ADC, retrying...\n");
356                 if (++tries > 10) {
357                         printk(KERN_ERR "therm_pm72: Error reading ADC !\n");
358                         return -1;
359                 }
360                 msleep(10);
361         }
362 }
363
364 static int fan_read_reg(int reg, unsigned char *buf, int nb)
365 {
366         int tries, nr, nw;
367
368         buf[0] = reg;
369         tries = 0;
370         for (;;) {
371                 nw = i2c_master_send(fcu, buf, 1);
372                 if (nw > 0 || (nw < 0 && nw != -EIO) || tries >= 100)
373                         break;
374                 msleep(10);
375                 ++tries;
376         }
377         if (nw <= 0) {
378                 printk(KERN_ERR "Failure writing address to FCU: %d", nw);
379                 return -EIO;
380         }
381         tries = 0;
382         for (;;) {
383                 nr = i2c_master_recv(fcu, buf, nb);
384                 if (nr > 0 || (nr < 0 && nr != ENODEV) || tries >= 100)
385                         break;
386                 msleep(10);
387                 ++tries;
388         }
389         if (nr <= 0)
390                 printk(KERN_ERR "Failure reading data from FCU: %d", nw);
391         return nr;
392 }
393
394 static int fan_write_reg(int reg, const unsigned char *ptr, int nb)
395 {
396         int tries, nw;
397         unsigned char buf[16];
398
399         buf[0] = reg;
400         memcpy(buf+1, ptr, nb);
401         ++nb;
402         tries = 0;
403         for (;;) {
404                 nw = i2c_master_send(fcu, buf, nb);
405                 if (nw > 0 || (nw < 0 && nw != EIO) || tries >= 100)
406                         break;
407                 msleep(10);
408                 ++tries;
409         }
410         if (nw < 0)
411                 printk(KERN_ERR "Failure writing to FCU: %d", nw);
412         return nw;
413 }
414
415 static int start_fcu(void)
416 {
417         unsigned char buf = 0xff;
418         int rc;
419
420         rc = fan_write_reg(0xe, &buf, 1);
421         if (rc < 0)
422                 return -EIO;
423         rc = fan_write_reg(0x2e, &buf, 1);
424         if (rc < 0)
425                 return -EIO;
426         return 0;
427 }
428
429 static int set_rpm_fan(int fan_index, int rpm)
430 {
431         unsigned char buf[2];
432         int rc, id;
433
434         if (fcu_fans[fan_index].type != FCU_FAN_RPM)
435                 return -EINVAL;
436         id = fcu_fans[fan_index].id; 
437         if (id == FCU_FAN_ABSENT_ID)
438                 return -EINVAL;
439
440         if (rpm < 300)
441                 rpm = 300;
442         else if (rpm > 8191)
443                 rpm = 8191;
444         buf[0] = rpm >> 5;
445         buf[1] = rpm << 3;
446         rc = fan_write_reg(0x10 + (id * 2), buf, 2);
447         if (rc < 0)
448                 return -EIO;
449         return 0;
450 }
451
452 static int get_rpm_fan(int fan_index, int programmed)
453 {
454         unsigned char failure;
455         unsigned char active;
456         unsigned char buf[2];
457         int rc, id, reg_base;
458
459         if (fcu_fans[fan_index].type != FCU_FAN_RPM)
460                 return -EINVAL;
461         id = fcu_fans[fan_index].id; 
462         if (id == FCU_FAN_ABSENT_ID)
463                 return -EINVAL;
464
465         rc = fan_read_reg(0xb, &failure, 1);
466         if (rc != 1)
467                 return -EIO;
468         if ((failure & (1 << id)) != 0)
469                 return -EFAULT;
470         rc = fan_read_reg(0xd, &active, 1);
471         if (rc != 1)
472                 return -EIO;
473         if ((active & (1 << id)) == 0)
474                 return -ENXIO;
475
476         /* Programmed value or real current speed */
477         reg_base = programmed ? 0x10 : 0x11;
478         rc = fan_read_reg(reg_base + (id * 2), buf, 2);
479         if (rc != 2)
480                 return -EIO;
481
482         return (buf[0] << 5) | buf[1] >> 3;
483 }
484
485 static int set_pwm_fan(int fan_index, int pwm)
486 {
487         unsigned char buf[2];
488         int rc, id;
489
490         if (fcu_fans[fan_index].type != FCU_FAN_PWM)
491                 return -EINVAL;
492         id = fcu_fans[fan_index].id; 
493         if (id == FCU_FAN_ABSENT_ID)
494                 return -EINVAL;
495
496         if (pwm < 10)
497                 pwm = 10;
498         else if (pwm > 100)
499                 pwm = 100;
500         pwm = (pwm * 2559) / 1000;
501         buf[0] = pwm;
502         rc = fan_write_reg(0x30 + (id * 2), buf, 1);
503         if (rc < 0)
504                 return rc;
505         return 0;
506 }
507
508 static int get_pwm_fan(int fan_index)
509 {
510         unsigned char failure;
511         unsigned char active;
512         unsigned char buf[2];
513         int rc, id;
514
515         if (fcu_fans[fan_index].type != FCU_FAN_PWM)
516                 return -EINVAL;
517         id = fcu_fans[fan_index].id; 
518         if (id == FCU_FAN_ABSENT_ID)
519                 return -EINVAL;
520
521         rc = fan_read_reg(0x2b, &failure, 1);
522         if (rc != 1)
523                 return -EIO;
524         if ((failure & (1 << id)) != 0)
525                 return -EFAULT;
526         rc = fan_read_reg(0x2d, &active, 1);
527         if (rc != 1)
528                 return -EIO;
529         if ((active & (1 << id)) == 0)
530                 return -ENXIO;
531
532         /* Programmed value or real current speed */
533         rc = fan_read_reg(0x30 + (id * 2), buf, 1);
534         if (rc != 1)
535                 return -EIO;
536
537         return (buf[0] * 1000) / 2559;
538 }
539
540 /*
541  * Utility routine to read the CPU calibration EEPROM data
542  * from the device-tree
543  */
544 static int read_eeprom(int cpu, struct mpu_data *out)
545 {
546         struct device_node *np;
547         char nodename[64];
548         u8 *data;
549         int len;
550
551         /* prom.c routine for finding a node by path is a bit brain dead
552          * and requires exact @xxx unit numbers. This is a bit ugly but
553          * will work for these machines
554          */
555         sprintf(nodename, "/u3@0,f8000000/i2c@f8001000/cpuid@a%d", cpu ? 2 : 0);
556         np = of_find_node_by_path(nodename);
557         if (np == NULL) {
558                 printk(KERN_ERR "therm_pm72: Failed to retreive cpuid node from device-tree\n");
559                 return -ENODEV;
560         }
561         data = (u8 *)get_property(np, "cpuid", &len);
562         if (data == NULL) {
563                 printk(KERN_ERR "therm_pm72: Failed to retreive cpuid property from device-tree\n");
564                 of_node_put(np);
565                 return -ENODEV;
566         }
567         memcpy(out, data, sizeof(struct mpu_data));
568         of_node_put(np);
569         
570         return 0;
571 }
572
573 /* 
574  * Now, unfortunately, sysfs doesn't give us a nice void * we could
575  * pass around to the attribute functions, so we don't really have
576  * choice but implement a bunch of them...
577  *
578  * That sucks a bit, we take the lock because FIX32TOPRINT evaluates
579  * the input twice... I accept patches :)
580  */
581 #define BUILD_SHOW_FUNC_FIX(name, data)                         \
582 static ssize_t show_##name(struct device *dev, char *buf)       \
583 {                                                               \
584         ssize_t r;                                              \
585         down(&driver_lock);                                     \
586         r = sprintf(buf, "%d.%03d", FIX32TOPRINT(data));        \
587         up(&driver_lock);                                       \
588         return r;                                               \
589 }
590 #define BUILD_SHOW_FUNC_INT(name, data)                         \
591 static ssize_t show_##name(struct device *dev, char *buf)       \
592 {                                                               \
593         return sprintf(buf, "%d", data);                        \
594 }
595
596 BUILD_SHOW_FUNC_FIX(cpu0_temperature, cpu_state[0].last_temp)
597 BUILD_SHOW_FUNC_FIX(cpu0_voltage, cpu_state[0].voltage)
598 BUILD_SHOW_FUNC_FIX(cpu0_current, cpu_state[0].current_a)
599 BUILD_SHOW_FUNC_INT(cpu0_exhaust_fan_rpm, cpu_state[0].rpm)
600 BUILD_SHOW_FUNC_INT(cpu0_intake_fan_rpm, cpu_state[0].intake_rpm)
601
602 BUILD_SHOW_FUNC_FIX(cpu1_temperature, cpu_state[1].last_temp)
603 BUILD_SHOW_FUNC_FIX(cpu1_voltage, cpu_state[1].voltage)
604 BUILD_SHOW_FUNC_FIX(cpu1_current, cpu_state[1].current_a)
605 BUILD_SHOW_FUNC_INT(cpu1_exhaust_fan_rpm, cpu_state[1].rpm)
606 BUILD_SHOW_FUNC_INT(cpu1_intake_fan_rpm, cpu_state[1].intake_rpm)
607
608 BUILD_SHOW_FUNC_FIX(backside_temperature, backside_state.last_temp)
609 BUILD_SHOW_FUNC_INT(backside_fan_pwm, backside_state.pwm)
610
611 BUILD_SHOW_FUNC_FIX(drives_temperature, drives_state.last_temp)
612 BUILD_SHOW_FUNC_INT(drives_fan_rpm, drives_state.rpm)
613
614 static DEVICE_ATTR(cpu0_temperature,S_IRUGO,show_cpu0_temperature,NULL);
615 static DEVICE_ATTR(cpu0_voltage,S_IRUGO,show_cpu0_voltage,NULL);
616 static DEVICE_ATTR(cpu0_current,S_IRUGO,show_cpu0_current,NULL);
617 static DEVICE_ATTR(cpu0_exhaust_fan_rpm,S_IRUGO,show_cpu0_exhaust_fan_rpm,NULL);
618 static DEVICE_ATTR(cpu0_intake_fan_rpm,S_IRUGO,show_cpu0_intake_fan_rpm,NULL);
619
620 static DEVICE_ATTR(cpu1_temperature,S_IRUGO,show_cpu1_temperature,NULL);
621 static DEVICE_ATTR(cpu1_voltage,S_IRUGO,show_cpu1_voltage,NULL);
622 static DEVICE_ATTR(cpu1_current,S_IRUGO,show_cpu1_current,NULL);
623 static DEVICE_ATTR(cpu1_exhaust_fan_rpm,S_IRUGO,show_cpu1_exhaust_fan_rpm,NULL);
624 static DEVICE_ATTR(cpu1_intake_fan_rpm,S_IRUGO,show_cpu1_intake_fan_rpm,NULL);
625
626 static DEVICE_ATTR(backside_temperature,S_IRUGO,show_backside_temperature,NULL);
627 static DEVICE_ATTR(backside_fan_pwm,S_IRUGO,show_backside_fan_pwm,NULL);
628
629 static DEVICE_ATTR(drives_temperature,S_IRUGO,show_drives_temperature,NULL);
630 static DEVICE_ATTR(drives_fan_rpm,S_IRUGO,show_drives_fan_rpm,NULL);
631
632 /*
633  * CPUs fans control loop
634  */
635
636 static int do_read_one_cpu_values(struct cpu_pid_state *state, s32 *temp, s32 *power)
637 {
638         s32 ltemp, volts, amps;
639         int rc = 0;
640
641         /* Default (in case of error) */
642         *temp = state->cur_temp;
643         *power = state->cur_power;
644
645         /* Read current fan status */
646         if (state->index == 0)
647                 rc = get_rpm_fan(CPUA_EXHAUST_FAN_RPM_INDEX, !RPM_PID_USE_ACTUAL_SPEED);
648         else
649                 rc = get_rpm_fan(CPUB_EXHAUST_FAN_RPM_INDEX, !RPM_PID_USE_ACTUAL_SPEED);
650         if (rc < 0) {
651                 /* XXX What do we do now ? Nothing for now, keep old value, but
652                  * return error upstream
653                  */
654                 DBG("  cpu %d, fan reading error !\n", state->index);
655         } else {
656                 state->rpm = rc;
657                 DBG("  cpu %d, exhaust RPM: %d\n", state->index, state->rpm);
658         }
659
660         /* Get some sensor readings and scale it */
661         ltemp = read_smon_adc(state, 1);
662         if (ltemp == -1) {
663                 /* XXX What do we do now ? */
664                 state->overtemp++;
665                 if (rc == 0)
666                         rc = -EIO;
667                 DBG("  cpu %d, temp reading error !\n", state->index);
668         } else {
669                 /* Fixup temperature according to diode calibration
670                  */
671                 DBG("  cpu %d, temp raw: %04x, m_diode: %04x, b_diode: %04x\n",
672                     state->index,
673                     ltemp, state->mpu.mdiode, state->mpu.bdiode);
674                 *temp = ((s32)ltemp * (s32)state->mpu.mdiode + ((s32)state->mpu.bdiode << 12)) >> 2;
675                 state->last_temp = *temp;
676                 DBG("  temp: %d.%03d\n", FIX32TOPRINT((*temp)));
677         }
678
679         /*
680          * Read voltage & current and calculate power
681          */
682         volts = read_smon_adc(state, 3);
683         amps = read_smon_adc(state, 4);
684
685         /* Scale voltage and current raw sensor values according to fixed scales
686          * obtained in Darwin and calculate power from I and V
687          */
688         volts *= ADC_CPU_VOLTAGE_SCALE;
689         amps *= ADC_CPU_CURRENT_SCALE;
690         *power = (((u64)volts) * ((u64)amps)) >> 16;
691         state->voltage = volts;
692         state->current_a = amps;
693         state->last_power = *power;
694
695         DBG("  cpu %d, current: %d.%03d, voltage: %d.%03d, power: %d.%03d W\n",
696             state->index, FIX32TOPRINT(state->current_a),
697             FIX32TOPRINT(state->voltage), FIX32TOPRINT(*power));
698
699         return 0;
700 }
701
702 static void do_cpu_pid(struct cpu_pid_state *state, s32 temp, s32 power)
703 {
704         s32 power_target, integral, derivative, proportional, adj_in_target, sval;
705         s64 integ_p, deriv_p, prop_p, sum; 
706         int i;
707
708         /* Calculate power target value (could be done once for all)
709          * and convert to a 16.16 fp number
710          */
711         power_target = ((u32)(state->mpu.pmaxh - state->mpu.padjmax)) << 16;
712         DBG("  power target: %d.%03d, error: %d.%03d\n",
713             FIX32TOPRINT(power_target), FIX32TOPRINT(power_target - power));
714
715         /* Store temperature and power in history array */
716         state->cur_temp = (state->cur_temp + 1) % CPU_TEMP_HISTORY_SIZE;
717         state->temp_history[state->cur_temp] = temp;
718         state->cur_power = (state->cur_power + 1) % state->count_power;
719         state->power_history[state->cur_power] = power;
720         state->error_history[state->cur_power] = power_target - power;
721         
722         /* If first loop, fill the history table */
723         if (state->first) {
724                 for (i = 0; i < (state->count_power - 1); i++) {
725                         state->cur_power = (state->cur_power + 1) % state->count_power;
726                         state->power_history[state->cur_power] = power;
727                         state->error_history[state->cur_power] = power_target - power;
728                 }
729                 for (i = 0; i < (CPU_TEMP_HISTORY_SIZE - 1); i++) {
730                         state->cur_temp = (state->cur_temp + 1) % CPU_TEMP_HISTORY_SIZE;
731                         state->temp_history[state->cur_temp] = temp;                    
732                 }
733                 state->first = 0;
734         }
735
736         /* Calculate the integral term normally based on the "power" values */
737         sum = 0;
738         integral = 0;
739         for (i = 0; i < state->count_power; i++)
740                 integral += state->error_history[i];
741         integral *= CPU_PID_INTERVAL;
742         DBG("  integral: %08x\n", integral);
743
744         /* Calculate the adjusted input (sense value).
745          *   G_r is 12.20
746          *   integ is 16.16
747          *   so the result is 28.36
748          *
749          * input target is mpu.ttarget, input max is mpu.tmax
750          */
751         integ_p = ((s64)state->mpu.pid_gr) * (s64)integral;
752         DBG("   integ_p: %d\n", (int)(integ_p >> 36));
753         sval = (state->mpu.tmax << 16) - ((integ_p >> 20) & 0xffffffff);
754         adj_in_target = (state->mpu.ttarget << 16);
755         if (adj_in_target > sval)
756                 adj_in_target = sval;
757         DBG("   adj_in_target: %d.%03d, ttarget: %d\n", FIX32TOPRINT(adj_in_target),
758             state->mpu.ttarget);
759
760         /* Calculate the derivative term */
761         derivative = state->temp_history[state->cur_temp] -
762                 state->temp_history[(state->cur_temp + CPU_TEMP_HISTORY_SIZE - 1)
763                                     % CPU_TEMP_HISTORY_SIZE];
764         derivative /= CPU_PID_INTERVAL;
765         deriv_p = ((s64)state->mpu.pid_gd) * (s64)derivative;
766         DBG("   deriv_p: %d\n", (int)(deriv_p >> 36));
767         sum += deriv_p;
768
769         /* Calculate the proportional term */
770         proportional = temp - adj_in_target;
771         prop_p = ((s64)state->mpu.pid_gp) * (s64)proportional;
772         DBG("   prop_p: %d\n", (int)(prop_p >> 36));
773         sum += prop_p;
774
775         /* Scale sum */
776         sum >>= 36;
777
778         DBG("   sum: %d\n", (int)sum);
779         state->rpm += (s32)sum;
780
781         if (state->rpm < (int)state->mpu.rminn_exhaust_fan)
782                 state->rpm = state->mpu.rminn_exhaust_fan;
783         if (state->rpm > (int)state->mpu.rmaxn_exhaust_fan)
784                 state->rpm = state->mpu.rmaxn_exhaust_fan;
785 }
786
787 static void do_monitor_cpu_combined(void)
788 {
789         struct cpu_pid_state *state0 = &cpu_state[0];
790         struct cpu_pid_state *state1 = &cpu_state[1];
791         s32 temp0, power0, temp1, power1;
792         s32 temp_combi, power_combi;
793         int rc, intake, pump;
794
795         rc = do_read_one_cpu_values(state0, &temp0, &power0);
796         if (rc < 0) {
797                 /* XXX What do we do now ? */
798         }
799         state1->overtemp = 0;
800         rc = do_read_one_cpu_values(state1, &temp1, &power1);
801         if (rc < 0) {
802                 /* XXX What do we do now ? */
803         }
804         if (state1->overtemp)
805                 state0->overtemp++;
806
807         temp_combi = max(temp0, temp1);
808         power_combi = max(power0, power1);
809
810         /* Check tmax, increment overtemp if we are there. At tmax+8, we go
811          * full blown immediately and try to trigger a shutdown
812          */
813         if (temp_combi >= ((state0->mpu.tmax + 8) << 16)) {
814                 printk(KERN_WARNING "Warning ! Temperature way above maximum (%d) !\n",
815                        temp_combi >> 16);
816                 state0->overtemp = CPU_MAX_OVERTEMP;
817         } else if (temp_combi > (state0->mpu.tmax << 16))
818                 state0->overtemp++;
819         else
820                 state0->overtemp = 0;
821         if (state0->overtemp >= CPU_MAX_OVERTEMP)
822                 critical_state = 1;
823         if (state0->overtemp > 0) {
824                 state0->rpm = state0->mpu.rmaxn_exhaust_fan;
825                 state0->intake_rpm = intake = state0->mpu.rmaxn_intake_fan;
826                 pump = CPU_PUMP_OUTPUT_MAX;
827                 goto do_set_fans;
828         }
829
830         /* Do the PID */
831         do_cpu_pid(state0, temp_combi, power_combi);
832
833         /* Calculate intake fan speed */
834         intake = (state0->rpm * CPU_INTAKE_SCALE) >> 16;
835         if (intake < (int)state0->mpu.rminn_intake_fan)
836                 intake = state0->mpu.rminn_intake_fan;
837         if (intake > (int)state0->mpu.rmaxn_intake_fan)
838                 intake = state0->mpu.rmaxn_intake_fan;
839         state0->intake_rpm = intake;
840
841         /* Calculate pump speed */
842         pump = (state0->rpm * CPU_PUMP_OUTPUT_MAX) /
843                 state0->mpu.rmaxn_exhaust_fan;
844         if (pump > CPU_PUMP_OUTPUT_MAX)
845                 pump = CPU_PUMP_OUTPUT_MAX;
846         if (pump < CPU_PUMP_OUTPUT_MIN)
847                 pump = CPU_PUMP_OUTPUT_MIN;
848         
849  do_set_fans:
850         /* We copy values from state 0 to state 1 for /sysfs */
851         state1->rpm = state0->rpm;
852         state1->intake_rpm = state0->intake_rpm;
853
854         DBG("** CPU %d RPM: %d Ex, %d, Pump: %d, In, overtemp: %d\n",
855             state1->index, (int)state1->rpm, intake, pump, state1->overtemp);
856
857         /* We should check for errors, shouldn't we ? But then, what
858          * do we do once the error occurs ? For FCU notified fan
859          * failures (-EFAULT) we probably want to notify userland
860          * some way...
861          */
862         set_rpm_fan(CPUA_INTAKE_FAN_RPM_INDEX, intake);
863         set_rpm_fan(CPUA_EXHAUST_FAN_RPM_INDEX, state0->rpm);
864         set_rpm_fan(CPUB_INTAKE_FAN_RPM_INDEX, intake);
865         set_rpm_fan(CPUB_EXHAUST_FAN_RPM_INDEX, state0->rpm);
866
867         if (fcu_fans[CPUA_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID)
868                 set_rpm_fan(CPUA_PUMP_RPM_INDEX, pump);
869         if (fcu_fans[CPUB_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID)
870                 set_rpm_fan(CPUB_PUMP_RPM_INDEX, pump);
871 }
872
873 static void do_monitor_cpu_split(struct cpu_pid_state *state)
874 {
875         s32 temp, power;
876         int rc, intake;
877
878         /* Read current fan status */
879         rc = do_read_one_cpu_values(state, &temp, &power);
880         if (rc < 0) {
881                 /* XXX What do we do now ? */
882         }
883
884         /* Check tmax, increment overtemp if we are there. At tmax+8, we go
885          * full blown immediately and try to trigger a shutdown
886          */
887         if (temp >= ((state->mpu.tmax + 8) << 16)) {
888                 printk(KERN_WARNING "Warning ! CPU %d temperature way above maximum"
889                        " (%d) !\n",
890                        state->index, temp >> 16);
891                 state->overtemp = CPU_MAX_OVERTEMP;
892         } else if (temp > (state->mpu.tmax << 16))
893                 state->overtemp++;
894         else
895                 state->overtemp = 0;
896         if (state->overtemp >= CPU_MAX_OVERTEMP)
897                 critical_state = 1;
898         if (state->overtemp > 0) {
899                 state->rpm = state->mpu.rmaxn_exhaust_fan;
900                 state->intake_rpm = intake = state->mpu.rmaxn_intake_fan;
901                 goto do_set_fans;
902         }
903
904         /* Do the PID */
905         do_cpu_pid(state, temp, power);
906
907         intake = (state->rpm * CPU_INTAKE_SCALE) >> 16;
908         if (intake < (int)state->mpu.rminn_intake_fan)
909                 intake = state->mpu.rminn_intake_fan;
910         if (intake > (int)state->mpu.rmaxn_intake_fan)
911                 intake = state->mpu.rmaxn_intake_fan;
912         state->intake_rpm = intake;
913
914  do_set_fans:
915         DBG("** CPU %d RPM: %d Ex, %d In, overtemp: %d\n",
916             state->index, (int)state->rpm, intake, state->overtemp);
917
918         /* We should check for errors, shouldn't we ? But then, what
919          * do we do once the error occurs ? For FCU notified fan
920          * failures (-EFAULT) we probably want to notify userland
921          * some way...
922          */
923         if (state->index == 0) {
924                 set_rpm_fan(CPUA_INTAKE_FAN_RPM_INDEX, intake);
925                 set_rpm_fan(CPUA_EXHAUST_FAN_RPM_INDEX, state->rpm);
926         } else {
927                 set_rpm_fan(CPUB_INTAKE_FAN_RPM_INDEX, intake);
928                 set_rpm_fan(CPUB_EXHAUST_FAN_RPM_INDEX, state->rpm);
929         }
930 }
931
932 /*
933  * Initialize the state structure for one CPU control loop
934  */
935 static int init_cpu_state(struct cpu_pid_state *state, int index)
936 {
937         state->index = index;
938         state->first = 1;
939         state->rpm = 1000;
940         state->overtemp = 0;
941         state->adc_config = 0x00;
942
943
944         if (index == 0)
945                 state->monitor = attach_i2c_chip(SUPPLY_MONITOR_ID, "CPU0_monitor");
946         else if (index == 1)
947                 state->monitor = attach_i2c_chip(SUPPLY_MONITORB_ID, "CPU1_monitor");
948         if (state->monitor == NULL)
949                 goto fail;
950
951         if (read_eeprom(index, &state->mpu))
952                 goto fail;
953
954         state->count_power = state->mpu.tguardband;
955         if (state->count_power > CPU_POWER_HISTORY_SIZE) {
956                 printk(KERN_WARNING "Warning ! too many power history slots\n");
957                 state->count_power = CPU_POWER_HISTORY_SIZE;
958         }
959         DBG("CPU %d Using %d power history entries\n", index, state->count_power);
960
961         if (index == 0) {
962                 device_create_file(&of_dev->dev, &dev_attr_cpu0_temperature);
963                 device_create_file(&of_dev->dev, &dev_attr_cpu0_voltage);
964                 device_create_file(&of_dev->dev, &dev_attr_cpu0_current);
965                 device_create_file(&of_dev->dev, &dev_attr_cpu0_exhaust_fan_rpm);
966                 device_create_file(&of_dev->dev, &dev_attr_cpu0_intake_fan_rpm);
967         } else {
968                 device_create_file(&of_dev->dev, &dev_attr_cpu1_temperature);
969                 device_create_file(&of_dev->dev, &dev_attr_cpu1_voltage);
970                 device_create_file(&of_dev->dev, &dev_attr_cpu1_current);
971                 device_create_file(&of_dev->dev, &dev_attr_cpu1_exhaust_fan_rpm);
972                 device_create_file(&of_dev->dev, &dev_attr_cpu1_intake_fan_rpm);
973         }
974
975         return 0;
976  fail:
977         if (state->monitor)
978                 detach_i2c_chip(state->monitor);
979         state->monitor = NULL;
980         
981         return -ENODEV;
982 }
983
984 /*
985  * Dispose of the state data for one CPU control loop
986  */
987 static void dispose_cpu_state(struct cpu_pid_state *state)
988 {
989         if (state->monitor == NULL)
990                 return;
991
992         if (state->index == 0) {
993                 device_remove_file(&of_dev->dev, &dev_attr_cpu0_temperature);
994                 device_remove_file(&of_dev->dev, &dev_attr_cpu0_voltage);
995                 device_remove_file(&of_dev->dev, &dev_attr_cpu0_current);
996                 device_remove_file(&of_dev->dev, &dev_attr_cpu0_exhaust_fan_rpm);
997                 device_remove_file(&of_dev->dev, &dev_attr_cpu0_intake_fan_rpm);
998         } else {
999                 device_remove_file(&of_dev->dev, &dev_attr_cpu1_temperature);
1000                 device_remove_file(&of_dev->dev, &dev_attr_cpu1_voltage);
1001                 device_remove_file(&of_dev->dev, &dev_attr_cpu1_current);
1002                 device_remove_file(&of_dev->dev, &dev_attr_cpu1_exhaust_fan_rpm);
1003                 device_remove_file(&of_dev->dev, &dev_attr_cpu1_intake_fan_rpm);
1004         }
1005
1006         detach_i2c_chip(state->monitor);
1007         state->monitor = NULL;
1008 }
1009
1010 /*
1011  * Motherboard backside & U3 heatsink fan control loop
1012  */
1013 static void do_monitor_backside(struct backside_pid_state *state)
1014 {
1015         s32 temp, integral, derivative;
1016         s64 integ_p, deriv_p, prop_p, sum; 
1017         int i, rc;
1018
1019         if (--state->ticks != 0)
1020                 return;
1021         state->ticks = BACKSIDE_PID_INTERVAL;
1022
1023         DBG("backside:\n");
1024
1025         /* Check fan status */
1026         rc = get_pwm_fan(BACKSIDE_FAN_PWM_INDEX);
1027         if (rc < 0) {
1028                 printk(KERN_WARNING "Error %d reading backside fan !\n", rc);
1029                 /* XXX What do we do now ? */
1030         } else
1031                 state->pwm = rc;
1032         DBG("  current pwm: %d\n", state->pwm);
1033
1034         /* Get some sensor readings */
1035         temp = i2c_smbus_read_byte_data(state->monitor, MAX6690_EXT_TEMP) << 16;
1036         state->last_temp = temp;
1037         DBG("  temp: %d.%03d, target: %d.%03d\n", FIX32TOPRINT(temp),
1038             FIX32TOPRINT(backside_params.input_target));
1039
1040         /* Store temperature and error in history array */
1041         state->cur_sample = (state->cur_sample + 1) % BACKSIDE_PID_HISTORY_SIZE;
1042         state->sample_history[state->cur_sample] = temp;
1043         state->error_history[state->cur_sample] = temp - backside_params.input_target;
1044         
1045         /* If first loop, fill the history table */
1046         if (state->first) {
1047                 for (i = 0; i < (BACKSIDE_PID_HISTORY_SIZE - 1); i++) {
1048                         state->cur_sample = (state->cur_sample + 1) %
1049                                 BACKSIDE_PID_HISTORY_SIZE;
1050                         state->sample_history[state->cur_sample] = temp;
1051                         state->error_history[state->cur_sample] =
1052                                 temp - backside_params.input_target;
1053                 }
1054                 state->first = 0;
1055         }
1056
1057         /* Calculate the integral term */
1058         sum = 0;
1059         integral = 0;
1060         for (i = 0; i < BACKSIDE_PID_HISTORY_SIZE; i++)
1061                 integral += state->error_history[i];
1062         integral *= BACKSIDE_PID_INTERVAL;
1063         DBG("  integral: %08x\n", integral);
1064         integ_p = ((s64)backside_params.G_r) * (s64)integral;
1065         DBG("   integ_p: %d\n", (int)(integ_p >> 36));
1066         sum += integ_p;
1067
1068         /* Calculate the derivative term */
1069         derivative = state->error_history[state->cur_sample] -
1070                 state->error_history[(state->cur_sample + BACKSIDE_PID_HISTORY_SIZE - 1)
1071                                     % BACKSIDE_PID_HISTORY_SIZE];
1072         derivative /= BACKSIDE_PID_INTERVAL;
1073         deriv_p = ((s64)backside_params.G_d) * (s64)derivative;
1074         DBG("   deriv_p: %d\n", (int)(deriv_p >> 36));
1075         sum += deriv_p;
1076
1077         /* Calculate the proportional term */
1078         prop_p = ((s64)backside_params.G_p) * (s64)(state->error_history[state->cur_sample]);
1079         DBG("   prop_p: %d\n", (int)(prop_p >> 36));
1080         sum += prop_p;
1081
1082         /* Scale sum */
1083         sum >>= 36;
1084
1085         DBG("   sum: %d\n", (int)sum);
1086         state->pwm += (s32)sum;
1087         if (state->pwm < backside_params.output_min)
1088                 state->pwm = backside_params.output_min;
1089         if (state->pwm > backside_params.output_max)
1090                 state->pwm = backside_params.output_max;
1091
1092         DBG("** BACKSIDE PWM: %d\n", (int)state->pwm);
1093         set_pwm_fan(BACKSIDE_FAN_PWM_INDEX, state->pwm);
1094 }
1095
1096 /*
1097  * Initialize the state structure for the backside fan control loop
1098  */
1099 static int init_backside_state(struct backside_pid_state *state)
1100 {
1101         struct device_node *u3;
1102         int u3h = 1; /* conservative by default */
1103
1104         /*
1105          * There are different PID params for machines with U3 and machines
1106          * with U3H, pick the right ones now
1107          */
1108         u3 = of_find_node_by_path("/u3@0,f8000000");
1109         if (u3 != NULL) {
1110                 u32 *vers = (u32 *)get_property(u3, "device-rev", NULL);
1111                 if (vers)
1112                         if (((*vers) & 0x3f) < 0x34)
1113                                 u3h = 0;
1114                 of_node_put(u3);
1115         }
1116
1117         backside_params.G_p = BACKSIDE_PID_G_p;
1118         backside_params.G_r = BACKSIDE_PID_G_r;
1119         backside_params.output_max = BACKSIDE_PID_OUTPUT_MAX;
1120         if (u3h) {
1121                 backside_params.G_d = BACKSIDE_PID_U3H_G_d;
1122                 backside_params.input_target = BACKSIDE_PID_U3H_INPUT_TARGET;
1123                 backside_params.output_min = BACKSIDE_PID_U3H_OUTPUT_MIN;
1124         } else {
1125                 backside_params.G_d = BACKSIDE_PID_U3_G_d;
1126                 backside_params.input_target = BACKSIDE_PID_U3_INPUT_TARGET;
1127                 backside_params.output_min = BACKSIDE_PID_U3_OUTPUT_MIN;
1128         }
1129
1130         state->ticks = 1;
1131         state->first = 1;
1132         state->pwm = 50;
1133
1134         state->monitor = attach_i2c_chip(BACKSIDE_MAX_ID, "backside_temp");
1135         if (state->monitor == NULL)
1136                 return -ENODEV;
1137
1138         device_create_file(&of_dev->dev, &dev_attr_backside_temperature);
1139         device_create_file(&of_dev->dev, &dev_attr_backside_fan_pwm);
1140
1141         return 0;
1142 }
1143
1144 /*
1145  * Dispose of the state data for the backside control loop
1146  */
1147 static void dispose_backside_state(struct backside_pid_state *state)
1148 {
1149         if (state->monitor == NULL)
1150                 return;
1151
1152         device_remove_file(&of_dev->dev, &dev_attr_backside_temperature);
1153         device_remove_file(&of_dev->dev, &dev_attr_backside_fan_pwm);
1154
1155         detach_i2c_chip(state->monitor);
1156         state->monitor = NULL;
1157 }
1158  
1159 /*
1160  * Drives bay fan control loop
1161  */
1162 static void do_monitor_drives(struct drives_pid_state *state)
1163 {
1164         s32 temp, integral, derivative;
1165         s64 integ_p, deriv_p, prop_p, sum; 
1166         int i, rc;
1167
1168         if (--state->ticks != 0)
1169                 return;
1170         state->ticks = DRIVES_PID_INTERVAL;
1171
1172         DBG("drives:\n");
1173
1174         /* Check fan status */
1175         rc = get_rpm_fan(DRIVES_FAN_RPM_INDEX, !RPM_PID_USE_ACTUAL_SPEED);
1176         if (rc < 0) {
1177                 printk(KERN_WARNING "Error %d reading drives fan !\n", rc);
1178                 /* XXX What do we do now ? */
1179         } else
1180                 state->rpm = rc;
1181         DBG("  current rpm: %d\n", state->rpm);
1182
1183         /* Get some sensor readings */
1184         temp = le16_to_cpu(i2c_smbus_read_word_data(state->monitor, DS1775_TEMP)) << 8;
1185         state->last_temp = temp;
1186         DBG("  temp: %d.%03d, target: %d.%03d\n", FIX32TOPRINT(temp),
1187             FIX32TOPRINT(DRIVES_PID_INPUT_TARGET));
1188
1189         /* Store temperature and error in history array */
1190         state->cur_sample = (state->cur_sample + 1) % DRIVES_PID_HISTORY_SIZE;
1191         state->sample_history[state->cur_sample] = temp;
1192         state->error_history[state->cur_sample] = temp - DRIVES_PID_INPUT_TARGET;
1193         
1194         /* If first loop, fill the history table */
1195         if (state->first) {
1196                 for (i = 0; i < (DRIVES_PID_HISTORY_SIZE - 1); i++) {
1197                         state->cur_sample = (state->cur_sample + 1) %
1198                                 DRIVES_PID_HISTORY_SIZE;
1199                         state->sample_history[state->cur_sample] = temp;
1200                         state->error_history[state->cur_sample] =
1201                                 temp - DRIVES_PID_INPUT_TARGET;
1202                 }
1203                 state->first = 0;
1204         }
1205
1206         /* Calculate the integral term */
1207         sum = 0;
1208         integral = 0;
1209         for (i = 0; i < DRIVES_PID_HISTORY_SIZE; i++)
1210                 integral += state->error_history[i];
1211         integral *= DRIVES_PID_INTERVAL;
1212         DBG("  integral: %08x\n", integral);
1213         integ_p = ((s64)DRIVES_PID_G_r) * (s64)integral;
1214         DBG("   integ_p: %d\n", (int)(integ_p >> 36));
1215         sum += integ_p;
1216
1217         /* Calculate the derivative term */
1218         derivative = state->error_history[state->cur_sample] -
1219                 state->error_history[(state->cur_sample + DRIVES_PID_HISTORY_SIZE - 1)
1220                                     % DRIVES_PID_HISTORY_SIZE];
1221         derivative /= DRIVES_PID_INTERVAL;
1222         deriv_p = ((s64)DRIVES_PID_G_d) * (s64)derivative;
1223         DBG("   deriv_p: %d\n", (int)(deriv_p >> 36));
1224         sum += deriv_p;
1225
1226         /* Calculate the proportional term */
1227         prop_p = ((s64)DRIVES_PID_G_p) * (s64)(state->error_history[state->cur_sample]);
1228         DBG("   prop_p: %d\n", (int)(prop_p >> 36));
1229         sum += prop_p;
1230
1231         /* Scale sum */
1232         sum >>= 36;
1233
1234         DBG("   sum: %d\n", (int)sum);
1235         state->rpm += (s32)sum;
1236         if (state->rpm < DRIVES_PID_OUTPUT_MIN)
1237                 state->rpm = DRIVES_PID_OUTPUT_MIN;
1238         if (state->rpm > DRIVES_PID_OUTPUT_MAX)
1239                 state->rpm = DRIVES_PID_OUTPUT_MAX;
1240
1241         DBG("** DRIVES RPM: %d\n", (int)state->rpm);
1242         set_rpm_fan(DRIVES_FAN_RPM_INDEX, state->rpm);
1243 }
1244
1245 /*
1246  * Initialize the state structure for the drives bay fan control loop
1247  */
1248 static int init_drives_state(struct drives_pid_state *state)
1249 {
1250         state->ticks = 1;
1251         state->first = 1;
1252         state->rpm = 1000;
1253
1254         state->monitor = attach_i2c_chip(DRIVES_DALLAS_ID, "drives_temp");
1255         if (state->monitor == NULL)
1256                 return -ENODEV;
1257
1258         device_create_file(&of_dev->dev, &dev_attr_drives_temperature);
1259         device_create_file(&of_dev->dev, &dev_attr_drives_fan_rpm);
1260
1261         return 0;
1262 }
1263
1264 /*
1265  * Dispose of the state data for the drives control loop
1266  */
1267 static void dispose_drives_state(struct drives_pid_state *state)
1268 {
1269         if (state->monitor == NULL)
1270                 return;
1271
1272         device_remove_file(&of_dev->dev, &dev_attr_drives_temperature);
1273         device_remove_file(&of_dev->dev, &dev_attr_drives_fan_rpm);
1274
1275         detach_i2c_chip(state->monitor);
1276         state->monitor = NULL;
1277 }
1278
1279 static int call_critical_overtemp(void)
1280 {
1281         char *argv[] = { critical_overtemp_path, NULL };
1282         static char *envp[] = { "HOME=/",
1283                                 "TERM=linux",
1284                                 "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
1285                                 NULL };
1286
1287         return call_usermodehelper(critical_overtemp_path, argv, envp, 0);
1288 }
1289
1290
1291 /*
1292  * Here's the kernel thread that calls the various control loops
1293  */
1294 static int main_control_loop(void *x)
1295 {
1296         daemonize("kfand");
1297
1298         DBG("main_control_loop started\n");
1299
1300         down(&driver_lock);
1301
1302         if (start_fcu() < 0) {
1303                 printk(KERN_ERR "kfand: failed to start FCU\n");
1304                 up(&driver_lock);
1305                 goto out;
1306         }
1307
1308         /* Set the PCI fan once for now */
1309         set_pwm_fan(SLOTS_FAN_PWM_INDEX, SLOTS_FAN_DEFAULT_PWM);
1310
1311         /* Initialize ADCs */
1312         initialize_adc(&cpu_state[0]);
1313         if (cpu_state[1].monitor != NULL)
1314                 initialize_adc(&cpu_state[1]);
1315
1316         up(&driver_lock);
1317
1318         while (state == state_attached) {
1319                 unsigned long elapsed, start;
1320
1321                 start = jiffies;
1322
1323                 down(&driver_lock);
1324                 if (cpu_pid_type == CPU_PID_TYPE_COMBINED)
1325                         do_monitor_cpu_combined();
1326                 else {
1327                         do_monitor_cpu_split(&cpu_state[0]);
1328                         if (cpu_state[1].monitor != NULL)
1329                                 do_monitor_cpu_split(&cpu_state[1]);
1330                 }
1331                 do_monitor_backside(&backside_state);
1332                 do_monitor_drives(&drives_state);
1333                 up(&driver_lock);
1334
1335                 if (critical_state == 1) {
1336                         printk(KERN_WARNING "Temperature control detected a critical condition\n");
1337                         printk(KERN_WARNING "Attempting to shut down...\n");
1338                         if (call_critical_overtemp()) {
1339                                 printk(KERN_WARNING "Can't call %s, power off now!\n",
1340                                        critical_overtemp_path);
1341                                 machine_power_off();
1342                         }
1343                 }
1344                 if (critical_state > 0)
1345                         critical_state++;
1346                 if (critical_state > MAX_CRITICAL_STATE) {
1347                         printk(KERN_WARNING "Shutdown timed out, power off now !\n");
1348                         machine_power_off();
1349                 }
1350
1351                 // FIXME: Deal with signals
1352                 set_current_state(TASK_INTERRUPTIBLE);
1353                 elapsed = jiffies - start;
1354                 if (elapsed < HZ)
1355                         schedule_timeout(HZ - elapsed);
1356         }
1357
1358  out:
1359         DBG("main_control_loop ended\n");
1360
1361         ctrl_task = 0;
1362         complete_and_exit(&ctrl_complete, 0);
1363 }
1364
1365 /*
1366  * Dispose the control loops when tearing down
1367  */
1368 static void dispose_control_loops(void)
1369 {
1370         dispose_cpu_state(&cpu_state[0]);
1371         dispose_cpu_state(&cpu_state[1]);
1372
1373         dispose_backside_state(&backside_state);
1374         dispose_drives_state(&drives_state);
1375 }
1376
1377 /*
1378  * Create the control loops. U3-0 i2c bus is up, so we can now
1379  * get to the various sensors
1380  */
1381 static int create_control_loops(void)
1382 {
1383         struct device_node *np;
1384
1385         /* Count CPUs from the device-tree, we don't care how many are
1386          * actually used by Linux
1387          */
1388         cpu_count = 0;
1389         for (np = NULL; NULL != (np = of_find_node_by_type(np, "cpu"));)
1390                 cpu_count++;
1391
1392         DBG("counted %d CPUs in the device-tree\n", cpu_count);
1393
1394         /* Decide the type of PID algorithm to use based on the presence of
1395          * the pumps, though that may not be the best way, that is good enough
1396          * for now
1397          */
1398         if (machine_is_compatible("PowerMac7,3")
1399             && (cpu_count > 1)
1400             && fcu_fans[CPUA_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID
1401             && fcu_fans[CPUB_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID) {
1402                 printk(KERN_INFO "Liquid cooling pumps detected, using new algorithm !\n");
1403                 cpu_pid_type = CPU_PID_TYPE_COMBINED;
1404         } else
1405                 cpu_pid_type = CPU_PID_TYPE_SPLIT;
1406
1407         /* Create control loops for everything. If any fail, everything
1408          * fails
1409          */
1410         if (init_cpu_state(&cpu_state[0], 0))
1411                 goto fail;
1412         if (cpu_count > 1 && init_cpu_state(&cpu_state[1], 1))
1413                 goto fail;
1414         if (init_backside_state(&backside_state))
1415                 goto fail;
1416         if (init_drives_state(&drives_state))
1417                 goto fail;
1418
1419         DBG("all control loops up !\n");
1420
1421         return 0;
1422         
1423  fail:
1424         DBG("failure creating control loops, disposing\n");
1425
1426         dispose_control_loops();
1427
1428         return -ENODEV;
1429 }
1430
1431 /*
1432  * Start the control loops after everything is up, that is create
1433  * the thread that will make them run
1434  */
1435 static void start_control_loops(void)
1436 {
1437         init_completion(&ctrl_complete);
1438
1439         ctrl_task = kernel_thread(main_control_loop, NULL, SIGCHLD | CLONE_KERNEL);
1440 }
1441
1442 /*
1443  * Stop the control loops when tearing down
1444  */
1445 static void stop_control_loops(void)
1446 {
1447         if (ctrl_task != 0)
1448                 wait_for_completion(&ctrl_complete);
1449 }
1450
1451 /*
1452  * Attach to the i2c FCU after detecting U3-1 bus
1453  */
1454 static int attach_fcu(void)
1455 {
1456         fcu = attach_i2c_chip(FAN_CTRLER_ID, "fcu");
1457         if (fcu == NULL)
1458                 return -ENODEV;
1459
1460         DBG("FCU attached\n");
1461
1462         return 0;
1463 }
1464
1465 /*
1466  * Detach from the i2c FCU when tearing down
1467  */
1468 static void detach_fcu(void)
1469 {
1470         if (fcu)
1471                 detach_i2c_chip(fcu);
1472         fcu = NULL;
1473 }
1474
1475 /*
1476  * Attach to the i2c controller. We probe the various chips based
1477  * on the device-tree nodes and build everything for the driver to
1478  * run, we then kick the driver monitoring thread
1479  */
1480 static int therm_pm72_attach(struct i2c_adapter *adapter)
1481 {
1482         down(&driver_lock);
1483
1484         /* Check state */
1485         if (state == state_detached)
1486                 state = state_attaching;
1487         if (state != state_attaching) {
1488                 up(&driver_lock);
1489                 return 0;
1490         }
1491
1492         /* Check if we are looking for one of these */
1493         if (u3_0 == NULL && !strcmp(adapter->name, "u3 0")) {
1494                 u3_0 = adapter;
1495                 DBG("found U3-0, creating control loops\n");
1496                 if (create_control_loops())
1497                         u3_0 = NULL;
1498         } else if (u3_1 == NULL && !strcmp(adapter->name, "u3 1")) {
1499                 u3_1 = adapter;
1500                 DBG("found U3-1, attaching FCU\n");
1501                 if (attach_fcu())
1502                         u3_1 = NULL;
1503         }
1504         /* We got all we need, start control loops */
1505         if (u3_0 != NULL && u3_1 != NULL) {
1506                 DBG("everything up, starting control loops\n");
1507                 state = state_attached;
1508                 start_control_loops();
1509         }
1510         up(&driver_lock);
1511
1512         return 0;
1513 }
1514
1515 /*
1516  * Called on every adapter when the driver or the i2c controller
1517  * is going away.
1518  */
1519 static int therm_pm72_detach(struct i2c_adapter *adapter)
1520 {
1521         down(&driver_lock);
1522
1523         if (state != state_detached)
1524                 state = state_detaching;
1525
1526         /* Stop control loops if any */
1527         DBG("stopping control loops\n");
1528         up(&driver_lock);
1529         stop_control_loops();
1530         down(&driver_lock);
1531
1532         if (u3_0 != NULL && !strcmp(adapter->name, "u3 0")) {
1533                 DBG("lost U3-0, disposing control loops\n");
1534                 dispose_control_loops();
1535                 u3_0 = NULL;
1536         }
1537         
1538         if (u3_1 != NULL && !strcmp(adapter->name, "u3 1")) {
1539                 DBG("lost U3-1, detaching FCU\n");
1540                 detach_fcu();
1541                 u3_1 = NULL;
1542         }
1543         if (u3_0 == NULL && u3_1 == NULL)
1544                 state = state_detached;
1545
1546         up(&driver_lock);
1547
1548         return 0;
1549 }
1550
1551 static void fcu_lookup_fans(struct device_node *fcu_node)
1552 {
1553         struct device_node *np = NULL;
1554         int i;
1555
1556         /* The table is filled by default with values that are suitable
1557          * for the old machines without device-tree informations. We scan
1558          * the device-tree and override those values with whatever is
1559          * there
1560          */
1561
1562         DBG("Looking up FCU controls in device-tree...\n");
1563
1564         while ((np = of_get_next_child(fcu_node, np)) != NULL) {
1565                 int type = -1;
1566                 char *loc;
1567                 u32 *reg;
1568
1569                 DBG(" control: %s, type: %s\n", np->name, np->type);
1570
1571                 /* Detect control type */
1572                 if (!strcmp(np->type, "fan-rpm-control") ||
1573                     !strcmp(np->type, "fan-rpm"))
1574                         type = FCU_FAN_RPM;
1575                 if (!strcmp(np->type, "fan-pwm-control") ||
1576                     !strcmp(np->type, "fan-pwm"))
1577                         type = FCU_FAN_PWM;
1578                 /* Only care about fans for now */
1579                 if (type == -1)
1580                         continue;
1581
1582                 /* Lookup for a matching location */
1583                 loc = (char *)get_property(np, "location", NULL);
1584                 reg = (u32 *)get_property(np, "reg", NULL);
1585                 if (loc == NULL || reg == NULL)
1586                         continue;
1587                 DBG(" matching location: %s, reg: 0x%08x\n", loc, *reg);
1588
1589                 for (i = 0; i < FCU_FAN_COUNT; i++) {
1590                         int fan_id;
1591
1592                         if (strcmp(loc, fcu_fans[i].loc))
1593                                 continue;
1594                         DBG(" location match, index: %d\n", i);
1595                         fcu_fans[i].id = FCU_FAN_ABSENT_ID;
1596                         if (type != fcu_fans[i].type) {
1597                                 printk(KERN_WARNING "therm_pm72: Fan type mismatch "
1598                                        "in device-tree for %s\n", np->full_name);
1599                                 break;
1600                         }
1601                         if (type == FCU_FAN_RPM)
1602                                 fan_id = ((*reg) - 0x10) / 2;
1603                         else
1604                                 fan_id = ((*reg) - 0x30) / 2;
1605                         if (fan_id > 7) {
1606                                 printk(KERN_WARNING "therm_pm72: Can't parse "
1607                                        "fan ID in device-tree for %s\n", np->full_name);
1608                                 break;
1609                         }
1610                         DBG(" fan id -> %d, type -> %d\n", fan_id, type);
1611                         fcu_fans[i].id = fan_id;
1612                 }
1613         }
1614
1615         /* Now dump the array */
1616         printk(KERN_INFO "Detected fan controls:\n");
1617         for (i = 0; i < FCU_FAN_COUNT; i++) {
1618                 if (fcu_fans[i].id == FCU_FAN_ABSENT_ID)
1619                         continue;
1620                 printk(KERN_INFO "  %d: %s fan, id %d, location: %s\n", i,
1621                        fcu_fans[i].type == FCU_FAN_RPM ? "RPM" : "PWM",
1622                        fcu_fans[i].id, fcu_fans[i].loc);
1623         }
1624 }
1625
1626 static int fcu_of_probe(struct of_device* dev, const struct of_match *match)
1627 {
1628         int rc;
1629
1630         state = state_detached;
1631
1632         /* Lookup the fans in the device tree */
1633         fcu_lookup_fans(dev->node);
1634
1635         /* Add the driver */
1636         rc = i2c_add_driver(&therm_pm72_driver);
1637         if (rc < 0)
1638                 return rc;
1639         return 0;
1640 }
1641
1642 static int fcu_of_remove(struct of_device* dev)
1643 {
1644         i2c_del_driver(&therm_pm72_driver);
1645
1646         return 0;
1647 }
1648
1649 static struct of_match fcu_of_match[] = 
1650 {
1651         {
1652         .name           = OF_ANY_MATCH,
1653         .type           = "fcu",
1654         .compatible     = OF_ANY_MATCH
1655         },
1656         {},
1657 };
1658
1659 static struct of_platform_driver fcu_of_platform_driver = 
1660 {
1661         .name           = "temperature",
1662         .match_table    = fcu_of_match,
1663         .probe          = fcu_of_probe,
1664         .remove         = fcu_of_remove
1665 };
1666
1667 /*
1668  * Check machine type, attach to i2c controller
1669  */
1670 static int __init therm_pm72_init(void)
1671 {
1672         struct device_node *np;
1673
1674         if (!machine_is_compatible("PowerMac7,2") &&
1675             !machine_is_compatible("PowerMac7,3"))
1676                 return -ENODEV;
1677
1678         printk(KERN_INFO "PowerMac G5 Thermal control driver %s\n", VERSION);
1679
1680         np = of_find_node_by_type(NULL, "fcu");
1681         if (np == NULL) {
1682                 /* Some machines have strangely broken device-tree */
1683                 np = of_find_node_by_path("/u3@0,f8000000/i2c@f8001000/fan@15e");
1684                 if (np == NULL) {
1685                             printk(KERN_ERR "Can't find FCU in device-tree !\n");
1686                             return -ENODEV;
1687                 }
1688         }
1689         of_dev = of_platform_device_create(np, "temperature");
1690         if (of_dev == NULL) {
1691                 printk(KERN_ERR "Can't register FCU platform device !\n");
1692                 return -ENODEV;
1693         }
1694
1695         of_register_driver(&fcu_of_platform_driver);
1696         
1697         return 0;
1698 }
1699
1700 static void __exit therm_pm72_exit(void)
1701 {
1702         of_unregister_driver(&fcu_of_platform_driver);
1703
1704         if (of_dev)
1705                 of_device_unregister(of_dev);
1706 }
1707
1708 module_init(therm_pm72_init);
1709 module_exit(therm_pm72_exit);
1710
1711 MODULE_AUTHOR("Benjamin Herrenschmidt <benh@kernel.crashing.org>");
1712 MODULE_DESCRIPTION("Driver for Apple's PowerMac7,2 G5 thermal control");
1713 MODULE_LICENSE("GPL");
1714