smu.c revision 205506
1/*-
2 * Copyright (c) 2009 Nathan Whitehorn
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
21 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: head/sys/powerpc/powermac/smu.c 205506 2010-03-23 03:14:44Z nwhitehorn $");
30
31#include <sys/param.h>
32#include <sys/bus.h>
33#include <sys/systm.h>
34#include <sys/module.h>
35#include <sys/conf.h>
36#include <sys/cpu.h>
37#include <sys/clock.h>
38#include <sys/ctype.h>
39#include <sys/kernel.h>
40#include <sys/kthread.h>
41#include <sys/reboot.h>
42#include <sys/rman.h>
43#include <sys/sysctl.h>
44#include <sys/unistd.h>
45
46#include <machine/bus.h>
47#include <machine/intr_machdep.h>
48#include <machine/md_var.h>
49
50#include <dev/led/led.h>
51#include <dev/ofw/openfirm.h>
52#include <dev/ofw/ofw_bus.h>
53#include <powerpc/powermac/macgpiovar.h>
54
55#include "clock_if.h"
56
57struct smu_cmd {
58	volatile uint8_t cmd;
59	uint8_t		len;
60	uint8_t		data[254];
61
62	STAILQ_ENTRY(smu_cmd) cmd_q;
63};
64
65STAILQ_HEAD(smu_cmdq, smu_cmd);
66
67struct smu_fan {
68	cell_t	reg;
69	cell_t	min_rpm;
70	cell_t	max_rpm;
71	cell_t	unmanaged_rpm;
72	char	location[32];
73
74	int	old_style;
75	int	setpoint;
76};
77
78struct smu_sensor {
79	cell_t	reg;
80	char	location[32];
81	enum {
82		SMU_CURRENT_SENSOR,
83		SMU_VOLTAGE_SENSOR,
84		SMU_POWER_SENSOR,
85		SMU_TEMP_SENSOR
86	} type;
87};
88
89struct smu_softc {
90	device_t	sc_dev;
91	struct mtx	sc_mtx;
92
93	struct resource	*sc_memr;
94	int		sc_memrid;
95
96	bus_dma_tag_t	sc_dmatag;
97	bus_space_tag_t	sc_bt;
98	bus_space_handle_t sc_mailbox;
99
100	struct smu_cmd	*sc_cmd, *sc_cur_cmd;
101	bus_addr_t	sc_cmd_phys;
102	bus_dmamap_t	sc_cmd_dmamap;
103	struct smu_cmdq	sc_cmdq;
104
105	struct smu_fan	*sc_fans;
106	int		sc_nfans;
107	struct smu_sensor *sc_sensors;
108	int		sc_nsensors;
109
110	int		sc_doorbellirqid;
111	struct resource	*sc_doorbellirq;
112	void		*sc_doorbellirqcookie;
113
114	struct proc	*sc_fanmgt_proc;
115	time_t		sc_lastuserchange;
116
117	/* Calibration data */
118	uint16_t	sc_cpu_diode_scale;
119	int16_t		sc_cpu_diode_offset;
120
121	uint16_t	sc_cpu_volt_scale;
122	int16_t		sc_cpu_volt_offset;
123	uint16_t	sc_cpu_curr_scale;
124	int16_t		sc_cpu_curr_offset;
125
126	uint16_t	sc_slots_pow_scale;
127	int16_t		sc_slots_pow_offset;
128
129	/* Thermal management parameters */
130	int		sc_target_temp;		/* Default 55 C */
131	int		sc_critical_temp;	/* Default 90 C */
132
133	struct cdev 	*sc_leddev;
134};
135
136/* regular bus attachment functions */
137
138static int	smu_probe(device_t);
139static int	smu_attach(device_t);
140
141/* cpufreq notification hooks */
142
143static void	smu_cpufreq_pre_change(device_t, const struct cf_level *level);
144static void	smu_cpufreq_post_change(device_t, const struct cf_level *level);
145
146/* clock interface */
147static int	smu_gettime(device_t dev, struct timespec *ts);
148static int	smu_settime(device_t dev, struct timespec *ts);
149
150/* utility functions */
151static int	smu_run_cmd(device_t dev, struct smu_cmd *cmd, int wait);
152static int	smu_get_datablock(device_t dev, int8_t id, uint8_t *buf,
153		    size_t len);
154static void	smu_attach_fans(device_t dev, phandle_t fanroot);
155static void	smu_attach_sensors(device_t dev, phandle_t sensroot);
156static void	smu_fan_management_proc(void *xdev);
157static void	smu_manage_fans(device_t smu);
158static void	smu_set_sleepled(void *xdev, int onoff);
159static int	smu_server_mode(SYSCTL_HANDLER_ARGS);
160static void	smu_doorbell_intr(void *xdev);
161
162/* where to find the doorbell GPIO */
163
164static device_t	smu_doorbell = NULL;
165
166static device_method_t  smu_methods[] = {
167	/* Device interface */
168	DEVMETHOD(device_probe,		smu_probe),
169	DEVMETHOD(device_attach,	smu_attach),
170
171	/* Clock interface */
172	DEVMETHOD(clock_gettime,	smu_gettime),
173	DEVMETHOD(clock_settime,	smu_settime),
174	{ 0, 0 },
175};
176
177static driver_t smu_driver = {
178	"smu",
179	smu_methods,
180	sizeof(struct smu_softc)
181};
182
183static devclass_t smu_devclass;
184
185DRIVER_MODULE(smu, nexus, smu_driver, smu_devclass, 0, 0);
186MALLOC_DEFINE(M_SMU, "smu", "SMU Sensor Information");
187
188#define SMU_MAILBOX		0x8000860c
189#define SMU_FANMGT_INTERVAL	1000 /* ms */
190
191/* Command types */
192#define SMU_ADC			0xd8
193#define SMU_FAN			0x4a
194#define SMU_I2C			0x9a
195#define  SMU_I2C_SIMPLE		0x00
196#define  SMU_I2C_NORMAL		0x01
197#define  SMU_I2C_COMBINED	0x02
198#define SMU_MISC		0xee
199#define  SMU_MISC_GET_DATA	0x02
200#define  SMU_MISC_LED_CTRL	0x04
201#define SMU_POWER		0xaa
202#define SMU_POWER_EVENTS	0x8f
203#define  SMU_PWR_GET_POWERUP	0x00
204#define  SMU_PWR_SET_POWERUP	0x01
205#define  SMU_PWR_CLR_POWERUP	0x02
206#define SMU_RTC			0x8e
207#define  SMU_RTC_GET		0x81
208#define  SMU_RTC_SET		0x80
209
210/* Power event types */
211#define SMU_WAKEUP_KEYPRESS	0x01
212#define SMU_WAKEUP_AC_INSERT	0x02
213#define SMU_WAKEUP_AC_CHANGE	0x04
214#define SMU_WAKEUP_RING		0x10
215
216/* Data blocks */
217#define SMU_CPUTEMP_CAL		0x18
218#define SMU_CPUVOLT_CAL		0x21
219#define SMU_SLOTPW_CAL		0x78
220
221/* Partitions */
222#define SMU_PARTITION		0x3e
223#define SMU_PARTITION_LATEST	0x01
224#define SMU_PARTITION_BASE	0x02
225#define SMU_PARTITION_UPDATE	0x03
226
227static int
228smu_probe(device_t dev)
229{
230	const char *name = ofw_bus_get_name(dev);
231
232	if (strcmp(name, "smu") != 0)
233		return (ENXIO);
234
235	device_set_desc(dev, "Apple System Management Unit");
236	return (0);
237}
238
239static void
240smu_phys_callback(void *xsc, bus_dma_segment_t *segs, int nsegs, int error)
241{
242	struct smu_softc *sc = xsc;
243
244	sc->sc_cmd_phys = segs[0].ds_addr;
245}
246
247static int
248smu_attach(device_t dev)
249{
250	struct smu_softc *sc;
251	phandle_t	node, child;
252	uint8_t		data[12];
253
254	sc = device_get_softc(dev);
255
256	mtx_init(&sc->sc_mtx, "smu", NULL, MTX_DEF);
257	sc->sc_cur_cmd = NULL;
258	sc->sc_doorbellirqid = -1;
259
260	/*
261	 * Map the mailbox area. This should be determined from firmware,
262	 * but I have not found a simple way to do that.
263	 */
264	bus_dma_tag_create(NULL, 16, 0, BUS_SPACE_MAXADDR_32BIT,
265	    BUS_SPACE_MAXADDR, NULL, NULL, PAGE_SIZE, 1, PAGE_SIZE, 0, NULL,
266	    NULL, &(sc->sc_dmatag));
267	sc->sc_bt = &bs_le_tag;
268	bus_space_map(sc->sc_bt, SMU_MAILBOX, 4, 0, &sc->sc_mailbox);
269
270	/*
271	 * Allocate the command buffer. This can be anywhere in the low 4 GB
272	 * of memory.
273	 */
274	bus_dmamem_alloc(sc->sc_dmatag, (void **)&sc->sc_cmd, BUS_DMA_WAITOK |
275	    BUS_DMA_ZERO, &sc->sc_cmd_dmamap);
276	bus_dmamap_load(sc->sc_dmatag, sc->sc_cmd_dmamap,
277	    sc->sc_cmd, PAGE_SIZE, smu_phys_callback, sc, 0);
278	STAILQ_INIT(&sc->sc_cmdq);
279
280	/*
281	 * Set up handlers to change CPU voltage when CPU frequency is changed.
282	 */
283	EVENTHANDLER_REGISTER(cpufreq_pre_change, smu_cpufreq_pre_change, dev,
284	    EVENTHANDLER_PRI_ANY);
285	EVENTHANDLER_REGISTER(cpufreq_post_change, smu_cpufreq_post_change, dev,
286	    EVENTHANDLER_PRI_ANY);
287
288	/*
289	 * Detect and attach child devices.
290	 */
291	node = ofw_bus_get_node(dev);
292	for (child = OF_child(node); child != 0; child = OF_peer(child)) {
293		char name[32];
294		memset(name, 0, sizeof(name));
295		OF_getprop(child, "name", name, sizeof(name));
296
297		if (strncmp(name, "rpm-fans", 9) == 0 ||
298		    strncmp(name, "fans", 5) == 0)
299			smu_attach_fans(dev, child);
300
301		if (strncmp(name, "sensors", 8) == 0)
302			smu_attach_sensors(dev, child);
303	}
304
305	/*
306	 * Collect calibration constants.
307	 */
308	smu_get_datablock(dev, SMU_CPUTEMP_CAL, data, sizeof(data));
309	sc->sc_cpu_diode_scale = (data[4] << 8) + data[5];
310	sc->sc_cpu_diode_offset = (data[6] << 8) + data[7];
311
312	smu_get_datablock(dev, SMU_CPUVOLT_CAL, data, sizeof(data));
313	sc->sc_cpu_volt_scale = (data[4] << 8) + data[5];
314	sc->sc_cpu_volt_offset = (data[6] << 8) + data[7];
315	sc->sc_cpu_curr_scale = (data[8] << 8) + data[9];
316	sc->sc_cpu_curr_offset = (data[10] << 8) + data[11];
317
318	smu_get_datablock(dev, SMU_SLOTPW_CAL, data, sizeof(data));
319	sc->sc_slots_pow_scale = (data[4] << 8) + data[5];
320	sc->sc_slots_pow_offset = (data[6] << 8) + data[7];
321
322	/*
323	 * Set up simple-minded thermal management.
324	 */
325	sc->sc_target_temp = 55;
326	sc->sc_critical_temp = 90;
327
328	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
329	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
330	    "target_temp", CTLTYPE_INT | CTLFLAG_RW, &sc->sc_target_temp,
331	    sizeof(int), "Target temperature (C)");
332	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
333	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
334	    "critical_temp", CTLTYPE_INT | CTLFLAG_RW,
335	    &sc->sc_critical_temp, sizeof(int), "Critical temperature (C)");
336
337	kproc_create(smu_fan_management_proc, dev, &sc->sc_fanmgt_proc,
338	    RFHIGHPID, 0, "smu_thermal");
339
340	/*
341	 * Set up LED interface
342	 */
343	sc->sc_leddev = led_create(smu_set_sleepled, dev, "sleepled");
344
345	/*
346	 * Reset on power loss behavior
347	 */
348
349	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
350            SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
351	    "server_mode", CTLTYPE_INT | CTLFLAG_RW, dev, 0,
352	    smu_server_mode, "I", "Enable reboot after power failure");
353
354	/*
355	 * Set up doorbell interrupt.
356	 */
357	sc->sc_doorbellirqid = 0;
358	sc->sc_doorbellirq = bus_alloc_resource_any(smu_doorbell, SYS_RES_IRQ,
359	    &sc->sc_doorbellirqid, RF_ACTIVE);
360	bus_setup_intr(smu_doorbell, sc->sc_doorbellirq,
361	    INTR_TYPE_MISC | INTR_MPSAFE, NULL, smu_doorbell_intr, dev,
362	    &sc->sc_doorbellirqcookie);
363	powerpc_config_intr(rman_get_start(sc->sc_doorbellirq),
364	    INTR_TRIGGER_EDGE, INTR_POLARITY_LOW);
365
366	/*
367	 * Connect RTC interface.
368	 */
369	clock_register(dev, 1000);
370
371	return (0);
372}
373
374static void
375smu_send_cmd(device_t dev, struct smu_cmd *cmd)
376{
377	struct smu_softc *sc;
378
379	sc = device_get_softc(dev);
380
381	mtx_assert(&sc->sc_mtx, MA_OWNED);
382
383	powerpc_pow_enabled = 0;	/* SMU cannot work if we go to NAP */
384	sc->sc_cur_cmd = cmd;
385
386	/* Copy the command to the mailbox */
387	sc->sc_cmd->cmd = cmd->cmd;
388	sc->sc_cmd->len = cmd->len;
389	memcpy(sc->sc_cmd->data, cmd->data, sizeof(cmd->data));
390	bus_dmamap_sync(sc->sc_dmatag, sc->sc_cmd_dmamap, BUS_DMASYNC_PREWRITE);
391	bus_space_write_4(sc->sc_bt, sc->sc_mailbox, 0, sc->sc_cmd_phys);
392
393	/* Flush the cacheline it is in -- SMU bypasses the cache */
394	__asm __volatile("sync; dcbf 0,%0; sync" :: "r"(sc->sc_cmd): "memory");
395
396	/* Ring SMU doorbell */
397	macgpio_write(smu_doorbell, GPIO_DDR_OUTPUT);
398}
399
400static void
401smu_doorbell_intr(void *xdev)
402{
403	device_t smu;
404	struct smu_softc *sc;
405	int doorbell_ack;
406
407	smu = xdev;
408	doorbell_ack = macgpio_read(smu_doorbell);
409	sc = device_get_softc(smu);
410
411	if (doorbell_ack != (GPIO_DDR_OUTPUT | GPIO_LEVEL_RO | GPIO_DATA))
412		return;
413
414	mtx_lock(&sc->sc_mtx);
415
416	if (sc->sc_cur_cmd == NULL)	/* spurious */
417		goto done;
418
419	/* Check result. First invalidate the cache again... */
420	__asm __volatile("dcbf 0,%0; sync" :: "r"(sc->sc_cmd) : "memory");
421
422	bus_dmamap_sync(sc->sc_dmatag, sc->sc_cmd_dmamap, BUS_DMASYNC_POSTREAD);
423
424	sc->sc_cur_cmd->cmd = sc->sc_cmd->cmd;
425	sc->sc_cur_cmd->len = sc->sc_cmd->len;
426	memcpy(sc->sc_cur_cmd->data, sc->sc_cmd->data,
427	    sizeof(sc->sc_cmd->data));
428	wakeup(sc->sc_cur_cmd);
429	sc->sc_cur_cmd = NULL;
430	powerpc_pow_enabled = 1;
431
432    done:
433	/* Queue next command if one is pending */
434	if (STAILQ_FIRST(&sc->sc_cmdq) != NULL) {
435		sc->sc_cur_cmd = STAILQ_FIRST(&sc->sc_cmdq);
436		STAILQ_REMOVE_HEAD(&sc->sc_cmdq, cmd_q);
437		smu_send_cmd(smu, sc->sc_cur_cmd);
438	}
439
440	mtx_unlock(&sc->sc_mtx);
441}
442
443static int
444smu_run_cmd(device_t dev, struct smu_cmd *cmd, int wait)
445{
446	struct smu_softc *sc;
447	uint8_t cmd_code;
448	int error;
449
450	sc = device_get_softc(dev);
451	cmd_code = cmd->cmd;
452
453	mtx_lock(&sc->sc_mtx);
454	if (sc->sc_cur_cmd != NULL) {
455		STAILQ_INSERT_TAIL(&sc->sc_cmdq, cmd, cmd_q);
456	} else
457		smu_send_cmd(dev, cmd);
458	mtx_unlock(&sc->sc_mtx);
459
460	if (!wait)
461		return (0);
462
463	if (sc->sc_doorbellirqid < 0) {
464		/* Poll if the IRQ has not been set up yet */
465		do {
466			DELAY(50);
467			smu_doorbell_intr(dev);
468		} while (sc->sc_cur_cmd != NULL);
469	} else {
470		/* smu_doorbell_intr will wake us when the command is ACK'ed */
471		error = tsleep(cmd, 0, "smu", 800 * hz / 1000);
472		if (error != 0)
473			smu_doorbell_intr(dev);	/* One last chance */
474
475		if (error != 0) {
476		    mtx_lock(&sc->sc_mtx);
477		    if (cmd->cmd == cmd_code) {	/* Never processed */
478			/* Abort this command if we timed out */
479			if (sc->sc_cur_cmd == cmd)
480				sc->sc_cur_cmd = NULL;
481			else
482				STAILQ_REMOVE(&sc->sc_cmdq, cmd, smu_cmd,
483				    cmd_q);
484			mtx_unlock(&sc->sc_mtx);
485			return (error);
486		    }
487		    error = 0;
488		    mtx_unlock(&sc->sc_mtx);
489		}
490	}
491
492	/* SMU acks the command by inverting the command bits */
493	if (cmd->cmd == ((~cmd_code) & 0xff))
494		error = 0;
495	else
496		error = EIO;
497
498	return (error);
499}
500
501static int
502smu_get_datablock(device_t dev, int8_t id, uint8_t *buf, size_t len)
503{
504	struct smu_cmd cmd;
505	uint8_t addr[4];
506
507	cmd.cmd = SMU_PARTITION;
508	cmd.len = 2;
509	cmd.data[0] = SMU_PARTITION_LATEST;
510	cmd.data[1] = id;
511
512	smu_run_cmd(dev, &cmd, 1);
513
514	addr[0] = addr[1] = 0;
515	addr[2] = cmd.data[0];
516	addr[3] = cmd.data[1];
517
518	cmd.cmd = SMU_MISC;
519	cmd.len = 7;
520	cmd.data[0] = SMU_MISC_GET_DATA;
521	cmd.data[1] = sizeof(addr);
522	memcpy(&cmd.data[2], addr, sizeof(addr));
523	cmd.data[6] = len;
524
525	smu_run_cmd(dev, &cmd, 1);
526	memcpy(buf, cmd.data, len);
527	return (0);
528}
529
530static void
531smu_slew_cpu_voltage(device_t dev, int to)
532{
533	struct smu_cmd cmd;
534
535	cmd.cmd = SMU_POWER;
536	cmd.len = 8;
537	cmd.data[0] = 'V';
538	cmd.data[1] = 'S';
539	cmd.data[2] = 'L';
540	cmd.data[3] = 'E';
541	cmd.data[4] = 'W';
542	cmd.data[5] = 0xff;
543	cmd.data[6] = 1;
544	cmd.data[7] = to;
545
546	smu_run_cmd(dev, &cmd, 1);
547}
548
549static void
550smu_cpufreq_pre_change(device_t dev, const struct cf_level *level)
551{
552	/*
553	 * Make sure the CPU voltage is raised before we raise
554	 * the clock.
555	 */
556
557	if (level->rel_set[0].freq == 10000 /* max */)
558		smu_slew_cpu_voltage(dev, 0);
559}
560
561static void
562smu_cpufreq_post_change(device_t dev, const struct cf_level *level)
563{
564	/* We are safe to reduce CPU voltage after a downward transition */
565
566	if (level->rel_set[0].freq < 10000 /* max */)
567		smu_slew_cpu_voltage(dev, 1); /* XXX: 1/4 voltage for 970MP? */
568}
569
570/* Routines for probing the SMU doorbell GPIO */
571static int doorbell_probe(device_t dev);
572static int doorbell_attach(device_t dev);
573
574static device_method_t  doorbell_methods[] = {
575	/* Device interface */
576	DEVMETHOD(device_probe,		doorbell_probe),
577	DEVMETHOD(device_attach,	doorbell_attach),
578	{ 0, 0 },
579};
580
581static driver_t doorbell_driver = {
582	"smudoorbell",
583	doorbell_methods,
584	0
585};
586
587static devclass_t doorbell_devclass;
588
589DRIVER_MODULE(smudoorbell, macgpio, doorbell_driver, doorbell_devclass, 0, 0);
590
591static int
592doorbell_probe(device_t dev)
593{
594	const char *name = ofw_bus_get_name(dev);
595
596	if (strcmp(name, "smu-doorbell") != 0)
597		return (ENXIO);
598
599	device_set_desc(dev, "SMU Doorbell GPIO");
600	device_quiet(dev);
601	return (0);
602}
603
604static int
605doorbell_attach(device_t dev)
606{
607	smu_doorbell = dev;
608	return (0);
609}
610
611/*
612 * Sensor and fan management
613 */
614
615static int
616smu_fan_set_rpm(device_t smu, struct smu_fan *fan, int rpm)
617{
618	struct smu_cmd cmd;
619	int error;
620
621	cmd.cmd = SMU_FAN;
622	error = EIO;
623
624	/* Clamp to allowed range */
625	rpm = max(fan->min_rpm, rpm);
626	rpm = min(fan->max_rpm, rpm);
627
628	/*
629	 * Apple has two fan control mechanisms. We can't distinguish
630	 * them except by seeing if the new one fails. If the new one
631	 * fails, use the old one.
632	 */
633
634	if (!fan->old_style) {
635		cmd.len = 4;
636		cmd.data[0] = 0x30;
637		cmd.data[1] = fan->reg;
638		cmd.data[2] = (rpm >> 8) & 0xff;
639		cmd.data[3] = rpm & 0xff;
640
641		error = smu_run_cmd(smu, &cmd, 1);
642		if (error)
643			fan->old_style = 1;
644	}
645
646	if (fan->old_style) {
647		cmd.len = 14;
648		cmd.data[0] = 0;
649		cmd.data[1] = 1 << fan->reg;
650		cmd.data[2 + 2*fan->reg] = (rpm >> 8) & 0xff;
651		cmd.data[3 + 2*fan->reg] = rpm & 0xff;
652		error = smu_run_cmd(smu, &cmd, 1);
653	}
654
655	if (error == 0)
656		fan->setpoint = rpm;
657
658	return (error);
659}
660
661static int
662smu_fan_read_rpm(device_t smu, struct smu_fan *fan)
663{
664	struct smu_cmd cmd;
665
666	cmd.cmd = SMU_FAN;
667	cmd.len = 1;
668	cmd.data[0] = 1;
669
670	smu_run_cmd(smu, &cmd, 1);
671
672	return ((cmd.data[fan->reg*2+1] << 8) | cmd.data[fan->reg*2+2]);
673}
674
675static int
676smu_fanrpm_sysctl(SYSCTL_HANDLER_ARGS)
677{
678	device_t smu;
679	struct smu_softc *sc;
680	struct smu_fan *fan;
681	int rpm, error;
682
683	smu = arg1;
684	sc = device_get_softc(smu);
685	fan = &sc->sc_fans[arg2];
686
687	rpm = smu_fan_read_rpm(smu, fan);
688	error = sysctl_handle_int(oidp, &rpm, 0, req);
689
690	if (error || !req->newptr)
691		return (error);
692
693	sc->sc_lastuserchange = time_uptime;
694
695	return (smu_fan_set_rpm(smu, fan, rpm));
696}
697
698static void
699smu_attach_fans(device_t dev, phandle_t fanroot)
700{
701	struct smu_fan *fan;
702	struct smu_softc *sc;
703	struct sysctl_oid *oid, *fanroot_oid;
704	struct sysctl_ctx_list *ctx;
705	phandle_t child;
706	char type[32], sysctl_name[32];
707	int i;
708
709	sc = device_get_softc(dev);
710	sc->sc_nfans = 0;
711
712	for (child = OF_child(fanroot); child != 0; child = OF_peer(child))
713		sc->sc_nfans++;
714
715	if (sc->sc_nfans == 0) {
716		device_printf(dev, "WARNING: No fans detected!\n");
717		return;
718	}
719
720	sc->sc_fans = malloc(sc->sc_nfans * sizeof(struct smu_fan), M_SMU,
721	    M_WAITOK | M_ZERO);
722
723	fan = sc->sc_fans;
724	sc->sc_nfans = 0;
725
726	ctx = device_get_sysctl_ctx(dev);
727	fanroot_oid = SYSCTL_ADD_NODE(ctx,
728	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "fans",
729	    CTLFLAG_RD, 0, "SMU Fan Information");
730
731	for (child = OF_child(fanroot); child != 0; child = OF_peer(child)) {
732		OF_getprop(child, "device_type", type, sizeof(type));
733		if (strcmp(type, "fan-rpm-control") != 0)
734			continue;
735
736		fan->old_style = 0;
737		OF_getprop(child, "reg", &fan->reg, sizeof(cell_t));
738		OF_getprop(child, "min-value", &fan->min_rpm, sizeof(cell_t));
739		OF_getprop(child, "max-value", &fan->max_rpm, sizeof(cell_t));
740
741		if (OF_getprop(child, "unmanaged-value", &fan->unmanaged_rpm,
742		    sizeof(cell_t)) != sizeof(cell_t))
743			fan->unmanaged_rpm = fan->max_rpm;
744
745		fan->setpoint = smu_fan_read_rpm(dev, fan);
746
747		OF_getprop(child, "location", fan->location,
748		    sizeof(fan->location));
749
750		/* Add sysctls */
751		for (i = 0; i < strlen(fan->location); i++) {
752			sysctl_name[i] = tolower(fan->location[i]);
753			if (isspace(sysctl_name[i]))
754				sysctl_name[i] = '_';
755		}
756		sysctl_name[i] = 0;
757
758		oid = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(fanroot_oid),
759		    OID_AUTO, sysctl_name, CTLFLAG_RD, 0, "Fan Information");
760		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO, "minrpm",
761		    CTLTYPE_INT | CTLFLAG_RD, &fan->min_rpm, sizeof(cell_t),
762		    "Minimum allowed RPM");
763		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(oid), OID_AUTO, "maxrpm",
764		    CTLTYPE_INT | CTLFLAG_RD, &fan->max_rpm, sizeof(cell_t),
765		    "Maximum allowed RPM");
766		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(oid), OID_AUTO, "rpm",
767		    CTLTYPE_INT | CTLFLAG_RW, dev, sc->sc_nfans,
768		    smu_fanrpm_sysctl, "I", "Fan RPM");
769
770		fan++;
771		sc->sc_nfans++;
772	}
773}
774
775static int
776smu_sensor_read(device_t smu, struct smu_sensor *sens, int *val)
777{
778	struct smu_cmd cmd;
779	struct smu_softc *sc;
780	int64_t value;
781	int error;
782
783	cmd.cmd = SMU_ADC;
784	cmd.len = 1;
785	cmd.data[0] = sens->reg;
786	error = 0;
787
788	error = smu_run_cmd(smu, &cmd, 1);
789	if (error != 0)
790		return (error);
791
792	sc = device_get_softc(smu);
793	value = (cmd.data[0] << 8) | cmd.data[1];
794
795	switch (sens->type) {
796	case SMU_TEMP_SENSOR:
797		value *= sc->sc_cpu_diode_scale;
798		value >>= 3;
799		value += ((int64_t)sc->sc_cpu_diode_offset) << 9;
800		value <<= 1;
801
802		/* Convert from 16.16 fixed point degC into integer C. */
803		value >>= 16;
804		break;
805	case SMU_VOLTAGE_SENSOR:
806		value *= sc->sc_cpu_volt_scale;
807		value += sc->sc_cpu_volt_offset;
808		value <<= 4;
809
810		/* Convert from 16.16 fixed point V into mV. */
811		value *= 15625;
812		value /= 1024;
813		value /= 1000;
814		break;
815	case SMU_CURRENT_SENSOR:
816		value *= sc->sc_cpu_curr_scale;
817		value += sc->sc_cpu_curr_offset;
818		value <<= 4;
819
820		/* Convert from 16.16 fixed point A into mA. */
821		value *= 15625;
822		value /= 1024;
823		value /= 1000;
824		break;
825	case SMU_POWER_SENSOR:
826		value *= sc->sc_slots_pow_scale;
827		value += sc->sc_slots_pow_offset;
828		value <<= 4;
829
830		/* Convert from 16.16 fixed point W into mW. */
831		value *= 15625;
832		value /= 1024;
833		value /= 1000;
834		break;
835	}
836
837	*val = value;
838	return (0);
839}
840
841static int
842smu_sensor_sysctl(SYSCTL_HANDLER_ARGS)
843{
844	device_t smu;
845	struct smu_softc *sc;
846	struct smu_sensor *sens;
847	int value, error;
848
849	smu = arg1;
850	sc = device_get_softc(smu);
851	sens = &sc->sc_sensors[arg2];
852
853	error = smu_sensor_read(smu, sens, &value);
854	if (error != 0)
855		return (error);
856
857	error = sysctl_handle_int(oidp, &value, 0, req);
858
859	return (error);
860}
861
862static void
863smu_attach_sensors(device_t dev, phandle_t sensroot)
864{
865	struct smu_sensor *sens;
866	struct smu_softc *sc;
867	struct sysctl_oid *sensroot_oid;
868	struct sysctl_ctx_list *ctx;
869	phandle_t child;
870	char type[32];
871	int i;
872
873	sc = device_get_softc(dev);
874	sc->sc_nsensors = 0;
875
876	for (child = OF_child(sensroot); child != 0; child = OF_peer(child))
877		sc->sc_nsensors++;
878
879	if (sc->sc_nsensors == 0) {
880		device_printf(dev, "WARNING: No sensors detected!\n");
881		return;
882	}
883
884	sc->sc_sensors = malloc(sc->sc_nsensors * sizeof(struct smu_sensor),
885	    M_SMU, M_WAITOK | M_ZERO);
886
887	sens = sc->sc_sensors;
888	sc->sc_nsensors = 0;
889
890	ctx = device_get_sysctl_ctx(dev);
891	sensroot_oid = SYSCTL_ADD_NODE(ctx,
892	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "sensors",
893	    CTLFLAG_RD, 0, "SMU Sensor Information");
894
895	for (child = OF_child(sensroot); child != 0; child = OF_peer(child)) {
896		char sysctl_name[40], sysctl_desc[40];
897		const char *units;
898
899		OF_getprop(child, "device_type", type, sizeof(type));
900
901		if (strcmp(type, "current-sensor") == 0) {
902			sens->type = SMU_CURRENT_SENSOR;
903			units = "mA";
904		} else if (strcmp(type, "temp-sensor") == 0) {
905			sens->type = SMU_TEMP_SENSOR;
906			units = "C";
907		} else if (strcmp(type, "voltage-sensor") == 0) {
908			sens->type = SMU_VOLTAGE_SENSOR;
909			units = "mV";
910		} else if (strcmp(type, "power-sensor") == 0) {
911			sens->type = SMU_POWER_SENSOR;
912			units = "mW";
913		} else {
914			continue;
915		}
916
917		OF_getprop(child, "reg", &sens->reg, sizeof(cell_t));
918		OF_getprop(child, "location", sens->location,
919		    sizeof(sens->location));
920
921		for (i = 0; i < strlen(sens->location); i++) {
922			sysctl_name[i] = tolower(sens->location[i]);
923			if (isspace(sysctl_name[i]))
924				sysctl_name[i] = '_';
925		}
926		sysctl_name[i] = 0;
927
928		sprintf(sysctl_desc,"%s (%s)", sens->location, units);
929
930		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(sensroot_oid), OID_AUTO,
931		    sysctl_name, CTLTYPE_INT | CTLFLAG_RD, dev, sc->sc_nsensors,
932		    smu_sensor_sysctl, "I", sysctl_desc);
933
934		sens++;
935		sc->sc_nsensors++;
936	}
937}
938
939static void
940smu_fan_management_proc(void *xdev)
941{
942	device_t smu = xdev;
943
944	while(1) {
945		smu_manage_fans(smu);
946		pause("smu", SMU_FANMGT_INTERVAL * hz / 1000);
947	}
948}
949
950static void
951smu_manage_fans(device_t smu)
952{
953	struct smu_softc *sc;
954	int i, maxtemp, temp, factor, error;
955
956	sc = device_get_softc(smu);
957
958	maxtemp = 0;
959	for (i = 0; i < sc->sc_nsensors; i++) {
960		if (sc->sc_sensors[i].type != SMU_TEMP_SENSOR)
961			continue;
962
963		error = smu_sensor_read(smu, &sc->sc_sensors[i], &temp);
964		if (error == 0 && temp > maxtemp)
965			maxtemp = temp;
966	}
967
968	if (maxtemp < 10) { /* Bail if no good sensors */
969		for (i = 0; i < sc->sc_nfans; i++)
970			smu_fan_set_rpm(smu, &sc->sc_fans[i],
971			    sc->sc_fans[i].unmanaged_rpm);
972		return;
973	}
974
975	if (maxtemp > sc->sc_critical_temp) {
976		device_printf(smu, "WARNING: Current system temperature (%d C) "
977		    "exceeds critical temperature (%d C)! Shutting down!\n",
978		    maxtemp, sc->sc_critical_temp);
979		shutdown_nice(RB_POWEROFF);
980	}
981
982	if (maxtemp - sc->sc_target_temp > 20)
983		device_printf(smu, "WARNING: Current system temperature (%d C) "
984		    "more than 20 degrees over target temperature (%d C)!\n",
985		    maxtemp, sc->sc_target_temp);
986
987	if (time_uptime - sc->sc_lastuserchange < 3) {
988		/*
989		 * If we have heard from a user process in the last 3 seconds,
990		 * go away.
991		 */
992
993		return;
994	}
995
996	if (maxtemp - sc->sc_target_temp > 4)
997		factor = 110;
998	else if (maxtemp - sc->sc_target_temp > 1)
999		factor = 105;
1000	else if (sc->sc_target_temp - maxtemp > 4)
1001		factor = 90;
1002	else if (sc->sc_target_temp - maxtemp > 1)
1003		factor = 95;
1004	else
1005		factor = 100;
1006
1007	for (i = 0; i < sc->sc_nfans; i++)
1008		smu_fan_set_rpm(smu, &sc->sc_fans[i],
1009		    (sc->sc_fans[i].setpoint * factor) / 100);
1010}
1011
1012static void
1013smu_set_sleepled(void *xdev, int onoff)
1014{
1015	static struct smu_cmd cmd;
1016	device_t smu = xdev;
1017
1018	cmd.cmd = SMU_MISC;
1019	cmd.len = 3;
1020	cmd.data[0] = SMU_MISC_LED_CTRL;
1021	cmd.data[1] = 0;
1022	cmd.data[2] = onoff;
1023
1024	smu_run_cmd(smu, &cmd, 0);
1025}
1026
1027static int
1028smu_server_mode(SYSCTL_HANDLER_ARGS)
1029{
1030	struct smu_cmd cmd;
1031	u_int server_mode;
1032	device_t smu = arg1;
1033	int error;
1034
1035	cmd.cmd = SMU_POWER_EVENTS;
1036	cmd.len = 1;
1037	cmd.data[0] = SMU_PWR_GET_POWERUP;
1038
1039	error = smu_run_cmd(smu, &cmd, 1);
1040
1041	if (error)
1042		return (error);
1043
1044	server_mode = (cmd.data[1] & SMU_WAKEUP_AC_INSERT) ? 1 : 0;
1045
1046	error = sysctl_handle_int(oidp, &server_mode, 0, req);
1047
1048	if (error || !req->newptr)
1049		return (error);
1050
1051	if (server_mode == 1)
1052		cmd.data[0] = SMU_PWR_SET_POWERUP;
1053	else if (server_mode == 0)
1054		cmd.data[0] = SMU_PWR_CLR_POWERUP;
1055	else
1056		return (EINVAL);
1057
1058	cmd.len = 3;
1059	cmd.data[1] = 0;
1060	cmd.data[2] = SMU_WAKEUP_AC_INSERT;
1061
1062	return (smu_run_cmd(smu, &cmd, 1));
1063}
1064
1065static int
1066smu_gettime(device_t dev, struct timespec *ts)
1067{
1068	struct smu_cmd cmd;
1069	struct clocktime ct;
1070
1071	cmd.cmd = SMU_RTC;
1072	cmd.len = 1;
1073	cmd.data[0] = SMU_RTC_GET;
1074
1075	if (smu_run_cmd(dev, &cmd, 1) != 0)
1076		return (ENXIO);
1077
1078	ct.nsec	= 0;
1079	ct.sec	= bcd2bin(cmd.data[0]);
1080	ct.min	= bcd2bin(cmd.data[1]);
1081	ct.hour	= bcd2bin(cmd.data[2]);
1082	ct.dow	= bcd2bin(cmd.data[3]);
1083	ct.day	= bcd2bin(cmd.data[4]);
1084	ct.mon	= bcd2bin(cmd.data[5]);
1085	ct.year	= bcd2bin(cmd.data[6]) + 2000;
1086
1087	return (clock_ct_to_ts(&ct, ts));
1088}
1089
1090static int
1091smu_settime(device_t dev, struct timespec *ts)
1092{
1093	struct smu_cmd cmd;
1094	struct clocktime ct;
1095
1096	cmd.cmd = SMU_RTC;
1097	cmd.len = 8;
1098	cmd.data[0] = SMU_RTC_SET;
1099
1100	clock_ts_to_ct(ts, &ct);
1101
1102	cmd.data[1] = bin2bcd(ct.sec);
1103	cmd.data[2] = bin2bcd(ct.min);
1104	cmd.data[3] = bin2bcd(ct.hour);
1105	cmd.data[4] = bin2bcd(ct.dow);
1106	cmd.data[5] = bin2bcd(ct.day);
1107	cmd.data[6] = bin2bcd(ct.mon);
1108	cmd.data[7] = bin2bcd(ct.year - 2000);
1109
1110	return (smu_run_cmd(dev, &cmd, 1));
1111}
1112
1113