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