1/*
2 * drivers/hwmon/applesmc.c - driver for Apple's SMC (accelerometer, temperature
3 * sensors, fan control, keyboard backlight control) used in Intel-based Apple
4 * computers.
5 *
6 * Copyright (C) 2007 Nicolas Boichat <nicolas@boichat.ch>
7 * Copyright (C) 2010 Henrik Rydberg <rydberg@euromail.se>
8 *
9 * Based on hdaps.c driver:
10 * Copyright (C) 2005 Robert Love <rml@novell.com>
11 * Copyright (C) 2005 Jesper Juhl <jj@chaosbits.net>
12 *
13 * Fan control based on smcFanControl:
14 * Copyright (C) 2006 Hendrik Holtmann <holtmann@mac.com>
15 *
16 * This program is free software; you can redistribute it and/or modify it
17 * under the terms of the GNU General Public License v2 as published by the
18 * Free Software Foundation.
19 *
20 * This program is distributed in the hope that it will be useful, but WITHOUT
21 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
22 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
23 * more details.
24 *
25 * You should have received a copy of the GNU General Public License along with
26 * this program; if not, write to the Free Software Foundation, Inc.,
27 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
28 */
29
30#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31
32#include <linux/delay.h>
33#include <linux/platform_device.h>
34#include <linux/input-polldev.h>
35#include <linux/kernel.h>
36#include <linux/slab.h>
37#include <linux/module.h>
38#include <linux/timer.h>
39#include <linux/dmi.h>
40#include <linux/mutex.h>
41#include <linux/hwmon-sysfs.h>
42#include <linux/io.h>
43#include <linux/leds.h>
44#include <linux/hwmon.h>
45#include <linux/workqueue.h>
46#include <linux/err.h>
47
48/* data port used by Apple SMC */
49#define APPLESMC_DATA_PORT	0x300
50/* command/status port used by Apple SMC */
51#define APPLESMC_CMD_PORT	0x304
52
53#define APPLESMC_NR_PORTS	32 /* 0x300-0x31f */
54
55#define APPLESMC_MAX_DATA_LENGTH 32
56
57/* wait up to 128 ms for a status change. */
58#define APPLESMC_MIN_WAIT	0x0010
59#define APPLESMC_RETRY_WAIT	0x0100
60#define APPLESMC_MAX_WAIT	0x20000
61
62#define APPLESMC_READ_CMD	0x10
63#define APPLESMC_WRITE_CMD	0x11
64#define APPLESMC_GET_KEY_BY_INDEX_CMD	0x12
65#define APPLESMC_GET_KEY_TYPE_CMD	0x13
66
67#define KEY_COUNT_KEY		"#KEY" /* r-o ui32 */
68
69#define LIGHT_SENSOR_LEFT_KEY	"ALV0" /* r-o {alv (6-10 bytes) */
70#define LIGHT_SENSOR_RIGHT_KEY	"ALV1" /* r-o {alv (6-10 bytes) */
71#define BACKLIGHT_KEY		"LKSB" /* w-o {lkb (2 bytes) */
72
73#define CLAMSHELL_KEY		"MSLD" /* r-o ui8 (unused) */
74
75#define MOTION_SENSOR_X_KEY	"MO_X" /* r-o sp78 (2 bytes) */
76#define MOTION_SENSOR_Y_KEY	"MO_Y" /* r-o sp78 (2 bytes) */
77#define MOTION_SENSOR_Z_KEY	"MO_Z" /* r-o sp78 (2 bytes) */
78#define MOTION_SENSOR_KEY	"MOCN" /* r/w ui16 */
79
80#define FANS_COUNT		"FNum" /* r-o ui8 */
81#define FANS_MANUAL		"FS! " /* r-w ui16 */
82#define FAN_ID_FMT		"F%dID" /* r-o char[16] */
83
84#define TEMP_SENSOR_TYPE	"sp78"
85
86/* List of keys used to read/write fan speeds */
87static const char *const fan_speed_fmt[] = {
88	"F%dAc",		/* actual speed */
89	"F%dMn",		/* minimum speed (rw) */
90	"F%dMx",		/* maximum speed */
91	"F%dSf",		/* safe speed - not all models */
92	"F%dTg",		/* target speed (manual: rw) */
93};
94
95#define INIT_TIMEOUT_MSECS	5000	/* wait up to 5s for device init ... */
96#define INIT_WAIT_MSECS		50	/* ... in 50ms increments */
97
98#define APPLESMC_POLL_INTERVAL	50	/* msecs */
99#define APPLESMC_INPUT_FUZZ	4	/* input event threshold */
100#define APPLESMC_INPUT_FLAT	4
101
102#define to_index(attr) (to_sensor_dev_attr(attr)->index & 0xffff)
103#define to_option(attr) (to_sensor_dev_attr(attr)->index >> 16)
104
105/* Dynamic device node attributes */
106struct applesmc_dev_attr {
107	struct sensor_device_attribute sda;	/* hwmon attributes */
108	char name[32];				/* room for node file name */
109};
110
111/* Dynamic device node group */
112struct applesmc_node_group {
113	char *format;				/* format string */
114	void *show;				/* show function */
115	void *store;				/* store function */
116	int option;				/* function argument */
117	struct applesmc_dev_attr *nodes;	/* dynamic node array */
118};
119
120/* AppleSMC entry - cached register information */
121struct applesmc_entry {
122	char key[5];		/* four-letter key code */
123	u8 valid;		/* set when entry is successfully read once */
124	u8 len;			/* bounded by APPLESMC_MAX_DATA_LENGTH */
125	char type[5];		/* four-letter type code */
126	u8 flags;		/* 0x10: func; 0x40: write; 0x80: read */
127};
128
129/* Register lookup and registers common to all SMCs */
130static struct applesmc_registers {
131	struct mutex mutex;		/* register read/write mutex */
132	unsigned int key_count;		/* number of SMC registers */
133	unsigned int fan_count;		/* number of fans */
134	unsigned int temp_count;	/* number of temperature registers */
135	unsigned int temp_begin;	/* temperature lower index bound */
136	unsigned int temp_end;		/* temperature upper index bound */
137	unsigned int index_count;	/* size of temperature index array */
138	int num_light_sensors;		/* number of light sensors */
139	bool has_accelerometer;		/* has motion sensor */
140	bool has_key_backlight;		/* has keyboard backlight */
141	bool init_complete;		/* true when fully initialized */
142	struct applesmc_entry *cache;	/* cached key entries */
143	const char **index;		/* temperature key index */
144} smcreg = {
145	.mutex = __MUTEX_INITIALIZER(smcreg.mutex),
146};
147
148static const int debug;
149static struct platform_device *pdev;
150static s16 rest_x;
151static s16 rest_y;
152static u8 backlight_state[2];
153
154static struct device *hwmon_dev;
155static struct input_polled_dev *applesmc_idev;
156
157/*
158 * Last index written to key_at_index sysfs file, and value to use for all other
159 * key_at_index_* sysfs files.
160 */
161static unsigned int key_at_index;
162
163static struct workqueue_struct *applesmc_led_wq;
164
165/*
166 * wait_read - Wait for a byte to appear on SMC port. Callers must
167 * hold applesmc_lock.
168 */
169static int wait_read(void)
170{
171	u8 status;
172	int us;
173	for (us = APPLESMC_MIN_WAIT; us < APPLESMC_MAX_WAIT; us <<= 1) {
174		udelay(us);
175		status = inb(APPLESMC_CMD_PORT);
176		/* read: wait for smc to settle */
177		if (status & 0x01)
178			return 0;
179	}
180
181	pr_warn("wait_read() fail: 0x%02x\n", status);
182	return -EIO;
183}
184
185/*
186 * send_byte - Write to SMC port, retrying when necessary. Callers
187 * must hold applesmc_lock.
188 */
189static int send_byte(u8 cmd, u16 port)
190{
191	u8 status;
192	int us;
193
194	outb(cmd, port);
195	for (us = APPLESMC_MIN_WAIT; us < APPLESMC_MAX_WAIT; us <<= 1) {
196		udelay(us);
197		status = inb(APPLESMC_CMD_PORT);
198		/* write: wait for smc to settle */
199		if (status & 0x02)
200			continue;
201		/* ready: cmd accepted, return */
202		if (status & 0x04)
203			return 0;
204		/* timeout: give up */
205		if (us << 1 == APPLESMC_MAX_WAIT)
206			break;
207		/* busy: long wait and resend */
208		udelay(APPLESMC_RETRY_WAIT);
209		outb(cmd, port);
210	}
211
212	pr_warn("send_byte(0x%02x, 0x%04x) fail: 0x%02x\n", cmd, port, status);
213	return -EIO;
214}
215
216static int send_command(u8 cmd)
217{
218	return send_byte(cmd, APPLESMC_CMD_PORT);
219}
220
221static int send_argument(const char *key)
222{
223	int i;
224
225	for (i = 0; i < 4; i++)
226		if (send_byte(key[i], APPLESMC_DATA_PORT))
227			return -EIO;
228	return 0;
229}
230
231static int read_smc(u8 cmd, const char *key, u8 *buffer, u8 len)
232{
233	u8 status, data = 0;
234	int i;
235
236	if (send_command(cmd) || send_argument(key)) {
237		pr_warn("%.4s: read arg fail\n", key);
238		return -EIO;
239	}
240
241	/* This has no effect on newer (2012) SMCs */
242	if (send_byte(len, APPLESMC_DATA_PORT)) {
243		pr_warn("%.4s: read len fail\n", key);
244		return -EIO;
245	}
246
247	for (i = 0; i < len; i++) {
248		if (wait_read()) {
249			pr_warn("%.4s: read data[%d] fail\n", key, i);
250			return -EIO;
251		}
252		buffer[i] = inb(APPLESMC_DATA_PORT);
253	}
254
255	/* Read the data port until bit0 is cleared */
256	for (i = 0; i < 16; i++) {
257		udelay(APPLESMC_MIN_WAIT);
258		status = inb(APPLESMC_CMD_PORT);
259		if (!(status & 0x01))
260			break;
261		data = inb(APPLESMC_DATA_PORT);
262	}
263	if (i)
264		pr_warn("flushed %d bytes, last value is: %d\n", i, data);
265
266	return 0;
267}
268
269static int write_smc(u8 cmd, const char *key, const u8 *buffer, u8 len)
270{
271	int i;
272
273	if (send_command(cmd) || send_argument(key)) {
274		pr_warn("%s: write arg fail\n", key);
275		return -EIO;
276	}
277
278	if (send_byte(len, APPLESMC_DATA_PORT)) {
279		pr_warn("%.4s: write len fail\n", key);
280		return -EIO;
281	}
282
283	for (i = 0; i < len; i++) {
284		if (send_byte(buffer[i], APPLESMC_DATA_PORT)) {
285			pr_warn("%s: write data fail\n", key);
286			return -EIO;
287		}
288	}
289
290	return 0;
291}
292
293static int read_register_count(unsigned int *count)
294{
295	__be32 be;
296	int ret;
297
298	ret = read_smc(APPLESMC_READ_CMD, KEY_COUNT_KEY, (u8 *)&be, 4);
299	if (ret)
300		return ret;
301
302	*count = be32_to_cpu(be);
303	return 0;
304}
305
306/*
307 * Serialized I/O
308 *
309 * Returns zero on success or a negative error on failure.
310 * All functions below are concurrency safe - callers should NOT hold lock.
311 */
312
313static int applesmc_read_entry(const struct applesmc_entry *entry,
314			       u8 *buf, u8 len)
315{
316	int ret;
317
318	if (entry->len != len)
319		return -EINVAL;
320	mutex_lock(&smcreg.mutex);
321	ret = read_smc(APPLESMC_READ_CMD, entry->key, buf, len);
322	mutex_unlock(&smcreg.mutex);
323
324	return ret;
325}
326
327static int applesmc_write_entry(const struct applesmc_entry *entry,
328				const u8 *buf, u8 len)
329{
330	int ret;
331
332	if (entry->len != len)
333		return -EINVAL;
334	mutex_lock(&smcreg.mutex);
335	ret = write_smc(APPLESMC_WRITE_CMD, entry->key, buf, len);
336	mutex_unlock(&smcreg.mutex);
337	return ret;
338}
339
340static const struct applesmc_entry *applesmc_get_entry_by_index(int index)
341{
342	struct applesmc_entry *cache = &smcreg.cache[index];
343	u8 key[4], info[6];
344	__be32 be;
345	int ret = 0;
346
347	if (cache->valid)
348		return cache;
349
350	mutex_lock(&smcreg.mutex);
351
352	if (cache->valid)
353		goto out;
354	be = cpu_to_be32(index);
355	ret = read_smc(APPLESMC_GET_KEY_BY_INDEX_CMD, (u8 *)&be, key, 4);
356	if (ret)
357		goto out;
358	ret = read_smc(APPLESMC_GET_KEY_TYPE_CMD, key, info, 6);
359	if (ret)
360		goto out;
361
362	memcpy(cache->key, key, 4);
363	cache->len = info[0];
364	memcpy(cache->type, &info[1], 4);
365	cache->flags = info[5];
366	cache->valid = 1;
367
368out:
369	mutex_unlock(&smcreg.mutex);
370	if (ret)
371		return ERR_PTR(ret);
372	return cache;
373}
374
375static int applesmc_get_lower_bound(unsigned int *lo, const char *key)
376{
377	int begin = 0, end = smcreg.key_count;
378	const struct applesmc_entry *entry;
379
380	while (begin != end) {
381		int middle = begin + (end - begin) / 2;
382		entry = applesmc_get_entry_by_index(middle);
383		if (IS_ERR(entry)) {
384			*lo = 0;
385			return PTR_ERR(entry);
386		}
387		if (strcmp(entry->key, key) < 0)
388			begin = middle + 1;
389		else
390			end = middle;
391	}
392
393	*lo = begin;
394	return 0;
395}
396
397static int applesmc_get_upper_bound(unsigned int *hi, const char *key)
398{
399	int begin = 0, end = smcreg.key_count;
400	const struct applesmc_entry *entry;
401
402	while (begin != end) {
403		int middle = begin + (end - begin) / 2;
404		entry = applesmc_get_entry_by_index(middle);
405		if (IS_ERR(entry)) {
406			*hi = smcreg.key_count;
407			return PTR_ERR(entry);
408		}
409		if (strcmp(key, entry->key) < 0)
410			end = middle;
411		else
412			begin = middle + 1;
413	}
414
415	*hi = begin;
416	return 0;
417}
418
419static const struct applesmc_entry *applesmc_get_entry_by_key(const char *key)
420{
421	int begin, end;
422	int ret;
423
424	ret = applesmc_get_lower_bound(&begin, key);
425	if (ret)
426		return ERR_PTR(ret);
427	ret = applesmc_get_upper_bound(&end, key);
428	if (ret)
429		return ERR_PTR(ret);
430	if (end - begin != 1)
431		return ERR_PTR(-EINVAL);
432
433	return applesmc_get_entry_by_index(begin);
434}
435
436static int applesmc_read_key(const char *key, u8 *buffer, u8 len)
437{
438	const struct applesmc_entry *entry;
439
440	entry = applesmc_get_entry_by_key(key);
441	if (IS_ERR(entry))
442		return PTR_ERR(entry);
443
444	return applesmc_read_entry(entry, buffer, len);
445}
446
447static int applesmc_write_key(const char *key, const u8 *buffer, u8 len)
448{
449	const struct applesmc_entry *entry;
450
451	entry = applesmc_get_entry_by_key(key);
452	if (IS_ERR(entry))
453		return PTR_ERR(entry);
454
455	return applesmc_write_entry(entry, buffer, len);
456}
457
458static int applesmc_has_key(const char *key, bool *value)
459{
460	const struct applesmc_entry *entry;
461
462	entry = applesmc_get_entry_by_key(key);
463	if (IS_ERR(entry) && PTR_ERR(entry) != -EINVAL)
464		return PTR_ERR(entry);
465
466	*value = !IS_ERR(entry);
467	return 0;
468}
469
470/*
471 * applesmc_read_s16 - Read 16-bit signed big endian register
472 */
473static int applesmc_read_s16(const char *key, s16 *value)
474{
475	u8 buffer[2];
476	int ret;
477
478	ret = applesmc_read_key(key, buffer, 2);
479	if (ret)
480		return ret;
481
482	*value = ((s16)buffer[0] << 8) | buffer[1];
483	return 0;
484}
485
486/*
487 * applesmc_device_init - initialize the accelerometer.  Can sleep.
488 */
489static void applesmc_device_init(void)
490{
491	int total;
492	u8 buffer[2];
493
494	if (!smcreg.has_accelerometer)
495		return;
496
497	for (total = INIT_TIMEOUT_MSECS; total > 0; total -= INIT_WAIT_MSECS) {
498		if (!applesmc_read_key(MOTION_SENSOR_KEY, buffer, 2) &&
499				(buffer[0] != 0x00 || buffer[1] != 0x00))
500			return;
501		buffer[0] = 0xe0;
502		buffer[1] = 0x00;
503		applesmc_write_key(MOTION_SENSOR_KEY, buffer, 2);
504		msleep(INIT_WAIT_MSECS);
505	}
506
507	pr_warn("failed to init the device\n");
508}
509
510static int applesmc_init_index(struct applesmc_registers *s)
511{
512	const struct applesmc_entry *entry;
513	unsigned int i;
514
515	if (s->index)
516		return 0;
517
518	s->index = kcalloc(s->temp_count, sizeof(s->index[0]), GFP_KERNEL);
519	if (!s->index)
520		return -ENOMEM;
521
522	for (i = s->temp_begin; i < s->temp_end; i++) {
523		entry = applesmc_get_entry_by_index(i);
524		if (IS_ERR(entry))
525			continue;
526		if (strcmp(entry->type, TEMP_SENSOR_TYPE))
527			continue;
528		s->index[s->index_count++] = entry->key;
529	}
530
531	return 0;
532}
533
534/*
535 * applesmc_init_smcreg_try - Try to initialize register cache. Idempotent.
536 */
537static int applesmc_init_smcreg_try(void)
538{
539	struct applesmc_registers *s = &smcreg;
540	bool left_light_sensor, right_light_sensor;
541	unsigned int count;
542	u8 tmp[1];
543	int ret;
544
545	if (s->init_complete)
546		return 0;
547
548	ret = read_register_count(&count);
549	if (ret)
550		return ret;
551
552	if (s->cache && s->key_count != count) {
553		pr_warn("key count changed from %d to %d\n",
554			s->key_count, count);
555		kfree(s->cache);
556		s->cache = NULL;
557	}
558	s->key_count = count;
559
560	if (!s->cache)
561		s->cache = kcalloc(s->key_count, sizeof(*s->cache), GFP_KERNEL);
562	if (!s->cache)
563		return -ENOMEM;
564
565	ret = applesmc_read_key(FANS_COUNT, tmp, 1);
566	if (ret)
567		return ret;
568	s->fan_count = tmp[0];
569
570	ret = applesmc_get_lower_bound(&s->temp_begin, "T");
571	if (ret)
572		return ret;
573	ret = applesmc_get_lower_bound(&s->temp_end, "U");
574	if (ret)
575		return ret;
576	s->temp_count = s->temp_end - s->temp_begin;
577
578	ret = applesmc_init_index(s);
579	if (ret)
580		return ret;
581
582	ret = applesmc_has_key(LIGHT_SENSOR_LEFT_KEY, &left_light_sensor);
583	if (ret)
584		return ret;
585	ret = applesmc_has_key(LIGHT_SENSOR_RIGHT_KEY, &right_light_sensor);
586	if (ret)
587		return ret;
588	ret = applesmc_has_key(MOTION_SENSOR_KEY, &s->has_accelerometer);
589	if (ret)
590		return ret;
591	ret = applesmc_has_key(BACKLIGHT_KEY, &s->has_key_backlight);
592	if (ret)
593		return ret;
594
595	s->num_light_sensors = left_light_sensor + right_light_sensor;
596	s->init_complete = true;
597
598	pr_info("key=%d fan=%d temp=%d index=%d acc=%d lux=%d kbd=%d\n",
599	       s->key_count, s->fan_count, s->temp_count, s->index_count,
600	       s->has_accelerometer,
601	       s->num_light_sensors,
602	       s->has_key_backlight);
603
604	return 0;
605}
606
607static void applesmc_destroy_smcreg(void)
608{
609	kfree(smcreg.index);
610	smcreg.index = NULL;
611	kfree(smcreg.cache);
612	smcreg.cache = NULL;
613	smcreg.init_complete = false;
614}
615
616/*
617 * applesmc_init_smcreg - Initialize register cache.
618 *
619 * Retries until initialization is successful, or the operation times out.
620 *
621 */
622static int applesmc_init_smcreg(void)
623{
624	int ms, ret;
625
626	for (ms = 0; ms < INIT_TIMEOUT_MSECS; ms += INIT_WAIT_MSECS) {
627		ret = applesmc_init_smcreg_try();
628		if (!ret) {
629			if (ms)
630				pr_info("init_smcreg() took %d ms\n", ms);
631			return 0;
632		}
633		msleep(INIT_WAIT_MSECS);
634	}
635
636	applesmc_destroy_smcreg();
637
638	return ret;
639}
640
641/* Device model stuff */
642static int applesmc_probe(struct platform_device *dev)
643{
644	int ret;
645
646	ret = applesmc_init_smcreg();
647	if (ret)
648		return ret;
649
650	applesmc_device_init();
651
652	return 0;
653}
654
655/* Synchronize device with memorized backlight state */
656static int applesmc_pm_resume(struct device *dev)
657{
658	if (smcreg.has_key_backlight)
659		applesmc_write_key(BACKLIGHT_KEY, backlight_state, 2);
660	return 0;
661}
662
663/* Reinitialize device on resume from hibernation */
664static int applesmc_pm_restore(struct device *dev)
665{
666	applesmc_device_init();
667	return applesmc_pm_resume(dev);
668}
669
670static const struct dev_pm_ops applesmc_pm_ops = {
671	.resume = applesmc_pm_resume,
672	.restore = applesmc_pm_restore,
673};
674
675static struct platform_driver applesmc_driver = {
676	.probe = applesmc_probe,
677	.driver	= {
678		.name = "applesmc",
679		.owner = THIS_MODULE,
680		.pm = &applesmc_pm_ops,
681	},
682};
683
684/*
685 * applesmc_calibrate - Set our "resting" values.  Callers must
686 * hold applesmc_lock.
687 */
688static void applesmc_calibrate(void)
689{
690	applesmc_read_s16(MOTION_SENSOR_X_KEY, &rest_x);
691	applesmc_read_s16(MOTION_SENSOR_Y_KEY, &rest_y);
692	rest_x = -rest_x;
693}
694
695static void applesmc_idev_poll(struct input_polled_dev *dev)
696{
697	struct input_dev *idev = dev->input;
698	s16 x, y;
699
700	if (applesmc_read_s16(MOTION_SENSOR_X_KEY, &x))
701		return;
702	if (applesmc_read_s16(MOTION_SENSOR_Y_KEY, &y))
703		return;
704
705	x = -x;
706	input_report_abs(idev, ABS_X, x - rest_x);
707	input_report_abs(idev, ABS_Y, y - rest_y);
708	input_sync(idev);
709}
710
711/* Sysfs Files */
712
713static ssize_t applesmc_name_show(struct device *dev,
714				   struct device_attribute *attr, char *buf)
715{
716	return snprintf(buf, PAGE_SIZE, "applesmc\n");
717}
718
719static ssize_t applesmc_position_show(struct device *dev,
720				   struct device_attribute *attr, char *buf)
721{
722	int ret;
723	s16 x, y, z;
724
725	ret = applesmc_read_s16(MOTION_SENSOR_X_KEY, &x);
726	if (ret)
727		goto out;
728	ret = applesmc_read_s16(MOTION_SENSOR_Y_KEY, &y);
729	if (ret)
730		goto out;
731	ret = applesmc_read_s16(MOTION_SENSOR_Z_KEY, &z);
732	if (ret)
733		goto out;
734
735out:
736	if (ret)
737		return ret;
738	else
739		return snprintf(buf, PAGE_SIZE, "(%d,%d,%d)\n", x, y, z);
740}
741
742static ssize_t applesmc_light_show(struct device *dev,
743				struct device_attribute *attr, char *sysfsbuf)
744{
745	const struct applesmc_entry *entry;
746	static int data_length;
747	int ret;
748	u8 left = 0, right = 0;
749	u8 buffer[10];
750
751	if (!data_length) {
752		entry = applesmc_get_entry_by_key(LIGHT_SENSOR_LEFT_KEY);
753		if (IS_ERR(entry))
754			return PTR_ERR(entry);
755		if (entry->len > 10)
756			return -ENXIO;
757		data_length = entry->len;
758		pr_info("light sensor data length set to %d\n", data_length);
759	}
760
761	ret = applesmc_read_key(LIGHT_SENSOR_LEFT_KEY, buffer, data_length);
762	/* newer macbooks report a single 10-bit bigendian value */
763	if (data_length == 10) {
764		left = be16_to_cpu(*(__be16 *)(buffer + 6)) >> 2;
765		goto out;
766	}
767	left = buffer[2];
768	if (ret)
769		goto out;
770	ret = applesmc_read_key(LIGHT_SENSOR_RIGHT_KEY, buffer, data_length);
771	right = buffer[2];
772
773out:
774	if (ret)
775		return ret;
776	else
777		return snprintf(sysfsbuf, PAGE_SIZE, "(%d,%d)\n", left, right);
778}
779
780/* Displays sensor key as label */
781static ssize_t applesmc_show_sensor_label(struct device *dev,
782			struct device_attribute *devattr, char *sysfsbuf)
783{
784	const char *key = smcreg.index[to_index(devattr)];
785
786	return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", key);
787}
788
789/* Displays degree Celsius * 1000 */
790static ssize_t applesmc_show_temperature(struct device *dev,
791			struct device_attribute *devattr, char *sysfsbuf)
792{
793	const char *key = smcreg.index[to_index(devattr)];
794	int ret;
795	s16 value;
796	int temp;
797
798	ret = applesmc_read_s16(key, &value);
799	if (ret)
800		return ret;
801
802	temp = 250 * (value >> 6);
803
804	return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", temp);
805}
806
807static ssize_t applesmc_show_fan_speed(struct device *dev,
808				struct device_attribute *attr, char *sysfsbuf)
809{
810	int ret;
811	unsigned int speed = 0;
812	char newkey[5];
813	u8 buffer[2];
814
815	sprintf(newkey, fan_speed_fmt[to_option(attr)], to_index(attr));
816
817	ret = applesmc_read_key(newkey, buffer, 2);
818	speed = ((buffer[0] << 8 | buffer[1]) >> 2);
819
820	if (ret)
821		return ret;
822	else
823		return snprintf(sysfsbuf, PAGE_SIZE, "%u\n", speed);
824}
825
826static ssize_t applesmc_store_fan_speed(struct device *dev,
827					struct device_attribute *attr,
828					const char *sysfsbuf, size_t count)
829{
830	int ret;
831	unsigned long speed;
832	char newkey[5];
833	u8 buffer[2];
834
835	if (kstrtoul(sysfsbuf, 10, &speed) < 0 || speed >= 0x4000)
836		return -EINVAL;		/* Bigger than a 14-bit value */
837
838	sprintf(newkey, fan_speed_fmt[to_option(attr)], to_index(attr));
839
840	buffer[0] = (speed >> 6) & 0xff;
841	buffer[1] = (speed << 2) & 0xff;
842	ret = applesmc_write_key(newkey, buffer, 2);
843
844	if (ret)
845		return ret;
846	else
847		return count;
848}
849
850static ssize_t applesmc_show_fan_manual(struct device *dev,
851			struct device_attribute *attr, char *sysfsbuf)
852{
853	int ret;
854	u16 manual = 0;
855	u8 buffer[2];
856
857	ret = applesmc_read_key(FANS_MANUAL, buffer, 2);
858	manual = ((buffer[0] << 8 | buffer[1]) >> to_index(attr)) & 0x01;
859
860	if (ret)
861		return ret;
862	else
863		return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", manual);
864}
865
866static ssize_t applesmc_store_fan_manual(struct device *dev,
867					 struct device_attribute *attr,
868					 const char *sysfsbuf, size_t count)
869{
870	int ret;
871	u8 buffer[2];
872	unsigned long input;
873	u16 val;
874
875	if (kstrtoul(sysfsbuf, 10, &input) < 0)
876		return -EINVAL;
877
878	ret = applesmc_read_key(FANS_MANUAL, buffer, 2);
879	val = (buffer[0] << 8 | buffer[1]);
880	if (ret)
881		goto out;
882
883	if (input)
884		val = val | (0x01 << to_index(attr));
885	else
886		val = val & ~(0x01 << to_index(attr));
887
888	buffer[0] = (val >> 8) & 0xFF;
889	buffer[1] = val & 0xFF;
890
891	ret = applesmc_write_key(FANS_MANUAL, buffer, 2);
892
893out:
894	if (ret)
895		return ret;
896	else
897		return count;
898}
899
900static ssize_t applesmc_show_fan_position(struct device *dev,
901				struct device_attribute *attr, char *sysfsbuf)
902{
903	int ret;
904	char newkey[5];
905	u8 buffer[17];
906
907	sprintf(newkey, FAN_ID_FMT, to_index(attr));
908
909	ret = applesmc_read_key(newkey, buffer, 16);
910	buffer[16] = 0;
911
912	if (ret)
913		return ret;
914	else
915		return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", buffer+4);
916}
917
918static ssize_t applesmc_calibrate_show(struct device *dev,
919				struct device_attribute *attr, char *sysfsbuf)
920{
921	return snprintf(sysfsbuf, PAGE_SIZE, "(%d,%d)\n", rest_x, rest_y);
922}
923
924static ssize_t applesmc_calibrate_store(struct device *dev,
925	struct device_attribute *attr, const char *sysfsbuf, size_t count)
926{
927	applesmc_calibrate();
928
929	return count;
930}
931
932static void applesmc_backlight_set(struct work_struct *work)
933{
934	applesmc_write_key(BACKLIGHT_KEY, backlight_state, 2);
935}
936static DECLARE_WORK(backlight_work, &applesmc_backlight_set);
937
938static void applesmc_brightness_set(struct led_classdev *led_cdev,
939						enum led_brightness value)
940{
941	int ret;
942
943	backlight_state[0] = value;
944	ret = queue_work(applesmc_led_wq, &backlight_work);
945
946	if (debug && (!ret))
947		dev_dbg(led_cdev->dev, "work was already on the queue.\n");
948}
949
950static ssize_t applesmc_key_count_show(struct device *dev,
951				struct device_attribute *attr, char *sysfsbuf)
952{
953	int ret;
954	u8 buffer[4];
955	u32 count;
956
957	ret = applesmc_read_key(KEY_COUNT_KEY, buffer, 4);
958	count = ((u32)buffer[0]<<24) + ((u32)buffer[1]<<16) +
959						((u32)buffer[2]<<8) + buffer[3];
960
961	if (ret)
962		return ret;
963	else
964		return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", count);
965}
966
967static ssize_t applesmc_key_at_index_read_show(struct device *dev,
968				struct device_attribute *attr, char *sysfsbuf)
969{
970	const struct applesmc_entry *entry;
971	int ret;
972
973	entry = applesmc_get_entry_by_index(key_at_index);
974	if (IS_ERR(entry))
975		return PTR_ERR(entry);
976	ret = applesmc_read_entry(entry, sysfsbuf, entry->len);
977	if (ret)
978		return ret;
979
980	return entry->len;
981}
982
983static ssize_t applesmc_key_at_index_data_length_show(struct device *dev,
984				struct device_attribute *attr, char *sysfsbuf)
985{
986	const struct applesmc_entry *entry;
987
988	entry = applesmc_get_entry_by_index(key_at_index);
989	if (IS_ERR(entry))
990		return PTR_ERR(entry);
991
992	return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", entry->len);
993}
994
995static ssize_t applesmc_key_at_index_type_show(struct device *dev,
996				struct device_attribute *attr, char *sysfsbuf)
997{
998	const struct applesmc_entry *entry;
999
1000	entry = applesmc_get_entry_by_index(key_at_index);
1001	if (IS_ERR(entry))
1002		return PTR_ERR(entry);
1003
1004	return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", entry->type);
1005}
1006
1007static ssize_t applesmc_key_at_index_name_show(struct device *dev,
1008				struct device_attribute *attr, char *sysfsbuf)
1009{
1010	const struct applesmc_entry *entry;
1011
1012	entry = applesmc_get_entry_by_index(key_at_index);
1013	if (IS_ERR(entry))
1014		return PTR_ERR(entry);
1015
1016	return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", entry->key);
1017}
1018
1019static ssize_t applesmc_key_at_index_show(struct device *dev,
1020				struct device_attribute *attr, char *sysfsbuf)
1021{
1022	return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", key_at_index);
1023}
1024
1025static ssize_t applesmc_key_at_index_store(struct device *dev,
1026	struct device_attribute *attr, const char *sysfsbuf, size_t count)
1027{
1028	unsigned long newkey;
1029
1030	if (kstrtoul(sysfsbuf, 10, &newkey) < 0
1031	    || newkey >= smcreg.key_count)
1032		return -EINVAL;
1033
1034	key_at_index = newkey;
1035	return count;
1036}
1037
1038static struct led_classdev applesmc_backlight = {
1039	.name			= "smc::kbd_backlight",
1040	.default_trigger	= "nand-disk",
1041	.brightness_set		= applesmc_brightness_set,
1042};
1043
1044static struct applesmc_node_group info_group[] = {
1045	{ "name", applesmc_name_show },
1046	{ "key_count", applesmc_key_count_show },
1047	{ "key_at_index", applesmc_key_at_index_show, applesmc_key_at_index_store },
1048	{ "key_at_index_name", applesmc_key_at_index_name_show },
1049	{ "key_at_index_type", applesmc_key_at_index_type_show },
1050	{ "key_at_index_data_length", applesmc_key_at_index_data_length_show },
1051	{ "key_at_index_data", applesmc_key_at_index_read_show },
1052	{ }
1053};
1054
1055static struct applesmc_node_group accelerometer_group[] = {
1056	{ "position", applesmc_position_show },
1057	{ "calibrate", applesmc_calibrate_show, applesmc_calibrate_store },
1058	{ }
1059};
1060
1061static struct applesmc_node_group light_sensor_group[] = {
1062	{ "light", applesmc_light_show },
1063	{ }
1064};
1065
1066static struct applesmc_node_group fan_group[] = {
1067	{ "fan%d_label", applesmc_show_fan_position },
1068	{ "fan%d_input", applesmc_show_fan_speed, NULL, 0 },
1069	{ "fan%d_min", applesmc_show_fan_speed, applesmc_store_fan_speed, 1 },
1070	{ "fan%d_max", applesmc_show_fan_speed, NULL, 2 },
1071	{ "fan%d_safe", applesmc_show_fan_speed, NULL, 3 },
1072	{ "fan%d_output", applesmc_show_fan_speed, applesmc_store_fan_speed, 4 },
1073	{ "fan%d_manual", applesmc_show_fan_manual, applesmc_store_fan_manual },
1074	{ }
1075};
1076
1077static struct applesmc_node_group temp_group[] = {
1078	{ "temp%d_label", applesmc_show_sensor_label },
1079	{ "temp%d_input", applesmc_show_temperature },
1080	{ }
1081};
1082
1083/* Module stuff */
1084
1085/*
1086 * applesmc_destroy_nodes - remove files and free associated memory
1087 */
1088static void applesmc_destroy_nodes(struct applesmc_node_group *groups)
1089{
1090	struct applesmc_node_group *grp;
1091	struct applesmc_dev_attr *node;
1092
1093	for (grp = groups; grp->nodes; grp++) {
1094		for (node = grp->nodes; node->sda.dev_attr.attr.name; node++)
1095			sysfs_remove_file(&pdev->dev.kobj,
1096					  &node->sda.dev_attr.attr);
1097		kfree(grp->nodes);
1098		grp->nodes = NULL;
1099	}
1100}
1101
1102/*
1103 * applesmc_create_nodes - create a two-dimensional group of sysfs files
1104 */
1105static int applesmc_create_nodes(struct applesmc_node_group *groups, int num)
1106{
1107	struct applesmc_node_group *grp;
1108	struct applesmc_dev_attr *node;
1109	struct attribute *attr;
1110	int ret, i;
1111
1112	for (grp = groups; grp->format; grp++) {
1113		grp->nodes = kcalloc(num + 1, sizeof(*node), GFP_KERNEL);
1114		if (!grp->nodes) {
1115			ret = -ENOMEM;
1116			goto out;
1117		}
1118		for (i = 0; i < num; i++) {
1119			node = &grp->nodes[i];
1120			sprintf(node->name, grp->format, i + 1);
1121			node->sda.index = (grp->option << 16) | (i & 0xffff);
1122			node->sda.dev_attr.show = grp->show;
1123			node->sda.dev_attr.store = grp->store;
1124			attr = &node->sda.dev_attr.attr;
1125			sysfs_attr_init(attr);
1126			attr->name = node->name;
1127			attr->mode = S_IRUGO | (grp->store ? S_IWUSR : 0);
1128			ret = sysfs_create_file(&pdev->dev.kobj, attr);
1129			if (ret) {
1130				attr->name = NULL;
1131				goto out;
1132			}
1133		}
1134	}
1135
1136	return 0;
1137out:
1138	applesmc_destroy_nodes(groups);
1139	return ret;
1140}
1141
1142/* Create accelerometer ressources */
1143static int applesmc_create_accelerometer(void)
1144{
1145	struct input_dev *idev;
1146	int ret;
1147
1148	if (!smcreg.has_accelerometer)
1149		return 0;
1150
1151	ret = applesmc_create_nodes(accelerometer_group, 1);
1152	if (ret)
1153		goto out;
1154
1155	applesmc_idev = input_allocate_polled_device();
1156	if (!applesmc_idev) {
1157		ret = -ENOMEM;
1158		goto out_sysfs;
1159	}
1160
1161	applesmc_idev->poll = applesmc_idev_poll;
1162	applesmc_idev->poll_interval = APPLESMC_POLL_INTERVAL;
1163
1164	/* initial calibrate for the input device */
1165	applesmc_calibrate();
1166
1167	/* initialize the input device */
1168	idev = applesmc_idev->input;
1169	idev->name = "applesmc";
1170	idev->id.bustype = BUS_HOST;
1171	idev->dev.parent = &pdev->dev;
1172	idev->evbit[0] = BIT_MASK(EV_ABS);
1173	input_set_abs_params(idev, ABS_X,
1174			-256, 256, APPLESMC_INPUT_FUZZ, APPLESMC_INPUT_FLAT);
1175	input_set_abs_params(idev, ABS_Y,
1176			-256, 256, APPLESMC_INPUT_FUZZ, APPLESMC_INPUT_FLAT);
1177
1178	ret = input_register_polled_device(applesmc_idev);
1179	if (ret)
1180		goto out_idev;
1181
1182	return 0;
1183
1184out_idev:
1185	input_free_polled_device(applesmc_idev);
1186
1187out_sysfs:
1188	applesmc_destroy_nodes(accelerometer_group);
1189
1190out:
1191	pr_warn("driver init failed (ret=%d)!\n", ret);
1192	return ret;
1193}
1194
1195/* Release all ressources used by the accelerometer */
1196static void applesmc_release_accelerometer(void)
1197{
1198	if (!smcreg.has_accelerometer)
1199		return;
1200	input_unregister_polled_device(applesmc_idev);
1201	input_free_polled_device(applesmc_idev);
1202	applesmc_destroy_nodes(accelerometer_group);
1203}
1204
1205static int applesmc_create_light_sensor(void)
1206{
1207	if (!smcreg.num_light_sensors)
1208		return 0;
1209	return applesmc_create_nodes(light_sensor_group, 1);
1210}
1211
1212static void applesmc_release_light_sensor(void)
1213{
1214	if (!smcreg.num_light_sensors)
1215		return;
1216	applesmc_destroy_nodes(light_sensor_group);
1217}
1218
1219static int applesmc_create_key_backlight(void)
1220{
1221	if (!smcreg.has_key_backlight)
1222		return 0;
1223	applesmc_led_wq = create_singlethread_workqueue("applesmc-led");
1224	if (!applesmc_led_wq)
1225		return -ENOMEM;
1226	return led_classdev_register(&pdev->dev, &applesmc_backlight);
1227}
1228
1229static void applesmc_release_key_backlight(void)
1230{
1231	if (!smcreg.has_key_backlight)
1232		return;
1233	led_classdev_unregister(&applesmc_backlight);
1234	destroy_workqueue(applesmc_led_wq);
1235}
1236
1237static int applesmc_dmi_match(const struct dmi_system_id *id)
1238{
1239	return 1;
1240}
1241
1242/*
1243 * Note that DMI_MATCH(...,"MacBook") will match "MacBookPro1,1".
1244 * So we need to put "Apple MacBook Pro" before "Apple MacBook".
1245 */
1246static __initdata struct dmi_system_id applesmc_whitelist[] = {
1247	{ applesmc_dmi_match, "Apple MacBook Air", {
1248	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
1249	  DMI_MATCH(DMI_PRODUCT_NAME, "MacBookAir") },
1250	},
1251	{ applesmc_dmi_match, "Apple MacBook Pro", {
1252	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
1253	  DMI_MATCH(DMI_PRODUCT_NAME, "MacBookPro") },
1254	},
1255	{ applesmc_dmi_match, "Apple MacBook", {
1256	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
1257	  DMI_MATCH(DMI_PRODUCT_NAME, "MacBook") },
1258	},
1259	{ applesmc_dmi_match, "Apple Macmini", {
1260	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
1261	  DMI_MATCH(DMI_PRODUCT_NAME, "Macmini") },
1262	},
1263	{ applesmc_dmi_match, "Apple MacPro", {
1264	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
1265	  DMI_MATCH(DMI_PRODUCT_NAME, "MacPro") },
1266	},
1267	{ applesmc_dmi_match, "Apple iMac", {
1268	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
1269	  DMI_MATCH(DMI_PRODUCT_NAME, "iMac") },
1270	},
1271	{ .ident = NULL }
1272};
1273
1274static int __init applesmc_init(void)
1275{
1276	int ret;
1277
1278	if (!dmi_check_system(applesmc_whitelist)) {
1279		pr_warn("supported laptop not found!\n");
1280		ret = -ENODEV;
1281		goto out;
1282	}
1283
1284	if (!request_region(APPLESMC_DATA_PORT, APPLESMC_NR_PORTS,
1285								"applesmc")) {
1286		ret = -ENXIO;
1287		goto out;
1288	}
1289
1290	ret = platform_driver_register(&applesmc_driver);
1291	if (ret)
1292		goto out_region;
1293
1294	pdev = platform_device_register_simple("applesmc", APPLESMC_DATA_PORT,
1295					       NULL, 0);
1296	if (IS_ERR(pdev)) {
1297		ret = PTR_ERR(pdev);
1298		goto out_driver;
1299	}
1300
1301	/* create register cache */
1302	ret = applesmc_init_smcreg();
1303	if (ret)
1304		goto out_device;
1305
1306	ret = applesmc_create_nodes(info_group, 1);
1307	if (ret)
1308		goto out_smcreg;
1309
1310	ret = applesmc_create_nodes(fan_group, smcreg.fan_count);
1311	if (ret)
1312		goto out_info;
1313
1314	ret = applesmc_create_nodes(temp_group, smcreg.index_count);
1315	if (ret)
1316		goto out_fans;
1317
1318	ret = applesmc_create_accelerometer();
1319	if (ret)
1320		goto out_temperature;
1321
1322	ret = applesmc_create_light_sensor();
1323	if (ret)
1324		goto out_accelerometer;
1325
1326	ret = applesmc_create_key_backlight();
1327	if (ret)
1328		goto out_light_sysfs;
1329
1330	hwmon_dev = hwmon_device_register(&pdev->dev);
1331	if (IS_ERR(hwmon_dev)) {
1332		ret = PTR_ERR(hwmon_dev);
1333		goto out_light_ledclass;
1334	}
1335
1336	return 0;
1337
1338out_light_ledclass:
1339	applesmc_release_key_backlight();
1340out_light_sysfs:
1341	applesmc_release_light_sensor();
1342out_accelerometer:
1343	applesmc_release_accelerometer();
1344out_temperature:
1345	applesmc_destroy_nodes(temp_group);
1346out_fans:
1347	applesmc_destroy_nodes(fan_group);
1348out_info:
1349	applesmc_destroy_nodes(info_group);
1350out_smcreg:
1351	applesmc_destroy_smcreg();
1352out_device:
1353	platform_device_unregister(pdev);
1354out_driver:
1355	platform_driver_unregister(&applesmc_driver);
1356out_region:
1357	release_region(APPLESMC_DATA_PORT, APPLESMC_NR_PORTS);
1358out:
1359	pr_warn("driver init failed (ret=%d)!\n", ret);
1360	return ret;
1361}
1362
1363static void __exit applesmc_exit(void)
1364{
1365	hwmon_device_unregister(hwmon_dev);
1366	applesmc_release_key_backlight();
1367	applesmc_release_light_sensor();
1368	applesmc_release_accelerometer();
1369	applesmc_destroy_nodes(temp_group);
1370	applesmc_destroy_nodes(fan_group);
1371	applesmc_destroy_nodes(info_group);
1372	applesmc_destroy_smcreg();
1373	platform_device_unregister(pdev);
1374	platform_driver_unregister(&applesmc_driver);
1375	release_region(APPLESMC_DATA_PORT, APPLESMC_NR_PORTS);
1376}
1377
1378module_init(applesmc_init);
1379module_exit(applesmc_exit);
1380
1381MODULE_AUTHOR("Nicolas Boichat");
1382MODULE_DESCRIPTION("Apple SMC");
1383MODULE_LICENSE("GPL v2");
1384MODULE_DEVICE_TABLE(dmi, applesmc_whitelist);
1385