ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / char / ipmi / ipmi_msghandler.c
1 /*
2  * ipmi_msghandler.c
3  *
4  * Incoming and outgoing message routing for an IPMI interface.
5  *
6  * Author: MontaVista Software, Inc.
7  *         Corey Minyard <minyard@mvista.com>
8  *         source@mvista.com
9  *
10  * Copyright 2002 MontaVista Software Inc.
11  *
12  *  This program is free software; you can redistribute it and/or modify it
13  *  under the terms of the GNU General Public License as published by the
14  *  Free Software Foundation; either version 2 of the License, or (at your
15  *  option) any later version.
16  *
17  *
18  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
19  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
26  *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27  *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  *  You should have received a copy of the GNU General Public License along
30  *  with this program; if not, write to the Free Software Foundation, Inc.,
31  *  675 Mass Ave, Cambridge, MA 02139, USA.
32  */
33
34 #include <linux/config.h>
35 #include <linux/module.h>
36 #include <linux/errno.h>
37 #include <asm/system.h>
38 #include <linux/sched.h>
39 #include <linux/poll.h>
40 #include <linux/spinlock.h>
41 #include <linux/rwsem.h>
42 #include <linux/slab.h>
43 #include <linux/ipmi.h>
44 #include <linux/ipmi_smi.h>
45 #include <linux/notifier.h>
46 #include <linux/init.h>
47 #include <linux/proc_fs.h>
48
49 #define IPMI_MSGHANDLER_VERSION "v31"
50
51 struct ipmi_recv_msg *ipmi_alloc_recv_msg(void);
52 static int ipmi_init_msghandler(void);
53
54 static int initialized = 0;
55
56 static struct proc_dir_entry *proc_ipmi_root = NULL;
57
58 #define MAX_EVENTS_IN_QUEUE     25
59
60 /* Don't let a message sit in a queue forever, always time it with at lest
61    the max message timer.  This is in milliseconds. */
62 #define MAX_MSG_TIMEOUT         60000
63
64 struct ipmi_user
65 {
66         struct list_head link;
67
68         /* The upper layer that handles receive messages. */
69         struct ipmi_user_hndl *handler;
70         void             *handler_data;
71
72         /* The interface this user is bound to. */
73         ipmi_smi_t intf;
74
75         /* Does this interface receive IPMI events? */
76         int gets_events;
77 };
78
79 struct cmd_rcvr
80 {
81         struct list_head link;
82
83         ipmi_user_t   user;
84         unsigned char netfn;
85         unsigned char cmd;
86 };
87
88 struct seq_table
89 {
90         unsigned int         inuse : 1;
91         unsigned int         broadcast : 1;
92
93         unsigned long        timeout;
94         unsigned long        orig_timeout;
95         unsigned int         retries_left;
96
97         /* To verify on an incoming send message response that this is
98            the message that the response is for, we keep a sequence id
99            and increment it every time we send a message. */
100         long                 seqid;
101
102         /* This is held so we can properly respond to the message on a
103            timeout, and it is used to hold the temporary data for
104            retransmission, too. */
105         struct ipmi_recv_msg *recv_msg;
106 };
107
108 /* Store the information in a msgid (long) to allow us to find a
109    sequence table entry from the msgid. */
110 #define STORE_SEQ_IN_MSGID(seq, seqid) (((seq&0xff)<<26) | (seqid&0x3ffffff))
111
112 #define GET_SEQ_FROM_MSGID(msgid, seq, seqid) \
113         do {                                                            \
114                 seq = ((msgid >> 26) & 0x3f);                           \
115                 seqid = (msgid & 0x3fffff);                             \
116         } while(0)
117
118 #define NEXT_SEQID(seqid) (((seqid) + 1) & 0x3fffff)
119
120 struct ipmi_channel
121 {
122         unsigned char medium;
123         unsigned char protocol;
124 };
125
126 #define IPMI_IPMB_NUM_SEQ       64
127 #define IPMI_MAX_CHANNELS       8
128 struct ipmi_smi
129 {
130         /* What interface number are we? */
131         int intf_num;
132
133         /* The list of upper layers that are using me.  We read-lock
134            this when delivering messages to the upper layer to keep
135            the user from going away while we are processing the
136            message.  This means that you cannot add or delete a user
137            from the receive callback. */
138         rwlock_t                users_lock;
139         struct list_head        users;
140
141         /* Used for wake ups at startup. */
142         wait_queue_head_t waitq;
143
144         /* The IPMI version of the BMC on the other end. */
145         unsigned char       version_major;
146         unsigned char       version_minor;
147
148         /* This is the lower-layer's sender routine. */
149         struct ipmi_smi_handlers *handlers;
150         void                     *send_info;
151
152         /* A table of sequence numbers for this interface.  We use the
153            sequence numbers for IPMB messages that go out of the
154            interface to match them up with their responses.  A routine
155            is called periodically to time the items in this list. */
156         spinlock_t       seq_lock;
157         struct seq_table seq_table[IPMI_IPMB_NUM_SEQ];
158         int curr_seq;
159
160         /* Messages that were delayed for some reason (out of memory,
161            for instance), will go in here to be processed later in a
162            periodic timer interrupt. */
163         spinlock_t       waiting_msgs_lock;
164         struct list_head waiting_msgs;
165
166         /* The list of command receivers that are registered for commands
167            on this interface. */
168         rwlock_t         cmd_rcvr_lock;
169         struct list_head cmd_rcvrs;
170
171         /* Events that were queues because no one was there to receive
172            them. */
173         spinlock_t       events_lock; /* For dealing with event stuff. */
174         struct list_head waiting_events;
175         unsigned int     waiting_events_count; /* How many events in queue? */
176
177         /* This will be non-null if someone registers to receive all
178            IPMI commands (this is for interface emulation).  There
179            may not be any things in the cmd_rcvrs list above when
180            this is registered. */
181         ipmi_user_t all_cmd_rcvr;
182
183         /* My slave address.  This is initialized to IPMI_BMC_SLAVE_ADDR,
184            but may be changed by the user. */
185         unsigned char my_address;
186
187         /* My LUN.  This should generally stay the SMS LUN, but just in
188            case... */
189         unsigned char my_lun;
190
191         /* The event receiver for my BMC, only really used at panic
192            shutdown as a place to store this. */
193         unsigned char event_receiver;
194         unsigned char event_receiver_lun;
195         unsigned char local_sel_device;
196         unsigned char local_event_generator;
197
198         /* A cheap hack, if this is non-null and a message to an
199            interface comes in with a NULL user, call this routine with
200            it.  Note that the message will still be freed by the
201            caller.  This only works on the system interface. */
202         void (*null_user_handler)(ipmi_smi_t intf, struct ipmi_smi_msg *msg);
203
204         /* When we are scanning the channels for an SMI, this will
205            tell which channel we are scanning. */
206         int curr_channel;
207
208         /* Channel information */
209         struct ipmi_channel channels[IPMI_MAX_CHANNELS];
210
211         /* Proc FS stuff. */
212         struct proc_dir_entry *proc_dir;
213         char                  proc_dir_name[10];
214
215         spinlock_t   counter_lock; /* For making counters atomic. */
216
217         /* Commands we got that were invalid. */
218         unsigned int sent_invalid_commands;
219
220         /* Commands we sent to the MC. */
221         unsigned int sent_local_commands;
222         /* Responses from the MC that were delivered to a user. */
223         unsigned int handled_local_responses;
224         /* Responses from the MC that were not delivered to a user. */
225         unsigned int unhandled_local_responses;
226
227         /* Commands we sent out to the IPMB bus. */
228         unsigned int sent_ipmb_commands;
229         /* Commands sent on the IPMB that had errors on the SEND CMD */
230         unsigned int sent_ipmb_command_errs;
231         /* Each retransmit increments this count. */
232         unsigned int retransmitted_ipmb_commands;
233         /* When a message times out (runs out of retransmits) this is
234            incremented. */
235         unsigned int timed_out_ipmb_commands;
236
237         /* This is like above, but for broadcasts.  Broadcasts are
238            *not* included in the above count (they are expected to
239            time out). */
240         unsigned int timed_out_ipmb_broadcasts;
241
242         /* Responses I have sent to the IPMB bus. */
243         unsigned int sent_ipmb_responses;
244
245         /* The response was delivered to the user. */
246         unsigned int handled_ipmb_responses;
247         /* The response had invalid data in it. */
248         unsigned int invalid_ipmb_responses;
249         /* The response didn't have anyone waiting for it. */
250         unsigned int unhandled_ipmb_responses;
251
252         /* Commands we sent out to the IPMB bus. */
253         unsigned int sent_lan_commands;
254         /* Commands sent on the IPMB that had errors on the SEND CMD */
255         unsigned int sent_lan_command_errs;
256         /* Each retransmit increments this count. */
257         unsigned int retransmitted_lan_commands;
258         /* When a message times out (runs out of retransmits) this is
259            incremented. */
260         unsigned int timed_out_lan_commands;
261
262         /* Responses I have sent to the IPMB bus. */
263         unsigned int sent_lan_responses;
264
265         /* The response was delivered to the user. */
266         unsigned int handled_lan_responses;
267         /* The response had invalid data in it. */
268         unsigned int invalid_lan_responses;
269         /* The response didn't have anyone waiting for it. */
270         unsigned int unhandled_lan_responses;
271
272         /* The command was delivered to the user. */
273         unsigned int handled_commands;
274         /* The command had invalid data in it. */
275         unsigned int invalid_commands;
276         /* The command didn't have anyone waiting for it. */
277         unsigned int unhandled_commands;
278
279         /* Invalid data in an event. */
280         unsigned int invalid_events;
281         /* Events that were received with the proper format. */
282         unsigned int events;
283 };
284
285 int
286 ipmi_register_all_cmd_rcvr(ipmi_user_t user)
287 {
288         unsigned long flags;
289         int           rv = -EBUSY;
290
291         write_lock_irqsave(&(user->intf->users_lock), flags);
292         write_lock(&(user->intf->cmd_rcvr_lock));
293         if ((user->intf->all_cmd_rcvr == NULL)
294             && (list_empty(&(user->intf->cmd_rcvrs))))
295         {
296                 user->intf->all_cmd_rcvr = user;
297                 rv = 0;
298         }
299         write_unlock(&(user->intf->cmd_rcvr_lock));
300         write_unlock_irqrestore(&(user->intf->users_lock), flags);
301         return rv;
302 }
303
304 int
305 ipmi_unregister_all_cmd_rcvr(ipmi_user_t user)
306 {
307         unsigned long flags;
308         int           rv = -EINVAL;
309
310         write_lock_irqsave(&(user->intf->users_lock), flags);
311         write_lock(&(user->intf->cmd_rcvr_lock));
312         if (user->intf->all_cmd_rcvr == user)
313         {
314                 user->intf->all_cmd_rcvr = NULL;
315                 rv = 0;
316         }
317         write_unlock(&(user->intf->cmd_rcvr_lock));
318         write_unlock_irqrestore(&(user->intf->users_lock), flags);
319         return rv;
320 }
321
322
323 #define MAX_IPMI_INTERFACES 4
324 static ipmi_smi_t ipmi_interfaces[MAX_IPMI_INTERFACES];
325
326 /* Used to keep interfaces from going away while operations are
327    operating on interfaces.  Grab read if you are not modifying the
328    interfaces, write if you are. */
329 static DECLARE_RWSEM(interfaces_sem);
330
331 /* Directly protects the ipmi_interfaces data structure.  This is
332    claimed in the timer interrupt. */
333 static spinlock_t interfaces_lock = SPIN_LOCK_UNLOCKED;
334
335 /* List of watchers that want to know when smi's are added and
336    deleted. */
337 static struct list_head smi_watchers = LIST_HEAD_INIT(smi_watchers);
338 static DECLARE_RWSEM(smi_watchers_sem);
339
340 int ipmi_smi_watcher_register(struct ipmi_smi_watcher *watcher)
341 {
342         int i;
343
344         down_read(&interfaces_sem);
345         down_write(&smi_watchers_sem);
346         list_add(&(watcher->link), &smi_watchers);
347         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
348                 if (ipmi_interfaces[i] != NULL) {
349                         watcher->new_smi(i);
350                 }
351         }
352         up_write(&smi_watchers_sem);
353         up_read(&interfaces_sem);
354         return 0;
355 }
356
357 int ipmi_smi_watcher_unregister(struct ipmi_smi_watcher *watcher)
358 {
359         down_write(&smi_watchers_sem);
360         list_del(&(watcher->link));
361         up_write(&smi_watchers_sem);
362         return 0;
363 }
364
365 static void
366 call_smi_watchers(int i)
367 {
368         struct ipmi_smi_watcher *w;
369
370         down_read(&smi_watchers_sem);
371         list_for_each_entry(w, &smi_watchers, link) {
372                 if (try_module_get(w->owner)) {
373                         w->new_smi(i);
374                         module_put(w->owner);
375                 }
376         }
377         up_read(&smi_watchers_sem);
378 }
379
380 int
381 ipmi_addr_equal(struct ipmi_addr *addr1, struct ipmi_addr *addr2)
382 {
383         if (addr1->addr_type != addr2->addr_type)
384                 return 0;
385
386         if (addr1->channel != addr2->channel)
387                 return 0;
388
389         if (addr1->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
390                 struct ipmi_system_interface_addr *smi_addr1
391                     = (struct ipmi_system_interface_addr *) addr1;
392                 struct ipmi_system_interface_addr *smi_addr2
393                     = (struct ipmi_system_interface_addr *) addr2;
394                 return (smi_addr1->lun == smi_addr2->lun);
395         }
396
397         if ((addr1->addr_type == IPMI_IPMB_ADDR_TYPE)
398             || (addr1->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE))
399         {
400                 struct ipmi_ipmb_addr *ipmb_addr1
401                     = (struct ipmi_ipmb_addr *) addr1;
402                 struct ipmi_ipmb_addr *ipmb_addr2
403                     = (struct ipmi_ipmb_addr *) addr2;
404
405                 return ((ipmb_addr1->slave_addr == ipmb_addr2->slave_addr)
406                         && (ipmb_addr1->lun == ipmb_addr2->lun));
407         }
408
409         if (addr1->addr_type == IPMI_LAN_ADDR_TYPE) {
410                 struct ipmi_lan_addr *lan_addr1
411                         = (struct ipmi_lan_addr *) addr1;
412                 struct ipmi_lan_addr *lan_addr2
413                     = (struct ipmi_lan_addr *) addr2;
414
415                 return ((lan_addr1->remote_SWID == lan_addr2->remote_SWID)
416                         && (lan_addr1->local_SWID == lan_addr2->local_SWID)
417                         && (lan_addr1->session_handle
418                             == lan_addr2->session_handle)
419                         && (lan_addr1->lun == lan_addr2->lun));
420         }
421
422         return 1;
423 }
424
425 int ipmi_validate_addr(struct ipmi_addr *addr, int len)
426 {
427         if (len < sizeof(struct ipmi_system_interface_addr)) {
428                 return -EINVAL;
429         }
430
431         if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
432                 if (addr->channel != IPMI_BMC_CHANNEL)
433                         return -EINVAL;
434                 return 0;
435         }
436
437         if ((addr->channel == IPMI_BMC_CHANNEL)
438             || (addr->channel >= IPMI_NUM_CHANNELS)
439             || (addr->channel < 0))
440                 return -EINVAL;
441
442         if ((addr->addr_type == IPMI_IPMB_ADDR_TYPE)
443             || (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE))
444         {
445                 if (len < sizeof(struct ipmi_ipmb_addr)) {
446                         return -EINVAL;
447                 }
448                 return 0;
449         }
450
451         if (addr->addr_type == IPMI_LAN_ADDR_TYPE) {
452                 if (len < sizeof(struct ipmi_lan_addr)) {
453                         return -EINVAL;
454                 }
455                 return 0;
456         }
457
458         return -EINVAL;
459 }
460
461 unsigned int ipmi_addr_length(int addr_type)
462 {
463         if (addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
464                 return sizeof(struct ipmi_system_interface_addr);
465
466         if ((addr_type == IPMI_IPMB_ADDR_TYPE)
467             || (addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE))
468         {
469                 return sizeof(struct ipmi_ipmb_addr);
470         }
471
472         return 0;
473 }
474
475 static void deliver_response(struct ipmi_recv_msg *msg)
476 {
477         msg->user->handler->ipmi_recv_hndl(msg, msg->user->handler_data);
478 }
479
480 /* Find the next sequence number not being used and add the given
481    message with the given timeout to the sequence table.  This must be
482    called with the interface's seq_lock held. */
483 static int intf_next_seq(ipmi_smi_t           intf,
484                          struct ipmi_recv_msg *recv_msg,
485                          unsigned long        timeout,
486                          int                  retries,
487                          int                  broadcast,
488                          unsigned char        *seq,
489                          long                 *seqid)
490 {
491         int          rv = 0;
492         unsigned int i;
493
494         for (i=intf->curr_seq;
495              (i+1)%IPMI_IPMB_NUM_SEQ != intf->curr_seq;
496              i=(i+1)%IPMI_IPMB_NUM_SEQ)
497         {
498                 if (! intf->seq_table[i].inuse)
499                         break;
500         }
501
502         if (! intf->seq_table[i].inuse) {
503                 intf->seq_table[i].recv_msg = recv_msg;
504
505                 /* Start with the maximum timeout, when the send response
506                    comes in we will start the real timer. */
507                 intf->seq_table[i].timeout = MAX_MSG_TIMEOUT;
508                 intf->seq_table[i].orig_timeout = timeout;
509                 intf->seq_table[i].retries_left = retries;
510                 intf->seq_table[i].broadcast = broadcast;
511                 intf->seq_table[i].inuse = 1;
512                 intf->seq_table[i].seqid = NEXT_SEQID(intf->seq_table[i].seqid);
513                 *seq = i;
514                 *seqid = intf->seq_table[i].seqid;
515                 intf->curr_seq = (i+1)%IPMI_IPMB_NUM_SEQ;
516         } else {
517                 rv = -EAGAIN;
518         }
519         
520         return rv;
521 }
522
523 /* Return the receive message for the given sequence number and
524    release the sequence number so it can be reused.  Some other data
525    is passed in to be sure the message matches up correctly (to help
526    guard against message coming in after their timeout and the
527    sequence number being reused). */
528 static int intf_find_seq(ipmi_smi_t           intf,
529                          unsigned char        seq,
530                          short                channel,
531                          unsigned char        cmd,
532                          unsigned char        netfn,
533                          struct ipmi_addr     *addr,
534                          struct ipmi_recv_msg **recv_msg)
535 {
536         int           rv = -ENODEV;
537         unsigned long flags;
538
539         if (seq >= IPMI_IPMB_NUM_SEQ)
540                 return -EINVAL;
541
542         spin_lock_irqsave(&(intf->seq_lock), flags);
543         if (intf->seq_table[seq].inuse) {
544                 struct ipmi_recv_msg *msg = intf->seq_table[seq].recv_msg;
545
546                 if ((msg->addr.channel == channel)
547                     && (msg->msg.cmd == cmd)
548                     && (msg->msg.netfn == netfn)
549                     && (ipmi_addr_equal(addr, &(msg->addr))))
550                 {
551                         *recv_msg = msg;
552                         intf->seq_table[seq].inuse = 0;
553                         rv = 0;
554                 }
555         }
556         spin_unlock_irqrestore(&(intf->seq_lock), flags);
557
558         return rv;
559 }
560
561
562 /* Start the timer for a specific sequence table entry. */
563 static int intf_start_seq_timer(ipmi_smi_t intf,
564                                 long       msgid)
565 {
566         int           rv = -ENODEV;
567         unsigned long flags;
568         unsigned char seq;
569         unsigned long seqid;
570
571
572         GET_SEQ_FROM_MSGID(msgid, seq, seqid);
573
574         spin_lock_irqsave(&(intf->seq_lock), flags);
575         /* We do this verification because the user can be deleted
576            while a message is outstanding. */
577         if ((intf->seq_table[seq].inuse)
578             && (intf->seq_table[seq].seqid == seqid))
579         {
580                 struct seq_table *ent = &(intf->seq_table[seq]);
581                 ent->timeout = ent->orig_timeout;
582                 rv = 0;
583         }
584         spin_unlock_irqrestore(&(intf->seq_lock), flags);
585
586         return rv;
587 }
588
589 /* Got an error for the send message for a specific sequence number. */
590 static int intf_err_seq(ipmi_smi_t   intf,
591                         long         msgid,
592                         unsigned int err)
593 {
594         int                  rv = -ENODEV;
595         unsigned long        flags;
596         unsigned char        seq;
597         unsigned long        seqid;
598         struct ipmi_recv_msg *msg = NULL;
599
600
601         GET_SEQ_FROM_MSGID(msgid, seq, seqid);
602
603         spin_lock_irqsave(&(intf->seq_lock), flags);
604         /* We do this verification because the user can be deleted
605            while a message is outstanding. */
606         if ((intf->seq_table[seq].inuse)
607             && (intf->seq_table[seq].seqid == seqid))
608         {
609                 struct seq_table *ent = &(intf->seq_table[seq]);
610
611                 ent->inuse = 0;
612                 msg = ent->recv_msg;
613                 rv = 0;
614         }
615         spin_unlock_irqrestore(&(intf->seq_lock), flags);
616
617         if (msg) {
618                 msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
619                 msg->msg_data[0] = err;
620                 msg->msg.netfn |= 1; /* Convert to a response. */
621                 msg->msg.data_len = 1;
622                 msg->msg.data = msg->msg_data;
623                 deliver_response(msg);
624         }
625
626         return rv;
627 }
628
629
630 int ipmi_create_user(unsigned int          if_num,
631                      struct ipmi_user_hndl *handler,
632                      void                  *handler_data,
633                      ipmi_user_t           *user)
634 {
635         unsigned long flags;
636         ipmi_user_t   new_user;
637         int           rv = 0;
638
639         /* There is no module usecount here, because it's not
640            required.  Since this can only be used by and called from
641            other modules, they will implicitly use this module, and
642            thus this can't be removed unless the other modules are
643            removed. */
644
645         if (handler == NULL)
646                 return -EINVAL;
647
648         /* Make sure the driver is actually initialized, this handles
649            problems with initialization order. */
650         if (!initialized) {
651                 rv = ipmi_init_msghandler();
652                 if (rv)
653                         return rv;
654
655                 /* The init code doesn't return an error if it was turned
656                    off, but it won't initialize.  Check that. */
657                 if (!initialized)
658                         return -ENODEV;
659         }
660
661         new_user = kmalloc(sizeof(*new_user), GFP_KERNEL);
662         if (! new_user)
663                 return -ENOMEM;
664
665         down_read(&interfaces_sem);
666         if ((if_num > MAX_IPMI_INTERFACES) || ipmi_interfaces[if_num] == NULL)
667         {
668                 rv = -EINVAL;
669                 goto out_unlock;
670         }
671
672         new_user->handler = handler;
673         new_user->handler_data = handler_data;
674         new_user->intf = ipmi_interfaces[if_num];
675         new_user->gets_events = 0;
676
677         if (!try_module_get(new_user->intf->handlers->owner)) {
678                 rv = -ENODEV;
679                 goto out_unlock;
680         }
681
682         write_lock_irqsave(&new_user->intf->users_lock, flags);
683         list_add_tail(&new_user->link, &new_user->intf->users);
684         write_unlock_irqrestore(&new_user->intf->users_lock, flags);
685
686  out_unlock:    
687         if (rv) {
688                 kfree(new_user);
689         } else {
690                 *user = new_user;
691         }
692
693         up_read(&interfaces_sem);
694         return rv;
695 }
696
697 static int ipmi_destroy_user_nolock(ipmi_user_t user)
698 {
699         int              rv = -ENODEV;
700         ipmi_user_t      t_user;
701         struct cmd_rcvr  *rcvr, *rcvr2;
702         int              i;
703         unsigned long    flags;
704
705         /* Find the user and delete them from the list. */
706         list_for_each_entry(t_user, &(user->intf->users), link) {
707                 if (t_user == user) {
708                         list_del(&t_user->link);
709                         rv = 0;
710                         break;
711                 }
712         }
713
714         if (rv) {
715                 goto out_unlock;
716         }
717
718         /* Remove the user from the interfaces sequence table. */
719         spin_lock_irqsave(&(user->intf->seq_lock), flags);
720         for (i=0; i<IPMI_IPMB_NUM_SEQ; i++) {
721                 if (user->intf->seq_table[i].inuse
722                     && (user->intf->seq_table[i].recv_msg->user == user))
723                 {
724                         user->intf->seq_table[i].inuse = 0;
725                 }
726         }
727         spin_unlock_irqrestore(&(user->intf->seq_lock), flags);
728
729         /* Remove the user from the command receiver's table. */
730         write_lock_irqsave(&(user->intf->cmd_rcvr_lock), flags);
731         list_for_each_entry_safe(rcvr, rcvr2, &(user->intf->cmd_rcvrs), link) {
732                 if (rcvr->user == user) {
733                         list_del(&rcvr->link);
734                         kfree(rcvr);
735                 }
736         }
737         write_unlock_irqrestore(&(user->intf->cmd_rcvr_lock), flags);
738
739         kfree(user);
740
741  out_unlock:
742
743         return rv;
744 }
745
746 int ipmi_destroy_user(ipmi_user_t user)
747 {
748         int           rv;
749         ipmi_smi_t    intf = user->intf;
750         unsigned long flags;
751
752         down_read(&interfaces_sem);
753         write_lock_irqsave(&intf->users_lock, flags);
754         rv = ipmi_destroy_user_nolock(user);
755         if (!rv)
756                 module_put(intf->handlers->owner);
757                 
758         write_unlock_irqrestore(&intf->users_lock, flags);
759         up_read(&interfaces_sem);
760         return rv;
761 }
762
763 void ipmi_get_version(ipmi_user_t   user,
764                       unsigned char *major,
765                       unsigned char *minor)
766 {
767         *major = user->intf->version_major;
768         *minor = user->intf->version_minor;
769 }
770
771 void ipmi_set_my_address(ipmi_user_t   user,
772                          unsigned char address)
773 {
774         user->intf->my_address = address;
775 }
776
777 unsigned char ipmi_get_my_address(ipmi_user_t user)
778 {
779         return user->intf->my_address;
780 }
781
782 void ipmi_set_my_LUN(ipmi_user_t   user,
783                      unsigned char LUN)
784 {
785         user->intf->my_lun = LUN & 0x3;
786 }
787
788 unsigned char ipmi_get_my_LUN(ipmi_user_t user)
789 {
790         return user->intf->my_lun;
791 }
792
793 int ipmi_set_gets_events(ipmi_user_t user, int val)
794 {
795         unsigned long         flags;
796         struct ipmi_recv_msg  *msg, *msg2;
797
798         read_lock(&(user->intf->users_lock));
799         spin_lock_irqsave(&(user->intf->events_lock), flags);
800         user->gets_events = val;
801
802         if (val) {
803                 /* Deliver any queued events. */
804                 list_for_each_entry_safe(msg, msg2, &(user->intf->waiting_events), link) {
805                         list_del(&msg->link);
806                         msg->user = user;
807                         deliver_response(msg);
808                 }
809         }
810         
811         spin_unlock_irqrestore(&(user->intf->events_lock), flags);
812         read_unlock(&(user->intf->users_lock));
813
814         return 0;
815 }
816
817 int ipmi_register_for_cmd(ipmi_user_t   user,
818                           unsigned char netfn,
819                           unsigned char cmd)
820 {
821         struct cmd_rcvr  *cmp;
822         unsigned long    flags;
823         struct cmd_rcvr  *rcvr;
824         int              rv = 0;
825
826
827         rcvr = kmalloc(sizeof(*rcvr), GFP_KERNEL);
828         if (! rcvr)
829                 return -ENOMEM;
830
831         read_lock(&(user->intf->users_lock));
832         write_lock_irqsave(&(user->intf->cmd_rcvr_lock), flags);
833         if (user->intf->all_cmd_rcvr != NULL) {
834                 rv = -EBUSY;
835                 goto out_unlock;
836         }
837
838         /* Make sure the command/netfn is not already registered. */
839         list_for_each_entry(cmp, &(user->intf->cmd_rcvrs), link) {
840                 if ((cmp->netfn == netfn) && (cmp->cmd == cmd)) {
841                         rv = -EBUSY;
842                         break;
843                 }
844         }
845
846         if (! rv) {
847                 rcvr->cmd = cmd;
848                 rcvr->netfn = netfn;
849                 rcvr->user = user;
850                 list_add_tail(&(rcvr->link), &(user->intf->cmd_rcvrs));
851         }
852  out_unlock:
853         write_unlock_irqrestore(&(user->intf->cmd_rcvr_lock), flags);
854         read_unlock(&(user->intf->users_lock));
855
856         if (rv)
857                 kfree(rcvr);
858
859         return rv;
860 }
861
862 int ipmi_unregister_for_cmd(ipmi_user_t   user,
863                             unsigned char netfn,
864                             unsigned char cmd)
865 {
866         unsigned long    flags;
867         struct cmd_rcvr  *rcvr;
868         int              rv = -ENOENT;
869
870         read_lock(&(user->intf->users_lock));
871         write_lock_irqsave(&(user->intf->cmd_rcvr_lock), flags);
872         /* Make sure the command/netfn is not already registered. */
873         list_for_each_entry(rcvr, &(user->intf->cmd_rcvrs), link) {
874                 if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)) {
875                         rv = 0;
876                         list_del(&rcvr->link);
877                         kfree(rcvr);
878                         break;
879                 }
880         }
881         write_unlock_irqrestore(&(user->intf->cmd_rcvr_lock), flags);
882         read_unlock(&(user->intf->users_lock));
883
884         return rv;
885 }
886
887 static unsigned char
888 ipmb_checksum(unsigned char *data, int size)
889 {
890         unsigned char csum = 0;
891         
892         for (; size > 0; size--, data++)
893                 csum += *data;
894
895         return -csum;
896 }
897
898 static inline void format_ipmb_msg(struct ipmi_smi_msg   *smi_msg,
899                                    struct ipmi_msg       *msg,
900                                    struct ipmi_ipmb_addr *ipmb_addr,
901                                    long                  msgid,
902                                    unsigned char         ipmb_seq,
903                                    int                   broadcast,
904                                    unsigned char         source_address,
905                                    unsigned char         source_lun)
906 {
907         int i = broadcast;
908
909         /* Format the IPMB header data. */
910         smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
911         smi_msg->data[1] = IPMI_SEND_MSG_CMD;
912         smi_msg->data[2] = ipmb_addr->channel;
913         if (broadcast)
914                 smi_msg->data[3] = 0;
915         smi_msg->data[i+3] = ipmb_addr->slave_addr;
916         smi_msg->data[i+4] = (msg->netfn << 2) | (ipmb_addr->lun & 0x3);
917         smi_msg->data[i+5] = ipmb_checksum(&(smi_msg->data[i+3]), 2);
918         smi_msg->data[i+6] = source_address;
919         smi_msg->data[i+7] = (ipmb_seq << 2) | source_lun;
920         smi_msg->data[i+8] = msg->cmd;
921
922         /* Now tack on the data to the message. */
923         if (msg->data_len > 0)
924                 memcpy(&(smi_msg->data[i+9]), msg->data,
925                        msg->data_len);
926         smi_msg->data_size = msg->data_len + 9;
927
928         /* Now calculate the checksum and tack it on. */
929         smi_msg->data[i+smi_msg->data_size]
930                 = ipmb_checksum(&(smi_msg->data[i+6]),
931                                 smi_msg->data_size-6);
932
933         /* Add on the checksum size and the offset from the
934            broadcast. */
935         smi_msg->data_size += 1 + i;
936
937         smi_msg->msgid = msgid;
938 }
939
940 static inline void format_lan_msg(struct ipmi_smi_msg   *smi_msg,
941                                   struct ipmi_msg       *msg,
942                                   struct ipmi_lan_addr  *lan_addr,
943                                   long                  msgid,
944                                   unsigned char         ipmb_seq,
945                                   unsigned char         source_lun)
946 {
947         /* Format the IPMB header data. */
948         smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
949         smi_msg->data[1] = IPMI_SEND_MSG_CMD;
950         smi_msg->data[2] = lan_addr->channel;
951         smi_msg->data[3] = lan_addr->session_handle;
952         smi_msg->data[4] = lan_addr->remote_SWID;
953         smi_msg->data[5] = (msg->netfn << 2) | (lan_addr->lun & 0x3);
954         smi_msg->data[6] = ipmb_checksum(&(smi_msg->data[4]), 2);
955         smi_msg->data[7] = lan_addr->local_SWID;
956         smi_msg->data[8] = (ipmb_seq << 2) | source_lun;
957         smi_msg->data[9] = msg->cmd;
958
959         /* Now tack on the data to the message. */
960         if (msg->data_len > 0)
961                 memcpy(&(smi_msg->data[10]), msg->data,
962                        msg->data_len);
963         smi_msg->data_size = msg->data_len + 10;
964
965         /* Now calculate the checksum and tack it on. */
966         smi_msg->data[smi_msg->data_size]
967                 = ipmb_checksum(&(smi_msg->data[7]),
968                                 smi_msg->data_size-7);
969
970         /* Add on the checksum size and the offset from the
971            broadcast. */
972         smi_msg->data_size += 1;
973
974         smi_msg->msgid = msgid;
975 }
976
977 /* Separate from ipmi_request so that the user does not have to be
978    supplied in certain circumstances (mainly at panic time).  If
979    messages are supplied, they will be freed, even if an error
980    occurs. */
981 static inline int i_ipmi_request(ipmi_user_t          user,
982                                  ipmi_smi_t           intf,
983                                  struct ipmi_addr     *addr,
984                                  long                 msgid,
985                                  struct ipmi_msg      *msg,
986                                  void                 *user_msg_data,
987                                  void                 *supplied_smi,
988                                  struct ipmi_recv_msg *supplied_recv,
989                                  int                  priority,
990                                  unsigned char        source_address,
991                                  unsigned char        source_lun,
992                                  int                  retries,
993                                  unsigned int         retry_time_ms)
994 {
995         int                  rv = 0;
996         struct ipmi_smi_msg  *smi_msg;
997         struct ipmi_recv_msg *recv_msg;
998         unsigned long        flags;
999
1000
1001         if (supplied_recv) {
1002                 recv_msg = supplied_recv;
1003         } else {
1004                 recv_msg = ipmi_alloc_recv_msg();
1005                 if (recv_msg == NULL) {
1006                         return -ENOMEM;
1007                 }
1008         }
1009         recv_msg->user_msg_data = user_msg_data;
1010
1011         if (supplied_smi) {
1012                 smi_msg = (struct ipmi_smi_msg *) supplied_smi;
1013         } else {
1014                 smi_msg = ipmi_alloc_smi_msg();
1015                 if (smi_msg == NULL) {
1016                         ipmi_free_recv_msg(recv_msg);
1017                         return -ENOMEM;
1018                 }
1019         }
1020
1021         recv_msg->user = user;
1022         recv_msg->msgid = msgid;
1023         /* Store the message to send in the receive message so timeout
1024            responses can get the proper response data. */
1025         recv_msg->msg = *msg;
1026
1027         if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
1028                 struct ipmi_system_interface_addr *smi_addr;
1029
1030                 if (msg->netfn & 1) {
1031                         /* Responses are not allowed to the SMI. */
1032                         rv = -EINVAL;
1033                         goto out_err;
1034                 }
1035
1036                 smi_addr = (struct ipmi_system_interface_addr *) addr;
1037                 if (smi_addr->lun > 3) {
1038                         spin_lock_irqsave(&intf->counter_lock, flags);
1039                         intf->sent_invalid_commands++;
1040                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1041                         rv = -EINVAL;
1042                         goto out_err;
1043                 }
1044
1045                 memcpy(&recv_msg->addr, smi_addr, sizeof(*smi_addr));
1046
1047                 if ((msg->netfn == IPMI_NETFN_APP_REQUEST)
1048                     && ((msg->cmd == IPMI_SEND_MSG_CMD)
1049                         || (msg->cmd == IPMI_GET_MSG_CMD)
1050                         || (msg->cmd == IPMI_READ_EVENT_MSG_BUFFER_CMD)))
1051                 {
1052                         /* We don't let the user do these, since we manage
1053                            the sequence numbers. */
1054                         spin_lock_irqsave(&intf->counter_lock, flags);
1055                         intf->sent_invalid_commands++;
1056                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1057                         rv = -EINVAL;
1058                         goto out_err;
1059                 }
1060
1061                 if ((msg->data_len + 2) > IPMI_MAX_MSG_LENGTH) {
1062                         spin_lock_irqsave(&intf->counter_lock, flags);
1063                         intf->sent_invalid_commands++;
1064                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1065                         rv = -EMSGSIZE;
1066                         goto out_err;
1067                 }
1068
1069                 smi_msg->data[0] = (msg->netfn << 2) | (smi_addr->lun & 0x3);
1070                 smi_msg->data[1] = msg->cmd;
1071                 smi_msg->msgid = msgid;
1072                 smi_msg->user_data = recv_msg;
1073                 if (msg->data_len > 0)
1074                         memcpy(&(smi_msg->data[2]), msg->data, msg->data_len);
1075                 smi_msg->data_size = msg->data_len + 2;
1076                 spin_lock_irqsave(&intf->counter_lock, flags);
1077                 intf->sent_local_commands++;
1078                 spin_unlock_irqrestore(&intf->counter_lock, flags);
1079         } else if ((addr->addr_type == IPMI_IPMB_ADDR_TYPE)
1080                    || (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE))
1081         {
1082                 struct ipmi_ipmb_addr *ipmb_addr;
1083                 unsigned char         ipmb_seq;
1084                 long                  seqid;
1085                 int                   broadcast = 0;
1086
1087                 if (addr->channel > IPMI_NUM_CHANNELS) {
1088                         spin_lock_irqsave(&intf->counter_lock, flags);
1089                         intf->sent_invalid_commands++;
1090                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1091                         rv = -EINVAL;
1092                         goto out_err;
1093                 }
1094
1095                 if (intf->channels[addr->channel].medium
1096                     != IPMI_CHANNEL_MEDIUM_IPMB)
1097                 {
1098                         spin_lock_irqsave(&intf->counter_lock, flags);
1099                         intf->sent_invalid_commands++;
1100                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1101                         rv = -EINVAL;
1102                         goto out_err;
1103                 }
1104
1105                 if (retries < 0) {
1106                     if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE)
1107                         retries = 0; /* Don't retry broadcasts. */
1108                     else
1109                         retries = 4;
1110                 }
1111                 if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE) {
1112                     /* Broadcasts add a zero at the beginning of the
1113                        message, but otherwise is the same as an IPMB
1114                        address. */
1115                     addr->addr_type = IPMI_IPMB_ADDR_TYPE;
1116                     broadcast = 1;
1117                 }
1118
1119
1120                 /* Default to 1 second retries. */
1121                 if (retry_time_ms == 0)
1122                     retry_time_ms = 1000;
1123
1124                 /* 9 for the header and 1 for the checksum, plus
1125                    possibly one for the broadcast. */
1126                 if ((msg->data_len + 10 + broadcast) > IPMI_MAX_MSG_LENGTH) {
1127                         spin_lock_irqsave(&intf->counter_lock, flags);
1128                         intf->sent_invalid_commands++;
1129                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1130                         rv = -EMSGSIZE;
1131                         goto out_err;
1132                 }
1133
1134                 ipmb_addr = (struct ipmi_ipmb_addr *) addr;
1135                 if (ipmb_addr->lun > 3) {
1136                         spin_lock_irqsave(&intf->counter_lock, flags);
1137                         intf->sent_invalid_commands++;
1138                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1139                         rv = -EINVAL;
1140                         goto out_err;
1141                 }
1142
1143                 memcpy(&recv_msg->addr, ipmb_addr, sizeof(*ipmb_addr));
1144
1145                 if (recv_msg->msg.netfn & 0x1) {
1146                         /* It's a response, so use the user's sequence
1147                            from msgid. */
1148                         spin_lock_irqsave(&intf->counter_lock, flags);
1149                         intf->sent_ipmb_responses++;
1150                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1151                         format_ipmb_msg(smi_msg, msg, ipmb_addr, msgid,
1152                                         msgid, broadcast,
1153                                         source_address, source_lun);
1154
1155                         /* Save the receive message so we can use it
1156                            to deliver the response. */
1157                         smi_msg->user_data = recv_msg;
1158                 } else {
1159                         /* It's a command, so get a sequence for it. */
1160
1161                         spin_lock_irqsave(&(intf->seq_lock), flags);
1162
1163                         spin_lock(&intf->counter_lock);
1164                         intf->sent_ipmb_commands++;
1165                         spin_unlock(&intf->counter_lock);
1166
1167                         /* Create a sequence number with a 1 second
1168                            timeout and 4 retries. */
1169                         rv = intf_next_seq(intf,
1170                                            recv_msg,
1171                                            retry_time_ms,
1172                                            retries,
1173                                            broadcast,
1174                                            &ipmb_seq,
1175                                            &seqid);
1176                         if (rv) {
1177                                 /* We have used up all the sequence numbers,
1178                                    probably, so abort. */
1179                                 spin_unlock_irqrestore(&(intf->seq_lock),
1180                                                        flags);
1181                                 goto out_err;
1182                         }
1183
1184                         /* Store the sequence number in the message,
1185                            so that when the send message response
1186                            comes back we can start the timer. */
1187                         format_ipmb_msg(smi_msg, msg, ipmb_addr,
1188                                         STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
1189                                         ipmb_seq, broadcast,
1190                                         source_address, source_lun);
1191
1192                         /* Copy the message into the recv message data, so we
1193                            can retransmit it later if necessary. */
1194                         memcpy(recv_msg->msg_data, smi_msg->data,
1195                                smi_msg->data_size);
1196                         recv_msg->msg.data = recv_msg->msg_data;
1197                         recv_msg->msg.data_len = smi_msg->data_size;
1198
1199                         /* We don't unlock until here, because we need
1200                            to copy the completed message into the
1201                            recv_msg before we release the lock.
1202                            Otherwise, race conditions may bite us.  I
1203                            know that's pretty paranoid, but I prefer
1204                            to be correct. */
1205                         spin_unlock_irqrestore(&(intf->seq_lock), flags);
1206                 }
1207         } else if (addr->addr_type == IPMI_LAN_ADDR_TYPE) {
1208                 struct ipmi_lan_addr  *lan_addr;
1209                 unsigned char         ipmb_seq;
1210                 long                  seqid;
1211
1212                 if (addr->channel > IPMI_NUM_CHANNELS) {
1213                         spin_lock_irqsave(&intf->counter_lock, flags);
1214                         intf->sent_invalid_commands++;
1215                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1216                         rv = -EINVAL;
1217                         goto out_err;
1218                 }
1219
1220                 if ((intf->channels[addr->channel].medium
1221                     != IPMI_CHANNEL_MEDIUM_8023LAN)
1222                     && (intf->channels[addr->channel].medium
1223                         != IPMI_CHANNEL_MEDIUM_ASYNC))
1224                 {
1225                         spin_lock_irqsave(&intf->counter_lock, flags);
1226                         intf->sent_invalid_commands++;
1227                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1228                         rv = -EINVAL;
1229                         goto out_err;
1230                 }
1231
1232                 retries = 4;
1233
1234                 /* Default to 1 second retries. */
1235                 if (retry_time_ms == 0)
1236                     retry_time_ms = 1000;
1237
1238                 /* 11 for the header and 1 for the checksum. */
1239                 if ((msg->data_len + 12) > IPMI_MAX_MSG_LENGTH) {
1240                         spin_lock_irqsave(&intf->counter_lock, flags);
1241                         intf->sent_invalid_commands++;
1242                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1243                         rv = -EMSGSIZE;
1244                         goto out_err;
1245                 }
1246
1247                 lan_addr = (struct ipmi_lan_addr *) addr;
1248                 if (lan_addr->lun > 3) {
1249                         spin_lock_irqsave(&intf->counter_lock, flags);
1250                         intf->sent_invalid_commands++;
1251                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1252                         rv = -EINVAL;
1253                         goto out_err;
1254                 }
1255
1256                 memcpy(&recv_msg->addr, lan_addr, sizeof(*lan_addr));
1257
1258                 if (recv_msg->msg.netfn & 0x1) {
1259                         /* It's a response, so use the user's sequence
1260                            from msgid. */
1261                         spin_lock_irqsave(&intf->counter_lock, flags);
1262                         intf->sent_lan_responses++;
1263                         spin_unlock_irqrestore(&intf->counter_lock, flags);
1264                         format_lan_msg(smi_msg, msg, lan_addr, msgid,
1265                                        msgid, source_lun);
1266
1267                         /* Save the receive message so we can use it
1268                            to deliver the response. */
1269                         smi_msg->user_data = recv_msg;
1270                 } else {
1271                         /* It's a command, so get a sequence for it. */
1272
1273                         spin_lock_irqsave(&(intf->seq_lock), flags);
1274
1275                         spin_lock(&intf->counter_lock);
1276                         intf->sent_lan_commands++;
1277                         spin_unlock(&intf->counter_lock);
1278
1279                         /* Create a sequence number with a 1 second
1280                            timeout and 4 retries. */
1281                         rv = intf_next_seq(intf,
1282                                            recv_msg,
1283                                            retry_time_ms,
1284                                            retries,
1285                                            0,
1286                                            &ipmb_seq,
1287                                            &seqid);
1288                         if (rv) {
1289                                 /* We have used up all the sequence numbers,
1290                                    probably, so abort. */
1291                                 spin_unlock_irqrestore(&(intf->seq_lock),
1292                                                        flags);
1293                                 goto out_err;
1294                         }
1295
1296                         /* Store the sequence number in the message,
1297                            so that when the send message response
1298                            comes back we can start the timer. */
1299                         format_lan_msg(smi_msg, msg, lan_addr,
1300                                        STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
1301                                        ipmb_seq, source_lun);
1302
1303                         /* Copy the message into the recv message data, so we
1304                            can retransmit it later if necessary. */
1305                         memcpy(recv_msg->msg_data, smi_msg->data,
1306                                smi_msg->data_size);
1307                         recv_msg->msg.data = recv_msg->msg_data;
1308                         recv_msg->msg.data_len = smi_msg->data_size;
1309
1310                         /* We don't unlock until here, because we need
1311                            to copy the completed message into the
1312                            recv_msg before we release the lock.
1313                            Otherwise, race conditions may bite us.  I
1314                            know that's pretty paranoid, but I prefer
1315                            to be correct. */
1316                         spin_unlock_irqrestore(&(intf->seq_lock), flags);
1317                 }
1318         } else {
1319             /* Unknown address type. */
1320                 spin_lock_irqsave(&intf->counter_lock, flags);
1321                 intf->sent_invalid_commands++;
1322                 spin_unlock_irqrestore(&intf->counter_lock, flags);
1323                 rv = -EINVAL;
1324                 goto out_err;
1325         }
1326
1327 #if DEBUG_MSGING
1328         {
1329                 int m;
1330                 for (m=0; m<smi_msg->data_size; m++)
1331                         printk(" %2.2x", smi_msg->data[m]);
1332                 printk("\n");
1333         }
1334 #endif
1335         intf->handlers->sender(intf->send_info, smi_msg, priority);
1336
1337         return 0;
1338
1339  out_err:
1340         ipmi_free_smi_msg(smi_msg);
1341         ipmi_free_recv_msg(recv_msg);
1342         return rv;
1343 }
1344
1345 int ipmi_request(ipmi_user_t      user,
1346                  struct ipmi_addr *addr,
1347                  long             msgid,
1348                  struct ipmi_msg  *msg,
1349                  void             *user_msg_data,
1350                  int              priority)
1351 {
1352         return i_ipmi_request(user,
1353                               user->intf,
1354                               addr,
1355                               msgid,
1356                               msg,
1357                               user_msg_data,
1358                               NULL, NULL,
1359                               priority,
1360                               user->intf->my_address,
1361                               user->intf->my_lun,
1362                               -1, 0);
1363 }
1364
1365 int ipmi_request_settime(ipmi_user_t      user,
1366                          struct ipmi_addr *addr,
1367                          long             msgid,
1368                          struct ipmi_msg  *msg,
1369                          void             *user_msg_data,
1370                          int              priority,
1371                          int              retries,
1372                          unsigned int     retry_time_ms)
1373 {
1374         return i_ipmi_request(user,
1375                               user->intf,
1376                               addr,
1377                               msgid,
1378                               msg,
1379                               user_msg_data,
1380                               NULL, NULL,
1381                               priority,
1382                               user->intf->my_address,
1383                               user->intf->my_lun,
1384                               retries,
1385                               retry_time_ms);
1386 }
1387
1388 int ipmi_request_supply_msgs(ipmi_user_t          user,
1389                              struct ipmi_addr     *addr,
1390                              long                 msgid,
1391                              struct ipmi_msg      *msg,
1392                              void                 *user_msg_data,
1393                              void                 *supplied_smi,
1394                              struct ipmi_recv_msg *supplied_recv,
1395                              int                  priority)
1396 {
1397         return i_ipmi_request(user,
1398                               user->intf,
1399                               addr,
1400                               msgid,
1401                               msg,
1402                               user_msg_data,
1403                               supplied_smi,
1404                               supplied_recv,
1405                               priority,
1406                               user->intf->my_address,
1407                               user->intf->my_lun,
1408                               -1, 0);
1409 }
1410
1411 int ipmi_request_with_source(ipmi_user_t      user,
1412                              struct ipmi_addr *addr,
1413                              long             msgid,
1414                              struct ipmi_msg  *msg,
1415                              void             *user_msg_data,
1416                              int              priority,
1417                              unsigned char    source_address,
1418                              unsigned char    source_lun)
1419 {
1420         return i_ipmi_request(user,
1421                               user->intf,
1422                               addr,
1423                               msgid,
1424                               msg,
1425                               user_msg_data,
1426                               NULL, NULL,
1427                               priority,
1428                               source_address,
1429                               source_lun,
1430                               -1, 0);
1431 }
1432
1433 static int ipmb_file_read_proc(char *page, char **start, off_t off,
1434                                int count, int *eof, void *data)
1435 {
1436         char       *out = (char *) page;
1437         ipmi_smi_t intf = data;
1438
1439         return sprintf(out, "%x\n", intf->my_address);
1440 }
1441
1442 static int version_file_read_proc(char *page, char **start, off_t off,
1443                                   int count, int *eof, void *data)
1444 {
1445         char       *out = (char *) page;
1446         ipmi_smi_t intf = data;
1447
1448         return sprintf(out, "%d.%d\n",
1449                        intf->version_major, intf->version_minor);
1450 }
1451
1452 static int stat_file_read_proc(char *page, char **start, off_t off,
1453                                int count, int *eof, void *data)
1454 {
1455         char       *out = (char *) page;
1456         ipmi_smi_t intf = data;
1457
1458         out += sprintf(out, "sent_invalid_commands:       %d\n",
1459                        intf->sent_invalid_commands);
1460         out += sprintf(out, "sent_local_commands:         %d\n",
1461                        intf->sent_local_commands);
1462         out += sprintf(out, "handled_local_responses:     %d\n",
1463                        intf->handled_local_responses);
1464         out += sprintf(out, "unhandled_local_responses:   %d\n",
1465                        intf->unhandled_local_responses);
1466         out += sprintf(out, "sent_ipmb_commands:          %d\n",
1467                        intf->sent_ipmb_commands);
1468         out += sprintf(out, "sent_ipmb_command_errs:      %d\n",
1469                        intf->sent_ipmb_command_errs);
1470         out += sprintf(out, "retransmitted_ipmb_commands: %d\n",
1471                        intf->retransmitted_ipmb_commands);
1472         out += sprintf(out, "timed_out_ipmb_commands:     %d\n",
1473                        intf->timed_out_ipmb_commands);
1474         out += sprintf(out, "timed_out_ipmb_broadcasts:   %d\n",
1475                        intf->timed_out_ipmb_broadcasts);
1476         out += sprintf(out, "sent_ipmb_responses:         %d\n",
1477                        intf->sent_ipmb_responses);
1478         out += sprintf(out, "handled_ipmb_responses:      %d\n",
1479                        intf->handled_ipmb_responses);
1480         out += sprintf(out, "invalid_ipmb_responses:      %d\n",
1481                        intf->invalid_ipmb_responses);
1482         out += sprintf(out, "unhandled_ipmb_responses:    %d\n",
1483                        intf->unhandled_ipmb_responses);
1484         out += sprintf(out, "sent_lan_commands:           %d\n",
1485                        intf->sent_lan_commands);
1486         out += sprintf(out, "sent_lan_command_errs:       %d\n",
1487                        intf->sent_lan_command_errs);
1488         out += sprintf(out, "retransmitted_lan_commands:  %d\n",
1489                        intf->retransmitted_lan_commands);
1490         out += sprintf(out, "timed_out_lan_commands:      %d\n",
1491                        intf->timed_out_lan_commands);
1492         out += sprintf(out, "sent_lan_responses:          %d\n",
1493                        intf->sent_lan_responses);
1494         out += sprintf(out, "handled_lan_responses:       %d\n",
1495                        intf->handled_lan_responses);
1496         out += sprintf(out, "invalid_lan_responses:       %d\n",
1497                        intf->invalid_lan_responses);
1498         out += sprintf(out, "unhandled_lan_responses:     %d\n",
1499                        intf->unhandled_lan_responses);
1500         out += sprintf(out, "handled_commands:            %d\n",
1501                        intf->handled_commands);
1502         out += sprintf(out, "invalid_commands:            %d\n",
1503                        intf->invalid_commands);
1504         out += sprintf(out, "unhandled_commands:          %d\n",
1505                        intf->unhandled_commands);
1506         out += sprintf(out, "invalid_events:              %d\n",
1507                        intf->invalid_events);
1508         out += sprintf(out, "events:                      %d\n",
1509                        intf->events);
1510
1511         return (out - ((char *) page));
1512 }
1513
1514 int ipmi_smi_add_proc_entry(ipmi_smi_t smi, char *name,
1515                             read_proc_t *read_proc, write_proc_t *write_proc,
1516                             void *data, struct module *owner)
1517 {
1518         struct proc_dir_entry *file;
1519         int                   rv = 0;
1520
1521         file = create_proc_entry(name, 0, smi->proc_dir);
1522         if (!file)
1523                 rv = -ENOMEM;
1524         else {
1525                 file->nlink = 1;
1526                 file->data = data;
1527                 file->read_proc = read_proc;
1528                 file->write_proc = write_proc;
1529                 file->owner = owner;
1530         }
1531
1532         return rv;
1533 }
1534
1535 static int add_proc_entries(ipmi_smi_t smi, int num)
1536 {
1537         int rv = 0;
1538
1539         sprintf(smi->proc_dir_name, "%d", num);
1540         smi->proc_dir = proc_mkdir(smi->proc_dir_name, proc_ipmi_root);
1541         if (!smi->proc_dir)
1542                 rv = -ENOMEM;
1543         else {
1544                 smi->proc_dir->owner = THIS_MODULE;
1545         }
1546
1547         if (rv == 0)
1548                 rv = ipmi_smi_add_proc_entry(smi, "stats",
1549                                              stat_file_read_proc, NULL,
1550                                              smi, THIS_MODULE);
1551
1552         if (rv == 0)
1553                 rv = ipmi_smi_add_proc_entry(smi, "ipmb",
1554                                              ipmb_file_read_proc, NULL,
1555                                              smi, THIS_MODULE);
1556
1557         if (rv == 0)
1558                 rv = ipmi_smi_add_proc_entry(smi, "version",
1559                                              version_file_read_proc, NULL,
1560                                              smi, THIS_MODULE);
1561
1562         return rv;
1563 }
1564
1565 static int
1566 send_channel_info_cmd(ipmi_smi_t intf, int chan)
1567 {
1568         struct ipmi_msg                   msg;
1569         unsigned char                     data[1];
1570         struct ipmi_system_interface_addr si;
1571
1572         si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
1573         si.channel = IPMI_BMC_CHANNEL;
1574         si.lun = 0;
1575
1576         msg.netfn = IPMI_NETFN_APP_REQUEST;
1577         msg.cmd = IPMI_GET_CHANNEL_INFO_CMD;
1578         msg.data = data;
1579         msg.data_len = 1;
1580         data[0] = chan;
1581         return i_ipmi_request(NULL,
1582                               intf,
1583                               (struct ipmi_addr *) &si,
1584                               0,
1585                               &msg,
1586                               NULL,
1587                               NULL,
1588                               NULL,
1589                               0,
1590                               intf->my_address,
1591                               intf->my_lun,
1592                               -1, 0);
1593 }
1594
1595 static void
1596 channel_handler(ipmi_smi_t intf, struct ipmi_smi_msg *msg)
1597 {
1598         int rv = 0;
1599         int chan;
1600
1601         if ((msg->rsp[0] == (IPMI_NETFN_APP_RESPONSE << 2))
1602             && (msg->rsp[1] == IPMI_GET_CHANNEL_INFO_CMD))
1603         {
1604                 /* It's the one we want */
1605                 if (msg->rsp[2] != 0) {
1606                         /* Got an error from the channel, just go on. */
1607                         goto next_channel;
1608                 }
1609                 if (msg->rsp_size < 6) {
1610                         /* Message not big enough, just go on. */
1611                         goto next_channel;
1612                 }
1613                 chan = intf->curr_channel;
1614                 intf->channels[chan].medium = msg->rsp[4] & 0x7f;
1615                 intf->channels[chan].protocol = msg->rsp[5] & 0x1f;
1616
1617         next_channel:
1618                 intf->curr_channel++;
1619                 if (intf->curr_channel >= IPMI_MAX_CHANNELS)
1620                         wake_up(&intf->waitq);
1621                 else
1622                         rv = send_channel_info_cmd(intf, intf->curr_channel);
1623
1624                 if (rv) {
1625                         /* Got an error somehow, just give up. */
1626                         intf->curr_channel = IPMI_MAX_CHANNELS;
1627                         wake_up(&intf->waitq);
1628
1629                         printk(KERN_WARNING "ipmi_msghandler: Error sending"
1630                                "channel information: 0x%x\n",
1631                                rv);
1632                 }
1633         }
1634 }
1635
1636 int ipmi_register_smi(struct ipmi_smi_handlers *handlers,
1637                       void                     *send_info,
1638                       unsigned char            version_major,
1639                       unsigned char            version_minor,
1640                       ipmi_smi_t               *intf)
1641 {
1642         int              i, j;
1643         int              rv;
1644         ipmi_smi_t       new_intf;
1645         unsigned long    flags;
1646
1647
1648         /* Make sure the driver is actually initialized, this handles
1649            problems with initialization order. */
1650         if (!initialized) {
1651                 rv = ipmi_init_msghandler();
1652                 if (rv)
1653                         return rv;
1654                 /* The init code doesn't return an error if it was turned
1655                    off, but it won't initialize.  Check that. */
1656                 if (!initialized)
1657                         return -ENODEV;
1658         }
1659
1660         new_intf = kmalloc(sizeof(*new_intf), GFP_KERNEL);
1661         if (!new_intf)
1662                 return -ENOMEM;
1663         memset(new_intf, 0, sizeof(*new_intf));
1664
1665         new_intf->proc_dir = NULL;
1666
1667         rv = -ENOMEM;
1668
1669         down_write(&interfaces_sem);
1670         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
1671                 if (ipmi_interfaces[i] == NULL) {
1672                         new_intf->intf_num = i;
1673                         new_intf->version_major = version_major;
1674                         new_intf->version_minor = version_minor;
1675                         new_intf->my_address = IPMI_BMC_SLAVE_ADDR;
1676                         new_intf->my_lun = 2;  /* the SMS LUN. */
1677                         rwlock_init(&(new_intf->users_lock));
1678                         INIT_LIST_HEAD(&(new_intf->users));
1679                         new_intf->handlers = handlers;
1680                         new_intf->send_info = send_info;
1681                         spin_lock_init(&(new_intf->seq_lock));
1682                         for (j=0; j<IPMI_IPMB_NUM_SEQ; j++) {
1683                                 new_intf->seq_table[j].inuse = 0;
1684                                 new_intf->seq_table[j].seqid = 0;
1685                         }
1686                         new_intf->curr_seq = 0;
1687                         spin_lock_init(&(new_intf->waiting_msgs_lock));
1688                         INIT_LIST_HEAD(&(new_intf->waiting_msgs));
1689                         spin_lock_init(&(new_intf->events_lock));
1690                         INIT_LIST_HEAD(&(new_intf->waiting_events));
1691                         new_intf->waiting_events_count = 0;
1692                         rwlock_init(&(new_intf->cmd_rcvr_lock));
1693                         init_waitqueue_head(&new_intf->waitq);
1694                         INIT_LIST_HEAD(&(new_intf->cmd_rcvrs));
1695                         new_intf->all_cmd_rcvr = NULL;
1696
1697                         spin_lock_init(&(new_intf->counter_lock));
1698
1699                         spin_lock_irqsave(&interfaces_lock, flags);
1700                         ipmi_interfaces[i] = new_intf;
1701                         spin_unlock_irqrestore(&interfaces_lock, flags);
1702
1703                         rv = 0;
1704                         *intf = new_intf;
1705                         break;
1706                 }
1707         }
1708
1709         downgrade_write(&interfaces_sem);
1710
1711         if (rv == 0)
1712                 rv = add_proc_entries(*intf, i);
1713
1714         if (rv == 0) {
1715                 if ((version_major > 1)
1716                     || ((version_major == 1) && (version_minor >= 5)))
1717                 {
1718                         /* Start scanning the channels to see what is
1719                            available. */
1720                         (*intf)->null_user_handler = channel_handler;
1721                         (*intf)->curr_channel = 0;
1722                         rv = send_channel_info_cmd(*intf, 0);
1723                         if (rv)
1724                                 goto out;
1725
1726                         /* Wait for the channel info to be read. */
1727                         up_read(&interfaces_sem);
1728                         wait_event((*intf)->waitq,
1729                                    ((*intf)->curr_channel>=IPMI_MAX_CHANNELS));
1730                         down_read(&interfaces_sem);
1731
1732                         if (ipmi_interfaces[i] != new_intf)
1733                                 /* Well, it went away.  Just return. */
1734                                 goto out;
1735                 } else {
1736                         /* Assume a single IPMB channel at zero. */
1737                         (*intf)->channels[0].medium = IPMI_CHANNEL_MEDIUM_IPMB;
1738                         (*intf)->channels[0].protocol
1739                                 = IPMI_CHANNEL_PROTOCOL_IPMB;
1740                 }
1741
1742                 /* Call all the watcher interfaces to tell
1743                    them that a new interface is available. */
1744                 call_smi_watchers(i);
1745         }
1746
1747  out:
1748         up_read(&interfaces_sem);
1749
1750         if (rv) {
1751                 if (new_intf->proc_dir)
1752                         remove_proc_entry(new_intf->proc_dir_name,
1753                                           proc_ipmi_root);
1754                 kfree(new_intf);
1755         }
1756
1757         return rv;
1758 }
1759
1760 static void free_recv_msg_list(struct list_head *q)
1761 {
1762         struct ipmi_recv_msg *msg, *msg2;
1763
1764         list_for_each_entry_safe(msg, msg2, q, link) {
1765                 list_del(&msg->link);
1766                 ipmi_free_recv_msg(msg);
1767         }
1768 }
1769
1770 static void free_cmd_rcvr_list(struct list_head *q)
1771 {
1772         struct cmd_rcvr  *rcvr, *rcvr2;
1773
1774         list_for_each_entry_safe(rcvr, rcvr2, q, link) {
1775                 list_del(&rcvr->link);
1776                 kfree(rcvr);
1777         }
1778 }
1779
1780 static void clean_up_interface_data(ipmi_smi_t intf)
1781 {
1782         int i;
1783
1784         free_recv_msg_list(&(intf->waiting_msgs));
1785         free_recv_msg_list(&(intf->waiting_events));
1786         free_cmd_rcvr_list(&(intf->cmd_rcvrs));
1787
1788         for (i=0; i<IPMI_IPMB_NUM_SEQ; i++) {
1789                 if ((intf->seq_table[i].inuse)
1790                     && (intf->seq_table[i].recv_msg))
1791                 {
1792                         ipmi_free_recv_msg(intf->seq_table[i].recv_msg);
1793                 }       
1794         }
1795 }
1796
1797 int ipmi_unregister_smi(ipmi_smi_t intf)
1798 {
1799         int                     rv = -ENODEV;
1800         int                     i;
1801         struct ipmi_smi_watcher *w;
1802         unsigned long           flags;
1803
1804         down_write(&interfaces_sem);
1805         if (list_empty(&(intf->users)))
1806         {
1807                 for (i=0; i<MAX_IPMI_INTERFACES; i++) {
1808                         if (ipmi_interfaces[i] == intf) {
1809                                 remove_proc_entry(intf->proc_dir_name,
1810                                                   proc_ipmi_root);
1811                                 spin_lock_irqsave(&interfaces_lock, flags);
1812                                 ipmi_interfaces[i] = NULL;
1813                                 clean_up_interface_data(intf);
1814                                 spin_unlock_irqrestore(&interfaces_lock,flags);
1815                                 kfree(intf);
1816                                 rv = 0;
1817                                 goto out_call_watcher;
1818                         }
1819                 }
1820         } else {
1821                 rv = -EBUSY;
1822         }
1823         up_write(&interfaces_sem);
1824
1825         return rv;
1826
1827  out_call_watcher:
1828         downgrade_write(&interfaces_sem);
1829
1830         /* Call all the watcher interfaces to tell them that
1831            an interface is gone. */
1832         down_read(&smi_watchers_sem);
1833         list_for_each_entry(w, &smi_watchers, link) {
1834                 w->smi_gone(i);
1835         }
1836         up_read(&smi_watchers_sem);
1837         up_read(&interfaces_sem);
1838         return 0;
1839 }
1840
1841 static int handle_ipmb_get_msg_rsp(ipmi_smi_t          intf,
1842                                    struct ipmi_smi_msg *msg)
1843 {
1844         struct ipmi_ipmb_addr ipmb_addr;
1845         struct ipmi_recv_msg  *recv_msg;
1846         unsigned long         flags;
1847
1848         
1849         /* This is 11, not 10, because the response must contain a
1850          * completion code. */
1851         if (msg->rsp_size < 11) {
1852                 /* Message not big enough, just ignore it. */
1853                 spin_lock_irqsave(&intf->counter_lock, flags);
1854                 intf->invalid_ipmb_responses++;
1855                 spin_unlock_irqrestore(&intf->counter_lock, flags);
1856                 return 0;
1857         }
1858
1859         if (msg->rsp[2] != 0) {
1860                 /* An error getting the response, just ignore it. */
1861                 return 0;
1862         }
1863
1864         ipmb_addr.addr_type = IPMI_IPMB_ADDR_TYPE;
1865         ipmb_addr.slave_addr = msg->rsp[6];
1866         ipmb_addr.channel = msg->rsp[3] & 0x0f;
1867         ipmb_addr.lun = msg->rsp[7] & 3;
1868
1869         /* It's a response from a remote entity.  Look up the sequence
1870            number and handle the response. */
1871         if (intf_find_seq(intf,
1872                           msg->rsp[7] >> 2,
1873                           msg->rsp[3] & 0x0f,
1874                           msg->rsp[8],
1875                           (msg->rsp[4] >> 2) & (~1),
1876                           (struct ipmi_addr *) &(ipmb_addr),
1877                           &recv_msg))
1878         {
1879                 /* We were unable to find the sequence number,
1880                    so just nuke the message. */
1881                 spin_lock_irqsave(&intf->counter_lock, flags);
1882                 intf->unhandled_ipmb_responses++;
1883                 spin_unlock_irqrestore(&intf->counter_lock, flags);
1884                 return 0;
1885         }
1886
1887         memcpy(recv_msg->msg_data,
1888                &(msg->rsp[9]),
1889                msg->rsp_size - 9);
1890         /* THe other fields matched, so no need to set them, except
1891            for netfn, which needs to be the response that was
1892            returned, not the request value. */
1893         recv_msg->msg.netfn = msg->rsp[4] >> 2;
1894         recv_msg->msg.data = recv_msg->msg_data;
1895         recv_msg->msg.data_len = msg->rsp_size - 10;
1896         recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
1897         spin_lock_irqsave(&intf->counter_lock, flags);
1898         intf->handled_ipmb_responses++;
1899         spin_unlock_irqrestore(&intf->counter_lock, flags);
1900         deliver_response(recv_msg);
1901
1902         return 0;
1903 }
1904
1905 static int handle_ipmb_get_msg_cmd(ipmi_smi_t          intf,
1906                                    struct ipmi_smi_msg *msg)
1907 {
1908         struct cmd_rcvr       *rcvr;
1909         int                   rv = 0;
1910         unsigned char         netfn;
1911         unsigned char         cmd;
1912         ipmi_user_t           user = NULL;
1913         struct ipmi_ipmb_addr *ipmb_addr;
1914         struct ipmi_recv_msg  *recv_msg;
1915         unsigned long         flags;
1916
1917         if (msg->rsp_size < 10) {
1918                 /* Message not big enough, just ignore it. */
1919                 spin_lock_irqsave(&intf->counter_lock, flags);
1920                 intf->invalid_commands++;
1921                 spin_unlock_irqrestore(&intf->counter_lock, flags);
1922                 return 0;
1923         }
1924
1925         if (msg->rsp[2] != 0) {
1926                 /* An error getting the response, just ignore it. */
1927                 return 0;
1928         }
1929
1930         netfn = msg->rsp[4] >> 2;
1931         cmd = msg->rsp[8];
1932
1933         read_lock(&(intf->cmd_rcvr_lock));
1934         
1935         if (intf->all_cmd_rcvr) {
1936                 user = intf->all_cmd_rcvr;
1937         } else {
1938                 /* Find the command/netfn. */
1939                 list_for_each_entry(rcvr, &(intf->cmd_rcvrs), link) {
1940                         if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)) {
1941                                 user = rcvr->user;
1942                                 break;
1943                         }
1944                 }
1945         }
1946         read_unlock(&(intf->cmd_rcvr_lock));
1947
1948         if (user == NULL) {
1949                 /* We didn't find a user, deliver an error response. */
1950                 spin_lock_irqsave(&intf->counter_lock, flags);
1951                 intf->unhandled_commands++;
1952                 spin_unlock_irqrestore(&intf->counter_lock, flags);
1953
1954                 msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
1955                 msg->data[1] = IPMI_SEND_MSG_CMD;
1956                 msg->data[2] = msg->rsp[3];
1957                 msg->data[3] = msg->rsp[6];
1958                 msg->data[4] = ((netfn + 1) << 2) | (msg->rsp[7] & 0x3);
1959                 msg->data[5] = ipmb_checksum(&(msg->data[3]), 2);
1960                 msg->data[6] = intf->my_address;
1961                 /* rqseq/lun */
1962                 msg->data[7] = (msg->rsp[7] & 0xfc) | (msg->rsp[4] & 0x3);
1963                 msg->data[8] = msg->rsp[8]; /* cmd */
1964                 msg->data[9] = IPMI_INVALID_CMD_COMPLETION_CODE;
1965                 msg->data[10] = ipmb_checksum(&(msg->data[6]), 4);
1966                 msg->data_size = 11;
1967
1968 #if DEBUG_MSGING
1969         {
1970                 int m;
1971                 printk("Invalid command:");
1972                 for (m=0; m<msg->data_size; m++)
1973                         printk(" %2.2x", msg->data[m]);
1974                 printk("\n");
1975         }
1976 #endif
1977                 intf->handlers->sender(intf->send_info, msg, 0);
1978
1979                 rv = -1; /* We used the message, so return the value that
1980                             causes it to not be freed or queued. */
1981         } else {
1982                 /* Deliver the message to the user. */
1983                 spin_lock_irqsave(&intf->counter_lock, flags);
1984                 intf->handled_commands++;
1985                 spin_unlock_irqrestore(&intf->counter_lock, flags);
1986
1987                 recv_msg = ipmi_alloc_recv_msg();
1988                 if (! recv_msg) {
1989                         /* We couldn't allocate memory for the
1990                            message, so requeue it for handling
1991                            later. */
1992                         rv = 1;
1993                 } else {
1994                         /* Extract the source address from the data. */
1995                         ipmb_addr = (struct ipmi_ipmb_addr *) &recv_msg->addr;
1996                         ipmb_addr->addr_type = IPMI_IPMB_ADDR_TYPE;
1997                         ipmb_addr->slave_addr = msg->rsp[6];
1998                         ipmb_addr->lun = msg->rsp[7] & 3;
1999                         ipmb_addr->channel = msg->rsp[3] & 0xf;
2000
2001                         /* Extract the rest of the message information
2002                            from the IPMB header.*/
2003                         recv_msg->user = user;
2004                         recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
2005                         recv_msg->msgid = msg->rsp[7] >> 2;
2006                         recv_msg->msg.netfn = msg->rsp[4] >> 2;
2007                         recv_msg->msg.cmd = msg->rsp[8];
2008                         recv_msg->msg.data = recv_msg->msg_data;
2009
2010                         /* We chop off 10, not 9 bytes because the checksum
2011                            at the end also needs to be removed. */
2012                         recv_msg->msg.data_len = msg->rsp_size - 10;
2013                         memcpy(recv_msg->msg_data,
2014                                &(msg->rsp[9]),
2015                                msg->rsp_size - 10);
2016                         deliver_response(recv_msg);
2017                 }
2018         }
2019
2020         return rv;
2021 }
2022
2023 static int handle_lan_get_msg_rsp(ipmi_smi_t          intf,
2024                                   struct ipmi_smi_msg *msg)
2025 {
2026         struct ipmi_lan_addr  lan_addr;
2027         struct ipmi_recv_msg  *recv_msg;
2028         unsigned long         flags;
2029
2030
2031         /* This is 13, not 12, because the response must contain a
2032          * completion code. */
2033         if (msg->rsp_size < 13) {
2034                 /* Message not big enough, just ignore it. */
2035                 spin_lock_irqsave(&intf->counter_lock, flags);
2036                 intf->invalid_lan_responses++;
2037                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2038                 return 0;
2039         }
2040
2041         if (msg->rsp[2] != 0) {
2042                 /* An error getting the response, just ignore it. */
2043                 return 0;
2044         }
2045
2046         lan_addr.addr_type = IPMI_LAN_ADDR_TYPE;
2047         lan_addr.session_handle = msg->rsp[4];
2048         lan_addr.remote_SWID = msg->rsp[8];
2049         lan_addr.local_SWID = msg->rsp[5];
2050         lan_addr.channel = msg->rsp[3] & 0x0f;
2051         lan_addr.privilege = msg->rsp[3] >> 4;
2052         lan_addr.lun = msg->rsp[9] & 3;
2053
2054         /* It's a response from a remote entity.  Look up the sequence
2055            number and handle the response. */
2056         if (intf_find_seq(intf,
2057                           msg->rsp[9] >> 2,
2058                           msg->rsp[3] & 0x0f,
2059                           msg->rsp[10],
2060                           (msg->rsp[6] >> 2) & (~1),
2061                           (struct ipmi_addr *) &(lan_addr),
2062                           &recv_msg))
2063         {
2064                 /* We were unable to find the sequence number,
2065                    so just nuke the message. */
2066                 spin_lock_irqsave(&intf->counter_lock, flags);
2067                 intf->unhandled_lan_responses++;
2068                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2069                 return 0;
2070         }
2071
2072         memcpy(recv_msg->msg_data,
2073                &(msg->rsp[11]),
2074                msg->rsp_size - 11);
2075         /* The other fields matched, so no need to set them, except
2076            for netfn, which needs to be the response that was
2077            returned, not the request value. */
2078         recv_msg->msg.netfn = msg->rsp[6] >> 2;
2079         recv_msg->msg.data = recv_msg->msg_data;
2080         recv_msg->msg.data_len = msg->rsp_size - 12;
2081         recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
2082         spin_lock_irqsave(&intf->counter_lock, flags);
2083         intf->handled_lan_responses++;
2084         spin_unlock_irqrestore(&intf->counter_lock, flags);
2085         deliver_response(recv_msg);
2086
2087         return 0;
2088 }
2089
2090 static int handle_lan_get_msg_cmd(ipmi_smi_t          intf,
2091                                   struct ipmi_smi_msg *msg)
2092 {
2093         struct cmd_rcvr       *rcvr;
2094         int                   rv = 0;
2095         unsigned char         netfn;
2096         unsigned char         cmd;
2097         ipmi_user_t           user = NULL;
2098         struct ipmi_lan_addr  *lan_addr;
2099         struct ipmi_recv_msg  *recv_msg;
2100         unsigned long         flags;
2101
2102         if (msg->rsp_size < 12) {
2103                 /* Message not big enough, just ignore it. */
2104                 spin_lock_irqsave(&intf->counter_lock, flags);
2105                 intf->invalid_commands++;
2106                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2107                 return 0;
2108         }
2109
2110         if (msg->rsp[2] != 0) {
2111                 /* An error getting the response, just ignore it. */
2112                 return 0;
2113         }
2114
2115         netfn = msg->rsp[6] >> 2;
2116         cmd = msg->rsp[10];
2117
2118         read_lock(&(intf->cmd_rcvr_lock));
2119
2120         if (intf->all_cmd_rcvr) {
2121                 user = intf->all_cmd_rcvr;
2122         } else {
2123                 /* Find the command/netfn. */
2124                 list_for_each_entry(rcvr, &(intf->cmd_rcvrs), link) {
2125                         if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)) {
2126                                 user = rcvr->user;
2127                                 break;
2128                         }
2129                 }
2130         }
2131         read_unlock(&(intf->cmd_rcvr_lock));
2132
2133         if (user == NULL) {
2134                 /* We didn't find a user, deliver an error response. */
2135                 spin_lock_irqsave(&intf->counter_lock, flags);
2136                 intf->unhandled_commands++;
2137                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2138
2139                 rv = 0; /* Don't do anything with these messages, just
2140                            allow them to be freed. */
2141         } else {
2142                 /* Deliver the message to the user. */
2143                 spin_lock_irqsave(&intf->counter_lock, flags);
2144                 intf->handled_commands++;
2145                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2146
2147                 recv_msg = ipmi_alloc_recv_msg();
2148                 if (! recv_msg) {
2149                         /* We couldn't allocate memory for the
2150                            message, so requeue it for handling
2151                            later. */
2152                         rv = 1;
2153                 } else {
2154                         /* Extract the source address from the data. */
2155                         lan_addr = (struct ipmi_lan_addr *) &recv_msg->addr;
2156                         lan_addr->addr_type = IPMI_LAN_ADDR_TYPE;
2157                         lan_addr->session_handle = msg->rsp[4];
2158                         lan_addr->remote_SWID = msg->rsp[8];
2159                         lan_addr->local_SWID = msg->rsp[5];
2160                         lan_addr->lun = msg->rsp[9] & 3;
2161                         lan_addr->channel = msg->rsp[3] & 0xf;
2162                         lan_addr->privilege = msg->rsp[3] >> 4;
2163
2164                         /* Extract the rest of the message information
2165                            from the IPMB header.*/
2166                         recv_msg->user = user;
2167                         recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
2168                         recv_msg->msgid = msg->rsp[9] >> 2;
2169                         recv_msg->msg.netfn = msg->rsp[6] >> 2;
2170                         recv_msg->msg.cmd = msg->rsp[10];
2171                         recv_msg->msg.data = recv_msg->msg_data;
2172
2173                         /* We chop off 12, not 11 bytes because the checksum
2174                            at the end also needs to be removed. */
2175                         recv_msg->msg.data_len = msg->rsp_size - 12;
2176                         memcpy(recv_msg->msg_data,
2177                                &(msg->rsp[11]),
2178                                msg->rsp_size - 12);
2179                         deliver_response(recv_msg);
2180                 }
2181         }
2182
2183         return rv;
2184 }
2185
2186 static void copy_event_into_recv_msg(struct ipmi_recv_msg *recv_msg,
2187                                      struct ipmi_smi_msg  *msg)
2188 {
2189         struct ipmi_system_interface_addr *smi_addr;
2190         
2191         recv_msg->msgid = 0;
2192         smi_addr = (struct ipmi_system_interface_addr *) &(recv_msg->addr);
2193         smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
2194         smi_addr->channel = IPMI_BMC_CHANNEL;
2195         smi_addr->lun = msg->rsp[0] & 3;
2196         recv_msg->recv_type = IPMI_ASYNC_EVENT_RECV_TYPE;
2197         recv_msg->msg.netfn = msg->rsp[0] >> 2;
2198         recv_msg->msg.cmd = msg->rsp[1];
2199         memcpy(recv_msg->msg_data, &(msg->rsp[3]), msg->rsp_size - 3);
2200         recv_msg->msg.data = recv_msg->msg_data;
2201         recv_msg->msg.data_len = msg->rsp_size - 3;
2202 }
2203
2204 /* This will be called with the intf->users_lock read-locked, so no need
2205    to do that here. */
2206 static int handle_read_event_rsp(ipmi_smi_t          intf,
2207                                  struct ipmi_smi_msg *msg)
2208 {
2209         struct ipmi_recv_msg *recv_msg, *recv_msg2;
2210         struct list_head     msgs;
2211         ipmi_user_t          user;
2212         int                  rv = 0;
2213         int                  deliver_count = 0;
2214         unsigned long        flags;
2215
2216         if (msg->rsp_size < 19) {
2217                 /* Message is too small to be an IPMB event. */
2218                 spin_lock_irqsave(&intf->counter_lock, flags);
2219                 intf->invalid_events++;
2220                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2221                 return 0;
2222         }
2223
2224         if (msg->rsp[2] != 0) {
2225                 /* An error getting the event, just ignore it. */
2226                 return 0;
2227         }
2228
2229         INIT_LIST_HEAD(&msgs);
2230
2231         spin_lock_irqsave(&(intf->events_lock), flags);
2232
2233         spin_lock(&intf->counter_lock);
2234         intf->events++;
2235         spin_unlock(&intf->counter_lock);
2236
2237         /* Allocate and fill in one message for every user that is getting
2238            events. */
2239         list_for_each_entry(user, &(intf->users), link) {
2240                 if (! user->gets_events)
2241                         continue;
2242
2243                 recv_msg = ipmi_alloc_recv_msg();
2244                 if (! recv_msg) {
2245                         list_for_each_entry_safe(recv_msg, recv_msg2, &msgs, link) {
2246                                 list_del(&recv_msg->link);
2247                                 ipmi_free_recv_msg(recv_msg);
2248                         }
2249                         /* We couldn't allocate memory for the
2250                            message, so requeue it for handling
2251                            later. */
2252                         rv = 1;
2253                         goto out;
2254                 }
2255
2256                 deliver_count++;
2257
2258                 copy_event_into_recv_msg(recv_msg, msg);
2259                 recv_msg->user = user;
2260                 list_add_tail(&(recv_msg->link), &msgs);
2261         }
2262
2263         if (deliver_count) {
2264                 /* Now deliver all the messages. */
2265                 list_for_each_entry_safe(recv_msg, recv_msg2, &msgs, link) {
2266                         list_del(&recv_msg->link);
2267                         deliver_response(recv_msg);
2268                 }
2269         } else if (intf->waiting_events_count < MAX_EVENTS_IN_QUEUE) {
2270                 /* No one to receive the message, put it in queue if there's
2271                    not already too many things in the queue. */
2272                 recv_msg = ipmi_alloc_recv_msg();
2273                 if (! recv_msg) {
2274                         /* We couldn't allocate memory for the
2275                            message, so requeue it for handling
2276                            later. */
2277                         rv = 1;
2278                         goto out;
2279                 }
2280
2281                 copy_event_into_recv_msg(recv_msg, msg);
2282                 list_add_tail(&(recv_msg->link), &(intf->waiting_events));
2283         } else {
2284                 /* There's too many things in the queue, discard this
2285                    message. */
2286                 printk(KERN_WARNING "ipmi: Event queue full, discarding an"
2287                        " incoming event\n");
2288         }
2289
2290  out:
2291         spin_unlock_irqrestore(&(intf->events_lock), flags);
2292
2293         return rv;
2294 }
2295
2296 static int handle_bmc_rsp(ipmi_smi_t          intf,
2297                           struct ipmi_smi_msg *msg)
2298 {
2299         struct ipmi_recv_msg *recv_msg;
2300         int                  found = 0;
2301         struct ipmi_user     *user;
2302         unsigned long        flags;
2303
2304         recv_msg = (struct ipmi_recv_msg *) msg->user_data;
2305
2306         /* Make sure the user still exists. */
2307         list_for_each_entry(user, &(intf->users), link) {
2308                 if (user == recv_msg->user) {
2309                         /* Found it, so we can deliver it */
2310                         found = 1;
2311                         break;
2312                 }
2313         }
2314
2315         if (!found) {
2316                 /* Special handling for NULL users. */
2317                 if (!recv_msg->user && intf->null_user_handler)
2318                         intf->null_user_handler(intf, msg);
2319                 /* The user for the message went away, so give up. */
2320                 spin_lock_irqsave(&intf->counter_lock, flags);
2321                 intf->unhandled_local_responses++;
2322                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2323                 ipmi_free_recv_msg(recv_msg);
2324         } else {
2325                 struct ipmi_system_interface_addr *smi_addr;
2326
2327                 spin_lock_irqsave(&intf->counter_lock, flags);
2328                 intf->handled_local_responses++;
2329                 spin_unlock_irqrestore(&intf->counter_lock, flags);
2330                 recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
2331                 recv_msg->msgid = msg->msgid;
2332                 smi_addr = ((struct ipmi_system_interface_addr *)
2333                             &(recv_msg->addr));
2334                 smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
2335                 smi_addr->channel = IPMI_BMC_CHANNEL;
2336                 smi_addr->lun = msg->rsp[0] & 3;
2337                 recv_msg->msg.netfn = msg->rsp[0] >> 2;
2338                 recv_msg->msg.cmd = msg->rsp[1];
2339                 memcpy(recv_msg->msg_data,
2340                        &(msg->rsp[2]),
2341                        msg->rsp_size - 2);
2342                 recv_msg->msg.data = recv_msg->msg_data;
2343                 recv_msg->msg.data_len = msg->rsp_size - 2;
2344                 deliver_response(recv_msg);
2345         }
2346
2347         return 0;
2348 }
2349
2350 /* Handle a new message.  Return 1 if the message should be requeued,
2351    0 if the message should be freed, or -1 if the message should not
2352    be freed or requeued. */
2353 static int handle_new_recv_msg(ipmi_smi_t          intf,
2354                                struct ipmi_smi_msg *msg)
2355 {
2356         int requeue;
2357         int chan;
2358
2359 #if DEBUG_MSGING
2360         int m;
2361         printk("Recv:");
2362         for (m=0; m<msg->rsp_size; m++)
2363                 printk(" %2.2x", msg->rsp[m]);
2364         printk("\n");
2365 #endif
2366         if (msg->rsp_size < 2) {
2367                 /* Message is too small to be correct. */
2368                 requeue = 0;
2369         } else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
2370                    && (msg->rsp[1] == IPMI_SEND_MSG_CMD)
2371                    && (msg->user_data != NULL))
2372         {
2373                 /* It's a response to a response we sent.  For this we
2374                    deliver a send message response to the user. */
2375                 struct ipmi_recv_msg *recv_msg = msg->user_data;
2376
2377                 requeue = 0;
2378                 if (msg->rsp_size < 2)
2379                         /* Message is too small to be correct. */
2380                         goto out;
2381
2382                 chan = msg->data[2] & 0x0f;
2383                 if (chan >= IPMI_MAX_CHANNELS)
2384                         /* Invalid channel number */
2385                         goto out;
2386
2387                 if (recv_msg) {
2388                         recv_msg->recv_type = IPMI_RESPONSE_RESPONSE_TYPE;
2389                         recv_msg->msg.data = recv_msg->msg_data;
2390                         recv_msg->msg.data_len = 1;
2391                         recv_msg->msg_data[0] = msg->rsp[2];
2392                         deliver_response(recv_msg);
2393                 }
2394         } else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
2395                    && (msg->rsp[1] == IPMI_GET_MSG_CMD))
2396         {
2397                 /* It's from the receive queue. */
2398                 chan = msg->rsp[3] & 0xf;
2399                 if (chan >= IPMI_MAX_CHANNELS) {
2400                         /* Invalid channel number */
2401                         requeue = 0;
2402                         goto out;
2403                 }
2404
2405                 switch (intf->channels[chan].medium) {
2406                 case IPMI_CHANNEL_MEDIUM_IPMB:
2407                         if (msg->rsp[4] & 0x04) {
2408                                 /* It's a response, so find the
2409                                    requesting message and send it up. */
2410                                 requeue = handle_ipmb_get_msg_rsp(intf, msg);
2411                         } else {
2412                                 /* It's a command to the SMS from some other
2413                                    entity.  Handle that. */
2414                                 requeue = handle_ipmb_get_msg_cmd(intf, msg);
2415                         }
2416                         break;
2417
2418                 case IPMI_CHANNEL_MEDIUM_8023LAN:
2419                 case IPMI_CHANNEL_MEDIUM_ASYNC:
2420                         if (msg->rsp[6] & 0x04) {
2421                                 /* It's a response, so find the
2422                                    requesting message and send it up. */
2423                                 requeue = handle_lan_get_msg_rsp(intf, msg);
2424                         } else {
2425                                 /* It's a command to the SMS from some other
2426                                    entity.  Handle that. */
2427                                 requeue = handle_lan_get_msg_cmd(intf, msg);
2428                         }
2429                         break;
2430
2431                 default:
2432                         /* We don't handle the channel type, so just
2433                          * free the message. */
2434                         requeue = 0;
2435                 }
2436
2437         } else if (msg->rsp[1] == IPMI_READ_EVENT_MSG_BUFFER_CMD) {
2438                 /* It's an asyncronous event. */
2439                 requeue = handle_read_event_rsp(intf, msg);
2440         } else {
2441                 /* It's a response from the local BMC. */
2442                 requeue = handle_bmc_rsp(intf, msg);
2443         }
2444
2445  out:
2446         return requeue;
2447 }
2448
2449 /* Handle a new message from the lower layer. */
2450 void ipmi_smi_msg_received(ipmi_smi_t          intf,
2451                            struct ipmi_smi_msg *msg)
2452 {
2453         unsigned long flags;
2454         int           rv;
2455
2456
2457         /* Lock the user lock so the user can't go away while we are
2458            working on it. */
2459         read_lock(&(intf->users_lock));
2460
2461         if ((msg->data_size >= 2)
2462             && (msg->data[0] == (IPMI_NETFN_APP_REQUEST << 2))
2463             && (msg->data[1] == IPMI_SEND_MSG_CMD)
2464             && (msg->user_data == NULL)) {
2465                 /* This is the local response to a command send, start
2466                    the timer for these.  The user_data will not be
2467                    NULL if this is a response send, and we will let
2468                    response sends just go through. */
2469
2470                 /* Check for errors, if we get certain errors (ones
2471                    that mean basically we can try again later), we
2472                    ignore them and start the timer.  Otherwise we
2473                    report the error immediately. */
2474                 if ((msg->rsp_size >= 3) && (msg->rsp[2] != 0)
2475                     && (msg->rsp[2] != IPMI_NODE_BUSY_ERR)
2476                     && (msg->rsp[2] != IPMI_LOST_ARBITRATION_ERR))
2477                 {
2478                         int chan = msg->rsp[3] & 0xf;
2479
2480                         /* Got an error sending the message, handle it. */
2481                         spin_lock_irqsave(&intf->counter_lock, flags);
2482                         if (chan >= IPMI_MAX_CHANNELS)
2483                                 ; /* This shouldn't happen */
2484                         else if ((intf->channels[chan].medium
2485                                   == IPMI_CHANNEL_MEDIUM_8023LAN)
2486                                  || (intf->channels[chan].medium
2487                                      == IPMI_CHANNEL_MEDIUM_ASYNC))
2488                                 intf->sent_lan_command_errs++;
2489                         else
2490                                 intf->sent_ipmb_command_errs++;
2491                         spin_unlock_irqrestore(&intf->counter_lock, flags);
2492                         intf_err_seq(intf, msg->msgid, msg->rsp[2]);
2493                 } else {
2494                         /* The message was sent, start the timer. */
2495                         intf_start_seq_timer(intf, msg->msgid);
2496                 }
2497
2498                 ipmi_free_smi_msg(msg);
2499                 goto out_unlock;
2500         }
2501
2502         /* To preserve message order, if the list is not empty, we
2503            tack this message onto the end of the list. */
2504         spin_lock_irqsave(&(intf->waiting_msgs_lock), flags);
2505         if (!list_empty(&(intf->waiting_msgs))) {
2506                 list_add_tail(&(msg->link), &(intf->waiting_msgs));
2507                 spin_unlock(&(intf->waiting_msgs_lock));
2508                 goto out_unlock;
2509         }
2510         spin_unlock_irqrestore(&(intf->waiting_msgs_lock), flags);
2511                 
2512         rv = handle_new_recv_msg(intf, msg);
2513         if (rv > 0) {
2514                 /* Could not handle the message now, just add it to a
2515                    list to handle later. */
2516                 spin_lock(&(intf->waiting_msgs_lock));
2517                 list_add_tail(&(msg->link), &(intf->waiting_msgs));
2518                 spin_unlock(&(intf->waiting_msgs_lock));
2519         } else if (rv == 0) {
2520                 ipmi_free_smi_msg(msg);
2521         }
2522
2523  out_unlock:
2524         read_unlock(&(intf->users_lock));
2525 }
2526
2527 void ipmi_smi_watchdog_pretimeout(ipmi_smi_t intf)
2528 {
2529         ipmi_user_t user;
2530
2531         read_lock(&(intf->users_lock));
2532         list_for_each_entry(user, &(intf->users), link) {
2533                 if (! user->handler->ipmi_watchdog_pretimeout)
2534                         continue;
2535
2536                 user->handler->ipmi_watchdog_pretimeout(user->handler_data);
2537         }
2538         read_unlock(&(intf->users_lock));
2539 }
2540
2541 static void
2542 handle_msg_timeout(struct ipmi_recv_msg *msg)
2543 {
2544         msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
2545         msg->msg_data[0] = IPMI_TIMEOUT_COMPLETION_CODE;
2546         msg->msg.netfn |= 1; /* Convert to a response. */
2547         msg->msg.data_len = 1;
2548         msg->msg.data = msg->msg_data;
2549         deliver_response(msg);
2550 }
2551
2552 static void
2553 send_from_recv_msg(ipmi_smi_t intf, struct ipmi_recv_msg *recv_msg,
2554                    struct ipmi_smi_msg *smi_msg,
2555                    unsigned char seq, long seqid)
2556 {
2557         if (!smi_msg)
2558                 smi_msg = ipmi_alloc_smi_msg();
2559         if (!smi_msg)
2560                 /* If we can't allocate the message, then just return, we
2561                    get 4 retries, so this should be ok. */
2562                 return;
2563
2564         memcpy(smi_msg->data, recv_msg->msg.data, recv_msg->msg.data_len);
2565         smi_msg->data_size = recv_msg->msg.data_len;
2566         smi_msg->msgid = STORE_SEQ_IN_MSGID(seq, seqid);
2567                 
2568         /* Send the new message.  We send with a zero priority.  It
2569            timed out, I doubt time is that critical now, and high
2570            priority messages are really only for messages to the local
2571            MC, which don't get resent. */
2572         intf->handlers->sender(intf->send_info, smi_msg, 0);
2573
2574 #if DEBUG_MSGING
2575         {
2576                 int m;
2577                 printk("Resend: ");
2578                 for (m=0; m<smi_msg->data_size; m++)
2579                         printk(" %2.2x", smi_msg->data[m]);
2580                 printk("\n");
2581         }
2582 #endif
2583 }
2584
2585 static void
2586 ipmi_timeout_handler(long timeout_period)
2587 {
2588         ipmi_smi_t           intf;
2589         struct list_head     timeouts;
2590         struct ipmi_recv_msg *msg, *msg2;
2591         struct ipmi_smi_msg  *smi_msg, *smi_msg2;
2592         unsigned long        flags;
2593         int                  i, j;
2594
2595         INIT_LIST_HEAD(&timeouts);
2596
2597         spin_lock(&interfaces_lock);
2598         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
2599                 intf = ipmi_interfaces[i];
2600                 if (intf == NULL)
2601                         continue;
2602
2603                 read_lock(&(intf->users_lock));
2604
2605                 /* See if any waiting messages need to be processed. */
2606                 spin_lock_irqsave(&(intf->waiting_msgs_lock), flags);
2607                 list_for_each_entry_safe(smi_msg, smi_msg2, &(intf->waiting_msgs), link) {
2608                         if (! handle_new_recv_msg(intf, smi_msg)) {
2609                                 list_del(&smi_msg->link);
2610                                 ipmi_free_smi_msg(smi_msg);
2611                         } else {
2612                                 /* To preserve message order, quit if we
2613                                    can't handle a message. */
2614                                 break;
2615                         }
2616                 }
2617                 spin_unlock_irqrestore(&(intf->waiting_msgs_lock), flags);
2618
2619                 /* Go through the seq table and find any messages that
2620                    have timed out, putting them in the timeouts
2621                    list. */
2622                 spin_lock_irqsave(&(intf->seq_lock), flags);
2623                 for (j=0; j<IPMI_IPMB_NUM_SEQ; j++) {
2624                         struct seq_table *ent = &(intf->seq_table[j]);
2625                         if (!ent->inuse)
2626                                 continue;
2627
2628                         ent->timeout -= timeout_period;
2629                         if (ent->timeout > 0)
2630                                 continue;
2631
2632                         if (ent->retries_left == 0) {
2633                                 /* The message has used all its retries. */
2634                                 ent->inuse = 0;
2635                                 msg = ent->recv_msg;
2636                                 list_add_tail(&(msg->link), &timeouts);
2637                                 spin_lock(&intf->counter_lock);
2638                                 if (ent->broadcast)
2639                                         intf->timed_out_ipmb_broadcasts++;
2640                                 else if (ent->recv_msg->addr.addr_type
2641                                          == IPMI_LAN_ADDR_TYPE)
2642                                         intf->timed_out_lan_commands++;
2643                                 else
2644                                         intf->timed_out_ipmb_commands++;
2645                                 spin_unlock(&intf->counter_lock);
2646                         } else {
2647                                 /* More retries, send again. */
2648
2649                                 /* Start with the max timer, set to normal
2650                                    timer after the message is sent. */
2651                                 ent->timeout = MAX_MSG_TIMEOUT;
2652                                 ent->retries_left--;
2653                                 send_from_recv_msg(intf, ent->recv_msg, NULL,
2654                                                    j, ent->seqid);
2655                                 spin_lock(&intf->counter_lock);
2656                                 if (ent->recv_msg->addr.addr_type
2657                                     == IPMI_LAN_ADDR_TYPE)
2658                                         intf->retransmitted_lan_commands++;
2659                                 else
2660                                         intf->retransmitted_ipmb_commands++;
2661                                 spin_unlock(&intf->counter_lock);
2662                         }
2663                 }
2664                 spin_unlock_irqrestore(&(intf->seq_lock), flags);
2665
2666                 list_for_each_entry_safe(msg, msg2, &timeouts, link) {
2667                         handle_msg_timeout(msg);
2668                 }
2669
2670                 read_unlock(&(intf->users_lock));
2671         }
2672         spin_unlock(&interfaces_lock);
2673 }
2674
2675 static void ipmi_request_event(void)
2676 {
2677         ipmi_smi_t intf;
2678         int        i;
2679
2680         spin_lock(&interfaces_lock);
2681         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
2682                 intf = ipmi_interfaces[i];
2683                 if (intf == NULL)
2684                         continue;
2685
2686                 intf->handlers->request_events(intf->send_info);
2687         }
2688         spin_unlock(&interfaces_lock);
2689 }
2690
2691 static struct timer_list ipmi_timer;
2692
2693 /* Call every ~100 ms. */
2694 #define IPMI_TIMEOUT_TIME       100
2695
2696 /* How many jiffies does it take to get to the timeout time. */
2697 #define IPMI_TIMEOUT_JIFFIES    ((IPMI_TIMEOUT_TIME * HZ) / 1000)
2698
2699 /* Request events from the queue every second (this is the number of
2700    IPMI_TIMEOUT_TIMES between event requests).  Hopefully, in the
2701    future, IPMI will add a way to know immediately if an event is in
2702    the queue and this silliness can go away. */
2703 #define IPMI_REQUEST_EV_TIME    (1000 / (IPMI_TIMEOUT_TIME))
2704
2705 static volatile int stop_operation = 0;
2706 static volatile int timer_stopped = 0;
2707 static unsigned int ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
2708
2709 static void ipmi_timeout(unsigned long data)
2710 {
2711         if (stop_operation) {
2712                 timer_stopped = 1;
2713                 return;
2714         }
2715
2716         ticks_to_req_ev--;
2717         if (ticks_to_req_ev == 0) {
2718                 ipmi_request_event();
2719                 ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
2720         }
2721
2722         ipmi_timeout_handler(IPMI_TIMEOUT_TIME);
2723
2724         ipmi_timer.expires += IPMI_TIMEOUT_JIFFIES;
2725         add_timer(&ipmi_timer);
2726 }
2727
2728
2729 static atomic_t smi_msg_inuse_count = ATOMIC_INIT(0);
2730 static atomic_t recv_msg_inuse_count = ATOMIC_INIT(0);
2731
2732 /* FIXME - convert these to slabs. */
2733 static void free_smi_msg(struct ipmi_smi_msg *msg)
2734 {
2735         atomic_dec(&smi_msg_inuse_count);
2736         kfree(msg);
2737 }
2738
2739 struct ipmi_smi_msg *ipmi_alloc_smi_msg(void)
2740 {
2741         struct ipmi_smi_msg *rv;
2742         rv = kmalloc(sizeof(struct ipmi_smi_msg), GFP_ATOMIC);
2743         if (rv) {
2744                 rv->done = free_smi_msg;
2745                 rv->user_data = NULL;
2746                 atomic_inc(&smi_msg_inuse_count);
2747         }
2748         return rv;
2749 }
2750
2751 static void free_recv_msg(struct ipmi_recv_msg *msg)
2752 {
2753         atomic_dec(&recv_msg_inuse_count);
2754         kfree(msg);
2755 }
2756
2757 struct ipmi_recv_msg *ipmi_alloc_recv_msg(void)
2758 {
2759         struct ipmi_recv_msg *rv;
2760
2761         rv = kmalloc(sizeof(struct ipmi_recv_msg), GFP_ATOMIC);
2762         if (rv) {
2763                 rv->done = free_recv_msg;
2764                 atomic_inc(&recv_msg_inuse_count);
2765         }
2766         return rv;
2767 }
2768
2769 #ifdef CONFIG_IPMI_PANIC_EVENT
2770
2771 static void dummy_smi_done_handler(struct ipmi_smi_msg *msg)
2772 {
2773 }
2774
2775 static void dummy_recv_done_handler(struct ipmi_recv_msg *msg)
2776 {
2777 }
2778
2779 #ifdef CONFIG_IPMI_PANIC_STRING
2780 static void event_receiver_fetcher(ipmi_smi_t intf, struct ipmi_smi_msg *msg)
2781 {
2782         if ((msg->rsp[0] == (IPMI_NETFN_SENSOR_EVENT_RESPONSE << 2))
2783             && (msg->rsp[1] == IPMI_GET_EVENT_RECEIVER_CMD)
2784             && (msg->rsp[2] == IPMI_CC_NO_ERROR))
2785         {
2786                 /* A get event receiver command, save it. */
2787                 intf->event_receiver = msg->rsp[3];
2788                 intf->event_receiver_lun = msg->rsp[4] & 0x3;
2789         }
2790 }
2791
2792 static void device_id_fetcher(ipmi_smi_t intf, struct ipmi_smi_msg *msg)
2793 {
2794         if ((msg->rsp[0] == (IPMI_NETFN_APP_RESPONSE << 2))
2795             && (msg->rsp[1] == IPMI_GET_DEVICE_ID_CMD)
2796             && (msg->rsp[2] == IPMI_CC_NO_ERROR))
2797         {
2798                 /* A get device id command, save if we are an event
2799                    receiver or generator. */
2800                 intf->local_sel_device = (msg->rsp[8] >> 2) & 1;
2801                 intf->local_event_generator = (msg->rsp[8] >> 5) & 1;
2802         }
2803 }
2804 #endif
2805
2806 static void send_panic_events(char *str)
2807 {
2808         struct ipmi_msg                   msg;
2809         ipmi_smi_t                        intf;
2810         unsigned char                     data[16];
2811         int                               i;
2812         struct ipmi_system_interface_addr *si;
2813         struct ipmi_addr                  addr;
2814         struct ipmi_smi_msg               smi_msg;
2815         struct ipmi_recv_msg              recv_msg;
2816
2817         si = (struct ipmi_system_interface_addr *) &addr;
2818         si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
2819         si->channel = IPMI_BMC_CHANNEL;
2820         si->lun = 0;
2821
2822         /* Fill in an event telling that we have failed. */
2823         msg.netfn = 0x04; /* Sensor or Event. */
2824         msg.cmd = 2; /* Platform event command. */
2825         msg.data = data;
2826         msg.data_len = 8;
2827         data[0] = 0x21; /* Kernel generator ID, IPMI table 5-4 */
2828         data[1] = 0x03; /* This is for IPMI 1.0. */
2829         data[2] = 0x20; /* OS Critical Stop, IPMI table 36-3 */
2830         data[4] = 0x6f; /* Sensor specific, IPMI table 36-1 */
2831         data[5] = 0xa1; /* Runtime stop OEM bytes 2 & 3. */
2832
2833         /* Put a few breadcrumbs in.  Hopefully later we can add more things
2834            to make the panic events more useful. */
2835         if (str) {
2836                 data[3] = str[0];
2837                 data[6] = str[1];
2838                 data[7] = str[2];
2839         }
2840
2841         smi_msg.done = dummy_smi_done_handler;
2842         recv_msg.done = dummy_recv_done_handler;
2843
2844         /* For every registered interface, send the event. */
2845         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
2846                 intf = ipmi_interfaces[i];
2847                 if (intf == NULL)
2848                         continue;
2849
2850                 /* Send the event announcing the panic. */
2851                 intf->handlers->set_run_to_completion(intf->send_info, 1);
2852                 i_ipmi_request(NULL,
2853                                intf,
2854                                &addr,
2855                                0,
2856                                &msg,
2857                                NULL,
2858                                &smi_msg,
2859                                &recv_msg,
2860                                0,
2861                                intf->my_address,
2862                                intf->my_lun,
2863                                0, 1); /* Don't retry, and don't wait. */
2864         }
2865
2866 #ifdef CONFIG_IPMI_PANIC_STRING
2867         /* On every interface, dump a bunch of OEM event holding the
2868            string. */
2869         if (!str) 
2870                 return;
2871
2872         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
2873                 char                  *p = str;
2874                 struct ipmi_ipmb_addr *ipmb;
2875                 int                   j;
2876
2877                 intf = ipmi_interfaces[i];
2878                 if (intf == NULL)
2879                         continue;
2880
2881                 /* First job here is to figure out where to send the
2882                    OEM events.  There's no way in IPMI to send OEM
2883                    events using an event send command, so we have to
2884                    find the SEL to put them in and stick them in
2885                    there. */
2886
2887                 /* Get capabilities from the get device id. */
2888                 intf->local_sel_device = 0;
2889                 intf->local_event_generator = 0;
2890                 intf->event_receiver = 0;
2891
2892                 /* Request the device info from the local MC. */
2893                 msg.netfn = IPMI_NETFN_APP_REQUEST;
2894                 msg.cmd = IPMI_GET_DEVICE_ID_CMD;
2895                 msg.data = NULL;
2896                 msg.data_len = 0;
2897                 intf->null_user_handler = device_id_fetcher;
2898                 i_ipmi_request(NULL,
2899                                intf,
2900                                &addr,
2901                                0,
2902                                &msg,
2903                                NULL,
2904                                &smi_msg,
2905                                &recv_msg,
2906                                0,
2907                                intf->my_address,
2908                                intf->my_lun,
2909                                0, 1); /* Don't retry, and don't wait. */
2910
2911                 if (intf->local_event_generator) {
2912                         /* Request the event receiver from the local MC. */
2913                         msg.netfn = IPMI_NETFN_SENSOR_EVENT_REQUEST;
2914                         msg.cmd = IPMI_GET_EVENT_RECEIVER_CMD;
2915                         msg.data = NULL;
2916                         msg.data_len = 0;
2917                         intf->null_user_handler = event_receiver_fetcher;
2918                         i_ipmi_request(NULL,
2919                                        intf,
2920                                        &addr,
2921                                        0,
2922                                        &msg,
2923                                        NULL,
2924                                        &smi_msg,
2925                                        &recv_msg,
2926                                        0,
2927                                        intf->my_address,
2928                                        intf->my_lun,
2929                                        0, 1); /* no retry, and no wait. */
2930                 }
2931                 intf->null_user_handler = NULL;
2932
2933                 /* Validate the event receiver.  The low bit must not
2934                    be 1 (it must be a valid IPMB address), it cannot
2935                    be zero, and it must not be my address. */
2936                 if (((intf->event_receiver & 1) == 0)
2937                     && (intf->event_receiver != 0)
2938                     && (intf->event_receiver != intf->my_address))
2939                 {
2940                         /* The event receiver is valid, send an IPMB
2941                            message. */
2942                         ipmb = (struct ipmi_ipmb_addr *) &addr;
2943                         ipmb->addr_type = IPMI_IPMB_ADDR_TYPE;
2944                         ipmb->channel = 0; /* FIXME - is this right? */
2945                         ipmb->lun = intf->event_receiver_lun;
2946                         ipmb->slave_addr = intf->event_receiver;
2947                 } else if (intf->local_sel_device) {
2948                         /* The event receiver was not valid (or was
2949                            me), but I am an SEL device, just dump it
2950                            in my SEL. */
2951                         si = (struct ipmi_system_interface_addr *) &addr;
2952                         si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
2953                         si->channel = IPMI_BMC_CHANNEL;
2954                         si->lun = 0;
2955                 } else
2956                         continue; /* No where to send the event. */
2957
2958                 
2959                 msg.netfn = IPMI_NETFN_STORAGE_REQUEST; /* Storage. */
2960                 msg.cmd = IPMI_ADD_SEL_ENTRY_CMD;
2961                 msg.data = data;
2962                 msg.data_len = 16;
2963
2964                 j = 0;
2965                 while (*p) {
2966                         int size = strlen(p);
2967
2968                         if (size > 11)
2969                                 size = 11;
2970                         data[0] = 0;
2971                         data[1] = 0;
2972                         data[2] = 0xf0; /* OEM event without timestamp. */
2973                         data[3] = intf->my_address;
2974                         data[4] = j++; /* sequence # */
2975                         /* Always give 11 bytes, so strncpy will fill
2976                            it with zeroes for me. */
2977                         strncpy(data+5, p, 11);
2978                         p += size;
2979
2980                         i_ipmi_request(NULL,
2981                                        intf,
2982                                        &addr,
2983                                        0,
2984                                        &msg,
2985                                        NULL,
2986                                        &smi_msg,
2987                                        &recv_msg,
2988                                        0,
2989                                        intf->my_address,
2990                                        intf->my_lun,
2991                                        0, 1); /* no retry, and no wait. */
2992                 }
2993         }       
2994 #endif /* CONFIG_IPMI_PANIC_STRING */
2995 }
2996 #endif /* CONFIG_IPMI_PANIC_EVENT */
2997
2998 static int has_paniced = 0;
2999
3000 static int panic_event(struct notifier_block *this,
3001                        unsigned long         event,
3002                        void                  *ptr)
3003 {
3004         int        i;
3005         ipmi_smi_t intf;
3006
3007         if (has_paniced)
3008                 return NOTIFY_DONE;
3009         has_paniced = 1;
3010
3011         /* For every registered interface, set it to run to completion. */
3012         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
3013                 intf = ipmi_interfaces[i];
3014                 if (intf == NULL)
3015                         continue;
3016
3017                 intf->handlers->set_run_to_completion(intf->send_info, 1);
3018         }
3019
3020 #ifdef CONFIG_IPMI_PANIC_EVENT
3021         send_panic_events(ptr);
3022 #endif
3023
3024         return NOTIFY_DONE;
3025 }
3026
3027 static struct notifier_block panic_block = {
3028         panic_event,
3029         NULL,
3030         200   /* priority: INT_MAX >= x >= 0 */
3031 };
3032
3033 static __init int ipmi_init_msghandler(void)
3034 {
3035         int i;
3036
3037         if (initialized)
3038                 return 0;
3039
3040         printk(KERN_INFO "ipmi message handler version "
3041                IPMI_MSGHANDLER_VERSION "\n");
3042
3043         for (i=0; i<MAX_IPMI_INTERFACES; i++) {
3044                 ipmi_interfaces[i] = NULL;
3045         }
3046
3047         proc_ipmi_root = proc_mkdir("ipmi", 0);
3048         if (!proc_ipmi_root) {
3049             printk("Unable to create IPMI proc dir");
3050             return -ENOMEM;
3051         }
3052
3053         proc_ipmi_root->owner = THIS_MODULE;
3054
3055         init_timer(&ipmi_timer);
3056         ipmi_timer.data = 0;
3057         ipmi_timer.function = ipmi_timeout;
3058         ipmi_timer.expires = jiffies + IPMI_TIMEOUT_JIFFIES;
3059         add_timer(&ipmi_timer);
3060
3061         notifier_chain_register(&panic_notifier_list, &panic_block);
3062
3063         initialized = 1;
3064
3065         return 0;
3066 }
3067
3068 static __exit void cleanup_ipmi(void)
3069 {
3070         int count;
3071
3072         if (!initialized)
3073                 return;
3074
3075         notifier_chain_unregister(&panic_notifier_list, &panic_block);
3076
3077         /* This can't be called if any interfaces exist, so no worry about
3078            shutting down the interfaces. */
3079
3080         /* Tell the timer to stop, then wait for it to stop.  This avoids
3081            problems with race conditions removing the timer here. */
3082         stop_operation = 1;
3083         while (!timer_stopped) {
3084                 set_current_state(TASK_UNINTERRUPTIBLE);
3085                 schedule_timeout(1);
3086         }
3087
3088         remove_proc_entry(proc_ipmi_root->name, &proc_root);
3089
3090         initialized = 0;
3091
3092         /* Check for buffer leaks. */
3093         count = atomic_read(&smi_msg_inuse_count);
3094         if (count != 0)
3095                 printk("ipmi_msghandler: SMI message count %d at exit\n",
3096                        count);
3097         count = atomic_read(&recv_msg_inuse_count);
3098         if (count != 0)
3099                 printk("ipmi_msghandler: recv message count %d at exit\n",
3100                        count);
3101 }
3102 module_exit(cleanup_ipmi);
3103
3104 module_init(ipmi_init_msghandler);
3105 MODULE_LICENSE("GPL");
3106
3107 EXPORT_SYMBOL(ipmi_alloc_recv_msg);
3108 EXPORT_SYMBOL(ipmi_create_user);
3109 EXPORT_SYMBOL(ipmi_destroy_user);
3110 EXPORT_SYMBOL(ipmi_get_version);
3111 EXPORT_SYMBOL(ipmi_request);
3112 EXPORT_SYMBOL(ipmi_request_settime);
3113 EXPORT_SYMBOL(ipmi_request_supply_msgs);
3114 EXPORT_SYMBOL(ipmi_request_with_source);
3115 EXPORT_SYMBOL(ipmi_register_smi);
3116 EXPORT_SYMBOL(ipmi_unregister_smi);
3117 EXPORT_SYMBOL(ipmi_register_for_cmd);
3118 EXPORT_SYMBOL(ipmi_unregister_for_cmd);
3119 EXPORT_SYMBOL(ipmi_smi_msg_received);
3120 EXPORT_SYMBOL(ipmi_smi_watchdog_pretimeout);
3121 EXPORT_SYMBOL(ipmi_alloc_smi_msg);
3122 EXPORT_SYMBOL(ipmi_register_all_cmd_rcvr);
3123 EXPORT_SYMBOL(ipmi_unregister_all_cmd_rcvr);
3124 EXPORT_SYMBOL(ipmi_addr_length);
3125 EXPORT_SYMBOL(ipmi_validate_addr);
3126 EXPORT_SYMBOL(ipmi_set_gets_events);
3127 EXPORT_SYMBOL(ipmi_addr_equal);
3128 EXPORT_SYMBOL(ipmi_smi_watcher_register);
3129 EXPORT_SYMBOL(ipmi_smi_watcher_unregister);
3130 EXPORT_SYMBOL(ipmi_set_my_address);
3131 EXPORT_SYMBOL(ipmi_get_my_address);
3132 EXPORT_SYMBOL(ipmi_set_my_LUN);
3133 EXPORT_SYMBOL(ipmi_get_my_LUN);
3134 EXPORT_SYMBOL(ipmi_smi_add_proc_entry);