xref: /linux/drivers/char/ipmi/ipmi_si_intf.c (revision 09dd798270ff582d7309f285d4aaf5dbebae01cb)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * ipmi_si.c
4  *
5  * The interface to the IPMI driver for the system interfaces (KCS, SMIC,
6  * BT).
7  *
8  * Author: MontaVista Software, Inc.
9  *         Corey Minyard <minyard@mvista.com>
10  *         source@mvista.com
11  *
12  * Copyright 2002 MontaVista Software Inc.
13  * Copyright 2006 IBM Corp., Christian Krafft <krafft@de.ibm.com>
14  */
15 
16 /*
17  * This file holds the "policy" for the interface to the SMI state
18  * machine.  It does the configuration, handles timers and interrupts,
19  * and drives the real SMI state machine.
20  */
21 
22 #define pr_fmt(fmt) "ipmi_si: " fmt
23 
24 #include <linux/module.h>
25 #include <linux/moduleparam.h>
26 #include <linux/sched.h>
27 #include <linux/seq_file.h>
28 #include <linux/timer.h>
29 #include <linux/errno.h>
30 #include <linux/spinlock.h>
31 #include <linux/slab.h>
32 #include <linux/delay.h>
33 #include <linux/list.h>
34 #include <linux/notifier.h>
35 #include <linux/mutex.h>
36 #include <linux/kthread.h>
37 #include <asm/irq.h>
38 #include <linux/interrupt.h>
39 #include <linux/rcupdate.h>
40 #include <linux/ipmi.h>
41 #include <linux/ipmi_smi.h>
42 #include "ipmi_si.h"
43 #include "ipmi_si_sm.h"
44 #include <linux/string.h>
45 #include <linux/ctype.h>
46 
47 /* Measure times between events in the driver. */
48 #undef DEBUG_TIMING
49 
50 /* Call every 10 ms. */
51 #define SI_TIMEOUT_TIME_USEC	10000
52 #define SI_USEC_PER_JIFFY	(1000000/HZ)
53 #define SI_TIMEOUT_JIFFIES	(SI_TIMEOUT_TIME_USEC/SI_USEC_PER_JIFFY)
54 #define SI_SHORT_TIMEOUT_USEC  250 /* .25ms when the SM request a
55 				      short timeout */
56 #define SI_TIMEOUT_HOSED	(HZ) /* 1 second when in hosed state. */
57 
58 enum si_intf_state {
59 	SI_NORMAL,
60 	SI_GETTING_FLAGS,
61 	SI_GETTING_EVENTS,
62 	SI_CLEARING_FLAGS,
63 	SI_GETTING_MESSAGES,
64 	SI_CHECKING_ENABLES,
65 	SI_SETTING_ENABLES,
66 	SI_HOSED
67 	/* FIXME - add watchdog stuff. */
68 };
69 
70 /* Some BT-specific defines we need here. */
71 #define IPMI_BT_INTMASK_REG		2
72 #define IPMI_BT_INTMASK_CLEAR_IRQ_BIT	2
73 #define IPMI_BT_INTMASK_ENABLE_IRQ_BIT	1
74 
75 /* 'invalid' to allow a firmware-specified interface to be disabled */
76 const char *const si_to_str[] = { "invalid", "kcs", "smic", "bt", NULL };
77 
78 const struct ipmi_match_info ipmi_kcs_si_info = { .type = SI_KCS };
79 const struct ipmi_match_info ipmi_smic_si_info = { .type = SI_SMIC };
80 const struct ipmi_match_info ipmi_bt_si_info = { .type = SI_BT };
81 
82 static bool initialized;
83 
84 /*
85  * Indexes into stats[] in smi_info below.
86  */
87 enum si_stat_indexes {
88 	/*
89 	 * Number of times the driver requested a timer while an operation
90 	 * was in progress.
91 	 */
92 	SI_STAT_short_timeouts = 0,
93 
94 	/*
95 	 * Number of times the driver requested a timer while nothing was in
96 	 * progress.
97 	 */
98 	SI_STAT_long_timeouts,
99 
100 	/* Number of times the interface was idle while being polled. */
101 	SI_STAT_idles,
102 
103 	/* Number of interrupts the driver handled. */
104 	SI_STAT_interrupts,
105 
106 	/* Number of time the driver got an ATTN from the hardware. */
107 	SI_STAT_attentions,
108 
109 	/* Number of times the driver requested flags from the hardware. */
110 	SI_STAT_flag_fetches,
111 
112 	/* Number of times the hardware didn't follow the state machine. */
113 	SI_STAT_hosed_count,
114 
115 	/* Number of completed messages. */
116 	SI_STAT_complete_transactions,
117 
118 	/* Number of IPMI events received from the hardware. */
119 	SI_STAT_events,
120 
121 	/* Number of watchdog pretimeouts. */
122 	SI_STAT_watchdog_pretimeouts,
123 
124 	/* Number of asynchronous messages received. */
125 	SI_STAT_incoming_messages,
126 
127 
128 	/* This *must* remain last, add new values above this. */
129 	SI_NUM_STATS
130 };
131 
132 struct smi_info {
133 	int                    si_num;
134 	struct ipmi_smi        *intf;
135 	struct si_sm_data      *si_sm;
136 	const struct si_sm_handlers *handlers;
137 	spinlock_t             si_lock;
138 	struct ipmi_smi_msg    *waiting_msg;
139 	struct ipmi_smi_msg    *curr_msg;
140 	enum si_intf_state     si_state;
141 
142 	/*
143 	 * Used to handle the various types of I/O that can occur with
144 	 * IPMI
145 	 */
146 	struct si_sm_io io;
147 
148 	/*
149 	 * Per-OEM handler, called from handle_flags().  Returns 1
150 	 * when handle_flags() needs to be re-run or 0 indicating it
151 	 * set si_state itself.
152 	 */
153 	int (*oem_data_avail_handler)(struct smi_info *smi_info);
154 
155 	/*
156 	 * Flags from the last GET_MSG_FLAGS command, used when an ATTN
157 	 * is set to hold the flags until we are done handling everything
158 	 * from the flags.
159 	 */
160 #define RECEIVE_MSG_AVAIL	0x01
161 #define EVENT_MSG_BUFFER_FULL	0x02
162 #define WDT_PRE_TIMEOUT_INT	0x08
163 #define OEM0_DATA_AVAIL     0x20
164 #define OEM1_DATA_AVAIL     0x40
165 #define OEM2_DATA_AVAIL     0x80
166 #define OEM_DATA_AVAIL      (OEM0_DATA_AVAIL | \
167 			     OEM1_DATA_AVAIL | \
168 			     OEM2_DATA_AVAIL)
169 	unsigned char       msg_flags;
170 
171 	/* When requesting events and messages, don't do it forever. */
172 	unsigned int        num_requests_in_a_row;
173 	bool		    last_was_flag_fetch;
174 
175 	/* Does the BMC have an event buffer? */
176 	bool		    has_event_buffer;
177 
178 	/*
179 	 * If set to true, this will request events the next time the
180 	 * state machine is idle.
181 	 */
182 	atomic_t            req_events;
183 
184 	/*
185 	 * If true, run the state machine to completion on every send
186 	 * call.  Generally used after a panic to make sure stuff goes
187 	 * out.
188 	 */
189 	bool                run_to_completion;
190 
191 	/* The timer for this si. */
192 	struct timer_list   si_timer;
193 
194 	/* This flag is set, if the timer can be set */
195 	bool		    timer_can_start;
196 
197 	/* This flag is set, if the timer is running (timer_pending() isn't enough) */
198 	bool		    timer_running;
199 
200 	/* The time (in jiffies) the last timeout occurred at. */
201 	unsigned long       last_timeout_jiffies;
202 
203 	/* Are we waiting for the events, pretimeouts, received msgs? */
204 	atomic_t            need_watch;
205 
206 	/*
207 	 * The driver will disable interrupts when it gets into a
208 	 * situation where it cannot handle messages due to lack of
209 	 * memory.  Once that situation clears up, it will re-enable
210 	 * interrupts.
211 	 */
212 	bool interrupt_disabled;
213 
214 	/*
215 	 * Does the BMC support events?
216 	 */
217 	bool supports_event_msg_buff;
218 
219 	/*
220 	 * Can we disable interrupts the global enables receive irq
221 	 * bit?  There are currently two forms of brokenness, some
222 	 * systems cannot disable the bit (which is technically within
223 	 * the spec but a bad idea) and some systems have the bit
224 	 * forced to zero even though interrupts work (which is
225 	 * clearly outside the spec).  The next bool tells which form
226 	 * of brokenness is present.
227 	 */
228 	bool cannot_disable_irq;
229 
230 	/*
231 	 * Some systems are broken and cannot set the irq enable
232 	 * bit, even if they support interrupts.
233 	 */
234 	bool irq_enable_broken;
235 
236 	/* Is the driver in maintenance mode? */
237 	bool in_maintenance_mode;
238 
239 	/*
240 	 * Did we get an attention that we did not handle?
241 	 */
242 	bool got_attn;
243 
244 	/* From the get device id response... */
245 	struct ipmi_device_id device_id;
246 
247 	/* Have we added the device group to the device? */
248 	bool dev_group_added;
249 
250 	/* Counters and things for the proc filesystem. */
251 	atomic_t stats[SI_NUM_STATS];
252 
253 	struct task_struct *thread;
254 
255 	struct list_head link;
256 };
257 
258 #define smi_inc_stat(smi, stat) \
259 	atomic_inc(&(smi)->stats[SI_STAT_ ## stat])
260 #define smi_get_stat(smi, stat) \
261 	((unsigned int) atomic_read(&(smi)->stats[SI_STAT_ ## stat]))
262 
263 #define IPMI_MAX_INTFS 4
264 static int force_kipmid[IPMI_MAX_INTFS];
265 static int num_force_kipmid;
266 
267 static unsigned int kipmid_max_busy_us[IPMI_MAX_INTFS];
268 static int num_max_busy_us;
269 
270 static bool unload_when_empty = true;
271 
272 static int try_smi_init(struct smi_info *smi);
273 static void cleanup_one_si(struct smi_info *smi_info);
274 static void cleanup_ipmi_si(void);
275 
276 #ifdef DEBUG_TIMING
277 void debug_timestamp(struct smi_info *smi_info, char *msg)
278 {
279 	struct timespec64 t;
280 
281 	ktime_get_ts64(&t);
282 	dev_dbg(smi_info->io.dev, "**%s: %ptSp\n", msg, &t);
283 }
284 #else
285 #define debug_timestamp(smi_info, x)
286 #endif
287 
288 static ATOMIC_NOTIFIER_HEAD(xaction_notifier_list);
289 static int register_xaction_notifier(struct notifier_block *nb)
290 {
291 	return atomic_notifier_chain_register(&xaction_notifier_list, nb);
292 }
293 
294 static void deliver_recv_msg(struct smi_info *smi_info,
295 			     struct ipmi_smi_msg *msg)
296 {
297 	/* Deliver the message to the upper layer. */
298 	ipmi_smi_msg_received(smi_info->intf, msg);
299 }
300 
301 static void return_hosed_msg(struct smi_info *smi_info, int cCode)
302 {
303 	struct ipmi_smi_msg *msg = smi_info->curr_msg;
304 
305 	if (cCode < 0 || cCode > IPMI_ERR_UNSPECIFIED)
306 		cCode = IPMI_ERR_UNSPECIFIED;
307 	/* else use it as is */
308 
309 	/* Make it a response */
310 	msg->rsp[0] = msg->data[0] | 4;
311 	msg->rsp[1] = msg->data[1];
312 	msg->rsp[2] = cCode;
313 	msg->rsp_size = 3;
314 
315 	smi_info->curr_msg = NULL;
316 	deliver_recv_msg(smi_info, msg);
317 }
318 
319 static enum si_sm_result start_next_msg(struct smi_info *smi_info)
320 {
321 	int rv;
322 
323 	if (!smi_info->waiting_msg) {
324 		smi_info->curr_msg = NULL;
325 		rv = SI_SM_IDLE;
326 	} else {
327 		int err;
328 
329 		smi_info->curr_msg = smi_info->waiting_msg;
330 		smi_info->waiting_msg = NULL;
331 		debug_timestamp(smi_info, "Start2");
332 		err = atomic_notifier_call_chain(&xaction_notifier_list,
333 				0, smi_info);
334 		if (err & NOTIFY_STOP_MASK) {
335 			rv = SI_SM_CALL_WITHOUT_DELAY;
336 			goto out;
337 		}
338 		err = smi_info->handlers->start_transaction(
339 			smi_info->si_sm,
340 			smi_info->curr_msg->data,
341 			smi_info->curr_msg->data_size);
342 		if (err)
343 			return_hosed_msg(smi_info, err);
344 
345 		rv = SI_SM_CALL_WITHOUT_DELAY;
346 	}
347 out:
348 	return rv;
349 }
350 
351 static void smi_mod_timer(struct smi_info *smi_info, unsigned long new_val)
352 {
353 	if (!smi_info->timer_can_start)
354 		return;
355 	smi_info->last_timeout_jiffies = jiffies;
356 	mod_timer(&smi_info->si_timer, new_val);
357 	smi_info->timer_running = true;
358 }
359 
360 /*
361  * Start a new message and (re)start the timer and thread.
362  */
363 static void start_new_msg(struct smi_info *smi_info, unsigned char *msg,
364 			  unsigned int size)
365 {
366 	smi_mod_timer(smi_info, jiffies + SI_TIMEOUT_JIFFIES);
367 
368 	if (smi_info->thread)
369 		wake_up_process(smi_info->thread);
370 
371 	smi_info->handlers->start_transaction(smi_info->si_sm, msg, size);
372 }
373 
374 static void start_check_enables(struct smi_info *smi_info)
375 {
376 	unsigned char msg[2];
377 
378 	msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
379 	msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
380 
381 	start_new_msg(smi_info, msg, 2);
382 	smi_info->si_state = SI_CHECKING_ENABLES;
383 }
384 
385 static void start_clear_flags(struct smi_info *smi_info)
386 {
387 	unsigned char msg[3];
388 
389 	/* Make sure the watchdog pre-timeout flag is not set at startup. */
390 	msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
391 	msg[1] = IPMI_CLEAR_MSG_FLAGS_CMD;
392 	msg[2] = WDT_PRE_TIMEOUT_INT;
393 
394 	start_new_msg(smi_info, msg, 3);
395 	smi_info->si_state = SI_CLEARING_FLAGS;
396 }
397 
398 static void start_get_flags(struct smi_info *smi_info)
399 {
400 	unsigned char msg[2];
401 
402 	msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
403 	msg[1] = IPMI_GET_MSG_FLAGS_CMD;
404 
405 	start_new_msg(smi_info, msg, 2);
406 	smi_info->si_state = SI_GETTING_FLAGS;
407 }
408 
409 static void start_getting_msg_queue(struct smi_info *smi_info)
410 {
411 	smi_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
412 	smi_info->curr_msg->data[1] = IPMI_GET_MSG_CMD;
413 	smi_info->curr_msg->data_size = 2;
414 
415 	start_new_msg(smi_info, smi_info->curr_msg->data,
416 		      smi_info->curr_msg->data_size);
417 	if (smi_info->si_state != SI_GETTING_MESSAGES) {
418 		smi_info->num_requests_in_a_row = 0;
419 		smi_info->si_state = SI_GETTING_MESSAGES;
420 	}
421 }
422 
423 static void start_getting_events(struct smi_info *smi_info)
424 {
425 	smi_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
426 	smi_info->curr_msg->data[1] = IPMI_READ_EVENT_MSG_BUFFER_CMD;
427 	smi_info->curr_msg->data_size = 2;
428 
429 	start_new_msg(smi_info, smi_info->curr_msg->data,
430 		      smi_info->curr_msg->data_size);
431 	if (smi_info->si_state != SI_GETTING_EVENTS) {
432 		smi_info->num_requests_in_a_row = 0;
433 		smi_info->si_state = SI_GETTING_EVENTS;
434 	}
435 }
436 
437 /*
438  * When we have a situtaion where we run out of memory and cannot
439  * allocate messages, we just leave them in the BMC and run the system
440  * polled until we can allocate some memory.  Once we have some
441  * memory, we will re-enable the interrupt.
442  *
443  * Note that we cannot just use disable_irq(), since the interrupt may
444  * be shared.
445  */
446 static inline bool disable_si_irq(struct smi_info *smi_info)
447 {
448 	if ((smi_info->io.irq) && (!smi_info->interrupt_disabled)) {
449 		smi_info->interrupt_disabled = true;
450 		start_check_enables(smi_info);
451 		return true;
452 	}
453 	return false;
454 }
455 
456 static inline bool enable_si_irq(struct smi_info *smi_info)
457 {
458 	if ((smi_info->io.irq) && (smi_info->interrupt_disabled)) {
459 		smi_info->interrupt_disabled = false;
460 		start_check_enables(smi_info);
461 		return true;
462 	}
463 	return false;
464 }
465 
466 /*
467  * Allocate a message.  If unable to allocate, start the interrupt
468  * disable process and return NULL.  If able to allocate but
469  * interrupts are disabled, free the message and return NULL after
470  * starting the interrupt enable process.
471  */
472 static struct ipmi_smi_msg *alloc_msg_handle_irq(struct smi_info *smi_info)
473 {
474 	struct ipmi_smi_msg *msg;
475 
476 	msg = ipmi_alloc_smi_msg();
477 	if (!msg) {
478 		if (!disable_si_irq(smi_info))
479 			smi_info->si_state = SI_NORMAL;
480 	} else if (enable_si_irq(smi_info)) {
481 		ipmi_free_smi_msg(msg);
482 		msg = NULL;
483 	}
484 	return msg;
485 }
486 
487 static void handle_flags(struct smi_info *smi_info)
488 {
489 retry:
490 	if (smi_info->msg_flags & WDT_PRE_TIMEOUT_INT) {
491 		/* Watchdog pre-timeout */
492 		smi_inc_stat(smi_info, watchdog_pretimeouts);
493 
494 		start_clear_flags(smi_info);
495 		smi_info->msg_flags &= ~WDT_PRE_TIMEOUT_INT;
496 		ipmi_smi_watchdog_pretimeout(smi_info->intf);
497 	} else if (smi_info->msg_flags & RECEIVE_MSG_AVAIL) {
498 		/* Messages available. */
499 		smi_info->curr_msg = alloc_msg_handle_irq(smi_info);
500 		if (!smi_info->curr_msg) {
501 			smi_info->si_state = SI_NORMAL;
502 			return;
503 		}
504 
505 		start_getting_msg_queue(smi_info);
506 	} else if (smi_info->msg_flags & EVENT_MSG_BUFFER_FULL) {
507 		/* Events available. */
508 		smi_info->curr_msg = alloc_msg_handle_irq(smi_info);
509 		if (!smi_info->curr_msg) {
510 			smi_info->si_state = SI_NORMAL;
511 			return;
512 		}
513 
514 		start_getting_events(smi_info);
515 	} else if (smi_info->msg_flags & OEM_DATA_AVAIL &&
516 		   smi_info->oem_data_avail_handler) {
517 		if (smi_info->oem_data_avail_handler(smi_info))
518 			goto retry;
519 	} else
520 		smi_info->si_state = SI_NORMAL;
521 }
522 
523 /*
524  * Global enables we care about.
525  */
526 #define GLOBAL_ENABLES_MASK (IPMI_BMC_EVT_MSG_BUFF | IPMI_BMC_RCV_MSG_INTR | \
527 			     IPMI_BMC_EVT_MSG_INTR)
528 
529 static u8 current_global_enables(struct smi_info *smi_info, u8 base,
530 				 bool *irq_on)
531 {
532 	u8 enables = 0;
533 
534 	if (smi_info->supports_event_msg_buff)
535 		enables |= IPMI_BMC_EVT_MSG_BUFF;
536 
537 	if (((smi_info->io.irq && !smi_info->interrupt_disabled) ||
538 	     smi_info->cannot_disable_irq) &&
539 	    !smi_info->irq_enable_broken)
540 		enables |= IPMI_BMC_RCV_MSG_INTR;
541 
542 	if (smi_info->supports_event_msg_buff &&
543 	    smi_info->io.irq && !smi_info->interrupt_disabled &&
544 	    !smi_info->irq_enable_broken)
545 		enables |= IPMI_BMC_EVT_MSG_INTR;
546 
547 	*irq_on = enables & (IPMI_BMC_EVT_MSG_INTR | IPMI_BMC_RCV_MSG_INTR);
548 
549 	return enables;
550 }
551 
552 static void check_bt_irq(struct smi_info *smi_info, bool irq_on)
553 {
554 	u8 irqstate = smi_info->io.inputb(&smi_info->io, IPMI_BT_INTMASK_REG);
555 
556 	irqstate &= IPMI_BT_INTMASK_ENABLE_IRQ_BIT;
557 
558 	if ((bool)irqstate == irq_on)
559 		return;
560 
561 	if (irq_on)
562 		smi_info->io.outputb(&smi_info->io, IPMI_BT_INTMASK_REG,
563 				     IPMI_BT_INTMASK_ENABLE_IRQ_BIT);
564 	else
565 		smi_info->io.outputb(&smi_info->io, IPMI_BT_INTMASK_REG, 0);
566 }
567 
568 static void handle_transaction_done(struct smi_info *smi_info)
569 {
570 	struct ipmi_smi_msg *msg;
571 
572 	debug_timestamp(smi_info, "Done");
573 	switch (smi_info->si_state) {
574 	case SI_NORMAL:
575 		if (!smi_info->curr_msg)
576 			break;
577 
578 		smi_info->curr_msg->rsp_size
579 			= smi_info->handlers->get_result(
580 				smi_info->si_sm,
581 				smi_info->curr_msg->rsp,
582 				IPMI_MAX_MSG_LENGTH);
583 
584 		/*
585 		 * Do this here becase deliver_recv_msg() releases the
586 		 * lock, and a new message can be put in during the
587 		 * time the lock is released.
588 		 */
589 		msg = smi_info->curr_msg;
590 		smi_info->curr_msg = NULL;
591 		deliver_recv_msg(smi_info, msg);
592 		break;
593 
594 	case SI_GETTING_FLAGS:
595 	{
596 		unsigned char msg[4];
597 		unsigned int  len;
598 
599 		/* We got the flags from the SMI, now handle them. */
600 		len = smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
601 		if (msg[2] != 0) {
602 			/* Error fetching flags, just give up for now. */
603 			smi_info->si_state = SI_NORMAL;
604 		} else if (len < 4) {
605 			/*
606 			 * Hmm, no flags.  That's technically illegal, but
607 			 * don't use uninitialized data.
608 			 */
609 			smi_info->si_state = SI_NORMAL;
610 		} else {
611 			smi_info->msg_flags = msg[3];
612 			smi_info->last_was_flag_fetch = true;
613 			handle_flags(smi_info);
614 		}
615 		break;
616 	}
617 
618 	case SI_CLEARING_FLAGS:
619 	{
620 		unsigned char msg[3];
621 
622 		/* We cleared the flags. */
623 		smi_info->handlers->get_result(smi_info->si_sm, msg, 3);
624 		if (msg[2] != 0) {
625 			/* Error clearing flags */
626 			dev_warn_ratelimited(smi_info->io.dev,
627 				 "Error clearing flags: %2.2x\n", msg[2]);
628 		}
629 		smi_info->si_state = SI_NORMAL;
630 		break;
631 	}
632 
633 	case SI_GETTING_EVENTS:
634 	{
635 		smi_info->curr_msg->rsp_size
636 			= smi_info->handlers->get_result(
637 				smi_info->si_sm,
638 				smi_info->curr_msg->rsp,
639 				IPMI_MAX_MSG_LENGTH);
640 
641 		/*
642 		 * Do this here becase deliver_recv_msg() releases the
643 		 * lock, and a new message can be put in during the
644 		 * time the lock is released.
645 		 */
646 		msg = smi_info->curr_msg;
647 		smi_info->curr_msg = NULL;
648 		/*
649 		 * It appears some BMCs, with no event data, return no
650 		 * data in the message and not a 0x80 error as the
651 		 * spec says they should.  Shut down processing if
652 		 * the data is not the right length.
653 		 */
654 		if (msg->rsp[2] != 0 || msg->rsp_size != 19) {
655 			/* Error getting event, probably done. */
656 			msg->done(msg);
657 
658 			/* Take off the event flag. */
659 			smi_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
660 			handle_flags(smi_info);
661 		} else {
662 			smi_inc_stat(smi_info, events);
663 
664 			smi_info->num_requests_in_a_row++;
665 			if (smi_info->num_requests_in_a_row > 10)
666 				/* Stop if we do this too many times. */
667 				smi_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
668 
669 			/*
670 			 * Do this before we deliver the message
671 			 * because delivering the message releases the
672 			 * lock and something else can mess with the
673 			 * state.
674 			 */
675 			handle_flags(smi_info);
676 
677 			deliver_recv_msg(smi_info, msg);
678 		}
679 		break;
680 	}
681 
682 	case SI_GETTING_MESSAGES:
683 	{
684 		smi_info->curr_msg->rsp_size
685 			= smi_info->handlers->get_result(
686 				smi_info->si_sm,
687 				smi_info->curr_msg->rsp,
688 				IPMI_MAX_MSG_LENGTH);
689 
690 		/*
691 		 * Do this here becase deliver_recv_msg() releases the
692 		 * lock, and a new message can be put in during the
693 		 * time the lock is released.
694 		 */
695 		msg = smi_info->curr_msg;
696 		smi_info->curr_msg = NULL;
697 		if (msg->rsp[2] != 0) {
698 			/* Error getting event, probably done. */
699 			msg->done(msg);
700 
701 			/* Take off the msg flag. */
702 			smi_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
703 			handle_flags(smi_info);
704 		} else {
705 			smi_inc_stat(smi_info, incoming_messages);
706 
707 			smi_info->num_requests_in_a_row++;
708 			if (smi_info->num_requests_in_a_row > 10)
709 				/* Stop if we do this too many times. */
710 				smi_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
711 
712 			/*
713 			 * Do this before we deliver the message
714 			 * because delivering the message releases the
715 			 * lock and something else can mess with the
716 			 * state.
717 			 */
718 			handle_flags(smi_info);
719 
720 			deliver_recv_msg(smi_info, msg);
721 		}
722 		break;
723 	}
724 
725 	case SI_CHECKING_ENABLES:
726 	{
727 		unsigned char msg[4];
728 		u8 enables;
729 		bool irq_on;
730 
731 		/* We got the flags from the SMI, now handle them. */
732 		smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
733 		if (msg[2] != 0) {
734 			dev_warn_ratelimited(smi_info->io.dev,
735 				"Couldn't get irq info: %x,\n"
736 				"Maybe ok, but ipmi might run very slowly.\n",
737 				msg[2]);
738 			smi_info->si_state = SI_NORMAL;
739 			break;
740 		}
741 		enables = current_global_enables(smi_info, 0, &irq_on);
742 		if (smi_info->io.si_info->type == SI_BT)
743 			/* BT has its own interrupt enable bit. */
744 			check_bt_irq(smi_info, irq_on);
745 		if (enables != (msg[3] & GLOBAL_ENABLES_MASK)) {
746 			/* Enables are not correct, fix them. */
747 			msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
748 			msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
749 			msg[2] = enables | (msg[3] & ~GLOBAL_ENABLES_MASK);
750 			smi_info->handlers->start_transaction(
751 				smi_info->si_sm, msg, 3);
752 			smi_info->si_state = SI_SETTING_ENABLES;
753 		} else if (smi_info->supports_event_msg_buff) {
754 			smi_info->curr_msg = ipmi_alloc_smi_msg();
755 			if (!smi_info->curr_msg) {
756 				smi_info->si_state = SI_NORMAL;
757 				break;
758 			}
759 			start_getting_events(smi_info);
760 		} else {
761 			smi_info->si_state = SI_NORMAL;
762 		}
763 		break;
764 	}
765 
766 	case SI_SETTING_ENABLES:
767 	{
768 		unsigned char msg[4];
769 
770 		smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
771 		if (msg[2] != 0)
772 			dev_warn_ratelimited(smi_info->io.dev,
773 				 "Could not set the global enables: 0x%x.\n",
774 				 msg[2]);
775 
776 		if (smi_info->supports_event_msg_buff) {
777 			smi_info->curr_msg = ipmi_alloc_smi_msg();
778 			if (!smi_info->curr_msg) {
779 				smi_info->si_state = SI_NORMAL;
780 				break;
781 			}
782 			start_getting_events(smi_info);
783 		} else {
784 			smi_info->si_state = SI_NORMAL;
785 		}
786 		break;
787 	}
788 	case SI_HOSED: /* Shouldn't happen. */
789 		break;
790 	}
791 }
792 
793 /*
794  * Called on timeouts and events.  Timeouts should pass the elapsed
795  * time, interrupts should pass in zero.  Must be called with
796  * si_lock held and interrupts disabled.
797  */
798 static enum si_sm_result smi_event_handler(struct smi_info *smi_info,
799 					   int time)
800 {
801 	enum si_sm_result si_sm_result;
802 
803 restart:
804 	if (smi_info->si_state == SI_HOSED)
805 		/* Just in case, hosed state is only left from the timeout. */
806 		return SI_SM_HOSED;
807 
808 	/*
809 	 * There used to be a loop here that waited a little while
810 	 * (around 25us) before giving up.  That turned out to be
811 	 * pointless, the minimum delays I was seeing were in the 300us
812 	 * range, which is far too long to wait in an interrupt.  So
813 	 * we just run until the state machine tells us something
814 	 * happened or it needs a delay.
815 	 */
816 	si_sm_result = smi_info->handlers->event(smi_info->si_sm, time);
817 	time = 0;
818 	while (si_sm_result == SI_SM_CALL_WITHOUT_DELAY)
819 		si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
820 
821 	if (si_sm_result == SI_SM_TRANSACTION_COMPLETE) {
822 		smi_inc_stat(smi_info, complete_transactions);
823 
824 		handle_transaction_done(smi_info);
825 		goto restart;
826 	} else if (si_sm_result == SI_SM_HOSED) {
827 		smi_inc_stat(smi_info, hosed_count);
828 
829 		/*
830 		 * Do the before return_hosed_msg, because that
831 		 * releases the lock.  We just disable operations for
832 		 * a while and retry in hosed state.
833 		 */
834 		smi_info->si_state = SI_HOSED;
835 		if (smi_info->curr_msg != NULL) {
836 			/*
837 			 * If we were handling a user message, format
838 			 * a response to send to the upper layer to
839 			 * tell it about the error.
840 			 */
841 			return_hosed_msg(smi_info, IPMI_BUS_ERR);
842 		}
843 		if (smi_info->waiting_msg != NULL) {
844 			/* Also handle if there was a message waiting. */
845 			smi_info->curr_msg = smi_info->waiting_msg;
846 			smi_info->waiting_msg = NULL;
847 			return_hosed_msg(smi_info, IPMI_BUS_ERR);
848 		}
849 		smi_mod_timer(smi_info, jiffies + SI_TIMEOUT_HOSED);
850 		goto out;
851 	}
852 
853 	/*
854 	 * If we are currently idle, or if the last thing that was
855 	 * done was a flag fetch and there is a message pending, try
856 	 * to start the next message.
857 	 *
858 	 * We do the waiting message check to avoid a stuck flag
859 	 * completely wedging the driver.  Let a message through
860 	 * in between flag operations if that happens.
861 	 */
862 	if (si_sm_result == SI_SM_IDLE ||
863 	    (si_sm_result == SI_SM_ATTN && smi_info->waiting_msg &&
864 	     smi_info->last_was_flag_fetch)) {
865 		smi_info->last_was_flag_fetch = false;
866 		smi_inc_stat(smi_info, idles);
867 
868 		si_sm_result = start_next_msg(smi_info);
869 		if (si_sm_result != SI_SM_IDLE)
870 			goto restart;
871 	}
872 
873 	/*
874 	 * We prefer handling attn over new messages.  But don't do
875 	 * this if there is not yet an upper layer to handle anything.
876 	 */
877 	if (si_sm_result == SI_SM_ATTN || smi_info->got_attn) {
878 		if (smi_info->si_state != SI_NORMAL) {
879 			/*
880 			 * We got an ATTN, but we are doing something else.
881 			 * Handle the ATTN later.
882 			 */
883 			smi_info->got_attn = true;
884 		} else {
885 			smi_info->got_attn = false;
886 			smi_inc_stat(smi_info, attentions);
887 
888 			/*
889 			 * Got a attn, send down a get message flags to see
890 			 * what's causing it.  It would be better to handle
891 			 * this in the upper layer, but due to the way
892 			 * interrupts work with the SMI, that's not really
893 			 * possible.
894 			 */
895 			start_get_flags(smi_info);
896 			goto restart;
897 		}
898 	}
899 
900 	if ((si_sm_result == SI_SM_IDLE)
901 	    && (atomic_read(&smi_info->req_events))) {
902 		/*
903 		 * We are idle and the upper layer requested that I fetch
904 		 * events, so do so.
905 		 */
906 		atomic_set(&smi_info->req_events, 0);
907 
908 		/*
909 		 * Take this opportunity to check the interrupt and
910 		 * message enable state for the BMC.  The BMC can be
911 		 * asynchronously reset, and may thus get interrupts
912 		 * disable and messages disabled.
913 		 */
914 		if (smi_info->supports_event_msg_buff || smi_info->io.irq) {
915 			start_check_enables(smi_info);
916 		} else {
917 			smi_info->curr_msg = alloc_msg_handle_irq(smi_info);
918 			if (!smi_info->curr_msg)
919 				goto out;
920 
921 			start_getting_events(smi_info);
922 		}
923 		goto restart;
924 	}
925 
926 	if (si_sm_result == SI_SM_IDLE && smi_info->timer_running) {
927 		/* Ok it if fails, the timer will just go off. */
928 		if (timer_delete(&smi_info->si_timer))
929 			smi_info->timer_running = false;
930 	}
931 
932 out:
933 	return si_sm_result;
934 }
935 
936 static void check_start_timer_thread(struct smi_info *smi_info)
937 {
938 	if (smi_info->si_state == SI_NORMAL && smi_info->curr_msg == NULL) {
939 		smi_mod_timer(smi_info, jiffies + SI_TIMEOUT_JIFFIES);
940 
941 		if (smi_info->thread)
942 			wake_up_process(smi_info->thread);
943 
944 		start_next_msg(smi_info);
945 		smi_event_handler(smi_info, 0);
946 	}
947 }
948 
949 static void flush_messages(void *send_info)
950 {
951 	struct smi_info *smi_info = send_info;
952 	enum si_sm_result result;
953 
954 	/*
955 	 * Currently, this function is called only in run-to-completion
956 	 * mode.  This means we are single-threaded, no need for locks.
957 	 */
958 	result = smi_event_handler(smi_info, 0);
959 	while (result != SI_SM_IDLE && result != SI_SM_HOSED) {
960 		udelay(SI_SHORT_TIMEOUT_USEC);
961 		result = smi_event_handler(smi_info, SI_SHORT_TIMEOUT_USEC);
962 	}
963 }
964 
965 static int sender(void *send_info, struct ipmi_smi_msg *msg)
966 {
967 	struct smi_info   *smi_info = send_info;
968 	unsigned long     flags;
969 	int rv = IPMI_CC_NO_ERROR;
970 
971 	debug_timestamp(smi_info, "Enqueue");
972 
973 	/*
974 	 * Check here for run to completion mode.  A check under lock is
975 	 * later.
976 	 */
977 	if (smi_info->si_state == SI_HOSED)
978 		return IPMI_BUS_ERR;
979 
980 	if (smi_info->run_to_completion) {
981 		/*
982 		 * If we are running to completion, start it.  Upper
983 		 * layer will call flush_messages to clear it out.
984 		 */
985 		smi_info->waiting_msg = msg;
986 		return IPMI_CC_NO_ERROR;
987 	}
988 
989 	spin_lock_irqsave(&smi_info->si_lock, flags);
990 	if (smi_info->si_state == SI_HOSED) {
991 		rv = IPMI_BUS_ERR;
992 	} else {
993 		BUG_ON(smi_info->waiting_msg);
994 		smi_info->waiting_msg = msg;
995 		check_start_timer_thread(smi_info);
996 	}
997 	spin_unlock_irqrestore(&smi_info->si_lock, flags);
998 	return rv;
999 }
1000 
1001 static void set_run_to_completion(void *send_info, bool i_run_to_completion)
1002 {
1003 	struct smi_info   *smi_info = send_info;
1004 
1005 	smi_info->run_to_completion = i_run_to_completion;
1006 	if (i_run_to_completion)
1007 		flush_messages(smi_info);
1008 }
1009 
1010 /*
1011  * Use -1 as a special constant to tell that we are spinning in kipmid
1012  * looking for something and not delaying between checks
1013  */
1014 #define IPMI_TIME_NOT_BUSY ns_to_ktime(-1ull)
1015 static inline bool ipmi_thread_busy_wait(enum si_sm_result smi_result,
1016 					 const struct smi_info *smi_info,
1017 					 ktime_t *busy_until)
1018 {
1019 	unsigned int max_busy_us = 0;
1020 
1021 	if (smi_info->si_num < num_max_busy_us)
1022 		max_busy_us = kipmid_max_busy_us[smi_info->si_num];
1023 	if (max_busy_us == 0 || smi_result != SI_SM_CALL_WITH_DELAY)
1024 		*busy_until = IPMI_TIME_NOT_BUSY;
1025 	else if (*busy_until == IPMI_TIME_NOT_BUSY) {
1026 		*busy_until = ktime_get() + max_busy_us * NSEC_PER_USEC;
1027 	} else {
1028 		if (unlikely(ktime_get() > *busy_until)) {
1029 			*busy_until = IPMI_TIME_NOT_BUSY;
1030 			return false;
1031 		}
1032 	}
1033 	return true;
1034 }
1035 
1036 
1037 /*
1038  * A busy-waiting loop for speeding up IPMI operation.
1039  *
1040  * Lousy hardware makes this hard.  This is only enabled for systems
1041  * that are not BT and do not have interrupts.  It starts spinning
1042  * when an operation is complete or until max_busy tells it to stop
1043  * (if that is enabled).  See the paragraph on kimid_max_busy_us in
1044  * Documentation/driver-api/ipmi.rst for details.
1045  */
1046 static int ipmi_thread(void *data)
1047 {
1048 	struct smi_info *smi_info = data;
1049 	unsigned long flags;
1050 	enum si_sm_result smi_result;
1051 	ktime_t busy_until = IPMI_TIME_NOT_BUSY;
1052 
1053 	set_user_nice(current, MAX_NICE);
1054 	while (!kthread_should_stop()) {
1055 		int busy_wait;
1056 
1057 		spin_lock_irqsave(&(smi_info->si_lock), flags);
1058 		smi_result = smi_event_handler(smi_info, 0);
1059 
1060 		/*
1061 		 * If the driver is doing something, there is a possible
1062 		 * race with the timer.  If the timer handler see idle,
1063 		 * and the thread here sees something else, the timer
1064 		 * handler won't restart the timer even though it is
1065 		 * required.  So start it here if necessary.
1066 		 */
1067 		if (smi_result != SI_SM_IDLE && !smi_info->timer_running)
1068 			smi_mod_timer(smi_info, jiffies + SI_TIMEOUT_JIFFIES);
1069 
1070 		spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1071 		busy_wait = ipmi_thread_busy_wait(smi_result, smi_info,
1072 						  &busy_until);
1073 		if (smi_result == SI_SM_CALL_WITHOUT_DELAY) {
1074 			; /* do nothing */
1075 		} else if (smi_result == SI_SM_CALL_WITH_DELAY && busy_wait) {
1076 			/*
1077 			 * In maintenance mode we run as fast as
1078 			 * possible to allow firmware updates to
1079 			 * complete as fast as possible, but normally
1080 			 * don't bang on the scheduler.
1081 			 */
1082 			if (smi_info->in_maintenance_mode)
1083 				schedule();
1084 			else
1085 				usleep_range(100, 200);
1086 		} else if (smi_result == SI_SM_IDLE) {
1087 			if (atomic_read(&smi_info->need_watch)) {
1088 				schedule_timeout_interruptible(100);
1089 			} else {
1090 				/* Wait to be woken up when we are needed. */
1091 				__set_current_state(TASK_INTERRUPTIBLE);
1092 				schedule();
1093 			}
1094 		} else {
1095 			schedule_timeout_interruptible(1);
1096 		}
1097 	}
1098 	return 0;
1099 }
1100 
1101 
1102 static void poll(void *send_info)
1103 {
1104 	struct smi_info *smi_info = send_info;
1105 	unsigned long flags = 0;
1106 	bool run_to_completion = smi_info->run_to_completion;
1107 
1108 	/*
1109 	 * Make sure there is some delay in the poll loop so we can
1110 	 * drive time forward and timeout things.
1111 	 */
1112 	udelay(10);
1113 	if (!run_to_completion)
1114 		spin_lock_irqsave(&smi_info->si_lock, flags);
1115 	smi_event_handler(smi_info, 10);
1116 	if (!run_to_completion)
1117 		spin_unlock_irqrestore(&smi_info->si_lock, flags);
1118 }
1119 
1120 static void request_events(void *send_info)
1121 {
1122 	struct smi_info *smi_info = send_info;
1123 
1124 	if (!smi_info->has_event_buffer)
1125 		return;
1126 
1127 	atomic_set(&smi_info->req_events, 1);
1128 }
1129 
1130 static void set_need_watch(void *send_info, unsigned int watch_mask)
1131 {
1132 	struct smi_info *smi_info = send_info;
1133 	unsigned long flags;
1134 	int enable;
1135 
1136 	enable = !!watch_mask;
1137 
1138 	atomic_set(&smi_info->need_watch, enable);
1139 	spin_lock_irqsave(&smi_info->si_lock, flags);
1140 	check_start_timer_thread(smi_info);
1141 	spin_unlock_irqrestore(&smi_info->si_lock, flags);
1142 }
1143 
1144 static void smi_timeout(struct timer_list *t)
1145 {
1146 	struct smi_info   *smi_info = timer_container_of(smi_info, t,
1147 							 si_timer);
1148 	enum si_sm_result smi_result;
1149 	unsigned long     flags;
1150 	unsigned long     jiffies_now;
1151 	long              time_diff;
1152 	long		  timeout;
1153 
1154 	spin_lock_irqsave(&(smi_info->si_lock), flags);
1155 	debug_timestamp(smi_info, "Timer");
1156 
1157 	if (smi_info->si_state == SI_HOSED)
1158 		/* Try something to see if the BMC is now operational. */
1159 		start_get_flags(smi_info);
1160 
1161 	jiffies_now = jiffies;
1162 	time_diff = (((long)jiffies_now - (long)smi_info->last_timeout_jiffies)
1163 		     * SI_USEC_PER_JIFFY);
1164 	smi_result = smi_event_handler(smi_info, time_diff);
1165 
1166 	if (smi_info->si_state == SI_HOSED) {
1167 		timeout = jiffies + SI_TIMEOUT_HOSED;
1168 	} else if ((smi_info->io.irq) && (!smi_info->interrupt_disabled)) {
1169 		/* Running with interrupts, only do long timeouts. */
1170 		timeout = jiffies + SI_TIMEOUT_JIFFIES;
1171 		smi_inc_stat(smi_info, long_timeouts);
1172 	} else if (smi_result == SI_SM_CALL_WITH_DELAY) {
1173 		/*
1174 		 * If the state machine asks for a short delay, then shorten
1175 		 * the timer timeout.
1176 		 */
1177 		smi_inc_stat(smi_info, short_timeouts);
1178 		timeout = jiffies + 1;
1179 	} else {
1180 		smi_inc_stat(smi_info, long_timeouts);
1181 		timeout = jiffies + SI_TIMEOUT_JIFFIES;
1182 	}
1183 
1184 	if (smi_result != SI_SM_IDLE)
1185 		smi_mod_timer(smi_info, timeout);
1186 	else
1187 		smi_info->timer_running = false;
1188 	spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1189 }
1190 
1191 irqreturn_t ipmi_si_irq_handler(int irq, void *data)
1192 {
1193 	struct smi_info *smi_info = data;
1194 	unsigned long   flags;
1195 
1196 	if (smi_info->io.si_info->type == SI_BT)
1197 		/* We need to clear the IRQ flag for the BT interface. */
1198 		smi_info->io.outputb(&smi_info->io, IPMI_BT_INTMASK_REG,
1199 				     IPMI_BT_INTMASK_CLEAR_IRQ_BIT
1200 				     | IPMI_BT_INTMASK_ENABLE_IRQ_BIT);
1201 
1202 	spin_lock_irqsave(&(smi_info->si_lock), flags);
1203 
1204 	smi_inc_stat(smi_info, interrupts);
1205 
1206 	debug_timestamp(smi_info, "Interrupt");
1207 
1208 	smi_event_handler(smi_info, 0);
1209 	spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1210 	return IRQ_HANDLED;
1211 }
1212 
1213 static int smi_start_processing(void            *send_info,
1214 				struct ipmi_smi *intf)
1215 {
1216 	struct smi_info *new_smi = send_info;
1217 	int             enable = 0;
1218 
1219 	new_smi->intf = intf;
1220 
1221 	/* Set up the timer that drives the interface. */
1222 	timer_setup(&new_smi->si_timer, smi_timeout, 0);
1223 	new_smi->timer_can_start = true;
1224 	smi_mod_timer(new_smi, jiffies + SI_TIMEOUT_JIFFIES);
1225 
1226 	/* Try to claim any interrupts. */
1227 	if (new_smi->io.irq_setup) {
1228 		new_smi->io.irq_handler_data = new_smi;
1229 		new_smi->io.irq_setup(&new_smi->io);
1230 	}
1231 
1232 	/*
1233 	 * Check if the user forcefully enabled the daemon.
1234 	 */
1235 	if (new_smi->si_num < num_force_kipmid)
1236 		enable = force_kipmid[new_smi->si_num];
1237 	/*
1238 	 * The BT interface is efficient enough to not need a thread,
1239 	 * and there is no need for a thread if we have interrupts.
1240 	 */
1241 	else if (new_smi->io.si_info->type != SI_BT && !new_smi->io.irq)
1242 		enable = 1;
1243 
1244 	if (enable) {
1245 		new_smi->thread = kthread_run(ipmi_thread, new_smi,
1246 					      "kipmi%d", new_smi->si_num);
1247 		if (IS_ERR(new_smi->thread)) {
1248 			dev_notice(new_smi->io.dev,
1249 				   "Could not start kernel thread due to error %ld, only using timers to drive the interface\n",
1250 				   PTR_ERR(new_smi->thread));
1251 			new_smi->thread = NULL;
1252 		}
1253 	}
1254 
1255 	return 0;
1256 }
1257 
1258 static int get_smi_info(void *send_info, struct ipmi_smi_info *data)
1259 {
1260 	struct smi_info *smi = send_info;
1261 
1262 	data->addr_src = smi->io.addr_source;
1263 	data->dev = smi->io.dev;
1264 	data->addr_info = smi->io.addr_info;
1265 	get_device(smi->io.dev);
1266 
1267 	return 0;
1268 }
1269 
1270 static void set_maintenance_mode(void *send_info, bool enable)
1271 {
1272 	struct smi_info   *smi_info = send_info;
1273 
1274 	if (!enable)
1275 		atomic_set(&smi_info->req_events, 0);
1276 	smi_info->in_maintenance_mode = enable;
1277 }
1278 
1279 static void shutdown_smi(void *send_info);
1280 static const struct ipmi_smi_handlers handlers = {
1281 	.owner                  = THIS_MODULE,
1282 	.start_processing       = smi_start_processing,
1283 	.shutdown               = shutdown_smi,
1284 	.get_smi_info		= get_smi_info,
1285 	.sender			= sender,
1286 	.request_events		= request_events,
1287 	.set_need_watch		= set_need_watch,
1288 	.set_maintenance_mode   = set_maintenance_mode,
1289 	.set_run_to_completion  = set_run_to_completion,
1290 	.flush_messages		= flush_messages,
1291 	.poll			= poll,
1292 };
1293 
1294 static LIST_HEAD(smi_infos);
1295 static DEFINE_MUTEX(smi_infos_lock);
1296 static int smi_num; /* Used to sequence the SMIs */
1297 
1298 static const char * const addr_space_to_str[] = { "i/o", "mem" };
1299 
1300 module_param_array(force_kipmid, int, &num_force_kipmid, 0);
1301 MODULE_PARM_DESC(force_kipmid,
1302 		 "Force the kipmi daemon to be enabled (1) or disabled(0).  Normally the IPMI driver auto-detects this, but the value may be overridden by this parm.");
1303 module_param(unload_when_empty, bool, 0);
1304 MODULE_PARM_DESC(unload_when_empty,
1305 		 "Unload the module if no interfaces are specified or found, default is 1.  Setting to 0 is useful for hot add of devices using hotmod.");
1306 module_param_array(kipmid_max_busy_us, uint, &num_max_busy_us, 0644);
1307 MODULE_PARM_DESC(kipmid_max_busy_us,
1308 		 "Max time (in microseconds) to busy-wait for IPMI data before sleeping. 0 (default) means to wait forever. Set to 100-500 if kipmid is using up a lot of CPU time.");
1309 
1310 void ipmi_irq_finish_setup(struct si_sm_io *io)
1311 {
1312 	if (io->si_info->type == SI_BT)
1313 		/* Enable the interrupt in the BT interface. */
1314 		io->outputb(io, IPMI_BT_INTMASK_REG,
1315 			    IPMI_BT_INTMASK_ENABLE_IRQ_BIT);
1316 }
1317 
1318 void ipmi_irq_start_cleanup(struct si_sm_io *io)
1319 {
1320 	if (io->si_info->type == SI_BT)
1321 		/* Disable the interrupt in the BT interface. */
1322 		io->outputb(io, IPMI_BT_INTMASK_REG, 0);
1323 }
1324 
1325 static void std_irq_cleanup(struct si_sm_io *io)
1326 {
1327 	ipmi_irq_start_cleanup(io);
1328 	free_irq(io->irq, io->irq_handler_data);
1329 }
1330 
1331 int ipmi_std_irq_setup(struct si_sm_io *io)
1332 {
1333 	int rv;
1334 
1335 	if (!io->irq)
1336 		return 0;
1337 
1338 	rv = request_irq(io->irq,
1339 			 ipmi_si_irq_handler,
1340 			 IRQF_SHARED,
1341 			 SI_DEVICE_NAME,
1342 			 io->irq_handler_data);
1343 	if (rv) {
1344 		dev_warn(io->dev, "%s unable to claim interrupt %d, running polled\n",
1345 			 SI_DEVICE_NAME, io->irq);
1346 		io->irq = 0;
1347 	} else {
1348 		io->irq_cleanup = std_irq_cleanup;
1349 		ipmi_irq_finish_setup(io);
1350 		dev_info(io->dev, "Using irq %d\n", io->irq);
1351 	}
1352 
1353 	return rv;
1354 }
1355 
1356 static int wait_for_msg_done(struct smi_info *smi_info)
1357 {
1358 	enum si_sm_result     smi_result;
1359 
1360 	smi_result = smi_info->handlers->event(smi_info->si_sm, 0);
1361 	for (;;) {
1362 		if (smi_result == SI_SM_CALL_WITH_DELAY ||
1363 		    smi_result == SI_SM_CALL_WITH_TICK_DELAY) {
1364 			schedule_timeout_uninterruptible(1);
1365 			smi_result = smi_info->handlers->event(
1366 				smi_info->si_sm, jiffies_to_usecs(1));
1367 		} else if (smi_result == SI_SM_CALL_WITHOUT_DELAY) {
1368 			smi_result = smi_info->handlers->event(
1369 				smi_info->si_sm, 0);
1370 		} else
1371 			break;
1372 	}
1373 	if (smi_result == SI_SM_HOSED)
1374 		/*
1375 		 * We couldn't get the state machine to run, so whatever's at
1376 		 * the port is probably not an IPMI SMI interface.
1377 		 */
1378 		return -ENODEV;
1379 
1380 	return 0;
1381 }
1382 
1383 static int try_get_dev_id(struct smi_info *smi_info)
1384 {
1385 	unsigned char         msg[2];
1386 	unsigned char         *resp;
1387 	unsigned long         resp_len;
1388 	int                   rv = 0;
1389 	unsigned int          retry_count = 0;
1390 
1391 	resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
1392 	if (!resp)
1393 		return -ENOMEM;
1394 
1395 	/*
1396 	 * Do a Get Device ID command, since it comes back with some
1397 	 * useful info.
1398 	 */
1399 	msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1400 	msg[1] = IPMI_GET_DEVICE_ID_CMD;
1401 
1402 retry:
1403 	smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
1404 
1405 	rv = wait_for_msg_done(smi_info);
1406 	if (rv)
1407 		goto out;
1408 
1409 	resp_len = smi_info->handlers->get_result(smi_info->si_sm,
1410 						  resp, IPMI_MAX_MSG_LENGTH);
1411 
1412 	/* Check and record info from the get device id, in case we need it. */
1413 	rv = ipmi_demangle_device_id(resp[0] >> 2, resp[1],
1414 			resp + 2, resp_len - 2, &smi_info->device_id);
1415 	if (rv) {
1416 		/* record completion code */
1417 		unsigned char cc = *(resp + 2);
1418 
1419 		if (cc != IPMI_CC_NO_ERROR &&
1420 		    ++retry_count <= GET_DEVICE_ID_MAX_RETRY) {
1421 			dev_warn_ratelimited(smi_info->io.dev,
1422 			    "BMC returned 0x%2.2x, retry get bmc device id\n",
1423 			    cc);
1424 			goto retry;
1425 		}
1426 	}
1427 
1428 out:
1429 	kfree(resp);
1430 	return rv;
1431 }
1432 
1433 static int get_global_enables(struct smi_info *smi_info, u8 *enables)
1434 {
1435 	unsigned char         msg[3];
1436 	unsigned char         *resp;
1437 	unsigned long         resp_len;
1438 	int                   rv;
1439 
1440 	resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
1441 	if (!resp)
1442 		return -ENOMEM;
1443 
1444 	msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1445 	msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
1446 	smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
1447 
1448 	rv = wait_for_msg_done(smi_info);
1449 	if (rv) {
1450 		dev_warn(smi_info->io.dev,
1451 			 "Error getting response from get global enables command: %d\n",
1452 			 rv);
1453 		goto out;
1454 	}
1455 
1456 	resp_len = smi_info->handlers->get_result(smi_info->si_sm,
1457 						  resp, IPMI_MAX_MSG_LENGTH);
1458 
1459 	if (resp_len < 4 ||
1460 			resp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2 ||
1461 			resp[1] != IPMI_GET_BMC_GLOBAL_ENABLES_CMD   ||
1462 			resp[2] != 0) {
1463 		dev_warn(smi_info->io.dev,
1464 			 "Invalid return from get global enables command: %ld %x %x %x\n",
1465 			 resp_len, resp[0], resp[1], resp[2]);
1466 		rv = -EINVAL;
1467 		goto out;
1468 	} else {
1469 		*enables = resp[3];
1470 	}
1471 
1472 out:
1473 	kfree(resp);
1474 	return rv;
1475 }
1476 
1477 /*
1478  * Returns 1 if it gets an error from the command.
1479  */
1480 static int set_global_enables(struct smi_info *smi_info, u8 enables)
1481 {
1482 	unsigned char         msg[3];
1483 	unsigned char         *resp;
1484 	unsigned long         resp_len;
1485 	int                   rv;
1486 
1487 	resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
1488 	if (!resp)
1489 		return -ENOMEM;
1490 
1491 	msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1492 	msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
1493 	msg[2] = enables;
1494 	smi_info->handlers->start_transaction(smi_info->si_sm, msg, 3);
1495 
1496 	rv = wait_for_msg_done(smi_info);
1497 	if (rv) {
1498 		dev_warn(smi_info->io.dev,
1499 			 "Error getting response from set global enables command: %d\n",
1500 			 rv);
1501 		goto out;
1502 	}
1503 
1504 	resp_len = smi_info->handlers->get_result(smi_info->si_sm,
1505 						  resp, IPMI_MAX_MSG_LENGTH);
1506 
1507 	if (resp_len < 3 ||
1508 			resp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2 ||
1509 			resp[1] != IPMI_SET_BMC_GLOBAL_ENABLES_CMD) {
1510 		dev_warn(smi_info->io.dev,
1511 			 "Invalid return from set global enables command: %ld %x %x\n",
1512 			 resp_len, resp[0], resp[1]);
1513 		rv = -EINVAL;
1514 		goto out;
1515 	}
1516 
1517 	if (resp[2] != 0)
1518 		rv = 1;
1519 
1520 out:
1521 	kfree(resp);
1522 	return rv;
1523 }
1524 
1525 /*
1526  * Some BMCs do not support clearing the receive irq bit in the global
1527  * enables (even if they don't support interrupts on the BMC).  Check
1528  * for this and handle it properly.
1529  */
1530 static void check_clr_rcv_irq(struct smi_info *smi_info)
1531 {
1532 	u8 enables = 0;
1533 	int rv;
1534 
1535 	rv = get_global_enables(smi_info, &enables);
1536 	if (!rv) {
1537 		if ((enables & IPMI_BMC_RCV_MSG_INTR) == 0)
1538 			/* Already clear, should work ok. */
1539 			return;
1540 
1541 		enables &= ~IPMI_BMC_RCV_MSG_INTR;
1542 		rv = set_global_enables(smi_info, enables);
1543 	}
1544 
1545 	if (rv < 0) {
1546 		dev_err(smi_info->io.dev,
1547 			"Cannot check clearing the rcv irq: %d\n", rv);
1548 		return;
1549 	}
1550 
1551 	if (rv) {
1552 		/*
1553 		 * An error when setting the event buffer bit means
1554 		 * clearing the bit is not supported.
1555 		 */
1556 		dev_warn(smi_info->io.dev,
1557 			 "The BMC does not support clearing the recv irq bit, compensating, but the BMC needs to be fixed.\n");
1558 		smi_info->cannot_disable_irq = true;
1559 	}
1560 }
1561 
1562 /*
1563  * Some BMCs do not support setting the interrupt bits in the global
1564  * enables even if they support interrupts.  Clearly bad, but we can
1565  * compensate.
1566  */
1567 static void check_set_rcv_irq(struct smi_info *smi_info)
1568 {
1569 	u8 enables = 0;
1570 	int rv;
1571 
1572 	if (!smi_info->io.irq)
1573 		return;
1574 
1575 	rv = get_global_enables(smi_info, &enables);
1576 	if (!rv) {
1577 		enables |= IPMI_BMC_RCV_MSG_INTR;
1578 		rv = set_global_enables(smi_info, enables);
1579 	}
1580 
1581 	if (rv < 0) {
1582 		dev_err(smi_info->io.dev,
1583 			"Cannot check setting the rcv irq: %d\n", rv);
1584 		return;
1585 	}
1586 
1587 	if (rv) {
1588 		/*
1589 		 * An error when setting the event buffer bit means
1590 		 * setting the bit is not supported.
1591 		 */
1592 		dev_warn(smi_info->io.dev,
1593 			 "The BMC does not support setting the recv irq bit, compensating, but the BMC needs to be fixed.\n");
1594 		smi_info->cannot_disable_irq = true;
1595 		smi_info->irq_enable_broken = true;
1596 	}
1597 }
1598 
1599 static int try_enable_event_buffer(struct smi_info *smi_info)
1600 {
1601 	unsigned char         msg[3];
1602 	unsigned char         *resp;
1603 	unsigned long         resp_len;
1604 	int                   rv = 0;
1605 
1606 	resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
1607 	if (!resp)
1608 		return -ENOMEM;
1609 
1610 	msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1611 	msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
1612 	smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
1613 
1614 	rv = wait_for_msg_done(smi_info);
1615 	if (rv) {
1616 		pr_warn("Error getting response from get global enables command, the event buffer is not enabled\n");
1617 		goto out;
1618 	}
1619 
1620 	resp_len = smi_info->handlers->get_result(smi_info->si_sm,
1621 						  resp, IPMI_MAX_MSG_LENGTH);
1622 
1623 	if (resp_len < 4 ||
1624 			resp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2 ||
1625 			resp[1] != IPMI_GET_BMC_GLOBAL_ENABLES_CMD   ||
1626 			resp[2] != 0) {
1627 		pr_warn("Invalid return from get global enables command, cannot enable the event buffer\n");
1628 		rv = -EINVAL;
1629 		goto out;
1630 	}
1631 
1632 	if (resp[3] & IPMI_BMC_EVT_MSG_BUFF) {
1633 		/* buffer is already enabled, nothing to do. */
1634 		smi_info->supports_event_msg_buff = true;
1635 		goto out;
1636 	}
1637 
1638 	msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1639 	msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
1640 	msg[2] = resp[3] | IPMI_BMC_EVT_MSG_BUFF;
1641 	smi_info->handlers->start_transaction(smi_info->si_sm, msg, 3);
1642 
1643 	rv = wait_for_msg_done(smi_info);
1644 	if (rv) {
1645 		pr_warn("Error getting response from set global, enables command, the event buffer is not enabled\n");
1646 		goto out;
1647 	}
1648 
1649 	resp_len = smi_info->handlers->get_result(smi_info->si_sm,
1650 						  resp, IPMI_MAX_MSG_LENGTH);
1651 
1652 	if (resp_len < 3 ||
1653 			resp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2 ||
1654 			resp[1] != IPMI_SET_BMC_GLOBAL_ENABLES_CMD) {
1655 		pr_warn("Invalid return from get global, enables command, not enable the event buffer\n");
1656 		rv = -EINVAL;
1657 		goto out;
1658 	}
1659 
1660 	if (resp[2] != 0)
1661 		/*
1662 		 * An error when setting the event buffer bit means
1663 		 * that the event buffer is not supported.
1664 		 */
1665 		rv = -ENOENT;
1666 	else
1667 		smi_info->supports_event_msg_buff = true;
1668 
1669 out:
1670 	kfree(resp);
1671 	return rv;
1672 }
1673 
1674 #define IPMI_SI_ATTR(name) \
1675 static ssize_t name##_show(struct device *dev,			\
1676 			   struct device_attribute *attr,		\
1677 			   char *buf)					\
1678 {									\
1679 	struct smi_info *smi_info = dev_get_drvdata(dev);		\
1680 									\
1681 	return sysfs_emit(buf, "%u\n", smi_get_stat(smi_info, name));	\
1682 }									\
1683 static DEVICE_ATTR_RO(name)
1684 
1685 static ssize_t type_show(struct device *dev,
1686 			 struct device_attribute *attr,
1687 			 char *buf)
1688 {
1689 	struct smi_info *smi_info = dev_get_drvdata(dev);
1690 
1691 	return sysfs_emit(buf, "%s\n", si_to_str[smi_info->io.si_info->type]);
1692 }
1693 static DEVICE_ATTR_RO(type);
1694 
1695 static ssize_t interrupts_enabled_show(struct device *dev,
1696 				       struct device_attribute *attr,
1697 				       char *buf)
1698 {
1699 	struct smi_info *smi_info = dev_get_drvdata(dev);
1700 	int enabled = smi_info->io.irq && !smi_info->interrupt_disabled;
1701 
1702 	return sysfs_emit(buf, "%d\n", enabled);
1703 }
1704 static DEVICE_ATTR_RO(interrupts_enabled);
1705 
1706 IPMI_SI_ATTR(short_timeouts);
1707 IPMI_SI_ATTR(long_timeouts);
1708 IPMI_SI_ATTR(idles);
1709 IPMI_SI_ATTR(interrupts);
1710 IPMI_SI_ATTR(attentions);
1711 IPMI_SI_ATTR(flag_fetches);
1712 IPMI_SI_ATTR(hosed_count);
1713 IPMI_SI_ATTR(complete_transactions);
1714 IPMI_SI_ATTR(events);
1715 IPMI_SI_ATTR(watchdog_pretimeouts);
1716 IPMI_SI_ATTR(incoming_messages);
1717 
1718 static ssize_t params_show(struct device *dev,
1719 			   struct device_attribute *attr,
1720 			   char *buf)
1721 {
1722 	struct smi_info *smi_info = dev_get_drvdata(dev);
1723 
1724 	return sysfs_emit(buf,
1725 			"%s,%s,0x%lx,rsp=%d,rsi=%d,rsh=%d,irq=%d,ipmb=%d\n",
1726 			si_to_str[smi_info->io.si_info->type],
1727 			addr_space_to_str[smi_info->io.addr_space],
1728 			smi_info->io.addr_data,
1729 			smi_info->io.regspacing,
1730 			smi_info->io.regsize,
1731 			smi_info->io.regshift,
1732 			smi_info->io.irq,
1733 			smi_info->io.slave_addr);
1734 }
1735 static DEVICE_ATTR_RO(params);
1736 
1737 static struct attribute *ipmi_si_dev_attrs[] = {
1738 	&dev_attr_type.attr,
1739 	&dev_attr_interrupts_enabled.attr,
1740 	&dev_attr_short_timeouts.attr,
1741 	&dev_attr_long_timeouts.attr,
1742 	&dev_attr_idles.attr,
1743 	&dev_attr_interrupts.attr,
1744 	&dev_attr_attentions.attr,
1745 	&dev_attr_flag_fetches.attr,
1746 	&dev_attr_hosed_count.attr,
1747 	&dev_attr_complete_transactions.attr,
1748 	&dev_attr_events.attr,
1749 	&dev_attr_watchdog_pretimeouts.attr,
1750 	&dev_attr_incoming_messages.attr,
1751 	&dev_attr_params.attr,
1752 	NULL
1753 };
1754 
1755 static const struct attribute_group ipmi_si_dev_attr_group = {
1756 	.attrs		= ipmi_si_dev_attrs,
1757 };
1758 
1759 /*
1760  * oem_data_avail_to_receive_msg_avail
1761  * @info - smi_info structure with msg_flags set
1762  *
1763  * Converts flags from OEM_DATA_AVAIL to RECEIVE_MSG_AVAIL
1764  * Returns 1 indicating need to re-run handle_flags().
1765  */
1766 static int oem_data_avail_to_receive_msg_avail(struct smi_info *smi_info)
1767 {
1768 	smi_info->msg_flags = ((smi_info->msg_flags & ~OEM_DATA_AVAIL) |
1769 			       RECEIVE_MSG_AVAIL);
1770 	return 1;
1771 }
1772 
1773 /*
1774  * setup_dell_poweredge_oem_data_handler
1775  * @info - smi_info.device_id must be populated
1776  *
1777  * Systems that match, but have firmware version < 1.40 may assert
1778  * OEM0_DATA_AVAIL on their own, without being told via Set Flags that
1779  * it's safe to do so.  Such systems will de-assert OEM1_DATA_AVAIL
1780  * upon receipt of IPMI_GET_MSG_CMD, so we should treat these flags
1781  * as RECEIVE_MSG_AVAIL instead.
1782  *
1783  * As Dell has no plans to release IPMI 1.5 firmware that *ever*
1784  * assert the OEM[012] bits, and if it did, the driver would have to
1785  * change to handle that properly, we don't actually check for the
1786  * firmware version.
1787  * Device ID = 0x20                BMC on PowerEdge 8G servers
1788  * Device Revision = 0x80
1789  * Firmware Revision1 = 0x01       BMC version 1.40
1790  * Firmware Revision2 = 0x40       BCD encoded
1791  * IPMI Version = 0x51             IPMI 1.5
1792  * Manufacturer ID = A2 02 00      Dell IANA
1793  *
1794  * Additionally, PowerEdge systems with IPMI < 1.5 may also assert
1795  * OEM0_DATA_AVAIL and needs to be treated as RECEIVE_MSG_AVAIL.
1796  *
1797  */
1798 #define DELL_POWEREDGE_8G_BMC_DEVICE_ID  0x20
1799 #define DELL_POWEREDGE_8G_BMC_DEVICE_REV 0x80
1800 #define DELL_POWEREDGE_8G_BMC_IPMI_VERSION 0x51
1801 #define DELL_IANA_MFR_ID 0x0002a2
1802 static void setup_dell_poweredge_oem_data_handler(struct smi_info *smi_info)
1803 {
1804 	struct ipmi_device_id *id = &smi_info->device_id;
1805 	if (id->manufacturer_id == DELL_IANA_MFR_ID) {
1806 		if (id->device_id       == DELL_POWEREDGE_8G_BMC_DEVICE_ID  &&
1807 		    id->device_revision == DELL_POWEREDGE_8G_BMC_DEVICE_REV &&
1808 		    id->ipmi_version   == DELL_POWEREDGE_8G_BMC_IPMI_VERSION) {
1809 			smi_info->oem_data_avail_handler =
1810 				oem_data_avail_to_receive_msg_avail;
1811 		} else if (ipmi_version_major(id) < 1 ||
1812 			   (ipmi_version_major(id) == 1 &&
1813 			    ipmi_version_minor(id) < 5)) {
1814 			smi_info->oem_data_avail_handler =
1815 				oem_data_avail_to_receive_msg_avail;
1816 		}
1817 	}
1818 }
1819 
1820 #define CANNOT_RETURN_REQUESTED_LENGTH 0xCA
1821 static void return_hosed_msg_badsize(struct smi_info *smi_info)
1822 {
1823 	struct ipmi_smi_msg *msg = smi_info->curr_msg;
1824 
1825 	/* Make it a response */
1826 	msg->rsp[0] = msg->data[0] | 4;
1827 	msg->rsp[1] = msg->data[1];
1828 	msg->rsp[2] = CANNOT_RETURN_REQUESTED_LENGTH;
1829 	msg->rsp_size = 3;
1830 	smi_info->curr_msg = NULL;
1831 	deliver_recv_msg(smi_info, msg);
1832 }
1833 
1834 /*
1835  * dell_poweredge_bt_xaction_handler
1836  * @info - smi_info.device_id must be populated
1837  *
1838  * Dell PowerEdge servers with the BT interface (x6xx and 1750) will
1839  * not respond to a Get SDR command if the length of the data
1840  * requested is exactly 0x3A, which leads to command timeouts and no
1841  * data returned.  This intercepts such commands, and causes userspace
1842  * callers to try again with a different-sized buffer, which succeeds.
1843  */
1844 
1845 #define STORAGE_NETFN 0x0A
1846 #define STORAGE_CMD_GET_SDR 0x23
1847 static int dell_poweredge_bt_xaction_handler(struct notifier_block *self,
1848 					     unsigned long unused,
1849 					     void *in)
1850 {
1851 	struct smi_info *smi_info = in;
1852 	unsigned char *data = smi_info->curr_msg->data;
1853 	unsigned int size   = smi_info->curr_msg->data_size;
1854 	if (size >= 8 &&
1855 	    (data[0]>>2) == STORAGE_NETFN &&
1856 	    data[1] == STORAGE_CMD_GET_SDR &&
1857 	    data[7] == 0x3A) {
1858 		return_hosed_msg_badsize(smi_info);
1859 		return NOTIFY_STOP;
1860 	}
1861 	return NOTIFY_DONE;
1862 }
1863 
1864 static struct notifier_block dell_poweredge_bt_xaction_notifier = {
1865 	.notifier_call	= dell_poweredge_bt_xaction_handler,
1866 };
1867 
1868 /*
1869  * setup_dell_poweredge_bt_xaction_handler
1870  * @info - smi_info.device_id must be filled in already
1871  *
1872  * Fills in smi_info.device_id.start_transaction_pre_hook
1873  * when we know what function to use there.
1874  */
1875 static void
1876 setup_dell_poweredge_bt_xaction_handler(struct smi_info *smi_info)
1877 {
1878 	struct ipmi_device_id *id = &smi_info->device_id;
1879 	if (id->manufacturer_id == DELL_IANA_MFR_ID &&
1880 	    smi_info->io.si_info->type == SI_BT)
1881 		register_xaction_notifier(&dell_poweredge_bt_xaction_notifier);
1882 }
1883 
1884 /*
1885  * setup_oem_data_handler
1886  * @info - smi_info.device_id must be filled in already
1887  *
1888  * Fills in smi_info.device_id.oem_data_available_handler
1889  * when we know what function to use there.
1890  */
1891 
1892 static void setup_oem_data_handler(struct smi_info *smi_info)
1893 {
1894 	setup_dell_poweredge_oem_data_handler(smi_info);
1895 }
1896 
1897 static void setup_xaction_handlers(struct smi_info *smi_info)
1898 {
1899 	setup_dell_poweredge_bt_xaction_handler(smi_info);
1900 }
1901 
1902 static void check_for_broken_irqs(struct smi_info *smi_info)
1903 {
1904 	check_clr_rcv_irq(smi_info);
1905 	check_set_rcv_irq(smi_info);
1906 }
1907 
1908 static inline void stop_timer_and_thread(struct smi_info *smi_info)
1909 {
1910 	if (smi_info->thread != NULL) {
1911 		kthread_stop(smi_info->thread);
1912 		smi_info->thread = NULL;
1913 	}
1914 
1915 	smi_info->timer_can_start = false;
1916 	timer_delete_sync(&smi_info->si_timer);
1917 }
1918 
1919 static struct smi_info *find_dup_si(struct smi_info *info)
1920 {
1921 	struct smi_info *e;
1922 
1923 	list_for_each_entry(e, &smi_infos, link) {
1924 		if (e->io.addr_space != info->io.addr_space)
1925 			continue;
1926 		if (e->io.addr_data == info->io.addr_data) {
1927 			/*
1928 			 * This is a cheap hack, ACPI doesn't have a defined
1929 			 * slave address but SMBIOS does.  Pick it up from
1930 			 * any source that has it available.
1931 			 */
1932 			if (info->io.slave_addr && !e->io.slave_addr)
1933 				e->io.slave_addr = info->io.slave_addr;
1934 			return e;
1935 		}
1936 	}
1937 
1938 	return NULL;
1939 }
1940 
1941 int ipmi_si_add_smi(struct si_sm_io *io)
1942 {
1943 	int rv = 0;
1944 	struct smi_info *new_smi, *dup;
1945 
1946 	/*
1947 	 * If the user gave us a hard-coded device at the same
1948 	 * address, they presumably want us to use it and not what is
1949 	 * in the firmware.
1950 	 */
1951 	if (io->addr_source != SI_HARDCODED && io->addr_source != SI_HOTMOD &&
1952 	    ipmi_si_hardcode_match(io->addr_space, io->addr_data)) {
1953 		dev_info(io->dev,
1954 			 "Hard-coded device at this address already exists");
1955 		return -ENODEV;
1956 	}
1957 
1958 	if (!io->io_setup) {
1959 		if (IS_ENABLED(CONFIG_HAS_IOPORT) &&
1960 		    io->addr_space == IPMI_IO_ADDR_SPACE) {
1961 			io->io_setup = ipmi_si_port_setup;
1962 		} else if (io->addr_space == IPMI_MEM_ADDR_SPACE) {
1963 			io->io_setup = ipmi_si_mem_setup;
1964 		} else {
1965 			return -EINVAL;
1966 		}
1967 	}
1968 
1969 	new_smi = kzalloc_obj(*new_smi);
1970 	if (!new_smi)
1971 		return -ENOMEM;
1972 	spin_lock_init(&new_smi->si_lock);
1973 
1974 	new_smi->io = *io;
1975 
1976 	mutex_lock(&smi_infos_lock);
1977 	dup = find_dup_si(new_smi);
1978 	if (dup) {
1979 		if (new_smi->io.addr_source == SI_ACPI &&
1980 		    dup->io.addr_source == SI_SMBIOS) {
1981 			/* We prefer ACPI over SMBIOS. */
1982 			dev_info(dup->io.dev,
1983 				 "Removing SMBIOS-specified %s state machine in favor of ACPI\n",
1984 				 si_to_str[new_smi->io.si_info->type]);
1985 			cleanup_one_si(dup);
1986 		} else {
1987 			dev_info(new_smi->io.dev,
1988 				 "%s-specified %s state machine: duplicate\n",
1989 				 ipmi_addr_src_to_str(new_smi->io.addr_source),
1990 				 si_to_str[new_smi->io.si_info->type]);
1991 			rv = -EBUSY;
1992 			kfree(new_smi);
1993 			goto out_err;
1994 		}
1995 	}
1996 
1997 	pr_info("Adding %s-specified %s state machine\n",
1998 		ipmi_addr_src_to_str(new_smi->io.addr_source),
1999 		si_to_str[new_smi->io.si_info->type]);
2000 
2001 	list_add_tail(&new_smi->link, &smi_infos);
2002 
2003 	if (initialized)
2004 		rv = try_smi_init(new_smi);
2005 out_err:
2006 	mutex_unlock(&smi_infos_lock);
2007 	return rv;
2008 }
2009 
2010 /*
2011  * Try to start up an interface.  Must be called with smi_infos_lock
2012  * held, primarily to keep smi_num consistent, we only one to do these
2013  * one at a time.
2014  */
2015 static int try_smi_init(struct smi_info *new_smi)
2016 {
2017 	int rv = 0;
2018 	int i;
2019 
2020 	pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n",
2021 		ipmi_addr_src_to_str(new_smi->io.addr_source),
2022 		si_to_str[new_smi->io.si_info->type],
2023 		addr_space_to_str[new_smi->io.addr_space],
2024 		new_smi->io.addr_data,
2025 		new_smi->io.slave_addr, new_smi->io.irq);
2026 
2027 	switch (new_smi->io.si_info->type) {
2028 	case SI_KCS:
2029 		new_smi->handlers = &kcs_smi_handlers;
2030 		break;
2031 
2032 	case SI_SMIC:
2033 		new_smi->handlers = &smic_smi_handlers;
2034 		break;
2035 
2036 	case SI_BT:
2037 		new_smi->handlers = &bt_smi_handlers;
2038 		break;
2039 
2040 	default:
2041 		/* No support for anything else yet. */
2042 		rv = -EIO;
2043 		goto out_err;
2044 	}
2045 
2046 	new_smi->si_num = smi_num;
2047 
2048 	/* Do this early so it's available for logs. */
2049 	if (!new_smi->io.dev) {
2050 		pr_err("IPMI interface added with no device\n");
2051 		rv = -EIO;
2052 		goto out_err;
2053 	}
2054 
2055 	/* Allocate the state machine's data and initialize it. */
2056 	new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL);
2057 	if (!new_smi->si_sm) {
2058 		rv = -ENOMEM;
2059 		goto out_err;
2060 	}
2061 	new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm,
2062 							   &new_smi->io);
2063 
2064 	/* Now that we know the I/O size, we can set up the I/O. */
2065 	rv = new_smi->io.io_setup(&new_smi->io);
2066 	if (rv) {
2067 		dev_err(new_smi->io.dev, "Could not set up I/O space\n");
2068 		goto out_err;
2069 	}
2070 
2071 	/* Do low-level detection first. */
2072 	if (new_smi->handlers->detect(new_smi->si_sm)) {
2073 		if (new_smi->io.addr_source)
2074 			dev_err(new_smi->io.dev,
2075 				"Interface detection failed\n");
2076 		rv = -ENODEV;
2077 		goto out_err;
2078 	}
2079 
2080 	/*
2081 	 * Attempt a get device id command.  If it fails, we probably
2082 	 * don't have a BMC here.
2083 	 */
2084 	rv = try_get_dev_id(new_smi);
2085 	if (rv) {
2086 		if (new_smi->io.addr_source)
2087 			dev_err(new_smi->io.dev,
2088 			       "There appears to be no BMC at this location\n");
2089 		goto out_err;
2090 	}
2091 
2092 	setup_oem_data_handler(new_smi);
2093 	setup_xaction_handlers(new_smi);
2094 	check_for_broken_irqs(new_smi);
2095 
2096 	new_smi->waiting_msg = NULL;
2097 	new_smi->curr_msg = NULL;
2098 	atomic_set(&new_smi->req_events, 0);
2099 	new_smi->run_to_completion = false;
2100 	for (i = 0; i < SI_NUM_STATS; i++)
2101 		atomic_set(&new_smi->stats[i], 0);
2102 
2103 	new_smi->interrupt_disabled = true;
2104 	atomic_set(&new_smi->need_watch, 0);
2105 
2106 	rv = try_enable_event_buffer(new_smi);
2107 	if (rv == 0)
2108 		new_smi->has_event_buffer = true;
2109 
2110 	/*
2111 	 * Start clearing the flags before we enable interrupts or the
2112 	 * timer to avoid racing with the timer.
2113 	 */
2114 	start_clear_flags(new_smi);
2115 
2116 	/*
2117 	 * IRQ is defined to be set when non-zero.  req_events will
2118 	 * cause a global flags check that will enable interrupts.
2119 	 */
2120 	if (new_smi->io.irq) {
2121 		new_smi->interrupt_disabled = false;
2122 		atomic_set(&new_smi->req_events, 1);
2123 	}
2124 
2125 	dev_set_drvdata(new_smi->io.dev, new_smi);
2126 	rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group);
2127 	if (rv) {
2128 		dev_err(new_smi->io.dev,
2129 			"Unable to add device attributes: error %d\n",
2130 			rv);
2131 		goto out_err;
2132 	}
2133 	new_smi->dev_group_added = true;
2134 
2135 	rv = ipmi_register_smi(&handlers,
2136 			       new_smi,
2137 			       new_smi->io.dev,
2138 			       new_smi->io.slave_addr);
2139 	if (rv) {
2140 		dev_err(new_smi->io.dev,
2141 			"Unable to register device: error %d\n",
2142 			rv);
2143 		goto out_err;
2144 	}
2145 
2146 	/* Don't increment till we know we have succeeded. */
2147 	smi_num++;
2148 
2149 	dev_info(new_smi->io.dev, "IPMI %s interface initialized\n",
2150 		 si_to_str[new_smi->io.si_info->type]);
2151 
2152 	WARN_ON(new_smi->io.dev->init_name != NULL);
2153 
2154  out_err:
2155 	if (rv && new_smi->io.io_cleanup) {
2156 		new_smi->io.io_cleanup(&new_smi->io);
2157 		new_smi->io.io_cleanup = NULL;
2158 	}
2159 
2160 	if (rv && new_smi->si_sm) {
2161 		kfree(new_smi->si_sm);
2162 		new_smi->si_sm = NULL;
2163 	}
2164 
2165 	return rv;
2166 }
2167 
2168 /*
2169  * Devices in the same address space at the same address are the same.
2170  */
2171 static bool __init ipmi_smi_info_same(struct smi_info *e1, struct smi_info *e2)
2172 {
2173 	return (e1->io.addr_space == e2->io.addr_space &&
2174 		e1->io.addr_data == e2->io.addr_data);
2175 }
2176 
2177 static int __init init_ipmi_si(void)
2178 {
2179 	struct smi_info *e, *e2;
2180 
2181 	if (initialized)
2182 		return 0;
2183 
2184 	ipmi_hardcode_init();
2185 
2186 	pr_info("IPMI System Interface driver\n");
2187 
2188 	ipmi_si_platform_init();
2189 
2190 	ipmi_si_pci_init();
2191 
2192 	ipmi_si_ls2k_init();
2193 
2194 	ipmi_si_parisc_init();
2195 
2196 	mutex_lock(&smi_infos_lock);
2197 
2198 	/*
2199 	 * Scan through all the devices.  We prefer devices with
2200 	 * interrupts, so go through those first in case there are any
2201 	 * duplicates that don't have the interrupt set.
2202 	 */
2203 	list_for_each_entry(e, &smi_infos, link) {
2204 		bool dup = false;
2205 
2206 		/* Register ones with interrupts first. */
2207 		if (!e->io.irq)
2208 			continue;
2209 
2210 		/*
2211 		 * Go through the ones we have already seen to see if this
2212 		 * is a dup.
2213 		 */
2214 		list_for_each_entry(e2, &smi_infos, link) {
2215 			if (e2 == e)
2216 				break;
2217 			if (e2->io.irq && ipmi_smi_info_same(e, e2)) {
2218 				dup = true;
2219 				break;
2220 			}
2221 		}
2222 		if (!dup)
2223 			try_smi_init(e);
2224 	}
2225 
2226 	/*
2227 	 * Now try devices without interrupts.
2228 	 */
2229 	list_for_each_entry(e, &smi_infos, link) {
2230 		bool dup = false;
2231 
2232 		if (e->io.irq)
2233 			continue;
2234 
2235 		/*
2236 		 * Go through the ones we have already seen to see if
2237 		 * this is a dup.  We have already looked at the ones
2238 		 * with interrupts.
2239 		 */
2240 		list_for_each_entry(e2, &smi_infos, link) {
2241 			if (!e2->io.irq)
2242 				continue;
2243 			if (ipmi_smi_info_same(e, e2)) {
2244 				dup = true;
2245 				break;
2246 			}
2247 		}
2248 		list_for_each_entry(e2, &smi_infos, link) {
2249 			if (e2 == e)
2250 				break;
2251 			if (ipmi_smi_info_same(e, e2)) {
2252 				dup = true;
2253 				break;
2254 			}
2255 		}
2256 		if (!dup)
2257 			try_smi_init(e);
2258 	}
2259 
2260 	initialized = true;
2261 	mutex_unlock(&smi_infos_lock);
2262 
2263 	mutex_lock(&smi_infos_lock);
2264 	if (unload_when_empty && list_empty(&smi_infos)) {
2265 		mutex_unlock(&smi_infos_lock);
2266 		cleanup_ipmi_si();
2267 		pr_warn("Unable to find any System Interface(s)\n");
2268 		return -ENODEV;
2269 	} else {
2270 		mutex_unlock(&smi_infos_lock);
2271 		return 0;
2272 	}
2273 }
2274 module_init(init_ipmi_si);
2275 
2276 static void wait_msg_processed(struct smi_info *smi_info)
2277 {
2278 	unsigned long jiffies_now;
2279 	long time_diff;
2280 
2281 	while (smi_info->si_state != SI_HOSED &&
2282 		    (smi_info->curr_msg || (smi_info->si_state != SI_NORMAL))) {
2283 		jiffies_now = jiffies;
2284 		time_diff = (((long)jiffies_now - (long)smi_info->last_timeout_jiffies)
2285 		     * SI_USEC_PER_JIFFY);
2286 		smi_event_handler(smi_info, time_diff);
2287 		schedule_timeout_uninterruptible(1);
2288 	}
2289 }
2290 
2291 static void shutdown_smi(void *send_info)
2292 {
2293 	struct smi_info *smi_info = send_info;
2294 
2295 	if (smi_info->dev_group_added) {
2296 		device_remove_group(smi_info->io.dev, &ipmi_si_dev_attr_group);
2297 		smi_info->dev_group_added = false;
2298 	}
2299 	if (smi_info->io.dev)
2300 		dev_set_drvdata(smi_info->io.dev, NULL);
2301 
2302 	/*
2303 	 * Make sure that interrupts, the timer and the thread are
2304 	 * stopped and will not run again.
2305 	 */
2306 	smi_info->interrupt_disabled = true;
2307 	if (smi_info->io.irq_cleanup) {
2308 		smi_info->io.irq_cleanup(&smi_info->io);
2309 		smi_info->io.irq_cleanup = NULL;
2310 	}
2311 	stop_timer_and_thread(smi_info);
2312 
2313 	/*
2314 	 * Wait until we know that we are out of any interrupt
2315 	 * handlers might have been running before we freed the
2316 	 * interrupt.
2317 	 */
2318 	synchronize_rcu();
2319 
2320 	/*
2321 	 * Timeouts are stopped, now make sure the interrupts are off
2322 	 * in the BMC.  Note that timers and CPU interrupts are off,
2323 	 * so no need for locks.
2324 	 */
2325 	wait_msg_processed(smi_info);
2326 
2327 	if (smi_info->handlers)
2328 		disable_si_irq(smi_info);
2329 
2330 	wait_msg_processed(smi_info);
2331 
2332 	if (smi_info->handlers)
2333 		smi_info->handlers->cleanup(smi_info->si_sm);
2334 
2335 	if (smi_info->io.io_cleanup) {
2336 		smi_info->io.io_cleanup(&smi_info->io);
2337 		smi_info->io.io_cleanup = NULL;
2338 	}
2339 
2340 	kfree(smi_info->si_sm);
2341 	smi_info->si_sm = NULL;
2342 
2343 	smi_info->intf = NULL;
2344 }
2345 
2346 /*
2347  * Must be called with smi_infos_lock held, to serialize the
2348  * smi_info->intf check.
2349  */
2350 static void cleanup_one_si(struct smi_info *smi_info)
2351 {
2352 	if (!smi_info)
2353 		return;
2354 
2355 	list_del(&smi_info->link);
2356 	ipmi_unregister_smi(smi_info->intf);
2357 	kfree(smi_info);
2358 }
2359 
2360 void ipmi_si_remove_by_dev(struct device *dev)
2361 {
2362 	struct smi_info *e;
2363 
2364 	mutex_lock(&smi_infos_lock);
2365 	list_for_each_entry(e, &smi_infos, link) {
2366 		if (e->io.dev == dev) {
2367 			cleanup_one_si(e);
2368 			break;
2369 		}
2370 	}
2371 	mutex_unlock(&smi_infos_lock);
2372 }
2373 
2374 struct device *ipmi_si_remove_by_data(int addr_space, enum si_type si_type,
2375 				      unsigned long addr)
2376 {
2377 	/* remove */
2378 	struct smi_info *e, *tmp_e;
2379 	struct device *dev = NULL;
2380 
2381 	mutex_lock(&smi_infos_lock);
2382 	list_for_each_entry_safe(e, tmp_e, &smi_infos, link) {
2383 		if (e->io.addr_space != addr_space)
2384 			continue;
2385 		if (e->io.si_info->type != si_type)
2386 			continue;
2387 		if (e->io.addr_data == addr) {
2388 			dev = get_device(e->io.dev);
2389 			cleanup_one_si(e);
2390 		}
2391 	}
2392 	mutex_unlock(&smi_infos_lock);
2393 
2394 	return dev;
2395 }
2396 
2397 static void cleanup_ipmi_si(void)
2398 {
2399 	struct smi_info *e, *tmp_e;
2400 
2401 	if (!initialized)
2402 		return;
2403 
2404 	ipmi_si_pci_shutdown();
2405 
2406 	ipmi_si_ls2k_shutdown();
2407 
2408 	ipmi_si_parisc_shutdown();
2409 
2410 	ipmi_si_platform_shutdown();
2411 
2412 	mutex_lock(&smi_infos_lock);
2413 	list_for_each_entry_safe(e, tmp_e, &smi_infos, link)
2414 		cleanup_one_si(e);
2415 	mutex_unlock(&smi_infos_lock);
2416 
2417 	ipmi_si_hardcode_exit();
2418 	ipmi_si_hotmod_exit();
2419 }
2420 module_exit(cleanup_ipmi_si);
2421 
2422 MODULE_ALIAS("platform:dmi-ipmi-si");
2423 MODULE_LICENSE("GPL");
2424 MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
2425 MODULE_DESCRIPTION("Interface to the IPMI driver for the KCS, SMIC, and BT system interfaces.");
2426