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