ipmi: use a tasklet for handling received messages
[linux-2.6.git] / drivers / char / ipmi / ipmi_si_intf.c
1 /*
2  * ipmi_si.c
3  *
4  * The interface to the IPMI driver for the system interfaces (KCS, SMIC,
5  * BT).
6  *
7  * Author: MontaVista Software, Inc.
8  *         Corey Minyard <minyard@mvista.com>
9  *         source@mvista.com
10  *
11  * Copyright 2002 MontaVista Software Inc.
12  * Copyright 2006 IBM Corp., Christian Krafft <krafft@de.ibm.com>
13  *
14  *  This program is free software; you can redistribute it and/or modify it
15  *  under the terms of the GNU General Public License as published by the
16  *  Free Software Foundation; either version 2 of the License, or (at your
17  *  option) any later version.
18  *
19  *
20  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
21  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
26  *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27  *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
28  *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
29  *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  *  You should have received a copy of the GNU General Public License along
32  *  with this program; if not, write to the Free Software Foundation, Inc.,
33  *  675 Mass Ave, Cambridge, MA 02139, USA.
34  */
35
36 /*
37  * This file holds the "policy" for the interface to the SMI state
38  * machine.  It does the configuration, handles timers and interrupts,
39  * and drives the real SMI state machine.
40  */
41
42 #include <linux/module.h>
43 #include <linux/moduleparam.h>
44 #include <asm/system.h>
45 #include <linux/sched.h>
46 #include <linux/seq_file.h>
47 #include <linux/timer.h>
48 #include <linux/errno.h>
49 #include <linux/spinlock.h>
50 #include <linux/slab.h>
51 #include <linux/delay.h>
52 #include <linux/list.h>
53 #include <linux/pci.h>
54 #include <linux/ioport.h>
55 #include <linux/notifier.h>
56 #include <linux/mutex.h>
57 #include <linux/kthread.h>
58 #include <asm/irq.h>
59 #include <linux/interrupt.h>
60 #include <linux/rcupdate.h>
61 #include <linux/ipmi.h>
62 #include <linux/ipmi_smi.h>
63 #include <asm/io.h>
64 #include "ipmi_si_sm.h"
65 #include <linux/init.h>
66 #include <linux/dmi.h>
67 #include <linux/string.h>
68 #include <linux/ctype.h>
69 #include <linux/pnp.h>
70 #include <linux/of_device.h>
71 #include <linux/of_platform.h>
72 #include <linux/of_address.h>
73 #include <linux/of_irq.h>
74
75 #define PFX "ipmi_si: "
76
77 /* Measure times between events in the driver. */
78 #undef DEBUG_TIMING
79
80 /* Call every 10 ms. */
81 #define SI_TIMEOUT_TIME_USEC    10000
82 #define SI_USEC_PER_JIFFY       (1000000/HZ)
83 #define SI_TIMEOUT_JIFFIES      (SI_TIMEOUT_TIME_USEC/SI_USEC_PER_JIFFY)
84 #define SI_SHORT_TIMEOUT_USEC  250 /* .25ms when the SM request a
85                                       short timeout */
86
87 enum si_intf_state {
88         SI_NORMAL,
89         SI_GETTING_FLAGS,
90         SI_GETTING_EVENTS,
91         SI_CLEARING_FLAGS,
92         SI_CLEARING_FLAGS_THEN_SET_IRQ,
93         SI_GETTING_MESSAGES,
94         SI_ENABLE_INTERRUPTS1,
95         SI_ENABLE_INTERRUPTS2,
96         SI_DISABLE_INTERRUPTS1,
97         SI_DISABLE_INTERRUPTS2
98         /* FIXME - add watchdog stuff. */
99 };
100
101 /* Some BT-specific defines we need here. */
102 #define IPMI_BT_INTMASK_REG             2
103 #define IPMI_BT_INTMASK_CLEAR_IRQ_BIT   2
104 #define IPMI_BT_INTMASK_ENABLE_IRQ_BIT  1
105
106 enum si_type {
107     SI_KCS, SI_SMIC, SI_BT
108 };
109 static char *si_to_str[] = { "kcs", "smic", "bt" };
110
111 static char *ipmi_addr_src_to_str[] = { NULL, "hotmod", "hardcoded", "SPMI",
112                                         "ACPI", "SMBIOS", "PCI",
113                                         "device-tree", "default" };
114
115 #define DEVICE_NAME "ipmi_si"
116
117 static struct platform_driver ipmi_driver;
118
119 /*
120  * Indexes into stats[] in smi_info below.
121  */
122 enum si_stat_indexes {
123         /*
124          * Number of times the driver requested a timer while an operation
125          * was in progress.
126          */
127         SI_STAT_short_timeouts = 0,
128
129         /*
130          * Number of times the driver requested a timer while nothing was in
131          * progress.
132          */
133         SI_STAT_long_timeouts,
134
135         /* Number of times the interface was idle while being polled. */
136         SI_STAT_idles,
137
138         /* Number of interrupts the driver handled. */
139         SI_STAT_interrupts,
140
141         /* Number of time the driver got an ATTN from the hardware. */
142         SI_STAT_attentions,
143
144         /* Number of times the driver requested flags from the hardware. */
145         SI_STAT_flag_fetches,
146
147         /* Number of times the hardware didn't follow the state machine. */
148         SI_STAT_hosed_count,
149
150         /* Number of completed messages. */
151         SI_STAT_complete_transactions,
152
153         /* Number of IPMI events received from the hardware. */
154         SI_STAT_events,
155
156         /* Number of watchdog pretimeouts. */
157         SI_STAT_watchdog_pretimeouts,
158
159         /* Number of asyncronous messages received. */
160         SI_STAT_incoming_messages,
161
162
163         /* This *must* remain last, add new values above this. */
164         SI_NUM_STATS
165 };
166
167 struct smi_info {
168         int                    intf_num;
169         ipmi_smi_t             intf;
170         struct si_sm_data      *si_sm;
171         struct si_sm_handlers  *handlers;
172         enum si_type           si_type;
173         spinlock_t             si_lock;
174         spinlock_t             msg_lock;
175         struct list_head       xmit_msgs;
176         struct list_head       hp_xmit_msgs;
177         struct ipmi_smi_msg    *curr_msg;
178         enum si_intf_state     si_state;
179
180         /*
181          * Used to handle the various types of I/O that can occur with
182          * IPMI
183          */
184         struct si_sm_io io;
185         int (*io_setup)(struct smi_info *info);
186         void (*io_cleanup)(struct smi_info *info);
187         int (*irq_setup)(struct smi_info *info);
188         void (*irq_cleanup)(struct smi_info *info);
189         unsigned int io_size;
190         enum ipmi_addr_src addr_source; /* ACPI, PCI, SMBIOS, hardcode, etc. */
191         void (*addr_source_cleanup)(struct smi_info *info);
192         void *addr_source_data;
193
194         /*
195          * Per-OEM handler, called from handle_flags().  Returns 1
196          * when handle_flags() needs to be re-run or 0 indicating it
197          * set si_state itself.
198          */
199         int (*oem_data_avail_handler)(struct smi_info *smi_info);
200
201         /*
202          * Flags from the last GET_MSG_FLAGS command, used when an ATTN
203          * is set to hold the flags until we are done handling everything
204          * from the flags.
205          */
206 #define RECEIVE_MSG_AVAIL       0x01
207 #define EVENT_MSG_BUFFER_FULL   0x02
208 #define WDT_PRE_TIMEOUT_INT     0x08
209 #define OEM0_DATA_AVAIL     0x20
210 #define OEM1_DATA_AVAIL     0x40
211 #define OEM2_DATA_AVAIL     0x80
212 #define OEM_DATA_AVAIL      (OEM0_DATA_AVAIL | \
213                              OEM1_DATA_AVAIL | \
214                              OEM2_DATA_AVAIL)
215         unsigned char       msg_flags;
216
217         /* Does the BMC have an event buffer? */
218         char                has_event_buffer;
219
220         /*
221          * If set to true, this will request events the next time the
222          * state machine is idle.
223          */
224         atomic_t            req_events;
225
226         /*
227          * If true, run the state machine to completion on every send
228          * call.  Generally used after a panic to make sure stuff goes
229          * out.
230          */
231         int                 run_to_completion;
232
233         /* The I/O port of an SI interface. */
234         int                 port;
235
236         /*
237          * The space between start addresses of the two ports.  For
238          * instance, if the first port is 0xca2 and the spacing is 4, then
239          * the second port is 0xca6.
240          */
241         unsigned int        spacing;
242
243         /* zero if no irq; */
244         int                 irq;
245
246         /* The timer for this si. */
247         struct timer_list   si_timer;
248
249         /* The time (in jiffies) the last timeout occurred at. */
250         unsigned long       last_timeout_jiffies;
251
252         /* Used to gracefully stop the timer without race conditions. */
253         atomic_t            stop_operation;
254
255         /*
256          * The driver will disable interrupts when it gets into a
257          * situation where it cannot handle messages due to lack of
258          * memory.  Once that situation clears up, it will re-enable
259          * interrupts.
260          */
261         int interrupt_disabled;
262
263         /* From the get device id response... */
264         struct ipmi_device_id device_id;
265
266         /* Driver model stuff. */
267         struct device *dev;
268         struct platform_device *pdev;
269
270         /*
271          * True if we allocated the device, false if it came from
272          * someplace else (like PCI).
273          */
274         int dev_registered;
275
276         /* Slave address, could be reported from DMI. */
277         unsigned char slave_addr;
278
279         /* Counters and things for the proc filesystem. */
280         atomic_t stats[SI_NUM_STATS];
281
282         struct task_struct *thread;
283
284         struct list_head link;
285         union ipmi_smi_info_union addr_info;
286 };
287
288 #define smi_inc_stat(smi, stat) \
289         atomic_inc(&(smi)->stats[SI_STAT_ ## stat])
290 #define smi_get_stat(smi, stat) \
291         ((unsigned int) atomic_read(&(smi)->stats[SI_STAT_ ## stat]))
292
293 #define SI_MAX_PARMS 4
294
295 static int force_kipmid[SI_MAX_PARMS];
296 static int num_force_kipmid;
297 #ifdef CONFIG_PCI
298 static int pci_registered;
299 #endif
300 #ifdef CONFIG_ACPI
301 static int pnp_registered;
302 #endif
303
304 static unsigned int kipmid_max_busy_us[SI_MAX_PARMS];
305 static int num_max_busy_us;
306
307 static int unload_when_empty = 1;
308
309 static int add_smi(struct smi_info *smi);
310 static int try_smi_init(struct smi_info *smi);
311 static void cleanup_one_si(struct smi_info *to_clean);
312 static void cleanup_ipmi_si(void);
313
314 static ATOMIC_NOTIFIER_HEAD(xaction_notifier_list);
315 static int register_xaction_notifier(struct notifier_block *nb)
316 {
317         return atomic_notifier_chain_register(&xaction_notifier_list, nb);
318 }
319
320 static void deliver_recv_msg(struct smi_info *smi_info,
321                              struct ipmi_smi_msg *msg)
322 {
323         /* Deliver the message to the upper layer. */
324         ipmi_smi_msg_received(smi_info->intf, msg);
325 }
326
327 static void return_hosed_msg(struct smi_info *smi_info, int cCode)
328 {
329         struct ipmi_smi_msg *msg = smi_info->curr_msg;
330
331         if (cCode < 0 || cCode > IPMI_ERR_UNSPECIFIED)
332                 cCode = IPMI_ERR_UNSPECIFIED;
333         /* else use it as is */
334
335         /* Make it a response */
336         msg->rsp[0] = msg->data[0] | 4;
337         msg->rsp[1] = msg->data[1];
338         msg->rsp[2] = cCode;
339         msg->rsp_size = 3;
340
341         smi_info->curr_msg = NULL;
342         deliver_recv_msg(smi_info, msg);
343 }
344
345 static enum si_sm_result start_next_msg(struct smi_info *smi_info)
346 {
347         int              rv;
348         struct list_head *entry = NULL;
349 #ifdef DEBUG_TIMING
350         struct timeval t;
351 #endif
352
353         /*
354          * No need to save flags, we aleady have interrupts off and we
355          * already hold the SMI lock.
356          */
357         if (!smi_info->run_to_completion)
358                 spin_lock(&(smi_info->msg_lock));
359
360         /* Pick the high priority queue first. */
361         if (!list_empty(&(smi_info->hp_xmit_msgs))) {
362                 entry = smi_info->hp_xmit_msgs.next;
363         } else if (!list_empty(&(smi_info->xmit_msgs))) {
364                 entry = smi_info->xmit_msgs.next;
365         }
366
367         if (!entry) {
368                 smi_info->curr_msg = NULL;
369                 rv = SI_SM_IDLE;
370         } else {
371                 int err;
372
373                 list_del(entry);
374                 smi_info->curr_msg = list_entry(entry,
375                                                 struct ipmi_smi_msg,
376                                                 link);
377 #ifdef DEBUG_TIMING
378                 do_gettimeofday(&t);
379                 printk(KERN_DEBUG "**Start2: %d.%9.9d\n", t.tv_sec, t.tv_usec);
380 #endif
381                 err = atomic_notifier_call_chain(&xaction_notifier_list,
382                                 0, smi_info);
383                 if (err & NOTIFY_STOP_MASK) {
384                         rv = SI_SM_CALL_WITHOUT_DELAY;
385                         goto out;
386                 }
387                 err = smi_info->handlers->start_transaction(
388                         smi_info->si_sm,
389                         smi_info->curr_msg->data,
390                         smi_info->curr_msg->data_size);
391                 if (err)
392                         return_hosed_msg(smi_info, err);
393
394                 rv = SI_SM_CALL_WITHOUT_DELAY;
395         }
396  out:
397         if (!smi_info->run_to_completion)
398                 spin_unlock(&(smi_info->msg_lock));
399
400         return rv;
401 }
402
403 static void start_enable_irq(struct smi_info *smi_info)
404 {
405         unsigned char msg[2];
406
407         /*
408          * If we are enabling interrupts, we have to tell the
409          * BMC to use them.
410          */
411         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
412         msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
413
414         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
415         smi_info->si_state = SI_ENABLE_INTERRUPTS1;
416 }
417
418 static void start_disable_irq(struct smi_info *smi_info)
419 {
420         unsigned char msg[2];
421
422         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
423         msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
424
425         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
426         smi_info->si_state = SI_DISABLE_INTERRUPTS1;
427 }
428
429 static void start_clear_flags(struct smi_info *smi_info)
430 {
431         unsigned char msg[3];
432
433         /* Make sure the watchdog pre-timeout flag is not set at startup. */
434         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
435         msg[1] = IPMI_CLEAR_MSG_FLAGS_CMD;
436         msg[2] = WDT_PRE_TIMEOUT_INT;
437
438         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 3);
439         smi_info->si_state = SI_CLEARING_FLAGS;
440 }
441
442 /*
443  * When we have a situtaion where we run out of memory and cannot
444  * allocate messages, we just leave them in the BMC and run the system
445  * polled until we can allocate some memory.  Once we have some
446  * memory, we will re-enable the interrupt.
447  */
448 static inline void disable_si_irq(struct smi_info *smi_info)
449 {
450         if ((smi_info->irq) && (!smi_info->interrupt_disabled)) {
451                 start_disable_irq(smi_info);
452                 smi_info->interrupt_disabled = 1;
453                 if (!atomic_read(&smi_info->stop_operation))
454                         mod_timer(&smi_info->si_timer,
455                                   jiffies + SI_TIMEOUT_JIFFIES);
456         }
457 }
458
459 static inline void enable_si_irq(struct smi_info *smi_info)
460 {
461         if ((smi_info->irq) && (smi_info->interrupt_disabled)) {
462                 start_enable_irq(smi_info);
463                 smi_info->interrupt_disabled = 0;
464         }
465 }
466
467 static void handle_flags(struct smi_info *smi_info)
468 {
469  retry:
470         if (smi_info->msg_flags & WDT_PRE_TIMEOUT_INT) {
471                 /* Watchdog pre-timeout */
472                 smi_inc_stat(smi_info, watchdog_pretimeouts);
473
474                 start_clear_flags(smi_info);
475                 smi_info->msg_flags &= ~WDT_PRE_TIMEOUT_INT;
476                 ipmi_smi_watchdog_pretimeout(smi_info->intf);
477         } else if (smi_info->msg_flags & RECEIVE_MSG_AVAIL) {
478                 /* Messages available. */
479                 smi_info->curr_msg = ipmi_alloc_smi_msg();
480                 if (!smi_info->curr_msg) {
481                         disable_si_irq(smi_info);
482                         smi_info->si_state = SI_NORMAL;
483                         return;
484                 }
485                 enable_si_irq(smi_info);
486
487                 smi_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
488                 smi_info->curr_msg->data[1] = IPMI_GET_MSG_CMD;
489                 smi_info->curr_msg->data_size = 2;
490
491                 smi_info->handlers->start_transaction(
492                         smi_info->si_sm,
493                         smi_info->curr_msg->data,
494                         smi_info->curr_msg->data_size);
495                 smi_info->si_state = SI_GETTING_MESSAGES;
496         } else if (smi_info->msg_flags & EVENT_MSG_BUFFER_FULL) {
497                 /* Events available. */
498                 smi_info->curr_msg = ipmi_alloc_smi_msg();
499                 if (!smi_info->curr_msg) {
500                         disable_si_irq(smi_info);
501                         smi_info->si_state = SI_NORMAL;
502                         return;
503                 }
504                 enable_si_irq(smi_info);
505
506                 smi_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
507                 smi_info->curr_msg->data[1] = IPMI_READ_EVENT_MSG_BUFFER_CMD;
508                 smi_info->curr_msg->data_size = 2;
509
510                 smi_info->handlers->start_transaction(
511                         smi_info->si_sm,
512                         smi_info->curr_msg->data,
513                         smi_info->curr_msg->data_size);
514                 smi_info->si_state = SI_GETTING_EVENTS;
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 static void handle_transaction_done(struct smi_info *smi_info)
524 {
525         struct ipmi_smi_msg *msg;
526 #ifdef DEBUG_TIMING
527         struct timeval t;
528
529         do_gettimeofday(&t);
530         printk(KERN_DEBUG "**Done: %d.%9.9d\n", t.tv_sec, t.tv_usec);
531 #endif
532         switch (smi_info->si_state) {
533         case SI_NORMAL:
534                 if (!smi_info->curr_msg)
535                         break;
536
537                 smi_info->curr_msg->rsp_size
538                         = smi_info->handlers->get_result(
539                                 smi_info->si_sm,
540                                 smi_info->curr_msg->rsp,
541                                 IPMI_MAX_MSG_LENGTH);
542
543                 /*
544                  * Do this here becase deliver_recv_msg() releases the
545                  * lock, and a new message can be put in during the
546                  * time the lock is released.
547                  */
548                 msg = smi_info->curr_msg;
549                 smi_info->curr_msg = NULL;
550                 deliver_recv_msg(smi_info, msg);
551                 break;
552
553         case SI_GETTING_FLAGS:
554         {
555                 unsigned char msg[4];
556                 unsigned int  len;
557
558                 /* We got the flags from the SMI, now handle them. */
559                 len = smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
560                 if (msg[2] != 0) {
561                         /* Error fetching flags, just give up for now. */
562                         smi_info->si_state = SI_NORMAL;
563                 } else if (len < 4) {
564                         /*
565                          * Hmm, no flags.  That's technically illegal, but
566                          * don't use uninitialized data.
567                          */
568                         smi_info->si_state = SI_NORMAL;
569                 } else {
570                         smi_info->msg_flags = msg[3];
571                         handle_flags(smi_info);
572                 }
573                 break;
574         }
575
576         case SI_CLEARING_FLAGS:
577         case SI_CLEARING_FLAGS_THEN_SET_IRQ:
578         {
579                 unsigned char msg[3];
580
581                 /* We cleared the flags. */
582                 smi_info->handlers->get_result(smi_info->si_sm, msg, 3);
583                 if (msg[2] != 0) {
584                         /* Error clearing flags */
585                         dev_warn(smi_info->dev,
586                                  "Error clearing flags: %2.2x\n", msg[2]);
587                 }
588                 if (smi_info->si_state == SI_CLEARING_FLAGS_THEN_SET_IRQ)
589                         start_enable_irq(smi_info);
590                 else
591                         smi_info->si_state = SI_NORMAL;
592                 break;
593         }
594
595         case SI_GETTING_EVENTS:
596         {
597                 smi_info->curr_msg->rsp_size
598                         = smi_info->handlers->get_result(
599                                 smi_info->si_sm,
600                                 smi_info->curr_msg->rsp,
601                                 IPMI_MAX_MSG_LENGTH);
602
603                 /*
604                  * Do this here becase deliver_recv_msg() releases the
605                  * lock, and a new message can be put in during the
606                  * time the lock is released.
607                  */
608                 msg = smi_info->curr_msg;
609                 smi_info->curr_msg = NULL;
610                 if (msg->rsp[2] != 0) {
611                         /* Error getting event, probably done. */
612                         msg->done(msg);
613
614                         /* Take off the event flag. */
615                         smi_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
616                         handle_flags(smi_info);
617                 } else {
618                         smi_inc_stat(smi_info, events);
619
620                         /*
621                          * Do this before we deliver the message
622                          * because delivering the message releases the
623                          * lock and something else can mess with the
624                          * state.
625                          */
626                         handle_flags(smi_info);
627
628                         deliver_recv_msg(smi_info, msg);
629                 }
630                 break;
631         }
632
633         case SI_GETTING_MESSAGES:
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                 if (msg->rsp[2] != 0) {
649                         /* Error getting event, probably done. */
650                         msg->done(msg);
651
652                         /* Take off the msg flag. */
653                         smi_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
654                         handle_flags(smi_info);
655                 } else {
656                         smi_inc_stat(smi_info, incoming_messages);
657
658                         /*
659                          * Do this before we deliver the message
660                          * because delivering the message releases the
661                          * lock and something else can mess with the
662                          * state.
663                          */
664                         handle_flags(smi_info);
665
666                         deliver_recv_msg(smi_info, msg);
667                 }
668                 break;
669         }
670
671         case SI_ENABLE_INTERRUPTS1:
672         {
673                 unsigned char msg[4];
674
675                 /* We got the flags from the SMI, now handle them. */
676                 smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
677                 if (msg[2] != 0) {
678                         dev_warn(smi_info->dev, "Could not enable interrupts"
679                                  ", failed get, using polled mode.\n");
680                         smi_info->si_state = SI_NORMAL;
681                 } else {
682                         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
683                         msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
684                         msg[2] = (msg[3] |
685                                   IPMI_BMC_RCV_MSG_INTR |
686                                   IPMI_BMC_EVT_MSG_INTR);
687                         smi_info->handlers->start_transaction(
688                                 smi_info->si_sm, msg, 3);
689                         smi_info->si_state = SI_ENABLE_INTERRUPTS2;
690                 }
691                 break;
692         }
693
694         case SI_ENABLE_INTERRUPTS2:
695         {
696                 unsigned char msg[4];
697
698                 /* We got the flags from the SMI, now handle them. */
699                 smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
700                 if (msg[2] != 0)
701                         dev_warn(smi_info->dev, "Could not enable interrupts"
702                                  ", failed set, using polled mode.\n");
703                 else
704                         smi_info->interrupt_disabled = 0;
705                 smi_info->si_state = SI_NORMAL;
706                 break;
707         }
708
709         case SI_DISABLE_INTERRUPTS1:
710         {
711                 unsigned char msg[4];
712
713                 /* We got the flags from the SMI, now handle them. */
714                 smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
715                 if (msg[2] != 0) {
716                         dev_warn(smi_info->dev, "Could not disable interrupts"
717                                  ", failed get.\n");
718                         smi_info->si_state = SI_NORMAL;
719                 } else {
720                         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
721                         msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
722                         msg[2] = (msg[3] &
723                                   ~(IPMI_BMC_RCV_MSG_INTR |
724                                     IPMI_BMC_EVT_MSG_INTR));
725                         smi_info->handlers->start_transaction(
726                                 smi_info->si_sm, msg, 3);
727                         smi_info->si_state = SI_DISABLE_INTERRUPTS2;
728                 }
729                 break;
730         }
731
732         case SI_DISABLE_INTERRUPTS2:
733         {
734                 unsigned char msg[4];
735
736                 /* We got the flags from the SMI, now handle them. */
737                 smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
738                 if (msg[2] != 0) {
739                         dev_warn(smi_info->dev, "Could not disable interrupts"
740                                  ", failed set.\n");
741                 }
742                 smi_info->si_state = SI_NORMAL;
743                 break;
744         }
745         }
746 }
747
748 /*
749  * Called on timeouts and events.  Timeouts should pass the elapsed
750  * time, interrupts should pass in zero.  Must be called with
751  * si_lock held and interrupts disabled.
752  */
753 static enum si_sm_result smi_event_handler(struct smi_info *smi_info,
754                                            int time)
755 {
756         enum si_sm_result si_sm_result;
757
758  restart:
759         /*
760          * There used to be a loop here that waited a little while
761          * (around 25us) before giving up.  That turned out to be
762          * pointless, the minimum delays I was seeing were in the 300us
763          * range, which is far too long to wait in an interrupt.  So
764          * we just run until the state machine tells us something
765          * happened or it needs a delay.
766          */
767         si_sm_result = smi_info->handlers->event(smi_info->si_sm, time);
768         time = 0;
769         while (si_sm_result == SI_SM_CALL_WITHOUT_DELAY)
770                 si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
771
772         if (si_sm_result == SI_SM_TRANSACTION_COMPLETE) {
773                 smi_inc_stat(smi_info, complete_transactions);
774
775                 handle_transaction_done(smi_info);
776                 si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
777         } else if (si_sm_result == SI_SM_HOSED) {
778                 smi_inc_stat(smi_info, hosed_count);
779
780                 /*
781                  * Do the before return_hosed_msg, because that
782                  * releases the lock.
783                  */
784                 smi_info->si_state = SI_NORMAL;
785                 if (smi_info->curr_msg != NULL) {
786                         /*
787                          * If we were handling a user message, format
788                          * a response to send to the upper layer to
789                          * tell it about the error.
790                          */
791                         return_hosed_msg(smi_info, IPMI_ERR_UNSPECIFIED);
792                 }
793                 si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
794         }
795
796         /*
797          * We prefer handling attn over new messages.  But don't do
798          * this if there is not yet an upper layer to handle anything.
799          */
800         if (likely(smi_info->intf) && si_sm_result == SI_SM_ATTN) {
801                 unsigned char msg[2];
802
803                 smi_inc_stat(smi_info, attentions);
804
805                 /*
806                  * Got a attn, send down a get message flags to see
807                  * what's causing it.  It would be better to handle
808                  * this in the upper layer, but due to the way
809                  * interrupts work with the SMI, that's not really
810                  * possible.
811                  */
812                 msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
813                 msg[1] = IPMI_GET_MSG_FLAGS_CMD;
814
815                 smi_info->handlers->start_transaction(
816                         smi_info->si_sm, msg, 2);
817                 smi_info->si_state = SI_GETTING_FLAGS;
818                 goto restart;
819         }
820
821         /* If we are currently idle, try to start the next message. */
822         if (si_sm_result == SI_SM_IDLE) {
823                 smi_inc_stat(smi_info, idles);
824
825                 si_sm_result = start_next_msg(smi_info);
826                 if (si_sm_result != SI_SM_IDLE)
827                         goto restart;
828         }
829
830         if ((si_sm_result == SI_SM_IDLE)
831             && (atomic_read(&smi_info->req_events))) {
832                 /*
833                  * We are idle and the upper layer requested that I fetch
834                  * events, so do so.
835                  */
836                 atomic_set(&smi_info->req_events, 0);
837
838                 smi_info->curr_msg = ipmi_alloc_smi_msg();
839                 if (!smi_info->curr_msg)
840                         goto out;
841
842                 smi_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
843                 smi_info->curr_msg->data[1] = IPMI_READ_EVENT_MSG_BUFFER_CMD;
844                 smi_info->curr_msg->data_size = 2;
845
846                 smi_info->handlers->start_transaction(
847                         smi_info->si_sm,
848                         smi_info->curr_msg->data,
849                         smi_info->curr_msg->data_size);
850                 smi_info->si_state = SI_GETTING_EVENTS;
851                 goto restart;
852         }
853  out:
854         return si_sm_result;
855 }
856
857 static void sender(void                *send_info,
858                    struct ipmi_smi_msg *msg,
859                    int                 priority)
860 {
861         struct smi_info   *smi_info = send_info;
862         enum si_sm_result result;
863         unsigned long     flags;
864 #ifdef DEBUG_TIMING
865         struct timeval    t;
866 #endif
867
868         if (atomic_read(&smi_info->stop_operation)) {
869                 msg->rsp[0] = msg->data[0] | 4;
870                 msg->rsp[1] = msg->data[1];
871                 msg->rsp[2] = IPMI_ERR_UNSPECIFIED;
872                 msg->rsp_size = 3;
873                 deliver_recv_msg(smi_info, msg);
874                 return;
875         }
876
877 #ifdef DEBUG_TIMING
878         do_gettimeofday(&t);
879         printk("**Enqueue: %d.%9.9d\n", t.tv_sec, t.tv_usec);
880 #endif
881
882         /*
883          * last_timeout_jiffies is updated here to avoid
884          * smi_timeout() handler passing very large time_diff
885          * value to smi_event_handler() that causes
886          * the send command to abort.
887          */
888         smi_info->last_timeout_jiffies = jiffies;
889
890         mod_timer(&smi_info->si_timer, jiffies + SI_TIMEOUT_JIFFIES);
891
892         if (smi_info->thread)
893                 wake_up_process(smi_info->thread);
894
895         if (smi_info->run_to_completion) {
896                 /*
897                  * If we are running to completion, then throw it in
898                  * the list and run transactions until everything is
899                  * clear.  Priority doesn't matter here.
900                  */
901
902                 /*
903                  * Run to completion means we are single-threaded, no
904                  * need for locks.
905                  */
906                 list_add_tail(&(msg->link), &(smi_info->xmit_msgs));
907
908                 result = smi_event_handler(smi_info, 0);
909                 while (result != SI_SM_IDLE) {
910                         udelay(SI_SHORT_TIMEOUT_USEC);
911                         result = smi_event_handler(smi_info,
912                                                    SI_SHORT_TIMEOUT_USEC);
913                 }
914                 return;
915         }
916
917         spin_lock_irqsave(&smi_info->msg_lock, flags);
918         if (priority > 0)
919                 list_add_tail(&msg->link, &smi_info->hp_xmit_msgs);
920         else
921                 list_add_tail(&msg->link, &smi_info->xmit_msgs);
922         spin_unlock_irqrestore(&smi_info->msg_lock, flags);
923
924         spin_lock_irqsave(&smi_info->si_lock, flags);
925         if (smi_info->si_state == SI_NORMAL && smi_info->curr_msg == NULL) {
926                 start_next_msg(smi_info);
927                 smi_event_handler(smi_info, 0);
928         }
929         spin_unlock_irqrestore(&smi_info->si_lock, flags);
930 }
931
932 static void set_run_to_completion(void *send_info, int i_run_to_completion)
933 {
934         struct smi_info   *smi_info = send_info;
935         enum si_sm_result result;
936
937         smi_info->run_to_completion = i_run_to_completion;
938         if (i_run_to_completion) {
939                 result = smi_event_handler(smi_info, 0);
940                 while (result != SI_SM_IDLE) {
941                         udelay(SI_SHORT_TIMEOUT_USEC);
942                         result = smi_event_handler(smi_info,
943                                                    SI_SHORT_TIMEOUT_USEC);
944                 }
945         }
946 }
947
948 /*
949  * Use -1 in the nsec value of the busy waiting timespec to tell that
950  * we are spinning in kipmid looking for something and not delaying
951  * between checks
952  */
953 static inline void ipmi_si_set_not_busy(struct timespec *ts)
954 {
955         ts->tv_nsec = -1;
956 }
957 static inline int ipmi_si_is_busy(struct timespec *ts)
958 {
959         return ts->tv_nsec != -1;
960 }
961
962 static int ipmi_thread_busy_wait(enum si_sm_result smi_result,
963                                  const struct smi_info *smi_info,
964                                  struct timespec *busy_until)
965 {
966         unsigned int max_busy_us = 0;
967
968         if (smi_info->intf_num < num_max_busy_us)
969                 max_busy_us = kipmid_max_busy_us[smi_info->intf_num];
970         if (max_busy_us == 0 || smi_result != SI_SM_CALL_WITH_DELAY)
971                 ipmi_si_set_not_busy(busy_until);
972         else if (!ipmi_si_is_busy(busy_until)) {
973                 getnstimeofday(busy_until);
974                 timespec_add_ns(busy_until, max_busy_us*NSEC_PER_USEC);
975         } else {
976                 struct timespec now;
977                 getnstimeofday(&now);
978                 if (unlikely(timespec_compare(&now, busy_until) > 0)) {
979                         ipmi_si_set_not_busy(busy_until);
980                         return 0;
981                 }
982         }
983         return 1;
984 }
985
986
987 /*
988  * A busy-waiting loop for speeding up IPMI operation.
989  *
990  * Lousy hardware makes this hard.  This is only enabled for systems
991  * that are not BT and do not have interrupts.  It starts spinning
992  * when an operation is complete or until max_busy tells it to stop
993  * (if that is enabled).  See the paragraph on kimid_max_busy_us in
994  * Documentation/IPMI.txt for details.
995  */
996 static int ipmi_thread(void *data)
997 {
998         struct smi_info *smi_info = data;
999         unsigned long flags;
1000         enum si_sm_result smi_result;
1001         struct timespec busy_until;
1002
1003         ipmi_si_set_not_busy(&busy_until);
1004         set_user_nice(current, 19);
1005         while (!kthread_should_stop()) {
1006                 int busy_wait;
1007
1008                 spin_lock_irqsave(&(smi_info->si_lock), flags);
1009                 smi_result = smi_event_handler(smi_info, 0);
1010                 spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1011                 busy_wait = ipmi_thread_busy_wait(smi_result, smi_info,
1012                                                   &busy_until);
1013                 if (smi_result == SI_SM_CALL_WITHOUT_DELAY)
1014                         ; /* do nothing */
1015                 else if (smi_result == SI_SM_CALL_WITH_DELAY && busy_wait)
1016                         schedule();
1017                 else if (smi_result == SI_SM_IDLE)
1018                         schedule_timeout_interruptible(100);
1019                 else
1020                         schedule_timeout_interruptible(1);
1021         }
1022         return 0;
1023 }
1024
1025
1026 static void poll(void *send_info)
1027 {
1028         struct smi_info *smi_info = send_info;
1029         unsigned long flags;
1030
1031         /*
1032          * Make sure there is some delay in the poll loop so we can
1033          * drive time forward and timeout things.
1034          */
1035         udelay(10);
1036         spin_lock_irqsave(&smi_info->si_lock, flags);
1037         smi_event_handler(smi_info, 10);
1038         spin_unlock_irqrestore(&smi_info->si_lock, flags);
1039 }
1040
1041 static void request_events(void *send_info)
1042 {
1043         struct smi_info *smi_info = send_info;
1044
1045         if (atomic_read(&smi_info->stop_operation) ||
1046                                 !smi_info->has_event_buffer)
1047                 return;
1048
1049         atomic_set(&smi_info->req_events, 1);
1050 }
1051
1052 static int initialized;
1053
1054 static void smi_timeout(unsigned long data)
1055 {
1056         struct smi_info   *smi_info = (struct smi_info *) data;
1057         enum si_sm_result smi_result;
1058         unsigned long     flags;
1059         unsigned long     jiffies_now;
1060         long              time_diff;
1061         long              timeout;
1062 #ifdef DEBUG_TIMING
1063         struct timeval    t;
1064 #endif
1065
1066         spin_lock_irqsave(&(smi_info->si_lock), flags);
1067 #ifdef DEBUG_TIMING
1068         do_gettimeofday(&t);
1069         printk(KERN_DEBUG "**Timer: %d.%9.9d\n", t.tv_sec, t.tv_usec);
1070 #endif
1071         jiffies_now = jiffies;
1072         time_diff = (((long)jiffies_now - (long)smi_info->last_timeout_jiffies)
1073                      * SI_USEC_PER_JIFFY);
1074         smi_result = smi_event_handler(smi_info, time_diff);
1075
1076         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1077
1078         smi_info->last_timeout_jiffies = jiffies_now;
1079
1080         if ((smi_info->irq) && (!smi_info->interrupt_disabled)) {
1081                 /* Running with interrupts, only do long timeouts. */
1082                 timeout = jiffies + SI_TIMEOUT_JIFFIES;
1083                 smi_inc_stat(smi_info, long_timeouts);
1084                 goto do_mod_timer;
1085         }
1086
1087         /*
1088          * If the state machine asks for a short delay, then shorten
1089          * the timer timeout.
1090          */
1091         if (smi_result == SI_SM_CALL_WITH_DELAY) {
1092                 smi_inc_stat(smi_info, short_timeouts);
1093                 timeout = jiffies + 1;
1094         } else {
1095                 smi_inc_stat(smi_info, long_timeouts);
1096                 timeout = jiffies + SI_TIMEOUT_JIFFIES;
1097         }
1098
1099  do_mod_timer:
1100         if (smi_result != SI_SM_IDLE)
1101                 mod_timer(&(smi_info->si_timer), timeout);
1102 }
1103
1104 static irqreturn_t si_irq_handler(int irq, void *data)
1105 {
1106         struct smi_info *smi_info = data;
1107         unsigned long   flags;
1108 #ifdef DEBUG_TIMING
1109         struct timeval  t;
1110 #endif
1111
1112         spin_lock_irqsave(&(smi_info->si_lock), flags);
1113
1114         smi_inc_stat(smi_info, interrupts);
1115
1116 #ifdef DEBUG_TIMING
1117         do_gettimeofday(&t);
1118         printk(KERN_DEBUG "**Interrupt: %d.%9.9d\n", t.tv_sec, t.tv_usec);
1119 #endif
1120         smi_event_handler(smi_info, 0);
1121         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1122         return IRQ_HANDLED;
1123 }
1124
1125 static irqreturn_t si_bt_irq_handler(int irq, void *data)
1126 {
1127         struct smi_info *smi_info = data;
1128         /* We need to clear the IRQ flag for the BT interface. */
1129         smi_info->io.outputb(&smi_info->io, IPMI_BT_INTMASK_REG,
1130                              IPMI_BT_INTMASK_CLEAR_IRQ_BIT
1131                              | IPMI_BT_INTMASK_ENABLE_IRQ_BIT);
1132         return si_irq_handler(irq, data);
1133 }
1134
1135 static int smi_start_processing(void       *send_info,
1136                                 ipmi_smi_t intf)
1137 {
1138         struct smi_info *new_smi = send_info;
1139         int             enable = 0;
1140
1141         new_smi->intf = intf;
1142
1143         /* Try to claim any interrupts. */
1144         if (new_smi->irq_setup)
1145                 new_smi->irq_setup(new_smi);
1146
1147         /* Set up the timer that drives the interface. */
1148         setup_timer(&new_smi->si_timer, smi_timeout, (long)new_smi);
1149         new_smi->last_timeout_jiffies = jiffies;
1150         mod_timer(&new_smi->si_timer, jiffies + SI_TIMEOUT_JIFFIES);
1151
1152         /*
1153          * Check if the user forcefully enabled the daemon.
1154          */
1155         if (new_smi->intf_num < num_force_kipmid)
1156                 enable = force_kipmid[new_smi->intf_num];
1157         /*
1158          * The BT interface is efficient enough to not need a thread,
1159          * and there is no need for a thread if we have interrupts.
1160          */
1161         else if ((new_smi->si_type != SI_BT) && (!new_smi->irq))
1162                 enable = 1;
1163
1164         if (enable) {
1165                 new_smi->thread = kthread_run(ipmi_thread, new_smi,
1166                                               "kipmi%d", new_smi->intf_num);
1167                 if (IS_ERR(new_smi->thread)) {
1168                         dev_notice(new_smi->dev, "Could not start"
1169                                    " kernel thread due to error %ld, only using"
1170                                    " timers to drive the interface\n",
1171                                    PTR_ERR(new_smi->thread));
1172                         new_smi->thread = NULL;
1173                 }
1174         }
1175
1176         return 0;
1177 }
1178
1179 static int get_smi_info(void *send_info, struct ipmi_smi_info *data)
1180 {
1181         struct smi_info *smi = send_info;
1182
1183         data->addr_src = smi->addr_source;
1184         data->dev = smi->dev;
1185         data->addr_info = smi->addr_info;
1186         get_device(smi->dev);
1187
1188         return 0;
1189 }
1190
1191 static void set_maintenance_mode(void *send_info, int enable)
1192 {
1193         struct smi_info   *smi_info = send_info;
1194
1195         if (!enable)
1196                 atomic_set(&smi_info->req_events, 0);
1197 }
1198
1199 static struct ipmi_smi_handlers handlers = {
1200         .owner                  = THIS_MODULE,
1201         .start_processing       = smi_start_processing,
1202         .get_smi_info           = get_smi_info,
1203         .sender                 = sender,
1204         .request_events         = request_events,
1205         .set_maintenance_mode   = set_maintenance_mode,
1206         .set_run_to_completion  = set_run_to_completion,
1207         .poll                   = poll,
1208 };
1209
1210 /*
1211  * There can be 4 IO ports passed in (with or without IRQs), 4 addresses,
1212  * a default IO port, and 1 ACPI/SPMI address.  That sets SI_MAX_DRIVERS.
1213  */
1214
1215 static LIST_HEAD(smi_infos);
1216 static DEFINE_MUTEX(smi_infos_lock);
1217 static int smi_num; /* Used to sequence the SMIs */
1218
1219 #define DEFAULT_REGSPACING      1
1220 #define DEFAULT_REGSIZE         1
1221
1222 static bool          si_trydefaults = 1;
1223 static char          *si_type[SI_MAX_PARMS];
1224 #define MAX_SI_TYPE_STR 30
1225 static char          si_type_str[MAX_SI_TYPE_STR];
1226 static unsigned long addrs[SI_MAX_PARMS];
1227 static unsigned int num_addrs;
1228 static unsigned int  ports[SI_MAX_PARMS];
1229 static unsigned int num_ports;
1230 static int           irqs[SI_MAX_PARMS];
1231 static unsigned int num_irqs;
1232 static int           regspacings[SI_MAX_PARMS];
1233 static unsigned int num_regspacings;
1234 static int           regsizes[SI_MAX_PARMS];
1235 static unsigned int num_regsizes;
1236 static int           regshifts[SI_MAX_PARMS];
1237 static unsigned int num_regshifts;
1238 static int slave_addrs[SI_MAX_PARMS]; /* Leaving 0 chooses the default value */
1239 static unsigned int num_slave_addrs;
1240
1241 #define IPMI_IO_ADDR_SPACE  0
1242 #define IPMI_MEM_ADDR_SPACE 1
1243 static char *addr_space_to_str[] = { "i/o", "mem" };
1244
1245 static int hotmod_handler(const char *val, struct kernel_param *kp);
1246
1247 module_param_call(hotmod, hotmod_handler, NULL, NULL, 0200);
1248 MODULE_PARM_DESC(hotmod, "Add and remove interfaces.  See"
1249                  " Documentation/IPMI.txt in the kernel sources for the"
1250                  " gory details.");
1251
1252 module_param_named(trydefaults, si_trydefaults, bool, 0);
1253 MODULE_PARM_DESC(trydefaults, "Setting this to 'false' will disable the"
1254                  " default scan of the KCS and SMIC interface at the standard"
1255                  " address");
1256 module_param_string(type, si_type_str, MAX_SI_TYPE_STR, 0);
1257 MODULE_PARM_DESC(type, "Defines the type of each interface, each"
1258                  " interface separated by commas.  The types are 'kcs',"
1259                  " 'smic', and 'bt'.  For example si_type=kcs,bt will set"
1260                  " the first interface to kcs and the second to bt");
1261 module_param_array(addrs, ulong, &num_addrs, 0);
1262 MODULE_PARM_DESC(addrs, "Sets the memory address of each interface, the"
1263                  " addresses separated by commas.  Only use if an interface"
1264                  " is in memory.  Otherwise, set it to zero or leave"
1265                  " it blank.");
1266 module_param_array(ports, uint, &num_ports, 0);
1267 MODULE_PARM_DESC(ports, "Sets the port address of each interface, the"
1268                  " addresses separated by commas.  Only use if an interface"
1269                  " is a port.  Otherwise, set it to zero or leave"
1270                  " it blank.");
1271 module_param_array(irqs, int, &num_irqs, 0);
1272 MODULE_PARM_DESC(irqs, "Sets the interrupt of each interface, the"
1273                  " addresses separated by commas.  Only use if an interface"
1274                  " has an interrupt.  Otherwise, set it to zero or leave"
1275                  " it blank.");
1276 module_param_array(regspacings, int, &num_regspacings, 0);
1277 MODULE_PARM_DESC(regspacings, "The number of bytes between the start address"
1278                  " and each successive register used by the interface.  For"
1279                  " instance, if the start address is 0xca2 and the spacing"
1280                  " is 2, then the second address is at 0xca4.  Defaults"
1281                  " to 1.");
1282 module_param_array(regsizes, int, &num_regsizes, 0);
1283 MODULE_PARM_DESC(regsizes, "The size of the specific IPMI register in bytes."
1284                  " This should generally be 1, 2, 4, or 8 for an 8-bit,"
1285                  " 16-bit, 32-bit, or 64-bit register.  Use this if you"
1286                  " the 8-bit IPMI register has to be read from a larger"
1287                  " register.");
1288 module_param_array(regshifts, int, &num_regshifts, 0);
1289 MODULE_PARM_DESC(regshifts, "The amount to shift the data read from the."
1290                  " IPMI register, in bits.  For instance, if the data"
1291                  " is read from a 32-bit word and the IPMI data is in"
1292                  " bit 8-15, then the shift would be 8");
1293 module_param_array(slave_addrs, int, &num_slave_addrs, 0);
1294 MODULE_PARM_DESC(slave_addrs, "Set the default IPMB slave address for"
1295                  " the controller.  Normally this is 0x20, but can be"
1296                  " overridden by this parm.  This is an array indexed"
1297                  " by interface number.");
1298 module_param_array(force_kipmid, int, &num_force_kipmid, 0);
1299 MODULE_PARM_DESC(force_kipmid, "Force the kipmi daemon to be enabled (1) or"
1300                  " disabled(0).  Normally the IPMI driver auto-detects"
1301                  " this, but the value may be overridden by this parm.");
1302 module_param(unload_when_empty, int, 0);
1303 MODULE_PARM_DESC(unload_when_empty, "Unload the module if no interfaces are"
1304                  " specified or found, default is 1.  Setting to 0"
1305                  " 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"
1309                  " sleeping. 0 (default) means to wait forever. Set to 100-500"
1310                  " if kipmid is using up a lot of CPU time.");
1311
1312
1313 static void std_irq_cleanup(struct smi_info *info)
1314 {
1315         if (info->si_type == SI_BT)
1316                 /* Disable the interrupt in the BT interface. */
1317                 info->io.outputb(&info->io, IPMI_BT_INTMASK_REG, 0);
1318         free_irq(info->irq, info);
1319 }
1320
1321 static int std_irq_setup(struct smi_info *info)
1322 {
1323         int rv;
1324
1325         if (!info->irq)
1326                 return 0;
1327
1328         if (info->si_type == SI_BT) {
1329                 rv = request_irq(info->irq,
1330                                  si_bt_irq_handler,
1331                                  IRQF_SHARED | IRQF_DISABLED,
1332                                  DEVICE_NAME,
1333                                  info);
1334                 if (!rv)
1335                         /* Enable the interrupt in the BT interface. */
1336                         info->io.outputb(&info->io, IPMI_BT_INTMASK_REG,
1337                                          IPMI_BT_INTMASK_ENABLE_IRQ_BIT);
1338         } else
1339                 rv = request_irq(info->irq,
1340                                  si_irq_handler,
1341                                  IRQF_SHARED | IRQF_DISABLED,
1342                                  DEVICE_NAME,
1343                                  info);
1344         if (rv) {
1345                 dev_warn(info->dev, "%s unable to claim interrupt %d,"
1346                          " running polled\n",
1347                          DEVICE_NAME, info->irq);
1348                 info->irq = 0;
1349         } else {
1350                 info->irq_cleanup = std_irq_cleanup;
1351                 dev_info(info->dev, "Using irq %d\n", info->irq);
1352         }
1353
1354         return rv;
1355 }
1356
1357 static unsigned char port_inb(struct si_sm_io *io, unsigned int offset)
1358 {
1359         unsigned int addr = io->addr_data;
1360
1361         return inb(addr + (offset * io->regspacing));
1362 }
1363
1364 static void port_outb(struct si_sm_io *io, unsigned int offset,
1365                       unsigned char b)
1366 {
1367         unsigned int addr = io->addr_data;
1368
1369         outb(b, addr + (offset * io->regspacing));
1370 }
1371
1372 static unsigned char port_inw(struct si_sm_io *io, unsigned int offset)
1373 {
1374         unsigned int addr = io->addr_data;
1375
1376         return (inw(addr + (offset * io->regspacing)) >> io->regshift) & 0xff;
1377 }
1378
1379 static void port_outw(struct si_sm_io *io, unsigned int offset,
1380                       unsigned char b)
1381 {
1382         unsigned int addr = io->addr_data;
1383
1384         outw(b << io->regshift, addr + (offset * io->regspacing));
1385 }
1386
1387 static unsigned char port_inl(struct si_sm_io *io, unsigned int offset)
1388 {
1389         unsigned int addr = io->addr_data;
1390
1391         return (inl(addr + (offset * io->regspacing)) >> io->regshift) & 0xff;
1392 }
1393
1394 static void port_outl(struct si_sm_io *io, unsigned int offset,
1395                       unsigned char b)
1396 {
1397         unsigned int addr = io->addr_data;
1398
1399         outl(b << io->regshift, addr+(offset * io->regspacing));
1400 }
1401
1402 static void port_cleanup(struct smi_info *info)
1403 {
1404         unsigned int addr = info->io.addr_data;
1405         int          idx;
1406
1407         if (addr) {
1408                 for (idx = 0; idx < info->io_size; idx++)
1409                         release_region(addr + idx * info->io.regspacing,
1410                                        info->io.regsize);
1411         }
1412 }
1413
1414 static int port_setup(struct smi_info *info)
1415 {
1416         unsigned int addr = info->io.addr_data;
1417         int          idx;
1418
1419         if (!addr)
1420                 return -ENODEV;
1421
1422         info->io_cleanup = port_cleanup;
1423
1424         /*
1425          * Figure out the actual inb/inw/inl/etc routine to use based
1426          * upon the register size.
1427          */
1428         switch (info->io.regsize) {
1429         case 1:
1430                 info->io.inputb = port_inb;
1431                 info->io.outputb = port_outb;
1432                 break;
1433         case 2:
1434                 info->io.inputb = port_inw;
1435                 info->io.outputb = port_outw;
1436                 break;
1437         case 4:
1438                 info->io.inputb = port_inl;
1439                 info->io.outputb = port_outl;
1440                 break;
1441         default:
1442                 dev_warn(info->dev, "Invalid register size: %d\n",
1443                          info->io.regsize);
1444                 return -EINVAL;
1445         }
1446
1447         /*
1448          * Some BIOSes reserve disjoint I/O regions in their ACPI
1449          * tables.  This causes problems when trying to register the
1450          * entire I/O region.  Therefore we must register each I/O
1451          * port separately.
1452          */
1453         for (idx = 0; idx < info->io_size; idx++) {
1454                 if (request_region(addr + idx * info->io.regspacing,
1455                                    info->io.regsize, DEVICE_NAME) == NULL) {
1456                         /* Undo allocations */
1457                         while (idx--) {
1458                                 release_region(addr + idx * info->io.regspacing,
1459                                                info->io.regsize);
1460                         }
1461                         return -EIO;
1462                 }
1463         }
1464         return 0;
1465 }
1466
1467 static unsigned char intf_mem_inb(struct si_sm_io *io, unsigned int offset)
1468 {
1469         return readb((io->addr)+(offset * io->regspacing));
1470 }
1471
1472 static void intf_mem_outb(struct si_sm_io *io, unsigned int offset,
1473                      unsigned char b)
1474 {
1475         writeb(b, (io->addr)+(offset * io->regspacing));
1476 }
1477
1478 static unsigned char intf_mem_inw(struct si_sm_io *io, unsigned int offset)
1479 {
1480         return (readw((io->addr)+(offset * io->regspacing)) >> io->regshift)
1481                 & 0xff;
1482 }
1483
1484 static void intf_mem_outw(struct si_sm_io *io, unsigned int offset,
1485                      unsigned char b)
1486 {
1487         writeb(b << io->regshift, (io->addr)+(offset * io->regspacing));
1488 }
1489
1490 static unsigned char intf_mem_inl(struct si_sm_io *io, unsigned int offset)
1491 {
1492         return (readl((io->addr)+(offset * io->regspacing)) >> io->regshift)
1493                 & 0xff;
1494 }
1495
1496 static void intf_mem_outl(struct si_sm_io *io, unsigned int offset,
1497                      unsigned char b)
1498 {
1499         writel(b << io->regshift, (io->addr)+(offset * io->regspacing));
1500 }
1501
1502 #ifdef readq
1503 static unsigned char mem_inq(struct si_sm_io *io, unsigned int offset)
1504 {
1505         return (readq((io->addr)+(offset * io->regspacing)) >> io->regshift)
1506                 & 0xff;
1507 }
1508
1509 static void mem_outq(struct si_sm_io *io, unsigned int offset,
1510                      unsigned char b)
1511 {
1512         writeq(b << io->regshift, (io->addr)+(offset * io->regspacing));
1513 }
1514 #endif
1515
1516 static void mem_cleanup(struct smi_info *info)
1517 {
1518         unsigned long addr = info->io.addr_data;
1519         int           mapsize;
1520
1521         if (info->io.addr) {
1522                 iounmap(info->io.addr);
1523
1524                 mapsize = ((info->io_size * info->io.regspacing)
1525                            - (info->io.regspacing - info->io.regsize));
1526
1527                 release_mem_region(addr, mapsize);
1528         }
1529 }
1530
1531 static int mem_setup(struct smi_info *info)
1532 {
1533         unsigned long addr = info->io.addr_data;
1534         int           mapsize;
1535
1536         if (!addr)
1537                 return -ENODEV;
1538
1539         info->io_cleanup = mem_cleanup;
1540
1541         /*
1542          * Figure out the actual readb/readw/readl/etc routine to use based
1543          * upon the register size.
1544          */
1545         switch (info->io.regsize) {
1546         case 1:
1547                 info->io.inputb = intf_mem_inb;
1548                 info->io.outputb = intf_mem_outb;
1549                 break;
1550         case 2:
1551                 info->io.inputb = intf_mem_inw;
1552                 info->io.outputb = intf_mem_outw;
1553                 break;
1554         case 4:
1555                 info->io.inputb = intf_mem_inl;
1556                 info->io.outputb = intf_mem_outl;
1557                 break;
1558 #ifdef readq
1559         case 8:
1560                 info->io.inputb = mem_inq;
1561                 info->io.outputb = mem_outq;
1562                 break;
1563 #endif
1564         default:
1565                 dev_warn(info->dev, "Invalid register size: %d\n",
1566                          info->io.regsize);
1567                 return -EINVAL;
1568         }
1569
1570         /*
1571          * Calculate the total amount of memory to claim.  This is an
1572          * unusual looking calculation, but it avoids claiming any
1573          * more memory than it has to.  It will claim everything
1574          * between the first address to the end of the last full
1575          * register.
1576          */
1577         mapsize = ((info->io_size * info->io.regspacing)
1578                    - (info->io.regspacing - info->io.regsize));
1579
1580         if (request_mem_region(addr, mapsize, DEVICE_NAME) == NULL)
1581                 return -EIO;
1582
1583         info->io.addr = ioremap(addr, mapsize);
1584         if (info->io.addr == NULL) {
1585                 release_mem_region(addr, mapsize);
1586                 return -EIO;
1587         }
1588         return 0;
1589 }
1590
1591 /*
1592  * Parms come in as <op1>[:op2[:op3...]].  ops are:
1593  *   add|remove,kcs|bt|smic,mem|i/o,<address>[,<opt1>[,<opt2>[,...]]]
1594  * Options are:
1595  *   rsp=<regspacing>
1596  *   rsi=<regsize>
1597  *   rsh=<regshift>
1598  *   irq=<irq>
1599  *   ipmb=<ipmb addr>
1600  */
1601 enum hotmod_op { HM_ADD, HM_REMOVE };
1602 struct hotmod_vals {
1603         char *name;
1604         int  val;
1605 };
1606 static struct hotmod_vals hotmod_ops[] = {
1607         { "add",        HM_ADD },
1608         { "remove",     HM_REMOVE },
1609         { NULL }
1610 };
1611 static struct hotmod_vals hotmod_si[] = {
1612         { "kcs",        SI_KCS },
1613         { "smic",       SI_SMIC },
1614         { "bt",         SI_BT },
1615         { NULL }
1616 };
1617 static struct hotmod_vals hotmod_as[] = {
1618         { "mem",        IPMI_MEM_ADDR_SPACE },
1619         { "i/o",        IPMI_IO_ADDR_SPACE },
1620         { NULL }
1621 };
1622
1623 static int parse_str(struct hotmod_vals *v, int *val, char *name, char **curr)
1624 {
1625         char *s;
1626         int  i;
1627
1628         s = strchr(*curr, ',');
1629         if (!s) {
1630                 printk(KERN_WARNING PFX "No hotmod %s given.\n", name);
1631                 return -EINVAL;
1632         }
1633         *s = '\0';
1634         s++;
1635         for (i = 0; hotmod_ops[i].name; i++) {
1636                 if (strcmp(*curr, v[i].name) == 0) {
1637                         *val = v[i].val;
1638                         *curr = s;
1639                         return 0;
1640                 }
1641         }
1642
1643         printk(KERN_WARNING PFX "Invalid hotmod %s '%s'\n", name, *curr);
1644         return -EINVAL;
1645 }
1646
1647 static int check_hotmod_int_op(const char *curr, const char *option,
1648                                const char *name, int *val)
1649 {
1650         char *n;
1651
1652         if (strcmp(curr, name) == 0) {
1653                 if (!option) {
1654                         printk(KERN_WARNING PFX
1655                                "No option given for '%s'\n",
1656                                curr);
1657                         return -EINVAL;
1658                 }
1659                 *val = simple_strtoul(option, &n, 0);
1660                 if ((*n != '\0') || (*option == '\0')) {
1661                         printk(KERN_WARNING PFX
1662                                "Bad option given for '%s'\n",
1663                                curr);
1664                         return -EINVAL;
1665                 }
1666                 return 1;
1667         }
1668         return 0;
1669 }
1670
1671 static struct smi_info *smi_info_alloc(void)
1672 {
1673         struct smi_info *info = kzalloc(sizeof(*info), GFP_KERNEL);
1674
1675         if (info) {
1676                 spin_lock_init(&info->si_lock);
1677                 spin_lock_init(&info->msg_lock);
1678         }
1679         return info;
1680 }
1681
1682 static int hotmod_handler(const char *val, struct kernel_param *kp)
1683 {
1684         char *str = kstrdup(val, GFP_KERNEL);
1685         int  rv;
1686         char *next, *curr, *s, *n, *o;
1687         enum hotmod_op op;
1688         enum si_type si_type;
1689         int  addr_space;
1690         unsigned long addr;
1691         int regspacing;
1692         int regsize;
1693         int regshift;
1694         int irq;
1695         int ipmb;
1696         int ival;
1697         int len;
1698         struct smi_info *info;
1699
1700         if (!str)
1701                 return -ENOMEM;
1702
1703         /* Kill any trailing spaces, as we can get a "\n" from echo. */
1704         len = strlen(str);
1705         ival = len - 1;
1706         while ((ival >= 0) && isspace(str[ival])) {
1707                 str[ival] = '\0';
1708                 ival--;
1709         }
1710
1711         for (curr = str; curr; curr = next) {
1712                 regspacing = 1;
1713                 regsize = 1;
1714                 regshift = 0;
1715                 irq = 0;
1716                 ipmb = 0; /* Choose the default if not specified */
1717
1718                 next = strchr(curr, ':');
1719                 if (next) {
1720                         *next = '\0';
1721                         next++;
1722                 }
1723
1724                 rv = parse_str(hotmod_ops, &ival, "operation", &curr);
1725                 if (rv)
1726                         break;
1727                 op = ival;
1728
1729                 rv = parse_str(hotmod_si, &ival, "interface type", &curr);
1730                 if (rv)
1731                         break;
1732                 si_type = ival;
1733
1734                 rv = parse_str(hotmod_as, &addr_space, "address space", &curr);
1735                 if (rv)
1736                         break;
1737
1738                 s = strchr(curr, ',');
1739                 if (s) {
1740                         *s = '\0';
1741                         s++;
1742                 }
1743                 addr = simple_strtoul(curr, &n, 0);
1744                 if ((*n != '\0') || (*curr == '\0')) {
1745                         printk(KERN_WARNING PFX "Invalid hotmod address"
1746                                " '%s'\n", curr);
1747                         break;
1748                 }
1749
1750                 while (s) {
1751                         curr = s;
1752                         s = strchr(curr, ',');
1753                         if (s) {
1754                                 *s = '\0';
1755                                 s++;
1756                         }
1757                         o = strchr(curr, '=');
1758                         if (o) {
1759                                 *o = '\0';
1760                                 o++;
1761                         }
1762                         rv = check_hotmod_int_op(curr, o, "rsp", &regspacing);
1763                         if (rv < 0)
1764                                 goto out;
1765                         else if (rv)
1766                                 continue;
1767                         rv = check_hotmod_int_op(curr, o, "rsi", &regsize);
1768                         if (rv < 0)
1769                                 goto out;
1770                         else if (rv)
1771                                 continue;
1772                         rv = check_hotmod_int_op(curr, o, "rsh", &regshift);
1773                         if (rv < 0)
1774                                 goto out;
1775                         else if (rv)
1776                                 continue;
1777                         rv = check_hotmod_int_op(curr, o, "irq", &irq);
1778                         if (rv < 0)
1779                                 goto out;
1780                         else if (rv)
1781                                 continue;
1782                         rv = check_hotmod_int_op(curr, o, "ipmb", &ipmb);
1783                         if (rv < 0)
1784                                 goto out;
1785                         else if (rv)
1786                                 continue;
1787
1788                         rv = -EINVAL;
1789                         printk(KERN_WARNING PFX
1790                                "Invalid hotmod option '%s'\n",
1791                                curr);
1792                         goto out;
1793                 }
1794
1795                 if (op == HM_ADD) {
1796                         info = smi_info_alloc();
1797                         if (!info) {
1798                                 rv = -ENOMEM;
1799                                 goto out;
1800                         }
1801
1802                         info->addr_source = SI_HOTMOD;
1803                         info->si_type = si_type;
1804                         info->io.addr_data = addr;
1805                         info->io.addr_type = addr_space;
1806                         if (addr_space == IPMI_MEM_ADDR_SPACE)
1807                                 info->io_setup = mem_setup;
1808                         else
1809                                 info->io_setup = port_setup;
1810
1811                         info->io.addr = NULL;
1812                         info->io.regspacing = regspacing;
1813                         if (!info->io.regspacing)
1814                                 info->io.regspacing = DEFAULT_REGSPACING;
1815                         info->io.regsize = regsize;
1816                         if (!info->io.regsize)
1817                                 info->io.regsize = DEFAULT_REGSPACING;
1818                         info->io.regshift = regshift;
1819                         info->irq = irq;
1820                         if (info->irq)
1821                                 info->irq_setup = std_irq_setup;
1822                         info->slave_addr = ipmb;
1823
1824                         if (!add_smi(info)) {
1825                                 if (try_smi_init(info))
1826                                         cleanup_one_si(info);
1827                         } else {
1828                                 kfree(info);
1829                         }
1830                 } else {
1831                         /* remove */
1832                         struct smi_info *e, *tmp_e;
1833
1834                         mutex_lock(&smi_infos_lock);
1835                         list_for_each_entry_safe(e, tmp_e, &smi_infos, link) {
1836                                 if (e->io.addr_type != addr_space)
1837                                         continue;
1838                                 if (e->si_type != si_type)
1839                                         continue;
1840                                 if (e->io.addr_data == addr)
1841                                         cleanup_one_si(e);
1842                         }
1843                         mutex_unlock(&smi_infos_lock);
1844                 }
1845         }
1846         rv = len;
1847  out:
1848         kfree(str);
1849         return rv;
1850 }
1851
1852 static int __devinit hardcode_find_bmc(void)
1853 {
1854         int ret = -ENODEV;
1855         int             i;
1856         struct smi_info *info;
1857
1858         for (i = 0; i < SI_MAX_PARMS; i++) {
1859                 if (!ports[i] && !addrs[i])
1860                         continue;
1861
1862                 info = smi_info_alloc();
1863                 if (!info)
1864                         return -ENOMEM;
1865
1866                 info->addr_source = SI_HARDCODED;
1867                 printk(KERN_INFO PFX "probing via hardcoded address\n");
1868
1869                 if (!si_type[i] || strcmp(si_type[i], "kcs") == 0) {
1870                         info->si_type = SI_KCS;
1871                 } else if (strcmp(si_type[i], "smic") == 0) {
1872                         info->si_type = SI_SMIC;
1873                 } else if (strcmp(si_type[i], "bt") == 0) {
1874                         info->si_type = SI_BT;
1875                 } else {
1876                         printk(KERN_WARNING PFX "Interface type specified "
1877                                "for interface %d, was invalid: %s\n",
1878                                i, si_type[i]);
1879                         kfree(info);
1880                         continue;
1881                 }
1882
1883                 if (ports[i]) {
1884                         /* An I/O port */
1885                         info->io_setup = port_setup;
1886                         info->io.addr_data = ports[i];
1887                         info->io.addr_type = IPMI_IO_ADDR_SPACE;
1888                 } else if (addrs[i]) {
1889                         /* A memory port */
1890                         info->io_setup = mem_setup;
1891                         info->io.addr_data = addrs[i];
1892                         info->io.addr_type = IPMI_MEM_ADDR_SPACE;
1893                 } else {
1894                         printk(KERN_WARNING PFX "Interface type specified "
1895                                "for interface %d, but port and address were "
1896                                "not set or set to zero.\n", i);
1897                         kfree(info);
1898                         continue;
1899                 }
1900
1901                 info->io.addr = NULL;
1902                 info->io.regspacing = regspacings[i];
1903                 if (!info->io.regspacing)
1904                         info->io.regspacing = DEFAULT_REGSPACING;
1905                 info->io.regsize = regsizes[i];
1906                 if (!info->io.regsize)
1907                         info->io.regsize = DEFAULT_REGSPACING;
1908                 info->io.regshift = regshifts[i];
1909                 info->irq = irqs[i];
1910                 if (info->irq)
1911                         info->irq_setup = std_irq_setup;
1912                 info->slave_addr = slave_addrs[i];
1913
1914                 if (!add_smi(info)) {
1915                         if (try_smi_init(info))
1916                                 cleanup_one_si(info);
1917                         ret = 0;
1918                 } else {
1919                         kfree(info);
1920                 }
1921         }
1922         return ret;
1923 }
1924
1925 #ifdef CONFIG_ACPI
1926
1927 #include <linux/acpi.h>
1928
1929 /*
1930  * Once we get an ACPI failure, we don't try any more, because we go
1931  * through the tables sequentially.  Once we don't find a table, there
1932  * are no more.
1933  */
1934 static int acpi_failure;
1935
1936 /* For GPE-type interrupts. */
1937 static u32 ipmi_acpi_gpe(acpi_handle gpe_device,
1938         u32 gpe_number, void *context)
1939 {
1940         struct smi_info *smi_info = context;
1941         unsigned long   flags;
1942 #ifdef DEBUG_TIMING
1943         struct timeval t;
1944 #endif
1945
1946         spin_lock_irqsave(&(smi_info->si_lock), flags);
1947
1948         smi_inc_stat(smi_info, interrupts);
1949
1950 #ifdef DEBUG_TIMING
1951         do_gettimeofday(&t);
1952         printk("**ACPI_GPE: %d.%9.9d\n", t.tv_sec, t.tv_usec);
1953 #endif
1954         smi_event_handler(smi_info, 0);
1955         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1956
1957         return ACPI_INTERRUPT_HANDLED;
1958 }
1959
1960 static void acpi_gpe_irq_cleanup(struct smi_info *info)
1961 {
1962         if (!info->irq)
1963                 return;
1964
1965         acpi_remove_gpe_handler(NULL, info->irq, &ipmi_acpi_gpe);
1966 }
1967
1968 static int acpi_gpe_irq_setup(struct smi_info *info)
1969 {
1970         acpi_status status;
1971
1972         if (!info->irq)
1973                 return 0;
1974
1975         /* FIXME - is level triggered right? */
1976         status = acpi_install_gpe_handler(NULL,
1977                                           info->irq,
1978                                           ACPI_GPE_LEVEL_TRIGGERED,
1979                                           &ipmi_acpi_gpe,
1980                                           info);
1981         if (status != AE_OK) {
1982                 dev_warn(info->dev, "%s unable to claim ACPI GPE %d,"
1983                          " running polled\n", DEVICE_NAME, info->irq);
1984                 info->irq = 0;
1985                 return -EINVAL;
1986         } else {
1987                 info->irq_cleanup = acpi_gpe_irq_cleanup;
1988                 dev_info(info->dev, "Using ACPI GPE %d\n", info->irq);
1989                 return 0;
1990         }
1991 }
1992
1993 /*
1994  * Defined at
1995  * http://h21007.www2.hp.com/portal/download/files/unprot/hpspmi.pdf
1996  */
1997 struct SPMITable {
1998         s8      Signature[4];
1999         u32     Length;
2000         u8      Revision;
2001         u8      Checksum;
2002         s8      OEMID[6];
2003         s8      OEMTableID[8];
2004         s8      OEMRevision[4];
2005         s8      CreatorID[4];
2006         s8      CreatorRevision[4];
2007         u8      InterfaceType;
2008         u8      IPMIlegacy;
2009         s16     SpecificationRevision;
2010
2011         /*
2012          * Bit 0 - SCI interrupt supported
2013          * Bit 1 - I/O APIC/SAPIC
2014          */
2015         u8      InterruptType;
2016
2017         /*
2018          * If bit 0 of InterruptType is set, then this is the SCI
2019          * interrupt in the GPEx_STS register.
2020          */
2021         u8      GPE;
2022
2023         s16     Reserved;
2024
2025         /*
2026          * If bit 1 of InterruptType is set, then this is the I/O
2027          * APIC/SAPIC interrupt.
2028          */
2029         u32     GlobalSystemInterrupt;
2030
2031         /* The actual register address. */
2032         struct acpi_generic_address addr;
2033
2034         u8      UID[4];
2035
2036         s8      spmi_id[1]; /* A '\0' terminated array starts here. */
2037 };
2038
2039 static int __devinit try_init_spmi(struct SPMITable *spmi)
2040 {
2041         struct smi_info  *info;
2042
2043         if (spmi->IPMIlegacy != 1) {
2044                 printk(KERN_INFO PFX "Bad SPMI legacy %d\n", spmi->IPMIlegacy);
2045                 return -ENODEV;
2046         }
2047
2048         info = smi_info_alloc();
2049         if (!info) {
2050                 printk(KERN_ERR PFX "Could not allocate SI data (3)\n");
2051                 return -ENOMEM;
2052         }
2053
2054         info->addr_source = SI_SPMI;
2055         printk(KERN_INFO PFX "probing via SPMI\n");
2056
2057         /* Figure out the interface type. */
2058         switch (spmi->InterfaceType) {
2059         case 1: /* KCS */
2060                 info->si_type = SI_KCS;
2061                 break;
2062         case 2: /* SMIC */
2063                 info->si_type = SI_SMIC;
2064                 break;
2065         case 3: /* BT */
2066                 info->si_type = SI_BT;
2067                 break;
2068         default:
2069                 printk(KERN_INFO PFX "Unknown ACPI/SPMI SI type %d\n",
2070                        spmi->InterfaceType);
2071                 kfree(info);
2072                 return -EIO;
2073         }
2074
2075         if (spmi->InterruptType & 1) {
2076                 /* We've got a GPE interrupt. */
2077                 info->irq = spmi->GPE;
2078                 info->irq_setup = acpi_gpe_irq_setup;
2079         } else if (spmi->InterruptType & 2) {
2080                 /* We've got an APIC/SAPIC interrupt. */
2081                 info->irq = spmi->GlobalSystemInterrupt;
2082                 info->irq_setup = std_irq_setup;
2083         } else {
2084                 /* Use the default interrupt setting. */
2085                 info->irq = 0;
2086                 info->irq_setup = NULL;
2087         }
2088
2089         if (spmi->addr.bit_width) {
2090                 /* A (hopefully) properly formed register bit width. */
2091                 info->io.regspacing = spmi->addr.bit_width / 8;
2092         } else {
2093                 info->io.regspacing = DEFAULT_REGSPACING;
2094         }
2095         info->io.regsize = info->io.regspacing;
2096         info->io.regshift = spmi->addr.bit_offset;
2097
2098         if (spmi->addr.space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
2099                 info->io_setup = mem_setup;
2100                 info->io.addr_type = IPMI_MEM_ADDR_SPACE;
2101         } else if (spmi->addr.space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
2102                 info->io_setup = port_setup;
2103                 info->io.addr_type = IPMI_IO_ADDR_SPACE;
2104         } else {
2105                 kfree(info);
2106                 printk(KERN_WARNING PFX "Unknown ACPI I/O Address type\n");
2107                 return -EIO;
2108         }
2109         info->io.addr_data = spmi->addr.address;
2110
2111         pr_info("ipmi_si: SPMI: %s %#lx regsize %d spacing %d irq %d\n",
2112                  (info->io.addr_type == IPMI_IO_ADDR_SPACE) ? "io" : "mem",
2113                  info->io.addr_data, info->io.regsize, info->io.regspacing,
2114                  info->irq);
2115
2116         if (add_smi(info))
2117                 kfree(info);
2118
2119         return 0;
2120 }
2121
2122 static void __devinit spmi_find_bmc(void)
2123 {
2124         acpi_status      status;
2125         struct SPMITable *spmi;
2126         int              i;
2127
2128         if (acpi_disabled)
2129                 return;
2130
2131         if (acpi_failure)
2132                 return;
2133
2134         for (i = 0; ; i++) {
2135                 status = acpi_get_table(ACPI_SIG_SPMI, i+1,
2136                                         (struct acpi_table_header **)&spmi);
2137                 if (status != AE_OK)
2138                         return;
2139
2140                 try_init_spmi(spmi);
2141         }
2142 }
2143
2144 static int __devinit ipmi_pnp_probe(struct pnp_dev *dev,
2145                                     const struct pnp_device_id *dev_id)
2146 {
2147         struct acpi_device *acpi_dev;
2148         struct smi_info *info;
2149         struct resource *res, *res_second;
2150         acpi_handle handle;
2151         acpi_status status;
2152         unsigned long long tmp;
2153
2154         acpi_dev = pnp_acpi_device(dev);
2155         if (!acpi_dev)
2156                 return -ENODEV;
2157
2158         info = smi_info_alloc();
2159         if (!info)
2160                 return -ENOMEM;
2161
2162         info->addr_source = SI_ACPI;
2163         printk(KERN_INFO PFX "probing via ACPI\n");
2164
2165         handle = acpi_dev->handle;
2166         info->addr_info.acpi_info.acpi_handle = handle;
2167
2168         /* _IFT tells us the interface type: KCS, BT, etc */
2169         status = acpi_evaluate_integer(handle, "_IFT", NULL, &tmp);
2170         if (ACPI_FAILURE(status))
2171                 goto err_free;
2172
2173         switch (tmp) {
2174         case 1:
2175                 info->si_type = SI_KCS;
2176                 break;
2177         case 2:
2178                 info->si_type = SI_SMIC;
2179                 break;
2180         case 3:
2181                 info->si_type = SI_BT;
2182                 break;
2183         default:
2184                 dev_info(&dev->dev, "unknown IPMI type %lld\n", tmp);
2185                 goto err_free;
2186         }
2187
2188         res = pnp_get_resource(dev, IORESOURCE_IO, 0);
2189         if (res) {
2190                 info->io_setup = port_setup;
2191                 info->io.addr_type = IPMI_IO_ADDR_SPACE;
2192         } else {
2193                 res = pnp_get_resource(dev, IORESOURCE_MEM, 0);
2194                 if (res) {
2195                         info->io_setup = mem_setup;
2196                         info->io.addr_type = IPMI_MEM_ADDR_SPACE;
2197                 }
2198         }
2199         if (!res) {
2200                 dev_err(&dev->dev, "no I/O or memory address\n");
2201                 goto err_free;
2202         }
2203         info->io.addr_data = res->start;
2204
2205         info->io.regspacing = DEFAULT_REGSPACING;
2206         res_second = pnp_get_resource(dev,
2207                                (info->io.addr_type == IPMI_IO_ADDR_SPACE) ?
2208                                         IORESOURCE_IO : IORESOURCE_MEM,
2209                                1);
2210         if (res_second) {
2211                 if (res_second->start > info->io.addr_data)
2212                         info->io.regspacing = res_second->start - info->io.addr_data;
2213         }
2214         info->io.regsize = DEFAULT_REGSPACING;
2215         info->io.regshift = 0;
2216
2217         /* If _GPE exists, use it; otherwise use standard interrupts */
2218         status = acpi_evaluate_integer(handle, "_GPE", NULL, &tmp);
2219         if (ACPI_SUCCESS(status)) {
2220                 info->irq = tmp;
2221                 info->irq_setup = acpi_gpe_irq_setup;
2222         } else if (pnp_irq_valid(dev, 0)) {
2223                 info->irq = pnp_irq(dev, 0);
2224                 info->irq_setup = std_irq_setup;
2225         }
2226
2227         info->dev = &dev->dev;
2228         pnp_set_drvdata(dev, info);
2229
2230         dev_info(info->dev, "%pR regsize %d spacing %d irq %d\n",
2231                  res, info->io.regsize, info->io.regspacing,
2232                  info->irq);
2233
2234         if (add_smi(info))
2235                 goto err_free;
2236
2237         return 0;
2238
2239 err_free:
2240         kfree(info);
2241         return -EINVAL;
2242 }
2243
2244 static void __devexit ipmi_pnp_remove(struct pnp_dev *dev)
2245 {
2246         struct smi_info *info = pnp_get_drvdata(dev);
2247
2248         cleanup_one_si(info);
2249 }
2250
2251 static const struct pnp_device_id pnp_dev_table[] = {
2252         {"IPI0001", 0},
2253         {"", 0},
2254 };
2255
2256 static struct pnp_driver ipmi_pnp_driver = {
2257         .name           = DEVICE_NAME,
2258         .probe          = ipmi_pnp_probe,
2259         .remove         = __devexit_p(ipmi_pnp_remove),
2260         .id_table       = pnp_dev_table,
2261 };
2262 #endif
2263
2264 #ifdef CONFIG_DMI
2265 struct dmi_ipmi_data {
2266         u8              type;
2267         u8              addr_space;
2268         unsigned long   base_addr;
2269         u8              irq;
2270         u8              offset;
2271         u8              slave_addr;
2272 };
2273
2274 static int __devinit decode_dmi(const struct dmi_header *dm,
2275                                 struct dmi_ipmi_data *dmi)
2276 {
2277         const u8        *data = (const u8 *)dm;
2278         unsigned long   base_addr;
2279         u8              reg_spacing;
2280         u8              len = dm->length;
2281
2282         dmi->type = data[4];
2283
2284         memcpy(&base_addr, data+8, sizeof(unsigned long));
2285         if (len >= 0x11) {
2286                 if (base_addr & 1) {
2287                         /* I/O */
2288                         base_addr &= 0xFFFE;
2289                         dmi->addr_space = IPMI_IO_ADDR_SPACE;
2290                 } else
2291                         /* Memory */
2292                         dmi->addr_space = IPMI_MEM_ADDR_SPACE;
2293
2294                 /* If bit 4 of byte 0x10 is set, then the lsb for the address
2295                    is odd. */
2296                 dmi->base_addr = base_addr | ((data[0x10] & 0x10) >> 4);
2297
2298                 dmi->irq = data[0x11];
2299
2300                 /* The top two bits of byte 0x10 hold the register spacing. */
2301                 reg_spacing = (data[0x10] & 0xC0) >> 6;
2302                 switch (reg_spacing) {
2303                 case 0x00: /* Byte boundaries */
2304                     dmi->offset = 1;
2305                     break;
2306                 case 0x01: /* 32-bit boundaries */
2307                     dmi->offset = 4;
2308                     break;
2309                 case 0x02: /* 16-byte boundaries */
2310                     dmi->offset = 16;
2311                     break;
2312                 default:
2313                     /* Some other interface, just ignore it. */
2314                     return -EIO;
2315                 }
2316         } else {
2317                 /* Old DMI spec. */
2318                 /*
2319                  * Note that technically, the lower bit of the base
2320                  * address should be 1 if the address is I/O and 0 if
2321                  * the address is in memory.  So many systems get that
2322                  * wrong (and all that I have seen are I/O) so we just
2323                  * ignore that bit and assume I/O.  Systems that use
2324                  * memory should use the newer spec, anyway.
2325                  */
2326                 dmi->base_addr = base_addr & 0xfffe;
2327                 dmi->addr_space = IPMI_IO_ADDR_SPACE;
2328                 dmi->offset = 1;
2329         }
2330
2331         dmi->slave_addr = data[6];
2332
2333         return 0;
2334 }
2335
2336 static void __devinit try_init_dmi(struct dmi_ipmi_data *ipmi_data)
2337 {
2338         struct smi_info *info;
2339
2340         info = smi_info_alloc();
2341         if (!info) {
2342                 printk(KERN_ERR PFX "Could not allocate SI data\n");
2343                 return;
2344         }
2345
2346         info->addr_source = SI_SMBIOS;
2347         printk(KERN_INFO PFX "probing via SMBIOS\n");
2348
2349         switch (ipmi_data->type) {
2350         case 0x01: /* KCS */
2351                 info->si_type = SI_KCS;
2352                 break;
2353         case 0x02: /* SMIC */
2354                 info->si_type = SI_SMIC;
2355                 break;
2356         case 0x03: /* BT */
2357                 info->si_type = SI_BT;
2358                 break;
2359         default:
2360                 kfree(info);
2361                 return;
2362         }
2363
2364         switch (ipmi_data->addr_space) {
2365         case IPMI_MEM_ADDR_SPACE:
2366                 info->io_setup = mem_setup;
2367                 info->io.addr_type = IPMI_MEM_ADDR_SPACE;
2368                 break;
2369
2370         case IPMI_IO_ADDR_SPACE:
2371                 info->io_setup = port_setup;
2372                 info->io.addr_type = IPMI_IO_ADDR_SPACE;
2373                 break;
2374
2375         default:
2376                 kfree(info);
2377                 printk(KERN_WARNING PFX "Unknown SMBIOS I/O Address type: %d\n",
2378                        ipmi_data->addr_space);
2379                 return;
2380         }
2381         info->io.addr_data = ipmi_data->base_addr;
2382
2383         info->io.regspacing = ipmi_data->offset;
2384         if (!info->io.regspacing)
2385                 info->io.regspacing = DEFAULT_REGSPACING;
2386         info->io.regsize = DEFAULT_REGSPACING;
2387         info->io.regshift = 0;
2388
2389         info->slave_addr = ipmi_data->slave_addr;
2390
2391         info->irq = ipmi_data->irq;
2392         if (info->irq)
2393                 info->irq_setup = std_irq_setup;
2394
2395         pr_info("ipmi_si: SMBIOS: %s %#lx regsize %d spacing %d irq %d\n",
2396                  (info->io.addr_type == IPMI_IO_ADDR_SPACE) ? "io" : "mem",
2397                  info->io.addr_data, info->io.regsize, info->io.regspacing,
2398                  info->irq);
2399
2400         if (add_smi(info))
2401                 kfree(info);
2402 }
2403
2404 static void __devinit dmi_find_bmc(void)
2405 {
2406         const struct dmi_device *dev = NULL;
2407         struct dmi_ipmi_data data;
2408         int                  rv;
2409
2410         while ((dev = dmi_find_device(DMI_DEV_TYPE_IPMI, NULL, dev))) {
2411                 memset(&data, 0, sizeof(data));
2412                 rv = decode_dmi((const struct dmi_header *) dev->device_data,
2413                                 &data);
2414                 if (!rv)
2415                         try_init_dmi(&data);
2416         }
2417 }
2418 #endif /* CONFIG_DMI */
2419
2420 #ifdef CONFIG_PCI
2421
2422 #define PCI_ERMC_CLASSCODE              0x0C0700
2423 #define PCI_ERMC_CLASSCODE_MASK         0xffffff00
2424 #define PCI_ERMC_CLASSCODE_TYPE_MASK    0xff
2425 #define PCI_ERMC_CLASSCODE_TYPE_SMIC    0x00
2426 #define PCI_ERMC_CLASSCODE_TYPE_KCS     0x01
2427 #define PCI_ERMC_CLASSCODE_TYPE_BT      0x02
2428
2429 #define PCI_HP_VENDOR_ID    0x103C
2430 #define PCI_MMC_DEVICE_ID   0x121A
2431 #define PCI_MMC_ADDR_CW     0x10
2432
2433 static void ipmi_pci_cleanup(struct smi_info *info)
2434 {
2435         struct pci_dev *pdev = info->addr_source_data;
2436
2437         pci_disable_device(pdev);
2438 }
2439
2440 static int __devinit ipmi_pci_probe(struct pci_dev *pdev,
2441                                     const struct pci_device_id *ent)
2442 {
2443         int rv;
2444         int class_type = pdev->class & PCI_ERMC_CLASSCODE_TYPE_MASK;
2445         struct smi_info *info;
2446
2447         info = smi_info_alloc();
2448         if (!info)
2449                 return -ENOMEM;
2450
2451         info->addr_source = SI_PCI;
2452         dev_info(&pdev->dev, "probing via PCI");
2453
2454         switch (class_type) {
2455         case PCI_ERMC_CLASSCODE_TYPE_SMIC:
2456                 info->si_type = SI_SMIC;
2457                 break;
2458
2459         case PCI_ERMC_CLASSCODE_TYPE_KCS:
2460                 info->si_type = SI_KCS;
2461                 break;
2462
2463         case PCI_ERMC_CLASSCODE_TYPE_BT:
2464                 info->si_type = SI_BT;
2465                 break;
2466
2467         default:
2468                 kfree(info);
2469                 dev_info(&pdev->dev, "Unknown IPMI type: %d\n", class_type);
2470                 return -ENOMEM;
2471         }
2472
2473         rv = pci_enable_device(pdev);
2474         if (rv) {
2475                 dev_err(&pdev->dev, "couldn't enable PCI device\n");
2476                 kfree(info);
2477                 return rv;
2478         }
2479
2480         info->addr_source_cleanup = ipmi_pci_cleanup;
2481         info->addr_source_data = pdev;
2482
2483         if (pci_resource_flags(pdev, 0) & IORESOURCE_IO) {
2484                 info->io_setup = port_setup;
2485                 info->io.addr_type = IPMI_IO_ADDR_SPACE;
2486         } else {
2487                 info->io_setup = mem_setup;
2488                 info->io.addr_type = IPMI_MEM_ADDR_SPACE;
2489         }
2490         info->io.addr_data = pci_resource_start(pdev, 0);
2491
2492         info->io.regspacing = DEFAULT_REGSPACING;
2493         info->io.regsize = DEFAULT_REGSPACING;
2494         info->io.regshift = 0;
2495
2496         info->irq = pdev->irq;
2497         if (info->irq)
2498                 info->irq_setup = std_irq_setup;
2499
2500         info->dev = &pdev->dev;
2501         pci_set_drvdata(pdev, info);
2502
2503         dev_info(&pdev->dev, "%pR regsize %d spacing %d irq %d\n",
2504                 &pdev->resource[0], info->io.regsize, info->io.regspacing,
2505                 info->irq);
2506
2507         if (add_smi(info))
2508                 kfree(info);
2509
2510         return 0;
2511 }
2512
2513 static void __devexit ipmi_pci_remove(struct pci_dev *pdev)
2514 {
2515         struct smi_info *info = pci_get_drvdata(pdev);
2516         cleanup_one_si(info);
2517 }
2518
2519 #ifdef CONFIG_PM
2520 static int ipmi_pci_suspend(struct pci_dev *pdev, pm_message_t state)
2521 {
2522         return 0;
2523 }
2524
2525 static int ipmi_pci_resume(struct pci_dev *pdev)
2526 {
2527         return 0;
2528 }
2529 #endif
2530
2531 static struct pci_device_id ipmi_pci_devices[] = {
2532         { PCI_DEVICE(PCI_HP_VENDOR_ID, PCI_MMC_DEVICE_ID) },
2533         { PCI_DEVICE_CLASS(PCI_ERMC_CLASSCODE, PCI_ERMC_CLASSCODE_MASK) },
2534         { 0, }
2535 };
2536 MODULE_DEVICE_TABLE(pci, ipmi_pci_devices);
2537
2538 static struct pci_driver ipmi_pci_driver = {
2539         .name =         DEVICE_NAME,
2540         .id_table =     ipmi_pci_devices,
2541         .probe =        ipmi_pci_probe,
2542         .remove =       __devexit_p(ipmi_pci_remove),
2543 #ifdef CONFIG_PM
2544         .suspend =      ipmi_pci_suspend,
2545         .resume =       ipmi_pci_resume,
2546 #endif
2547 };
2548 #endif /* CONFIG_PCI */
2549
2550 static struct of_device_id ipmi_match[];
2551 static int __devinit ipmi_probe(struct platform_device *dev)
2552 {
2553 #ifdef CONFIG_OF
2554         const struct of_device_id *match;
2555         struct smi_info *info;
2556         struct resource resource;
2557         const __be32 *regsize, *regspacing, *regshift;
2558         struct device_node *np = dev->dev.of_node;
2559         int ret;
2560         int proplen;
2561
2562         dev_info(&dev->dev, "probing via device tree\n");
2563
2564         match = of_match_device(ipmi_match, &dev->dev);
2565         if (!match)
2566                 return -EINVAL;
2567
2568         ret = of_address_to_resource(np, 0, &resource);
2569         if (ret) {
2570                 dev_warn(&dev->dev, PFX "invalid address from OF\n");
2571                 return ret;
2572         }
2573
2574         regsize = of_get_property(np, "reg-size", &proplen);
2575         if (regsize && proplen != 4) {
2576                 dev_warn(&dev->dev, PFX "invalid regsize from OF\n");
2577                 return -EINVAL;
2578         }
2579
2580         regspacing = of_get_property(np, "reg-spacing", &proplen);
2581         if (regspacing && proplen != 4) {
2582                 dev_warn(&dev->dev, PFX "invalid regspacing from OF\n");
2583                 return -EINVAL;
2584         }
2585
2586         regshift = of_get_property(np, "reg-shift", &proplen);
2587         if (regshift && proplen != 4) {
2588                 dev_warn(&dev->dev, PFX "invalid regshift from OF\n");
2589                 return -EINVAL;
2590         }
2591
2592         info = smi_info_alloc();
2593
2594         if (!info) {
2595                 dev_err(&dev->dev,
2596                         "could not allocate memory for OF probe\n");
2597                 return -ENOMEM;
2598         }
2599
2600         info->si_type           = (enum si_type) match->data;
2601         info->addr_source       = SI_DEVICETREE;
2602         info->irq_setup         = std_irq_setup;
2603
2604         if (resource.flags & IORESOURCE_IO) {
2605                 info->io_setup          = port_setup;
2606                 info->io.addr_type      = IPMI_IO_ADDR_SPACE;
2607         } else {
2608                 info->io_setup          = mem_setup;
2609                 info->io.addr_type      = IPMI_MEM_ADDR_SPACE;
2610         }
2611
2612         info->io.addr_data      = resource.start;
2613
2614         info->io.regsize        = regsize ? be32_to_cpup(regsize) : DEFAULT_REGSIZE;
2615         info->io.regspacing     = regspacing ? be32_to_cpup(regspacing) : DEFAULT_REGSPACING;
2616         info->io.regshift       = regshift ? be32_to_cpup(regshift) : 0;
2617
2618         info->irq               = irq_of_parse_and_map(dev->dev.of_node, 0);
2619         info->dev               = &dev->dev;
2620
2621         dev_dbg(&dev->dev, "addr 0x%lx regsize %d spacing %d irq %d\n",
2622                 info->io.addr_data, info->io.regsize, info->io.regspacing,
2623                 info->irq);
2624
2625         dev_set_drvdata(&dev->dev, info);
2626
2627         if (add_smi(info)) {
2628                 kfree(info);
2629                 return -EBUSY;
2630         }
2631 #endif
2632         return 0;
2633 }
2634
2635 static int __devexit ipmi_remove(struct platform_device *dev)
2636 {
2637 #ifdef CONFIG_OF
2638         cleanup_one_si(dev_get_drvdata(&dev->dev));
2639 #endif
2640         return 0;
2641 }
2642
2643 static struct of_device_id ipmi_match[] =
2644 {
2645         { .type = "ipmi", .compatible = "ipmi-kcs",
2646           .data = (void *)(unsigned long) SI_KCS },
2647         { .type = "ipmi", .compatible = "ipmi-smic",
2648           .data = (void *)(unsigned long) SI_SMIC },
2649         { .type = "ipmi", .compatible = "ipmi-bt",
2650           .data = (void *)(unsigned long) SI_BT },
2651         {},
2652 };
2653
2654 static struct platform_driver ipmi_driver = {
2655         .driver = {
2656                 .name = DEVICE_NAME,
2657                 .owner = THIS_MODULE,
2658                 .of_match_table = ipmi_match,
2659         },
2660         .probe          = ipmi_probe,
2661         .remove         = __devexit_p(ipmi_remove),
2662 };
2663
2664 static int wait_for_msg_done(struct smi_info *smi_info)
2665 {
2666         enum si_sm_result     smi_result;
2667
2668         smi_result = smi_info->handlers->event(smi_info->si_sm, 0);
2669         for (;;) {
2670                 if (smi_result == SI_SM_CALL_WITH_DELAY ||
2671                     smi_result == SI_SM_CALL_WITH_TICK_DELAY) {
2672                         schedule_timeout_uninterruptible(1);
2673                         smi_result = smi_info->handlers->event(
2674                                 smi_info->si_sm, 100);
2675                 } else if (smi_result == SI_SM_CALL_WITHOUT_DELAY) {
2676                         smi_result = smi_info->handlers->event(
2677                                 smi_info->si_sm, 0);
2678                 } else
2679                         break;
2680         }
2681         if (smi_result == SI_SM_HOSED)
2682                 /*
2683                  * We couldn't get the state machine to run, so whatever's at
2684                  * the port is probably not an IPMI SMI interface.
2685                  */
2686                 return -ENODEV;
2687
2688         return 0;
2689 }
2690
2691 static int try_get_dev_id(struct smi_info *smi_info)
2692 {
2693         unsigned char         msg[2];
2694         unsigned char         *resp;
2695         unsigned long         resp_len;
2696         int                   rv = 0;
2697
2698         resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
2699         if (!resp)
2700                 return -ENOMEM;
2701
2702         /*
2703          * Do a Get Device ID command, since it comes back with some
2704          * useful info.
2705          */
2706         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
2707         msg[1] = IPMI_GET_DEVICE_ID_CMD;
2708         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
2709
2710         rv = wait_for_msg_done(smi_info);
2711         if (rv)
2712                 goto out;
2713
2714         resp_len = smi_info->handlers->get_result(smi_info->si_sm,
2715                                                   resp, IPMI_MAX_MSG_LENGTH);
2716
2717         /* Check and record info from the get device id, in case we need it. */
2718         rv = ipmi_demangle_device_id(resp, resp_len, &smi_info->device_id);
2719
2720  out:
2721         kfree(resp);
2722         return rv;
2723 }
2724
2725 static int try_enable_event_buffer(struct smi_info *smi_info)
2726 {
2727         unsigned char         msg[3];
2728         unsigned char         *resp;
2729         unsigned long         resp_len;
2730         int                   rv = 0;
2731
2732         resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
2733         if (!resp)
2734                 return -ENOMEM;
2735
2736         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
2737         msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
2738         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
2739
2740         rv = wait_for_msg_done(smi_info);
2741         if (rv) {
2742                 printk(KERN_WARNING PFX "Error getting response from get"
2743                        " global enables command, the event buffer is not"
2744                        " enabled.\n");
2745                 goto out;
2746         }
2747
2748         resp_len = smi_info->handlers->get_result(smi_info->si_sm,
2749                                                   resp, IPMI_MAX_MSG_LENGTH);
2750
2751         if (resp_len < 4 ||
2752                         resp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2 ||
2753                         resp[1] != IPMI_GET_BMC_GLOBAL_ENABLES_CMD   ||
2754                         resp[2] != 0) {
2755                 printk(KERN_WARNING PFX "Invalid return from get global"
2756                        " enables command, cannot enable the event buffer.\n");
2757                 rv = -EINVAL;
2758                 goto out;
2759         }
2760
2761         if (resp[3] & IPMI_BMC_EVT_MSG_BUFF)
2762                 /* buffer is already enabled, nothing to do. */
2763                 goto out;
2764
2765         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
2766         msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
2767         msg[2] = resp[3] | IPMI_BMC_EVT_MSG_BUFF;
2768         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 3);
2769
2770         rv = wait_for_msg_done(smi_info);
2771         if (rv) {
2772                 printk(KERN_WARNING PFX "Error getting response from set"
2773                        " global, enables command, the event buffer is not"
2774                        " enabled.\n");
2775                 goto out;
2776         }
2777
2778         resp_len = smi_info->handlers->get_result(smi_info->si_sm,
2779                                                   resp, IPMI_MAX_MSG_LENGTH);
2780
2781         if (resp_len < 3 ||
2782                         resp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2 ||
2783                         resp[1] != IPMI_SET_BMC_GLOBAL_ENABLES_CMD) {
2784                 printk(KERN_WARNING PFX "Invalid return from get global,"
2785                        "enables command, not enable the event buffer.\n");
2786                 rv = -EINVAL;
2787                 goto out;
2788         }
2789
2790         if (resp[2] != 0)
2791                 /*
2792                  * An error when setting the event buffer bit means
2793                  * that the event buffer is not supported.
2794                  */
2795                 rv = -ENOENT;
2796  out:
2797         kfree(resp);
2798         return rv;
2799 }
2800
2801 static int smi_type_proc_show(struct seq_file *m, void *v)
2802 {
2803         struct smi_info *smi = m->private;
2804
2805         return seq_printf(m, "%s\n", si_to_str[smi->si_type]);
2806 }
2807
2808 static int smi_type_proc_open(struct inode *inode, struct file *file)
2809 {
2810         return single_open(file, smi_type_proc_show, PDE(inode)->data);
2811 }
2812
2813 static const struct file_operations smi_type_proc_ops = {
2814         .open           = smi_type_proc_open,
2815         .read           = seq_read,
2816         .llseek         = seq_lseek,
2817         .release        = single_release,
2818 };
2819
2820 static int smi_si_stats_proc_show(struct seq_file *m, void *v)
2821 {
2822         struct smi_info *smi = m->private;
2823
2824         seq_printf(m, "interrupts_enabled:    %d\n",
2825                        smi->irq && !smi->interrupt_disabled);
2826         seq_printf(m, "short_timeouts:        %u\n",
2827                        smi_get_stat(smi, short_timeouts));
2828         seq_printf(m, "long_timeouts:         %u\n",
2829                        smi_get_stat(smi, long_timeouts));
2830         seq_printf(m, "idles:                 %u\n",
2831                        smi_get_stat(smi, idles));
2832         seq_printf(m, "interrupts:            %u\n",
2833                        smi_get_stat(smi, interrupts));
2834         seq_printf(m, "attentions:            %u\n",
2835                        smi_get_stat(smi, attentions));
2836         seq_printf(m, "flag_fetches:          %u\n",
2837                        smi_get_stat(smi, flag_fetches));
2838         seq_printf(m, "hosed_count:           %u\n",
2839                        smi_get_stat(smi, hosed_count));
2840         seq_printf(m, "complete_transactions: %u\n",
2841                        smi_get_stat(smi, complete_transactions));
2842         seq_printf(m, "events:                %u\n",
2843                        smi_get_stat(smi, events));
2844         seq_printf(m, "watchdog_pretimeouts:  %u\n",
2845                        smi_get_stat(smi, watchdog_pretimeouts));
2846         seq_printf(m, "incoming_messages:     %u\n",
2847                        smi_get_stat(smi, incoming_messages));
2848         return 0;
2849 }
2850
2851 static int smi_si_stats_proc_open(struct inode *inode, struct file *file)
2852 {
2853         return single_open(file, smi_si_stats_proc_show, PDE(inode)->data);
2854 }
2855
2856 static const struct file_operations smi_si_stats_proc_ops = {
2857         .open           = smi_si_stats_proc_open,
2858         .read           = seq_read,
2859         .llseek         = seq_lseek,
2860         .release        = single_release,
2861 };
2862
2863 static int smi_params_proc_show(struct seq_file *m, void *v)
2864 {
2865         struct smi_info *smi = m->private;
2866
2867         return seq_printf(m,
2868                        "%s,%s,0x%lx,rsp=%d,rsi=%d,rsh=%d,irq=%d,ipmb=%d\n",
2869                        si_to_str[smi->si_type],
2870                        addr_space_to_str[smi->io.addr_type],
2871                        smi->io.addr_data,
2872                        smi->io.regspacing,
2873                        smi->io.regsize,
2874                        smi->io.regshift,
2875                        smi->irq,
2876                        smi->slave_addr);
2877 }
2878
2879 static int smi_params_proc_open(struct inode *inode, struct file *file)
2880 {
2881         return single_open(file, smi_params_proc_show, PDE(inode)->data);
2882 }
2883
2884 static const struct file_operations smi_params_proc_ops = {
2885         .open           = smi_params_proc_open,
2886         .read           = seq_read,
2887         .llseek         = seq_lseek,
2888         .release        = single_release,
2889 };
2890
2891 /*
2892  * oem_data_avail_to_receive_msg_avail
2893  * @info - smi_info structure with msg_flags set
2894  *
2895  * Converts flags from OEM_DATA_AVAIL to RECEIVE_MSG_AVAIL
2896  * Returns 1 indicating need to re-run handle_flags().
2897  */
2898 static int oem_data_avail_to_receive_msg_avail(struct smi_info *smi_info)
2899 {
2900         smi_info->msg_flags = ((smi_info->msg_flags & ~OEM_DATA_AVAIL) |
2901                                RECEIVE_MSG_AVAIL);
2902         return 1;
2903 }
2904
2905 /*
2906  * setup_dell_poweredge_oem_data_handler
2907  * @info - smi_info.device_id must be populated
2908  *
2909  * Systems that match, but have firmware version < 1.40 may assert
2910  * OEM0_DATA_AVAIL on their own, without being told via Set Flags that
2911  * it's safe to do so.  Such systems will de-assert OEM1_DATA_AVAIL
2912  * upon receipt of IPMI_GET_MSG_CMD, so we should treat these flags
2913  * as RECEIVE_MSG_AVAIL instead.
2914  *
2915  * As Dell has no plans to release IPMI 1.5 firmware that *ever*
2916  * assert the OEM[012] bits, and if it did, the driver would have to
2917  * change to handle that properly, we don't actually check for the
2918  * firmware version.
2919  * Device ID = 0x20                BMC on PowerEdge 8G servers
2920  * Device Revision = 0x80
2921  * Firmware Revision1 = 0x01       BMC version 1.40
2922  * Firmware Revision2 = 0x40       BCD encoded
2923  * IPMI Version = 0x51             IPMI 1.5
2924  * Manufacturer ID = A2 02 00      Dell IANA
2925  *
2926  * Additionally, PowerEdge systems with IPMI < 1.5 may also assert
2927  * OEM0_DATA_AVAIL and needs to be treated as RECEIVE_MSG_AVAIL.
2928  *
2929  */
2930 #define DELL_POWEREDGE_8G_BMC_DEVICE_ID  0x20
2931 #define DELL_POWEREDGE_8G_BMC_DEVICE_REV 0x80
2932 #define DELL_POWEREDGE_8G_BMC_IPMI_VERSION 0x51
2933 #define DELL_IANA_MFR_ID 0x0002a2
2934 static void setup_dell_poweredge_oem_data_handler(struct smi_info *smi_info)
2935 {
2936         struct ipmi_device_id *id = &smi_info->device_id;
2937         if (id->manufacturer_id == DELL_IANA_MFR_ID) {
2938                 if (id->device_id       == DELL_POWEREDGE_8G_BMC_DEVICE_ID  &&
2939                     id->device_revision == DELL_POWEREDGE_8G_BMC_DEVICE_REV &&
2940                     id->ipmi_version   == DELL_POWEREDGE_8G_BMC_IPMI_VERSION) {
2941                         smi_info->oem_data_avail_handler =
2942                                 oem_data_avail_to_receive_msg_avail;
2943                 } else if (ipmi_version_major(id) < 1 ||
2944                            (ipmi_version_major(id) == 1 &&
2945                             ipmi_version_minor(id) < 5)) {
2946                         smi_info->oem_data_avail_handler =
2947                                 oem_data_avail_to_receive_msg_avail;
2948                 }
2949         }
2950 }
2951
2952 #define CANNOT_RETURN_REQUESTED_LENGTH 0xCA
2953 static void return_hosed_msg_badsize(struct smi_info *smi_info)
2954 {
2955         struct ipmi_smi_msg *msg = smi_info->curr_msg;
2956
2957         /* Make it a response */
2958         msg->rsp[0] = msg->data[0] | 4;
2959         msg->rsp[1] = msg->data[1];
2960         msg->rsp[2] = CANNOT_RETURN_REQUESTED_LENGTH;
2961         msg->rsp_size = 3;
2962         smi_info->curr_msg = NULL;
2963         deliver_recv_msg(smi_info, msg);
2964 }
2965
2966 /*
2967  * dell_poweredge_bt_xaction_handler
2968  * @info - smi_info.device_id must be populated
2969  *
2970  * Dell PowerEdge servers with the BT interface (x6xx and 1750) will
2971  * not respond to a Get SDR command if the length of the data
2972  * requested is exactly 0x3A, which leads to command timeouts and no
2973  * data returned.  This intercepts such commands, and causes userspace
2974  * callers to try again with a different-sized buffer, which succeeds.
2975  */
2976
2977 #define STORAGE_NETFN 0x0A
2978 #define STORAGE_CMD_GET_SDR 0x23
2979 static int dell_poweredge_bt_xaction_handler(struct notifier_block *self,
2980                                              unsigned long unused,
2981                                              void *in)
2982 {
2983         struct smi_info *smi_info = in;
2984         unsigned char *data = smi_info->curr_msg->data;
2985         unsigned int size   = smi_info->curr_msg->data_size;
2986         if (size >= 8 &&
2987             (data[0]>>2) == STORAGE_NETFN &&
2988             data[1] == STORAGE_CMD_GET_SDR &&
2989             data[7] == 0x3A) {
2990                 return_hosed_msg_badsize(smi_info);
2991                 return NOTIFY_STOP;
2992         }
2993         return NOTIFY_DONE;
2994 }
2995
2996 static struct notifier_block dell_poweredge_bt_xaction_notifier = {
2997         .notifier_call  = dell_poweredge_bt_xaction_handler,
2998 };
2999
3000 /*
3001  * setup_dell_poweredge_bt_xaction_handler
3002  * @info - smi_info.device_id must be filled in already
3003  *
3004  * Fills in smi_info.device_id.start_transaction_pre_hook
3005  * when we know what function to use there.
3006  */
3007 static void
3008 setup_dell_poweredge_bt_xaction_handler(struct smi_info *smi_info)
3009 {
3010         struct ipmi_device_id *id = &smi_info->device_id;
3011         if (id->manufacturer_id == DELL_IANA_MFR_ID &&
3012             smi_info->si_type == SI_BT)
3013                 register_xaction_notifier(&dell_poweredge_bt_xaction_notifier);
3014 }
3015
3016 /*
3017  * setup_oem_data_handler
3018  * @info - smi_info.device_id must be filled in already
3019  *
3020  * Fills in smi_info.device_id.oem_data_available_handler
3021  * when we know what function to use there.
3022  */
3023
3024 static void setup_oem_data_handler(struct smi_info *smi_info)
3025 {
3026         setup_dell_poweredge_oem_data_handler(smi_info);
3027 }
3028
3029 static void setup_xaction_handlers(struct smi_info *smi_info)
3030 {
3031         setup_dell_poweredge_bt_xaction_handler(smi_info);
3032 }
3033
3034 static inline void wait_for_timer_and_thread(struct smi_info *smi_info)
3035 {
3036         if (smi_info->intf) {
3037                 /*
3038                  * The timer and thread are only running if the
3039                  * interface has been started up and registered.
3040                  */
3041                 if (smi_info->thread != NULL)
3042                         kthread_stop(smi_info->thread);
3043                 del_timer_sync(&smi_info->si_timer);
3044         }
3045 }
3046
3047 static __devinitdata struct ipmi_default_vals
3048 {
3049         int type;
3050         int port;
3051 } ipmi_defaults[] =
3052 {
3053         { .type = SI_KCS, .port = 0xca2 },
3054         { .type = SI_SMIC, .port = 0xca9 },
3055         { .type = SI_BT, .port = 0xe4 },
3056         { .port = 0 }
3057 };
3058
3059 static void __devinit default_find_bmc(void)
3060 {
3061         struct smi_info *info;
3062         int             i;
3063
3064         for (i = 0; ; i++) {
3065                 if (!ipmi_defaults[i].port)
3066                         break;
3067 #ifdef CONFIG_PPC
3068                 if (check_legacy_ioport(ipmi_defaults[i].port))
3069                         continue;
3070 #endif
3071                 info = smi_info_alloc();
3072                 if (!info)
3073                         return;
3074
3075                 info->addr_source = SI_DEFAULT;
3076
3077                 info->si_type = ipmi_defaults[i].type;
3078                 info->io_setup = port_setup;
3079                 info->io.addr_data = ipmi_defaults[i].port;
3080                 info->io.addr_type = IPMI_IO_ADDR_SPACE;
3081
3082                 info->io.addr = NULL;
3083                 info->io.regspacing = DEFAULT_REGSPACING;
3084                 info->io.regsize = DEFAULT_REGSPACING;
3085                 info->io.regshift = 0;
3086
3087                 if (add_smi(info) == 0) {
3088                         if ((try_smi_init(info)) == 0) {
3089                                 /* Found one... */
3090                                 printk(KERN_INFO PFX "Found default %s"
3091                                 " state machine at %s address 0x%lx\n",
3092                                 si_to_str[info->si_type],
3093                                 addr_space_to_str[info->io.addr_type],
3094                                 info->io.addr_data);
3095                         } else
3096                                 cleanup_one_si(info);
3097                 } else {
3098                         kfree(info);
3099                 }
3100         }
3101 }
3102
3103 static int is_new_interface(struct smi_info *info)
3104 {
3105         struct smi_info *e;
3106
3107         list_for_each_entry(e, &smi_infos, link) {
3108                 if (e->io.addr_type != info->io.addr_type)
3109                         continue;
3110                 if (e->io.addr_data == info->io.addr_data)
3111                         return 0;
3112         }
3113
3114         return 1;
3115 }
3116
3117 static int add_smi(struct smi_info *new_smi)
3118 {
3119         int rv = 0;
3120
3121         printk(KERN_INFO PFX "Adding %s-specified %s state machine",
3122                         ipmi_addr_src_to_str[new_smi->addr_source],
3123                         si_to_str[new_smi->si_type]);
3124         mutex_lock(&smi_infos_lock);
3125         if (!is_new_interface(new_smi)) {
3126                 printk(KERN_CONT " duplicate interface\n");
3127                 rv = -EBUSY;
3128                 goto out_err;
3129         }
3130
3131         printk(KERN_CONT "\n");
3132
3133         /* So we know not to free it unless we have allocated one. */
3134         new_smi->intf = NULL;
3135         new_smi->si_sm = NULL;
3136         new_smi->handlers = NULL;
3137
3138         list_add_tail(&new_smi->link, &smi_infos);
3139
3140 out_err:
3141         mutex_unlock(&smi_infos_lock);
3142         return rv;
3143 }
3144
3145 static int try_smi_init(struct smi_info *new_smi)
3146 {
3147         int rv = 0;
3148         int i;
3149
3150         printk(KERN_INFO PFX "Trying %s-specified %s state"
3151                " machine at %s address 0x%lx, slave address 0x%x,"
3152                " irq %d\n",
3153                ipmi_addr_src_to_str[new_smi->addr_source],
3154                si_to_str[new_smi->si_type],
3155                addr_space_to_str[new_smi->io.addr_type],
3156                new_smi->io.addr_data,
3157                new_smi->slave_addr, new_smi->irq);
3158
3159         switch (new_smi->si_type) {
3160         case SI_KCS:
3161                 new_smi->handlers = &kcs_smi_handlers;
3162                 break;
3163
3164         case SI_SMIC:
3165                 new_smi->handlers = &smic_smi_handlers;
3166                 break;
3167
3168         case SI_BT:
3169                 new_smi->handlers = &bt_smi_handlers;
3170                 break;
3171
3172         default:
3173                 /* No support for anything else yet. */
3174                 rv = -EIO;
3175                 goto out_err;
3176         }
3177
3178         /* Allocate the state machine's data and initialize it. */
3179         new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL);
3180         if (!new_smi->si_sm) {
3181                 printk(KERN_ERR PFX
3182                        "Could not allocate state machine memory\n");
3183                 rv = -ENOMEM;
3184                 goto out_err;
3185         }
3186         new_smi->io_size = new_smi->handlers->init_data(new_smi->si_sm,
3187                                                         &new_smi->io);
3188
3189         /* Now that we know the I/O size, we can set up the I/O. */
3190         rv = new_smi->io_setup(new_smi);
3191         if (rv) {
3192                 printk(KERN_ERR PFX "Could not set up I/O space\n");
3193                 goto out_err;
3194         }
3195
3196         /* Do low-level detection first. */
3197         if (new_smi->handlers->detect(new_smi->si_sm)) {
3198                 if (new_smi->addr_source)
3199                         printk(KERN_INFO PFX "Interface detection failed\n");
3200                 rv = -ENODEV;
3201                 goto out_err;
3202         }
3203
3204         /*
3205          * Attempt a get device id command.  If it fails, we probably
3206          * don't have a BMC here.
3207          */
3208         rv = try_get_dev_id(new_smi);
3209         if (rv) {
3210                 if (new_smi->addr_source)
3211                         printk(KERN_INFO PFX "There appears to be no BMC"
3212                                " at this location\n");
3213                 goto out_err;
3214         }
3215
3216         setup_oem_data_handler(new_smi);
3217         setup_xaction_handlers(new_smi);
3218
3219         INIT_LIST_HEAD(&(new_smi->xmit_msgs));
3220         INIT_LIST_HEAD(&(new_smi->hp_xmit_msgs));
3221         new_smi->curr_msg = NULL;
3222         atomic_set(&new_smi->req_events, 0);
3223         new_smi->run_to_completion = 0;
3224         for (i = 0; i < SI_NUM_STATS; i++)
3225                 atomic_set(&new_smi->stats[i], 0);
3226
3227         new_smi->interrupt_disabled = 1;
3228         atomic_set(&new_smi->stop_operation, 0);
3229         new_smi->intf_num = smi_num;
3230         smi_num++;
3231
3232         rv = try_enable_event_buffer(new_smi);
3233         if (rv == 0)
3234                 new_smi->has_event_buffer = 1;
3235
3236         /*
3237          * Start clearing the flags before we enable interrupts or the
3238          * timer to avoid racing with the timer.
3239          */
3240         start_clear_flags(new_smi);
3241         /* IRQ is defined to be set when non-zero. */
3242         if (new_smi->irq)
3243                 new_smi->si_state = SI_CLEARING_FLAGS_THEN_SET_IRQ;
3244
3245         if (!new_smi->dev) {
3246                 /*
3247                  * If we don't already have a device from something
3248                  * else (like PCI), then register a new one.
3249                  */
3250                 new_smi->pdev = platform_device_alloc("ipmi_si",
3251                                                       new_smi->intf_num);
3252                 if (!new_smi->pdev) {
3253                         printk(KERN_ERR PFX
3254                                "Unable to allocate platform device\n");
3255                         goto out_err;
3256                 }
3257                 new_smi->dev = &new_smi->pdev->dev;
3258                 new_smi->dev->driver = &ipmi_driver.driver;
3259
3260                 rv = platform_device_add(new_smi->pdev);
3261                 if (rv) {
3262                         printk(KERN_ERR PFX
3263                                "Unable to register system interface device:"
3264                                " %d\n",
3265                                rv);
3266                         goto out_err;
3267                 }
3268                 new_smi->dev_registered = 1;
3269         }
3270
3271         rv = ipmi_register_smi(&handlers,
3272                                new_smi,
3273                                &new_smi->device_id,
3274                                new_smi->dev,
3275                                "bmc",
3276                                new_smi->slave_addr);
3277         if (rv) {
3278                 dev_err(new_smi->dev, "Unable to register device: error %d\n",
3279                         rv);
3280                 goto out_err_stop_timer;
3281         }
3282
3283         rv = ipmi_smi_add_proc_entry(new_smi->intf, "type",
3284                                      &smi_type_proc_ops,
3285                                      new_smi);
3286         if (rv) {
3287                 dev_err(new_smi->dev, "Unable to create proc entry: %d\n", rv);
3288                 goto out_err_stop_timer;
3289         }
3290
3291         rv = ipmi_smi_add_proc_entry(new_smi->intf, "si_stats",
3292                                      &smi_si_stats_proc_ops,
3293                                      new_smi);
3294         if (rv) {
3295                 dev_err(new_smi->dev, "Unable to create proc entry: %d\n", rv);
3296                 goto out_err_stop_timer;
3297         }
3298
3299         rv = ipmi_smi_add_proc_entry(new_smi->intf, "params",
3300                                      &smi_params_proc_ops,
3301                                      new_smi);
3302         if (rv) {
3303                 dev_err(new_smi->dev, "Unable to create proc entry: %d\n", rv);
3304                 goto out_err_stop_timer;
3305         }
3306
3307         dev_info(new_smi->dev, "IPMI %s interface initialized\n",
3308                  si_to_str[new_smi->si_type]);
3309
3310         return 0;
3311
3312  out_err_stop_timer:
3313         atomic_inc(&new_smi->stop_operation);
3314         wait_for_timer_and_thread(new_smi);
3315
3316  out_err:
3317         new_smi->interrupt_disabled = 1;
3318
3319         if (new_smi->intf) {
3320                 ipmi_unregister_smi(new_smi->intf);
3321                 new_smi->intf = NULL;
3322         }
3323
3324         if (new_smi->irq_cleanup) {
3325                 new_smi->irq_cleanup(new_smi);
3326                 new_smi->irq_cleanup = NULL;
3327         }
3328
3329         /*
3330          * Wait until we know that we are out of any interrupt
3331          * handlers might have been running before we freed the
3332          * interrupt.
3333          */
3334         synchronize_sched();
3335
3336         if (new_smi->si_sm) {
3337                 if (new_smi->handlers)
3338                         new_smi->handlers->cleanup(new_smi->si_sm);
3339                 kfree(new_smi->si_sm);
3340                 new_smi->si_sm = NULL;
3341         }
3342         if (new_smi->addr_source_cleanup) {
3343                 new_smi->addr_source_cleanup(new_smi);
3344                 new_smi->addr_source_cleanup = NULL;
3345         }
3346         if (new_smi->io_cleanup) {
3347                 new_smi->io_cleanup(new_smi);
3348                 new_smi->io_cleanup = NULL;
3349         }
3350
3351         if (new_smi->dev_registered) {
3352                 platform_device_unregister(new_smi->pdev);
3353                 new_smi->dev_registered = 0;
3354         }
3355
3356         return rv;
3357 }
3358
3359 static int __devinit init_ipmi_si(void)
3360 {
3361         int  i;
3362         char *str;
3363         int  rv;
3364         struct smi_info *e;
3365         enum ipmi_addr_src type = SI_INVALID;
3366
3367         if (initialized)
3368                 return 0;
3369         initialized = 1;
3370
3371         rv = platform_driver_register(&ipmi_driver);
3372         if (rv) {
3373                 printk(KERN_ERR PFX "Unable to register driver: %d\n", rv);
3374                 return rv;
3375         }
3376
3377
3378         /* Parse out the si_type string into its components. */
3379         str = si_type_str;
3380         if (*str != '\0') {
3381                 for (i = 0; (i < SI_MAX_PARMS) && (*str != '\0'); i++) {
3382                         si_type[i] = str;
3383                         str = strchr(str, ',');
3384                         if (str) {
3385                                 *str = '\0';
3386                                 str++;
3387                         } else {
3388                                 break;
3389                         }
3390                 }
3391         }
3392
3393         printk(KERN_INFO "IPMI System Interface driver.\n");
3394
3395         /* If the user gave us a device, they presumably want us to use it */
3396         if (!hardcode_find_bmc())
3397                 return 0;
3398
3399 #ifdef CONFIG_PCI
3400         rv = pci_register_driver(&ipmi_pci_driver);
3401         if (rv)
3402                 printk(KERN_ERR PFX "Unable to register PCI driver: %d\n", rv);
3403         else
3404                 pci_registered = 1;
3405 #endif
3406
3407 #ifdef CONFIG_ACPI
3408         pnp_register_driver(&ipmi_pnp_driver);
3409         pnp_registered = 1;
3410 #endif
3411
3412 #ifdef CONFIG_DMI
3413         dmi_find_bmc();
3414 #endif
3415
3416 #ifdef CONFIG_ACPI
3417         spmi_find_bmc();
3418 #endif
3419
3420         /* We prefer devices with interrupts, but in the case of a machine
3421            with multiple BMCs we assume that there will be several instances
3422            of a given type so if we succeed in registering a type then also
3423            try to register everything else of the same type */
3424
3425         mutex_lock(&smi_infos_lock);
3426         list_for_each_entry(e, &smi_infos, link) {
3427                 /* Try to register a device if it has an IRQ and we either
3428                    haven't successfully registered a device yet or this
3429                    device has the same type as one we successfully registered */
3430                 if (e->irq && (!type || e->addr_source == type)) {
3431                         if (!try_smi_init(e)) {
3432                                 type = e->addr_source;
3433                         }
3434                 }
3435         }
3436
3437         /* type will only have been set if we successfully registered an si */
3438         if (type) {
3439                 mutex_unlock(&smi_infos_lock);
3440                 return 0;
3441         }
3442
3443         /* Fall back to the preferred device */
3444
3445         list_for_each_entry(e, &smi_infos, link) {
3446                 if (!e->irq && (!type || e->addr_source == type)) {
3447                         if (!try_smi_init(e)) {
3448                                 type = e->addr_source;
3449                         }
3450                 }
3451         }
3452         mutex_unlock(&smi_infos_lock);
3453
3454         if (type)
3455                 return 0;
3456
3457         if (si_trydefaults) {
3458                 mutex_lock(&smi_infos_lock);
3459                 if (list_empty(&smi_infos)) {
3460                         /* No BMC was found, try defaults. */
3461                         mutex_unlock(&smi_infos_lock);
3462                         default_find_bmc();
3463                 } else
3464                         mutex_unlock(&smi_infos_lock);
3465         }
3466
3467         mutex_lock(&smi_infos_lock);
3468         if (unload_when_empty && list_empty(&smi_infos)) {
3469                 mutex_unlock(&smi_infos_lock);
3470                 cleanup_ipmi_si();
3471                 printk(KERN_WARNING PFX
3472                        "Unable to find any System Interface(s)\n");
3473                 return -ENODEV;
3474         } else {
3475                 mutex_unlock(&smi_infos_lock);
3476                 return 0;
3477         }
3478 }
3479 module_init(init_ipmi_si);
3480
3481 static void cleanup_one_si(struct smi_info *to_clean)
3482 {
3483         int           rv = 0;
3484         unsigned long flags;
3485
3486         if (!to_clean)
3487                 return;
3488
3489         list_del(&to_clean->link);
3490
3491         /* Tell the driver that we are shutting down. */
3492         atomic_inc(&to_clean->stop_operation);
3493
3494         /*
3495          * Make sure the timer and thread are stopped and will not run
3496          * again.
3497          */
3498         wait_for_timer_and_thread(to_clean);
3499
3500         /*
3501          * Timeouts are stopped, now make sure the interrupts are off
3502          * for the device.  A little tricky with locks to make sure
3503          * there are no races.
3504          */
3505         spin_lock_irqsave(&to_clean->si_lock, flags);
3506         while (to_clean->curr_msg || (to_clean->si_state != SI_NORMAL)) {
3507                 spin_unlock_irqrestore(&to_clean->si_lock, flags);
3508                 poll(to_clean);
3509                 schedule_timeout_uninterruptible(1);
3510                 spin_lock_irqsave(&to_clean->si_lock, flags);
3511         }
3512         disable_si_irq(to_clean);
3513         spin_unlock_irqrestore(&to_clean->si_lock, flags);
3514         while (to_clean->curr_msg || (to_clean->si_state != SI_NORMAL)) {
3515                 poll(to_clean);
3516                 schedule_timeout_uninterruptible(1);
3517         }
3518
3519         /* Clean up interrupts and make sure that everything is done. */
3520         if (to_clean->irq_cleanup)
3521                 to_clean->irq_cleanup(to_clean);
3522         while (to_clean->curr_msg || (to_clean->si_state != SI_NORMAL)) {
3523                 poll(to_clean);
3524                 schedule_timeout_uninterruptible(1);
3525         }
3526
3527         if (to_clean->intf)
3528                 rv = ipmi_unregister_smi(to_clean->intf);
3529
3530         if (rv) {
3531                 printk(KERN_ERR PFX "Unable to unregister device: errno=%d\n",
3532                        rv);
3533         }
3534
3535         if (to_clean->handlers)
3536                 to_clean->handlers->cleanup(to_clean->si_sm);
3537
3538         kfree(to_clean->si_sm);
3539
3540         if (to_clean->addr_source_cleanup)
3541                 to_clean->addr_source_cleanup(to_clean);
3542         if (to_clean->io_cleanup)
3543                 to_clean->io_cleanup(to_clean);
3544
3545         if (to_clean->dev_registered)
3546                 platform_device_unregister(to_clean->pdev);
3547
3548         kfree(to_clean);
3549 }
3550
3551 static void cleanup_ipmi_si(void)
3552 {
3553         struct smi_info *e, *tmp_e;
3554
3555         if (!initialized)
3556                 return;
3557
3558 #ifdef CONFIG_PCI
3559         if (pci_registered)
3560                 pci_unregister_driver(&ipmi_pci_driver);
3561 #endif
3562 #ifdef CONFIG_ACPI
3563         if (pnp_registered)
3564                 pnp_unregister_driver(&ipmi_pnp_driver);
3565 #endif
3566
3567         platform_driver_unregister(&ipmi_driver);
3568
3569         mutex_lock(&smi_infos_lock);
3570         list_for_each_entry_safe(e, tmp_e, &smi_infos, link)
3571                 cleanup_one_si(e);
3572         mutex_unlock(&smi_infos_lock);
3573 }
3574 module_exit(cleanup_ipmi_si);
3575
3576 MODULE_LICENSE("GPL");
3577 MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
3578 MODULE_DESCRIPTION("Interface to the IPMI driver for the KCS, SMIC, and BT"
3579                    " system interfaces.");