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