commented early_printk patch because of rejects.
[linux-flexiantxendom0-3.2.10.git] / drivers / char / ipmi / ipmi_kcs_intf.c
1 /*
2  * ipmi_kcs_intf.c
3  *
4  * The interface to the IPMI driver for the KCS.
5  *
6  * Author: MontaVista Software, Inc.
7  *         Corey Minyard <minyard@mvista.com>
8  *         source@mvista.com
9  *
10  * Copyright 2002 MontaVista Software Inc.
11  *
12  *  This program is free software; you can redistribute it and/or modify it
13  *  under the terms of the GNU General Public License as published by the
14  *  Free Software Foundation; either version 2 of the License, or (at your
15  *  option) any later version.
16  *
17  *
18  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
19  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
26  *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27  *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  *  You should have received a copy of the GNU General Public License along
30  *  with this program; if not, write to the Free Software Foundation, Inc.,
31  *  675 Mass Ave, Cambridge, MA 02139, USA.
32  */
33
34 /*
35  * This file holds the "policy" for the interface to the KCS state
36  * machine.  It does the configuration, handles timers and interrupts,
37  * and drives the real KCS state machine.
38  */
39
40 #include <linux/config.h>
41 #include <linux/module.h>
42 #include <asm/system.h>
43 #include <linux/sched.h>
44 #include <linux/timer.h>
45 #include <linux/errno.h>
46 #include <linux/spinlock.h>
47 #include <linux/slab.h>
48 #include <linux/delay.h>
49 #include <linux/list.h>
50 #include <linux/ioport.h>
51 #ifdef CONFIG_HIGH_RES_TIMERS
52 #include <linux/hrtime.h>
53 #endif
54 #include <linux/interrupt.h>
55 #include <linux/rcupdate.h>
56 #include <linux/ipmi_smi.h>
57 #include <asm/io.h>
58 #include "ipmi_kcs_sm.h"
59 #include <linux/init.h>
60
61 /* Measure times between events in the driver. */
62 #undef DEBUG_TIMING
63
64 /* Timing parameters.  Call every 10 ms when not doing anything,
65    otherwise call every KCS_SHORT_TIMEOUT_USEC microseconds. */
66 #define KCS_TIMEOUT_TIME_USEC   10000
67 #define KCS_USEC_PER_JIFFY      (1000000/HZ)
68 #define KCS_TIMEOUT_JIFFIES     (KCS_TIMEOUT_TIME_USEC/KCS_USEC_PER_JIFFY)
69 #define KCS_SHORT_TIMEOUT_USEC  250 /* .25ms when the SM request a
70                                        short timeout */
71
72 #ifdef CONFIG_IPMI_KCS
73 /* This forces a dependency to the config file for this option. */
74 #endif
75
76 enum kcs_intf_state {
77         KCS_NORMAL,
78         KCS_GETTING_FLAGS,
79         KCS_GETTING_EVENTS,
80         KCS_CLEARING_FLAGS,
81         KCS_CLEARING_FLAGS_THEN_SET_IRQ,
82         KCS_GETTING_MESSAGES,
83         KCS_ENABLE_INTERRUPTS1,
84         KCS_ENABLE_INTERRUPTS2
85         /* FIXME - add watchdog stuff. */
86 };
87
88 struct kcs_info
89 {
90         ipmi_smi_t          intf;
91         struct kcs_data     *kcs_sm;
92         spinlock_t          kcs_lock;
93         spinlock_t          msg_lock;
94         struct list_head    xmit_msgs;
95         struct list_head    hp_xmit_msgs;
96         struct ipmi_smi_msg *curr_msg;
97         enum kcs_intf_state kcs_state;
98
99         /* Flags from the last GET_MSG_FLAGS command, used when an ATTN
100            is set to hold the flags until we are done handling everything
101            from the flags. */
102 #define RECEIVE_MSG_AVAIL       0x01
103 #define EVENT_MSG_BUFFER_FULL   0x02
104 #define WDT_PRE_TIMEOUT_INT     0x08
105         unsigned char       msg_flags;
106
107         /* If set to true, this will request events the next time the
108            state machine is idle. */
109         atomic_t            req_events;
110
111         /* If true, run the state machine to completion on every send
112            call.  Generally used after a panic to make sure stuff goes
113            out. */
114         int                 run_to_completion;
115
116         /* The I/O port of a KCS interface. */
117         int                 port;
118
119         /* zero if no irq; */
120         int                 irq;
121
122         /* The physical and remapped memory addresses of a KCS interface. */
123         unsigned long       physaddr;
124         unsigned char       *addr;
125
126         /* The timer for this kcs. */
127         struct timer_list   kcs_timer;
128
129         /* The time (in jiffies) the last timeout occurred at. */
130         unsigned long       last_timeout_jiffies;
131
132         /* Used to gracefully stop the timer without race conditions. */
133         volatile int        stop_operation;
134         volatile int        timer_stopped;
135
136         /* The driver will disable interrupts when it gets into a
137            situation where it cannot handle messages due to lack of
138            memory.  Once that situation clears up, it will re-enable
139            interrupts. */
140         int                 interrupt_disabled;
141 };
142
143 static void kcs_restart_short_timer(struct kcs_info *kcs_info);
144
145 static void deliver_recv_msg(struct kcs_info *kcs_info, struct ipmi_smi_msg *msg)
146 {
147         /* Deliver the message to the upper layer with the lock
148            released. */
149         spin_unlock(&(kcs_info->kcs_lock));
150         ipmi_smi_msg_received(kcs_info->intf, msg);
151         spin_lock(&(kcs_info->kcs_lock));
152 }
153
154 static void return_hosed_msg(struct kcs_info *kcs_info)
155 {
156         struct ipmi_smi_msg *msg = kcs_info->curr_msg;
157
158         /* Make it a reponse */
159         msg->rsp[0] = msg->data[0] | 4;
160         msg->rsp[1] = msg->data[1];
161         msg->rsp[2] = 0xFF; /* Unknown error. */
162         msg->rsp_size = 3;
163                         
164         kcs_info->curr_msg = NULL;
165         deliver_recv_msg(kcs_info, msg);
166 }
167
168 static enum kcs_result start_next_msg(struct kcs_info *kcs_info)
169 {
170         int              rv;
171         struct list_head *entry = NULL;
172 #ifdef DEBUG_TIMING
173         struct timeval t;
174 #endif
175
176         /* No need to save flags, we aleady have interrupts off and we
177            already hold the KCS lock. */
178         spin_lock(&(kcs_info->msg_lock));
179         
180         /* Pick the high priority queue first. */
181         if (! list_empty(&(kcs_info->hp_xmit_msgs))) {
182                 entry = kcs_info->hp_xmit_msgs.next;
183         } else if (! list_empty(&(kcs_info->xmit_msgs))) {
184                 entry = kcs_info->xmit_msgs.next;
185         }
186
187         if (!entry) {
188                 kcs_info->curr_msg = NULL;
189                 rv = KCS_SM_IDLE;
190         } else {
191                 int err;
192
193                 list_del(entry);
194                 kcs_info->curr_msg = list_entry(entry,
195                                                 struct ipmi_smi_msg,
196                                                 link);
197 #ifdef DEBUG_TIMING
198                 do_gettimeofday(&t);
199                 printk("**Start2: %d.%9.9d\n", t.tv_sec, t.tv_usec);
200 #endif
201                 err = start_kcs_transaction(kcs_info->kcs_sm,
202                                            kcs_info->curr_msg->data,
203                                            kcs_info->curr_msg->data_size);
204                 if (err) {
205                         return_hosed_msg(kcs_info);
206                 }
207
208                 rv = KCS_CALL_WITHOUT_DELAY;
209         }
210         spin_unlock(&(kcs_info->msg_lock));
211
212         return rv;
213 }
214
215 static void start_enable_irq(struct kcs_info *kcs_info)
216 {
217         unsigned char msg[2];
218
219         /* If we are enabling interrupts, we have to tell the
220            BMC to use them. */
221         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
222         msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
223
224         start_kcs_transaction(kcs_info->kcs_sm, msg, 2);
225         kcs_info->kcs_state = KCS_ENABLE_INTERRUPTS1;
226 }
227
228 static void start_clear_flags(struct kcs_info *kcs_info)
229 {
230         unsigned char msg[3];
231
232         /* Make sure the watchdog pre-timeout flag is not set at startup. */
233         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
234         msg[1] = IPMI_CLEAR_MSG_FLAGS_CMD;
235         msg[2] = WDT_PRE_TIMEOUT_INT;
236
237         start_kcs_transaction(kcs_info->kcs_sm, msg, 3);
238         kcs_info->kcs_state = KCS_CLEARING_FLAGS;
239 }
240
241 /* When we have a situtaion where we run out of memory and cannot
242    allocate messages, we just leave them in the BMC and run the system
243    polled until we can allocate some memory.  Once we have some
244    memory, we will re-enable the interrupt. */
245 static inline void disable_kcs_irq(struct kcs_info *kcs_info)
246 {
247         if ((kcs_info->irq) && (!kcs_info->interrupt_disabled)) {
248                 disable_irq_nosync(kcs_info->irq);
249                 kcs_info->interrupt_disabled = 1;
250         }
251 }
252
253 static inline void enable_kcs_irq(struct kcs_info *kcs_info)
254 {
255         if ((kcs_info->irq) && (kcs_info->interrupt_disabled)) {
256                 enable_irq(kcs_info->irq);
257                 kcs_info->interrupt_disabled = 0;
258         }
259 }
260
261 static void handle_flags(struct kcs_info *kcs_info)
262 {
263         if (kcs_info->msg_flags & WDT_PRE_TIMEOUT_INT) {
264                 /* Watchdog pre-timeout */
265                 start_clear_flags(kcs_info);
266                 kcs_info->msg_flags &= ~WDT_PRE_TIMEOUT_INT;
267                 spin_unlock(&(kcs_info->kcs_lock));
268                 ipmi_smi_watchdog_pretimeout(kcs_info->intf);
269                 spin_lock(&(kcs_info->kcs_lock));
270         } else if (kcs_info->msg_flags & RECEIVE_MSG_AVAIL) {
271                 /* Messages available. */
272                 kcs_info->curr_msg = ipmi_alloc_smi_msg();
273                 if (!kcs_info->curr_msg) {
274                         disable_kcs_irq(kcs_info);
275                         kcs_info->kcs_state = KCS_NORMAL;
276                         return;
277                 }
278                 enable_kcs_irq(kcs_info);
279
280                 kcs_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
281                 kcs_info->curr_msg->data[1] = IPMI_GET_MSG_CMD;
282                 kcs_info->curr_msg->data_size = 2;
283
284                 start_kcs_transaction(kcs_info->kcs_sm,
285                                       kcs_info->curr_msg->data,
286                                       kcs_info->curr_msg->data_size);
287                 kcs_info->kcs_state = KCS_GETTING_MESSAGES;
288         } else if (kcs_info->msg_flags & EVENT_MSG_BUFFER_FULL) {
289                 /* Events available. */
290                 kcs_info->curr_msg = ipmi_alloc_smi_msg();
291                 if (!kcs_info->curr_msg) {
292                         disable_kcs_irq(kcs_info);
293                         kcs_info->kcs_state = KCS_NORMAL;
294                         return;
295                 }
296                 enable_kcs_irq(kcs_info);
297
298                 kcs_info->curr_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
299                 kcs_info->curr_msg->data[1] = IPMI_READ_EVENT_MSG_BUFFER_CMD;
300                 kcs_info->curr_msg->data_size = 2;
301
302                 start_kcs_transaction(kcs_info->kcs_sm,
303                                       kcs_info->curr_msg->data,
304                                       kcs_info->curr_msg->data_size);
305                 kcs_info->kcs_state = KCS_GETTING_EVENTS;
306         } else {
307                 kcs_info->kcs_state = KCS_NORMAL;
308         }
309 }
310
311 static void handle_transaction_done(struct kcs_info *kcs_info)
312 {
313         struct ipmi_smi_msg *msg;
314 #ifdef DEBUG_TIMING
315         struct timeval t;
316
317         do_gettimeofday(&t);
318         printk("**Done: %d.%9.9d\n", t.tv_sec, t.tv_usec);
319 #endif
320         switch (kcs_info->kcs_state) {
321         case KCS_NORMAL:
322                 if (!kcs_info->curr_msg)
323                         break;
324                         
325                 kcs_info->curr_msg->rsp_size
326                         = kcs_get_result(kcs_info->kcs_sm,
327                                          kcs_info->curr_msg->rsp,
328                                          IPMI_MAX_MSG_LENGTH);
329                 
330                 /* Do this here becase deliver_recv_msg() releases the
331                    lock, and a new message can be put in during the
332                    time the lock is released. */
333                 msg = kcs_info->curr_msg;
334                 kcs_info->curr_msg = NULL;
335                 deliver_recv_msg(kcs_info, msg);
336                 break;
337                 
338         case KCS_GETTING_FLAGS:
339         {
340                 unsigned char msg[4];
341                 unsigned int  len;
342
343                 /* We got the flags from the KCS, now handle them. */
344                 len = kcs_get_result(kcs_info->kcs_sm, msg, 4);
345                 if (msg[2] != 0) {
346                         /* Error fetching flags, just give up for
347                            now. */
348                         kcs_info->kcs_state = KCS_NORMAL;
349                 } else if (len < 3) {
350                         /* Hmm, no flags.  That's technically illegal, but
351                            don't use uninitialized data. */
352                         kcs_info->kcs_state = KCS_NORMAL;
353                 } else {
354                         kcs_info->msg_flags = msg[3];
355                         handle_flags(kcs_info);
356                 }
357                 break;
358         }
359
360         case KCS_CLEARING_FLAGS:
361         case KCS_CLEARING_FLAGS_THEN_SET_IRQ:
362         {
363                 unsigned char msg[3];
364
365                 /* We cleared the flags. */
366                 kcs_get_result(kcs_info->kcs_sm, msg, 3);
367                 if (msg[2] != 0) {
368                         /* Error clearing flags */
369                         printk(KERN_WARNING
370                                "ipmi_kcs: Error clearing flags: %2.2x\n",
371                                msg[2]);
372                 }
373                 if (kcs_info->kcs_state == KCS_CLEARING_FLAGS_THEN_SET_IRQ)
374                         start_enable_irq(kcs_info);
375                 else
376                         kcs_info->kcs_state = KCS_NORMAL;
377                 break;
378         }
379
380         case KCS_GETTING_EVENTS:
381         {
382                 kcs_info->curr_msg->rsp_size
383                         = kcs_get_result(kcs_info->kcs_sm,
384                                          kcs_info->curr_msg->rsp,
385                                          IPMI_MAX_MSG_LENGTH);
386
387                 /* Do this here becase deliver_recv_msg() releases the
388                    lock, and a new message can be put in during the
389                    time the lock is released. */
390                 msg = kcs_info->curr_msg;
391                 kcs_info->curr_msg = NULL;
392                 if (msg->rsp[2] != 0) {
393                         /* Error getting event, probably done. */
394                         msg->done(msg);
395
396                         /* Take off the event flag. */
397                         kcs_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
398                 } else {
399                         deliver_recv_msg(kcs_info, msg);
400                 }
401                 handle_flags(kcs_info);
402                 break;
403         }
404
405         case KCS_GETTING_MESSAGES:
406         {
407                 kcs_info->curr_msg->rsp_size
408                         = kcs_get_result(kcs_info->kcs_sm,
409                                          kcs_info->curr_msg->rsp,
410                                          IPMI_MAX_MSG_LENGTH);
411
412                 /* Do this here becase deliver_recv_msg() releases the
413                    lock, and a new message can be put in during the
414                    time the lock is released. */
415                 msg = kcs_info->curr_msg;
416                 kcs_info->curr_msg = NULL;
417                 if (msg->rsp[2] != 0) {
418                         /* Error getting event, probably done. */
419                         msg->done(msg);
420
421                         /* Take off the msg flag. */
422                         kcs_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
423                 } else {
424                         deliver_recv_msg(kcs_info, msg);
425                 }
426                 handle_flags(kcs_info);
427                 break;
428         }
429
430         case KCS_ENABLE_INTERRUPTS1:
431         {
432                 unsigned char msg[4];
433
434                 /* We got the flags from the KCS, now handle them. */
435                 kcs_get_result(kcs_info->kcs_sm, msg, 4);
436                 if (msg[2] != 0) {
437                         printk(KERN_WARNING
438                                "ipmi_kcs: Could not enable interrupts"
439                                ", failed get, using polled mode.\n");
440                         kcs_info->kcs_state = KCS_NORMAL;
441                 } else {
442                         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
443                         msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
444                         msg[2] = msg[3] | 1; /* enable msg queue int */
445                         start_kcs_transaction(kcs_info->kcs_sm, msg,3);
446                         kcs_info->kcs_state = KCS_ENABLE_INTERRUPTS2;
447                 }
448                 break;
449         }
450
451         case KCS_ENABLE_INTERRUPTS2:
452         {
453                 unsigned char msg[4];
454
455                 /* We got the flags from the KCS, now handle them. */
456                 kcs_get_result(kcs_info->kcs_sm, msg, 4);
457                 if (msg[2] != 0) {
458                         printk(KERN_WARNING
459                                "ipmi_kcs: Could not enable interrupts"
460                                ", failed set, using polled mode.\n");
461                 }
462                 kcs_info->kcs_state = KCS_NORMAL;
463                 break;
464         }
465         }
466 }
467
468 /* Called on timeouts and events.  Timeouts should pass the elapsed
469    time, interrupts should pass in zero. */
470 static enum kcs_result kcs_event_handler(struct kcs_info *kcs_info, int time)
471 {
472         enum kcs_result kcs_result;
473
474  restart:
475         /* There used to be a loop here that waited a little while
476            (around 25us) before giving up.  That turned out to be
477            pointless, the minimum delays I was seeing were in the 300us
478            range, which is far too long to wait in an interrupt.  So
479            we just run until the state machine tells us something
480            happened or it needs a delay. */
481         kcs_result = kcs_event(kcs_info->kcs_sm, time);
482         time = 0;
483         while (kcs_result == KCS_CALL_WITHOUT_DELAY)
484         {
485                 kcs_result = kcs_event(kcs_info->kcs_sm, 0);
486         }
487
488         if (kcs_result == KCS_TRANSACTION_COMPLETE)
489         {
490                 handle_transaction_done(kcs_info);
491                 kcs_result = kcs_event(kcs_info->kcs_sm, 0);
492         }
493         else if (kcs_result == KCS_SM_HOSED)
494         {
495                 if (kcs_info->curr_msg != NULL) {
496                         /* If we were handling a user message, format
497                            a response to send to the upper layer to
498                            tell it about the error. */
499                         return_hosed_msg(kcs_info);
500                 }
501                 kcs_result = kcs_event(kcs_info->kcs_sm, 0);
502                 kcs_info->kcs_state = KCS_NORMAL;
503         }
504
505         /* We prefer handling attn over new messages. */
506         if (kcs_result == KCS_ATTN)
507         {
508                 unsigned char msg[2];
509
510                 /* Got a attn, send down a get message flags to see
511                    what's causing it.  It would be better to handle
512                    this in the upper layer, but due to the way
513                    interrupts work with the KCS, that's not really
514                    possible. */
515                 msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
516                 msg[1] = IPMI_GET_MSG_FLAGS_CMD;
517
518                 start_kcs_transaction(kcs_info->kcs_sm, msg, 2);
519                 kcs_info->kcs_state = KCS_GETTING_FLAGS;
520                 goto restart;
521         }
522
523         /* If we are currently idle, try to start the next message. */
524         if (kcs_result == KCS_SM_IDLE) {
525                 kcs_result = start_next_msg(kcs_info);
526                 if (kcs_result != KCS_SM_IDLE)
527                         goto restart;
528         }
529
530         if ((kcs_result == KCS_SM_IDLE)
531             && (atomic_read(&kcs_info->req_events)))
532         {
533                 /* We are idle and the upper layer requested that I fetch
534                    events, so do so. */
535                 unsigned char msg[2];
536
537                 atomic_set(&kcs_info->req_events, 0);
538                 msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
539                 msg[1] = IPMI_GET_MSG_FLAGS_CMD;
540
541                 start_kcs_transaction(kcs_info->kcs_sm, msg, 2);
542                 kcs_info->kcs_state = KCS_GETTING_FLAGS;
543                 goto restart;
544         }
545
546         return kcs_result;
547 }
548
549 static void sender(void                *send_info,
550                    struct ipmi_smi_msg *msg,
551                    int                 priority)
552 {
553         struct kcs_info *kcs_info = (struct kcs_info *) send_info;
554         enum kcs_result result;
555         unsigned long   flags;
556 #ifdef DEBUG_TIMING
557         struct timeval t;
558 #endif
559
560         spin_lock_irqsave(&(kcs_info->msg_lock), flags);
561 #ifdef DEBUG_TIMING
562         do_gettimeofday(&t);
563         printk("**Enqueue: %d.%9.9d\n", t.tv_sec, t.tv_usec);
564 #endif
565
566         if (kcs_info->run_to_completion) {
567                 /* If we are running to completion, then throw it in
568                    the list and run transactions until everything is
569                    clear.  Priority doesn't matter here. */
570                 list_add_tail(&(msg->link), &(kcs_info->xmit_msgs));
571
572                 /* We have to release the msg lock and claim the kcs
573                    lock in this case, because of race conditions. */
574                 spin_unlock_irqrestore(&(kcs_info->msg_lock), flags);
575
576                 spin_lock_irqsave(&(kcs_info->kcs_lock), flags);
577                 result = kcs_event_handler(kcs_info, 0);
578                 while (result != KCS_SM_IDLE) {
579                         udelay(KCS_SHORT_TIMEOUT_USEC);
580                         result = kcs_event_handler(kcs_info,
581                                                    KCS_SHORT_TIMEOUT_USEC);
582                 }
583                 spin_unlock_irqrestore(&(kcs_info->kcs_lock), flags);
584                 return;
585         } else {
586                 if (priority > 0) {
587                         list_add_tail(&(msg->link), &(kcs_info->hp_xmit_msgs));
588                 } else {
589                         list_add_tail(&(msg->link), &(kcs_info->xmit_msgs));
590                 }
591         }
592         spin_unlock_irqrestore(&(kcs_info->msg_lock), flags);
593
594         spin_lock_irqsave(&(kcs_info->kcs_lock), flags);
595         if ((kcs_info->kcs_state == KCS_NORMAL)
596             && (kcs_info->curr_msg == NULL))
597         {
598                 start_next_msg(kcs_info);
599                 kcs_restart_short_timer(kcs_info);
600         }
601         spin_unlock_irqrestore(&(kcs_info->kcs_lock), flags);
602 }
603
604 static void set_run_to_completion(void *send_info, int i_run_to_completion)
605 {
606         struct kcs_info *kcs_info = (struct kcs_info *) send_info;
607         enum kcs_result result;
608         unsigned long   flags;
609
610         spin_lock_irqsave(&(kcs_info->kcs_lock), flags);
611
612         kcs_info->run_to_completion = i_run_to_completion;
613         if (i_run_to_completion) {
614                 result = kcs_event_handler(kcs_info, 0);
615                 while (result != KCS_SM_IDLE) {
616                         udelay(KCS_SHORT_TIMEOUT_USEC);
617                         result = kcs_event_handler(kcs_info,
618                                                    KCS_SHORT_TIMEOUT_USEC);
619                 }
620         }
621
622         spin_unlock_irqrestore(&(kcs_info->kcs_lock), flags);
623 }
624
625 static void request_events(void *send_info)
626 {
627         struct kcs_info *kcs_info = (struct kcs_info *) send_info;
628
629         atomic_set(&kcs_info->req_events, 1);
630 }
631
632 static int initialized = 0;
633
634 /* Must be called with interrupts off and with the kcs_lock held. */
635 static void kcs_restart_short_timer(struct kcs_info *kcs_info)
636 {
637         if (del_timer(&(kcs_info->kcs_timer))) {
638 #ifdef CONFIG_HIGH_RES_TIMERS
639                 unsigned long jiffies_now;
640
641                 /* If we don't delete the timer, then it will go off
642                    immediately, anyway.  So we only process if we
643                    actually delete the timer. */
644
645                 /* We already have irqsave on, so no need for it
646                    here. */
647                 read_lock(&xtime_lock);
648                 jiffies_now = jiffies;
649                 kcs_info->kcs_timer.expires = jiffies_now;
650
651                 kcs_info->kcs_timer.sub_expires
652                         = quick_update_jiffies_sub(jiffies_now);
653                 read_unlock(&xtime_lock);
654
655                 kcs_info->kcs_timer.sub_expires
656                         += usec_to_arch_cycles(KCS_SHORT_TIMEOUT_USEC);
657                 while (kcs_info->kcs_timer.sub_expires >= cycles_per_jiffies) {
658                         kcs_info->kcs_timer.expires++;
659                         kcs_info->kcs_timer.sub_expires -= cycles_per_jiffies;
660                 }
661 #else
662                 kcs_info->kcs_timer.expires = jiffies + 1;
663 #endif
664                 add_timer(&(kcs_info->kcs_timer));
665         }
666 }
667
668 static void kcs_timeout(unsigned long data)
669 {
670         struct kcs_info *kcs_info = (struct kcs_info *) data;
671         enum kcs_result kcs_result;
672         unsigned long   flags;
673         unsigned long   jiffies_now;
674         unsigned long   time_diff;
675 #ifdef DEBUG_TIMING
676         struct timeval t;
677 #endif
678
679         if (kcs_info->stop_operation) {
680                 kcs_info->timer_stopped = 1;
681                 return;
682         }
683
684         spin_lock_irqsave(&(kcs_info->kcs_lock), flags);
685 #ifdef DEBUG_TIMING
686         do_gettimeofday(&t);
687         printk("**Timer: %d.%9.9d\n", t.tv_sec, t.tv_usec);
688 #endif
689         jiffies_now = jiffies;
690
691         time_diff = ((jiffies_now - kcs_info->last_timeout_jiffies)
692                      * KCS_USEC_PER_JIFFY);
693         kcs_result = kcs_event_handler(kcs_info, time_diff);
694
695         kcs_info->last_timeout_jiffies = jiffies_now;
696
697         if ((kcs_info->irq) && (! kcs_info->interrupt_disabled)) {
698                 /* Running with interrupts, only do long timeouts. */
699                 kcs_info->kcs_timer.expires = jiffies + KCS_TIMEOUT_JIFFIES;
700                 goto do_add_timer;
701         }
702
703         /* If the state machine asks for a short delay, then shorten
704            the timer timeout. */
705 #ifdef CONFIG_HIGH_RES_TIMERS
706         if (kcs_result == KCS_CALL_WITH_DELAY) {
707                 kcs_info->kcs_timer.sub_expires
708                         += usec_to_arch_cycles(KCS_SHORT_TIMEOUT_USEC);
709                 while (kcs_info->kcs_timer.sub_expires >= cycles_per_jiffies) {
710                         kcs_info->kcs_timer.expires++;
711                         kcs_info->kcs_timer.sub_expires -= cycles_per_jiffies;
712                 }
713         } else {
714                 kcs_info->kcs_timer.expires = jiffies + KCS_TIMEOUT_JIFFIES;
715                 kcs_info->kcs_timer.sub_expires = 0;
716         }
717 #else
718         /* If requested, take the shortest delay possible */
719         if (kcs_result == KCS_CALL_WITH_DELAY) {
720                 kcs_info->kcs_timer.expires = jiffies + 1;
721         } else {
722                 kcs_info->kcs_timer.expires = jiffies + KCS_TIMEOUT_JIFFIES;
723         }
724 #endif
725
726  do_add_timer:
727         add_timer(&(kcs_info->kcs_timer));
728         spin_unlock_irqrestore(&(kcs_info->kcs_lock), flags);
729 }
730
731 static irqreturn_t kcs_irq_handler(int irq, void *data, struct pt_regs *regs)
732 {
733         struct kcs_info *kcs_info = (struct kcs_info *) data;
734         unsigned long   flags;
735 #ifdef DEBUG_TIMING
736         struct timeval t;
737 #endif
738
739         spin_lock_irqsave(&(kcs_info->kcs_lock), flags);
740         if (kcs_info->stop_operation)
741                 goto out;
742
743 #ifdef DEBUG_TIMING
744         do_gettimeofday(&t);
745         printk("**Interrupt: %d.%9.9d\n", t.tv_sec, t.tv_usec);
746 #endif
747         kcs_event_handler(kcs_info, 0);
748  out:
749         spin_unlock_irqrestore(&(kcs_info->kcs_lock), flags);
750         return IRQ_HANDLED;
751 }
752
753 static struct ipmi_smi_handlers handlers =
754 {
755         .owner                  = THIS_MODULE,
756         .sender                 = sender,
757         .request_events         = request_events,
758         .set_run_to_completion  = set_run_to_completion,
759 };
760
761 static unsigned char ipmi_kcs_dev_rev;
762 static unsigned char ipmi_kcs_fw_rev_major;
763 static unsigned char ipmi_kcs_fw_rev_minor;
764 static unsigned char ipmi_version_major;
765 static unsigned char ipmi_version_minor;
766
767 extern int kcs_dbg;
768 static int ipmi_kcs_detect_hardware(unsigned int port,
769                                     unsigned char *addr,
770                                     struct kcs_data *data)
771 {
772         unsigned char   msg[2];
773         unsigned char   resp[IPMI_MAX_MSG_LENGTH];
774         unsigned long   resp_len;
775         enum kcs_result kcs_result;
776
777         /* It's impossible for the KCS status register to be all 1's,
778            (assuming a properly functioning, self-initialized BMC)
779            but that's what you get from reading a bogus address, so we
780            test that first. */
781
782         if (port) {
783                 if (inb(port+1) == 0xff) return -ENODEV; 
784         } else { 
785                 if (readb(addr+1) == 0xff) return -ENODEV; 
786         }
787
788         /* Do a Get Device ID command, since it comes back with some
789            useful info. */
790         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
791         msg[1] = IPMI_GET_DEVICE_ID_CMD;
792         start_kcs_transaction(data, msg, 2);
793         
794         kcs_result = kcs_event(data, 0);
795         for (;;)
796         {
797                 if (kcs_result == KCS_CALL_WITH_DELAY) {
798                         udelay(100);
799                         kcs_result = kcs_event(data, 100);
800                 }
801                 else if (kcs_result == KCS_CALL_WITHOUT_DELAY)
802                 {
803                         kcs_result = kcs_event(data, 0);
804                 }
805                 else
806                         break;
807         }
808         if (kcs_result == KCS_SM_HOSED) {
809                 /* We couldn't get the state machine to run, so whatever's at
810                    the port is probably not an IPMI KCS interface. */
811                 return -ENODEV;
812         }
813         /* Otherwise, we got some data. */
814         resp_len = kcs_get_result(data, resp, IPMI_MAX_MSG_LENGTH);
815         if (resp_len < 6)
816                 /* That's odd, it should be longer. */
817                 return -EINVAL;
818         
819         if ((resp[1] != IPMI_GET_DEVICE_ID_CMD) || (resp[2] != 0))
820                 /* That's odd, it shouldn't be able to fail. */
821                 return -EINVAL;
822         
823         ipmi_kcs_dev_rev = resp[4] & 0xf;
824         ipmi_kcs_fw_rev_major = resp[5] & 0x7f;
825         ipmi_kcs_fw_rev_minor = resp[6];
826         ipmi_version_major = resp[7] & 0xf;
827         ipmi_version_minor = resp[7] >> 4;
828
829         return 0;
830 }
831
832 /* There can be 4 IO ports passed in (with or without IRQs), 4 addresses,
833    a default IO port, and 1 ACPI/SPMI address.  That sets KCS_MAX_DRIVERS */
834
835 #define KCS_MAX_PARMS 4
836 #define KCS_MAX_DRIVERS ((KCS_MAX_PARMS * 2) + 2)
837 static struct kcs_info *kcs_infos[KCS_MAX_DRIVERS] =
838 { NULL, NULL, NULL, NULL };
839
840 #define DEVICE_NAME "ipmi_kcs"
841
842 #define DEFAULT_IO_PORT 0xca2
843
844 static int kcs_trydefaults = 1;
845 static unsigned long kcs_addrs[KCS_MAX_PARMS] = { 0, 0, 0, 0 };
846 static int kcs_ports[KCS_MAX_PARMS] = { 0, 0, 0, 0 };
847 static int kcs_irqs[KCS_MAX_PARMS] = { 0, 0, 0, 0 };
848
849 MODULE_PARM(kcs_trydefaults, "i");
850 MODULE_PARM(kcs_addrs, "1-4l");
851 MODULE_PARM(kcs_irqs, "1-4i");
852 MODULE_PARM(kcs_ports, "1-4i");
853
854 /* Returns 0 if initialized, or negative on an error. */
855 static int init_one_kcs(int kcs_port, 
856                         int irq, 
857                         unsigned long kcs_physaddr,
858                         struct kcs_info **kcs)
859 {
860         int             rv;
861         struct kcs_info *new_kcs;
862
863         /* Did anything get passed in at all?  Both == zero disables the
864            driver. */
865
866         if (!(kcs_port || kcs_physaddr)) 
867                 return -ENODEV;
868         
869         /* Only initialize a port OR a physical address on this call.
870            Also, IRQs can go with either ports or addresses. */
871
872         if (kcs_port && kcs_physaddr)
873                 return -EINVAL;
874
875         new_kcs = kmalloc(sizeof(*new_kcs), GFP_KERNEL);
876         if (!new_kcs) {
877                 printk(KERN_ERR "ipmi_kcs: out of memory\n");
878                 return -ENOMEM;
879         }
880
881         /* So we know not to free it unless we have allocated one. */
882         new_kcs->kcs_sm = NULL;
883
884         new_kcs->addr = NULL;
885         new_kcs->physaddr = kcs_physaddr;
886         new_kcs->port = kcs_port;
887
888         if (kcs_port) {
889                 if (request_region(kcs_port, 2, DEVICE_NAME) == NULL) {
890                         kfree(new_kcs);
891                         printk(KERN_ERR 
892                                "ipmi_kcs: can't reserve port @ 0x%4.4x\n",
893                                kcs_port);
894                         return -EIO;
895                 }
896         } else {
897                 if (request_mem_region(kcs_physaddr, 2, DEVICE_NAME) == NULL) {
898                         kfree(new_kcs);
899                         printk(KERN_ERR 
900                                "ipmi_kcs: can't reserve memory @ 0x%lx\n",
901                                kcs_physaddr);
902                         return -EIO;
903                 }
904                 if ((new_kcs->addr = ioremap(kcs_physaddr, 2)) == NULL) {
905                         kfree(new_kcs);
906                         printk(KERN_ERR 
907                                "ipmi_kcs: can't remap memory at 0x%lx\n",
908                                kcs_physaddr);
909                         return -EIO;
910                 }
911         }
912
913         new_kcs->kcs_sm = kmalloc(kcs_size(), GFP_KERNEL);
914         if (!new_kcs->kcs_sm) {
915                 printk(KERN_ERR "ipmi_kcs: out of memory\n");
916                 rv = -ENOMEM;
917                 goto out_err;
918         }
919         init_kcs_data(new_kcs->kcs_sm, kcs_port, new_kcs->addr);
920         spin_lock_init(&(new_kcs->kcs_lock));
921         spin_lock_init(&(new_kcs->msg_lock));
922
923         rv = ipmi_kcs_detect_hardware(kcs_port, new_kcs->addr, new_kcs->kcs_sm);
924         if (rv) {
925                 if (kcs_port) 
926                         printk(KERN_ERR 
927                                "ipmi_kcs: No KCS @ port 0x%4.4x\n", 
928                                kcs_port);
929                 else
930                         printk(KERN_ERR 
931                                "ipmi_kcs: No KCS @ addr 0x%lx\n", 
932                                kcs_physaddr);
933                 goto out_err;
934         }
935
936         if (irq != 0) {
937                 rv = request_irq(irq,
938                                  kcs_irq_handler,
939                                  SA_INTERRUPT,
940                                  DEVICE_NAME,
941                                  new_kcs);
942                 if (rv) {
943                         printk(KERN_WARNING
944                                "ipmi_kcs: %s unable to claim interrupt %d,"
945                                " running polled\n",
946                                DEVICE_NAME, irq);
947                         irq = 0;
948                 }
949         }
950         new_kcs->irq = irq;
951
952         INIT_LIST_HEAD(&(new_kcs->xmit_msgs));
953         INIT_LIST_HEAD(&(new_kcs->hp_xmit_msgs));
954         new_kcs->curr_msg = NULL;
955         atomic_set(&new_kcs->req_events, 0);
956         new_kcs->run_to_completion = 0;
957
958         start_clear_flags(new_kcs);
959
960         if (irq) {
961                 new_kcs->kcs_state = KCS_CLEARING_FLAGS_THEN_SET_IRQ;
962
963                 printk(KERN_INFO 
964                        "ipmi_kcs: Acquiring BMC @ port=0x%x irq=%d\n",
965                        kcs_port, irq);
966
967         } else {
968                 if (kcs_port)
969                         printk(KERN_INFO 
970                                "ipmi_kcs: Acquiring BMC @ port=0x%x\n",
971                                kcs_port);
972                 else
973                         printk(KERN_INFO 
974                                "ipmi_kcs: Acquiring BMC @ addr=0x%lx\n",
975                                kcs_physaddr);
976         }
977
978         rv = ipmi_register_smi(&handlers,
979                                new_kcs,
980                                ipmi_version_major,
981                                ipmi_version_minor,
982                                &(new_kcs->intf));
983         if (rv) {
984                 free_irq(irq, new_kcs);
985                 printk(KERN_ERR 
986                        "ipmi_kcs: Unable to register device: error %d\n",
987                        rv);
988                 goto out_err;
989         }
990
991         new_kcs->interrupt_disabled = 0;
992         new_kcs->timer_stopped = 0;
993         new_kcs->stop_operation = 0;
994
995         init_timer(&(new_kcs->kcs_timer));
996         new_kcs->kcs_timer.data = (long) new_kcs;
997         new_kcs->kcs_timer.function = kcs_timeout;
998         new_kcs->last_timeout_jiffies = jiffies;
999         new_kcs->kcs_timer.expires = jiffies + KCS_TIMEOUT_JIFFIES;
1000         add_timer(&(new_kcs->kcs_timer));
1001
1002         *kcs = new_kcs;
1003
1004         return 0;
1005
1006  out_err:
1007         if (kcs_port) 
1008                 release_region (kcs_port, 2);
1009         if (new_kcs->addr) 
1010                 iounmap(new_kcs->addr);
1011         if (kcs_physaddr) 
1012                 release_mem_region(kcs_physaddr, 2);
1013         if (new_kcs->kcs_sm)
1014                 kfree(new_kcs->kcs_sm);
1015         kfree(new_kcs);
1016         return rv;
1017 }
1018
1019 #ifdef CONFIG_ACPI_INTERPRETER
1020
1021 /* Retrieve the base physical address from ACPI tables.  Originally
1022    from Hewlett-Packard simple bmc.c, a GPL KCS driver. */
1023
1024 #include <linux/acpi.h>
1025
1026 struct SPMITable {
1027         s8      Signature[4];
1028         u32     Length;
1029         u8      Revision;
1030         u8      Checksum;
1031         s8      OEMID[6];
1032         s8      OEMTableID[8];
1033         s8      OEMRevision[4];
1034         s8      CreatorID[4];
1035         s8      CreatorRevision[4];
1036         s16     InterfaceType;
1037         s16     SpecificationRevision;
1038         u8      InterruptType;
1039         u8      GPE;
1040         s16     Reserved;
1041         u64     GlobalSystemInterrupt;
1042         u8      BaseAddress[12];
1043         u8      UID[4];
1044 } __attribute__ ((packed));
1045
1046 static unsigned long acpi_find_bmc(void)
1047 {
1048         acpi_status status;
1049         struct acpi_table_header *spmi;
1050         static unsigned long io_base = 0;
1051
1052         if (io_base != 0)
1053                 return io_base;
1054
1055         status = acpi_get_firmware_table("SPMI", 1,
1056                         ACPI_LOGICAL_ADDRESSING, &spmi);
1057
1058         if (status != AE_OK) {
1059                 printk(KERN_ERR "ipmi_kcs: SPMI table not found.\n");
1060                 return 0;
1061         }
1062
1063         memcpy(&io_base, ((struct SPMITable *)spmi)->BaseAddress,
1064                         sizeof(io_base));
1065         
1066         return io_base;
1067 }
1068 #endif
1069
1070 static __init int init_ipmi_kcs(void)
1071 {
1072         int             rv = 0;
1073         int             pos = 0;
1074         int             i = 0;
1075 #ifdef CONFIG_ACPI_INTERPRETER
1076         unsigned long   physaddr = 0;
1077 #endif
1078
1079         if (initialized)
1080                 return 0;
1081         initialized = 1;
1082
1083         /* First do the "command-line" parameters */
1084
1085         for (i=0; i < KCS_MAX_PARMS; i++) {
1086                 rv = init_one_kcs(kcs_ports[i], 
1087                                   kcs_irqs[i], 
1088                                   0, 
1089                                   &(kcs_infos[pos]));
1090                 if (rv == 0)
1091                         pos++;
1092
1093                 rv = init_one_kcs(0, 
1094                                   kcs_irqs[i], 
1095                                   kcs_addrs[i], 
1096                                   &(kcs_infos[pos]));
1097                 if (rv == 0)
1098                         pos++;
1099         }
1100
1101         /* Only try the defaults if enabled and resources are available
1102            (because they weren't already specified above). */
1103
1104         if (kcs_trydefaults) {
1105 #ifdef CONFIG_ACPI_INTERPRETER
1106                 if ((physaddr = acpi_find_bmc())) {
1107                         if (!check_mem_region(physaddr, 2)) {
1108                                 rv = init_one_kcs(0, 
1109                                                   0, 
1110                                                   physaddr, 
1111                                                   &(kcs_infos[pos]));
1112                                 if (rv == 0)
1113                                         pos++;
1114                         }
1115                 }
1116 #endif
1117                 if (!check_region(DEFAULT_IO_PORT, 2)) {
1118                         rv = init_one_kcs(DEFAULT_IO_PORT, 
1119                                           0, 
1120                                           0, 
1121                                           &(kcs_infos[pos]));
1122                         if (rv == 0)
1123                                 pos++;
1124                 }
1125         }
1126
1127         if (kcs_infos[0] == NULL) {
1128                 printk("ipmi_kcs: Unable to find any KCS interfaces\n");
1129                 return -ENODEV;
1130         } 
1131
1132         return 0;
1133 }
1134 module_init(init_ipmi_kcs);
1135
1136 #ifdef MODULE
1137 void __exit cleanup_one_kcs(struct kcs_info *to_clean)
1138 {
1139         int           rv;
1140         unsigned long flags;
1141
1142         if (! to_clean)
1143                 return;
1144
1145         /* Tell the timer and interrupt handlers that we are shutting
1146            down. */
1147         spin_lock_irqsave(&(to_clean->kcs_lock), flags);
1148         spin_lock(&(to_clean->msg_lock));
1149
1150         to_clean->stop_operation = 1;
1151
1152         if (to_clean->irq != 0)
1153                 free_irq(to_clean->irq, to_clean);
1154         if (to_clean->port) {
1155                 printk(KERN_INFO 
1156                        "ipmi_kcs: Releasing BMC @ port=0x%x\n",
1157                        to_clean->port);
1158                 release_region (to_clean->port, 2);
1159         }
1160         if (to_clean->addr) {
1161                 printk(KERN_INFO 
1162                        "ipmi_kcs: Releasing BMC @ addr=0x%lx\n",
1163                        to_clean->physaddr);
1164                 iounmap(to_clean->addr);
1165                 release_mem_region(to_clean->physaddr, 2);
1166         }
1167
1168         spin_unlock(&(to_clean->msg_lock));
1169         spin_unlock_irqrestore(&(to_clean->kcs_lock), flags);
1170
1171         /* Wait until we know that we are out of any interrupt
1172            handlers might have been running before we freed the
1173            interrupt. */
1174         synchronize_kernel();
1175
1176         /* Wait for the timer to stop.  This avoids problems with race
1177            conditions removing the timer here. */
1178         while (!to_clean->timer_stopped) {
1179                 schedule_timeout(1);
1180         }
1181
1182         rv = ipmi_unregister_smi(to_clean->intf);
1183         if (rv) {
1184                 printk(KERN_ERR 
1185                        "ipmi_kcs: Unable to unregister device: errno=%d\n",
1186                        rv);
1187         }
1188
1189         initialized = 0;
1190
1191         kfree(to_clean->kcs_sm);
1192         kfree(to_clean);
1193 }
1194
1195 static __exit void cleanup_ipmi_kcs(void)
1196 {
1197         int i;
1198
1199         if (!initialized)
1200                 return;
1201
1202         for (i=0; i<KCS_MAX_DRIVERS; i++) {
1203                 cleanup_one_kcs(kcs_infos[i]);
1204         }
1205 }
1206 module_exit(cleanup_ipmi_kcs);
1207 #else
1208
1209 /* Unfortunately, cmdline::get_options() only returns integers, not
1210    longs.  Since we need ulongs (64-bit physical addresses) parse the 
1211    comma-separated list manually.  Arguments can be one of these forms:
1212    m0xaabbccddeeff      A physical memory address without an IRQ
1213    m0xaabbccddeeff:cc   A physical memory address with an IRQ
1214    p0xaabb              An IO port without an IRQ
1215    p0xaabb:cc           An IO port with an IRQ
1216    nodefaults           Suppress trying the default IO port or ACPI address 
1217
1218    For example, to pass one IO port with an IRQ, one address, and 
1219    suppress the use of the default IO port and ACPI address,
1220    use this option string: ipmi_kcs=p0xCA2:5,m0xFF5B0022,nodefaults
1221
1222    Remember, ipmi_kcs_setup() is passed the string after the equal sign. */
1223
1224 static int __init ipmi_kcs_setup(char *str)
1225 {
1226         unsigned long val;
1227         char *cur, *colon;
1228         int pos;
1229
1230         pos = 0;
1231         
1232         cur = strsep(&str, ",");
1233         while ((cur) && (*cur) && (pos < KCS_MAX_PARMS)) {
1234                 switch (*cur) {
1235                 case 'n':
1236                         if (strcmp(cur, "nodefaults") == 0)
1237                                 kcs_trydefaults = 0;
1238                         else
1239                                 printk(KERN_INFO 
1240                                        "ipmi_kcs: bad parameter value %s\n",
1241                                        cur);
1242                         break;
1243                 
1244                 case 'm':
1245                 case 'p':
1246                         val = simple_strtoul(cur + 1,
1247                                              &colon,
1248                                              0);
1249                         if (*cur == 'p')
1250                                 kcs_ports[pos] = val;
1251                         else
1252                                 kcs_addrs[pos] = val;
1253                         if (*colon == ':') {
1254                                 val = simple_strtoul(colon + 1,
1255                                                      &colon,
1256                                                      0);
1257                                 kcs_irqs[pos] = val;
1258                         }
1259                         pos++;
1260                         break;
1261
1262                 default:
1263                         printk(KERN_INFO 
1264                                "ipmi_kcs: bad parameter value %s\n",
1265                                cur);
1266                 }
1267                 cur = strsep(&str, ",");
1268         }
1269
1270         return 1;
1271 }
1272 __setup("ipmi_kcs=", ipmi_kcs_setup);
1273 #endif
1274
1275 MODULE_LICENSE("GPL");