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