applesmc.c 31.3 KB
Newer Older
1 2 3 4 5 6
/*
 * drivers/hwmon/applesmc.c - driver for Apple's SMC (accelerometer, temperature
 * sensors, fan control, keyboard backlight control) used in Intel-based Apple
 * computers.
 *
 * Copyright (C) 2007 Nicolas Boichat <nicolas@boichat.ch>
7
 * Copyright (C) 2010 Henrik Rydberg <rydberg@euromail.se>
8 9 10
 *
 * Based on hdaps.c driver:
 * Copyright (C) 2005 Robert Love <rml@novell.com>
11
 * Copyright (C) 2005 Jesper Juhl <jj@chaosbits.net>
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *
 * Fan control based on smcFanControl:
 * Copyright (C) 2006 Hendrik Holtmann <holtmann@mac.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License v2 as published by the
 * Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

30 31
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

32 33
#include <linux/delay.h>
#include <linux/platform_device.h>
34
#include <linux/input-polldev.h>
35
#include <linux/kernel.h>
36
#include <linux/slab.h>
37 38 39 40 41
#include <linux/module.h>
#include <linux/timer.h>
#include <linux/dmi.h>
#include <linux/mutex.h>
#include <linux/hwmon-sysfs.h>
42
#include <linux/io.h>
43 44 45 46 47 48 49 50 51 52 53 54 55
#include <linux/leds.h>
#include <linux/hwmon.h>
#include <linux/workqueue.h>

/* data port used by Apple SMC */
#define APPLESMC_DATA_PORT	0x300
/* command/status port used by Apple SMC */
#define APPLESMC_CMD_PORT	0x304

#define APPLESMC_NR_PORTS	32 /* 0x300-0x31f */

#define APPLESMC_MAX_DATA_LENGTH 32

56
/* wait up to 32 ms for a status change. */
57
#define APPLESMC_MIN_WAIT	0x0010
58 59
#define APPLESMC_MAX_WAIT	0x8000

60 61 62 63 64 65 66 67
#define APPLESMC_STATUS_MASK	0x0f
#define APPLESMC_READ_CMD	0x10
#define APPLESMC_WRITE_CMD	0x11
#define APPLESMC_GET_KEY_BY_INDEX_CMD	0x12
#define APPLESMC_GET_KEY_TYPE_CMD	0x13

#define KEY_COUNT_KEY		"#KEY" /* r-o ui32 */

68 69
#define LIGHT_SENSOR_LEFT_KEY	"ALV0" /* r-o {alv (6-10 bytes) */
#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 75 76 77 78 79 80

#define MOTION_SENSOR_X_KEY	"MO_X" /* r-o sp78 (2 bytes) */
#define MOTION_SENSOR_Y_KEY	"MO_Y" /* r-o sp78 (2 bytes) */
#define MOTION_SENSOR_Z_KEY	"MO_Z" /* r-o sp78 (2 bytes) */
#define MOTION_SENSOR_KEY	"MOCN" /* r/w ui16 */

#define FANS_COUNT		"FNum" /* r-o ui8 */
#define FANS_MANUAL		"FS! " /* r-w ui16 */
81
#define FAN_ID_FMT		"F%dID" /* r-o char[16] */
82 83

/* List of keys used to read/write fan speeds */
84 85 86 87 88 89
static const char *const fan_speed_fmt[] = {
	"F%dAc",		/* actual speed */
	"F%dMn",		/* minimum speed (rw) */
	"F%dMx",		/* maximum speed */
	"F%dSf",		/* safe speed - not all models */
	"F%dTg",		/* target speed (manual: rw) */
90 91 92 93 94
};

#define INIT_TIMEOUT_MSECS	5000	/* wait up to 5s for device init ... */
#define INIT_WAIT_MSECS		50	/* ... in 50ms increments */

95
#define APPLESMC_POLL_INTERVAL	50	/* msecs */
96 97 98
#define APPLESMC_INPUT_FUZZ	4	/* input event threshold */
#define APPLESMC_INPUT_FLAT	4

99 100
#define to_index(attr) (to_sensor_dev_attr(attr)->index & 0xffff)
#define to_option(attr) (to_sensor_dev_attr(attr)->index >> 16)
101 102 103 104 105 106 107 108 109 110 111 112

/* Dynamic device node attributes */
struct applesmc_dev_attr {
	struct sensor_device_attribute sda;	/* hwmon attributes */
	char name[32];				/* room for node file name */
};

/* Dynamic device node group */
struct applesmc_node_group {
	char *format;				/* format string */
	void *show;				/* show function */
	void *store;				/* store function */
113
	int option;				/* function argument */
114 115 116
	struct applesmc_dev_attr *nodes;	/* dynamic node array */
};

117 118 119 120 121 122 123 124 125 126 127 128 129
/* AppleSMC entry - cached register information */
struct applesmc_entry {
	char key[5];		/* four-letter key code */
	u8 valid;		/* set when entry is successfully read once */
	u8 len;			/* bounded by APPLESMC_MAX_DATA_LENGTH */
	char type[5];		/* four-letter type code */
	u8 flags;		/* 0x10: func; 0x40: write; 0x80: read */
};

/* Register lookup and registers common to all SMCs */
static struct applesmc_registers {
	struct mutex mutex;		/* register read/write mutex */
	unsigned int key_count;		/* number of SMC registers */
130
	unsigned int fan_count;		/* number of fans */
131 132 133
	unsigned int temp_count;	/* number of temperature registers */
	unsigned int temp_begin;	/* temperature lower index bound */
	unsigned int temp_end;		/* temperature upper index bound */
134 135 136
	int num_light_sensors;		/* number of light sensors */
	bool has_accelerometer;		/* has motion sensor */
	bool has_key_backlight;		/* has keyboard backlight */
137 138 139 140 141 142
	bool init_complete;		/* true when fully initialized */
	struct applesmc_entry *cache;	/* cached key entries */
} smcreg = {
	.mutex = __MUTEX_INITIALIZER(smcreg.mutex),
};

143 144 145 146
static const int debug;
static struct platform_device *pdev;
static s16 rest_x;
static s16 rest_y;
147 148
static u8 backlight_state[2];

149
static struct device *hwmon_dev;
150
static struct input_polled_dev *applesmc_idev;
151 152 153 154 155 156 157 158 159 160

/*
 * Last index written to key_at_index sysfs file, and value to use for all other
 * key_at_index_* sysfs files.
 */
static unsigned int key_at_index;

static struct workqueue_struct *applesmc_led_wq;

/*
161
 * __wait_status - Wait up to 32ms for the status port to get a certain value
162 163 164 165 166
 * (masked with 0x0f), returning zero if the value is obtained.  Callers must
 * hold applesmc_lock.
 */
static int __wait_status(u8 val)
{
167
	int us;
168 169 170

	val = val & APPLESMC_STATUS_MASK;

171 172
	for (us = APPLESMC_MIN_WAIT; us < APPLESMC_MAX_WAIT; us <<= 1) {
		udelay(us);
173
		if ((inb(APPLESMC_CMD_PORT) & APPLESMC_STATUS_MASK) == val)
174 175 176 177 178 179
			return 0;
	}

	return -EIO;
}

180 181 182 183 184 185 186
/*
 * special treatment of command port - on newer macbooks, it seems necessary
 * to resend the command byte before polling the status again. Callers must
 * hold applesmc_lock.
 */
static int send_command(u8 cmd)
{
187 188
	int us;
	for (us = APPLESMC_MIN_WAIT; us < APPLESMC_MAX_WAIT; us <<= 1) {
189
		outb(cmd, APPLESMC_CMD_PORT);
190
		udelay(us);
191 192 193 194 195 196
		if ((inb(APPLESMC_CMD_PORT) & APPLESMC_STATUS_MASK) == 0x0c)
			return 0;
	}
	return -EIO;
}

197
static int send_argument(const char *key)
198 199 200 201 202 203 204 205
{
	int i;

	for (i = 0; i < 4; i++) {
		outb(key[i], APPLESMC_DATA_PORT);
		if (__wait_status(0x04))
			return -EIO;
	}
206 207 208 209 210 211 212 213
	return 0;
}

static int read_smc(u8 cmd, const char *key, u8 *buffer, u8 len)
{
	int i;

	if (send_command(cmd) || send_argument(key)) {
214
		pr_warn("%.4s: read arg fail\n", key);
215 216
		return -EIO;
	}
217 218 219 220

	outb(len, APPLESMC_DATA_PORT);

	for (i = 0; i < len; i++) {
221
		if (__wait_status(0x05)) {
222
			pr_warn("%.4s: read data fail\n", key);
223
			return -EIO;
224
		}
225 226 227 228 229 230
		buffer[i] = inb(APPLESMC_DATA_PORT);
	}

	return 0;
}

231
static int write_smc(u8 cmd, const char *key, const u8 *buffer, u8 len)
232 233 234
{
	int i;

235 236
	if (send_command(cmd) || send_argument(key)) {
		pr_warn("%s: write arg fail\n", key);
237 238 239 240 241 242
		return -EIO;
	}

	outb(len, APPLESMC_DATA_PORT);

	for (i = 0; i < len; i++) {
243 244
		if (__wait_status(0x04)) {
			pr_warn("%s: write data fail\n", key);
245
			return -EIO;
246
		}
247 248 249 250 251 252
		outb(buffer[i], APPLESMC_DATA_PORT);
	}

	return 0;
}

253 254 255 256 257 258 259 260 261 262 263 264 265
static int read_register_count(unsigned int *count)
{
	__be32 be;
	int ret;

	ret = read_smc(APPLESMC_READ_CMD, KEY_COUNT_KEY, (u8 *)&be, 4);
	if (ret)
		return ret;

	*count = be32_to_cpu(be);
	return 0;
}

266
/*
267 268 269 270
 * Serialized I/O
 *
 * Returns zero on success or a negative error on failure.
 * All functions below are concurrency safe - callers should NOT hold lock.
271
 */
272 273 274

static int applesmc_read_entry(const struct applesmc_entry *entry,
			       u8 *buf, u8 len)
275
{
276
	int ret;
277

278 279 280 281 282
	if (entry->len != len)
		return -EINVAL;
	mutex_lock(&smcreg.mutex);
	ret = read_smc(APPLESMC_READ_CMD, entry->key, buf, len);
	mutex_unlock(&smcreg.mutex);
283

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
	return ret;
}

static int applesmc_write_entry(const struct applesmc_entry *entry,
				const u8 *buf, u8 len)
{
	int ret;

	if (entry->len != len)
		return -EINVAL;
	mutex_lock(&smcreg.mutex);
	ret = write_smc(APPLESMC_WRITE_CMD, entry->key, buf, len);
	mutex_unlock(&smcreg.mutex);
	return ret;
}

static const struct applesmc_entry *applesmc_get_entry_by_index(int index)
{
	struct applesmc_entry *cache = &smcreg.cache[index];
	u8 key[4], info[6];
	__be32 be;
	int ret = 0;

	if (cache->valid)
		return cache;

	mutex_lock(&smcreg.mutex);

	if (cache->valid)
		goto out;
	be = cpu_to_be32(index);
	ret = read_smc(APPLESMC_GET_KEY_BY_INDEX_CMD, (u8 *)&be, key, 4);
	if (ret)
		goto out;
	ret = read_smc(APPLESMC_GET_KEY_TYPE_CMD, key, info, 6);
	if (ret)
		goto out;

	memcpy(cache->key, key, 4);
	cache->len = info[0];
	memcpy(cache->type, &info[1], 4);
	cache->flags = info[5];
	cache->valid = 1;

out:
	mutex_unlock(&smcreg.mutex);
	if (ret)
		return ERR_PTR(ret);
	return cache;
}

static int applesmc_get_lower_bound(unsigned int *lo, const char *key)
{
	int begin = 0, end = smcreg.key_count;
	const struct applesmc_entry *entry;

	while (begin != end) {
		int middle = begin + (end - begin) / 2;
		entry = applesmc_get_entry_by_index(middle);
343 344
		if (IS_ERR(entry)) {
			*lo = 0;
345
			return PTR_ERR(entry);
346
		}
347 348 349 350
		if (strcmp(entry->key, key) < 0)
			begin = middle + 1;
		else
			end = middle;
351 352
	}

353 354 355
	*lo = begin;
	return 0;
}
356

357 358 359 360 361 362 363 364
static int applesmc_get_upper_bound(unsigned int *hi, const char *key)
{
	int begin = 0, end = smcreg.key_count;
	const struct applesmc_entry *entry;

	while (begin != end) {
		int middle = begin + (end - begin) / 2;
		entry = applesmc_get_entry_by_index(middle);
365 366
		if (IS_ERR(entry)) {
			*hi = smcreg.key_count;
367
			return PTR_ERR(entry);
368
		}
369 370 371 372
		if (strcmp(key, entry->key) < 0)
			end = middle;
		else
			begin = middle + 1;
373 374
	}

375
	*hi = begin;
376 377 378
	return 0;
}

379
static const struct applesmc_entry *applesmc_get_entry_by_key(const char *key)
380
{
381 382
	int begin, end;
	int ret;
383

384 385 386 387 388 389 390 391
	ret = applesmc_get_lower_bound(&begin, key);
	if (ret)
		return ERR_PTR(ret);
	ret = applesmc_get_upper_bound(&end, key);
	if (ret)
		return ERR_PTR(ret);
	if (end - begin != 1)
		return ERR_PTR(-EINVAL);
392

393 394
	return applesmc_get_entry_by_index(begin);
}
395

396 397 398
static int applesmc_read_key(const char *key, u8 *buffer, u8 len)
{
	const struct applesmc_entry *entry;
399

400 401 402
	entry = applesmc_get_entry_by_key(key);
	if (IS_ERR(entry))
		return PTR_ERR(entry);
403

404 405 406 407 408 409 410 411 412 413 414 415
	return applesmc_read_entry(entry, buffer, len);
}

static int applesmc_write_key(const char *key, const u8 *buffer, u8 len)
{
	const struct applesmc_entry *entry;

	entry = applesmc_get_entry_by_key(key);
	if (IS_ERR(entry))
		return PTR_ERR(entry);

	return applesmc_write_entry(entry, buffer, len);
416 417
}

418 419 420 421 422 423 424 425 426 427 428 429
static int applesmc_has_key(const char *key, bool *value)
{
	const struct applesmc_entry *entry;

	entry = applesmc_get_entry_by_key(key);
	if (IS_ERR(entry) && PTR_ERR(entry) != -EINVAL)
		return PTR_ERR(entry);

	*value = !IS_ERR(entry);
	return 0;
}

430
/*
431
 * applesmc_read_s16 - Read 16-bit signed big endian register
432
 */
433
static int applesmc_read_s16(const char *key, s16 *value)
434 435 436 437
{
	u8 buffer[2];
	int ret;

438 439 440
	ret = applesmc_read_key(key, buffer, 2);
	if (ret)
		return ret;
441 442

	*value = ((s16)buffer[0] << 8) | buffer[1];
443
	return 0;
444 445 446
}

/*
447
 * applesmc_device_init - initialize the accelerometer.  Can sleep.
448
 */
449
static void applesmc_device_init(void)
450
{
451
	int total;
452 453
	u8 buffer[2];

454
	if (!smcreg.has_accelerometer)
455
		return;
456 457 458

	for (total = INIT_TIMEOUT_MSECS; total > 0; total -= INIT_WAIT_MSECS) {
		if (!applesmc_read_key(MOTION_SENSOR_KEY, buffer, 2) &&
459
				(buffer[0] != 0x00 || buffer[1] != 0x00))
460
			return;
461 462 463 464 465 466
		buffer[0] = 0xe0;
		buffer[1] = 0x00;
		applesmc_write_key(MOTION_SENSOR_KEY, buffer, 2);
		msleep(INIT_WAIT_MSECS);
	}

467
	pr_warn("failed to init the device\n");
468 469
}

470 471 472 473 474 475
/*
 * applesmc_init_smcreg_try - Try to initialize register cache. Idempotent.
 */
static int applesmc_init_smcreg_try(void)
{
	struct applesmc_registers *s = &smcreg;
476
	bool left_light_sensor, right_light_sensor;
477
	u8 tmp[1];
478 479 480 481 482 483 484 485 486 487 488 489 490 491
	int ret;

	if (s->init_complete)
		return 0;

	ret = read_register_count(&s->key_count);
	if (ret)
		return ret;

	if (!s->cache)
		s->cache = kcalloc(s->key_count, sizeof(*s->cache), GFP_KERNEL);
	if (!s->cache)
		return -ENOMEM;

492 493 494 495 496
	ret = applesmc_read_key(FANS_COUNT, tmp, 1);
	if (ret)
		return ret;
	s->fan_count = tmp[0];

497 498 499 500 501 502 503 504
	ret = applesmc_get_lower_bound(&s->temp_begin, "T");
	if (ret)
		return ret;
	ret = applesmc_get_lower_bound(&s->temp_end, "U");
	if (ret)
		return ret;
	s->temp_count = s->temp_end - s->temp_begin;

505 506 507 508 509 510 511 512 513 514 515 516 517 518
	ret = applesmc_has_key(LIGHT_SENSOR_LEFT_KEY, &left_light_sensor);
	if (ret)
		return ret;
	ret = applesmc_has_key(LIGHT_SENSOR_RIGHT_KEY, &right_light_sensor);
	if (ret)
		return ret;
	ret = applesmc_has_key(MOTION_SENSOR_KEY, &s->has_accelerometer);
	if (ret)
		return ret;
	ret = applesmc_has_key(BACKLIGHT_KEY, &s->has_key_backlight);
	if (ret)
		return ret;

	s->num_light_sensors = left_light_sensor + right_light_sensor;
519 520
	s->init_complete = true;

521 522
	pr_info("key=%d fan=%d temp=%d acc=%d lux=%d kbd=%d\n",
	       s->key_count, s->fan_count, s->temp_count,
523 524 525
	       s->has_accelerometer,
	       s->num_light_sensors,
	       s->has_key_backlight);
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

	return 0;
}

/*
 * applesmc_init_smcreg - Initialize register cache.
 *
 * Retries until initialization is successful, or the operation times out.
 *
 */
static int applesmc_init_smcreg(void)
{
	int ms, ret;

	for (ms = 0; ms < INIT_TIMEOUT_MSECS; ms += INIT_WAIT_MSECS) {
		ret = applesmc_init_smcreg_try();
		if (!ret) {
			if (ms)
				pr_info("init_smcreg() took %d ms\n", ms);
			return 0;
		}
		msleep(INIT_WAIT_MSECS);
	}

	kfree(smcreg.cache);
	smcreg.cache = NULL;

	return ret;
}

static void applesmc_destroy_smcreg(void)
{
	kfree(smcreg.cache);
	smcreg.cache = NULL;
	smcreg.init_complete = false;
}

563 564 565
/* Device model stuff */
static int applesmc_probe(struct platform_device *dev)
{
566 567 568 569 570 571
	int ret;

	ret = applesmc_init_smcreg();
	if (ret)
		return ret;

572
	applesmc_device_init();
573 574 575 576

	return 0;
}

577 578 579
/* Synchronize device with memorized backlight state */
static int applesmc_pm_resume(struct device *dev)
{
580
	if (smcreg.has_key_backlight)
581 582 583 584 585 586
		applesmc_write_key(BACKLIGHT_KEY, backlight_state, 2);
	return 0;
}

/* Reinitialize device on resume from hibernation */
static int applesmc_pm_restore(struct device *dev)
587
{
588
	applesmc_device_init();
589
	return applesmc_pm_resume(dev);
590 591
}

592
static const struct dev_pm_ops applesmc_pm_ops = {
593 594 595 596
	.resume = applesmc_pm_resume,
	.restore = applesmc_pm_restore,
};

597 598 599 600 601
static struct platform_driver applesmc_driver = {
	.probe = applesmc_probe,
	.driver	= {
		.name = "applesmc",
		.owner = THIS_MODULE,
602
		.pm = &applesmc_pm_ops,
603 604 605 606 607 608 609 610 611
	},
};

/*
 * applesmc_calibrate - Set our "resting" values.  Callers must
 * hold applesmc_lock.
 */
static void applesmc_calibrate(void)
{
612 613
	applesmc_read_s16(MOTION_SENSOR_X_KEY, &rest_x);
	applesmc_read_s16(MOTION_SENSOR_Y_KEY, &rest_y);
614 615 616
	rest_x = -rest_x;
}

617
static void applesmc_idev_poll(struct input_polled_dev *dev)
618
{
619
	struct input_dev *idev = dev->input;
620 621
	s16 x, y;

622
	if (applesmc_read_s16(MOTION_SENSOR_X_KEY, &x))
623
		return;
624
	if (applesmc_read_s16(MOTION_SENSOR_Y_KEY, &y))
625
		return;
626 627

	x = -x;
628 629 630
	input_report_abs(idev, ABS_X, x - rest_x);
	input_report_abs(idev, ABS_Y, y - rest_y);
	input_sync(idev);
631 632 633 634
}

/* Sysfs Files */

635 636 637 638 639 640
static ssize_t applesmc_name_show(struct device *dev,
				   struct device_attribute *attr, char *buf)
{
	return snprintf(buf, PAGE_SIZE, "applesmc\n");
}

641 642 643 644 645 646
static ssize_t applesmc_position_show(struct device *dev,
				   struct device_attribute *attr, char *buf)
{
	int ret;
	s16 x, y, z;

647
	ret = applesmc_read_s16(MOTION_SENSOR_X_KEY, &x);
648 649
	if (ret)
		goto out;
650
	ret = applesmc_read_s16(MOTION_SENSOR_Y_KEY, &y);
651 652
	if (ret)
		goto out;
653
	ret = applesmc_read_s16(MOTION_SENSOR_Z_KEY, &z);
654 655 656 657 658 659 660 661 662 663 664 665 666
	if (ret)
		goto out;

out:
	if (ret)
		return ret;
	else
		return snprintf(buf, PAGE_SIZE, "(%d,%d,%d)\n", x, y, z);
}

static ssize_t applesmc_light_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
667
	const struct applesmc_entry *entry;
668
	static int data_length;
669 670
	int ret;
	u8 left = 0, right = 0;
671
	u8 buffer[10];
672

673
	if (!data_length) {
674 675 676 677 678 679
		entry = applesmc_get_entry_by_key(LIGHT_SENSOR_LEFT_KEY);
		if (IS_ERR(entry))
			return PTR_ERR(entry);
		if (entry->len > 10)
			return -ENXIO;
		data_length = entry->len;
680
		pr_info("light sensor data length set to %d\n", data_length);
681 682 683
	}

	ret = applesmc_read_key(LIGHT_SENSOR_LEFT_KEY, buffer, data_length);
684 685 686 687 688
	/* newer macbooks report a single 10-bit bigendian value */
	if (data_length == 10) {
		left = be16_to_cpu(*(__be16 *)(buffer + 6)) >> 2;
		goto out;
	}
689 690 691
	left = buffer[2];
	if (ret)
		goto out;
692
	ret = applesmc_read_key(LIGHT_SENSOR_RIGHT_KEY, buffer, data_length);
693 694 695 696 697 698 699 700 701
	right = buffer[2];

out:
	if (ret)
		return ret;
	else
		return snprintf(sysfsbuf, PAGE_SIZE, "(%d,%d)\n", left, right);
}

702 703 704 705
/* Displays sensor key as label */
static ssize_t applesmc_show_sensor_label(struct device *dev,
			struct device_attribute *devattr, char *sysfsbuf)
{
706 707
	int index = smcreg.temp_begin + to_index(devattr);
	const struct applesmc_entry *entry;
708

709 710 711 712 713
	entry = applesmc_get_entry_by_index(index);
	if (IS_ERR(entry))
		return PTR_ERR(entry);

	return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", entry->key);
714 715
}

716 717 718 719
/* Displays degree Celsius * 1000 */
static ssize_t applesmc_show_temperature(struct device *dev,
			struct device_attribute *devattr, char *sysfsbuf)
{
720 721
	int index = smcreg.temp_begin + to_index(devattr);
	const struct applesmc_entry *entry;
722 723 724 725
	int ret;
	u8 buffer[2];
	unsigned int temp;

726 727 728
	entry = applesmc_get_entry_by_index(index);
	if (IS_ERR(entry))
		return PTR_ERR(entry);
729 730
	if (entry->len > 2)
		return -EINVAL;
731

732
	ret = applesmc_read_entry(entry, buffer, entry->len);
733 734
	if (ret)
		return ret;
735

736 737 738 739 740 741
	if (entry->len == 2) {
		temp = buffer[0] * 1000;
		temp += (buffer[1] >> 6) * 250;
	} else {
		temp = buffer[0] * 4000;
	}
742 743

	return snprintf(sysfsbuf, PAGE_SIZE, "%u\n", temp);
744 745 746 747 748 749 750 751 752 753
}

static ssize_t applesmc_show_fan_speed(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
	int ret;
	unsigned int speed = 0;
	char newkey[5];
	u8 buffer[2];

754
	sprintf(newkey, fan_speed_fmt[to_option(attr)], to_index(attr));
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769

	ret = applesmc_read_key(newkey, buffer, 2);
	speed = ((buffer[0] << 8 | buffer[1]) >> 2);

	if (ret)
		return ret;
	else
		return snprintf(sysfsbuf, PAGE_SIZE, "%u\n", speed);
}

static ssize_t applesmc_store_fan_speed(struct device *dev,
					struct device_attribute *attr,
					const char *sysfsbuf, size_t count)
{
	int ret;
770
	unsigned long speed;
771 772 773
	char newkey[5];
	u8 buffer[2];

774
	if (kstrtoul(sysfsbuf, 10, &speed) < 0 || speed >= 0x4000)
775
		return -EINVAL;		/* Bigger than a 14-bit value */
776

777
	sprintf(newkey, fan_speed_fmt[to_option(attr)], to_index(attr));
778 779 780 781 782 783 784 785 786 787 788 789

	buffer[0] = (speed >> 6) & 0xff;
	buffer[1] = (speed << 2) & 0xff;
	ret = applesmc_write_key(newkey, buffer, 2);

	if (ret)
		return ret;
	else
		return count;
}

static ssize_t applesmc_show_fan_manual(struct device *dev,
790
			struct device_attribute *attr, char *sysfsbuf)
791 792 793 794 795 796
{
	int ret;
	u16 manual = 0;
	u8 buffer[2];

	ret = applesmc_read_key(FANS_MANUAL, buffer, 2);
797
	manual = ((buffer[0] << 8 | buffer[1]) >> to_index(attr)) & 0x01;
798 799 800 801 802 803 804 805

	if (ret)
		return ret;
	else
		return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", manual);
}

static ssize_t applesmc_store_fan_manual(struct device *dev,
806
					 struct device_attribute *attr,
807 808 809 810
					 const char *sysfsbuf, size_t count)
{
	int ret;
	u8 buffer[2];
811
	unsigned long input;
812 813
	u16 val;

814
	if (kstrtoul(sysfsbuf, 10, &input) < 0)
815
		return -EINVAL;
816 817 818 819 820 821 822

	ret = applesmc_read_key(FANS_MANUAL, buffer, 2);
	val = (buffer[0] << 8 | buffer[1]);
	if (ret)
		goto out;

	if (input)
823
		val = val | (0x01 << to_index(attr));
824
	else
825
		val = val & ~(0x01 << to_index(attr));
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

	buffer[0] = (val >> 8) & 0xFF;
	buffer[1] = val & 0xFF;

	ret = applesmc_write_key(FANS_MANUAL, buffer, 2);

out:
	if (ret)
		return ret;
	else
		return count;
}

static ssize_t applesmc_show_fan_position(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
	int ret;
	char newkey[5];
	u8 buffer[17];

846
	sprintf(newkey, FAN_ID_FMT, to_index(attr));
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872

	ret = applesmc_read_key(newkey, buffer, 16);
	buffer[16] = 0;

	if (ret)
		return ret;
	else
		return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", buffer+4);
}

static ssize_t applesmc_calibrate_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
	return snprintf(sysfsbuf, PAGE_SIZE, "(%d,%d)\n", rest_x, rest_y);
}

static ssize_t applesmc_calibrate_store(struct device *dev,
	struct device_attribute *attr, const char *sysfsbuf, size_t count)
{
	applesmc_calibrate();

	return count;
}

static void applesmc_backlight_set(struct work_struct *work)
{
873
	applesmc_write_key(BACKLIGHT_KEY, backlight_state, 2);
874 875 876 877 878 879 880 881
}
static DECLARE_WORK(backlight_work, &applesmc_backlight_set);

static void applesmc_brightness_set(struct led_classdev *led_cdev,
						enum led_brightness value)
{
	int ret;

882
	backlight_state[0] = value;
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
	ret = queue_work(applesmc_led_wq, &backlight_work);

	if (debug && (!ret))
		printk(KERN_DEBUG "applesmc: work was already on the queue.\n");
}

static ssize_t applesmc_key_count_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
	int ret;
	u8 buffer[4];
	u32 count;

	ret = applesmc_read_key(KEY_COUNT_KEY, buffer, 4);
	count = ((u32)buffer[0]<<24) + ((u32)buffer[1]<<16) +
						((u32)buffer[2]<<8) + buffer[3];

	if (ret)
		return ret;
	else
		return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", count);
}

static ssize_t applesmc_key_at_index_read_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
909
	const struct applesmc_entry *entry;
910 911
	int ret;

912 913 914 915 916
	entry = applesmc_get_entry_by_index(key_at_index);
	if (IS_ERR(entry))
		return PTR_ERR(entry);
	ret = applesmc_read_entry(entry, sysfsbuf, entry->len);
	if (ret)
917 918
		return ret;

919
	return entry->len;
920 921 922 923 924
}

static ssize_t applesmc_key_at_index_data_length_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
925
	const struct applesmc_entry *entry;
926

927 928 929
	entry = applesmc_get_entry_by_index(key_at_index);
	if (IS_ERR(entry))
		return PTR_ERR(entry);
930

931
	return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", entry->len);
932 933 934 935 936
}

static ssize_t applesmc_key_at_index_type_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
937
	const struct applesmc_entry *entry;
938

939 940 941
	entry = applesmc_get_entry_by_index(key_at_index);
	if (IS_ERR(entry))
		return PTR_ERR(entry);
942

943
	return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", entry->type);
944 945 946 947 948
}

static ssize_t applesmc_key_at_index_name_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
949
	const struct applesmc_entry *entry;
950

951 952 953
	entry = applesmc_get_entry_by_index(key_at_index);
	if (IS_ERR(entry))
		return PTR_ERR(entry);
954

955
	return snprintf(sysfsbuf, PAGE_SIZE, "%s\n", entry->key);
956 957 958 959 960 961 962 963 964 965 966
}

static ssize_t applesmc_key_at_index_show(struct device *dev,
				struct device_attribute *attr, char *sysfsbuf)
{
	return snprintf(sysfsbuf, PAGE_SIZE, "%d\n", key_at_index);
}

static ssize_t applesmc_key_at_index_store(struct device *dev,
	struct device_attribute *attr, const char *sysfsbuf, size_t count)
{
967
	unsigned long newkey;
968

969
	if (kstrtoul(sysfsbuf, 10, &newkey) < 0
970 971
	    || newkey >= smcreg.key_count)
		return -EINVAL;
972

973
	key_at_index = newkey;
974 975 976 977
	return count;
}

static struct led_classdev applesmc_backlight = {
978
	.name			= "smc::kbd_backlight",
979 980 981 982
	.default_trigger	= "nand-disk",
	.brightness_set		= applesmc_brightness_set,
};

983 984 985 986 987 988 989 990 991
static struct applesmc_node_group info_group[] = {
	{ "name", applesmc_name_show },
	{ "key_count", applesmc_key_count_show },
	{ "key_at_index", applesmc_key_at_index_show, applesmc_key_at_index_store },
	{ "key_at_index_name", applesmc_key_at_index_name_show },
	{ "key_at_index_type", applesmc_key_at_index_type_show },
	{ "key_at_index_data_length", applesmc_key_at_index_data_length_show },
	{ "key_at_index_data", applesmc_key_at_index_read_show },
	{ }
992 993
};

994 995 996 997
static struct applesmc_node_group accelerometer_group[] = {
	{ "position", applesmc_position_show },
	{ "calibrate", applesmc_calibrate_show, applesmc_calibrate_store },
	{ }
998 999
};

1000 1001 1002 1003
static struct applesmc_node_group light_sensor_group[] = {
	{ "light", applesmc_light_show },
	{ }
};
1004

1005 1006 1007 1008 1009 1010 1011 1012 1013
static struct applesmc_node_group fan_group[] = {
	{ "fan%d_label", applesmc_show_fan_position },
	{ "fan%d_input", applesmc_show_fan_speed, NULL, 0 },
	{ "fan%d_min", applesmc_show_fan_speed, applesmc_store_fan_speed, 1 },
	{ "fan%d_max", applesmc_show_fan_speed, NULL, 2 },
	{ "fan%d_safe", applesmc_show_fan_speed, NULL, 3 },
	{ "fan%d_output", applesmc_show_fan_speed, applesmc_store_fan_speed, 4 },
	{ "fan%d_manual", applesmc_show_fan_manual, applesmc_store_fan_manual },
	{ }
1014 1015
};

1016 1017 1018 1019
static struct applesmc_node_group temp_group[] = {
	{ "temp%d_label", applesmc_show_sensor_label },
	{ "temp%d_input", applesmc_show_temperature },
	{ }
1020 1021
};

1022 1023
/* Module stuff */

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
/*
 * applesmc_destroy_nodes - remove files and free associated memory
 */
static void applesmc_destroy_nodes(struct applesmc_node_group *groups)
{
	struct applesmc_node_group *grp;
	struct applesmc_dev_attr *node;

	for (grp = groups; grp->nodes; grp++) {
		for (node = grp->nodes; node->sda.dev_attr.attr.name; node++)
			sysfs_remove_file(&pdev->dev.kobj,
					  &node->sda.dev_attr.attr);
		kfree(grp->nodes);
		grp->nodes = NULL;
	}
}

/*
 * applesmc_create_nodes - create a two-dimensional group of sysfs files
 */
static int applesmc_create_nodes(struct applesmc_node_group *groups, int num)
{
	struct applesmc_node_group *grp;
	struct applesmc_dev_attr *node;
	struct attribute *attr;
	int ret, i;

	for (grp = groups; grp->format; grp++) {
		grp->nodes = kcalloc(num + 1, sizeof(*node), GFP_KERNEL);
		if (!grp->nodes) {
			ret = -ENOMEM;
			goto out;
		}
		for (i = 0; i < num; i++) {
			node = &grp->nodes[i];
			sprintf(node->name, grp->format, i + 1);
1060
			node->sda.index = (grp->option << 16) | (i & 0xffff);
1061 1062 1063
			node->sda.dev_attr.show = grp->show;
			node->sda.dev_attr.store = grp->store;
			attr = &node->sda.dev_attr.attr;
1064
			sysfs_attr_init(attr);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
			attr->name = node->name;
			attr->mode = S_IRUGO | (grp->store ? S_IWUSR : 0);
			ret = sysfs_create_file(&pdev->dev.kobj, attr);
			if (ret) {
				attr->name = NULL;
				goto out;
			}
		}
	}

	return 0;
out:
	applesmc_destroy_nodes(groups);
	return ret;
}

1081 1082 1083
/* Create accelerometer ressources */
static int applesmc_create_accelerometer(void)
{
1084
	struct input_dev *idev;
1085 1086
	int ret;

1087 1088 1089 1090
	if (!smcreg.has_accelerometer)
		return 0;

	ret = applesmc_create_nodes(accelerometer_group, 1);
1091 1092 1093
	if (ret)
		goto out;

1094
	applesmc_idev = input_allocate_polled_device();
1095 1096 1097 1098 1099
	if (!applesmc_idev) {
		ret = -ENOMEM;
		goto out_sysfs;
	}

1100 1101 1102
	applesmc_idev->poll = applesmc_idev_poll;
	applesmc_idev->poll_interval = APPLESMC_POLL_INTERVAL;

1103 1104 1105
	/* initial calibrate for the input device */
	applesmc_calibrate();

1106 1107 1108 1109 1110
	/* initialize the input device */
	idev = applesmc_idev->input;
	idev->name = "applesmc";
	idev->id.bustype = BUS_HOST;
	idev->dev.parent = &pdev->dev;
1111
	idev->evbit[0] = BIT_MASK(EV_ABS);
1112
	input_set_abs_params(idev, ABS_X,
1113
			-256, 256, APPLESMC_INPUT_FUZZ, APPLESMC_INPUT_FLAT);
1114
	input_set_abs_params(idev, ABS_Y,
1115 1116
			-256, 256, APPLESMC_INPUT_FUZZ, APPLESMC_INPUT_FLAT);

1117
	ret = input_register_polled_device(applesmc_idev);
1118 1119 1120 1121 1122 1123
	if (ret)
		goto out_idev;

	return 0;

out_idev:
1124
	input_free_polled_device(applesmc_idev);
1125 1126

out_sysfs:
1127
	applesmc_destroy_nodes(accelerometer_group);
1128 1129

out:
1130
	pr_warn("driver init failed (ret=%d)!\n", ret);
1131 1132 1133 1134 1135 1136
	return ret;
}

/* Release all ressources used by the accelerometer */
static void applesmc_release_accelerometer(void)
{
1137 1138
	if (!smcreg.has_accelerometer)
		return;
1139 1140
	input_unregister_polled_device(applesmc_idev);
	input_free_polled_device(applesmc_idev);
1141
	applesmc_destroy_nodes(accelerometer_group);
1142
}
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

static int applesmc_create_light_sensor(void)
{
	if (!smcreg.num_light_sensors)
		return 0;
	return applesmc_create_nodes(light_sensor_group, 1);
}

static void applesmc_release_light_sensor(void)
{
	if (!smcreg.num_light_sensors)
		return;
	applesmc_destroy_nodes(light_sensor_group);
}

static int applesmc_create_key_backlight(void)
{
	if (!smcreg.has_key_backlight)
		return 0;
	applesmc_led_wq = create_singlethread_workqueue("applesmc-led");
	if (!applesmc_led_wq)
		return -ENOMEM;
	return led_classdev_register(&pdev->dev, &applesmc_backlight);
}

static void applesmc_release_key_backlight(void)
{
	if (!smcreg.has_key_backlight)
		return;
	led_classdev_unregister(&applesmc_backlight);
	destroy_workqueue(applesmc_led_wq);
}

1176 1177 1178 1179
static int applesmc_dmi_match(const struct dmi_system_id *id)
{
	return 1;
}
1180

1181 1182 1183 1184
/*
 * Note that DMI_MATCH(...,"MacBook") will match "MacBookPro1,1".
 * So we need to put "Apple MacBook Pro" before "Apple MacBook".
 */
1185
static __initdata struct dmi_system_id applesmc_whitelist[] = {
1186 1187 1188
	{ applesmc_dmi_match, "Apple MacBook Air", {
	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
	  DMI_MATCH(DMI_PRODUCT_NAME, "MacBookAir") },
1189
	},
1190
	{ applesmc_dmi_match, "Apple MacBook Pro", {
1191 1192
	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
	  DMI_MATCH(DMI_PRODUCT_NAME, "MacBookPro") },
1193
	},
1194
	{ applesmc_dmi_match, "Apple MacBook", {
1195 1196
	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
	  DMI_MATCH(DMI_PRODUCT_NAME, "MacBook") },
1197
	},
1198
	{ applesmc_dmi_match, "Apple Macmini", {
1199 1200
	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
	  DMI_MATCH(DMI_PRODUCT_NAME, "Macmini") },
1201
	},
1202 1203 1204
	{ applesmc_dmi_match, "Apple MacPro", {
	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
	  DMI_MATCH(DMI_PRODUCT_NAME, "MacPro") },
1205
	},
1206
	{ applesmc_dmi_match, "Apple iMac", {
1207 1208
	  DMI_MATCH(DMI_BOARD_VENDOR, "Apple"),
	  DMI_MATCH(DMI_PRODUCT_NAME, "iMac") },
1209
	},
1210 1211 1212 1213 1214 1215 1216 1217
	{ .ident = NULL }
};

static int __init applesmc_init(void)
{
	int ret;

	if (!dmi_check_system(applesmc_whitelist)) {
1218
		pr_warn("supported laptop not found!\n");
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
		ret = -ENODEV;
		goto out;
	}

	if (!request_region(APPLESMC_DATA_PORT, APPLESMC_NR_PORTS,
								"applesmc")) {
		ret = -ENXIO;
		goto out;
	}

	ret = platform_driver_register(&applesmc_driver);
	if (ret)
		goto out_region;

1233 1234
	pdev = platform_device_register_simple("applesmc", APPLESMC_DATA_PORT,
					       NULL, 0);
1235 1236 1237 1238 1239
	if (IS_ERR(pdev)) {
		ret = PTR_ERR(pdev);
		goto out_driver;
	}

1240 1241
	/* create register cache */
	ret = applesmc_init_smcreg();
1242 1243
	if (ret)
		goto out_device;
1244

1245
	ret = applesmc_create_nodes(info_group, 1);
1246 1247 1248
	if (ret)
		goto out_smcreg;

1249 1250 1251
	ret = applesmc_create_nodes(fan_group, smcreg.fan_count);
	if (ret)
		goto out_info;
1252

1253 1254 1255
	ret = applesmc_create_nodes(temp_group, smcreg.temp_count);
	if (ret)
		goto out_fans;
1256

1257 1258 1259
	ret = applesmc_create_accelerometer();
	if (ret)
		goto out_temperature;
1260

1261 1262 1263
	ret = applesmc_create_light_sensor();
	if (ret)
		goto out_accelerometer;
1264

1265 1266 1267
	ret = applesmc_create_key_backlight();
	if (ret)
		goto out_light_sysfs;
1268

1269 1270 1271
	hwmon_dev = hwmon_device_register(&pdev->dev);
	if (IS_ERR(hwmon_dev)) {
		ret = PTR_ERR(hwmon_dev);
1272 1273 1274 1275 1276 1277
		goto out_light_ledclass;
	}

	return 0;

out_light_ledclass:
1278
	applesmc_release_key_backlight();
1279
out_light_sysfs:
1280
	applesmc_release_light_sensor();
1281
out_accelerometer:
1282
	applesmc_release_accelerometer();
1283
out_temperature:
1284
	applesmc_destroy_nodes(temp_group);
1285
out_fans:
1286 1287
	applesmc_destroy_nodes(fan_group);
out_info:
1288
	applesmc_destroy_nodes(info_group);
1289 1290
out_smcreg:
	applesmc_destroy_smcreg();
1291 1292 1293 1294 1295 1296 1297
out_device:
	platform_device_unregister(pdev);
out_driver:
	platform_driver_unregister(&applesmc_driver);
out_region:
	release_region(APPLESMC_DATA_PORT, APPLESMC_NR_PORTS);
out:
1298
	pr_warn("driver init failed (ret=%d)!\n", ret);
1299 1300 1301 1302 1303
	return ret;
}

static void __exit applesmc_exit(void)
{
1304
	hwmon_device_unregister(hwmon_dev);
1305 1306 1307
	applesmc_release_key_backlight();
	applesmc_release_light_sensor();
	applesmc_release_accelerometer();
1308
	applesmc_destroy_nodes(temp_group);
1309
	applesmc_destroy_nodes(fan_group);
1310
	applesmc_destroy_nodes(info_group);
1311
	applesmc_destroy_smcreg();
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
	platform_device_unregister(pdev);
	platform_driver_unregister(&applesmc_driver);
	release_region(APPLESMC_DATA_PORT, APPLESMC_NR_PORTS);
}

module_init(applesmc_init);
module_exit(applesmc_exit);

MODULE_AUTHOR("Nicolas Boichat");
MODULE_DESCRIPTION("Apple SMC");
MODULE_LICENSE("GPL v2");
1323
MODULE_DEVICE_TABLE(dmi, applesmc_whitelist);