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