1/*
2    abituguru.c Copyright (c) 2005-2006 Hans de Goede <j.w.r.degoede@hhs.nl>
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17*/
18/*
19    This driver supports the sensor part of the custom Abit uGuru chip found
20    on Abit uGuru motherboards. Note: because of lack of specs the CPU / RAM /
21    etc voltage & frequency control is not supported!
22*/
23#include <linux/module.h>
24#include <linux/sched.h>
25#include <linux/init.h>
26#include <linux/slab.h>
27#include <linux/jiffies.h>
28#include <linux/mutex.h>
29#include <linux/err.h>
30#include <linux/delay.h>
31#include <linux/platform_device.h>
32#include <linux/hwmon.h>
33#include <linux/hwmon-sysfs.h>
34#include <asm/io.h>
35
36/* Banks */
37#define ABIT_UGURU_ALARM_BANK			0x20 /* 1x 3 bytes */
38#define ABIT_UGURU_SENSOR_BANK1			0x21 /* 16x volt and temp */
39#define ABIT_UGURU_FAN_PWM			0x24 /* 3x 5 bytes */
40#define ABIT_UGURU_SENSOR_BANK2			0x26 /* fans */
41/* max nr of sensors in bank1, a bank1 sensor can be in, temp or nc */
42#define ABIT_UGURU_MAX_BANK1_SENSORS		16
43/* Warning if you increase one of the 2 MAX defines below to 10 or higher you
44   should adjust the belonging _NAMES_LENGTH macro for the 2 digit number! */
45/* max nr of sensors in bank2, currently mb's with max 6 fans are known */
46#define ABIT_UGURU_MAX_BANK2_SENSORS		6
47/* max nr of pwm outputs, currently mb's with max 5 pwm outputs are known */
48#define ABIT_UGURU_MAX_PWMS			5
49/* uGuru sensor bank 1 flags */			     /* Alarm if: */
50#define ABIT_UGURU_TEMP_HIGH_ALARM_ENABLE	0x01 /*  temp over warn */
51#define ABIT_UGURU_VOLT_HIGH_ALARM_ENABLE	0x02 /*  volt over max */
52#define ABIT_UGURU_VOLT_LOW_ALARM_ENABLE	0x04 /*  volt under min */
53#define ABIT_UGURU_TEMP_HIGH_ALARM_FLAG		0x10 /* temp is over warn */
54#define ABIT_UGURU_VOLT_HIGH_ALARM_FLAG		0x20 /* volt is over max */
55#define ABIT_UGURU_VOLT_LOW_ALARM_FLAG		0x40 /* volt is under min */
56/* uGuru sensor bank 2 flags */			     /* Alarm if: */
57#define ABIT_UGURU_FAN_LOW_ALARM_ENABLE		0x01 /*   fan under min */
58/* uGuru sensor bank common flags */
59#define ABIT_UGURU_BEEP_ENABLE			0x08 /* beep if alarm */
60#define ABIT_UGURU_SHUTDOWN_ENABLE		0x80 /* shutdown if alarm */
61/* uGuru fan PWM (speed control) flags */
62#define ABIT_UGURU_FAN_PWM_ENABLE		0x80 /* enable speed control */
63/* Values used for conversion */
64#define ABIT_UGURU_FAN_MAX			15300 /* RPM */
65/* Bank1 sensor types */
66#define ABIT_UGURU_IN_SENSOR			0
67#define ABIT_UGURU_TEMP_SENSOR			1
68#define ABIT_UGURU_NC				2
69/* In many cases we need to wait for the uGuru to reach a certain status, most
70   of the time it will reach this status within 30 - 90 ISA reads, and thus we
71   can best busy wait. This define gives the total amount of reads to try. */
72#define ABIT_UGURU_WAIT_TIMEOUT			125
73/* However sometimes older versions of the uGuru seem to be distracted and they
74   do not respond for a long time. To handle this we sleep before each of the
75   last ABIT_UGURU_WAIT_TIMEOUT_SLEEP tries. */
76#define ABIT_UGURU_WAIT_TIMEOUT_SLEEP		5
77/* Normally all expected status in abituguru_ready, are reported after the
78   first read, but sometimes not and we need to poll. */
79#define ABIT_UGURU_READY_TIMEOUT		5
80/* Maximum 3 retries on timedout reads/writes, delay 200 ms before retrying */
81#define ABIT_UGURU_MAX_RETRIES			3
82#define ABIT_UGURU_RETRY_DELAY			(HZ/5)
83/* Maximum 2 timeouts in abituguru_update_device, iow 3 in a row is an error */
84#define ABIT_UGURU_MAX_TIMEOUTS			2
85/* utility macros */
86#define ABIT_UGURU_NAME				"abituguru"
87#define ABIT_UGURU_DEBUG(level, format, arg...)				\
88	if (level <= verbose)						\
89		printk(KERN_DEBUG ABIT_UGURU_NAME ": "	format , ## arg)
90/* Macros to help calculate the sysfs_names array length */
91/* sum of strlen of: in??_input\0, in??_{min,max}\0, in??_{min,max}_alarm\0,
92   in??_{min,max}_alarm_enable\0, in??_beep\0, in??_shutdown\0 */
93#define ABITUGURU_IN_NAMES_LENGTH	(11 + 2 * 9 + 2 * 15 + 2 * 22 + 10 + 14)
94/* sum of strlen of: temp??_input\0, temp??_max\0, temp??_crit\0,
95   temp??_alarm\0, temp??_alarm_enable\0, temp??_beep\0, temp??_shutdown\0 */
96#define ABITUGURU_TEMP_NAMES_LENGTH	(13 + 11 + 12 + 13 + 20 + 12 + 16)
97/* sum of strlen of: fan?_input\0, fan?_min\0, fan?_alarm\0,
98   fan?_alarm_enable\0, fan?_beep\0, fan?_shutdown\0 */
99#define ABITUGURU_FAN_NAMES_LENGTH	(11 + 9 + 11 + 18 + 10 + 14)
100/* sum of strlen of: pwm?_enable\0, pwm?_auto_channels_temp\0,
101   pwm?_auto_point{1,2}_pwm\0, pwm?_auto_point{1,2}_temp\0 */
102#define ABITUGURU_PWM_NAMES_LENGTH	(12 + 24 + 2 * 21 + 2 * 22)
103/* IN_NAMES_LENGTH > TEMP_NAMES_LENGTH so assume all bank1 sensors are in */
104#define ABITUGURU_SYSFS_NAMES_LENGTH	( \
105	ABIT_UGURU_MAX_BANK1_SENSORS * ABITUGURU_IN_NAMES_LENGTH + \
106	ABIT_UGURU_MAX_BANK2_SENSORS * ABITUGURU_FAN_NAMES_LENGTH + \
107	ABIT_UGURU_MAX_PWMS * ABITUGURU_PWM_NAMES_LENGTH)
108
109/* All the macros below are named identical to the oguru and oguru2 programs
110   reverse engineered by Olle Sandberg, hence the names might not be 100%
111   logical. I could come up with better names, but I prefer keeping the names
112   identical so that this driver can be compared with his work more easily. */
113/* Two i/o-ports are used by uGuru */
114#define ABIT_UGURU_BASE				0x00E0
115/* Used to tell uGuru what to read and to read the actual data */
116#define ABIT_UGURU_CMD				0x00
117/* Mostly used to check if uGuru is busy */
118#define ABIT_UGURU_DATA				0x04
119#define ABIT_UGURU_REGION_LENGTH		5
120/* uGuru status' */
121#define ABIT_UGURU_STATUS_WRITE			0x00 /* Ready to be written */
122#define ABIT_UGURU_STATUS_READ			0x01 /* Ready to be read */
123#define ABIT_UGURU_STATUS_INPUT			0x08 /* More input */
124#define ABIT_UGURU_STATUS_READY			0x09 /* Ready to be written */
125
126/* Constants */
127/* in (Volt) sensors go up to 3494 mV, temp to 255000 millidegrees Celsius */
128static const int abituguru_bank1_max_value[2] = { 3494, 255000 };
129/* Min / Max allowed values for sensor2 (fan) alarm threshold, these values
130   correspond to 300-3000 RPM */
131static const u8 abituguru_bank2_min_threshold = 5;
132static const u8 abituguru_bank2_max_threshold = 50;
133/* Register 0 is a bitfield, 1 and 2 are pwm settings (255 = 100%), 3 and 4
134   are temperature trip points. */
135static const int abituguru_pwm_settings_multiplier[5] = { 0, 1, 1, 1000, 1000 };
136/* Min / Max allowed values for pwm_settings. Note: pwm1 (CPU fan) is a
137   special case the minium allowed pwm% setting for this is 30% (77) on
138   some MB's this special case is handled in the code! */
139static const u8 abituguru_pwm_min[5] = { 0, 170, 170, 25, 25 };
140static const u8 abituguru_pwm_max[5] = { 0, 255, 255, 75, 75 };
141
142
143/* Insmod parameters */
144static int force;
145module_param(force, bool, 0);
146MODULE_PARM_DESC(force, "Set to one to force detection.");
147static int bank1_types[ABIT_UGURU_MAX_BANK1_SENSORS] = { -1, -1, -1, -1, -1,
148	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
149module_param_array(bank1_types, int, NULL, 0);
150MODULE_PARM_DESC(bank1_types, "Bank1 sensortype autodetection override:\n"
151	"   -1 autodetect\n"
152	"    0 volt sensor\n"
153	"    1 temp sensor\n"
154	"    2 not connected");
155static int fan_sensors;
156module_param(fan_sensors, int, 0);
157MODULE_PARM_DESC(fan_sensors, "Number of fan sensors on the uGuru "
158	"(0 = autodetect)");
159static int pwms;
160module_param(pwms, int, 0);
161MODULE_PARM_DESC(pwms, "Number of PWMs on the uGuru "
162	"(0 = autodetect)");
163
164/* Default verbose is 2, since this driver is still in the testing phase */
165static int verbose = 2;
166module_param(verbose, int, 0644);
167MODULE_PARM_DESC(verbose, "How verbose should the driver be? (0-3):\n"
168	"   0 normal output\n"
169	"   1 + verbose error reporting\n"
170	"   2 + sensors type probing info\n"
171	"   3 + retryable error reporting");
172
173
174/* For the Abit uGuru, we need to keep some data in memory.
175   The structure is dynamically allocated, at the same time when a new
176   abituguru device is allocated. */
177struct abituguru_data {
178	struct class_device *class_dev; /* hwmon registered device */
179	struct mutex update_lock;	/* protect access to data and uGuru */
180	unsigned long last_updated;	/* In jiffies */
181	unsigned short addr;		/* uguru base address */
182	char uguru_ready;		/* is the uguru in ready state? */
183	unsigned char update_timeouts;	/* number of update timeouts since last
184					   successful update */
185
186	/* The sysfs attr and their names are generated automatically, for bank1
187	   we cannot use a predefined array because we don't know beforehand
188	   of a sensor is a volt or a temp sensor, for bank2 and the pwms its
189	   easier todo things the same way.  For in sensors we have 9 (temp 7)
190	   sysfs entries per sensor, for bank2 and pwms 6. */
191	struct sensor_device_attribute_2 sysfs_attr[
192		ABIT_UGURU_MAX_BANK1_SENSORS * 9 +
193		ABIT_UGURU_MAX_BANK2_SENSORS * 6 + ABIT_UGURU_MAX_PWMS * 6];
194	/* Buffer to store the dynamically generated sysfs names */
195	char sysfs_names[ABITUGURU_SYSFS_NAMES_LENGTH];
196
197	/* Bank 1 data */
198	/* number of and addresses of [0] in, [1] temp sensors */
199	u8 bank1_sensors[2];
200	u8 bank1_address[2][ABIT_UGURU_MAX_BANK1_SENSORS];
201	u8 bank1_value[ABIT_UGURU_MAX_BANK1_SENSORS];
202	/* This array holds 3 entries per sensor for the bank 1 sensor settings
203	   (flags, min, max for voltage / flags, warn, shutdown for temp). */
204	u8 bank1_settings[ABIT_UGURU_MAX_BANK1_SENSORS][3];
205	/* Maximum value for each sensor used for scaling in mV/millidegrees
206	   Celsius. */
207	int bank1_max_value[ABIT_UGURU_MAX_BANK1_SENSORS];
208
209	/* Bank 2 data, ABIT_UGURU_MAX_BANK2_SENSORS entries for bank2 */
210	u8 bank2_sensors; /* actual number of bank2 sensors found */
211	u8 bank2_value[ABIT_UGURU_MAX_BANK2_SENSORS];
212	u8 bank2_settings[ABIT_UGURU_MAX_BANK2_SENSORS][2]; /* flags, min */
213
214	/* Alarms 2 bytes for bank1, 1 byte for bank2 */
215	u8 alarms[3];
216
217	/* Fan PWM (speed control) 5 bytes per PWM */
218	u8 pwms; /* actual number of pwms found */
219	u8 pwm_settings[ABIT_UGURU_MAX_PWMS][5];
220};
221
222/* wait till the uguru is in the specified state */
223static int abituguru_wait(struct abituguru_data *data, u8 state)
224{
225	int timeout = ABIT_UGURU_WAIT_TIMEOUT;
226
227	while (inb_p(data->addr + ABIT_UGURU_DATA) != state) {
228		timeout--;
229		if (timeout == 0)
230			return -EBUSY;
231		/* sleep a bit before our last few tries, see the comment on
232		   this where ABIT_UGURU_WAIT_TIMEOUT_SLEEP is defined. */
233		if (timeout <= ABIT_UGURU_WAIT_TIMEOUT_SLEEP)
234			msleep(0);
235	}
236	return 0;
237}
238
239/* Put the uguru in ready for input state */
240static int abituguru_ready(struct abituguru_data *data)
241{
242	int timeout = ABIT_UGURU_READY_TIMEOUT;
243
244	if (data->uguru_ready)
245		return 0;
246
247	/* Reset? / Prepare for next read/write cycle */
248	outb(0x00, data->addr + ABIT_UGURU_DATA);
249
250	/* Wait till the uguru is ready */
251	if (abituguru_wait(data, ABIT_UGURU_STATUS_READY)) {
252		ABIT_UGURU_DEBUG(1,
253			"timeout exceeded waiting for ready state\n");
254		return -EIO;
255	}
256
257	/* Cmd port MUST be read now and should contain 0xAC */
258	while (inb_p(data->addr + ABIT_UGURU_CMD) != 0xAC) {
259		timeout--;
260		if (timeout == 0) {
261			ABIT_UGURU_DEBUG(1,
262			   "CMD reg does not hold 0xAC after ready command\n");
263			return -EIO;
264		}
265		msleep(0);
266	}
267
268	/* After this the ABIT_UGURU_DATA port should contain
269	   ABIT_UGURU_STATUS_INPUT */
270	timeout = ABIT_UGURU_READY_TIMEOUT;
271	while (inb_p(data->addr + ABIT_UGURU_DATA) != ABIT_UGURU_STATUS_INPUT) {
272		timeout--;
273		if (timeout == 0) {
274			ABIT_UGURU_DEBUG(1,
275				"state != more input after ready command\n");
276			return -EIO;
277		}
278		msleep(0);
279	}
280
281	data->uguru_ready = 1;
282	return 0;
283}
284
285/* Send the bank and then sensor address to the uGuru for the next read/write
286   cycle. This function gets called as the first part of a read/write by
287   abituguru_read and abituguru_write. This function should never be
288   called by any other function. */
289static int abituguru_send_address(struct abituguru_data *data,
290	u8 bank_addr, u8 sensor_addr, int retries)
291{
292	/* assume the caller does error handling itself if it has not requested
293	   any retries, and thus be quiet. */
294	int report_errors = retries;
295
296	for (;;) {
297		/* Make sure the uguru is ready and then send the bank address,
298		   after this the uguru is no longer "ready". */
299		if (abituguru_ready(data) != 0)
300			return -EIO;
301		outb(bank_addr, data->addr + ABIT_UGURU_DATA);
302		data->uguru_ready = 0;
303
304		/* Wait till the uguru is ABIT_UGURU_STATUS_INPUT state again
305		   and send the sensor addr */
306		if (abituguru_wait(data, ABIT_UGURU_STATUS_INPUT)) {
307			if (retries) {
308				ABIT_UGURU_DEBUG(3, "timeout exceeded "
309					"waiting for more input state, %d "
310					"tries remaining\n", retries);
311				set_current_state(TASK_UNINTERRUPTIBLE);
312				schedule_timeout(ABIT_UGURU_RETRY_DELAY);
313				retries--;
314				continue;
315			}
316			if (report_errors)
317				ABIT_UGURU_DEBUG(1, "timeout exceeded "
318					"waiting for more input state "
319					"(bank: %d)\n", (int)bank_addr);
320			return -EBUSY;
321		}
322		outb(sensor_addr, data->addr + ABIT_UGURU_CMD);
323		return 0;
324	}
325}
326
327/* Read count bytes from sensor sensor_addr in bank bank_addr and store the
328   result in buf, retry the send address part of the read retries times. */
329static int abituguru_read(struct abituguru_data *data,
330	u8 bank_addr, u8 sensor_addr, u8 *buf, int count, int retries)
331{
332	int i;
333
334	/* Send the address */
335	i = abituguru_send_address(data, bank_addr, sensor_addr, retries);
336	if (i)
337		return i;
338
339	/* And read the data */
340	for (i = 0; i < count; i++) {
341		if (abituguru_wait(data, ABIT_UGURU_STATUS_READ)) {
342			ABIT_UGURU_DEBUG(retries ? 1 : 3,
343				"timeout exceeded waiting for "
344				"read state (bank: %d, sensor: %d)\n",
345				(int)bank_addr, (int)sensor_addr);
346			break;
347		}
348		buf[i] = inb(data->addr + ABIT_UGURU_CMD);
349	}
350
351	/* Last put the chip back in ready state */
352	abituguru_ready(data);
353
354	return i;
355}
356
357/* Write count bytes from buf to sensor sensor_addr in bank bank_addr, the send
358   address part of the write is always retried ABIT_UGURU_MAX_RETRIES times. */
359static int abituguru_write(struct abituguru_data *data,
360	u8 bank_addr, u8 sensor_addr, u8 *buf, int count)
361{
362	/* We use the ready timeout as we have to wait for 0xAC just like the
363	   ready function */
364	int i, timeout = ABIT_UGURU_READY_TIMEOUT;
365
366	/* Send the address */
367	i = abituguru_send_address(data, bank_addr, sensor_addr,
368		ABIT_UGURU_MAX_RETRIES);
369	if (i)
370		return i;
371
372	/* And write the data */
373	for (i = 0; i < count; i++) {
374		if (abituguru_wait(data, ABIT_UGURU_STATUS_WRITE)) {
375			ABIT_UGURU_DEBUG(1, "timeout exceeded waiting for "
376				"write state (bank: %d, sensor: %d)\n",
377				(int)bank_addr, (int)sensor_addr);
378			break;
379		}
380		outb(buf[i], data->addr + ABIT_UGURU_CMD);
381	}
382
383	/* Now we need to wait till the chip is ready to be read again,
384	   so that we can read 0xAC as confirmation that our write has
385	   succeeded. */
386	if (abituguru_wait(data, ABIT_UGURU_STATUS_READ)) {
387		ABIT_UGURU_DEBUG(1, "timeout exceeded waiting for read state "
388			"after write (bank: %d, sensor: %d)\n", (int)bank_addr,
389			(int)sensor_addr);
390		return -EIO;
391	}
392
393	/* Cmd port MUST be read now and should contain 0xAC */
394	while (inb_p(data->addr + ABIT_UGURU_CMD) != 0xAC) {
395		timeout--;
396		if (timeout == 0) {
397			ABIT_UGURU_DEBUG(1, "CMD reg does not hold 0xAC after "
398				"write (bank: %d, sensor: %d)\n",
399				(int)bank_addr, (int)sensor_addr);
400			return -EIO;
401		}
402		msleep(0);
403	}
404
405	/* Last put the chip back in ready state */
406	abituguru_ready(data);
407
408	return i;
409}
410
411/* Detect sensor type. Temp and Volt sensors are enabled with
412   different masks and will ignore enable masks not meant for them.
413   This enables us to test what kind of sensor we're dealing with.
414   By setting the alarm thresholds so that we will always get an
415   alarm for sensor type X and then enabling the sensor as sensor type
416   X, if we then get an alarm it is a sensor of type X. */
417static int __devinit
418abituguru_detect_bank1_sensor_type(struct abituguru_data *data,
419				   u8 sensor_addr)
420{
421	u8 val, buf[3];
422	int i, ret = -ENODEV; /* error is the most common used retval :| */
423
424	/* If overriden by the user return the user selected type */
425	if (bank1_types[sensor_addr] >= ABIT_UGURU_IN_SENSOR &&
426			bank1_types[sensor_addr] <= ABIT_UGURU_NC) {
427		ABIT_UGURU_DEBUG(2, "assuming sensor type %d for bank1 sensor "
428			"%d because of \"bank1_types\" module param\n",
429			bank1_types[sensor_addr], (int)sensor_addr);
430		return bank1_types[sensor_addr];
431	}
432
433	/* First read the sensor and the current settings */
434	if (abituguru_read(data, ABIT_UGURU_SENSOR_BANK1, sensor_addr, &val,
435			1, ABIT_UGURU_MAX_RETRIES) != 1)
436		return -ENODEV;
437
438	/* Test val is sane / usable for sensor type detection. */
439	if ((val < 10u) || (val > 240u)) {
440		printk(KERN_WARNING ABIT_UGURU_NAME
441			": bank1-sensor: %d reading (%d) too close to limits, "
442			"unable to determine sensor type, skipping sensor\n",
443			(int)sensor_addr, (int)val);
444		/* assume no sensor is there for sensors for which we can't
445		   determine the sensor type because their reading is too close
446		   to their limits, this usually means no sensor is there. */
447		return ABIT_UGURU_NC;
448	}
449
450	ABIT_UGURU_DEBUG(2, "testing bank1 sensor %d\n", (int)sensor_addr);
451	/* Volt sensor test, enable volt low alarm, set min value ridicously
452	   high. If its a volt sensor this should always give us an alarm. */
453	buf[0] = ABIT_UGURU_VOLT_LOW_ALARM_ENABLE;
454	buf[1] = 245;
455	buf[2] = 250;
456	if (abituguru_write(data, ABIT_UGURU_SENSOR_BANK1 + 2, sensor_addr,
457			buf, 3) != 3)
458		goto abituguru_detect_bank1_sensor_type_exit;
459	/* Now we need 20 ms to give the uguru time to read the sensors
460	   and raise a voltage alarm */
461	set_current_state(TASK_UNINTERRUPTIBLE);
462	schedule_timeout(HZ/50);
463	/* Check for alarm and check the alarm is a volt low alarm. */
464	if (abituguru_read(data, ABIT_UGURU_ALARM_BANK, 0, buf, 3,
465			ABIT_UGURU_MAX_RETRIES) != 3)
466		goto abituguru_detect_bank1_sensor_type_exit;
467	if (buf[sensor_addr/8] & (0x01 << (sensor_addr % 8))) {
468		if (abituguru_read(data, ABIT_UGURU_SENSOR_BANK1 + 1,
469				sensor_addr, buf, 3,
470				ABIT_UGURU_MAX_RETRIES) != 3)
471			goto abituguru_detect_bank1_sensor_type_exit;
472		if (buf[0] & ABIT_UGURU_VOLT_LOW_ALARM_FLAG) {
473			ABIT_UGURU_DEBUG(2, "  found volt sensor\n");
474			ret = ABIT_UGURU_IN_SENSOR;
475			goto abituguru_detect_bank1_sensor_type_exit;
476		} else
477			ABIT_UGURU_DEBUG(2, "  alarm raised during volt "
478				"sensor test, but volt low flag not set\n");
479	} else
480		ABIT_UGURU_DEBUG(2, "  alarm not raised during volt sensor "
481			"test\n");
482
483	/* Temp sensor test, enable sensor as a temp sensor, set beep value
484	   ridicously low (but not too low, otherwise uguru ignores it).
485	   If its a temp sensor this should always give us an alarm. */
486	buf[0] = ABIT_UGURU_TEMP_HIGH_ALARM_ENABLE;
487	buf[1] = 5;
488	buf[2] = 10;
489	if (abituguru_write(data, ABIT_UGURU_SENSOR_BANK1 + 2, sensor_addr,
490			buf, 3) != 3)
491		goto abituguru_detect_bank1_sensor_type_exit;
492	/* Now we need 50 ms to give the uguru time to read the sensors
493	   and raise a temp alarm */
494	set_current_state(TASK_UNINTERRUPTIBLE);
495	schedule_timeout(HZ/20);
496	/* Check for alarm and check the alarm is a temp high alarm. */
497	if (abituguru_read(data, ABIT_UGURU_ALARM_BANK, 0, buf, 3,
498			ABIT_UGURU_MAX_RETRIES) != 3)
499		goto abituguru_detect_bank1_sensor_type_exit;
500	if (buf[sensor_addr/8] & (0x01 << (sensor_addr % 8))) {
501		if (abituguru_read(data, ABIT_UGURU_SENSOR_BANK1 + 1,
502				sensor_addr, buf, 3,
503				ABIT_UGURU_MAX_RETRIES) != 3)
504			goto abituguru_detect_bank1_sensor_type_exit;
505		if (buf[0] & ABIT_UGURU_TEMP_HIGH_ALARM_FLAG) {
506			ABIT_UGURU_DEBUG(2, "  found temp sensor\n");
507			ret = ABIT_UGURU_TEMP_SENSOR;
508			goto abituguru_detect_bank1_sensor_type_exit;
509		} else
510			ABIT_UGURU_DEBUG(2, "  alarm raised during temp "
511				"sensor test, but temp high flag not set\n");
512	} else
513		ABIT_UGURU_DEBUG(2, "  alarm not raised during temp sensor "
514			"test\n");
515
516	ret = ABIT_UGURU_NC;
517abituguru_detect_bank1_sensor_type_exit:
518	/* Restore original settings, failing here is really BAD, it has been
519	   reported that some BIOS-es hang when entering the uGuru menu with
520	   invalid settings present in the uGuru, so we try this 3 times. */
521	for (i = 0; i < 3; i++)
522		if (abituguru_write(data, ABIT_UGURU_SENSOR_BANK1 + 2,
523				sensor_addr, data->bank1_settings[sensor_addr],
524				3) == 3)
525			break;
526	if (i == 3) {
527		printk(KERN_ERR ABIT_UGURU_NAME
528			": Fatal error could not restore original settings. "
529			"This should never happen please report this to the "
530			"abituguru maintainer (see MAINTAINERS)\n");
531		return -ENODEV;
532	}
533	return ret;
534}
535
536/* These functions try to find out how many sensors there are in bank2 and how
537   many pwms there are. The purpose of this is to make sure that we don't give
538   the user the possibility to change settings for non-existent sensors / pwm.
539   The uGuru will happily read / write whatever memory happens to be after the
540   memory storing the PWM settings when reading/writing to a PWM which is not
541   there. Notice even if we detect a PWM which doesn't exist we normally won't
542   write to it, unless the user tries to change the settings.
543
544   Although the uGuru allows reading (settings) from non existing bank2
545   sensors, my version of the uGuru does seem to stop writing to them, the
546   write function above aborts in this case with:
547   "CMD reg does not hold 0xAC after write"
548
549   Notice these 2 tests are non destructive iow read-only tests, otherwise
550   they would defeat their purpose. Although for the bank2_sensors detection a
551   read/write test would be feasible because of the reaction above, I've
552   however opted to stay on the safe side. */
553static void __devinit
554abituguru_detect_no_bank2_sensors(struct abituguru_data *data)
555{
556	int i;
557
558	if (fan_sensors > 0 && fan_sensors <= ABIT_UGURU_MAX_BANK2_SENSORS) {
559		data->bank2_sensors = fan_sensors;
560		ABIT_UGURU_DEBUG(2, "assuming %d fan sensors because of "
561			"\"fan_sensors\" module param\n",
562			(int)data->bank2_sensors);
563		return;
564	}
565
566	ABIT_UGURU_DEBUG(2, "detecting number of fan sensors\n");
567	for (i = 0; i < ABIT_UGURU_MAX_BANK2_SENSORS; i++) {
568		/* 0x89 are the known used bits:
569		   -0x80 enable shutdown
570		   -0x08 enable beep
571		   -0x01 enable alarm
572		   All other bits should be 0, but on some motherboards
573		   0x40 (bit 6) is also high for some of the fans?? */
574		if (data->bank2_settings[i][0] & ~0xC9) {
575			ABIT_UGURU_DEBUG(2, "  bank2 sensor %d does not seem "
576				"to be a fan sensor: settings[0] = %02X\n",
577				i, (unsigned int)data->bank2_settings[i][0]);
578			break;
579		}
580
581		/* check if the threshold is within the allowed range */
582		if (data->bank2_settings[i][1] <
583				abituguru_bank2_min_threshold) {
584			ABIT_UGURU_DEBUG(2, "  bank2 sensor %d does not seem "
585				"to be a fan sensor: the threshold (%d) is "
586				"below the minimum (%d)\n", i,
587				(int)data->bank2_settings[i][1],
588				(int)abituguru_bank2_min_threshold);
589			break;
590		}
591		if (data->bank2_settings[i][1] >
592				abituguru_bank2_max_threshold) {
593			ABIT_UGURU_DEBUG(2, "  bank2 sensor %d does not seem "
594				"to be a fan sensor: the threshold (%d) is "
595				"above the maximum (%d)\n", i,
596				(int)data->bank2_settings[i][1],
597				(int)abituguru_bank2_max_threshold);
598			break;
599		}
600	}
601
602	data->bank2_sensors = i;
603	ABIT_UGURU_DEBUG(2, " found: %d fan sensors\n",
604		(int)data->bank2_sensors);
605}
606
607static void __devinit
608abituguru_detect_no_pwms(struct abituguru_data *data)
609{
610	int i, j;
611
612	if (pwms > 0 && pwms <= ABIT_UGURU_MAX_PWMS) {
613		data->pwms = pwms;
614		ABIT_UGURU_DEBUG(2, "assuming %d PWM outputs because of "
615			"\"pwms\" module param\n", (int)data->pwms);
616		return;
617	}
618
619	ABIT_UGURU_DEBUG(2, "detecting number of PWM outputs\n");
620	for (i = 0; i < ABIT_UGURU_MAX_PWMS; i++) {
621		/* 0x80 is the enable bit and the low
622		   nibble is which temp sensor to use,
623		   the other bits should be 0 */
624		if (data->pwm_settings[i][0] & ~0x8F) {
625			ABIT_UGURU_DEBUG(2, "  pwm channel %d does not seem "
626				"to be a pwm channel: settings[0] = %02X\n",
627				i, (unsigned int)data->pwm_settings[i][0]);
628			break;
629		}
630
631		/* the low nibble must correspond to one of the temp sensors
632		   we've found */
633		for (j = 0; j < data->bank1_sensors[ABIT_UGURU_TEMP_SENSOR];
634				j++) {
635			if (data->bank1_address[ABIT_UGURU_TEMP_SENSOR][j] ==
636					(data->pwm_settings[i][0] & 0x0F))
637				break;
638		}
639		if (j == data->bank1_sensors[ABIT_UGURU_TEMP_SENSOR]) {
640			ABIT_UGURU_DEBUG(2, "  pwm channel %d does not seem "
641				"to be a pwm channel: %d is not a valid temp "
642				"sensor address\n", i,
643				data->pwm_settings[i][0] & 0x0F);
644			break;
645		}
646
647		/* check if all other settings are within the allowed range */
648		for (j = 1; j < 5; j++) {
649			u8 min;
650			/* special case pwm1 min pwm% */
651			if ((i == 0) && ((j == 1) || (j == 2)))
652				min = 77;
653			else
654				min = abituguru_pwm_min[j];
655			if (data->pwm_settings[i][j] < min) {
656				ABIT_UGURU_DEBUG(2, "  pwm channel %d does "
657					"not seem to be a pwm channel: "
658					"setting %d (%d) is below the minimum "
659					"value (%d)\n", i, j,
660					(int)data->pwm_settings[i][j],
661					(int)min);
662				goto abituguru_detect_no_pwms_exit;
663			}
664			if (data->pwm_settings[i][j] > abituguru_pwm_max[j]) {
665				ABIT_UGURU_DEBUG(2, "  pwm channel %d does "
666					"not seem to be a pwm channel: "
667					"setting %d (%d) is above the maximum "
668					"value (%d)\n", i, j,
669					(int)data->pwm_settings[i][j],
670					(int)abituguru_pwm_max[j]);
671				goto abituguru_detect_no_pwms_exit;
672			}
673		}
674
675		/* check that min temp < max temp and min pwm < max pwm */
676		if (data->pwm_settings[i][1] >= data->pwm_settings[i][2]) {
677			ABIT_UGURU_DEBUG(2, "  pwm channel %d does not seem "
678				"to be a pwm channel: min pwm (%d) >= "
679				"max pwm (%d)\n", i,
680				(int)data->pwm_settings[i][1],
681				(int)data->pwm_settings[i][2]);
682			break;
683		}
684		if (data->pwm_settings[i][3] >= data->pwm_settings[i][4]) {
685			ABIT_UGURU_DEBUG(2, "  pwm channel %d does not seem "
686				"to be a pwm channel: min temp (%d) >= "
687				"max temp (%d)\n", i,
688				(int)data->pwm_settings[i][3],
689				(int)data->pwm_settings[i][4]);
690			break;
691		}
692	}
693
694abituguru_detect_no_pwms_exit:
695	data->pwms = i;
696	ABIT_UGURU_DEBUG(2, " found: %d PWM outputs\n", (int)data->pwms);
697}
698
699/* Following are the sysfs callback functions. These functions expect:
700   sensor_device_attribute_2->index:   sensor address/offset in the bank
701   sensor_device_attribute_2->nr:      register offset, bitmask or NA. */
702static struct abituguru_data *abituguru_update_device(struct device *dev);
703
704static ssize_t show_bank1_value(struct device *dev,
705	struct device_attribute *devattr, char *buf)
706{
707	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
708	struct abituguru_data *data = abituguru_update_device(dev);
709	if (!data)
710		return -EIO;
711	return sprintf(buf, "%d\n", (data->bank1_value[attr->index] *
712		data->bank1_max_value[attr->index] + 128) / 255);
713}
714
715static ssize_t show_bank1_setting(struct device *dev,
716	struct device_attribute *devattr, char *buf)
717{
718	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
719	struct abituguru_data *data = dev_get_drvdata(dev);
720	return sprintf(buf, "%d\n",
721		(data->bank1_settings[attr->index][attr->nr] *
722		data->bank1_max_value[attr->index] + 128) / 255);
723}
724
725static ssize_t show_bank2_value(struct device *dev,
726	struct device_attribute *devattr, char *buf)
727{
728	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
729	struct abituguru_data *data = abituguru_update_device(dev);
730	if (!data)
731		return -EIO;
732	return sprintf(buf, "%d\n", (data->bank2_value[attr->index] *
733		ABIT_UGURU_FAN_MAX + 128) / 255);
734}
735
736static ssize_t show_bank2_setting(struct device *dev,
737	struct device_attribute *devattr, char *buf)
738{
739	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
740	struct abituguru_data *data = dev_get_drvdata(dev);
741	return sprintf(buf, "%d\n",
742		(data->bank2_settings[attr->index][attr->nr] *
743		ABIT_UGURU_FAN_MAX + 128) / 255);
744}
745
746static ssize_t store_bank1_setting(struct device *dev, struct device_attribute
747	*devattr, const char *buf, size_t count)
748{
749	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
750	struct abituguru_data *data = dev_get_drvdata(dev);
751	u8 val = (simple_strtoul(buf, NULL, 10) * 255 +
752		data->bank1_max_value[attr->index]/2) /
753		data->bank1_max_value[attr->index];
754	ssize_t ret = count;
755
756	mutex_lock(&data->update_lock);
757	if (data->bank1_settings[attr->index][attr->nr] != val) {
758		u8 orig_val = data->bank1_settings[attr->index][attr->nr];
759		data->bank1_settings[attr->index][attr->nr] = val;
760		if (abituguru_write(data, ABIT_UGURU_SENSOR_BANK1 + 2,
761				attr->index, data->bank1_settings[attr->index],
762				3) <= attr->nr) {
763			data->bank1_settings[attr->index][attr->nr] = orig_val;
764			ret = -EIO;
765		}
766	}
767	mutex_unlock(&data->update_lock);
768	return ret;
769}
770
771static ssize_t store_bank2_setting(struct device *dev, struct device_attribute
772	*devattr, const char *buf, size_t count)
773{
774	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
775	struct abituguru_data *data = dev_get_drvdata(dev);
776	u8 val = (simple_strtoul(buf, NULL, 10)*255 + ABIT_UGURU_FAN_MAX/2) /
777		ABIT_UGURU_FAN_MAX;
778	ssize_t ret = count;
779
780	/* this check can be done before taking the lock */
781	if ((val < abituguru_bank2_min_threshold) ||
782			(val > abituguru_bank2_max_threshold))
783		return -EINVAL;
784
785	mutex_lock(&data->update_lock);
786	if (data->bank2_settings[attr->index][attr->nr] != val) {
787		u8 orig_val = data->bank2_settings[attr->index][attr->nr];
788		data->bank2_settings[attr->index][attr->nr] = val;
789		if (abituguru_write(data, ABIT_UGURU_SENSOR_BANK2 + 2,
790				attr->index, data->bank2_settings[attr->index],
791				2) <= attr->nr) {
792			data->bank2_settings[attr->index][attr->nr] = orig_val;
793			ret = -EIO;
794		}
795	}
796	mutex_unlock(&data->update_lock);
797	return ret;
798}
799
800static ssize_t show_bank1_alarm(struct device *dev,
801	struct device_attribute *devattr, char *buf)
802{
803	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
804	struct abituguru_data *data = abituguru_update_device(dev);
805	if (!data)
806		return -EIO;
807	/* See if the alarm bit for this sensor is set, and if the
808	   alarm matches the type of alarm we're looking for (for volt
809	   it can be either low or high). The type is stored in a few
810	   readonly bits in the settings part of the relevant sensor.
811	   The bitmask of the type is passed to us in attr->nr. */
812	if ((data->alarms[attr->index / 8] & (0x01 << (attr->index % 8))) &&
813			(data->bank1_settings[attr->index][0] & attr->nr))
814		return sprintf(buf, "1\n");
815	else
816		return sprintf(buf, "0\n");
817}
818
819static ssize_t show_bank2_alarm(struct device *dev,
820	struct device_attribute *devattr, char *buf)
821{
822	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
823	struct abituguru_data *data = abituguru_update_device(dev);
824	if (!data)
825		return -EIO;
826	if (data->alarms[2] & (0x01 << attr->index))
827		return sprintf(buf, "1\n");
828	else
829		return sprintf(buf, "0\n");
830}
831
832static ssize_t show_bank1_mask(struct device *dev,
833	struct device_attribute *devattr, char *buf)
834{
835	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
836	struct abituguru_data *data = dev_get_drvdata(dev);
837	if (data->bank1_settings[attr->index][0] & attr->nr)
838		return sprintf(buf, "1\n");
839	else
840		return sprintf(buf, "0\n");
841}
842
843static ssize_t show_bank2_mask(struct device *dev,
844	struct device_attribute *devattr, char *buf)
845{
846	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
847	struct abituguru_data *data = dev_get_drvdata(dev);
848	if (data->bank2_settings[attr->index][0] & attr->nr)
849		return sprintf(buf, "1\n");
850	else
851		return sprintf(buf, "0\n");
852}
853
854static ssize_t store_bank1_mask(struct device *dev,
855	struct device_attribute *devattr, const char *buf, size_t count)
856{
857	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
858	struct abituguru_data *data = dev_get_drvdata(dev);
859	int mask = simple_strtoul(buf, NULL, 10);
860	ssize_t ret = count;
861	u8 orig_val;
862
863	mutex_lock(&data->update_lock);
864	orig_val = data->bank1_settings[attr->index][0];
865
866	if (mask)
867		data->bank1_settings[attr->index][0] |= attr->nr;
868	else
869		data->bank1_settings[attr->index][0] &= ~attr->nr;
870
871	if ((data->bank1_settings[attr->index][0] != orig_val) &&
872			(abituguru_write(data,
873			ABIT_UGURU_SENSOR_BANK1 + 2, attr->index,
874			data->bank1_settings[attr->index], 3) < 1)) {
875		data->bank1_settings[attr->index][0] = orig_val;
876		ret = -EIO;
877	}
878	mutex_unlock(&data->update_lock);
879	return ret;
880}
881
882static ssize_t store_bank2_mask(struct device *dev,
883	struct device_attribute *devattr, const char *buf, size_t count)
884{
885	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
886	struct abituguru_data *data = dev_get_drvdata(dev);
887	int mask = simple_strtoul(buf, NULL, 10);
888	ssize_t ret = count;
889	u8 orig_val;
890
891	mutex_lock(&data->update_lock);
892	orig_val = data->bank2_settings[attr->index][0];
893
894	if (mask)
895		data->bank2_settings[attr->index][0] |= attr->nr;
896	else
897		data->bank2_settings[attr->index][0] &= ~attr->nr;
898
899	if ((data->bank2_settings[attr->index][0] != orig_val) &&
900			(abituguru_write(data,
901			ABIT_UGURU_SENSOR_BANK2 + 2, attr->index,
902			data->bank2_settings[attr->index], 2) < 1)) {
903		data->bank2_settings[attr->index][0] = orig_val;
904		ret = -EIO;
905	}
906	mutex_unlock(&data->update_lock);
907	return ret;
908}
909
910/* Fan PWM (speed control) */
911static ssize_t show_pwm_setting(struct device *dev,
912	struct device_attribute *devattr, char *buf)
913{
914	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
915	struct abituguru_data *data = dev_get_drvdata(dev);
916	return sprintf(buf, "%d\n", data->pwm_settings[attr->index][attr->nr] *
917		abituguru_pwm_settings_multiplier[attr->nr]);
918}
919
920static ssize_t store_pwm_setting(struct device *dev, struct device_attribute
921	*devattr, const char *buf, size_t count)
922{
923	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
924	struct abituguru_data *data = dev_get_drvdata(dev);
925	u8 min, val = (simple_strtoul(buf, NULL, 10) +
926		abituguru_pwm_settings_multiplier[attr->nr]/2) /
927		abituguru_pwm_settings_multiplier[attr->nr];
928	ssize_t ret = count;
929
930	/* special case pwm1 min pwm% */
931	if ((attr->index == 0) && ((attr->nr == 1) || (attr->nr == 2)))
932		min = 77;
933	else
934		min = abituguru_pwm_min[attr->nr];
935
936	/* this check can be done before taking the lock */
937	if ((val < min) || (val > abituguru_pwm_max[attr->nr]))
938		return -EINVAL;
939
940	mutex_lock(&data->update_lock);
941	/* this check needs to be done after taking the lock */
942	if ((attr->nr & 1) &&
943			(val >= data->pwm_settings[attr->index][attr->nr + 1]))
944		ret = -EINVAL;
945	else if (!(attr->nr & 1) &&
946			(val <= data->pwm_settings[attr->index][attr->nr - 1]))
947		ret = -EINVAL;
948	else if (data->pwm_settings[attr->index][attr->nr] != val) {
949		u8 orig_val = data->pwm_settings[attr->index][attr->nr];
950		data->pwm_settings[attr->index][attr->nr] = val;
951		if (abituguru_write(data, ABIT_UGURU_FAN_PWM + 1,
952				attr->index, data->pwm_settings[attr->index],
953				5) <= attr->nr) {
954			data->pwm_settings[attr->index][attr->nr] =
955				orig_val;
956			ret = -EIO;
957		}
958	}
959	mutex_unlock(&data->update_lock);
960	return ret;
961}
962
963static ssize_t show_pwm_sensor(struct device *dev,
964	struct device_attribute *devattr, char *buf)
965{
966	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
967	struct abituguru_data *data = dev_get_drvdata(dev);
968	int i;
969	/* We need to walk to the temp sensor addresses to find what
970	   the userspace id of the configured temp sensor is. */
971	for (i = 0; i < data->bank1_sensors[ABIT_UGURU_TEMP_SENSOR]; i++)
972		if (data->bank1_address[ABIT_UGURU_TEMP_SENSOR][i] ==
973				(data->pwm_settings[attr->index][0] & 0x0F))
974			return sprintf(buf, "%d\n", i+1);
975
976	return -ENXIO;
977}
978
979static ssize_t store_pwm_sensor(struct device *dev, struct device_attribute
980	*devattr, const char *buf, size_t count)
981{
982	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
983	struct abituguru_data *data = dev_get_drvdata(dev);
984	unsigned long val = simple_strtoul(buf, NULL, 10) - 1;
985	ssize_t ret = count;
986
987	mutex_lock(&data->update_lock);
988	if (val < data->bank1_sensors[ABIT_UGURU_TEMP_SENSOR]) {
989		u8 orig_val = data->pwm_settings[attr->index][0];
990		u8 address = data->bank1_address[ABIT_UGURU_TEMP_SENSOR][val];
991		data->pwm_settings[attr->index][0] &= 0xF0;
992		data->pwm_settings[attr->index][0] |= address;
993		if (data->pwm_settings[attr->index][0] != orig_val) {
994			if (abituguru_write(data, ABIT_UGURU_FAN_PWM + 1,
995					attr->index,
996					data->pwm_settings[attr->index],
997					5) < 1) {
998				data->pwm_settings[attr->index][0] = orig_val;
999				ret = -EIO;
1000			}
1001		}
1002	}
1003	else
1004		ret = -EINVAL;
1005	mutex_unlock(&data->update_lock);
1006	return ret;
1007}
1008
1009static ssize_t show_pwm_enable(struct device *dev,
1010	struct device_attribute *devattr, char *buf)
1011{
1012	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
1013	struct abituguru_data *data = dev_get_drvdata(dev);
1014	int res = 0;
1015	if (data->pwm_settings[attr->index][0] & ABIT_UGURU_FAN_PWM_ENABLE)
1016		res = 2;
1017	return sprintf(buf, "%d\n", res);
1018}
1019
1020static ssize_t store_pwm_enable(struct device *dev, struct device_attribute
1021	*devattr, const char *buf, size_t count)
1022{
1023	struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
1024	struct abituguru_data *data = dev_get_drvdata(dev);
1025	u8 orig_val, user_val = simple_strtoul(buf, NULL, 10);
1026	ssize_t ret = count;
1027
1028	mutex_lock(&data->update_lock);
1029	orig_val = data->pwm_settings[attr->index][0];
1030	switch (user_val) {
1031		case 0:
1032			data->pwm_settings[attr->index][0] &=
1033				~ABIT_UGURU_FAN_PWM_ENABLE;
1034			break;
1035		case 2:
1036			data->pwm_settings[attr->index][0] |=
1037				ABIT_UGURU_FAN_PWM_ENABLE;
1038			break;
1039		default:
1040			ret = -EINVAL;
1041	}
1042	if ((data->pwm_settings[attr->index][0] != orig_val) &&
1043			(abituguru_write(data, ABIT_UGURU_FAN_PWM + 1,
1044			attr->index, data->pwm_settings[attr->index],
1045			5) < 1)) {
1046		data->pwm_settings[attr->index][0] = orig_val;
1047		ret = -EIO;
1048	}
1049	mutex_unlock(&data->update_lock);
1050	return ret;
1051}
1052
1053static ssize_t show_name(struct device *dev,
1054	struct device_attribute *devattr, char *buf)
1055{
1056	return sprintf(buf, "%s\n", ABIT_UGURU_NAME);
1057}
1058
1059/* Sysfs attr templates, the real entries are generated automatically. */
1060static const
1061struct sensor_device_attribute_2 abituguru_sysfs_bank1_templ[2][9] = {
1062	{
1063	SENSOR_ATTR_2(in%d_input, 0444, show_bank1_value, NULL, 0, 0),
1064	SENSOR_ATTR_2(in%d_min, 0644, show_bank1_setting,
1065		store_bank1_setting, 1, 0),
1066	SENSOR_ATTR_2(in%d_min_alarm, 0444, show_bank1_alarm, NULL,
1067		ABIT_UGURU_VOLT_LOW_ALARM_FLAG, 0),
1068	SENSOR_ATTR_2(in%d_max, 0644, show_bank1_setting,
1069		store_bank1_setting, 2, 0),
1070	SENSOR_ATTR_2(in%d_max_alarm, 0444, show_bank1_alarm, NULL,
1071		ABIT_UGURU_VOLT_HIGH_ALARM_FLAG, 0),
1072	SENSOR_ATTR_2(in%d_beep, 0644, show_bank1_mask,
1073		store_bank1_mask, ABIT_UGURU_BEEP_ENABLE, 0),
1074	SENSOR_ATTR_2(in%d_shutdown, 0644, show_bank1_mask,
1075		store_bank1_mask, ABIT_UGURU_SHUTDOWN_ENABLE, 0),
1076	SENSOR_ATTR_2(in%d_min_alarm_enable, 0644, show_bank1_mask,
1077		store_bank1_mask, ABIT_UGURU_VOLT_LOW_ALARM_ENABLE, 0),
1078	SENSOR_ATTR_2(in%d_max_alarm_enable, 0644, show_bank1_mask,
1079		store_bank1_mask, ABIT_UGURU_VOLT_HIGH_ALARM_ENABLE, 0),
1080	}, {
1081	SENSOR_ATTR_2(temp%d_input, 0444, show_bank1_value, NULL, 0, 0),
1082	SENSOR_ATTR_2(temp%d_alarm, 0444, show_bank1_alarm, NULL,
1083		ABIT_UGURU_TEMP_HIGH_ALARM_FLAG, 0),
1084	SENSOR_ATTR_2(temp%d_max, 0644, show_bank1_setting,
1085		store_bank1_setting, 1, 0),
1086	SENSOR_ATTR_2(temp%d_crit, 0644, show_bank1_setting,
1087		store_bank1_setting, 2, 0),
1088	SENSOR_ATTR_2(temp%d_beep, 0644, show_bank1_mask,
1089		store_bank1_mask, ABIT_UGURU_BEEP_ENABLE, 0),
1090	SENSOR_ATTR_2(temp%d_shutdown, 0644, show_bank1_mask,
1091		store_bank1_mask, ABIT_UGURU_SHUTDOWN_ENABLE, 0),
1092	SENSOR_ATTR_2(temp%d_alarm_enable, 0644, show_bank1_mask,
1093		store_bank1_mask, ABIT_UGURU_TEMP_HIGH_ALARM_ENABLE, 0),
1094	}
1095};
1096
1097static const struct sensor_device_attribute_2 abituguru_sysfs_fan_templ[6] = {
1098	SENSOR_ATTR_2(fan%d_input, 0444, show_bank2_value, NULL, 0, 0),
1099	SENSOR_ATTR_2(fan%d_alarm, 0444, show_bank2_alarm, NULL, 0, 0),
1100	SENSOR_ATTR_2(fan%d_min, 0644, show_bank2_setting,
1101		store_bank2_setting, 1, 0),
1102	SENSOR_ATTR_2(fan%d_beep, 0644, show_bank2_mask,
1103		store_bank2_mask, ABIT_UGURU_BEEP_ENABLE, 0),
1104	SENSOR_ATTR_2(fan%d_shutdown, 0644, show_bank2_mask,
1105		store_bank2_mask, ABIT_UGURU_SHUTDOWN_ENABLE, 0),
1106	SENSOR_ATTR_2(fan%d_alarm_enable, 0644, show_bank2_mask,
1107		store_bank2_mask, ABIT_UGURU_FAN_LOW_ALARM_ENABLE, 0),
1108};
1109
1110static const struct sensor_device_attribute_2 abituguru_sysfs_pwm_templ[6] = {
1111	SENSOR_ATTR_2(pwm%d_enable, 0644, show_pwm_enable,
1112		store_pwm_enable, 0, 0),
1113	SENSOR_ATTR_2(pwm%d_auto_channels_temp, 0644, show_pwm_sensor,
1114		store_pwm_sensor, 0, 0),
1115	SENSOR_ATTR_2(pwm%d_auto_point1_pwm, 0644, show_pwm_setting,
1116		store_pwm_setting, 1, 0),
1117	SENSOR_ATTR_2(pwm%d_auto_point2_pwm, 0644, show_pwm_setting,
1118		store_pwm_setting, 2, 0),
1119	SENSOR_ATTR_2(pwm%d_auto_point1_temp, 0644, show_pwm_setting,
1120		store_pwm_setting, 3, 0),
1121	SENSOR_ATTR_2(pwm%d_auto_point2_temp, 0644, show_pwm_setting,
1122		store_pwm_setting, 4, 0),
1123};
1124
1125static struct sensor_device_attribute_2 abituguru_sysfs_attr[] = {
1126	SENSOR_ATTR_2(name, 0444, show_name, NULL, 0, 0),
1127};
1128
1129static int __devinit abituguru_probe(struct platform_device *pdev)
1130{
1131	struct abituguru_data *data;
1132	int i, j, used, sysfs_names_free, sysfs_attr_i, res = -ENODEV;
1133	char *sysfs_filename;
1134
1135	/* El weirdo probe order, to keep the sysfs order identical to the
1136	   BIOS and window-appliction listing order. */
1137	const u8 probe_order[ABIT_UGURU_MAX_BANK1_SENSORS] = {
1138		0x00, 0x01, 0x03, 0x04, 0x0A, 0x08, 0x0E, 0x02,
1139		0x09, 0x06, 0x05, 0x0B, 0x0F, 0x0D, 0x07, 0x0C };
1140
1141	if (!(data = kzalloc(sizeof(struct abituguru_data), GFP_KERNEL)))
1142		return -ENOMEM;
1143
1144	data->addr = platform_get_resource(pdev, IORESOURCE_IO, 0)->start;
1145	mutex_init(&data->update_lock);
1146	platform_set_drvdata(pdev, data);
1147
1148	/* See if the uGuru is ready */
1149	if (inb_p(data->addr + ABIT_UGURU_DATA) == ABIT_UGURU_STATUS_INPUT)
1150		data->uguru_ready = 1;
1151
1152	/* Completely read the uGuru this has 2 purposes:
1153	   - testread / see if one really is there.
1154	   - make an in memory copy of all the uguru settings for future use. */
1155	if (abituguru_read(data, ABIT_UGURU_ALARM_BANK, 0,
1156			data->alarms, 3, ABIT_UGURU_MAX_RETRIES) != 3)
1157		goto abituguru_probe_error;
1158
1159	for (i = 0; i < ABIT_UGURU_MAX_BANK1_SENSORS; i++) {
1160		if (abituguru_read(data, ABIT_UGURU_SENSOR_BANK1, i,
1161				&data->bank1_value[i], 1,
1162				ABIT_UGURU_MAX_RETRIES) != 1)
1163			goto abituguru_probe_error;
1164		if (abituguru_read(data, ABIT_UGURU_SENSOR_BANK1+1, i,
1165				data->bank1_settings[i], 3,
1166				ABIT_UGURU_MAX_RETRIES) != 3)
1167			goto abituguru_probe_error;
1168	}
1169	/* Note: We don't know how many bank2 sensors / pwms there really are,
1170	   but in order to "detect" this we need to read the maximum amount
1171	   anyways. If we read sensors/pwms not there we'll just read crap
1172	   this can't hurt. We need the detection because we don't want
1173	   unwanted writes, which will hurt! */
1174	for (i = 0; i < ABIT_UGURU_MAX_BANK2_SENSORS; i++) {
1175		if (abituguru_read(data, ABIT_UGURU_SENSOR_BANK2, i,
1176				&data->bank2_value[i], 1,
1177				ABIT_UGURU_MAX_RETRIES) != 1)
1178			goto abituguru_probe_error;
1179		if (abituguru_read(data, ABIT_UGURU_SENSOR_BANK2+1, i,
1180				data->bank2_settings[i], 2,
1181				ABIT_UGURU_MAX_RETRIES) != 2)
1182			goto abituguru_probe_error;
1183	}
1184	for (i = 0; i < ABIT_UGURU_MAX_PWMS; i++) {
1185		if (abituguru_read(data, ABIT_UGURU_FAN_PWM, i,
1186				data->pwm_settings[i], 5,
1187				ABIT_UGURU_MAX_RETRIES) != 5)
1188			goto abituguru_probe_error;
1189	}
1190	data->last_updated = jiffies;
1191
1192	/* Detect sensor types and fill the sysfs attr for bank1 */
1193	sysfs_attr_i = 0;
1194	sysfs_filename = data->sysfs_names;
1195	sysfs_names_free = ABITUGURU_SYSFS_NAMES_LENGTH;
1196	for (i = 0; i < ABIT_UGURU_MAX_BANK1_SENSORS; i++) {
1197		res = abituguru_detect_bank1_sensor_type(data, probe_order[i]);
1198		if (res < 0)
1199			goto abituguru_probe_error;
1200		if (res == ABIT_UGURU_NC)
1201			continue;
1202
1203		/* res 1 (temp) sensors have 7 sysfs entries, 0 (in) 9 */
1204		for (j = 0; j < (res ? 7 : 9); j++) {
1205			used = snprintf(sysfs_filename, sysfs_names_free,
1206				abituguru_sysfs_bank1_templ[res][j].dev_attr.
1207				attr.name, data->bank1_sensors[res] + res)
1208				+ 1;
1209			data->sysfs_attr[sysfs_attr_i] =
1210				abituguru_sysfs_bank1_templ[res][j];
1211			data->sysfs_attr[sysfs_attr_i].dev_attr.attr.name =
1212				sysfs_filename;
1213			data->sysfs_attr[sysfs_attr_i].index = probe_order[i];
1214			sysfs_filename += used;
1215			sysfs_names_free -= used;
1216			sysfs_attr_i++;
1217		}
1218		data->bank1_max_value[probe_order[i]] =
1219			abituguru_bank1_max_value[res];
1220		data->bank1_address[res][data->bank1_sensors[res]] =
1221			probe_order[i];
1222		data->bank1_sensors[res]++;
1223	}
1224	/* Detect number of sensors and fill the sysfs attr for bank2 (fans) */
1225	abituguru_detect_no_bank2_sensors(data);
1226	for (i = 0; i < data->bank2_sensors; i++) {
1227		for (j = 0; j < ARRAY_SIZE(abituguru_sysfs_fan_templ); j++) {
1228			used = snprintf(sysfs_filename, sysfs_names_free,
1229				abituguru_sysfs_fan_templ[j].dev_attr.attr.name,
1230				i + 1) + 1;
1231			data->sysfs_attr[sysfs_attr_i] =
1232				abituguru_sysfs_fan_templ[j];
1233			data->sysfs_attr[sysfs_attr_i].dev_attr.attr.name =
1234				sysfs_filename;
1235			data->sysfs_attr[sysfs_attr_i].index = i;
1236			sysfs_filename += used;
1237			sysfs_names_free -= used;
1238			sysfs_attr_i++;
1239		}
1240	}
1241	/* Detect number of sensors and fill the sysfs attr for pwms */
1242	abituguru_detect_no_pwms(data);
1243	for (i = 0; i < data->pwms; i++) {
1244		for (j = 0; j < ARRAY_SIZE(abituguru_sysfs_pwm_templ); j++) {
1245			used = snprintf(sysfs_filename, sysfs_names_free,
1246				abituguru_sysfs_pwm_templ[j].dev_attr.attr.name,
1247				i + 1) + 1;
1248			data->sysfs_attr[sysfs_attr_i] =
1249				abituguru_sysfs_pwm_templ[j];
1250			data->sysfs_attr[sysfs_attr_i].dev_attr.attr.name =
1251				sysfs_filename;
1252			data->sysfs_attr[sysfs_attr_i].index = i;
1253			sysfs_filename += used;
1254			sysfs_names_free -= used;
1255			sysfs_attr_i++;
1256		}
1257	}
1258	/* Fail safe check, this should never happen! */
1259	if (sysfs_names_free < 0) {
1260		printk(KERN_ERR ABIT_UGURU_NAME ": Fatal error ran out of "
1261		       "space for sysfs attr names. This should never "
1262		       "happen please report to the abituguru maintainer "
1263		       "(see MAINTAINERS)\n");
1264		res = -ENAMETOOLONG;
1265		goto abituguru_probe_error;
1266	}
1267	printk(KERN_INFO ABIT_UGURU_NAME ": found Abit uGuru\n");
1268
1269	/* Register sysfs hooks */
1270	for (i = 0; i < sysfs_attr_i; i++)
1271		if (device_create_file(&pdev->dev,
1272				&data->sysfs_attr[i].dev_attr))
1273			goto abituguru_probe_error;
1274	for (i = 0; i < ARRAY_SIZE(abituguru_sysfs_attr); i++)
1275		if (device_create_file(&pdev->dev,
1276				&abituguru_sysfs_attr[i].dev_attr))
1277			goto abituguru_probe_error;
1278
1279	data->class_dev = hwmon_device_register(&pdev->dev);
1280	if (!IS_ERR(data->class_dev))
1281		return 0; /* success */
1282
1283	res = PTR_ERR(data->class_dev);
1284abituguru_probe_error:
1285	for (i = 0; data->sysfs_attr[i].dev_attr.attr.name; i++)
1286		device_remove_file(&pdev->dev, &data->sysfs_attr[i].dev_attr);
1287	for (i = 0; i < ARRAY_SIZE(abituguru_sysfs_attr); i++)
1288		device_remove_file(&pdev->dev,
1289			&abituguru_sysfs_attr[i].dev_attr);
1290	kfree(data);
1291	return res;
1292}
1293
1294static int __devexit abituguru_remove(struct platform_device *pdev)
1295{
1296	int i;
1297	struct abituguru_data *data = platform_get_drvdata(pdev);
1298
1299	platform_set_drvdata(pdev, NULL);
1300	hwmon_device_unregister(data->class_dev);
1301	for (i = 0; data->sysfs_attr[i].dev_attr.attr.name; i++)
1302		device_remove_file(&pdev->dev, &data->sysfs_attr[i].dev_attr);
1303	for (i = 0; i < ARRAY_SIZE(abituguru_sysfs_attr); i++)
1304		device_remove_file(&pdev->dev,
1305			&abituguru_sysfs_attr[i].dev_attr);
1306	kfree(data);
1307
1308	return 0;
1309}
1310
1311static struct abituguru_data *abituguru_update_device(struct device *dev)
1312{
1313	int i, err;
1314	struct abituguru_data *data = dev_get_drvdata(dev);
1315	/* fake a complete successful read if no update necessary. */
1316	char success = 1;
1317
1318	mutex_lock(&data->update_lock);
1319	if (time_after(jiffies, data->last_updated + HZ)) {
1320		success = 0;
1321		if ((err = abituguru_read(data, ABIT_UGURU_ALARM_BANK, 0,
1322				data->alarms, 3, 0)) != 3)
1323			goto LEAVE_UPDATE;
1324		for (i = 0; i < ABIT_UGURU_MAX_BANK1_SENSORS; i++) {
1325			if ((err = abituguru_read(data,
1326					ABIT_UGURU_SENSOR_BANK1, i,
1327					&data->bank1_value[i], 1, 0)) != 1)
1328				goto LEAVE_UPDATE;
1329			if ((err = abituguru_read(data,
1330					ABIT_UGURU_SENSOR_BANK1 + 1, i,
1331					data->bank1_settings[i], 3, 0)) != 3)
1332				goto LEAVE_UPDATE;
1333		}
1334		for (i = 0; i < data->bank2_sensors; i++)
1335			if ((err = abituguru_read(data,
1336					ABIT_UGURU_SENSOR_BANK2, i,
1337					&data->bank2_value[i], 1, 0)) != 1)
1338				goto LEAVE_UPDATE;
1339		/* success! */
1340		success = 1;
1341		data->update_timeouts = 0;
1342LEAVE_UPDATE:
1343		/* handle timeout condition */
1344		if (!success && (err == -EBUSY || err >= 0)) {
1345			/* No overflow please */
1346			if (data->update_timeouts < 255u)
1347				data->update_timeouts++;
1348			if (data->update_timeouts <= ABIT_UGURU_MAX_TIMEOUTS) {
1349				ABIT_UGURU_DEBUG(3, "timeout exceeded, will "
1350					"try again next update\n");
1351				/* Just a timeout, fake a successful read */
1352				success = 1;
1353			} else
1354				ABIT_UGURU_DEBUG(1, "timeout exceeded %d "
1355					"times waiting for more input state\n",
1356					(int)data->update_timeouts);
1357		}
1358		/* On success set last_updated */
1359		if (success)
1360			data->last_updated = jiffies;
1361	}
1362	mutex_unlock(&data->update_lock);
1363
1364	if (success)
1365		return data;
1366	else
1367		return NULL;
1368}
1369
1370#ifdef CONFIG_PM
1371static int abituguru_suspend(struct platform_device *pdev, pm_message_t state)
1372{
1373	struct abituguru_data *data = platform_get_drvdata(pdev);
1374	/* make sure all communications with the uguru are done and no new
1375	   ones are started */
1376	mutex_lock(&data->update_lock);
1377	return 0;
1378}
1379
1380static int abituguru_resume(struct platform_device *pdev)
1381{
1382	struct abituguru_data *data = platform_get_drvdata(pdev);
1383	/* See if the uGuru is still ready */
1384	if (inb_p(data->addr + ABIT_UGURU_DATA) != ABIT_UGURU_STATUS_INPUT)
1385		data->uguru_ready = 0;
1386	mutex_unlock(&data->update_lock);
1387	return 0;
1388}
1389#else
1390#define abituguru_suspend	NULL
1391#define abituguru_resume	NULL
1392#endif /* CONFIG_PM */
1393
1394static struct platform_driver abituguru_driver = {
1395	.driver = {
1396		.owner	= THIS_MODULE,
1397		.name	= ABIT_UGURU_NAME,
1398	},
1399	.probe		= abituguru_probe,
1400	.remove		= __devexit_p(abituguru_remove),
1401	.suspend	= abituguru_suspend,
1402	.resume		= abituguru_resume,
1403};
1404
1405static int __init abituguru_detect(void)
1406{
1407	/* See if there is an uguru there. After a reboot uGuru will hold 0x00
1408	   at DATA and 0xAC, when this driver has already been loaded once
1409	   DATA will hold 0x08. For most uGuru's CMD will hold 0xAC in either
1410	   scenario but some will hold 0x00.
1411	   Some uGuru's initally hold 0x09 at DATA and will only hold 0x08
1412	   after reading CMD first, so CMD must be read first! */
1413	u8 cmd_val = inb_p(ABIT_UGURU_BASE + ABIT_UGURU_CMD);
1414	u8 data_val = inb_p(ABIT_UGURU_BASE + ABIT_UGURU_DATA);
1415	if (((data_val == 0x00) || (data_val == 0x08)) &&
1416	    ((cmd_val == 0x00) || (cmd_val == 0xAC)))
1417		return ABIT_UGURU_BASE;
1418
1419	ABIT_UGURU_DEBUG(2, "no Abit uGuru found, data = 0x%02X, cmd = "
1420		"0x%02X\n", (unsigned int)data_val, (unsigned int)cmd_val);
1421
1422	if (force) {
1423		printk(KERN_INFO ABIT_UGURU_NAME ": Assuming Abit uGuru is "
1424				"present because of \"force\" parameter\n");
1425		return ABIT_UGURU_BASE;
1426	}
1427
1428	/* No uGuru found */
1429	return -ENODEV;
1430}
1431
1432static struct platform_device *abituguru_pdev;
1433
1434static int __init abituguru_init(void)
1435{
1436	int address, err;
1437	struct resource res = { .flags = IORESOURCE_IO };
1438
1439	address = abituguru_detect();
1440	if (address < 0)
1441		return address;
1442
1443	err = platform_driver_register(&abituguru_driver);
1444	if (err)
1445		goto exit;
1446
1447	abituguru_pdev = platform_device_alloc(ABIT_UGURU_NAME, address);
1448	if (!abituguru_pdev) {
1449		printk(KERN_ERR ABIT_UGURU_NAME
1450			": Device allocation failed\n");
1451		err = -ENOMEM;
1452		goto exit_driver_unregister;
1453	}
1454
1455	res.start = address;
1456	res.end = address + ABIT_UGURU_REGION_LENGTH - 1;
1457	res.name = ABIT_UGURU_NAME;
1458
1459	err = platform_device_add_resources(abituguru_pdev, &res, 1);
1460	if (err) {
1461		printk(KERN_ERR ABIT_UGURU_NAME
1462			": Device resource addition failed (%d)\n", err);
1463		goto exit_device_put;
1464	}
1465
1466	err = platform_device_add(abituguru_pdev);
1467	if (err) {
1468		printk(KERN_ERR ABIT_UGURU_NAME
1469			": Device addition failed (%d)\n", err);
1470		goto exit_device_put;
1471	}
1472
1473	return 0;
1474
1475exit_device_put:
1476	platform_device_put(abituguru_pdev);
1477exit_driver_unregister:
1478	platform_driver_unregister(&abituguru_driver);
1479exit:
1480	return err;
1481}
1482
1483static void __exit abituguru_exit(void)
1484{
1485	platform_device_unregister(abituguru_pdev);
1486	platform_driver_unregister(&abituguru_driver);
1487}
1488
1489MODULE_AUTHOR("Hans de Goede <j.w.r.degoede@hhs.nl>");
1490MODULE_DESCRIPTION("Abit uGuru Sensor device");
1491MODULE_LICENSE("GPL");
1492
1493module_init(abituguru_init);
1494module_exit(abituguru_exit);
1495