xref: /linux/drivers/macintosh/smu.c (revision e724e7aaf9ca794670a4d4931af7a7e24e37fec3)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * PowerMac G5 SMU driver
4  *
5  * Copyright 2004 J. Mayer <l_indien@magic.fr>
6  * Copyright 2005 Benjamin Herrenschmidt, IBM Corp.
7  */
8 
9 /*
10  * TODO:
11  *  - maybe add timeout to commands ?
12  *  - blocking version of time functions
13  *  - polling version of i2c commands (including timer that works with
14  *    interrupts off)
15  *  - maybe avoid some data copies with i2c by directly using the smu cmd
16  *    buffer and a lower level internal interface
17  *  - understand SMU -> CPU events and implement reception of them via
18  *    the userland interface
19  */
20 
21 #include <linux/types.h>
22 #include <linux/kernel.h>
23 #include <linux/device.h>
24 #include <linux/dmapool.h>
25 #include <linux/memblock.h>
26 #include <linux/vmalloc.h>
27 #include <linux/highmem.h>
28 #include <linux/jiffies.h>
29 #include <linux/interrupt.h>
30 #include <linux/rtc.h>
31 #include <linux/completion.h>
32 #include <linux/miscdevice.h>
33 #include <linux/delay.h>
34 #include <linux/poll.h>
35 #include <linux/mutex.h>
36 #include <linux/of.h>
37 #include <linux/of_address.h>
38 #include <linux/of_irq.h>
39 #include <linux/of_platform.h>
40 #include <linux/slab.h>
41 #include <linux/sched/signal.h>
42 
43 #include <asm/byteorder.h>
44 #include <asm/io.h>
45 #include <asm/machdep.h>
46 #include <asm/pmac_feature.h>
47 #include <asm/smu.h>
48 #include <asm/sections.h>
49 #include <linux/uaccess.h>
50 
51 #define VERSION "0.7"
52 #define AUTHOR  "(c) 2005 Benjamin Herrenschmidt, IBM Corp."
53 
54 #undef DEBUG_SMU
55 
56 #ifdef DEBUG_SMU
57 #define DPRINTK(fmt, args...) do { printk(KERN_DEBUG fmt , ##args); } while (0)
58 #else
59 #define DPRINTK(fmt, args...) do { } while (0)
60 #endif
61 
62 /*
63  * This is the command buffer passed to the SMU hardware
64  */
65 #define SMU_MAX_DATA	254
66 
67 struct smu_cmd_buf {
68 	u8 cmd;
69 	u8 length;
70 	u8 data[SMU_MAX_DATA];
71 };
72 
73 struct smu_device {
74 	spinlock_t		lock;
75 	struct device_node	*of_node;
76 	struct platform_device	*of_dev;
77 	int			doorbell;	/* doorbell gpio */
78 	u32 __iomem		*db_buf;	/* doorbell buffer */
79 	struct device_node	*db_node;
80 	unsigned int		db_irq;
81 	int			msg;
82 	struct device_node	*msg_node;
83 	unsigned int		msg_irq;
84 	struct smu_cmd_buf	*cmd_buf;	/* command buffer virtual */
85 	u32			cmd_buf_abs;	/* command buffer absolute */
86 	struct list_head	cmd_list;
87 	struct smu_cmd		*cmd_cur;	/* pending command */
88 	int			broken_nap;
89 	struct list_head	cmd_i2c_list;
90 	struct smu_i2c_cmd	*cmd_i2c_cur;	/* pending i2c command */
91 	struct timer_list	i2c_timer;
92 };
93 
94 /*
95  * I don't think there will ever be more than one SMU, so
96  * for now, just hard code that
97  */
98 static DEFINE_MUTEX(smu_mutex);
99 static struct smu_device	*smu;
100 static DEFINE_MUTEX(smu_part_access);
101 static int smu_irq_inited;
102 static unsigned long smu_cmdbuf_abs;
103 
104 static void smu_i2c_retry(struct timer_list *t);
105 
106 /*
107  * SMU driver low level stuff
108  */
109 
110 static void smu_start_cmd(void)
111 {
112 	unsigned long faddr, fend;
113 	struct smu_cmd *cmd;
114 
115 	if (list_empty(&smu->cmd_list))
116 		return;
117 
118 	/* Fetch first command in queue */
119 	cmd = list_entry(smu->cmd_list.next, struct smu_cmd, link);
120 	smu->cmd_cur = cmd;
121 	list_del(&cmd->link);
122 
123 	DPRINTK("SMU: starting cmd %x, %d bytes data\n", cmd->cmd,
124 		cmd->data_len);
125 	DPRINTK("SMU: data buffer: %8ph\n", cmd->data_buf);
126 
127 	/* Fill the SMU command buffer */
128 	smu->cmd_buf->cmd = cmd->cmd;
129 	smu->cmd_buf->length = cmd->data_len;
130 	memcpy(smu->cmd_buf->data, cmd->data_buf, cmd->data_len);
131 
132 	/* Flush command and data to RAM */
133 	faddr = (unsigned long)smu->cmd_buf;
134 	fend = faddr + smu->cmd_buf->length + 2;
135 	flush_dcache_range(faddr, fend);
136 
137 
138 	/* We also disable NAP mode for the duration of the command
139 	 * on U3 based machines.
140 	 * This is slightly racy as it can be written back to 1 by a sysctl
141 	 * but that never happens in practice. There seem to be an issue with
142 	 * U3 based machines such as the iMac G5 where napping for the
143 	 * whole duration of the command prevents the SMU from fetching it
144 	 * from memory. This might be related to the strange i2c based
145 	 * mechanism the SMU uses to access memory.
146 	 */
147 	if (smu->broken_nap)
148 		powersave_nap = 0;
149 
150 	/* This isn't exactly a DMA mapping here, I suspect
151 	 * the SMU is actually communicating with us via i2c to the
152 	 * northbridge or the CPU to access RAM.
153 	 */
154 	writel(smu->cmd_buf_abs, smu->db_buf);
155 
156 	/* Ring the SMU doorbell */
157 	pmac_do_feature_call(PMAC_FTR_WRITE_GPIO, NULL, smu->doorbell, 4);
158 }
159 
160 
161 static irqreturn_t smu_db_intr(int irq, void *arg)
162 {
163 	unsigned long flags;
164 	struct smu_cmd *cmd;
165 	void (*done)(struct smu_cmd *cmd, void *misc) = NULL;
166 	void *misc = NULL;
167 	u8 gpio;
168 	int rc = 0;
169 
170 	/* SMU completed the command, well, we hope, let's make sure
171 	 * of it
172 	 */
173 	spin_lock_irqsave(&smu->lock, flags);
174 
175 	gpio = pmac_do_feature_call(PMAC_FTR_READ_GPIO, NULL, smu->doorbell);
176 	if ((gpio & 7) != 7) {
177 		spin_unlock_irqrestore(&smu->lock, flags);
178 		return IRQ_HANDLED;
179 	}
180 
181 	cmd = smu->cmd_cur;
182 	smu->cmd_cur = NULL;
183 	if (cmd == NULL)
184 		goto bail;
185 
186 	if (rc == 0) {
187 		unsigned long faddr;
188 		int reply_len;
189 		u8 ack;
190 
191 		/* CPU might have brought back the cache line, so we need
192 		 * to flush again before peeking at the SMU response. We
193 		 * flush the entire buffer for now as we haven't read the
194 		 * reply length (it's only 2 cache lines anyway)
195 		 */
196 		faddr = (unsigned long)smu->cmd_buf;
197 		flush_dcache_range(faddr, faddr + 256);
198 
199 		/* Now check ack */
200 		ack = (~cmd->cmd) & 0xff;
201 		if (ack != smu->cmd_buf->cmd) {
202 			DPRINTK("SMU: incorrect ack, want %x got %x\n",
203 				ack, smu->cmd_buf->cmd);
204 			rc = -EIO;
205 		}
206 		reply_len = rc == 0 ? smu->cmd_buf->length : 0;
207 		DPRINTK("SMU: reply len: %d\n", reply_len);
208 		if (reply_len > cmd->reply_len) {
209 			printk(KERN_WARNING "SMU: reply buffer too small,"
210 			       "got %d bytes for a %d bytes buffer\n",
211 			       reply_len, cmd->reply_len);
212 			reply_len = cmd->reply_len;
213 		}
214 		cmd->reply_len = reply_len;
215 		if (cmd->reply_buf && reply_len)
216 			memcpy(cmd->reply_buf, smu->cmd_buf->data, reply_len);
217 	}
218 
219 	/* Now complete the command. Write status last in order as we lost
220 	 * ownership of the command structure as soon as it's no longer -1
221 	 */
222 	done = cmd->done;
223 	misc = cmd->misc;
224 	mb();
225 	cmd->status = rc;
226 
227 	/* Re-enable NAP mode */
228 	if (smu->broken_nap)
229 		powersave_nap = 1;
230  bail:
231 	/* Start next command if any */
232 	smu_start_cmd();
233 	spin_unlock_irqrestore(&smu->lock, flags);
234 
235 	/* Call command completion handler if any */
236 	if (done)
237 		done(cmd, misc);
238 
239 	/* It's an edge interrupt, nothing to do */
240 	return IRQ_HANDLED;
241 }
242 
243 
244 static irqreturn_t smu_msg_intr(int irq, void *arg)
245 {
246 	/* I don't quite know what to do with this one, we seem to never
247 	 * receive it, so I suspect we have to arm it someway in the SMU
248 	 * to start getting events that way.
249 	 */
250 
251 	printk(KERN_INFO "SMU: message interrupt !\n");
252 
253 	/* It's an edge interrupt, nothing to do */
254 	return IRQ_HANDLED;
255 }
256 
257 
258 /*
259  * Queued command management.
260  *
261  */
262 
263 int smu_queue_cmd(struct smu_cmd *cmd)
264 {
265 	unsigned long flags;
266 
267 	if (smu == NULL)
268 		return -ENODEV;
269 	if (cmd->data_len > SMU_MAX_DATA ||
270 	    cmd->reply_len > SMU_MAX_DATA)
271 		return -EINVAL;
272 
273 	cmd->status = 1;
274 	spin_lock_irqsave(&smu->lock, flags);
275 	list_add_tail(&cmd->link, &smu->cmd_list);
276 	if (smu->cmd_cur == NULL)
277 		smu_start_cmd();
278 	spin_unlock_irqrestore(&smu->lock, flags);
279 
280 	/* Workaround for early calls when irq isn't available */
281 	if (!smu_irq_inited || !smu->db_irq)
282 		smu_spinwait_cmd(cmd);
283 
284 	return 0;
285 }
286 EXPORT_SYMBOL(smu_queue_cmd);
287 
288 
289 int smu_queue_simple(struct smu_simple_cmd *scmd, u8 command,
290 		     unsigned int data_len,
291 		     void (*done)(struct smu_cmd *cmd, void *misc),
292 		     void *misc, ...)
293 {
294 	struct smu_cmd *cmd = &scmd->cmd;
295 	va_list list;
296 	int i;
297 
298 	if (data_len > sizeof(scmd->buffer))
299 		return -EINVAL;
300 
301 	memset(scmd, 0, sizeof(*scmd));
302 	cmd->cmd = command;
303 	cmd->data_len = data_len;
304 	cmd->data_buf = scmd->buffer;
305 	cmd->reply_len = sizeof(scmd->buffer);
306 	cmd->reply_buf = scmd->buffer;
307 	cmd->done = done;
308 	cmd->misc = misc;
309 
310 	va_start(list, misc);
311 	for (i = 0; i < data_len; ++i)
312 		scmd->buffer[i] = (u8)va_arg(list, int);
313 	va_end(list);
314 
315 	return smu_queue_cmd(cmd);
316 }
317 EXPORT_SYMBOL(smu_queue_simple);
318 
319 
320 void smu_poll(void)
321 {
322 	u8 gpio;
323 
324 	if (smu == NULL)
325 		return;
326 
327 	gpio = pmac_do_feature_call(PMAC_FTR_READ_GPIO, NULL, smu->doorbell);
328 	if ((gpio & 7) == 7)
329 		smu_db_intr(smu->db_irq, smu);
330 }
331 EXPORT_SYMBOL(smu_poll);
332 
333 
334 void smu_done_complete(struct smu_cmd *cmd, void *misc)
335 {
336 	struct completion *comp = misc;
337 
338 	complete(comp);
339 }
340 EXPORT_SYMBOL(smu_done_complete);
341 
342 
343 void smu_spinwait_cmd(struct smu_cmd *cmd)
344 {
345 	while(cmd->status == 1)
346 		smu_poll();
347 }
348 EXPORT_SYMBOL(smu_spinwait_cmd);
349 
350 
351 /* RTC low level commands */
352 static inline int bcd2hex (int n)
353 {
354 	return (((n & 0xf0) >> 4) * 10) + (n & 0xf);
355 }
356 
357 
358 static inline int hex2bcd (int n)
359 {
360 	return ((n / 10) << 4) + (n % 10);
361 }
362 
363 
364 static inline void smu_fill_set_rtc_cmd(struct smu_cmd_buf *cmd_buf,
365 					struct rtc_time *time)
366 {
367 	cmd_buf->cmd = 0x8e;
368 	cmd_buf->length = 8;
369 	cmd_buf->data[0] = 0x80;
370 	cmd_buf->data[1] = hex2bcd(time->tm_sec);
371 	cmd_buf->data[2] = hex2bcd(time->tm_min);
372 	cmd_buf->data[3] = hex2bcd(time->tm_hour);
373 	cmd_buf->data[4] = time->tm_wday;
374 	cmd_buf->data[5] = hex2bcd(time->tm_mday);
375 	cmd_buf->data[6] = hex2bcd(time->tm_mon) + 1;
376 	cmd_buf->data[7] = hex2bcd(time->tm_year - 100);
377 }
378 
379 
380 int smu_get_rtc_time(struct rtc_time *time, int spinwait)
381 {
382 	struct smu_simple_cmd cmd;
383 	int rc;
384 
385 	if (smu == NULL)
386 		return -ENODEV;
387 
388 	memset(time, 0, sizeof(struct rtc_time));
389 	rc = smu_queue_simple(&cmd, SMU_CMD_RTC_COMMAND, 1, NULL, NULL,
390 			      SMU_CMD_RTC_GET_DATETIME);
391 	if (rc)
392 		return rc;
393 	smu_spinwait_simple(&cmd);
394 
395 	time->tm_sec = bcd2hex(cmd.buffer[0]);
396 	time->tm_min = bcd2hex(cmd.buffer[1]);
397 	time->tm_hour = bcd2hex(cmd.buffer[2]);
398 	time->tm_wday = bcd2hex(cmd.buffer[3]);
399 	time->tm_mday = bcd2hex(cmd.buffer[4]);
400 	time->tm_mon = bcd2hex(cmd.buffer[5]) - 1;
401 	time->tm_year = bcd2hex(cmd.buffer[6]) + 100;
402 
403 	return 0;
404 }
405 
406 
407 int smu_set_rtc_time(struct rtc_time *time, int spinwait)
408 {
409 	struct smu_simple_cmd cmd;
410 	int rc;
411 
412 	if (smu == NULL)
413 		return -ENODEV;
414 
415 	rc = smu_queue_simple(&cmd, SMU_CMD_RTC_COMMAND, 8, NULL, NULL,
416 			      SMU_CMD_RTC_SET_DATETIME,
417 			      hex2bcd(time->tm_sec),
418 			      hex2bcd(time->tm_min),
419 			      hex2bcd(time->tm_hour),
420 			      time->tm_wday,
421 			      hex2bcd(time->tm_mday),
422 			      hex2bcd(time->tm_mon) + 1,
423 			      hex2bcd(time->tm_year - 100));
424 	if (rc)
425 		return rc;
426 	smu_spinwait_simple(&cmd);
427 
428 	return 0;
429 }
430 
431 
432 void smu_shutdown(void)
433 {
434 	struct smu_simple_cmd cmd;
435 
436 	if (smu == NULL)
437 		return;
438 
439 	if (smu_queue_simple(&cmd, SMU_CMD_POWER_COMMAND, 9, NULL, NULL,
440 			     'S', 'H', 'U', 'T', 'D', 'O', 'W', 'N', 0))
441 		return;
442 	smu_spinwait_simple(&cmd);
443 	for (;;)
444 		;
445 }
446 
447 
448 void smu_restart(void)
449 {
450 	struct smu_simple_cmd cmd;
451 
452 	if (smu == NULL)
453 		return;
454 
455 	if (smu_queue_simple(&cmd, SMU_CMD_POWER_COMMAND, 8, NULL, NULL,
456 			     'R', 'E', 'S', 'T', 'A', 'R', 'T', 0))
457 		return;
458 	smu_spinwait_simple(&cmd);
459 	for (;;)
460 		;
461 }
462 
463 
464 int smu_present(void)
465 {
466 	return smu != NULL;
467 }
468 EXPORT_SYMBOL(smu_present);
469 
470 
471 int __init smu_init (void)
472 {
473 	struct device_node *np;
474 	u64 data;
475 	int ret = 0;
476 
477         np = of_find_node_by_type(NULL, "smu");
478         if (np == NULL)
479 		return -ENODEV;
480 
481 	printk(KERN_INFO "SMU: Driver %s %s\n", VERSION, AUTHOR);
482 
483 	/*
484 	 * SMU based G5s need some memory below 2Gb. Thankfully this is
485 	 * called at a time where memblock is still available.
486 	 */
487 	smu_cmdbuf_abs = memblock_phys_alloc_range(4096, 4096, 0, 0x80000000UL);
488 	if (smu_cmdbuf_abs == 0) {
489 		printk(KERN_ERR "SMU: Command buffer allocation failed !\n");
490 		ret = -EINVAL;
491 		goto fail_np;
492 	}
493 
494 	smu = memblock_alloc(sizeof(struct smu_device), SMP_CACHE_BYTES);
495 	if (!smu)
496 		panic("%s: Failed to allocate %zu bytes\n", __func__,
497 		      sizeof(struct smu_device));
498 
499 	spin_lock_init(&smu->lock);
500 	INIT_LIST_HEAD(&smu->cmd_list);
501 	INIT_LIST_HEAD(&smu->cmd_i2c_list);
502 	smu->of_node = np;
503 	smu->db_irq = 0;
504 	smu->msg_irq = 0;
505 
506 	/* smu_cmdbuf_abs is in the low 2G of RAM, can be converted to a
507 	 * 32 bits value safely
508 	 */
509 	smu->cmd_buf_abs = (u32)smu_cmdbuf_abs;
510 	smu->cmd_buf = __va(smu_cmdbuf_abs);
511 
512 	smu->db_node = of_find_node_by_name(NULL, "smu-doorbell");
513 	if (smu->db_node == NULL) {
514 		printk(KERN_ERR "SMU: Can't find doorbell GPIO !\n");
515 		ret = -ENXIO;
516 		goto fail_bootmem;
517 	}
518 	if (of_property_read_reg(smu->db_node, 0, &data, NULL)) {
519 		printk(KERN_ERR "SMU: Can't find doorbell GPIO address !\n");
520 		ret = -ENXIO;
521 		goto fail_db_node;
522 	}
523 
524 	/* Current setup has one doorbell GPIO that does both doorbell
525 	 * and ack. GPIOs are at 0x50, best would be to find that out
526 	 * in the device-tree though.
527 	 */
528 	smu->doorbell = data;
529 	if (smu->doorbell < 0x50)
530 		smu->doorbell += 0x50;
531 
532 	/* Now look for the smu-interrupt GPIO */
533 	do {
534 		smu->msg_node = of_find_node_by_name(NULL, "smu-interrupt");
535 		if (smu->msg_node == NULL)
536 			break;
537 		if (of_property_read_reg(smu->msg_node, 0, &data, NULL)) {
538 			of_node_put(smu->msg_node);
539 			smu->msg_node = NULL;
540 			break;
541 		}
542 		smu->msg = data;
543 		if (smu->msg < 0x50)
544 			smu->msg += 0x50;
545 	} while(0);
546 
547 	/* Doorbell buffer is currently hard-coded, I didn't find a proper
548 	 * device-tree entry giving the address. Best would probably to use
549 	 * an offset for K2 base though, but let's do it that way for now.
550 	 */
551 	smu->db_buf = ioremap(0x8000860c, 0x1000);
552 	if (smu->db_buf == NULL) {
553 		printk(KERN_ERR "SMU: Can't map doorbell buffer pointer !\n");
554 		ret = -ENXIO;
555 		goto fail_msg_node;
556 	}
557 
558 	/* U3 has an issue with NAP mode when issuing SMU commands */
559 	smu->broken_nap = pmac_get_uninorth_variant() < 4;
560 	if (smu->broken_nap)
561 		printk(KERN_INFO "SMU: using NAP mode workaround\n");
562 
563 	sys_ctrler = SYS_CTRLER_SMU;
564 	return 0;
565 
566 fail_msg_node:
567 	of_node_put(smu->msg_node);
568 fail_db_node:
569 	of_node_put(smu->db_node);
570 fail_bootmem:
571 	memblock_free(smu, sizeof(struct smu_device));
572 	smu = NULL;
573 fail_np:
574 	of_node_put(np);
575 	return ret;
576 }
577 
578 
579 static int smu_late_init(void)
580 {
581 	if (!smu)
582 		return 0;
583 
584 	timer_setup(&smu->i2c_timer, smu_i2c_retry, 0);
585 
586 	if (smu->db_node) {
587 		smu->db_irq = irq_of_parse_and_map(smu->db_node, 0);
588 		if (!smu->db_irq)
589 			printk(KERN_ERR "smu: failed to map irq for node %pOF\n",
590 			       smu->db_node);
591 	}
592 	if (smu->msg_node) {
593 		smu->msg_irq = irq_of_parse_and_map(smu->msg_node, 0);
594 		if (!smu->msg_irq)
595 			printk(KERN_ERR "smu: failed to map irq for node %pOF\n",
596 			       smu->msg_node);
597 	}
598 
599 	/*
600 	 * Try to request the interrupts
601 	 */
602 
603 	if (smu->db_irq) {
604 		if (request_irq(smu->db_irq, smu_db_intr,
605 				IRQF_SHARED, "SMU doorbell", smu) < 0) {
606 			printk(KERN_WARNING "SMU: can't "
607 			       "request interrupt %d\n",
608 			       smu->db_irq);
609 			smu->db_irq = 0;
610 		}
611 	}
612 
613 	if (smu->msg_irq) {
614 		if (request_irq(smu->msg_irq, smu_msg_intr,
615 				IRQF_SHARED, "SMU message", smu) < 0) {
616 			printk(KERN_WARNING "SMU: can't "
617 			       "request interrupt %d\n",
618 			       smu->msg_irq);
619 			smu->msg_irq = 0;
620 		}
621 	}
622 
623 	smu_irq_inited = 1;
624 	return 0;
625 }
626 /* This has to be before arch_initcall as the low i2c stuff relies on the
627  * above having been done before we reach arch_initcalls
628  */
629 core_initcall(smu_late_init);
630 
631 /*
632  * sysfs visibility
633  */
634 
635 static void smu_expose_childs(struct work_struct *unused)
636 {
637 	struct device_node *np;
638 
639 	for_each_child_of_node(smu->of_node, np)
640 		if (of_device_is_compatible(np, "smu-sensors"))
641 			of_platform_device_create(np, "smu-sensors",
642 						  &smu->of_dev->dev);
643 }
644 
645 static DECLARE_WORK(smu_expose_childs_work, smu_expose_childs);
646 
647 static int smu_platform_probe(struct platform_device* dev)
648 {
649 	if (!smu)
650 		return -ENODEV;
651 	smu->of_dev = dev;
652 
653 	/*
654 	 * Ok, we are matched, now expose all i2c busses. We have to defer
655 	 * that unfortunately or it would deadlock inside the device model
656 	 */
657 	schedule_work(&smu_expose_childs_work);
658 
659 	return 0;
660 }
661 
662 static const struct of_device_id smu_platform_match[] =
663 {
664 	{
665 		.type		= "smu",
666 	},
667 	{},
668 };
669 
670 static struct platform_driver smu_of_platform_driver =
671 {
672 	.driver = {
673 		.name = "smu",
674 		.of_match_table = smu_platform_match,
675 	},
676 	.probe		= smu_platform_probe,
677 };
678 
679 static int __init smu_init_sysfs(void)
680 {
681 	/*
682 	 * For now, we don't power manage machines with an SMU chip,
683 	 * I'm a bit too far from figuring out how that works with those
684 	 * new chipsets, but that will come back and bite us
685 	 */
686 	platform_driver_register(&smu_of_platform_driver);
687 	return 0;
688 }
689 
690 device_initcall(smu_init_sysfs);
691 
692 struct platform_device *smu_get_ofdev(void)
693 {
694 	if (!smu)
695 		return NULL;
696 	return smu->of_dev;
697 }
698 
699 EXPORT_SYMBOL_GPL(smu_get_ofdev);
700 
701 /*
702  * i2c interface
703  */
704 
705 static void smu_i2c_complete_command(struct smu_i2c_cmd *cmd, int fail)
706 {
707 	void (*done)(struct smu_i2c_cmd *cmd, void *misc) = cmd->done;
708 	void *misc = cmd->misc;
709 	unsigned long flags;
710 
711 	/* Check for read case */
712 	if (!fail && cmd->read) {
713 		if (cmd->pdata[0] < 1)
714 			fail = 1;
715 		else
716 			memcpy(cmd->info.data, &cmd->pdata[1],
717 			       cmd->info.datalen);
718 	}
719 
720 	DPRINTK("SMU: completing, success: %d\n", !fail);
721 
722 	/* Update status and mark no pending i2c command with lock
723 	 * held so nobody comes in while we dequeue an eventual
724 	 * pending next i2c command
725 	 */
726 	spin_lock_irqsave(&smu->lock, flags);
727 	smu->cmd_i2c_cur = NULL;
728 	wmb();
729 	cmd->status = fail ? -EIO : 0;
730 
731 	/* Is there another i2c command waiting ? */
732 	if (!list_empty(&smu->cmd_i2c_list)) {
733 		struct smu_i2c_cmd *newcmd;
734 
735 		/* Fetch it, new current, remove from list */
736 		newcmd = list_entry(smu->cmd_i2c_list.next,
737 				    struct smu_i2c_cmd, link);
738 		smu->cmd_i2c_cur = newcmd;
739 		list_del(&cmd->link);
740 
741 		/* Queue with low level smu */
742 		list_add_tail(&cmd->scmd.link, &smu->cmd_list);
743 		if (smu->cmd_cur == NULL)
744 			smu_start_cmd();
745 	}
746 	spin_unlock_irqrestore(&smu->lock, flags);
747 
748 	/* Call command completion handler if any */
749 	if (done)
750 		done(cmd, misc);
751 
752 }
753 
754 
755 static void smu_i2c_retry(struct timer_list *unused)
756 {
757 	struct smu_i2c_cmd	*cmd = smu->cmd_i2c_cur;
758 
759 	DPRINTK("SMU: i2c failure, requeuing...\n");
760 
761 	/* requeue command simply by resetting reply_len */
762 	cmd->pdata[0] = 0xff;
763 	cmd->scmd.reply_len = sizeof(cmd->pdata);
764 	smu_queue_cmd(&cmd->scmd);
765 }
766 
767 
768 static void smu_i2c_low_completion(struct smu_cmd *scmd, void *misc)
769 {
770 	struct smu_i2c_cmd	*cmd = misc;
771 	int			fail = 0;
772 
773 	DPRINTK("SMU: i2c compl. stage=%d status=%x pdata[0]=%x rlen: %x\n",
774 		cmd->stage, scmd->status, cmd->pdata[0], scmd->reply_len);
775 
776 	/* Check for possible status */
777 	if (scmd->status < 0)
778 		fail = 1;
779 	else if (cmd->read) {
780 		if (cmd->stage == 0)
781 			fail = cmd->pdata[0] != 0;
782 		else
783 			fail = cmd->pdata[0] >= 0x80;
784 	} else {
785 		fail = cmd->pdata[0] != 0;
786 	}
787 
788 	/* Handle failures by requeuing command, after 5ms interval
789 	 */
790 	if (fail && --cmd->retries > 0) {
791 		DPRINTK("SMU: i2c failure, starting timer...\n");
792 		BUG_ON(cmd != smu->cmd_i2c_cur);
793 		if (!smu_irq_inited) {
794 			mdelay(5);
795 			smu_i2c_retry(NULL);
796 			return;
797 		}
798 		mod_timer(&smu->i2c_timer, jiffies + msecs_to_jiffies(5));
799 		return;
800 	}
801 
802 	/* If failure or stage 1, command is complete */
803 	if (fail || cmd->stage != 0) {
804 		smu_i2c_complete_command(cmd, fail);
805 		return;
806 	}
807 
808 	DPRINTK("SMU: going to stage 1\n");
809 
810 	/* Ok, initial command complete, now poll status */
811 	scmd->reply_buf = cmd->pdata;
812 	scmd->reply_len = sizeof(cmd->pdata);
813 	scmd->data_buf = cmd->pdata;
814 	scmd->data_len = 1;
815 	cmd->pdata[0] = 0;
816 	cmd->stage = 1;
817 	cmd->retries = 20;
818 	smu_queue_cmd(scmd);
819 }
820 
821 
822 int smu_queue_i2c(struct smu_i2c_cmd *cmd)
823 {
824 	unsigned long flags;
825 
826 	if (smu == NULL)
827 		return -ENODEV;
828 
829 	/* Fill most fields of scmd */
830 	cmd->scmd.cmd = SMU_CMD_I2C_COMMAND;
831 	cmd->scmd.done = smu_i2c_low_completion;
832 	cmd->scmd.misc = cmd;
833 	cmd->scmd.reply_buf = cmd->pdata;
834 	cmd->scmd.reply_len = sizeof(cmd->pdata);
835 	cmd->scmd.data_buf = (u8 *)(char *)&cmd->info;
836 	cmd->scmd.status = 1;
837 	cmd->stage = 0;
838 	cmd->pdata[0] = 0xff;
839 	cmd->retries = 20;
840 	cmd->status = 1;
841 
842 	/* Check transfer type, sanitize some "info" fields
843 	 * based on transfer type and do more checking
844 	 */
845 	cmd->info.caddr = cmd->info.devaddr;
846 	cmd->read = cmd->info.devaddr & 0x01;
847 	switch(cmd->info.type) {
848 	case SMU_I2C_TRANSFER_SIMPLE:
849 		cmd->info.sublen = 0;
850 		memset(cmd->info.subaddr, 0, sizeof(cmd->info.subaddr));
851 		break;
852 	case SMU_I2C_TRANSFER_COMBINED:
853 		cmd->info.devaddr &= 0xfe;
854 		fallthrough;
855 	case SMU_I2C_TRANSFER_STDSUB:
856 		if (cmd->info.sublen > 3)
857 			return -EINVAL;
858 		break;
859 	default:
860 		return -EINVAL;
861 	}
862 
863 	/* Finish setting up command based on transfer direction
864 	 */
865 	if (cmd->read) {
866 		if (cmd->info.datalen > SMU_I2C_READ_MAX)
867 			return -EINVAL;
868 		memset(cmd->info.data, 0xff, cmd->info.datalen);
869 		cmd->scmd.data_len = 9;
870 	} else {
871 		if (cmd->info.datalen > SMU_I2C_WRITE_MAX)
872 			return -EINVAL;
873 		cmd->scmd.data_len = 9 + cmd->info.datalen;
874 	}
875 
876 	DPRINTK("SMU: i2c enqueuing command\n");
877 	DPRINTK("SMU:   %s, len=%d bus=%x addr=%x sub0=%x type=%x\n",
878 		cmd->read ? "read" : "write", cmd->info.datalen,
879 		cmd->info.bus, cmd->info.caddr,
880 		cmd->info.subaddr[0], cmd->info.type);
881 
882 
883 	/* Enqueue command in i2c list, and if empty, enqueue also in
884 	 * main command list
885 	 */
886 	spin_lock_irqsave(&smu->lock, flags);
887 	if (smu->cmd_i2c_cur == NULL) {
888 		smu->cmd_i2c_cur = cmd;
889 		list_add_tail(&cmd->scmd.link, &smu->cmd_list);
890 		if (smu->cmd_cur == NULL)
891 			smu_start_cmd();
892 	} else
893 		list_add_tail(&cmd->link, &smu->cmd_i2c_list);
894 	spin_unlock_irqrestore(&smu->lock, flags);
895 
896 	return 0;
897 }
898 
899 /*
900  * Handling of "partitions"
901  */
902 
903 static int smu_read_datablock(u8 *dest, unsigned int addr, unsigned int len)
904 {
905 	DECLARE_COMPLETION_ONSTACK(comp);
906 	unsigned int chunk;
907 	struct smu_cmd cmd;
908 	int rc;
909 	u8 params[8];
910 
911 	/* We currently use a chunk size of 0xe. We could check the
912 	 * SMU firmware version and use bigger sizes though
913 	 */
914 	chunk = 0xe;
915 
916 	while (len) {
917 		unsigned int clen = min(len, chunk);
918 
919 		cmd.cmd = SMU_CMD_MISC_ee_COMMAND;
920 		cmd.data_len = 7;
921 		cmd.data_buf = params;
922 		cmd.reply_len = chunk;
923 		cmd.reply_buf = dest;
924 		cmd.done = smu_done_complete;
925 		cmd.misc = &comp;
926 		params[0] = SMU_CMD_MISC_ee_GET_DATABLOCK_REC;
927 		params[1] = 0x4;
928 		*((u32 *)&params[2]) = addr;
929 		params[6] = clen;
930 
931 		rc = smu_queue_cmd(&cmd);
932 		if (rc)
933 			return rc;
934 		wait_for_completion(&comp);
935 		if (cmd.status != 0)
936 			return rc;
937 		if (cmd.reply_len != clen) {
938 			printk(KERN_DEBUG "SMU: short read in "
939 			       "smu_read_datablock, got: %d, want: %d\n",
940 			       cmd.reply_len, clen);
941 			return -EIO;
942 		}
943 		len -= clen;
944 		addr += clen;
945 		dest += clen;
946 	}
947 	return 0;
948 }
949 
950 static struct smu_sdbp_header *smu_create_sdb_partition(int id)
951 {
952 	DECLARE_COMPLETION_ONSTACK(comp);
953 	struct smu_simple_cmd cmd;
954 	unsigned int addr, len, tlen;
955 	struct smu_sdbp_header *hdr;
956 	struct property *prop;
957 
958 	/* First query the partition info */
959 	DPRINTK("SMU: Query partition infos ... (irq=%d)\n", smu->db_irq);
960 	smu_queue_simple(&cmd, SMU_CMD_PARTITION_COMMAND, 2,
961 			 smu_done_complete, &comp,
962 			 SMU_CMD_PARTITION_LATEST, id);
963 	wait_for_completion(&comp);
964 	DPRINTK("SMU: done, status: %d, reply_len: %d\n",
965 		cmd.cmd.status, cmd.cmd.reply_len);
966 
967 	/* Partition doesn't exist (or other error) */
968 	if (cmd.cmd.status != 0 || cmd.cmd.reply_len != 6)
969 		return NULL;
970 
971 	/* Fetch address and length from reply */
972 	addr = *((u16 *)cmd.buffer);
973 	len = cmd.buffer[3] << 2;
974 	/* Calucluate total length to allocate, including the 17 bytes
975 	 * for "sdb-partition-XX" that we append at the end of the buffer
976 	 */
977 	tlen = sizeof(struct property) + len + 18;
978 
979 	prop = kzalloc(tlen, GFP_KERNEL);
980 	if (prop == NULL)
981 		return NULL;
982 	hdr = (struct smu_sdbp_header *)(prop + 1);
983 	prop->name = ((char *)prop) + tlen - 18;
984 	sprintf(prop->name, "sdb-partition-%02x", id);
985 	prop->length = len;
986 	prop->value = hdr;
987 	prop->next = NULL;
988 
989 	/* Read the datablock */
990 	if (smu_read_datablock((u8 *)hdr, addr, len)) {
991 		printk(KERN_DEBUG "SMU: datablock read failed while reading "
992 		       "partition %02x !\n", id);
993 		goto failure;
994 	}
995 
996 	/* Got it, check a few things and create the property */
997 	if (hdr->id != id) {
998 		printk(KERN_DEBUG "SMU: Reading partition %02x and got "
999 		       "%02x !\n", id, hdr->id);
1000 		goto failure;
1001 	}
1002 	if (of_add_property(smu->of_node, prop)) {
1003 		printk(KERN_DEBUG "SMU: Failed creating sdb-partition-%02x "
1004 		       "property !\n", id);
1005 		goto failure;
1006 	}
1007 
1008 	return hdr;
1009  failure:
1010 	kfree(prop);
1011 	return NULL;
1012 }
1013 
1014 /* Note: Only allowed to return error code in pointers (using ERR_PTR)
1015  * when interruptible is 1
1016  */
1017 static const struct smu_sdbp_header *__smu_get_sdb_partition(int id,
1018 		unsigned int *size, int interruptible)
1019 {
1020 	char pname[32];
1021 	const struct smu_sdbp_header *part;
1022 
1023 	if (!smu)
1024 		return NULL;
1025 
1026 	sprintf(pname, "sdb-partition-%02x", id);
1027 
1028 	DPRINTK("smu_get_sdb_partition(%02x)\n", id);
1029 
1030 	if (interruptible) {
1031 		int rc;
1032 		rc = mutex_lock_interruptible(&smu_part_access);
1033 		if (rc)
1034 			return ERR_PTR(rc);
1035 	} else
1036 		mutex_lock(&smu_part_access);
1037 
1038 	part = of_get_property(smu->of_node, pname, size);
1039 	if (part == NULL) {
1040 		DPRINTK("trying to extract from SMU ...\n");
1041 		part = smu_create_sdb_partition(id);
1042 		if (part != NULL && size)
1043 			*size = part->len << 2;
1044 	}
1045 	mutex_unlock(&smu_part_access);
1046 	return part;
1047 }
1048 
1049 const struct smu_sdbp_header *smu_get_sdb_partition(int id, unsigned int *size)
1050 {
1051 	return __smu_get_sdb_partition(id, size, 0);
1052 }
1053 EXPORT_SYMBOL(smu_get_sdb_partition);
1054 
1055 
1056 /*
1057  * Userland driver interface
1058  */
1059 
1060 
1061 static LIST_HEAD(smu_clist);
1062 static DEFINE_SPINLOCK(smu_clist_lock);
1063 
1064 enum smu_file_mode {
1065 	smu_file_commands,
1066 	smu_file_events,
1067 	smu_file_closing
1068 };
1069 
1070 struct smu_private
1071 {
1072 	struct list_head	list;
1073 	enum smu_file_mode	mode;
1074 	int			busy;
1075 	struct smu_cmd		cmd;
1076 	spinlock_t		lock;
1077 	wait_queue_head_t	wait;
1078 	u8			buffer[SMU_MAX_DATA];
1079 };
1080 
1081 
1082 static int smu_open(struct inode *inode, struct file *file)
1083 {
1084 	struct smu_private *pp;
1085 	unsigned long flags;
1086 
1087 	pp = kzalloc(sizeof(struct smu_private), GFP_KERNEL);
1088 	if (!pp)
1089 		return -ENOMEM;
1090 	spin_lock_init(&pp->lock);
1091 	pp->mode = smu_file_commands;
1092 	init_waitqueue_head(&pp->wait);
1093 
1094 	mutex_lock(&smu_mutex);
1095 	spin_lock_irqsave(&smu_clist_lock, flags);
1096 	list_add(&pp->list, &smu_clist);
1097 	spin_unlock_irqrestore(&smu_clist_lock, flags);
1098 	file->private_data = pp;
1099 	mutex_unlock(&smu_mutex);
1100 
1101 	return 0;
1102 }
1103 
1104 
1105 static void smu_user_cmd_done(struct smu_cmd *cmd, void *misc)
1106 {
1107 	struct smu_private *pp = misc;
1108 
1109 	wake_up_all(&pp->wait);
1110 }
1111 
1112 
1113 static ssize_t smu_write(struct file *file, const char __user *buf,
1114 			 size_t count, loff_t *ppos)
1115 {
1116 	struct smu_private *pp = file->private_data;
1117 	unsigned long flags;
1118 	struct smu_user_cmd_hdr hdr;
1119 	int rc = 0;
1120 
1121 	if (pp->busy)
1122 		return -EBUSY;
1123 	else if (copy_from_user(&hdr, buf, sizeof(hdr)))
1124 		return -EFAULT;
1125 	else if (hdr.cmdtype == SMU_CMDTYPE_WANTS_EVENTS) {
1126 		pp->mode = smu_file_events;
1127 		return 0;
1128 	} else if (hdr.cmdtype == SMU_CMDTYPE_GET_PARTITION) {
1129 		const struct smu_sdbp_header *part;
1130 		part = __smu_get_sdb_partition(hdr.cmd, NULL, 1);
1131 		if (part == NULL)
1132 			return -EINVAL;
1133 		else if (IS_ERR(part))
1134 			return PTR_ERR(part);
1135 		return 0;
1136 	} else if (hdr.cmdtype != SMU_CMDTYPE_SMU)
1137 		return -EINVAL;
1138 	else if (pp->mode != smu_file_commands)
1139 		return -EBADFD;
1140 	else if (hdr.data_len > SMU_MAX_DATA)
1141 		return -EINVAL;
1142 
1143 	spin_lock_irqsave(&pp->lock, flags);
1144 	if (pp->busy) {
1145 		spin_unlock_irqrestore(&pp->lock, flags);
1146 		return -EBUSY;
1147 	}
1148 	pp->busy = 1;
1149 	pp->cmd.status = 1;
1150 	spin_unlock_irqrestore(&pp->lock, flags);
1151 
1152 	if (copy_from_user(pp->buffer, buf + sizeof(hdr), hdr.data_len)) {
1153 		pp->busy = 0;
1154 		return -EFAULT;
1155 	}
1156 
1157 	pp->cmd.cmd = hdr.cmd;
1158 	pp->cmd.data_len = hdr.data_len;
1159 	pp->cmd.reply_len = SMU_MAX_DATA;
1160 	pp->cmd.data_buf = pp->buffer;
1161 	pp->cmd.reply_buf = pp->buffer;
1162 	pp->cmd.done = smu_user_cmd_done;
1163 	pp->cmd.misc = pp;
1164 	rc = smu_queue_cmd(&pp->cmd);
1165 	if (rc < 0)
1166 		return rc;
1167 	return count;
1168 }
1169 
1170 
1171 static ssize_t smu_read_command(struct file *file, struct smu_private *pp,
1172 				char __user *buf, size_t count)
1173 {
1174 	DECLARE_WAITQUEUE(wait, current);
1175 	struct smu_user_reply_hdr hdr;
1176 	unsigned long flags;
1177 	int size, rc = 0;
1178 
1179 	if (!pp->busy)
1180 		return 0;
1181 	if (count < sizeof(struct smu_user_reply_hdr))
1182 		return -EOVERFLOW;
1183 	spin_lock_irqsave(&pp->lock, flags);
1184 	if (pp->cmd.status == 1) {
1185 		if (file->f_flags & O_NONBLOCK) {
1186 			spin_unlock_irqrestore(&pp->lock, flags);
1187 			return -EAGAIN;
1188 		}
1189 		add_wait_queue(&pp->wait, &wait);
1190 		for (;;) {
1191 			set_current_state(TASK_INTERRUPTIBLE);
1192 			rc = 0;
1193 			if (pp->cmd.status != 1)
1194 				break;
1195 			rc = -ERESTARTSYS;
1196 			if (signal_pending(current))
1197 				break;
1198 			spin_unlock_irqrestore(&pp->lock, flags);
1199 			schedule();
1200 			spin_lock_irqsave(&pp->lock, flags);
1201 		}
1202 		set_current_state(TASK_RUNNING);
1203 		remove_wait_queue(&pp->wait, &wait);
1204 	}
1205 	spin_unlock_irqrestore(&pp->lock, flags);
1206 	if (rc)
1207 		return rc;
1208 	if (pp->cmd.status != 0)
1209 		pp->cmd.reply_len = 0;
1210 	size = sizeof(hdr) + pp->cmd.reply_len;
1211 	if (count < size)
1212 		size = count;
1213 	rc = size;
1214 	hdr.status = pp->cmd.status;
1215 	hdr.reply_len = pp->cmd.reply_len;
1216 	if (copy_to_user(buf, &hdr, sizeof(hdr)))
1217 		return -EFAULT;
1218 	size -= sizeof(hdr);
1219 	if (size && copy_to_user(buf + sizeof(hdr), pp->buffer, size))
1220 		return -EFAULT;
1221 	pp->busy = 0;
1222 
1223 	return rc;
1224 }
1225 
1226 
1227 static ssize_t smu_read_events(struct file *file, struct smu_private *pp,
1228 			       char __user *buf, size_t count)
1229 {
1230 	/* Not implemented */
1231 	msleep_interruptible(1000);
1232 	return 0;
1233 }
1234 
1235 
1236 static ssize_t smu_read(struct file *file, char __user *buf,
1237 			size_t count, loff_t *ppos)
1238 {
1239 	struct smu_private *pp = file->private_data;
1240 
1241 	if (pp->mode == smu_file_commands)
1242 		return smu_read_command(file, pp, buf, count);
1243 	if (pp->mode == smu_file_events)
1244 		return smu_read_events(file, pp, buf, count);
1245 
1246 	return -EBADFD;
1247 }
1248 
1249 static __poll_t smu_fpoll(struct file *file, poll_table *wait)
1250 {
1251 	struct smu_private *pp = file->private_data;
1252 	__poll_t mask = 0;
1253 	unsigned long flags;
1254 
1255 	if (!pp)
1256 		return 0;
1257 
1258 	if (pp->mode == smu_file_commands) {
1259 		poll_wait(file, &pp->wait, wait);
1260 
1261 		spin_lock_irqsave(&pp->lock, flags);
1262 		if (pp->busy && pp->cmd.status != 1)
1263 			mask |= EPOLLIN;
1264 		spin_unlock_irqrestore(&pp->lock, flags);
1265 	}
1266 	if (pp->mode == smu_file_events) {
1267 		/* Not yet implemented */
1268 	}
1269 	return mask;
1270 }
1271 
1272 static int smu_release(struct inode *inode, struct file *file)
1273 {
1274 	struct smu_private *pp = file->private_data;
1275 	unsigned long flags;
1276 	unsigned int busy;
1277 
1278 	if (!pp)
1279 		return 0;
1280 
1281 	file->private_data = NULL;
1282 
1283 	/* Mark file as closing to avoid races with new request */
1284 	spin_lock_irqsave(&pp->lock, flags);
1285 	pp->mode = smu_file_closing;
1286 	busy = pp->busy;
1287 
1288 	/* Wait for any pending request to complete */
1289 	if (busy && pp->cmd.status == 1) {
1290 		DECLARE_WAITQUEUE(wait, current);
1291 
1292 		add_wait_queue(&pp->wait, &wait);
1293 		for (;;) {
1294 			set_current_state(TASK_UNINTERRUPTIBLE);
1295 			if (pp->cmd.status != 1)
1296 				break;
1297 			spin_unlock_irqrestore(&pp->lock, flags);
1298 			schedule();
1299 			spin_lock_irqsave(&pp->lock, flags);
1300 		}
1301 		set_current_state(TASK_RUNNING);
1302 		remove_wait_queue(&pp->wait, &wait);
1303 	}
1304 	spin_unlock_irqrestore(&pp->lock, flags);
1305 
1306 	spin_lock_irqsave(&smu_clist_lock, flags);
1307 	list_del(&pp->list);
1308 	spin_unlock_irqrestore(&smu_clist_lock, flags);
1309 	kfree(pp);
1310 
1311 	return 0;
1312 }
1313 
1314 
1315 static const struct file_operations smu_device_fops = {
1316 	.llseek		= no_llseek,
1317 	.read		= smu_read,
1318 	.write		= smu_write,
1319 	.poll		= smu_fpoll,
1320 	.open		= smu_open,
1321 	.release	= smu_release,
1322 };
1323 
1324 static struct miscdevice pmu_device = {
1325 	MISC_DYNAMIC_MINOR, "smu", &smu_device_fops
1326 };
1327 
1328 static int smu_device_init(void)
1329 {
1330 	if (!smu)
1331 		return -ENODEV;
1332 	if (misc_register(&pmu_device) < 0)
1333 		printk(KERN_ERR "via-pmu: cannot register misc device.\n");
1334 	return 0;
1335 }
1336 device_initcall(smu_device_init);
1337