Merge master.kernel.org:/home/rmk/linux-2.6-serial
[pandora-kernel.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  *
13  *  This program is free software; you can redistribute it and/or modify it
14  *  under the terms of the GNU General Public License as published by the
15  *  Free Software Foundation; either version 2 of the License, or (at your
16  *  option) any later version.
17  *
18  *
19  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
20  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24  *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
25  *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
27  *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
28  *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  *  You should have received a copy of the GNU General Public License along
31  *  with this program; if not, write to the Free Software Foundation, Inc.,
32  *  675 Mass Ave, Cambridge, MA 02139, USA.
33  */
34
35 /*
36  * This file holds the "policy" for the interface to the SMI state
37  * machine.  It does the configuration, handles timers and interrupts,
38  * and drives the real SMI state machine.
39  */
40
41 #include <linux/config.h>
42 #include <linux/module.h>
43 #include <linux/moduleparam.h>
44 #include <asm/system.h>
45 #include <linux/sched.h>
46 #include <linux/timer.h>
47 #include <linux/errno.h>
48 #include <linux/spinlock.h>
49 #include <linux/slab.h>
50 #include <linux/delay.h>
51 #include <linux/list.h>
52 #include <linux/pci.h>
53 #include <linux/ioport.h>
54 #include <linux/notifier.h>
55 #include <linux/kthread.h>
56 #include <asm/irq.h>
57 #ifdef CONFIG_HIGH_RES_TIMERS
58 #include <linux/hrtime.h>
59 # if defined(schedule_next_int)
60 /* Old high-res timer code, do translations. */
61 #  define get_arch_cycles(a) quick_update_jiffies_sub(a)
62 #  define arch_cycles_per_jiffy cycles_per_jiffies
63 # endif
64 static inline void add_usec_to_timer(struct timer_list *t, long v)
65 {
66         t->arch_cycle_expires += nsec_to_arch_cycle(v * 1000);
67         while (t->arch_cycle_expires >= arch_cycles_per_jiffy)
68         {
69                 t->expires++;
70                 t->arch_cycle_expires -= arch_cycles_per_jiffy;
71         }
72 }
73 #endif
74 #include <linux/interrupt.h>
75 #include <linux/rcupdate.h>
76 #include <linux/ipmi_smi.h>
77 #include <asm/io.h>
78 #include "ipmi_si_sm.h"
79 #include <linux/init.h>
80 #include <linux/dmi.h>
81
82 /* Measure times between events in the driver. */
83 #undef DEBUG_TIMING
84
85 /* Call every 10 ms. */
86 #define SI_TIMEOUT_TIME_USEC    10000
87 #define SI_USEC_PER_JIFFY       (1000000/HZ)
88 #define SI_TIMEOUT_JIFFIES      (SI_TIMEOUT_TIME_USEC/SI_USEC_PER_JIFFY)
89 #define SI_SHORT_TIMEOUT_USEC  250 /* .25ms when the SM request a
90                                        short timeout */
91
92 enum si_intf_state {
93         SI_NORMAL,
94         SI_GETTING_FLAGS,
95         SI_GETTING_EVENTS,
96         SI_CLEARING_FLAGS,
97         SI_CLEARING_FLAGS_THEN_SET_IRQ,
98         SI_GETTING_MESSAGES,
99         SI_ENABLE_INTERRUPTS1,
100         SI_ENABLE_INTERRUPTS2
101         /* FIXME - add watchdog stuff. */
102 };
103
104 /* Some BT-specific defines we need here. */
105 #define IPMI_BT_INTMASK_REG             2
106 #define IPMI_BT_INTMASK_CLEAR_IRQ_BIT   2
107 #define IPMI_BT_INTMASK_ENABLE_IRQ_BIT  1
108
109 enum si_type {
110     SI_KCS, SI_SMIC, SI_BT
111 };
112
113 struct ipmi_device_id {
114         unsigned char device_id;
115         unsigned char device_revision;
116         unsigned char firmware_revision_1;
117         unsigned char firmware_revision_2;
118         unsigned char ipmi_version;
119         unsigned char additional_device_support;
120         unsigned char manufacturer_id[3];
121         unsigned char product_id[2];
122         unsigned char aux_firmware_revision[4];
123 } __attribute__((packed));
124
125 #define ipmi_version_major(v) ((v)->ipmi_version & 0xf)
126 #define ipmi_version_minor(v) ((v)->ipmi_version >> 4)
127
128 struct smi_info
129 {
130         int                    intf_num;
131         ipmi_smi_t             intf;
132         struct si_sm_data      *si_sm;
133         struct si_sm_handlers  *handlers;
134         enum si_type           si_type;
135         spinlock_t             si_lock;
136         spinlock_t             msg_lock;
137         struct list_head       xmit_msgs;
138         struct list_head       hp_xmit_msgs;
139         struct ipmi_smi_msg    *curr_msg;
140         enum si_intf_state     si_state;
141
142         /* Used to handle the various types of I/O that can occur with
143            IPMI */
144         struct si_sm_io io;
145         int (*io_setup)(struct smi_info *info);
146         void (*io_cleanup)(struct smi_info *info);
147         int (*irq_setup)(struct smi_info *info);
148         void (*irq_cleanup)(struct smi_info *info);
149         unsigned int io_size;
150
151         /* Per-OEM handler, called from handle_flags().
152            Returns 1 when handle_flags() needs to be re-run
153            or 0 indicating it set si_state itself.
154         */
155         int (*oem_data_avail_handler)(struct smi_info *smi_info);
156
157         /* Flags from the last GET_MSG_FLAGS command, used when an ATTN
158            is set to hold the flags until we are done handling everything
159            from the flags. */
160 #define RECEIVE_MSG_AVAIL       0x01
161 #define EVENT_MSG_BUFFER_FULL   0x02
162 #define WDT_PRE_TIMEOUT_INT     0x08
163 #define OEM0_DATA_AVAIL     0x20
164 #define OEM1_DATA_AVAIL     0x40
165 #define OEM2_DATA_AVAIL     0x80
166 #define OEM_DATA_AVAIL      (OEM0_DATA_AVAIL | \
167                              OEM1_DATA_AVAIL | \
168                              OEM2_DATA_AVAIL)
169         unsigned char       msg_flags;
170
171         /* If set to true, this will request events the next time the
172            state machine is idle. */
173         atomic_t            req_events;
174
175         /* If true, run the state machine to completion on every send
176            call.  Generally used after a panic to make sure stuff goes
177            out. */
178         int                 run_to_completion;
179
180         /* The I/O port of an SI interface. */
181         int                 port;
182
183         /* The space between start addresses of the two ports.  For
184            instance, if the first port is 0xca2 and the spacing is 4, then
185            the second port is 0xca6. */
186         unsigned int        spacing;
187
188         /* zero if no irq; */
189         int                 irq;
190
191         /* The timer for this si. */
192         struct timer_list   si_timer;
193
194         /* The time (in jiffies) the last timeout occurred at. */
195         unsigned long       last_timeout_jiffies;
196
197         /* Used to gracefully stop the timer without race conditions. */
198         atomic_t            stop_operation;
199
200         /* The driver will disable interrupts when it gets into a
201            situation where it cannot handle messages due to lack of
202            memory.  Once that situation clears up, it will re-enable
203            interrupts. */
204         int interrupt_disabled;
205
206         struct ipmi_device_id device_id;
207
208         /* Slave address, could be reported from DMI. */
209         unsigned char slave_addr;
210
211         /* Counters and things for the proc filesystem. */
212         spinlock_t count_lock;
213         unsigned long short_timeouts;
214         unsigned long long_timeouts;
215         unsigned long timeout_restarts;
216         unsigned long idles;
217         unsigned long interrupts;
218         unsigned long attentions;
219         unsigned long flag_fetches;
220         unsigned long hosed_count;
221         unsigned long complete_transactions;
222         unsigned long events;
223         unsigned long watchdog_pretimeouts;
224         unsigned long incoming_messages;
225
226         struct task_struct *thread;
227 };
228
229 static struct notifier_block *xaction_notifier_list;
230 static int register_xaction_notifier(struct notifier_block * nb)
231 {
232         return notifier_chain_register(&xaction_notifier_list, nb);
233 }
234
235 static void si_restart_short_timer(struct smi_info *smi_info);
236
237 static void deliver_recv_msg(struct smi_info *smi_info,
238                              struct ipmi_smi_msg *msg)
239 {
240         /* Deliver the message to the upper layer with the lock
241            released. */
242         spin_unlock(&(smi_info->si_lock));
243         ipmi_smi_msg_received(smi_info->intf, msg);
244         spin_lock(&(smi_info->si_lock));
245 }
246
247 static void return_hosed_msg(struct smi_info *smi_info)
248 {
249         struct ipmi_smi_msg *msg = smi_info->curr_msg;
250
251         /* Make it a reponse */
252         msg->rsp[0] = msg->data[0] | 4;
253         msg->rsp[1] = msg->data[1];
254         msg->rsp[2] = 0xFF; /* Unknown error. */
255         msg->rsp_size = 3;
256
257         smi_info->curr_msg = NULL;
258         deliver_recv_msg(smi_info, msg);
259 }
260
261 static enum si_sm_result start_next_msg(struct smi_info *smi_info)
262 {
263         int              rv;
264         struct list_head *entry = NULL;
265 #ifdef DEBUG_TIMING
266         struct timeval t;
267 #endif
268
269         /* No need to save flags, we aleady have interrupts off and we
270            already hold the SMI lock. */
271         spin_lock(&(smi_info->msg_lock));
272
273         /* Pick the high priority queue first. */
274         if (! list_empty(&(smi_info->hp_xmit_msgs))) {
275                 entry = smi_info->hp_xmit_msgs.next;
276         } else if (! list_empty(&(smi_info->xmit_msgs))) {
277                 entry = smi_info->xmit_msgs.next;
278         }
279
280         if (! entry) {
281                 smi_info->curr_msg = NULL;
282                 rv = SI_SM_IDLE;
283         } else {
284                 int err;
285
286                 list_del(entry);
287                 smi_info->curr_msg = list_entry(entry,
288                                                 struct ipmi_smi_msg,
289                                                 link);
290 #ifdef DEBUG_TIMING
291                 do_gettimeofday(&t);
292                 printk("**Start2: %d.%9.9d\n", t.tv_sec, t.tv_usec);
293 #endif
294                 err = notifier_call_chain(&xaction_notifier_list, 0, smi_info);
295                 if (err & NOTIFY_STOP_MASK) {
296                         rv = SI_SM_CALL_WITHOUT_DELAY;
297                         goto out;
298                 }
299                 err = smi_info->handlers->start_transaction(
300                         smi_info->si_sm,
301                         smi_info->curr_msg->data,
302                         smi_info->curr_msg->data_size);
303                 if (err) {
304                         return_hosed_msg(smi_info);
305                 }
306
307                 rv = SI_SM_CALL_WITHOUT_DELAY;
308         }
309         out:
310         spin_unlock(&(smi_info->msg_lock));
311
312         return rv;
313 }
314
315 static void start_enable_irq(struct smi_info *smi_info)
316 {
317         unsigned char msg[2];
318
319         /* If we are enabling interrupts, we have to tell the
320            BMC to use them. */
321         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
322         msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
323
324         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
325         smi_info->si_state = SI_ENABLE_INTERRUPTS1;
326 }
327
328 static void start_clear_flags(struct smi_info *smi_info)
329 {
330         unsigned char msg[3];
331
332         /* Make sure the watchdog pre-timeout flag is not set at startup. */
333         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
334         msg[1] = IPMI_CLEAR_MSG_FLAGS_CMD;
335         msg[2] = WDT_PRE_TIMEOUT_INT;
336
337         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 3);
338         smi_info->si_state = SI_CLEARING_FLAGS;
339 }
340
341 /* When we have a situtaion where we run out of memory and cannot
342    allocate messages, we just leave them in the BMC and run the system
343    polled until we can allocate some memory.  Once we have some
344    memory, we will re-enable the interrupt. */
345 static inline void disable_si_irq(struct smi_info *smi_info)
346 {
347         if ((smi_info->irq) && (! smi_info->interrupt_disabled)) {
348                 disable_irq_nosync(smi_info->irq);
349                 smi_info->interrupt_disabled = 1;
350         }
351 }
352
353 static inline void enable_si_irq(struct smi_info *smi_info)
354 {
355         if ((smi_info->irq) && (smi_info->interrupt_disabled)) {
356                 enable_irq(smi_info->irq);
357                 smi_info->interrupt_disabled = 0;
358         }
359 }
360
361 static void handle_flags(struct smi_info *smi_info)
362 {
363  retry:
364         if (smi_info->msg_flags & WDT_PRE_TIMEOUT_INT) {
365                 /* Watchdog pre-timeout */
366                 spin_lock(&smi_info->count_lock);
367                 smi_info->watchdog_pretimeouts++;
368                 spin_unlock(&smi_info->count_lock);
369
370                 start_clear_flags(smi_info);
371                 smi_info->msg_flags &= ~WDT_PRE_TIMEOUT_INT;
372                 spin_unlock(&(smi_info->si_lock));
373                 ipmi_smi_watchdog_pretimeout(smi_info->intf);
374                 spin_lock(&(smi_info->si_lock));
375         } else if (smi_info->msg_flags & RECEIVE_MSG_AVAIL) {
376                 /* Messages available. */
377                 smi_info->curr_msg = ipmi_alloc_smi_msg();
378                 if (! smi_info->curr_msg) {
379                         disable_si_irq(smi_info);
380                         smi_info->si_state = SI_NORMAL;
381                         return;
382                 }
383                 enable_si_irq(smi_info);
384
385                 smi_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
386                 smi_info->curr_msg->data[1] = IPMI_GET_MSG_CMD;
387                 smi_info->curr_msg->data_size = 2;
388
389                 smi_info->handlers->start_transaction(
390                         smi_info->si_sm,
391                         smi_info->curr_msg->data,
392                         smi_info->curr_msg->data_size);
393                 smi_info->si_state = SI_GETTING_MESSAGES;
394         } else if (smi_info->msg_flags & EVENT_MSG_BUFFER_FULL) {
395                 /* Events available. */
396                 smi_info->curr_msg = ipmi_alloc_smi_msg();
397                 if (! smi_info->curr_msg) {
398                         disable_si_irq(smi_info);
399                         smi_info->si_state = SI_NORMAL;
400                         return;
401                 }
402                 enable_si_irq(smi_info);
403
404                 smi_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
405                 smi_info->curr_msg->data[1] = IPMI_READ_EVENT_MSG_BUFFER_CMD;
406                 smi_info->curr_msg->data_size = 2;
407
408                 smi_info->handlers->start_transaction(
409                         smi_info->si_sm,
410                         smi_info->curr_msg->data,
411                         smi_info->curr_msg->data_size);
412                 smi_info->si_state = SI_GETTING_EVENTS;
413         } else if (smi_info->msg_flags & OEM_DATA_AVAIL) {
414                 if (smi_info->oem_data_avail_handler)
415                         if (smi_info->oem_data_avail_handler(smi_info))
416                                 goto retry;
417         } else {
418                 smi_info->si_state = SI_NORMAL;
419         }
420 }
421
422 static void handle_transaction_done(struct smi_info *smi_info)
423 {
424         struct ipmi_smi_msg *msg;
425 #ifdef DEBUG_TIMING
426         struct timeval t;
427
428         do_gettimeofday(&t);
429         printk("**Done: %d.%9.9d\n", t.tv_sec, t.tv_usec);
430 #endif
431         switch (smi_info->si_state) {
432         case SI_NORMAL:
433                 if (! smi_info->curr_msg)
434                         break;
435
436                 smi_info->curr_msg->rsp_size
437                         = smi_info->handlers->get_result(
438                                 smi_info->si_sm,
439                                 smi_info->curr_msg->rsp,
440                                 IPMI_MAX_MSG_LENGTH);
441
442                 /* Do this here becase deliver_recv_msg() releases the
443                    lock, and a new message can be put in during the
444                    time the lock is released. */
445                 msg = smi_info->curr_msg;
446                 smi_info->curr_msg = NULL;
447                 deliver_recv_msg(smi_info, msg);
448                 break;
449
450         case SI_GETTING_FLAGS:
451         {
452                 unsigned char msg[4];
453                 unsigned int  len;
454
455                 /* We got the flags from the SMI, now handle them. */
456                 len = smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
457                 if (msg[2] != 0) {
458                         /* Error fetching flags, just give up for
459                            now. */
460                         smi_info->si_state = SI_NORMAL;
461                 } else if (len < 4) {
462                         /* Hmm, no flags.  That's technically illegal, but
463                            don't use uninitialized data. */
464                         smi_info->si_state = SI_NORMAL;
465                 } else {
466                         smi_info->msg_flags = msg[3];
467                         handle_flags(smi_info);
468                 }
469                 break;
470         }
471
472         case SI_CLEARING_FLAGS:
473         case SI_CLEARING_FLAGS_THEN_SET_IRQ:
474         {
475                 unsigned char msg[3];
476
477                 /* We cleared the flags. */
478                 smi_info->handlers->get_result(smi_info->si_sm, msg, 3);
479                 if (msg[2] != 0) {
480                         /* Error clearing flags */
481                         printk(KERN_WARNING
482                                "ipmi_si: Error clearing flags: %2.2x\n",
483                                msg[2]);
484                 }
485                 if (smi_info->si_state == SI_CLEARING_FLAGS_THEN_SET_IRQ)
486                         start_enable_irq(smi_info);
487                 else
488                         smi_info->si_state = SI_NORMAL;
489                 break;
490         }
491
492         case SI_GETTING_EVENTS:
493         {
494                 smi_info->curr_msg->rsp_size
495                         = smi_info->handlers->get_result(
496                                 smi_info->si_sm,
497                                 smi_info->curr_msg->rsp,
498                                 IPMI_MAX_MSG_LENGTH);
499
500                 /* Do this here becase deliver_recv_msg() releases the
501                    lock, and a new message can be put in during the
502                    time the lock is released. */
503                 msg = smi_info->curr_msg;
504                 smi_info->curr_msg = NULL;
505                 if (msg->rsp[2] != 0) {
506                         /* Error getting event, probably done. */
507                         msg->done(msg);
508
509                         /* Take off the event flag. */
510                         smi_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
511                         handle_flags(smi_info);
512                 } else {
513                         spin_lock(&smi_info->count_lock);
514                         smi_info->events++;
515                         spin_unlock(&smi_info->count_lock);
516
517                         /* Do this before we deliver the message
518                            because delivering the message releases the
519                            lock and something else can mess with the
520                            state. */
521                         handle_flags(smi_info);
522
523                         deliver_recv_msg(smi_info, msg);
524                 }
525                 break;
526         }
527
528         case SI_GETTING_MESSAGES:
529         {
530                 smi_info->curr_msg->rsp_size
531                         = smi_info->handlers->get_result(
532                                 smi_info->si_sm,
533                                 smi_info->curr_msg->rsp,
534                                 IPMI_MAX_MSG_LENGTH);
535
536                 /* Do this here becase deliver_recv_msg() releases the
537                    lock, and a new message can be put in during the
538                    time the lock is released. */
539                 msg = smi_info->curr_msg;
540                 smi_info->curr_msg = NULL;
541                 if (msg->rsp[2] != 0) {
542                         /* Error getting event, probably done. */
543                         msg->done(msg);
544
545                         /* Take off the msg flag. */
546                         smi_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
547                         handle_flags(smi_info);
548                 } else {
549                         spin_lock(&smi_info->count_lock);
550                         smi_info->incoming_messages++;
551                         spin_unlock(&smi_info->count_lock);
552
553                         /* Do this before we deliver the message
554                            because delivering the message releases the
555                            lock and something else can mess with the
556                            state. */
557                         handle_flags(smi_info);
558
559                         deliver_recv_msg(smi_info, msg);
560                 }
561                 break;
562         }
563
564         case SI_ENABLE_INTERRUPTS1:
565         {
566                 unsigned char msg[4];
567
568                 /* We got the flags from the SMI, now handle them. */
569                 smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
570                 if (msg[2] != 0) {
571                         printk(KERN_WARNING
572                                "ipmi_si: Could not enable interrupts"
573                                ", failed get, using polled mode.\n");
574                         smi_info->si_state = SI_NORMAL;
575                 } else {
576                         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
577                         msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
578                         msg[2] = msg[3] | 1; /* enable msg queue int */
579                         smi_info->handlers->start_transaction(
580                                 smi_info->si_sm, msg, 3);
581                         smi_info->si_state = SI_ENABLE_INTERRUPTS2;
582                 }
583                 break;
584         }
585
586         case SI_ENABLE_INTERRUPTS2:
587         {
588                 unsigned char msg[4];
589
590                 /* We got the flags from the SMI, now handle them. */
591                 smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
592                 if (msg[2] != 0) {
593                         printk(KERN_WARNING
594                                "ipmi_si: Could not enable interrupts"
595                                ", failed set, using polled mode.\n");
596                 }
597                 smi_info->si_state = SI_NORMAL;
598                 break;
599         }
600         }
601 }
602
603 /* Called on timeouts and events.  Timeouts should pass the elapsed
604    time, interrupts should pass in zero. */
605 static enum si_sm_result smi_event_handler(struct smi_info *smi_info,
606                                            int time)
607 {
608         enum si_sm_result si_sm_result;
609
610  restart:
611         /* There used to be a loop here that waited a little while
612            (around 25us) before giving up.  That turned out to be
613            pointless, the minimum delays I was seeing were in the 300us
614            range, which is far too long to wait in an interrupt.  So
615            we just run until the state machine tells us something
616            happened or it needs a delay. */
617         si_sm_result = smi_info->handlers->event(smi_info->si_sm, time);
618         time = 0;
619         while (si_sm_result == SI_SM_CALL_WITHOUT_DELAY)
620         {
621                 si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
622         }
623
624         if (si_sm_result == SI_SM_TRANSACTION_COMPLETE)
625         {
626                 spin_lock(&smi_info->count_lock);
627                 smi_info->complete_transactions++;
628                 spin_unlock(&smi_info->count_lock);
629
630                 handle_transaction_done(smi_info);
631                 si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
632         }
633         else if (si_sm_result == SI_SM_HOSED)
634         {
635                 spin_lock(&smi_info->count_lock);
636                 smi_info->hosed_count++;
637                 spin_unlock(&smi_info->count_lock);
638
639                 /* Do the before return_hosed_msg, because that
640                    releases the lock. */
641                 smi_info->si_state = SI_NORMAL;
642                 if (smi_info->curr_msg != NULL) {
643                         /* If we were handling a user message, format
644                            a response to send to the upper layer to
645                            tell it about the error. */
646                         return_hosed_msg(smi_info);
647                 }
648                 si_sm_result = smi_info->handlers->event(smi_info->si_sm, 0);
649         }
650
651         /* We prefer handling attn over new messages. */
652         if (si_sm_result == SI_SM_ATTN)
653         {
654                 unsigned char msg[2];
655
656                 spin_lock(&smi_info->count_lock);
657                 smi_info->attentions++;
658                 spin_unlock(&smi_info->count_lock);
659
660                 /* Got a attn, send down a get message flags to see
661                    what's causing it.  It would be better to handle
662                    this in the upper layer, but due to the way
663                    interrupts work with the SMI, that's not really
664                    possible. */
665                 msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
666                 msg[1] = IPMI_GET_MSG_FLAGS_CMD;
667
668                 smi_info->handlers->start_transaction(
669                         smi_info->si_sm, msg, 2);
670                 smi_info->si_state = SI_GETTING_FLAGS;
671                 goto restart;
672         }
673
674         /* If we are currently idle, try to start the next message. */
675         if (si_sm_result == SI_SM_IDLE) {
676                 spin_lock(&smi_info->count_lock);
677                 smi_info->idles++;
678                 spin_unlock(&smi_info->count_lock);
679
680                 si_sm_result = start_next_msg(smi_info);
681                 if (si_sm_result != SI_SM_IDLE)
682                         goto restart;
683         }
684
685         if ((si_sm_result == SI_SM_IDLE)
686             && (atomic_read(&smi_info->req_events)))
687         {
688                 /* We are idle and the upper layer requested that I fetch
689                    events, so do so. */
690                 unsigned char msg[2];
691
692                 spin_lock(&smi_info->count_lock);
693                 smi_info->flag_fetches++;
694                 spin_unlock(&smi_info->count_lock);
695
696                 atomic_set(&smi_info->req_events, 0);
697                 msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
698                 msg[1] = IPMI_GET_MSG_FLAGS_CMD;
699
700                 smi_info->handlers->start_transaction(
701                         smi_info->si_sm, msg, 2);
702                 smi_info->si_state = SI_GETTING_FLAGS;
703                 goto restart;
704         }
705
706         return si_sm_result;
707 }
708
709 static void sender(void                *send_info,
710                    struct ipmi_smi_msg *msg,
711                    int                 priority)
712 {
713         struct smi_info   *smi_info = send_info;
714         enum si_sm_result result;
715         unsigned long     flags;
716 #ifdef DEBUG_TIMING
717         struct timeval    t;
718 #endif
719
720         spin_lock_irqsave(&(smi_info->msg_lock), flags);
721 #ifdef DEBUG_TIMING
722         do_gettimeofday(&t);
723         printk("**Enqueue: %d.%9.9d\n", t.tv_sec, t.tv_usec);
724 #endif
725
726         if (smi_info->run_to_completion) {
727                 /* If we are running to completion, then throw it in
728                    the list and run transactions until everything is
729                    clear.  Priority doesn't matter here. */
730                 list_add_tail(&(msg->link), &(smi_info->xmit_msgs));
731
732                 /* We have to release the msg lock and claim the smi
733                    lock in this case, because of race conditions. */
734                 spin_unlock_irqrestore(&(smi_info->msg_lock), flags);
735
736                 spin_lock_irqsave(&(smi_info->si_lock), flags);
737                 result = smi_event_handler(smi_info, 0);
738                 while (result != SI_SM_IDLE) {
739                         udelay(SI_SHORT_TIMEOUT_USEC);
740                         result = smi_event_handler(smi_info,
741                                                    SI_SHORT_TIMEOUT_USEC);
742                 }
743                 spin_unlock_irqrestore(&(smi_info->si_lock), flags);
744                 return;
745         } else {
746                 if (priority > 0) {
747                         list_add_tail(&(msg->link), &(smi_info->hp_xmit_msgs));
748                 } else {
749                         list_add_tail(&(msg->link), &(smi_info->xmit_msgs));
750                 }
751         }
752         spin_unlock_irqrestore(&(smi_info->msg_lock), flags);
753
754         spin_lock_irqsave(&(smi_info->si_lock), flags);
755         if ((smi_info->si_state == SI_NORMAL)
756             && (smi_info->curr_msg == NULL))
757         {
758                 start_next_msg(smi_info);
759                 si_restart_short_timer(smi_info);
760         }
761         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
762 }
763
764 static void set_run_to_completion(void *send_info, int i_run_to_completion)
765 {
766         struct smi_info   *smi_info = send_info;
767         enum si_sm_result result;
768         unsigned long     flags;
769
770         spin_lock_irqsave(&(smi_info->si_lock), flags);
771
772         smi_info->run_to_completion = i_run_to_completion;
773         if (i_run_to_completion) {
774                 result = smi_event_handler(smi_info, 0);
775                 while (result != SI_SM_IDLE) {
776                         udelay(SI_SHORT_TIMEOUT_USEC);
777                         result = smi_event_handler(smi_info,
778                                                    SI_SHORT_TIMEOUT_USEC);
779                 }
780         }
781
782         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
783 }
784
785 static int ipmi_thread(void *data)
786 {
787         struct smi_info *smi_info = data;
788         unsigned long flags;
789         enum si_sm_result smi_result;
790
791         set_user_nice(current, 19);
792         while (!kthread_should_stop()) {
793                 spin_lock_irqsave(&(smi_info->si_lock), flags);
794                 smi_result=smi_event_handler(smi_info, 0);
795                 spin_unlock_irqrestore(&(smi_info->si_lock), flags);
796                 if (smi_result == SI_SM_CALL_WITHOUT_DELAY) {
797                         /* do nothing */
798                 }
799                 else if (smi_result == SI_SM_CALL_WITH_DELAY)
800                         udelay(1);
801                 else
802                         schedule_timeout_interruptible(1);
803         }
804         return 0;
805 }
806
807
808 static void poll(void *send_info)
809 {
810         struct smi_info *smi_info = send_info;
811
812         smi_event_handler(smi_info, 0);
813 }
814
815 static void request_events(void *send_info)
816 {
817         struct smi_info *smi_info = send_info;
818
819         atomic_set(&smi_info->req_events, 1);
820 }
821
822 static int initialized = 0;
823
824 /* Must be called with interrupts off and with the si_lock held. */
825 static void si_restart_short_timer(struct smi_info *smi_info)
826 {
827 #if defined(CONFIG_HIGH_RES_TIMERS)
828         unsigned long flags;
829         unsigned long jiffies_now;
830         unsigned long seq;
831
832         if (del_timer(&(smi_info->si_timer))) {
833                 /* If we don't delete the timer, then it will go off
834                    immediately, anyway.  So we only process if we
835                    actually delete the timer. */
836
837                 do {
838                         seq = read_seqbegin_irqsave(&xtime_lock, flags);
839                         jiffies_now = jiffies;
840                         smi_info->si_timer.expires = jiffies_now;
841                         smi_info->si_timer.arch_cycle_expires
842                                 = get_arch_cycles(jiffies_now);
843                 } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
844
845                 add_usec_to_timer(&smi_info->si_timer, SI_SHORT_TIMEOUT_USEC);
846
847                 add_timer(&(smi_info->si_timer));
848                 spin_lock_irqsave(&smi_info->count_lock, flags);
849                 smi_info->timeout_restarts++;
850                 spin_unlock_irqrestore(&smi_info->count_lock, flags);
851         }
852 #endif
853 }
854
855 static void smi_timeout(unsigned long data)
856 {
857         struct smi_info   *smi_info = (struct smi_info *) data;
858         enum si_sm_result smi_result;
859         unsigned long     flags;
860         unsigned long     jiffies_now;
861         long              time_diff;
862 #ifdef DEBUG_TIMING
863         struct timeval    t;
864 #endif
865
866         if (atomic_read(&smi_info->stop_operation))
867                 return;
868
869         spin_lock_irqsave(&(smi_info->si_lock), flags);
870 #ifdef DEBUG_TIMING
871         do_gettimeofday(&t);
872         printk("**Timer: %d.%9.9d\n", t.tv_sec, t.tv_usec);
873 #endif
874         jiffies_now = jiffies;
875         time_diff = (((long)jiffies_now - (long)smi_info->last_timeout_jiffies)
876                      * SI_USEC_PER_JIFFY);
877         smi_result = smi_event_handler(smi_info, time_diff);
878
879         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
880
881         smi_info->last_timeout_jiffies = jiffies_now;
882
883         if ((smi_info->irq) && (! smi_info->interrupt_disabled)) {
884                 /* Running with interrupts, only do long timeouts. */
885                 smi_info->si_timer.expires = jiffies + SI_TIMEOUT_JIFFIES;
886                 spin_lock_irqsave(&smi_info->count_lock, flags);
887                 smi_info->long_timeouts++;
888                 spin_unlock_irqrestore(&smi_info->count_lock, flags);
889                 goto do_add_timer;
890         }
891
892         /* If the state machine asks for a short delay, then shorten
893            the timer timeout. */
894         if (smi_result == SI_SM_CALL_WITH_DELAY) {
895 #if defined(CONFIG_HIGH_RES_TIMERS)
896                 unsigned long seq;
897 #endif
898                 spin_lock_irqsave(&smi_info->count_lock, flags);
899                 smi_info->short_timeouts++;
900                 spin_unlock_irqrestore(&smi_info->count_lock, flags);
901 #if defined(CONFIG_HIGH_RES_TIMERS)
902                 do {
903                         seq = read_seqbegin_irqsave(&xtime_lock, flags);
904                         smi_info->si_timer.expires = jiffies;
905                         smi_info->si_timer.arch_cycle_expires
906                                 = get_arch_cycles(smi_info->si_timer.expires);
907                 } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
908                 add_usec_to_timer(&smi_info->si_timer, SI_SHORT_TIMEOUT_USEC);
909 #else
910                 smi_info->si_timer.expires = jiffies + 1;
911 #endif
912         } else {
913                 spin_lock_irqsave(&smi_info->count_lock, flags);
914                 smi_info->long_timeouts++;
915                 spin_unlock_irqrestore(&smi_info->count_lock, flags);
916                 smi_info->si_timer.expires = jiffies + SI_TIMEOUT_JIFFIES;
917 #if defined(CONFIG_HIGH_RES_TIMERS)
918                 smi_info->si_timer.arch_cycle_expires = 0;
919 #endif
920         }
921
922  do_add_timer:
923         add_timer(&(smi_info->si_timer));
924 }
925
926 static irqreturn_t si_irq_handler(int irq, void *data, struct pt_regs *regs)
927 {
928         struct smi_info *smi_info = data;
929         unsigned long   flags;
930 #ifdef DEBUG_TIMING
931         struct timeval  t;
932 #endif
933
934         spin_lock_irqsave(&(smi_info->si_lock), flags);
935
936         spin_lock(&smi_info->count_lock);
937         smi_info->interrupts++;
938         spin_unlock(&smi_info->count_lock);
939
940         if (atomic_read(&smi_info->stop_operation))
941                 goto out;
942
943 #ifdef DEBUG_TIMING
944         do_gettimeofday(&t);
945         printk("**Interrupt: %d.%9.9d\n", t.tv_sec, t.tv_usec);
946 #endif
947         smi_event_handler(smi_info, 0);
948  out:
949         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
950         return IRQ_HANDLED;
951 }
952
953 static irqreturn_t si_bt_irq_handler(int irq, void *data, struct pt_regs *regs)
954 {
955         struct smi_info *smi_info = data;
956         /* We need to clear the IRQ flag for the BT interface. */
957         smi_info->io.outputb(&smi_info->io, IPMI_BT_INTMASK_REG,
958                              IPMI_BT_INTMASK_CLEAR_IRQ_BIT
959                              | IPMI_BT_INTMASK_ENABLE_IRQ_BIT);
960         return si_irq_handler(irq, data, regs);
961 }
962
963
964 static struct ipmi_smi_handlers handlers =
965 {
966         .owner                  = THIS_MODULE,
967         .sender                 = sender,
968         .request_events         = request_events,
969         .set_run_to_completion  = set_run_to_completion,
970         .poll                   = poll,
971 };
972
973 /* There can be 4 IO ports passed in (with or without IRQs), 4 addresses,
974    a default IO port, and 1 ACPI/SPMI address.  That sets SI_MAX_DRIVERS */
975
976 #define SI_MAX_PARMS 4
977 #define SI_MAX_DRIVERS ((SI_MAX_PARMS * 2) + 2)
978 static struct smi_info *smi_infos[SI_MAX_DRIVERS] =
979 { NULL, NULL, NULL, NULL };
980
981 #define DEVICE_NAME "ipmi_si"
982
983 #define DEFAULT_KCS_IO_PORT     0xca2
984 #define DEFAULT_SMIC_IO_PORT    0xca9
985 #define DEFAULT_BT_IO_PORT      0xe4
986 #define DEFAULT_REGSPACING      1
987
988 static int           si_trydefaults = 1;
989 static char          *si_type[SI_MAX_PARMS];
990 #define MAX_SI_TYPE_STR 30
991 static char          si_type_str[MAX_SI_TYPE_STR];
992 static unsigned long addrs[SI_MAX_PARMS];
993 static int num_addrs;
994 static unsigned int  ports[SI_MAX_PARMS];
995 static int num_ports;
996 static int           irqs[SI_MAX_PARMS];
997 static int num_irqs;
998 static int           regspacings[SI_MAX_PARMS];
999 static int num_regspacings = 0;
1000 static int           regsizes[SI_MAX_PARMS];
1001 static int num_regsizes = 0;
1002 static int           regshifts[SI_MAX_PARMS];
1003 static int num_regshifts = 0;
1004 static int slave_addrs[SI_MAX_PARMS];
1005 static int num_slave_addrs = 0;
1006
1007
1008 module_param_named(trydefaults, si_trydefaults, bool, 0);
1009 MODULE_PARM_DESC(trydefaults, "Setting this to 'false' will disable the"
1010                  " default scan of the KCS and SMIC interface at the standard"
1011                  " address");
1012 module_param_string(type, si_type_str, MAX_SI_TYPE_STR, 0);
1013 MODULE_PARM_DESC(type, "Defines the type of each interface, each"
1014                  " interface separated by commas.  The types are 'kcs',"
1015                  " 'smic', and 'bt'.  For example si_type=kcs,bt will set"
1016                  " the first interface to kcs and the second to bt");
1017 module_param_array(addrs, long, &num_addrs, 0);
1018 MODULE_PARM_DESC(addrs, "Sets the memory address of each interface, the"
1019                  " addresses separated by commas.  Only use if an interface"
1020                  " is in memory.  Otherwise, set it to zero or leave"
1021                  " it blank.");
1022 module_param_array(ports, int, &num_ports, 0);
1023 MODULE_PARM_DESC(ports, "Sets the port address of each interface, the"
1024                  " addresses separated by commas.  Only use if an interface"
1025                  " is a port.  Otherwise, set it to zero or leave"
1026                  " it blank.");
1027 module_param_array(irqs, int, &num_irqs, 0);
1028 MODULE_PARM_DESC(irqs, "Sets the interrupt of each interface, the"
1029                  " addresses separated by commas.  Only use if an interface"
1030                  " has an interrupt.  Otherwise, set it to zero or leave"
1031                  " it blank.");
1032 module_param_array(regspacings, int, &num_regspacings, 0);
1033 MODULE_PARM_DESC(regspacings, "The number of bytes between the start address"
1034                  " and each successive register used by the interface.  For"
1035                  " instance, if the start address is 0xca2 and the spacing"
1036                  " is 2, then the second address is at 0xca4.  Defaults"
1037                  " to 1.");
1038 module_param_array(regsizes, int, &num_regsizes, 0);
1039 MODULE_PARM_DESC(regsizes, "The size of the specific IPMI register in bytes."
1040                  " This should generally be 1, 2, 4, or 8 for an 8-bit,"
1041                  " 16-bit, 32-bit, or 64-bit register.  Use this if you"
1042                  " the 8-bit IPMI register has to be read from a larger"
1043                  " register.");
1044 module_param_array(regshifts, int, &num_regshifts, 0);
1045 MODULE_PARM_DESC(regshifts, "The amount to shift the data read from the."
1046                  " IPMI register, in bits.  For instance, if the data"
1047                  " is read from a 32-bit word and the IPMI data is in"
1048                  " bit 8-15, then the shift would be 8");
1049 module_param_array(slave_addrs, int, &num_slave_addrs, 0);
1050 MODULE_PARM_DESC(slave_addrs, "Set the default IPMB slave address for"
1051                  " the controller.  Normally this is 0x20, but can be"
1052                  " overridden by this parm.  This is an array indexed"
1053                  " by interface number.");
1054
1055
1056 #define IPMI_MEM_ADDR_SPACE 1
1057 #define IPMI_IO_ADDR_SPACE  2
1058
1059 #if defined(CONFIG_ACPI) || defined(CONFIG_DMI) || defined(CONFIG_PCI)
1060 static int is_new_interface(int intf, u8 addr_space, unsigned long base_addr)
1061 {
1062         int i;
1063
1064         for (i = 0; i < SI_MAX_PARMS; ++i) {
1065                 /* Don't check our address. */
1066                 if (i == intf)
1067                         continue;
1068                 if (si_type[i] != NULL) {
1069                         if ((addr_space == IPMI_MEM_ADDR_SPACE &&
1070                              base_addr == addrs[i]) ||
1071                             (addr_space == IPMI_IO_ADDR_SPACE &&
1072                              base_addr == ports[i]))
1073                                 return 0;
1074                 }
1075                 else
1076                         break;
1077         }
1078
1079         return 1;
1080 }
1081 #endif
1082
1083 static int std_irq_setup(struct smi_info *info)
1084 {
1085         int rv;
1086
1087         if (! info->irq)
1088                 return 0;
1089
1090         if (info->si_type == SI_BT) {
1091                 rv = request_irq(info->irq,
1092                                  si_bt_irq_handler,
1093                                  SA_INTERRUPT,
1094                                  DEVICE_NAME,
1095                                  info);
1096                 if (! rv)
1097                         /* Enable the interrupt in the BT interface. */
1098                         info->io.outputb(&info->io, IPMI_BT_INTMASK_REG,
1099                                          IPMI_BT_INTMASK_ENABLE_IRQ_BIT);
1100         } else
1101                 rv = request_irq(info->irq,
1102                                  si_irq_handler,
1103                                  SA_INTERRUPT,
1104                                  DEVICE_NAME,
1105                                  info);
1106         if (rv) {
1107                 printk(KERN_WARNING
1108                        "ipmi_si: %s unable to claim interrupt %d,"
1109                        " running polled\n",
1110                        DEVICE_NAME, info->irq);
1111                 info->irq = 0;
1112         } else {
1113                 printk("  Using irq %d\n", info->irq);
1114         }
1115
1116         return rv;
1117 }
1118
1119 static void std_irq_cleanup(struct smi_info *info)
1120 {
1121         if (! info->irq)
1122                 return;
1123
1124         if (info->si_type == SI_BT)
1125                 /* Disable the interrupt in the BT interface. */
1126                 info->io.outputb(&info->io, IPMI_BT_INTMASK_REG, 0);
1127         free_irq(info->irq, info);
1128 }
1129
1130 static unsigned char port_inb(struct si_sm_io *io, unsigned int offset)
1131 {
1132         unsigned int *addr = io->info;
1133
1134         return inb((*addr)+(offset*io->regspacing));
1135 }
1136
1137 static void port_outb(struct si_sm_io *io, unsigned int offset,
1138                       unsigned char b)
1139 {
1140         unsigned int *addr = io->info;
1141
1142         outb(b, (*addr)+(offset * io->regspacing));
1143 }
1144
1145 static unsigned char port_inw(struct si_sm_io *io, unsigned int offset)
1146 {
1147         unsigned int *addr = io->info;
1148
1149         return (inw((*addr)+(offset * io->regspacing)) >> io->regshift) & 0xff;
1150 }
1151
1152 static void port_outw(struct si_sm_io *io, unsigned int offset,
1153                       unsigned char b)
1154 {
1155         unsigned int *addr = io->info;
1156
1157         outw(b << io->regshift, (*addr)+(offset * io->regspacing));
1158 }
1159
1160 static unsigned char port_inl(struct si_sm_io *io, unsigned int offset)
1161 {
1162         unsigned int *addr = io->info;
1163
1164         return (inl((*addr)+(offset * io->regspacing)) >> io->regshift) & 0xff;
1165 }
1166
1167 static void port_outl(struct si_sm_io *io, unsigned int offset,
1168                       unsigned char b)
1169 {
1170         unsigned int *addr = io->info;
1171
1172         outl(b << io->regshift, (*addr)+(offset * io->regspacing));
1173 }
1174
1175 static void port_cleanup(struct smi_info *info)
1176 {
1177         unsigned int *addr = info->io.info;
1178         int           mapsize;
1179
1180         if (addr && (*addr)) {
1181                 mapsize = ((info->io_size * info->io.regspacing)
1182                            - (info->io.regspacing - info->io.regsize));
1183
1184                 release_region (*addr, mapsize);
1185         }
1186         kfree(info);
1187 }
1188
1189 static int port_setup(struct smi_info *info)
1190 {
1191         unsigned int *addr = info->io.info;
1192         int           mapsize;
1193
1194         if (! addr || (! *addr))
1195                 return -ENODEV;
1196
1197         info->io_cleanup = port_cleanup;
1198
1199         /* Figure out the actual inb/inw/inl/etc routine to use based
1200            upon the register size. */
1201         switch (info->io.regsize) {
1202         case 1:
1203                 info->io.inputb = port_inb;
1204                 info->io.outputb = port_outb;
1205                 break;
1206         case 2:
1207                 info->io.inputb = port_inw;
1208                 info->io.outputb = port_outw;
1209                 break;
1210         case 4:
1211                 info->io.inputb = port_inl;
1212                 info->io.outputb = port_outl;
1213                 break;
1214         default:
1215                 printk("ipmi_si: Invalid register size: %d\n",
1216                        info->io.regsize);
1217                 return -EINVAL;
1218         }
1219
1220         /* Calculate the total amount of memory to claim.  This is an
1221          * unusual looking calculation, but it avoids claiming any
1222          * more memory than it has to.  It will claim everything
1223          * between the first address to the end of the last full
1224          * register. */
1225         mapsize = ((info->io_size * info->io.regspacing)
1226                    - (info->io.regspacing - info->io.regsize));
1227
1228         if (request_region(*addr, mapsize, DEVICE_NAME) == NULL)
1229                 return -EIO;
1230         return 0;
1231 }
1232
1233 static int try_init_port(int intf_num, struct smi_info **new_info)
1234 {
1235         struct smi_info *info;
1236
1237         if (! ports[intf_num])
1238                 return -ENODEV;
1239
1240         if (! is_new_interface(intf_num, IPMI_IO_ADDR_SPACE,
1241                               ports[intf_num]))
1242                 return -ENODEV;
1243
1244         info = kmalloc(sizeof(*info), GFP_KERNEL);
1245         if (! info) {
1246                 printk(KERN_ERR "ipmi_si: Could not allocate SI data (1)\n");
1247                 return -ENOMEM;
1248         }
1249         memset(info, 0, sizeof(*info));
1250
1251         info->io_setup = port_setup;
1252         info->io.info = &(ports[intf_num]);
1253         info->io.addr = NULL;
1254         info->io.regspacing = regspacings[intf_num];
1255         if (! info->io.regspacing)
1256                 info->io.regspacing = DEFAULT_REGSPACING;
1257         info->io.regsize = regsizes[intf_num];
1258         if (! info->io.regsize)
1259                 info->io.regsize = DEFAULT_REGSPACING;
1260         info->io.regshift = regshifts[intf_num];
1261         info->irq = 0;
1262         info->irq_setup = NULL;
1263         *new_info = info;
1264
1265         if (si_type[intf_num] == NULL)
1266                 si_type[intf_num] = "kcs";
1267
1268         printk("ipmi_si: Trying \"%s\" at I/O port 0x%x\n",
1269                si_type[intf_num], ports[intf_num]);
1270         return 0;
1271 }
1272
1273 static unsigned char intf_mem_inb(struct si_sm_io *io, unsigned int offset)
1274 {
1275         return readb((io->addr)+(offset * io->regspacing));
1276 }
1277
1278 static void intf_mem_outb(struct si_sm_io *io, unsigned int offset,
1279                      unsigned char b)
1280 {
1281         writeb(b, (io->addr)+(offset * io->regspacing));
1282 }
1283
1284 static unsigned char intf_mem_inw(struct si_sm_io *io, unsigned int offset)
1285 {
1286         return (readw((io->addr)+(offset * io->regspacing)) >> io->regshift)
1287                 && 0xff;
1288 }
1289
1290 static void intf_mem_outw(struct si_sm_io *io, unsigned int offset,
1291                      unsigned char b)
1292 {
1293         writeb(b << io->regshift, (io->addr)+(offset * io->regspacing));
1294 }
1295
1296 static unsigned char intf_mem_inl(struct si_sm_io *io, unsigned int offset)
1297 {
1298         return (readl((io->addr)+(offset * io->regspacing)) >> io->regshift)
1299                 && 0xff;
1300 }
1301
1302 static void intf_mem_outl(struct si_sm_io *io, unsigned int offset,
1303                      unsigned char b)
1304 {
1305         writel(b << io->regshift, (io->addr)+(offset * io->regspacing));
1306 }
1307
1308 #ifdef readq
1309 static unsigned char mem_inq(struct si_sm_io *io, unsigned int offset)
1310 {
1311         return (readq((io->addr)+(offset * io->regspacing)) >> io->regshift)
1312                 && 0xff;
1313 }
1314
1315 static void mem_outq(struct si_sm_io *io, unsigned int offset,
1316                      unsigned char b)
1317 {
1318         writeq(b << io->regshift, (io->addr)+(offset * io->regspacing));
1319 }
1320 #endif
1321
1322 static void mem_cleanup(struct smi_info *info)
1323 {
1324         unsigned long *addr = info->io.info;
1325         int           mapsize;
1326
1327         if (info->io.addr) {
1328                 iounmap(info->io.addr);
1329
1330                 mapsize = ((info->io_size * info->io.regspacing)
1331                            - (info->io.regspacing - info->io.regsize));
1332
1333                 release_mem_region(*addr, mapsize);
1334         }
1335         kfree(info);
1336 }
1337
1338 static int mem_setup(struct smi_info *info)
1339 {
1340         unsigned long *addr = info->io.info;
1341         int           mapsize;
1342
1343         if (! addr || (! *addr))
1344                 return -ENODEV;
1345
1346         info->io_cleanup = mem_cleanup;
1347
1348         /* Figure out the actual readb/readw/readl/etc routine to use based
1349            upon the register size. */
1350         switch (info->io.regsize) {
1351         case 1:
1352                 info->io.inputb = intf_mem_inb;
1353                 info->io.outputb = intf_mem_outb;
1354                 break;
1355         case 2:
1356                 info->io.inputb = intf_mem_inw;
1357                 info->io.outputb = intf_mem_outw;
1358                 break;
1359         case 4:
1360                 info->io.inputb = intf_mem_inl;
1361                 info->io.outputb = intf_mem_outl;
1362                 break;
1363 #ifdef readq
1364         case 8:
1365                 info->io.inputb = mem_inq;
1366                 info->io.outputb = mem_outq;
1367                 break;
1368 #endif
1369         default:
1370                 printk("ipmi_si: Invalid register size: %d\n",
1371                        info->io.regsize);
1372                 return -EINVAL;
1373         }
1374
1375         /* Calculate the total amount of memory to claim.  This is an
1376          * unusual looking calculation, but it avoids claiming any
1377          * more memory than it has to.  It will claim everything
1378          * between the first address to the end of the last full
1379          * register. */
1380         mapsize = ((info->io_size * info->io.regspacing)
1381                    - (info->io.regspacing - info->io.regsize));
1382
1383         if (request_mem_region(*addr, mapsize, DEVICE_NAME) == NULL)
1384                 return -EIO;
1385
1386         info->io.addr = ioremap(*addr, mapsize);
1387         if (info->io.addr == NULL) {
1388                 release_mem_region(*addr, mapsize);
1389                 return -EIO;
1390         }
1391         return 0;
1392 }
1393
1394 static int try_init_mem(int intf_num, struct smi_info **new_info)
1395 {
1396         struct smi_info *info;
1397
1398         if (! addrs[intf_num])
1399                 return -ENODEV;
1400
1401         if (! is_new_interface(intf_num, IPMI_MEM_ADDR_SPACE,
1402                               addrs[intf_num]))
1403                 return -ENODEV;
1404
1405         info = kmalloc(sizeof(*info), GFP_KERNEL);
1406         if (! info) {
1407                 printk(KERN_ERR "ipmi_si: Could not allocate SI data (2)\n");
1408                 return -ENOMEM;
1409         }
1410         memset(info, 0, sizeof(*info));
1411
1412         info->io_setup = mem_setup;
1413         info->io.info = &addrs[intf_num];
1414         info->io.addr = NULL;
1415         info->io.regspacing = regspacings[intf_num];
1416         if (! info->io.regspacing)
1417                 info->io.regspacing = DEFAULT_REGSPACING;
1418         info->io.regsize = regsizes[intf_num];
1419         if (! info->io.regsize)
1420                 info->io.regsize = DEFAULT_REGSPACING;
1421         info->io.regshift = regshifts[intf_num];
1422         info->irq = 0;
1423         info->irq_setup = NULL;
1424         *new_info = info;
1425
1426         if (si_type[intf_num] == NULL)
1427                 si_type[intf_num] = "kcs";
1428
1429         printk("ipmi_si: Trying \"%s\" at memory address 0x%lx\n",
1430                si_type[intf_num], addrs[intf_num]);
1431         return 0;
1432 }
1433
1434
1435 #ifdef CONFIG_ACPI
1436
1437 #include <linux/acpi.h>
1438
1439 /* Once we get an ACPI failure, we don't try any more, because we go
1440    through the tables sequentially.  Once we don't find a table, there
1441    are no more. */
1442 static int acpi_failure = 0;
1443
1444 /* For GPE-type interrupts. */
1445 static u32 ipmi_acpi_gpe(void *context)
1446 {
1447         struct smi_info *smi_info = context;
1448         unsigned long   flags;
1449 #ifdef DEBUG_TIMING
1450         struct timeval t;
1451 #endif
1452
1453         spin_lock_irqsave(&(smi_info->si_lock), flags);
1454
1455         spin_lock(&smi_info->count_lock);
1456         smi_info->interrupts++;
1457         spin_unlock(&smi_info->count_lock);
1458
1459         if (atomic_read(&smi_info->stop_operation))
1460                 goto out;
1461
1462 #ifdef DEBUG_TIMING
1463         do_gettimeofday(&t);
1464         printk("**ACPI_GPE: %d.%9.9d\n", t.tv_sec, t.tv_usec);
1465 #endif
1466         smi_event_handler(smi_info, 0);
1467  out:
1468         spin_unlock_irqrestore(&(smi_info->si_lock), flags);
1469
1470         return ACPI_INTERRUPT_HANDLED;
1471 }
1472
1473 static int acpi_gpe_irq_setup(struct smi_info *info)
1474 {
1475         acpi_status status;
1476
1477         if (! info->irq)
1478                 return 0;
1479
1480         /* FIXME - is level triggered right? */
1481         status = acpi_install_gpe_handler(NULL,
1482                                           info->irq,
1483                                           ACPI_GPE_LEVEL_TRIGGERED,
1484                                           &ipmi_acpi_gpe,
1485                                           info);
1486         if (status != AE_OK) {
1487                 printk(KERN_WARNING
1488                        "ipmi_si: %s unable to claim ACPI GPE %d,"
1489                        " running polled\n",
1490                        DEVICE_NAME, info->irq);
1491                 info->irq = 0;
1492                 return -EINVAL;
1493         } else {
1494                 printk("  Using ACPI GPE %d\n", info->irq);
1495                 return 0;
1496         }
1497 }
1498
1499 static void acpi_gpe_irq_cleanup(struct smi_info *info)
1500 {
1501         if (! info->irq)
1502                 return;
1503
1504         acpi_remove_gpe_handler(NULL, info->irq, &ipmi_acpi_gpe);
1505 }
1506
1507 /*
1508  * Defined at
1509  * http://h21007.www2.hp.com/dspp/files/unprotected/devresource/Docs/TechPapers/IA64/hpspmi.pdf
1510  */
1511 struct SPMITable {
1512         s8      Signature[4];
1513         u32     Length;
1514         u8      Revision;
1515         u8      Checksum;
1516         s8      OEMID[6];
1517         s8      OEMTableID[8];
1518         s8      OEMRevision[4];
1519         s8      CreatorID[4];
1520         s8      CreatorRevision[4];
1521         u8      InterfaceType;
1522         u8      IPMIlegacy;
1523         s16     SpecificationRevision;
1524
1525         /*
1526          * Bit 0 - SCI interrupt supported
1527          * Bit 1 - I/O APIC/SAPIC
1528          */
1529         u8      InterruptType;
1530
1531         /* If bit 0 of InterruptType is set, then this is the SCI
1532            interrupt in the GPEx_STS register. */
1533         u8      GPE;
1534
1535         s16     Reserved;
1536
1537         /* If bit 1 of InterruptType is set, then this is the I/O
1538            APIC/SAPIC interrupt. */
1539         u32     GlobalSystemInterrupt;
1540
1541         /* The actual register address. */
1542         struct acpi_generic_address addr;
1543
1544         u8      UID[4];
1545
1546         s8      spmi_id[1]; /* A '\0' terminated array starts here. */
1547 };
1548
1549 static int try_init_acpi(int intf_num, struct smi_info **new_info)
1550 {
1551         struct smi_info  *info;
1552         acpi_status      status;
1553         struct SPMITable *spmi;
1554         char             *io_type;
1555         u8               addr_space;
1556
1557         if (acpi_disabled)
1558                 return -ENODEV;
1559
1560         if (acpi_failure)
1561                 return -ENODEV;
1562
1563         status = acpi_get_firmware_table("SPMI", intf_num+1,
1564                                          ACPI_LOGICAL_ADDRESSING,
1565                                          (struct acpi_table_header **) &spmi);
1566         if (status != AE_OK) {
1567                 acpi_failure = 1;
1568                 return -ENODEV;
1569         }
1570
1571         if (spmi->IPMIlegacy != 1) {
1572             printk(KERN_INFO "IPMI: Bad SPMI legacy %d\n", spmi->IPMIlegacy);
1573             return -ENODEV;
1574         }
1575
1576         if (spmi->addr.address_space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY)
1577                 addr_space = IPMI_MEM_ADDR_SPACE;
1578         else
1579                 addr_space = IPMI_IO_ADDR_SPACE;
1580         if (! is_new_interface(-1, addr_space, spmi->addr.address))
1581                 return -ENODEV;
1582
1583         /* Figure out the interface type. */
1584         switch (spmi->InterfaceType)
1585         {
1586         case 1: /* KCS */
1587                 si_type[intf_num] = "kcs";
1588                 break;
1589
1590         case 2: /* SMIC */
1591                 si_type[intf_num] = "smic";
1592                 break;
1593
1594         case 3: /* BT */
1595                 si_type[intf_num] = "bt";
1596                 break;
1597
1598         default:
1599                 printk(KERN_INFO "ipmi_si: Unknown ACPI/SPMI SI type %d\n",
1600                         spmi->InterfaceType);
1601                 return -EIO;
1602         }
1603
1604         info = kmalloc(sizeof(*info), GFP_KERNEL);
1605         if (! info) {
1606                 printk(KERN_ERR "ipmi_si: Could not allocate SI data (3)\n");
1607                 return -ENOMEM;
1608         }
1609         memset(info, 0, sizeof(*info));
1610
1611         if (spmi->InterruptType & 1) {
1612                 /* We've got a GPE interrupt. */
1613                 info->irq = spmi->GPE;
1614                 info->irq_setup = acpi_gpe_irq_setup;
1615                 info->irq_cleanup = acpi_gpe_irq_cleanup;
1616         } else if (spmi->InterruptType & 2) {
1617                 /* We've got an APIC/SAPIC interrupt. */
1618                 info->irq = spmi->GlobalSystemInterrupt;
1619                 info->irq_setup = std_irq_setup;
1620                 info->irq_cleanup = std_irq_cleanup;
1621         } else {
1622                 /* Use the default interrupt setting. */
1623                 info->irq = 0;
1624                 info->irq_setup = NULL;
1625         }
1626
1627         if (spmi->addr.register_bit_width) {
1628                 /* A (hopefully) properly formed register bit width. */
1629                 regspacings[intf_num] = spmi->addr.register_bit_width / 8;
1630                 info->io.regspacing = spmi->addr.register_bit_width / 8;
1631         } else {
1632                 regspacings[intf_num] = DEFAULT_REGSPACING;
1633                 info->io.regspacing = DEFAULT_REGSPACING;
1634         }
1635         regsizes[intf_num] = regspacings[intf_num];
1636         info->io.regsize = regsizes[intf_num];
1637         regshifts[intf_num] = spmi->addr.register_bit_offset;
1638         info->io.regshift = regshifts[intf_num];
1639
1640         if (spmi->addr.address_space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY) {
1641                 io_type = "memory";
1642                 info->io_setup = mem_setup;
1643                 addrs[intf_num] = spmi->addr.address;
1644                 info->io.info = &(addrs[intf_num]);
1645         } else if (spmi->addr.address_space_id == ACPI_ADR_SPACE_SYSTEM_IO) {
1646                 io_type = "I/O";
1647                 info->io_setup = port_setup;
1648                 ports[intf_num] = spmi->addr.address;
1649                 info->io.info = &(ports[intf_num]);
1650         } else {
1651                 kfree(info);
1652                 printk("ipmi_si: Unknown ACPI I/O Address type\n");
1653                 return -EIO;
1654         }
1655
1656         *new_info = info;
1657
1658         printk("ipmi_si: ACPI/SPMI specifies \"%s\" %s SI @ 0x%lx\n",
1659                si_type[intf_num], io_type, (unsigned long) spmi->addr.address);
1660         return 0;
1661 }
1662 #endif
1663
1664 #ifdef CONFIG_DMI
1665 typedef struct dmi_ipmi_data
1666 {
1667         u8              type;
1668         u8              addr_space;
1669         unsigned long   base_addr;
1670         u8              irq;
1671         u8              offset;
1672         u8              slave_addr;
1673 } dmi_ipmi_data_t;
1674
1675 static dmi_ipmi_data_t dmi_data[SI_MAX_DRIVERS];
1676 static int dmi_data_entries;
1677
1678 static int __init decode_dmi(struct dmi_header *dm, int intf_num)
1679 {
1680         u8              *data = (u8 *)dm;
1681         unsigned long   base_addr;
1682         u8              reg_spacing;
1683         u8              len = dm->length;
1684         dmi_ipmi_data_t *ipmi_data = dmi_data+intf_num;
1685
1686         ipmi_data->type = data[4];
1687
1688         memcpy(&base_addr, data+8, sizeof(unsigned long));
1689         if (len >= 0x11) {
1690                 if (base_addr & 1) {
1691                         /* I/O */
1692                         base_addr &= 0xFFFE;
1693                         ipmi_data->addr_space = IPMI_IO_ADDR_SPACE;
1694                 }
1695                 else {
1696                         /* Memory */
1697                         ipmi_data->addr_space = IPMI_MEM_ADDR_SPACE;
1698                 }
1699                 /* If bit 4 of byte 0x10 is set, then the lsb for the address
1700                    is odd. */
1701                 ipmi_data->base_addr = base_addr | ((data[0x10] & 0x10) >> 4);
1702
1703                 ipmi_data->irq = data[0x11];
1704
1705                 /* The top two bits of byte 0x10 hold the register spacing. */
1706                 reg_spacing = (data[0x10] & 0xC0) >> 6;
1707                 switch(reg_spacing){
1708                 case 0x00: /* Byte boundaries */
1709                     ipmi_data->offset = 1;
1710                     break;
1711                 case 0x01: /* 32-bit boundaries */
1712                     ipmi_data->offset = 4;
1713                     break;
1714                 case 0x02: /* 16-byte boundaries */
1715                     ipmi_data->offset = 16;
1716                     break;
1717                 default:
1718                     /* Some other interface, just ignore it. */
1719                     return -EIO;
1720                 }
1721         } else {
1722                 /* Old DMI spec. */
1723                 /* Note that technically, the lower bit of the base
1724                  * address should be 1 if the address is I/O and 0 if
1725                  * the address is in memory.  So many systems get that
1726                  * wrong (and all that I have seen are I/O) so we just
1727                  * ignore that bit and assume I/O.  Systems that use
1728                  * memory should use the newer spec, anyway. */
1729                 ipmi_data->base_addr = base_addr & 0xfffe;
1730                 ipmi_data->addr_space = IPMI_IO_ADDR_SPACE;
1731                 ipmi_data->offset = 1;
1732         }
1733
1734         ipmi_data->slave_addr = data[6];
1735
1736         if (is_new_interface(-1, ipmi_data->addr_space,ipmi_data->base_addr)) {
1737                 dmi_data_entries++;
1738                 return 0;
1739         }
1740
1741         memset(ipmi_data, 0, sizeof(dmi_ipmi_data_t));
1742
1743         return -1;
1744 }
1745
1746 static void __init dmi_find_bmc(void)
1747 {
1748         struct dmi_device *dev = NULL;
1749         int               intf_num = 0;
1750
1751         while ((dev = dmi_find_device(DMI_DEV_TYPE_IPMI, NULL, dev))) {
1752                 if (intf_num >= SI_MAX_DRIVERS)
1753                         break;
1754
1755                 decode_dmi((struct dmi_header *) dev->device_data, intf_num++);
1756         }
1757 }
1758
1759 static int try_init_smbios(int intf_num, struct smi_info **new_info)
1760 {
1761         struct smi_info *info;
1762         dmi_ipmi_data_t *ipmi_data = dmi_data+intf_num;
1763         char            *io_type;
1764
1765         if (intf_num >= dmi_data_entries)
1766                 return -ENODEV;
1767
1768         switch (ipmi_data->type) {
1769                 case 0x01: /* KCS */
1770                         si_type[intf_num] = "kcs";
1771                         break;
1772                 case 0x02: /* SMIC */
1773                         si_type[intf_num] = "smic";
1774                         break;
1775                 case 0x03: /* BT */
1776                         si_type[intf_num] = "bt";
1777                         break;
1778                 default:
1779                         return -EIO;
1780         }
1781
1782         info = kmalloc(sizeof(*info), GFP_KERNEL);
1783         if (! info) {
1784                 printk(KERN_ERR "ipmi_si: Could not allocate SI data (4)\n");
1785                 return -ENOMEM;
1786         }
1787         memset(info, 0, sizeof(*info));
1788
1789         if (ipmi_data->addr_space == 1) {
1790                 io_type = "memory";
1791                 info->io_setup = mem_setup;
1792                 addrs[intf_num] = ipmi_data->base_addr;
1793                 info->io.info = &(addrs[intf_num]);
1794         } else if (ipmi_data->addr_space == 2) {
1795                 io_type = "I/O";
1796                 info->io_setup = port_setup;
1797                 ports[intf_num] = ipmi_data->base_addr;
1798                 info->io.info = &(ports[intf_num]);
1799         } else {
1800                 kfree(info);
1801                 printk("ipmi_si: Unknown SMBIOS I/O Address type.\n");
1802                 return -EIO;
1803         }
1804
1805         regspacings[intf_num] = ipmi_data->offset;
1806         info->io.regspacing = regspacings[intf_num];
1807         if (! info->io.regspacing)
1808                 info->io.regspacing = DEFAULT_REGSPACING;
1809         info->io.regsize = DEFAULT_REGSPACING;
1810         info->io.regshift = regshifts[intf_num];
1811
1812         info->slave_addr = ipmi_data->slave_addr;
1813
1814         irqs[intf_num] = ipmi_data->irq;
1815
1816         *new_info = info;
1817
1818         printk("ipmi_si: Found SMBIOS-specified state machine at %s"
1819                " address 0x%lx, slave address 0x%x\n",
1820                io_type, (unsigned long)ipmi_data->base_addr,
1821                ipmi_data->slave_addr);
1822         return 0;
1823 }
1824 #endif /* CONFIG_DMI */
1825
1826 #ifdef CONFIG_PCI
1827
1828 #define PCI_ERMC_CLASSCODE  0x0C0700
1829 #define PCI_HP_VENDOR_ID    0x103C
1830 #define PCI_MMC_DEVICE_ID   0x121A
1831 #define PCI_MMC_ADDR_CW     0x10
1832
1833 /* Avoid more than one attempt to probe pci smic. */
1834 static int pci_smic_checked = 0;
1835
1836 static int find_pci_smic(int intf_num, struct smi_info **new_info)
1837 {
1838         struct smi_info  *info;
1839         int              error;
1840         struct pci_dev   *pci_dev = NULL;
1841         u16              base_addr;
1842         int              fe_rmc = 0;
1843
1844         if (pci_smic_checked)
1845                 return -ENODEV;
1846
1847         pci_smic_checked = 1;
1848
1849         pci_dev = pci_get_device(PCI_HP_VENDOR_ID, PCI_MMC_DEVICE_ID, NULL);
1850         if (! pci_dev) {
1851                 pci_dev = pci_get_class(PCI_ERMC_CLASSCODE, NULL);
1852                 if (pci_dev && (pci_dev->subsystem_vendor == PCI_HP_VENDOR_ID))
1853                         fe_rmc = 1;
1854                 else
1855                         return -ENODEV;
1856         }
1857
1858         error = pci_read_config_word(pci_dev, PCI_MMC_ADDR_CW, &base_addr);
1859         if (error)
1860         {
1861                 pci_dev_put(pci_dev);
1862                 printk(KERN_ERR
1863                        "ipmi_si: pci_read_config_word() failed (%d).\n",
1864                        error);
1865                 return -ENODEV;
1866         }
1867
1868         /* Bit 0: 1 specifies programmed I/O, 0 specifies memory mapped I/O */
1869         if (! (base_addr & 0x0001))
1870         {
1871                 pci_dev_put(pci_dev);
1872                 printk(KERN_ERR
1873                        "ipmi_si: memory mapped I/O not supported for PCI"
1874                        " smic.\n");
1875                 return -ENODEV;
1876         }
1877
1878         base_addr &= 0xFFFE;
1879         if (! fe_rmc)
1880                 /* Data register starts at base address + 1 in eRMC */
1881                 ++base_addr;
1882
1883         if (! is_new_interface(-1, IPMI_IO_ADDR_SPACE, base_addr)) {
1884                 pci_dev_put(pci_dev);
1885                 return -ENODEV;
1886         }
1887
1888         info = kmalloc(sizeof(*info), GFP_KERNEL);
1889         if (! info) {
1890                 pci_dev_put(pci_dev);
1891                 printk(KERN_ERR "ipmi_si: Could not allocate SI data (5)\n");
1892                 return -ENOMEM;
1893         }
1894         memset(info, 0, sizeof(*info));
1895
1896         info->io_setup = port_setup;
1897         ports[intf_num] = base_addr;
1898         info->io.info = &(ports[intf_num]);
1899         info->io.regspacing = regspacings[intf_num];
1900         if (! info->io.regspacing)
1901                 info->io.regspacing = DEFAULT_REGSPACING;
1902         info->io.regsize = DEFAULT_REGSPACING;
1903         info->io.regshift = regshifts[intf_num];
1904
1905         *new_info = info;
1906
1907         irqs[intf_num] = pci_dev->irq;
1908         si_type[intf_num] = "smic";
1909
1910         printk("ipmi_si: Found PCI SMIC at I/O address 0x%lx\n",
1911                 (long unsigned int) base_addr);
1912
1913         pci_dev_put(pci_dev);
1914         return 0;
1915 }
1916 #endif /* CONFIG_PCI */
1917
1918 static int try_init_plug_and_play(int intf_num, struct smi_info **new_info)
1919 {
1920 #ifdef CONFIG_PCI
1921         if (find_pci_smic(intf_num, new_info) == 0)
1922                 return 0;
1923 #endif
1924         /* Include other methods here. */
1925
1926         return -ENODEV;
1927 }
1928
1929
1930 static int try_get_dev_id(struct smi_info *smi_info)
1931 {
1932         unsigned char      msg[2];
1933         unsigned char      *resp;
1934         unsigned long      resp_len;
1935         enum si_sm_result smi_result;
1936         int               rv = 0;
1937
1938         resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
1939         if (! resp)
1940                 return -ENOMEM;
1941
1942         /* Do a Get Device ID command, since it comes back with some
1943            useful info. */
1944         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1945         msg[1] = IPMI_GET_DEVICE_ID_CMD;
1946         smi_info->handlers->start_transaction(smi_info->si_sm, msg, 2);
1947
1948         smi_result = smi_info->handlers->event(smi_info->si_sm, 0);
1949         for (;;)
1950         {
1951                 if (smi_result == SI_SM_CALL_WITH_DELAY ||
1952                     smi_result == SI_SM_CALL_WITH_TICK_DELAY) {
1953                         schedule_timeout_uninterruptible(1);
1954                         smi_result = smi_info->handlers->event(
1955                                 smi_info->si_sm, 100);
1956                 }
1957                 else if (smi_result == SI_SM_CALL_WITHOUT_DELAY)
1958                 {
1959                         smi_result = smi_info->handlers->event(
1960                                 smi_info->si_sm, 0);
1961                 }
1962                 else
1963                         break;
1964         }
1965         if (smi_result == SI_SM_HOSED) {
1966                 /* We couldn't get the state machine to run, so whatever's at
1967                    the port is probably not an IPMI SMI interface. */
1968                 rv = -ENODEV;
1969                 goto out;
1970         }
1971
1972         /* Otherwise, we got some data. */
1973         resp_len = smi_info->handlers->get_result(smi_info->si_sm,
1974                                                   resp, IPMI_MAX_MSG_LENGTH);
1975         if (resp_len < 6) {
1976                 /* That's odd, it should be longer. */
1977                 rv = -EINVAL;
1978                 goto out;
1979         }
1980
1981         if ((resp[1] != IPMI_GET_DEVICE_ID_CMD) || (resp[2] != 0)) {
1982                 /* That's odd, it shouldn't be able to fail. */
1983                 rv = -EINVAL;
1984                 goto out;
1985         }
1986
1987         /* Record info from the get device id, in case we need it. */
1988         memcpy(&smi_info->device_id, &resp[3],
1989                min_t(unsigned long, resp_len-3, sizeof(smi_info->device_id)));
1990
1991  out:
1992         kfree(resp);
1993         return rv;
1994 }
1995
1996 static int type_file_read_proc(char *page, char **start, off_t off,
1997                                int count, int *eof, void *data)
1998 {
1999         char            *out = (char *) page;
2000         struct smi_info *smi = data;
2001
2002         switch (smi->si_type) {
2003             case SI_KCS:
2004                 return sprintf(out, "kcs\n");
2005             case SI_SMIC:
2006                 return sprintf(out, "smic\n");
2007             case SI_BT:
2008                 return sprintf(out, "bt\n");
2009             default:
2010                 return 0;
2011         }
2012 }
2013
2014 static int stat_file_read_proc(char *page, char **start, off_t off,
2015                                int count, int *eof, void *data)
2016 {
2017         char            *out = (char *) page;
2018         struct smi_info *smi = data;
2019
2020         out += sprintf(out, "interrupts_enabled:    %d\n",
2021                        smi->irq && ! smi->interrupt_disabled);
2022         out += sprintf(out, "short_timeouts:        %ld\n",
2023                        smi->short_timeouts);
2024         out += sprintf(out, "long_timeouts:         %ld\n",
2025                        smi->long_timeouts);
2026         out += sprintf(out, "timeout_restarts:      %ld\n",
2027                        smi->timeout_restarts);
2028         out += sprintf(out, "idles:                 %ld\n",
2029                        smi->idles);
2030         out += sprintf(out, "interrupts:            %ld\n",
2031                        smi->interrupts);
2032         out += sprintf(out, "attentions:            %ld\n",
2033                        smi->attentions);
2034         out += sprintf(out, "flag_fetches:          %ld\n",
2035                        smi->flag_fetches);
2036         out += sprintf(out, "hosed_count:           %ld\n",
2037                        smi->hosed_count);
2038         out += sprintf(out, "complete_transactions: %ld\n",
2039                        smi->complete_transactions);
2040         out += sprintf(out, "events:                %ld\n",
2041                        smi->events);
2042         out += sprintf(out, "watchdog_pretimeouts:  %ld\n",
2043                        smi->watchdog_pretimeouts);
2044         out += sprintf(out, "incoming_messages:     %ld\n",
2045                        smi->incoming_messages);
2046
2047         return (out - ((char *) page));
2048 }
2049
2050 /*
2051  * oem_data_avail_to_receive_msg_avail
2052  * @info - smi_info structure with msg_flags set
2053  *
2054  * Converts flags from OEM_DATA_AVAIL to RECEIVE_MSG_AVAIL
2055  * Returns 1 indicating need to re-run handle_flags().
2056  */
2057 static int oem_data_avail_to_receive_msg_avail(struct smi_info *smi_info)
2058 {
2059         smi_info->msg_flags = ((smi_info->msg_flags & ~OEM_DATA_AVAIL) |
2060                                 RECEIVE_MSG_AVAIL);
2061         return 1;
2062 }
2063
2064 /*
2065  * setup_dell_poweredge_oem_data_handler
2066  * @info - smi_info.device_id must be populated
2067  *
2068  * Systems that match, but have firmware version < 1.40 may assert
2069  * OEM0_DATA_AVAIL on their own, without being told via Set Flags that
2070  * it's safe to do so.  Such systems will de-assert OEM1_DATA_AVAIL
2071  * upon receipt of IPMI_GET_MSG_CMD, so we should treat these flags
2072  * as RECEIVE_MSG_AVAIL instead.
2073  *
2074  * As Dell has no plans to release IPMI 1.5 firmware that *ever*
2075  * assert the OEM[012] bits, and if it did, the driver would have to
2076  * change to handle that properly, we don't actually check for the
2077  * firmware version.
2078  * Device ID = 0x20                BMC on PowerEdge 8G servers
2079  * Device Revision = 0x80
2080  * Firmware Revision1 = 0x01       BMC version 1.40
2081  * Firmware Revision2 = 0x40       BCD encoded
2082  * IPMI Version = 0x51             IPMI 1.5
2083  * Manufacturer ID = A2 02 00      Dell IANA
2084  *
2085  * Additionally, PowerEdge systems with IPMI < 1.5 may also assert
2086  * OEM0_DATA_AVAIL and needs to be treated as RECEIVE_MSG_AVAIL.
2087  *
2088  */
2089 #define DELL_POWEREDGE_8G_BMC_DEVICE_ID  0x20
2090 #define DELL_POWEREDGE_8G_BMC_DEVICE_REV 0x80
2091 #define DELL_POWEREDGE_8G_BMC_IPMI_VERSION 0x51
2092 #define DELL_IANA_MFR_ID {0xA2, 0x02, 0x00}
2093 static void setup_dell_poweredge_oem_data_handler(struct smi_info *smi_info)
2094 {
2095         struct ipmi_device_id *id = &smi_info->device_id;
2096         const char mfr[3]=DELL_IANA_MFR_ID;
2097         if (! memcmp(mfr, id->manufacturer_id, sizeof(mfr))) {
2098                 if (id->device_id       == DELL_POWEREDGE_8G_BMC_DEVICE_ID  &&
2099                     id->device_revision == DELL_POWEREDGE_8G_BMC_DEVICE_REV &&
2100                     id->ipmi_version    == DELL_POWEREDGE_8G_BMC_IPMI_VERSION) {
2101                         smi_info->oem_data_avail_handler =
2102                                 oem_data_avail_to_receive_msg_avail;
2103                 }
2104                 else if (ipmi_version_major(id) < 1 ||
2105                          (ipmi_version_major(id) == 1 &&
2106                           ipmi_version_minor(id) < 5)) {
2107                         smi_info->oem_data_avail_handler =
2108                                 oem_data_avail_to_receive_msg_avail;
2109                 }
2110         }
2111 }
2112
2113 #define CANNOT_RETURN_REQUESTED_LENGTH 0xCA
2114 static void return_hosed_msg_badsize(struct smi_info *smi_info)
2115 {
2116         struct ipmi_smi_msg *msg = smi_info->curr_msg;
2117
2118         /* Make it a reponse */
2119         msg->rsp[0] = msg->data[0] | 4;
2120         msg->rsp[1] = msg->data[1];
2121         msg->rsp[2] = CANNOT_RETURN_REQUESTED_LENGTH;
2122         msg->rsp_size = 3;
2123         smi_info->curr_msg = NULL;
2124         deliver_recv_msg(smi_info, msg);
2125 }
2126
2127 /*
2128  * dell_poweredge_bt_xaction_handler
2129  * @info - smi_info.device_id must be populated
2130  *
2131  * Dell PowerEdge servers with the BT interface (x6xx and 1750) will
2132  * not respond to a Get SDR command if the length of the data
2133  * requested is exactly 0x3A, which leads to command timeouts and no
2134  * data returned.  This intercepts such commands, and causes userspace
2135  * callers to try again with a different-sized buffer, which succeeds.
2136  */
2137
2138 #define STORAGE_NETFN 0x0A
2139 #define STORAGE_CMD_GET_SDR 0x23
2140 static int dell_poweredge_bt_xaction_handler(struct notifier_block *self,
2141                                              unsigned long unused,
2142                                              void *in)
2143 {
2144         struct smi_info *smi_info = in;
2145         unsigned char *data = smi_info->curr_msg->data;
2146         unsigned int size   = smi_info->curr_msg->data_size;
2147         if (size >= 8 &&
2148             (data[0]>>2) == STORAGE_NETFN &&
2149             data[1] == STORAGE_CMD_GET_SDR &&
2150             data[7] == 0x3A) {
2151                 return_hosed_msg_badsize(smi_info);
2152                 return NOTIFY_STOP;
2153         }
2154         return NOTIFY_DONE;
2155 }
2156
2157 static struct notifier_block dell_poweredge_bt_xaction_notifier = {
2158         .notifier_call  = dell_poweredge_bt_xaction_handler,
2159 };
2160
2161 /*
2162  * setup_dell_poweredge_bt_xaction_handler
2163  * @info - smi_info.device_id must be filled in already
2164  *
2165  * Fills in smi_info.device_id.start_transaction_pre_hook
2166  * when we know what function to use there.
2167  */
2168 static void
2169 setup_dell_poweredge_bt_xaction_handler(struct smi_info *smi_info)
2170 {
2171         struct ipmi_device_id *id = &smi_info->device_id;
2172         const char mfr[3]=DELL_IANA_MFR_ID;
2173         if (! memcmp(mfr, id->manufacturer_id, sizeof(mfr)) &&
2174             smi_info->si_type == SI_BT)
2175                 register_xaction_notifier(&dell_poweredge_bt_xaction_notifier);
2176 }
2177
2178 /*
2179  * setup_oem_data_handler
2180  * @info - smi_info.device_id must be filled in already
2181  *
2182  * Fills in smi_info.device_id.oem_data_available_handler
2183  * when we know what function to use there.
2184  */
2185
2186 static void setup_oem_data_handler(struct smi_info *smi_info)
2187 {
2188         setup_dell_poweredge_oem_data_handler(smi_info);
2189 }
2190
2191 static void setup_xaction_handlers(struct smi_info *smi_info)
2192 {
2193         setup_dell_poweredge_bt_xaction_handler(smi_info);
2194 }
2195
2196 static inline void wait_for_timer_and_thread(struct smi_info *smi_info)
2197 {
2198         if (smi_info->thread != NULL && smi_info->thread != ERR_PTR(-ENOMEM))
2199                 kthread_stop(smi_info->thread);
2200         del_timer_sync(&smi_info->si_timer);
2201 }
2202
2203 /* Returns 0 if initialized, or negative on an error. */
2204 static int init_one_smi(int intf_num, struct smi_info **smi)
2205 {
2206         int             rv;
2207         struct smi_info *new_smi;
2208
2209
2210         rv = try_init_mem(intf_num, &new_smi);
2211         if (rv)
2212                 rv = try_init_port(intf_num, &new_smi);
2213 #ifdef CONFIG_ACPI
2214         if (rv && si_trydefaults)
2215                 rv = try_init_acpi(intf_num, &new_smi);
2216 #endif
2217 #ifdef CONFIG_DMI
2218         if (rv && si_trydefaults)
2219                 rv = try_init_smbios(intf_num, &new_smi);
2220 #endif
2221         if (rv && si_trydefaults)
2222                 rv = try_init_plug_and_play(intf_num, &new_smi);
2223
2224         if (rv)
2225                 return rv;
2226
2227         /* So we know not to free it unless we have allocated one. */
2228         new_smi->intf = NULL;
2229         new_smi->si_sm = NULL;
2230         new_smi->handlers = NULL;
2231
2232         if (! new_smi->irq_setup) {
2233                 new_smi->irq = irqs[intf_num];
2234                 new_smi->irq_setup = std_irq_setup;
2235                 new_smi->irq_cleanup = std_irq_cleanup;
2236         }
2237
2238         /* Default to KCS if no type is specified. */
2239         if (si_type[intf_num] == NULL) {
2240                 if (si_trydefaults)
2241                         si_type[intf_num] = "kcs";
2242                 else {
2243                         rv = -EINVAL;
2244                         goto out_err;
2245                 }
2246         }
2247
2248         /* Set up the state machine to use. */
2249         if (strcmp(si_type[intf_num], "kcs") == 0) {
2250                 new_smi->handlers = &kcs_smi_handlers;
2251                 new_smi->si_type = SI_KCS;
2252         } else if (strcmp(si_type[intf_num], "smic") == 0) {
2253                 new_smi->handlers = &smic_smi_handlers;
2254                 new_smi->si_type = SI_SMIC;
2255         } else if (strcmp(si_type[intf_num], "bt") == 0) {
2256                 new_smi->handlers = &bt_smi_handlers;
2257                 new_smi->si_type = SI_BT;
2258         } else {
2259                 /* No support for anything else yet. */
2260                 rv = -EIO;
2261                 goto out_err;
2262         }
2263
2264         /* Allocate the state machine's data and initialize it. */
2265         new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL);
2266         if (! new_smi->si_sm) {
2267                 printk(" Could not allocate state machine memory\n");
2268                 rv = -ENOMEM;
2269                 goto out_err;
2270         }
2271         new_smi->io_size = new_smi->handlers->init_data(new_smi->si_sm,
2272                                                         &new_smi->io);
2273
2274         /* Now that we know the I/O size, we can set up the I/O. */
2275         rv = new_smi->io_setup(new_smi);
2276         if (rv) {
2277                 printk(" Could not set up I/O space\n");
2278                 goto out_err;
2279         }
2280
2281         spin_lock_init(&(new_smi->si_lock));
2282         spin_lock_init(&(new_smi->msg_lock));
2283         spin_lock_init(&(new_smi->count_lock));
2284
2285         /* Do low-level detection first. */
2286         if (new_smi->handlers->detect(new_smi->si_sm)) {
2287                 rv = -ENODEV;
2288                 goto out_err;
2289         }
2290
2291         /* Attempt a get device id command.  If it fails, we probably
2292            don't have a SMI here. */
2293         rv = try_get_dev_id(new_smi);
2294         if (rv)
2295                 goto out_err;
2296
2297         setup_oem_data_handler(new_smi);
2298         setup_xaction_handlers(new_smi);
2299
2300         /* Try to claim any interrupts. */
2301         new_smi->irq_setup(new_smi);
2302
2303         INIT_LIST_HEAD(&(new_smi->xmit_msgs));
2304         INIT_LIST_HEAD(&(new_smi->hp_xmit_msgs));
2305         new_smi->curr_msg = NULL;
2306         atomic_set(&new_smi->req_events, 0);
2307         new_smi->run_to_completion = 0;
2308
2309         new_smi->interrupt_disabled = 0;
2310         atomic_set(&new_smi->stop_operation, 0);
2311         new_smi->intf_num = intf_num;
2312
2313         /* Start clearing the flags before we enable interrupts or the
2314            timer to avoid racing with the timer. */
2315         start_clear_flags(new_smi);
2316         /* IRQ is defined to be set when non-zero. */
2317         if (new_smi->irq)
2318                 new_smi->si_state = SI_CLEARING_FLAGS_THEN_SET_IRQ;
2319
2320         /* The ipmi_register_smi() code does some operations to
2321            determine the channel information, so we must be ready to
2322            handle operations before it is called.  This means we have
2323            to stop the timer if we get an error after this point. */
2324         init_timer(&(new_smi->si_timer));
2325         new_smi->si_timer.data = (long) new_smi;
2326         new_smi->si_timer.function = smi_timeout;
2327         new_smi->last_timeout_jiffies = jiffies;
2328         new_smi->si_timer.expires = jiffies + SI_TIMEOUT_JIFFIES;
2329
2330         add_timer(&(new_smi->si_timer));
2331         if (new_smi->si_type != SI_BT)
2332                 new_smi->thread = kthread_run(ipmi_thread, new_smi,
2333                                               "kipmi%d", new_smi->intf_num);
2334
2335         rv = ipmi_register_smi(&handlers,
2336                                new_smi,
2337                                ipmi_version_major(&new_smi->device_id),
2338                                ipmi_version_minor(&new_smi->device_id),
2339                                new_smi->slave_addr,
2340                                &(new_smi->intf));
2341         if (rv) {
2342                 printk(KERN_ERR
2343                        "ipmi_si: Unable to register device: error %d\n",
2344                        rv);
2345                 goto out_err_stop_timer;
2346         }
2347
2348         rv = ipmi_smi_add_proc_entry(new_smi->intf, "type",
2349                                      type_file_read_proc, NULL,
2350                                      new_smi, THIS_MODULE);
2351         if (rv) {
2352                 printk(KERN_ERR
2353                        "ipmi_si: Unable to create proc entry: %d\n",
2354                        rv);
2355                 goto out_err_stop_timer;
2356         }
2357
2358         rv = ipmi_smi_add_proc_entry(new_smi->intf, "si_stats",
2359                                      stat_file_read_proc, NULL,
2360                                      new_smi, THIS_MODULE);
2361         if (rv) {
2362                 printk(KERN_ERR
2363                        "ipmi_si: Unable to create proc entry: %d\n",
2364                        rv);
2365                 goto out_err_stop_timer;
2366         }
2367
2368         *smi = new_smi;
2369
2370         printk(" IPMI %s interface initialized\n", si_type[intf_num]);
2371
2372         return 0;
2373
2374  out_err_stop_timer:
2375         atomic_inc(&new_smi->stop_operation);
2376         wait_for_timer_and_thread(new_smi);
2377
2378  out_err:
2379         if (new_smi->intf)
2380                 ipmi_unregister_smi(new_smi->intf);
2381
2382         new_smi->irq_cleanup(new_smi);
2383
2384         /* Wait until we know that we are out of any interrupt
2385            handlers might have been running before we freed the
2386            interrupt. */
2387         synchronize_sched();
2388
2389         if (new_smi->si_sm) {
2390                 if (new_smi->handlers)
2391                         new_smi->handlers->cleanup(new_smi->si_sm);
2392                 kfree(new_smi->si_sm);
2393         }
2394         if (new_smi->io_cleanup)
2395                 new_smi->io_cleanup(new_smi);
2396
2397         return rv;
2398 }
2399
2400 static __init int init_ipmi_si(void)
2401 {
2402         int  rv = 0;
2403         int  pos = 0;
2404         int  i;
2405         char *str;
2406
2407         if (initialized)
2408                 return 0;
2409         initialized = 1;
2410
2411         /* Parse out the si_type string into its components. */
2412         str = si_type_str;
2413         if (*str != '\0') {
2414                 for (i = 0; (i < SI_MAX_PARMS) && (*str != '\0'); i++) {
2415                         si_type[i] = str;
2416                         str = strchr(str, ',');
2417                         if (str) {
2418                                 *str = '\0';
2419                                 str++;
2420                         } else {
2421                                 break;
2422                         }
2423                 }
2424         }
2425
2426         printk(KERN_INFO "IPMI System Interface driver.\n");
2427
2428 #ifdef CONFIG_DMI
2429         dmi_find_bmc();
2430 #endif
2431
2432         rv = init_one_smi(0, &(smi_infos[pos]));
2433         if (rv && ! ports[0] && si_trydefaults) {
2434                 /* If we are trying defaults and the initial port is
2435                    not set, then set it. */
2436                 si_type[0] = "kcs";
2437                 ports[0] = DEFAULT_KCS_IO_PORT;
2438                 rv = init_one_smi(0, &(smi_infos[pos]));
2439                 if (rv) {
2440                         /* No KCS - try SMIC */
2441                         si_type[0] = "smic";
2442                         ports[0] = DEFAULT_SMIC_IO_PORT;
2443                         rv = init_one_smi(0, &(smi_infos[pos]));
2444                 }
2445                 if (rv) {
2446                         /* No SMIC - try BT */
2447                         si_type[0] = "bt";
2448                         ports[0] = DEFAULT_BT_IO_PORT;
2449                         rv = init_one_smi(0, &(smi_infos[pos]));
2450                 }
2451         }
2452         if (rv == 0)
2453                 pos++;
2454
2455         for (i = 1; i < SI_MAX_PARMS; i++) {
2456                 rv = init_one_smi(i, &(smi_infos[pos]));
2457                 if (rv == 0)
2458                         pos++;
2459         }
2460
2461         if (smi_infos[0] == NULL) {
2462                 printk("ipmi_si: Unable to find any System Interface(s)\n");
2463                 return -ENODEV;
2464         }
2465
2466         return 0;
2467 }
2468 module_init(init_ipmi_si);
2469
2470 static void __exit cleanup_one_si(struct smi_info *to_clean)
2471 {
2472         int           rv;
2473         unsigned long flags;
2474
2475         if (! to_clean)
2476                 return;
2477
2478         /* Tell the timer and interrupt handlers that we are shutting
2479            down. */
2480         spin_lock_irqsave(&(to_clean->si_lock), flags);
2481         spin_lock(&(to_clean->msg_lock));
2482
2483         atomic_inc(&to_clean->stop_operation);
2484         to_clean->irq_cleanup(to_clean);
2485
2486         spin_unlock(&(to_clean->msg_lock));
2487         spin_unlock_irqrestore(&(to_clean->si_lock), flags);
2488
2489         /* Wait until we know that we are out of any interrupt
2490            handlers might have been running before we freed the
2491            interrupt. */
2492         synchronize_sched();
2493
2494         wait_for_timer_and_thread(to_clean);
2495
2496         /* Interrupts and timeouts are stopped, now make sure the
2497            interface is in a clean state. */
2498         while (to_clean->curr_msg || (to_clean->si_state != SI_NORMAL)) {
2499                 poll(to_clean);
2500                 schedule_timeout_uninterruptible(1);
2501         }
2502
2503         rv = ipmi_unregister_smi(to_clean->intf);
2504         if (rv) {
2505                 printk(KERN_ERR
2506                        "ipmi_si: Unable to unregister device: errno=%d\n",
2507                        rv);
2508         }
2509
2510         to_clean->handlers->cleanup(to_clean->si_sm);
2511
2512         kfree(to_clean->si_sm);
2513
2514         if (to_clean->io_cleanup)
2515                 to_clean->io_cleanup(to_clean);
2516 }
2517
2518 static __exit void cleanup_ipmi_si(void)
2519 {
2520         int i;
2521
2522         if (! initialized)
2523                 return;
2524
2525         for (i = 0; i < SI_MAX_DRIVERS; i++) {
2526                 cleanup_one_si(smi_infos[i]);
2527         }
2528 }
2529 module_exit(cleanup_ipmi_si);
2530
2531 MODULE_LICENSE("GPL");
2532 MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
2533 MODULE_DESCRIPTION("Interface to the IPMI driver for the KCS, SMIC, and BT system interfaces.");