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