]> Git Repo - linux.git/blob - drivers/char/ipmi/ipmi_msghandler.c
docs: deprecated.rst: Add BUG()-family
[linux.git] / drivers / char / ipmi / ipmi_msghandler.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * ipmi_msghandler.c
4  *
5  * Incoming and outgoing message routing for an IPMI interface.
6  *
7  * Author: MontaVista Software, Inc.
8  *         Corey Minyard <[email protected]>
9  *         [email protected]
10  *
11  * Copyright 2002 MontaVista Software Inc.
12  */
13
14 #define pr_fmt(fmt) "%s" fmt, "IPMI message handler: "
15 #define dev_fmt pr_fmt
16
17 #include <linux/module.h>
18 #include <linux/errno.h>
19 #include <linux/poll.h>
20 #include <linux/sched.h>
21 #include <linux/seq_file.h>
22 #include <linux/spinlock.h>
23 #include <linux/mutex.h>
24 #include <linux/slab.h>
25 #include <linux/ipmi.h>
26 #include <linux/ipmi_smi.h>
27 #include <linux/notifier.h>
28 #include <linux/init.h>
29 #include <linux/proc_fs.h>
30 #include <linux/rcupdate.h>
31 #include <linux/interrupt.h>
32 #include <linux/moduleparam.h>
33 #include <linux/workqueue.h>
34 #include <linux/uuid.h>
35 #include <linux/nospec.h>
36
37 #define IPMI_DRIVER_VERSION "39.2"
38
39 static struct ipmi_recv_msg *ipmi_alloc_recv_msg(void);
40 static int ipmi_init_msghandler(void);
41 static void smi_recv_tasklet(unsigned long);
42 static void handle_new_recv_msgs(struct ipmi_smi *intf);
43 static void need_waiter(struct ipmi_smi *intf);
44 static int handle_one_recv_msg(struct ipmi_smi *intf,
45                                struct ipmi_smi_msg *msg);
46
47 static bool initialized;
48 static bool drvregistered;
49
50 enum ipmi_panic_event_op {
51         IPMI_SEND_PANIC_EVENT_NONE,
52         IPMI_SEND_PANIC_EVENT,
53         IPMI_SEND_PANIC_EVENT_STRING
54 };
55 #ifdef CONFIG_IPMI_PANIC_STRING
56 #define IPMI_PANIC_DEFAULT IPMI_SEND_PANIC_EVENT_STRING
57 #elif defined(CONFIG_IPMI_PANIC_EVENT)
58 #define IPMI_PANIC_DEFAULT IPMI_SEND_PANIC_EVENT
59 #else
60 #define IPMI_PANIC_DEFAULT IPMI_SEND_PANIC_EVENT_NONE
61 #endif
62 static enum ipmi_panic_event_op ipmi_send_panic_event = IPMI_PANIC_DEFAULT;
63
64 static int panic_op_write_handler(const char *val,
65                                   const struct kernel_param *kp)
66 {
67         char valcp[16];
68         char *s;
69
70         strncpy(valcp, val, 15);
71         valcp[15] = '\0';
72
73         s = strstrip(valcp);
74
75         if (strcmp(s, "none") == 0)
76                 ipmi_send_panic_event = IPMI_SEND_PANIC_EVENT_NONE;
77         else if (strcmp(s, "event") == 0)
78                 ipmi_send_panic_event = IPMI_SEND_PANIC_EVENT;
79         else if (strcmp(s, "string") == 0)
80                 ipmi_send_panic_event = IPMI_SEND_PANIC_EVENT_STRING;
81         else
82                 return -EINVAL;
83
84         return 0;
85 }
86
87 static int panic_op_read_handler(char *buffer, const struct kernel_param *kp)
88 {
89         switch (ipmi_send_panic_event) {
90         case IPMI_SEND_PANIC_EVENT_NONE:
91                 strcpy(buffer, "none");
92                 break;
93
94         case IPMI_SEND_PANIC_EVENT:
95                 strcpy(buffer, "event");
96                 break;
97
98         case IPMI_SEND_PANIC_EVENT_STRING:
99                 strcpy(buffer, "string");
100                 break;
101
102         default:
103                 strcpy(buffer, "???");
104                 break;
105         }
106
107         return strlen(buffer);
108 }
109
110 static const struct kernel_param_ops panic_op_ops = {
111         .set = panic_op_write_handler,
112         .get = panic_op_read_handler
113 };
114 module_param_cb(panic_op, &panic_op_ops, NULL, 0600);
115 MODULE_PARM_DESC(panic_op, "Sets if the IPMI driver will attempt to store panic information in the event log in the event of a panic.  Set to 'none' for no, 'event' for a single event, or 'string' for a generic event and the panic string in IPMI OEM events.");
116
117
118 #define MAX_EVENTS_IN_QUEUE     25
119
120 /* Remain in auto-maintenance mode for this amount of time (in ms). */
121 static unsigned long maintenance_mode_timeout_ms = 30000;
122 module_param(maintenance_mode_timeout_ms, ulong, 0644);
123 MODULE_PARM_DESC(maintenance_mode_timeout_ms,
124                  "The time (milliseconds) after the last maintenance message that the connection stays in maintenance mode.");
125
126 /*
127  * Don't let a message sit in a queue forever, always time it with at lest
128  * the max message timer.  This is in milliseconds.
129  */
130 #define MAX_MSG_TIMEOUT         60000
131
132 /*
133  * Timeout times below are in milliseconds, and are done off a 1
134  * second timer.  So setting the value to 1000 would mean anything
135  * between 0 and 1000ms.  So really the only reasonable minimum
136  * setting it 2000ms, which is between 1 and 2 seconds.
137  */
138
139 /* The default timeout for message retries. */
140 static unsigned long default_retry_ms = 2000;
141 module_param(default_retry_ms, ulong, 0644);
142 MODULE_PARM_DESC(default_retry_ms,
143                  "The time (milliseconds) between retry sends");
144
145 /* The default timeout for maintenance mode message retries. */
146 static unsigned long default_maintenance_retry_ms = 3000;
147 module_param(default_maintenance_retry_ms, ulong, 0644);
148 MODULE_PARM_DESC(default_maintenance_retry_ms,
149                  "The time (milliseconds) between retry sends in maintenance mode");
150
151 /* The default maximum number of retries */
152 static unsigned int default_max_retries = 4;
153 module_param(default_max_retries, uint, 0644);
154 MODULE_PARM_DESC(default_max_retries,
155                  "The time (milliseconds) between retry sends in maintenance mode");
156
157 /* Call every ~1000 ms. */
158 #define IPMI_TIMEOUT_TIME       1000
159
160 /* How many jiffies does it take to get to the timeout time. */
161 #define IPMI_TIMEOUT_JIFFIES    ((IPMI_TIMEOUT_TIME * HZ) / 1000)
162
163 /*
164  * Request events from the queue every second (this is the number of
165  * IPMI_TIMEOUT_TIMES between event requests).  Hopefully, in the
166  * future, IPMI will add a way to know immediately if an event is in
167  * the queue and this silliness can go away.
168  */
169 #define IPMI_REQUEST_EV_TIME    (1000 / (IPMI_TIMEOUT_TIME))
170
171 /* How long should we cache dynamic device IDs? */
172 #define IPMI_DYN_DEV_ID_EXPIRY  (10 * HZ)
173
174 /*
175  * The main "user" data structure.
176  */
177 struct ipmi_user {
178         struct list_head link;
179
180         /*
181          * Set to NULL when the user is destroyed, a pointer to myself
182          * so srcu_dereference can be used on it.
183          */
184         struct ipmi_user *self;
185         struct srcu_struct release_barrier;
186
187         struct kref refcount;
188
189         /* The upper layer that handles receive messages. */
190         const struct ipmi_user_hndl *handler;
191         void             *handler_data;
192
193         /* The interface this user is bound to. */
194         struct ipmi_smi *intf;
195
196         /* Does this interface receive IPMI events? */
197         bool gets_events;
198
199         /* Free must run in process context for RCU cleanup. */
200         struct work_struct remove_work;
201 };
202
203 static struct ipmi_user *acquire_ipmi_user(struct ipmi_user *user, int *index)
204         __acquires(user->release_barrier)
205 {
206         struct ipmi_user *ruser;
207
208         *index = srcu_read_lock(&user->release_barrier);
209         ruser = srcu_dereference(user->self, &user->release_barrier);
210         if (!ruser)
211                 srcu_read_unlock(&user->release_barrier, *index);
212         return ruser;
213 }
214
215 static void release_ipmi_user(struct ipmi_user *user, int index)
216 {
217         srcu_read_unlock(&user->release_barrier, index);
218 }
219
220 struct cmd_rcvr {
221         struct list_head link;
222
223         struct ipmi_user *user;
224         unsigned char netfn;
225         unsigned char cmd;
226         unsigned int  chans;
227
228         /*
229          * This is used to form a linked lised during mass deletion.
230          * Since this is in an RCU list, we cannot use the link above
231          * or change any data until the RCU period completes.  So we
232          * use this next variable during mass deletion so we can have
233          * a list and don't have to wait and restart the search on
234          * every individual deletion of a command.
235          */
236         struct cmd_rcvr *next;
237 };
238
239 struct seq_table {
240         unsigned int         inuse : 1;
241         unsigned int         broadcast : 1;
242
243         unsigned long        timeout;
244         unsigned long        orig_timeout;
245         unsigned int         retries_left;
246
247         /*
248          * To verify on an incoming send message response that this is
249          * the message that the response is for, we keep a sequence id
250          * and increment it every time we send a message.
251          */
252         long                 seqid;
253
254         /*
255          * This is held so we can properly respond to the message on a
256          * timeout, and it is used to hold the temporary data for
257          * retransmission, too.
258          */
259         struct ipmi_recv_msg *recv_msg;
260 };
261
262 /*
263  * Store the information in a msgid (long) to allow us to find a
264  * sequence table entry from the msgid.
265  */
266 #define STORE_SEQ_IN_MSGID(seq, seqid) \
267         ((((seq) & 0x3f) << 26) | ((seqid) & 0x3ffffff))
268
269 #define GET_SEQ_FROM_MSGID(msgid, seq, seqid) \
270         do {                                                            \
271                 seq = (((msgid) >> 26) & 0x3f);                         \
272                 seqid = ((msgid) & 0x3ffffff);                          \
273         } while (0)
274
275 #define NEXT_SEQID(seqid) (((seqid) + 1) & 0x3ffffff)
276
277 #define IPMI_MAX_CHANNELS       16
278 struct ipmi_channel {
279         unsigned char medium;
280         unsigned char protocol;
281 };
282
283 struct ipmi_channel_set {
284         struct ipmi_channel c[IPMI_MAX_CHANNELS];
285 };
286
287 struct ipmi_my_addrinfo {
288         /*
289          * My slave address.  This is initialized to IPMI_BMC_SLAVE_ADDR,
290          * but may be changed by the user.
291          */
292         unsigned char address;
293
294         /*
295          * My LUN.  This should generally stay the SMS LUN, but just in
296          * case...
297          */
298         unsigned char lun;
299 };
300
301 /*
302  * Note that the product id, manufacturer id, guid, and device id are
303  * immutable in this structure, so dyn_mutex is not required for
304  * accessing those.  If those change on a BMC, a new BMC is allocated.
305  */
306 struct bmc_device {
307         struct platform_device pdev;
308         struct list_head       intfs; /* Interfaces on this BMC. */
309         struct ipmi_device_id  id;
310         struct ipmi_device_id  fetch_id;
311         int                    dyn_id_set;
312         unsigned long          dyn_id_expiry;
313         struct mutex           dyn_mutex; /* Protects id, intfs, & dyn* */
314         guid_t                 guid;
315         guid_t                 fetch_guid;
316         int                    dyn_guid_set;
317         struct kref            usecount;
318         struct work_struct     remove_work;
319 };
320 #define to_bmc_device(x) container_of((x), struct bmc_device, pdev.dev)
321
322 static int bmc_get_device_id(struct ipmi_smi *intf, struct bmc_device *bmc,
323                              struct ipmi_device_id *id,
324                              bool *guid_set, guid_t *guid);
325
326 /*
327  * Various statistics for IPMI, these index stats[] in the ipmi_smi
328  * structure.
329  */
330 enum ipmi_stat_indexes {
331         /* Commands we got from the user that were invalid. */
332         IPMI_STAT_sent_invalid_commands = 0,
333
334         /* Commands we sent to the MC. */
335         IPMI_STAT_sent_local_commands,
336
337         /* Responses from the MC that were delivered to a user. */
338         IPMI_STAT_handled_local_responses,
339
340         /* Responses from the MC that were not delivered to a user. */
341         IPMI_STAT_unhandled_local_responses,
342
343         /* Commands we sent out to the IPMB bus. */
344         IPMI_STAT_sent_ipmb_commands,
345
346         /* Commands sent on the IPMB that had errors on the SEND CMD */
347         IPMI_STAT_sent_ipmb_command_errs,
348
349         /* Each retransmit increments this count. */
350         IPMI_STAT_retransmitted_ipmb_commands,
351
352         /*
353          * When a message times out (runs out of retransmits) this is
354          * incremented.
355          */
356         IPMI_STAT_timed_out_ipmb_commands,
357
358         /*
359          * This is like above, but for broadcasts.  Broadcasts are
360          * *not* included in the above count (they are expected to
361          * time out).
362          */
363         IPMI_STAT_timed_out_ipmb_broadcasts,
364
365         /* Responses I have sent to the IPMB bus. */
366         IPMI_STAT_sent_ipmb_responses,
367
368         /* The response was delivered to the user. */
369         IPMI_STAT_handled_ipmb_responses,
370
371         /* The response had invalid data in it. */
372         IPMI_STAT_invalid_ipmb_responses,
373
374         /* The response didn't have anyone waiting for it. */
375         IPMI_STAT_unhandled_ipmb_responses,
376
377         /* Commands we sent out to the IPMB bus. */
378         IPMI_STAT_sent_lan_commands,
379
380         /* Commands sent on the IPMB that had errors on the SEND CMD */
381         IPMI_STAT_sent_lan_command_errs,
382
383         /* Each retransmit increments this count. */
384         IPMI_STAT_retransmitted_lan_commands,
385
386         /*
387          * When a message times out (runs out of retransmits) this is
388          * incremented.
389          */
390         IPMI_STAT_timed_out_lan_commands,
391
392         /* Responses I have sent to the IPMB bus. */
393         IPMI_STAT_sent_lan_responses,
394
395         /* The response was delivered to the user. */
396         IPMI_STAT_handled_lan_responses,
397
398         /* The response had invalid data in it. */
399         IPMI_STAT_invalid_lan_responses,
400
401         /* The response didn't have anyone waiting for it. */
402         IPMI_STAT_unhandled_lan_responses,
403
404         /* The command was delivered to the user. */
405         IPMI_STAT_handled_commands,
406
407         /* The command had invalid data in it. */
408         IPMI_STAT_invalid_commands,
409
410         /* The command didn't have anyone waiting for it. */
411         IPMI_STAT_unhandled_commands,
412
413         /* Invalid data in an event. */
414         IPMI_STAT_invalid_events,
415
416         /* Events that were received with the proper format. */
417         IPMI_STAT_events,
418
419         /* Retransmissions on IPMB that failed. */
420         IPMI_STAT_dropped_rexmit_ipmb_commands,
421
422         /* Retransmissions on LAN that failed. */
423         IPMI_STAT_dropped_rexmit_lan_commands,
424
425         /* This *must* remain last, add new values above this. */
426         IPMI_NUM_STATS
427 };
428
429
430 #define IPMI_IPMB_NUM_SEQ       64
431 struct ipmi_smi {
432         struct module *owner;
433
434         /* What interface number are we? */
435         int intf_num;
436
437         struct kref refcount;
438
439         /* Set when the interface is being unregistered. */
440         bool in_shutdown;
441
442         /* Used for a list of interfaces. */
443         struct list_head link;
444
445         /*
446          * The list of upper layers that are using me.  seq_lock write
447          * protects this.  Read protection is with srcu.
448          */
449         struct list_head users;
450         struct srcu_struct users_srcu;
451
452         /* Used for wake ups at startup. */
453         wait_queue_head_t waitq;
454
455         /*
456          * Prevents the interface from being unregistered when the
457          * interface is used by being looked up through the BMC
458          * structure.
459          */
460         struct mutex bmc_reg_mutex;
461
462         struct bmc_device tmp_bmc;
463         struct bmc_device *bmc;
464         bool bmc_registered;
465         struct list_head bmc_link;
466         char *my_dev_name;
467         bool in_bmc_register;  /* Handle recursive situations.  Yuck. */
468         struct work_struct bmc_reg_work;
469
470         const struct ipmi_smi_handlers *handlers;
471         void                     *send_info;
472
473         /* Driver-model device for the system interface. */
474         struct device          *si_dev;
475
476         /*
477          * A table of sequence numbers for this interface.  We use the
478          * sequence numbers for IPMB messages that go out of the
479          * interface to match them up with their responses.  A routine
480          * is called periodically to time the items in this list.
481          */
482         spinlock_t       seq_lock;
483         struct seq_table seq_table[IPMI_IPMB_NUM_SEQ];
484         int curr_seq;
485
486         /*
487          * Messages queued for delivery.  If delivery fails (out of memory
488          * for instance), They will stay in here to be processed later in a
489          * periodic timer interrupt.  The tasklet is for handling received
490          * messages directly from the handler.
491          */
492         spinlock_t       waiting_rcv_msgs_lock;
493         struct list_head waiting_rcv_msgs;
494         atomic_t         watchdog_pretimeouts_to_deliver;
495         struct tasklet_struct recv_tasklet;
496
497         spinlock_t             xmit_msgs_lock;
498         struct list_head       xmit_msgs;
499         struct ipmi_smi_msg    *curr_msg;
500         struct list_head       hp_xmit_msgs;
501
502         /*
503          * The list of command receivers that are registered for commands
504          * on this interface.
505          */
506         struct mutex     cmd_rcvrs_mutex;
507         struct list_head cmd_rcvrs;
508
509         /*
510          * Events that were queues because no one was there to receive
511          * them.
512          */
513         spinlock_t       events_lock; /* For dealing with event stuff. */
514         struct list_head waiting_events;
515         unsigned int     waiting_events_count; /* How many events in queue? */
516         char             delivering_events;
517         char             event_msg_printed;
518
519         /* How many users are waiting for events? */
520         atomic_t         event_waiters;
521         unsigned int     ticks_to_req_ev;
522
523         spinlock_t       watch_lock; /* For dealing with watch stuff below. */
524
525         /* How many users are waiting for commands? */
526         unsigned int     command_waiters;
527
528         /* How many users are waiting for watchdogs? */
529         unsigned int     watchdog_waiters;
530
531         /* How many users are waiting for message responses? */
532         unsigned int     response_waiters;
533
534         /*
535          * Tells what the lower layer has last been asked to watch for,
536          * messages and/or watchdogs.  Protected by watch_lock.
537          */
538         unsigned int     last_watch_mask;
539
540         /*
541          * The event receiver for my BMC, only really used at panic
542          * shutdown as a place to store this.
543          */
544         unsigned char event_receiver;
545         unsigned char event_receiver_lun;
546         unsigned char local_sel_device;
547         unsigned char local_event_generator;
548
549         /* For handling of maintenance mode. */
550         int maintenance_mode;
551         bool maintenance_mode_enable;
552         int auto_maintenance_timeout;
553         spinlock_t maintenance_mode_lock; /* Used in a timer... */
554
555         /*
556          * If we are doing maintenance on something on IPMB, extend
557          * the timeout time to avoid timeouts writing firmware and
558          * such.
559          */
560         int ipmb_maintenance_mode_timeout;
561
562         /*
563          * A cheap hack, if this is non-null and a message to an
564          * interface comes in with a NULL user, call this routine with
565          * it.  Note that the message will still be freed by the
566          * caller.  This only works on the system interface.
567          *
568          * Protected by bmc_reg_mutex.
569          */
570         void (*null_user_handler)(struct ipmi_smi *intf,
571                                   struct ipmi_recv_msg *msg);
572
573         /*
574          * When we are scanning the channels for an SMI, this will
575          * tell which channel we are scanning.
576          */
577         int curr_channel;
578
579         /* Channel information */
580         struct ipmi_channel_set *channel_list;
581         unsigned int curr_working_cset; /* First index into the following. */
582         struct ipmi_channel_set wchannels[2];
583         struct ipmi_my_addrinfo addrinfo[IPMI_MAX_CHANNELS];
584         bool channels_ready;
585
586         atomic_t stats[IPMI_NUM_STATS];
587
588         /*
589          * run_to_completion duplicate of smb_info, smi_info
590          * and ipmi_serial_info structures. Used to decrease numbers of
591          * parameters passed by "low" level IPMI code.
592          */
593         int run_to_completion;
594 };
595 #define to_si_intf_from_dev(device) container_of(device, struct ipmi_smi, dev)
596
597 static void __get_guid(struct ipmi_smi *intf);
598 static void __ipmi_bmc_unregister(struct ipmi_smi *intf);
599 static int __ipmi_bmc_register(struct ipmi_smi *intf,
600                                struct ipmi_device_id *id,
601                                bool guid_set, guid_t *guid, int intf_num);
602 static int __scan_channels(struct ipmi_smi *intf, struct ipmi_device_id *id);
603
604
605 /**
606  * The driver model view of the IPMI messaging driver.
607  */
608 static struct platform_driver ipmidriver = {
609         .driver = {
610                 .name = "ipmi",
611                 .bus = &platform_bus_type
612         }
613 };
614 /*
615  * This mutex keeps us from adding the same BMC twice.
616  */
617 static DEFINE_MUTEX(ipmidriver_mutex);
618
619 static LIST_HEAD(ipmi_interfaces);
620 static DEFINE_MUTEX(ipmi_interfaces_mutex);
621 static struct srcu_struct ipmi_interfaces_srcu;
622
623 /*
624  * List of watchers that want to know when smi's are added and deleted.
625  */
626 static LIST_HEAD(smi_watchers);
627 static DEFINE_MUTEX(smi_watchers_mutex);
628
629 #define ipmi_inc_stat(intf, stat) \
630         atomic_inc(&(intf)->stats[IPMI_STAT_ ## stat])
631 #define ipmi_get_stat(intf, stat) \
632         ((unsigned int) atomic_read(&(intf)->stats[IPMI_STAT_ ## stat]))
633
634 static const char * const addr_src_to_str[] = {
635         "invalid", "hotmod", "hardcoded", "SPMI", "ACPI", "SMBIOS", "PCI",
636         "device-tree", "platform"
637 };
638
639 const char *ipmi_addr_src_to_str(enum ipmi_addr_src src)
640 {
641         if (src >= SI_LAST)
642                 src = 0; /* Invalid */
643         return addr_src_to_str[src];
644 }
645 EXPORT_SYMBOL(ipmi_addr_src_to_str);
646
647 static int is_lan_addr(struct ipmi_addr *addr)
648 {
649         return addr->addr_type == IPMI_LAN_ADDR_TYPE;
650 }
651
652 static int is_ipmb_addr(struct ipmi_addr *addr)
653 {
654         return addr->addr_type == IPMI_IPMB_ADDR_TYPE;
655 }
656
657 static int is_ipmb_bcast_addr(struct ipmi_addr *addr)
658 {
659         return addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE;
660 }
661
662 static void free_recv_msg_list(struct list_head *q)
663 {
664         struct ipmi_recv_msg *msg, *msg2;
665
666         list_for_each_entry_safe(msg, msg2, q, link) {
667                 list_del(&msg->link);
668                 ipmi_free_recv_msg(msg);
669         }
670 }
671
672 static void free_smi_msg_list(struct list_head *q)
673 {
674         struct ipmi_smi_msg *msg, *msg2;
675
676         list_for_each_entry_safe(msg, msg2, q, link) {
677                 list_del(&msg->link);
678                 ipmi_free_smi_msg(msg);
679         }
680 }
681
682 static void clean_up_interface_data(struct ipmi_smi *intf)
683 {
684         int              i;
685         struct cmd_rcvr  *rcvr, *rcvr2;
686         struct list_head list;
687
688         tasklet_kill(&intf->recv_tasklet);
689
690         free_smi_msg_list(&intf->waiting_rcv_msgs);
691         free_recv_msg_list(&intf->waiting_events);
692
693         /*
694          * Wholesale remove all the entries from the list in the
695          * interface and wait for RCU to know that none are in use.
696          */
697         mutex_lock(&intf->cmd_rcvrs_mutex);
698         INIT_LIST_HEAD(&list);
699         list_splice_init_rcu(&intf->cmd_rcvrs, &list, synchronize_rcu);
700         mutex_unlock(&intf->cmd_rcvrs_mutex);
701
702         list_for_each_entry_safe(rcvr, rcvr2, &list, link)
703                 kfree(rcvr);
704
705         for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
706                 if ((intf->seq_table[i].inuse)
707                                         && (intf->seq_table[i].recv_msg))
708                         ipmi_free_recv_msg(intf->seq_table[i].recv_msg);
709         }
710 }
711
712 static void intf_free(struct kref *ref)
713 {
714         struct ipmi_smi *intf = container_of(ref, struct ipmi_smi, refcount);
715
716         clean_up_interface_data(intf);
717         kfree(intf);
718 }
719
720 struct watcher_entry {
721         int              intf_num;
722         struct ipmi_smi  *intf;
723         struct list_head link;
724 };
725
726 int ipmi_smi_watcher_register(struct ipmi_smi_watcher *watcher)
727 {
728         struct ipmi_smi *intf;
729         int index, rv;
730
731         /*
732          * Make sure the driver is actually initialized, this handles
733          * problems with initialization order.
734          */
735         rv = ipmi_init_msghandler();
736         if (rv)
737                 return rv;
738
739         mutex_lock(&smi_watchers_mutex);
740
741         list_add(&watcher->link, &smi_watchers);
742
743         index = srcu_read_lock(&ipmi_interfaces_srcu);
744         list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
745                 int intf_num = READ_ONCE(intf->intf_num);
746
747                 if (intf_num == -1)
748                         continue;
749                 watcher->new_smi(intf_num, intf->si_dev);
750         }
751         srcu_read_unlock(&ipmi_interfaces_srcu, index);
752
753         mutex_unlock(&smi_watchers_mutex);
754
755         return 0;
756 }
757 EXPORT_SYMBOL(ipmi_smi_watcher_register);
758
759 int ipmi_smi_watcher_unregister(struct ipmi_smi_watcher *watcher)
760 {
761         mutex_lock(&smi_watchers_mutex);
762         list_del(&watcher->link);
763         mutex_unlock(&smi_watchers_mutex);
764         return 0;
765 }
766 EXPORT_SYMBOL(ipmi_smi_watcher_unregister);
767
768 /*
769  * Must be called with smi_watchers_mutex held.
770  */
771 static void
772 call_smi_watchers(int i, struct device *dev)
773 {
774         struct ipmi_smi_watcher *w;
775
776         mutex_lock(&smi_watchers_mutex);
777         list_for_each_entry(w, &smi_watchers, link) {
778                 if (try_module_get(w->owner)) {
779                         w->new_smi(i, dev);
780                         module_put(w->owner);
781                 }
782         }
783         mutex_unlock(&smi_watchers_mutex);
784 }
785
786 static int
787 ipmi_addr_equal(struct ipmi_addr *addr1, struct ipmi_addr *addr2)
788 {
789         if (addr1->addr_type != addr2->addr_type)
790                 return 0;
791
792         if (addr1->channel != addr2->channel)
793                 return 0;
794
795         if (addr1->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
796                 struct ipmi_system_interface_addr *smi_addr1
797                     = (struct ipmi_system_interface_addr *) addr1;
798                 struct ipmi_system_interface_addr *smi_addr2
799                     = (struct ipmi_system_interface_addr *) addr2;
800                 return (smi_addr1->lun == smi_addr2->lun);
801         }
802
803         if (is_ipmb_addr(addr1) || is_ipmb_bcast_addr(addr1)) {
804                 struct ipmi_ipmb_addr *ipmb_addr1
805                     = (struct ipmi_ipmb_addr *) addr1;
806                 struct ipmi_ipmb_addr *ipmb_addr2
807                     = (struct ipmi_ipmb_addr *) addr2;
808
809                 return ((ipmb_addr1->slave_addr == ipmb_addr2->slave_addr)
810                         && (ipmb_addr1->lun == ipmb_addr2->lun));
811         }
812
813         if (is_lan_addr(addr1)) {
814                 struct ipmi_lan_addr *lan_addr1
815                         = (struct ipmi_lan_addr *) addr1;
816                 struct ipmi_lan_addr *lan_addr2
817                     = (struct ipmi_lan_addr *) addr2;
818
819                 return ((lan_addr1->remote_SWID == lan_addr2->remote_SWID)
820                         && (lan_addr1->local_SWID == lan_addr2->local_SWID)
821                         && (lan_addr1->session_handle
822                             == lan_addr2->session_handle)
823                         && (lan_addr1->lun == lan_addr2->lun));
824         }
825
826         return 1;
827 }
828
829 int ipmi_validate_addr(struct ipmi_addr *addr, int len)
830 {
831         if (len < sizeof(struct ipmi_system_interface_addr))
832                 return -EINVAL;
833
834         if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
835                 if (addr->channel != IPMI_BMC_CHANNEL)
836                         return -EINVAL;
837                 return 0;
838         }
839
840         if ((addr->channel == IPMI_BMC_CHANNEL)
841             || (addr->channel >= IPMI_MAX_CHANNELS)
842             || (addr->channel < 0))
843                 return -EINVAL;
844
845         if (is_ipmb_addr(addr) || is_ipmb_bcast_addr(addr)) {
846                 if (len < sizeof(struct ipmi_ipmb_addr))
847                         return -EINVAL;
848                 return 0;
849         }
850
851         if (is_lan_addr(addr)) {
852                 if (len < sizeof(struct ipmi_lan_addr))
853                         return -EINVAL;
854                 return 0;
855         }
856
857         return -EINVAL;
858 }
859 EXPORT_SYMBOL(ipmi_validate_addr);
860
861 unsigned int ipmi_addr_length(int addr_type)
862 {
863         if (addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
864                 return sizeof(struct ipmi_system_interface_addr);
865
866         if ((addr_type == IPMI_IPMB_ADDR_TYPE)
867                         || (addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE))
868                 return sizeof(struct ipmi_ipmb_addr);
869
870         if (addr_type == IPMI_LAN_ADDR_TYPE)
871                 return sizeof(struct ipmi_lan_addr);
872
873         return 0;
874 }
875 EXPORT_SYMBOL(ipmi_addr_length);
876
877 static int deliver_response(struct ipmi_smi *intf, struct ipmi_recv_msg *msg)
878 {
879         int rv = 0;
880
881         if (!msg->user) {
882                 /* Special handling for NULL users. */
883                 if (intf->null_user_handler) {
884                         intf->null_user_handler(intf, msg);
885                 } else {
886                         /* No handler, so give up. */
887                         rv = -EINVAL;
888                 }
889                 ipmi_free_recv_msg(msg);
890         } else if (oops_in_progress) {
891                 /*
892                  * If we are running in the panic context, calling the
893                  * receive handler doesn't much meaning and has a deadlock
894                  * risk.  At this moment, simply skip it in that case.
895                  */
896                 ipmi_free_recv_msg(msg);
897         } else {
898                 int index;
899                 struct ipmi_user *user = acquire_ipmi_user(msg->user, &index);
900
901                 if (user) {
902                         user->handler->ipmi_recv_hndl(msg, user->handler_data);
903                         release_ipmi_user(user, index);
904                 } else {
905                         /* User went away, give up. */
906                         ipmi_free_recv_msg(msg);
907                         rv = -EINVAL;
908                 }
909         }
910
911         return rv;
912 }
913
914 static void deliver_local_response(struct ipmi_smi *intf,
915                                    struct ipmi_recv_msg *msg)
916 {
917         if (deliver_response(intf, msg))
918                 ipmi_inc_stat(intf, unhandled_local_responses);
919         else
920                 ipmi_inc_stat(intf, handled_local_responses);
921 }
922
923 static void deliver_err_response(struct ipmi_smi *intf,
924                                  struct ipmi_recv_msg *msg, int err)
925 {
926         msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
927         msg->msg_data[0] = err;
928         msg->msg.netfn |= 1; /* Convert to a response. */
929         msg->msg.data_len = 1;
930         msg->msg.data = msg->msg_data;
931         deliver_local_response(intf, msg);
932 }
933
934 static void smi_add_watch(struct ipmi_smi *intf, unsigned int flags)
935 {
936         unsigned long iflags;
937
938         if (!intf->handlers->set_need_watch)
939                 return;
940
941         spin_lock_irqsave(&intf->watch_lock, iflags);
942         if (flags & IPMI_WATCH_MASK_CHECK_MESSAGES)
943                 intf->response_waiters++;
944
945         if (flags & IPMI_WATCH_MASK_CHECK_WATCHDOG)
946                 intf->watchdog_waiters++;
947
948         if (flags & IPMI_WATCH_MASK_CHECK_COMMANDS)
949                 intf->command_waiters++;
950
951         if ((intf->last_watch_mask & flags) != flags) {
952                 intf->last_watch_mask |= flags;
953                 intf->handlers->set_need_watch(intf->send_info,
954                                                intf->last_watch_mask);
955         }
956         spin_unlock_irqrestore(&intf->watch_lock, iflags);
957 }
958
959 static void smi_remove_watch(struct ipmi_smi *intf, unsigned int flags)
960 {
961         unsigned long iflags;
962
963         if (!intf->handlers->set_need_watch)
964                 return;
965
966         spin_lock_irqsave(&intf->watch_lock, iflags);
967         if (flags & IPMI_WATCH_MASK_CHECK_MESSAGES)
968                 intf->response_waiters--;
969
970         if (flags & IPMI_WATCH_MASK_CHECK_WATCHDOG)
971                 intf->watchdog_waiters--;
972
973         if (flags & IPMI_WATCH_MASK_CHECK_COMMANDS)
974                 intf->command_waiters--;
975
976         flags = 0;
977         if (intf->response_waiters)
978                 flags |= IPMI_WATCH_MASK_CHECK_MESSAGES;
979         if (intf->watchdog_waiters)
980                 flags |= IPMI_WATCH_MASK_CHECK_WATCHDOG;
981         if (intf->command_waiters)
982                 flags |= IPMI_WATCH_MASK_CHECK_COMMANDS;
983
984         if (intf->last_watch_mask != flags) {
985                 intf->last_watch_mask = flags;
986                 intf->handlers->set_need_watch(intf->send_info,
987                                                intf->last_watch_mask);
988         }
989         spin_unlock_irqrestore(&intf->watch_lock, iflags);
990 }
991
992 /*
993  * Find the next sequence number not being used and add the given
994  * message with the given timeout to the sequence table.  This must be
995  * called with the interface's seq_lock held.
996  */
997 static int intf_next_seq(struct ipmi_smi      *intf,
998                          struct ipmi_recv_msg *recv_msg,
999                          unsigned long        timeout,
1000                          int                  retries,
1001                          int                  broadcast,
1002                          unsigned char        *seq,
1003                          long                 *seqid)
1004 {
1005         int          rv = 0;
1006         unsigned int i;
1007
1008         if (timeout == 0)
1009                 timeout = default_retry_ms;
1010         if (retries < 0)
1011                 retries = default_max_retries;
1012
1013         for (i = intf->curr_seq; (i+1)%IPMI_IPMB_NUM_SEQ != intf->curr_seq;
1014                                         i = (i+1)%IPMI_IPMB_NUM_SEQ) {
1015                 if (!intf->seq_table[i].inuse)
1016                         break;
1017         }
1018
1019         if (!intf->seq_table[i].inuse) {
1020                 intf->seq_table[i].recv_msg = recv_msg;
1021
1022                 /*
1023                  * Start with the maximum timeout, when the send response
1024                  * comes in we will start the real timer.
1025                  */
1026                 intf->seq_table[i].timeout = MAX_MSG_TIMEOUT;
1027                 intf->seq_table[i].orig_timeout = timeout;
1028                 intf->seq_table[i].retries_left = retries;
1029                 intf->seq_table[i].broadcast = broadcast;
1030                 intf->seq_table[i].inuse = 1;
1031                 intf->seq_table[i].seqid = NEXT_SEQID(intf->seq_table[i].seqid);
1032                 *seq = i;
1033                 *seqid = intf->seq_table[i].seqid;
1034                 intf->curr_seq = (i+1)%IPMI_IPMB_NUM_SEQ;
1035                 smi_add_watch(intf, IPMI_WATCH_MASK_CHECK_MESSAGES);
1036                 need_waiter(intf);
1037         } else {
1038                 rv = -EAGAIN;
1039         }
1040
1041         return rv;
1042 }
1043
1044 /*
1045  * Return the receive message for the given sequence number and
1046  * release the sequence number so it can be reused.  Some other data
1047  * is passed in to be sure the message matches up correctly (to help
1048  * guard against message coming in after their timeout and the
1049  * sequence number being reused).
1050  */
1051 static int intf_find_seq(struct ipmi_smi      *intf,
1052                          unsigned char        seq,
1053                          short                channel,
1054                          unsigned char        cmd,
1055                          unsigned char        netfn,
1056                          struct ipmi_addr     *addr,
1057                          struct ipmi_recv_msg **recv_msg)
1058 {
1059         int           rv = -ENODEV;
1060         unsigned long flags;
1061
1062         if (seq >= IPMI_IPMB_NUM_SEQ)
1063                 return -EINVAL;
1064
1065         spin_lock_irqsave(&intf->seq_lock, flags);
1066         if (intf->seq_table[seq].inuse) {
1067                 struct ipmi_recv_msg *msg = intf->seq_table[seq].recv_msg;
1068
1069                 if ((msg->addr.channel == channel) && (msg->msg.cmd == cmd)
1070                                 && (msg->msg.netfn == netfn)
1071                                 && (ipmi_addr_equal(addr, &msg->addr))) {
1072                         *recv_msg = msg;
1073                         intf->seq_table[seq].inuse = 0;
1074                         smi_remove_watch(intf, IPMI_WATCH_MASK_CHECK_MESSAGES);
1075                         rv = 0;
1076                 }
1077         }
1078         spin_unlock_irqrestore(&intf->seq_lock, flags);
1079
1080         return rv;
1081 }
1082
1083
1084 /* Start the timer for a specific sequence table entry. */
1085 static int intf_start_seq_timer(struct ipmi_smi *intf,
1086                                 long       msgid)
1087 {
1088         int           rv = -ENODEV;
1089         unsigned long flags;
1090         unsigned char seq;
1091         unsigned long seqid;
1092
1093
1094         GET_SEQ_FROM_MSGID(msgid, seq, seqid);
1095
1096         spin_lock_irqsave(&intf->seq_lock, flags);
1097         /*
1098          * We do this verification because the user can be deleted
1099          * while a message is outstanding.
1100          */
1101         if ((intf->seq_table[seq].inuse)
1102                                 && (intf->seq_table[seq].seqid == seqid)) {
1103                 struct seq_table *ent = &intf->seq_table[seq];
1104                 ent->timeout = ent->orig_timeout;
1105                 rv = 0;
1106         }
1107         spin_unlock_irqrestore(&intf->seq_lock, flags);
1108
1109         return rv;
1110 }
1111
1112 /* Got an error for the send message for a specific sequence number. */
1113 static int intf_err_seq(struct ipmi_smi *intf,
1114                         long         msgid,
1115                         unsigned int err)
1116 {
1117         int                  rv = -ENODEV;
1118         unsigned long        flags;
1119         unsigned char        seq;
1120         unsigned long        seqid;
1121         struct ipmi_recv_msg *msg = NULL;
1122
1123
1124         GET_SEQ_FROM_MSGID(msgid, seq, seqid);
1125
1126         spin_lock_irqsave(&intf->seq_lock, flags);
1127         /*
1128          * We do this verification because the user can be deleted
1129          * while a message is outstanding.
1130          */
1131         if ((intf->seq_table[seq].inuse)
1132                                 && (intf->seq_table[seq].seqid == seqid)) {
1133                 struct seq_table *ent = &intf->seq_table[seq];
1134
1135                 ent->inuse = 0;
1136                 smi_remove_watch(intf, IPMI_WATCH_MASK_CHECK_MESSAGES);
1137                 msg = ent->recv_msg;
1138                 rv = 0;
1139         }
1140         spin_unlock_irqrestore(&intf->seq_lock, flags);
1141
1142         if (msg)
1143                 deliver_err_response(intf, msg, err);
1144
1145         return rv;
1146 }
1147
1148 static void free_user_work(struct work_struct *work)
1149 {
1150         struct ipmi_user *user = container_of(work, struct ipmi_user,
1151                                               remove_work);
1152
1153         cleanup_srcu_struct(&user->release_barrier);
1154         kfree(user);
1155 }
1156
1157 int ipmi_create_user(unsigned int          if_num,
1158                      const struct ipmi_user_hndl *handler,
1159                      void                  *handler_data,
1160                      struct ipmi_user      **user)
1161 {
1162         unsigned long flags;
1163         struct ipmi_user *new_user;
1164         int           rv, index;
1165         struct ipmi_smi *intf;
1166
1167         /*
1168          * There is no module usecount here, because it's not
1169          * required.  Since this can only be used by and called from
1170          * other modules, they will implicitly use this module, and
1171          * thus this can't be removed unless the other modules are
1172          * removed.
1173          */
1174
1175         if (handler == NULL)
1176                 return -EINVAL;
1177
1178         /*
1179          * Make sure the driver is actually initialized, this handles
1180          * problems with initialization order.
1181          */
1182         rv = ipmi_init_msghandler();
1183         if (rv)
1184                 return rv;
1185
1186         new_user = kmalloc(sizeof(*new_user), GFP_KERNEL);
1187         if (!new_user)
1188                 return -ENOMEM;
1189
1190         index = srcu_read_lock(&ipmi_interfaces_srcu);
1191         list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
1192                 if (intf->intf_num == if_num)
1193                         goto found;
1194         }
1195         /* Not found, return an error */
1196         rv = -EINVAL;
1197         goto out_kfree;
1198
1199  found:
1200         INIT_WORK(&new_user->remove_work, free_user_work);
1201
1202         rv = init_srcu_struct(&new_user->release_barrier);
1203         if (rv)
1204                 goto out_kfree;
1205
1206         if (!try_module_get(intf->owner)) {
1207                 rv = -ENODEV;
1208                 goto out_kfree;
1209         }
1210
1211         /* Note that each existing user holds a refcount to the interface. */
1212         kref_get(&intf->refcount);
1213
1214         kref_init(&new_user->refcount);
1215         new_user->handler = handler;
1216         new_user->handler_data = handler_data;
1217         new_user->intf = intf;
1218         new_user->gets_events = false;
1219
1220         rcu_assign_pointer(new_user->self, new_user);
1221         spin_lock_irqsave(&intf->seq_lock, flags);
1222         list_add_rcu(&new_user->link, &intf->users);
1223         spin_unlock_irqrestore(&intf->seq_lock, flags);
1224         if (handler->ipmi_watchdog_pretimeout)
1225                 /* User wants pretimeouts, so make sure to watch for them. */
1226                 smi_add_watch(intf, IPMI_WATCH_MASK_CHECK_WATCHDOG);
1227         srcu_read_unlock(&ipmi_interfaces_srcu, index);
1228         *user = new_user;
1229         return 0;
1230
1231 out_kfree:
1232         srcu_read_unlock(&ipmi_interfaces_srcu, index);
1233         kfree(new_user);
1234         return rv;
1235 }
1236 EXPORT_SYMBOL(ipmi_create_user);
1237
1238 int ipmi_get_smi_info(int if_num, struct ipmi_smi_info *data)
1239 {
1240         int rv, index;
1241         struct ipmi_smi *intf;
1242
1243         index = srcu_read_lock(&ipmi_interfaces_srcu);
1244         list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
1245                 if (intf->intf_num == if_num)
1246                         goto found;
1247         }
1248         srcu_read_unlock(&ipmi_interfaces_srcu, index);
1249
1250         /* Not found, return an error */
1251         return -EINVAL;
1252
1253 found:
1254         if (!intf->handlers->get_smi_info)
1255                 rv = -ENOTTY;
1256         else
1257                 rv = intf->handlers->get_smi_info(intf->send_info, data);
1258         srcu_read_unlock(&ipmi_interfaces_srcu, index);
1259
1260         return rv;
1261 }
1262 EXPORT_SYMBOL(ipmi_get_smi_info);
1263
1264 static void free_user(struct kref *ref)
1265 {
1266         struct ipmi_user *user = container_of(ref, struct ipmi_user, refcount);
1267
1268         /* SRCU cleanup must happen in task context. */
1269         schedule_work(&user->remove_work);
1270 }
1271
1272 static void _ipmi_destroy_user(struct ipmi_user *user)
1273 {
1274         struct ipmi_smi  *intf = user->intf;
1275         int              i;
1276         unsigned long    flags;
1277         struct cmd_rcvr  *rcvr;
1278         struct cmd_rcvr  *rcvrs = NULL;
1279
1280         if (!acquire_ipmi_user(user, &i)) {
1281                 /*
1282                  * The user has already been cleaned up, just make sure
1283                  * nothing is using it and return.
1284                  */
1285                 synchronize_srcu(&user->release_barrier);
1286                 return;
1287         }
1288
1289         rcu_assign_pointer(user->self, NULL);
1290         release_ipmi_user(user, i);
1291
1292         synchronize_srcu(&user->release_barrier);
1293
1294         if (user->handler->shutdown)
1295                 user->handler->shutdown(user->handler_data);
1296
1297         if (user->handler->ipmi_watchdog_pretimeout)
1298                 smi_remove_watch(intf, IPMI_WATCH_MASK_CHECK_WATCHDOG);
1299
1300         if (user->gets_events)
1301                 atomic_dec(&intf->event_waiters);
1302
1303         /* Remove the user from the interface's sequence table. */
1304         spin_lock_irqsave(&intf->seq_lock, flags);
1305         list_del_rcu(&user->link);
1306
1307         for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
1308                 if (intf->seq_table[i].inuse
1309                     && (intf->seq_table[i].recv_msg->user == user)) {
1310                         intf->seq_table[i].inuse = 0;
1311                         smi_remove_watch(intf, IPMI_WATCH_MASK_CHECK_MESSAGES);
1312                         ipmi_free_recv_msg(intf->seq_table[i].recv_msg);
1313                 }
1314         }
1315         spin_unlock_irqrestore(&intf->seq_lock, flags);
1316
1317         /*
1318          * Remove the user from the command receiver's table.  First
1319          * we build a list of everything (not using the standard link,
1320          * since other things may be using it till we do
1321          * synchronize_srcu()) then free everything in that list.
1322          */
1323         mutex_lock(&intf->cmd_rcvrs_mutex);
1324         list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
1325                 if (rcvr->user == user) {
1326                         list_del_rcu(&rcvr->link);
1327                         rcvr->next = rcvrs;
1328                         rcvrs = rcvr;
1329                 }
1330         }
1331         mutex_unlock(&intf->cmd_rcvrs_mutex);
1332         synchronize_rcu();
1333         while (rcvrs) {
1334                 rcvr = rcvrs;
1335                 rcvrs = rcvr->next;
1336                 kfree(rcvr);
1337         }
1338
1339         kref_put(&intf->refcount, intf_free);
1340         module_put(intf->owner);
1341 }
1342
1343 int ipmi_destroy_user(struct ipmi_user *user)
1344 {
1345         _ipmi_destroy_user(user);
1346
1347         kref_put(&user->refcount, free_user);
1348
1349         return 0;
1350 }
1351 EXPORT_SYMBOL(ipmi_destroy_user);
1352
1353 int ipmi_get_version(struct ipmi_user *user,
1354                      unsigned char *major,
1355                      unsigned char *minor)
1356 {
1357         struct ipmi_device_id id;
1358         int rv, index;
1359
1360         user = acquire_ipmi_user(user, &index);
1361         if (!user)
1362                 return -ENODEV;
1363
1364         rv = bmc_get_device_id(user->intf, NULL, &id, NULL, NULL);
1365         if (!rv) {
1366                 *major = ipmi_version_major(&id);
1367                 *minor = ipmi_version_minor(&id);
1368         }
1369         release_ipmi_user(user, index);
1370
1371         return rv;
1372 }
1373 EXPORT_SYMBOL(ipmi_get_version);
1374
1375 int ipmi_set_my_address(struct ipmi_user *user,
1376                         unsigned int  channel,
1377                         unsigned char address)
1378 {
1379         int index, rv = 0;
1380
1381         user = acquire_ipmi_user(user, &index);
1382         if (!user)
1383                 return -ENODEV;
1384
1385         if (channel >= IPMI_MAX_CHANNELS) {
1386                 rv = -EINVAL;
1387         } else {
1388                 channel = array_index_nospec(channel, IPMI_MAX_CHANNELS);
1389                 user->intf->addrinfo[channel].address = address;
1390         }
1391         release_ipmi_user(user, index);
1392
1393         return rv;
1394 }
1395 EXPORT_SYMBOL(ipmi_set_my_address);
1396
1397 int ipmi_get_my_address(struct ipmi_user *user,
1398                         unsigned int  channel,
1399                         unsigned char *address)
1400 {
1401         int index, rv = 0;
1402
1403         user = acquire_ipmi_user(user, &index);
1404         if (!user)
1405                 return -ENODEV;
1406
1407         if (channel >= IPMI_MAX_CHANNELS) {
1408                 rv = -EINVAL;
1409         } else {
1410                 channel = array_index_nospec(channel, IPMI_MAX_CHANNELS);
1411                 *address = user->intf->addrinfo[channel].address;
1412         }
1413         release_ipmi_user(user, index);
1414
1415         return rv;
1416 }
1417 EXPORT_SYMBOL(ipmi_get_my_address);
1418
1419 int ipmi_set_my_LUN(struct ipmi_user *user,
1420                     unsigned int  channel,
1421                     unsigned char LUN)
1422 {
1423         int index, rv = 0;
1424
1425         user = acquire_ipmi_user(user, &index);
1426         if (!user)
1427                 return -ENODEV;
1428
1429         if (channel >= IPMI_MAX_CHANNELS) {
1430                 rv = -EINVAL;
1431         } else {
1432                 channel = array_index_nospec(channel, IPMI_MAX_CHANNELS);
1433                 user->intf->addrinfo[channel].lun = LUN & 0x3;
1434         }
1435         release_ipmi_user(user, index);
1436
1437         return rv;
1438 }
1439 EXPORT_SYMBOL(ipmi_set_my_LUN);
1440
1441 int ipmi_get_my_LUN(struct ipmi_user *user,
1442                     unsigned int  channel,
1443                     unsigned char *address)
1444 {
1445         int index, rv = 0;
1446
1447         user = acquire_ipmi_user(user, &index);
1448         if (!user)
1449                 return -ENODEV;
1450
1451         if (channel >= IPMI_MAX_CHANNELS) {
1452                 rv = -EINVAL;
1453         } else {
1454                 channel = array_index_nospec(channel, IPMI_MAX_CHANNELS);
1455                 *address = user->intf->addrinfo[channel].lun;
1456         }
1457         release_ipmi_user(user, index);
1458
1459         return rv;
1460 }
1461 EXPORT_SYMBOL(ipmi_get_my_LUN);
1462
1463 int ipmi_get_maintenance_mode(struct ipmi_user *user)
1464 {
1465         int mode, index;
1466         unsigned long flags;
1467
1468         user = acquire_ipmi_user(user, &index);
1469         if (!user)
1470                 return -ENODEV;
1471
1472         spin_lock_irqsave(&user->intf->maintenance_mode_lock, flags);
1473         mode = user->intf->maintenance_mode;
1474         spin_unlock_irqrestore(&user->intf->maintenance_mode_lock, flags);
1475         release_ipmi_user(user, index);
1476
1477         return mode;
1478 }
1479 EXPORT_SYMBOL(ipmi_get_maintenance_mode);
1480
1481 static void maintenance_mode_update(struct ipmi_smi *intf)
1482 {
1483         if (intf->handlers->set_maintenance_mode)
1484                 intf->handlers->set_maintenance_mode(
1485                         intf->send_info, intf->maintenance_mode_enable);
1486 }
1487
1488 int ipmi_set_maintenance_mode(struct ipmi_user *user, int mode)
1489 {
1490         int rv = 0, index;
1491         unsigned long flags;
1492         struct ipmi_smi *intf = user->intf;
1493
1494         user = acquire_ipmi_user(user, &index);
1495         if (!user)
1496                 return -ENODEV;
1497
1498         spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
1499         if (intf->maintenance_mode != mode) {
1500                 switch (mode) {
1501                 case IPMI_MAINTENANCE_MODE_AUTO:
1502                         intf->maintenance_mode_enable
1503                                 = (intf->auto_maintenance_timeout > 0);
1504                         break;
1505
1506                 case IPMI_MAINTENANCE_MODE_OFF:
1507                         intf->maintenance_mode_enable = false;
1508                         break;
1509
1510                 case IPMI_MAINTENANCE_MODE_ON:
1511                         intf->maintenance_mode_enable = true;
1512                         break;
1513
1514                 default:
1515                         rv = -EINVAL;
1516                         goto out_unlock;
1517                 }
1518                 intf->maintenance_mode = mode;
1519
1520                 maintenance_mode_update(intf);
1521         }
1522  out_unlock:
1523         spin_unlock_irqrestore(&intf->maintenance_mode_lock, flags);
1524         release_ipmi_user(user, index);
1525
1526         return rv;
1527 }
1528 EXPORT_SYMBOL(ipmi_set_maintenance_mode);
1529
1530 int ipmi_set_gets_events(struct ipmi_user *user, bool val)
1531 {
1532         unsigned long        flags;
1533         struct ipmi_smi      *intf = user->intf;
1534         struct ipmi_recv_msg *msg, *msg2;
1535         struct list_head     msgs;
1536         int index;
1537
1538         user = acquire_ipmi_user(user, &index);
1539         if (!user)
1540                 return -ENODEV;
1541
1542         INIT_LIST_HEAD(&msgs);
1543
1544         spin_lock_irqsave(&intf->events_lock, flags);
1545         if (user->gets_events == val)
1546                 goto out;
1547
1548         user->gets_events = val;
1549
1550         if (val) {
1551                 if (atomic_inc_return(&intf->event_waiters) == 1)
1552                         need_waiter(intf);
1553         } else {
1554                 atomic_dec(&intf->event_waiters);
1555         }
1556
1557         if (intf->delivering_events)
1558                 /*
1559                  * Another thread is delivering events for this, so
1560                  * let it handle any new events.
1561                  */
1562                 goto out;
1563
1564         /* Deliver any queued events. */
1565         while (user->gets_events && !list_empty(&intf->waiting_events)) {
1566                 list_for_each_entry_safe(msg, msg2, &intf->waiting_events, link)
1567                         list_move_tail(&msg->link, &msgs);
1568                 intf->waiting_events_count = 0;
1569                 if (intf->event_msg_printed) {
1570                         dev_warn(intf->si_dev, "Event queue no longer full\n");
1571                         intf->event_msg_printed = 0;
1572                 }
1573
1574                 intf->delivering_events = 1;
1575                 spin_unlock_irqrestore(&intf->events_lock, flags);
1576
1577                 list_for_each_entry_safe(msg, msg2, &msgs, link) {
1578                         msg->user = user;
1579                         kref_get(&user->refcount);
1580                         deliver_local_response(intf, msg);
1581                 }
1582
1583                 spin_lock_irqsave(&intf->events_lock, flags);
1584                 intf->delivering_events = 0;
1585         }
1586
1587  out:
1588         spin_unlock_irqrestore(&intf->events_lock, flags);
1589         release_ipmi_user(user, index);
1590
1591         return 0;
1592 }
1593 EXPORT_SYMBOL(ipmi_set_gets_events);
1594
1595 static struct cmd_rcvr *find_cmd_rcvr(struct ipmi_smi *intf,
1596                                       unsigned char netfn,
1597                                       unsigned char cmd,
1598                                       unsigned char chan)
1599 {
1600         struct cmd_rcvr *rcvr;
1601
1602         list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
1603                 if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)
1604                                         && (rcvr->chans & (1 << chan)))
1605                         return rcvr;
1606         }
1607         return NULL;
1608 }
1609
1610 static int is_cmd_rcvr_exclusive(struct ipmi_smi *intf,
1611                                  unsigned char netfn,
1612                                  unsigned char cmd,
1613                                  unsigned int  chans)
1614 {
1615         struct cmd_rcvr *rcvr;
1616
1617         list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
1618                 if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)
1619                                         && (rcvr->chans & chans))
1620                         return 0;
1621         }
1622         return 1;
1623 }
1624
1625 int ipmi_register_for_cmd(struct ipmi_user *user,
1626                           unsigned char netfn,
1627                           unsigned char cmd,
1628                           unsigned int  chans)
1629 {
1630         struct ipmi_smi *intf = user->intf;
1631         struct cmd_rcvr *rcvr;
1632         int rv = 0, index;
1633
1634         user = acquire_ipmi_user(user, &index);
1635         if (!user)
1636                 return -ENODEV;
1637
1638         rcvr = kmalloc(sizeof(*rcvr), GFP_KERNEL);
1639         if (!rcvr) {
1640                 rv = -ENOMEM;
1641                 goto out_release;
1642         }
1643         rcvr->cmd = cmd;
1644         rcvr->netfn = netfn;
1645         rcvr->chans = chans;
1646         rcvr->user = user;
1647
1648         mutex_lock(&intf->cmd_rcvrs_mutex);
1649         /* Make sure the command/netfn is not already registered. */
1650         if (!is_cmd_rcvr_exclusive(intf, netfn, cmd, chans)) {
1651                 rv = -EBUSY;
1652                 goto out_unlock;
1653         }
1654
1655         smi_add_watch(intf, IPMI_WATCH_MASK_CHECK_COMMANDS);
1656
1657         list_add_rcu(&rcvr->link, &intf->cmd_rcvrs);
1658
1659 out_unlock:
1660         mutex_unlock(&intf->cmd_rcvrs_mutex);
1661         if (rv)
1662                 kfree(rcvr);
1663 out_release:
1664         release_ipmi_user(user, index);
1665
1666         return rv;
1667 }
1668 EXPORT_SYMBOL(ipmi_register_for_cmd);
1669
1670 int ipmi_unregister_for_cmd(struct ipmi_user *user,
1671                             unsigned char netfn,
1672                             unsigned char cmd,
1673                             unsigned int  chans)
1674 {
1675         struct ipmi_smi *intf = user->intf;
1676         struct cmd_rcvr *rcvr;
1677         struct cmd_rcvr *rcvrs = NULL;
1678         int i, rv = -ENOENT, index;
1679
1680         user = acquire_ipmi_user(user, &index);
1681         if (!user)
1682                 return -ENODEV;
1683
1684         mutex_lock(&intf->cmd_rcvrs_mutex);
1685         for (i = 0; i < IPMI_NUM_CHANNELS; i++) {
1686                 if (((1 << i) & chans) == 0)
1687                         continue;
1688                 rcvr = find_cmd_rcvr(intf, netfn, cmd, i);
1689                 if (rcvr == NULL)
1690                         continue;
1691                 if (rcvr->user == user) {
1692                         rv = 0;
1693                         rcvr->chans &= ~chans;
1694                         if (rcvr->chans == 0) {
1695                                 list_del_rcu(&rcvr->link);
1696                                 rcvr->next = rcvrs;
1697                                 rcvrs = rcvr;
1698                         }
1699                 }
1700         }
1701         mutex_unlock(&intf->cmd_rcvrs_mutex);
1702         synchronize_rcu();
1703         release_ipmi_user(user, index);
1704         while (rcvrs) {
1705                 smi_remove_watch(intf, IPMI_WATCH_MASK_CHECK_COMMANDS);
1706                 rcvr = rcvrs;
1707                 rcvrs = rcvr->next;
1708                 kfree(rcvr);
1709         }
1710
1711         return rv;
1712 }
1713 EXPORT_SYMBOL(ipmi_unregister_for_cmd);
1714
1715 static unsigned char
1716 ipmb_checksum(unsigned char *data, int size)
1717 {
1718         unsigned char csum = 0;
1719
1720         for (; size > 0; size--, data++)
1721                 csum += *data;
1722
1723         return -csum;
1724 }
1725
1726 static inline void format_ipmb_msg(struct ipmi_smi_msg   *smi_msg,
1727                                    struct kernel_ipmi_msg *msg,
1728                                    struct ipmi_ipmb_addr *ipmb_addr,
1729                                    long                  msgid,
1730                                    unsigned char         ipmb_seq,
1731                                    int                   broadcast,
1732                                    unsigned char         source_address,
1733                                    unsigned char         source_lun)
1734 {
1735         int i = broadcast;
1736
1737         /* Format the IPMB header data. */
1738         smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
1739         smi_msg->data[1] = IPMI_SEND_MSG_CMD;
1740         smi_msg->data[2] = ipmb_addr->channel;
1741         if (broadcast)
1742                 smi_msg->data[3] = 0;
1743         smi_msg->data[i+3] = ipmb_addr->slave_addr;
1744         smi_msg->data[i+4] = (msg->netfn << 2) | (ipmb_addr->lun & 0x3);
1745         smi_msg->data[i+5] = ipmb_checksum(&smi_msg->data[i + 3], 2);
1746         smi_msg->data[i+6] = source_address;
1747         smi_msg->data[i+7] = (ipmb_seq << 2) | source_lun;
1748         smi_msg->data[i+8] = msg->cmd;
1749
1750         /* Now tack on the data to the message. */
1751         if (msg->data_len > 0)
1752                 memcpy(&smi_msg->data[i + 9], msg->data, msg->data_len);
1753         smi_msg->data_size = msg->data_len + 9;
1754
1755         /* Now calculate the checksum and tack it on. */
1756         smi_msg->data[i+smi_msg->data_size]
1757                 = ipmb_checksum(&smi_msg->data[i + 6], smi_msg->data_size - 6);
1758
1759         /*
1760          * Add on the checksum size and the offset from the
1761          * broadcast.
1762          */
1763         smi_msg->data_size += 1 + i;
1764
1765         smi_msg->msgid = msgid;
1766 }
1767
1768 static inline void format_lan_msg(struct ipmi_smi_msg   *smi_msg,
1769                                   struct kernel_ipmi_msg *msg,
1770                                   struct ipmi_lan_addr  *lan_addr,
1771                                   long                  msgid,
1772                                   unsigned char         ipmb_seq,
1773                                   unsigned char         source_lun)
1774 {
1775         /* Format the IPMB header data. */
1776         smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
1777         smi_msg->data[1] = IPMI_SEND_MSG_CMD;
1778         smi_msg->data[2] = lan_addr->channel;
1779         smi_msg->data[3] = lan_addr->session_handle;
1780         smi_msg->data[4] = lan_addr->remote_SWID;
1781         smi_msg->data[5] = (msg->netfn << 2) | (lan_addr->lun & 0x3);
1782         smi_msg->data[6] = ipmb_checksum(&smi_msg->data[4], 2);
1783         smi_msg->data[7] = lan_addr->local_SWID;
1784         smi_msg->data[8] = (ipmb_seq << 2) | source_lun;
1785         smi_msg->data[9] = msg->cmd;
1786
1787         /* Now tack on the data to the message. */
1788         if (msg->data_len > 0)
1789                 memcpy(&smi_msg->data[10], msg->data, msg->data_len);
1790         smi_msg->data_size = msg->data_len + 10;
1791
1792         /* Now calculate the checksum and tack it on. */
1793         smi_msg->data[smi_msg->data_size]
1794                 = ipmb_checksum(&smi_msg->data[7], smi_msg->data_size - 7);
1795
1796         /*
1797          * Add on the checksum size and the offset from the
1798          * broadcast.
1799          */
1800         smi_msg->data_size += 1;
1801
1802         smi_msg->msgid = msgid;
1803 }
1804
1805 static struct ipmi_smi_msg *smi_add_send_msg(struct ipmi_smi *intf,
1806                                              struct ipmi_smi_msg *smi_msg,
1807                                              int priority)
1808 {
1809         if (intf->curr_msg) {
1810                 if (priority > 0)
1811                         list_add_tail(&smi_msg->link, &intf->hp_xmit_msgs);
1812                 else
1813                         list_add_tail(&smi_msg->link, &intf->xmit_msgs);
1814                 smi_msg = NULL;
1815         } else {
1816                 intf->curr_msg = smi_msg;
1817         }
1818
1819         return smi_msg;
1820 }
1821
1822 static void smi_send(struct ipmi_smi *intf,
1823                      const struct ipmi_smi_handlers *handlers,
1824                      struct ipmi_smi_msg *smi_msg, int priority)
1825 {
1826         int run_to_completion = intf->run_to_completion;
1827         unsigned long flags = 0;
1828
1829         if (!run_to_completion)
1830                 spin_lock_irqsave(&intf->xmit_msgs_lock, flags);
1831         smi_msg = smi_add_send_msg(intf, smi_msg, priority);
1832
1833         if (!run_to_completion)
1834                 spin_unlock_irqrestore(&intf->xmit_msgs_lock, flags);
1835
1836         if (smi_msg)
1837                 handlers->sender(intf->send_info, smi_msg);
1838 }
1839
1840 static bool is_maintenance_mode_cmd(struct kernel_ipmi_msg *msg)
1841 {
1842         return (((msg->netfn == IPMI_NETFN_APP_REQUEST)
1843                  && ((msg->cmd == IPMI_COLD_RESET_CMD)
1844                      || (msg->cmd == IPMI_WARM_RESET_CMD)))
1845                 || (msg->netfn == IPMI_NETFN_FIRMWARE_REQUEST));
1846 }
1847
1848 static int i_ipmi_req_sysintf(struct ipmi_smi        *intf,
1849                               struct ipmi_addr       *addr,
1850                               long                   msgid,
1851                               struct kernel_ipmi_msg *msg,
1852                               struct ipmi_smi_msg    *smi_msg,
1853                               struct ipmi_recv_msg   *recv_msg,
1854                               int                    retries,
1855                               unsigned int           retry_time_ms)
1856 {
1857         struct ipmi_system_interface_addr *smi_addr;
1858
1859         if (msg->netfn & 1)
1860                 /* Responses are not allowed to the SMI. */
1861                 return -EINVAL;
1862
1863         smi_addr = (struct ipmi_system_interface_addr *) addr;
1864         if (smi_addr->lun > 3) {
1865                 ipmi_inc_stat(intf, sent_invalid_commands);
1866                 return -EINVAL;
1867         }
1868
1869         memcpy(&recv_msg->addr, smi_addr, sizeof(*smi_addr));
1870
1871         if ((msg->netfn == IPMI_NETFN_APP_REQUEST)
1872             && ((msg->cmd == IPMI_SEND_MSG_CMD)
1873                 || (msg->cmd == IPMI_GET_MSG_CMD)
1874                 || (msg->cmd == IPMI_READ_EVENT_MSG_BUFFER_CMD))) {
1875                 /*
1876                  * We don't let the user do these, since we manage
1877                  * the sequence numbers.
1878                  */
1879                 ipmi_inc_stat(intf, sent_invalid_commands);
1880                 return -EINVAL;
1881         }
1882
1883         if (is_maintenance_mode_cmd(msg)) {
1884                 unsigned long flags;
1885
1886                 spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
1887                 intf->auto_maintenance_timeout
1888                         = maintenance_mode_timeout_ms;
1889                 if (!intf->maintenance_mode
1890                     && !intf->maintenance_mode_enable) {
1891                         intf->maintenance_mode_enable = true;
1892                         maintenance_mode_update(intf);
1893                 }
1894                 spin_unlock_irqrestore(&intf->maintenance_mode_lock,
1895                                        flags);
1896         }
1897
1898         if (msg->data_len + 2 > IPMI_MAX_MSG_LENGTH) {
1899                 ipmi_inc_stat(intf, sent_invalid_commands);
1900                 return -EMSGSIZE;
1901         }
1902
1903         smi_msg->data[0] = (msg->netfn << 2) | (smi_addr->lun & 0x3);
1904         smi_msg->data[1] = msg->cmd;
1905         smi_msg->msgid = msgid;
1906         smi_msg->user_data = recv_msg;
1907         if (msg->data_len > 0)
1908                 memcpy(&smi_msg->data[2], msg->data, msg->data_len);
1909         smi_msg->data_size = msg->data_len + 2;
1910         ipmi_inc_stat(intf, sent_local_commands);
1911
1912         return 0;
1913 }
1914
1915 static int i_ipmi_req_ipmb(struct ipmi_smi        *intf,
1916                            struct ipmi_addr       *addr,
1917                            long                   msgid,
1918                            struct kernel_ipmi_msg *msg,
1919                            struct ipmi_smi_msg    *smi_msg,
1920                            struct ipmi_recv_msg   *recv_msg,
1921                            unsigned char          source_address,
1922                            unsigned char          source_lun,
1923                            int                    retries,
1924                            unsigned int           retry_time_ms)
1925 {
1926         struct ipmi_ipmb_addr *ipmb_addr;
1927         unsigned char ipmb_seq;
1928         long seqid;
1929         int broadcast = 0;
1930         struct ipmi_channel *chans;
1931         int rv = 0;
1932
1933         if (addr->channel >= IPMI_MAX_CHANNELS) {
1934                 ipmi_inc_stat(intf, sent_invalid_commands);
1935                 return -EINVAL;
1936         }
1937
1938         chans = READ_ONCE(intf->channel_list)->c;
1939
1940         if (chans[addr->channel].medium != IPMI_CHANNEL_MEDIUM_IPMB) {
1941                 ipmi_inc_stat(intf, sent_invalid_commands);
1942                 return -EINVAL;
1943         }
1944
1945         if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE) {
1946                 /*
1947                  * Broadcasts add a zero at the beginning of the
1948                  * message, but otherwise is the same as an IPMB
1949                  * address.
1950                  */
1951                 addr->addr_type = IPMI_IPMB_ADDR_TYPE;
1952                 broadcast = 1;
1953                 retries = 0; /* Don't retry broadcasts. */
1954         }
1955
1956         /*
1957          * 9 for the header and 1 for the checksum, plus
1958          * possibly one for the broadcast.
1959          */
1960         if ((msg->data_len + 10 + broadcast) > IPMI_MAX_MSG_LENGTH) {
1961                 ipmi_inc_stat(intf, sent_invalid_commands);
1962                 return -EMSGSIZE;
1963         }
1964
1965         ipmb_addr = (struct ipmi_ipmb_addr *) addr;
1966         if (ipmb_addr->lun > 3) {
1967                 ipmi_inc_stat(intf, sent_invalid_commands);
1968                 return -EINVAL;
1969         }
1970
1971         memcpy(&recv_msg->addr, ipmb_addr, sizeof(*ipmb_addr));
1972
1973         if (recv_msg->msg.netfn & 0x1) {
1974                 /*
1975                  * It's a response, so use the user's sequence
1976                  * from msgid.
1977                  */
1978                 ipmi_inc_stat(intf, sent_ipmb_responses);
1979                 format_ipmb_msg(smi_msg, msg, ipmb_addr, msgid,
1980                                 msgid, broadcast,
1981                                 source_address, source_lun);
1982
1983                 /*
1984                  * Save the receive message so we can use it
1985                  * to deliver the response.
1986                  */
1987                 smi_msg->user_data = recv_msg;
1988         } else {
1989                 /* It's a command, so get a sequence for it. */
1990                 unsigned long flags;
1991
1992                 spin_lock_irqsave(&intf->seq_lock, flags);
1993
1994                 if (is_maintenance_mode_cmd(msg))
1995                         intf->ipmb_maintenance_mode_timeout =
1996                                 maintenance_mode_timeout_ms;
1997
1998                 if (intf->ipmb_maintenance_mode_timeout && retry_time_ms == 0)
1999                         /* Different default in maintenance mode */
2000                         retry_time_ms = default_maintenance_retry_ms;
2001
2002                 /*
2003                  * Create a sequence number with a 1 second
2004                  * timeout and 4 retries.
2005                  */
2006                 rv = intf_next_seq(intf,
2007                                    recv_msg,
2008                                    retry_time_ms,
2009                                    retries,
2010                                    broadcast,
2011                                    &ipmb_seq,
2012                                    &seqid);
2013                 if (rv)
2014                         /*
2015                          * We have used up all the sequence numbers,
2016                          * probably, so abort.
2017                          */
2018                         goto out_err;
2019
2020                 ipmi_inc_stat(intf, sent_ipmb_commands);
2021
2022                 /*
2023                  * Store the sequence number in the message,
2024                  * so that when the send message response
2025                  * comes back we can start the timer.
2026                  */
2027                 format_ipmb_msg(smi_msg, msg, ipmb_addr,
2028                                 STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
2029                                 ipmb_seq, broadcast,
2030                                 source_address, source_lun);
2031
2032                 /*
2033                  * Copy the message into the recv message data, so we
2034                  * can retransmit it later if necessary.
2035                  */
2036                 memcpy(recv_msg->msg_data, smi_msg->data,
2037                        smi_msg->data_size);
2038                 recv_msg->msg.data = recv_msg->msg_data;
2039                 recv_msg->msg.data_len = smi_msg->data_size;
2040
2041                 /*
2042                  * We don't unlock until here, because we need
2043                  * to copy the completed message into the
2044                  * recv_msg before we release the lock.
2045                  * Otherwise, race conditions may bite us.  I
2046                  * know that's pretty paranoid, but I prefer
2047                  * to be correct.
2048                  */
2049 out_err:
2050                 spin_unlock_irqrestore(&intf->seq_lock, flags);
2051         }
2052
2053         return rv;
2054 }
2055
2056 static int i_ipmi_req_lan(struct ipmi_smi        *intf,
2057                           struct ipmi_addr       *addr,
2058                           long                   msgid,
2059                           struct kernel_ipmi_msg *msg,
2060                           struct ipmi_smi_msg    *smi_msg,
2061                           struct ipmi_recv_msg   *recv_msg,
2062                           unsigned char          source_lun,
2063                           int                    retries,
2064                           unsigned int           retry_time_ms)
2065 {
2066         struct ipmi_lan_addr  *lan_addr;
2067         unsigned char ipmb_seq;
2068         long seqid;
2069         struct ipmi_channel *chans;
2070         int rv = 0;
2071
2072         if (addr->channel >= IPMI_MAX_CHANNELS) {
2073                 ipmi_inc_stat(intf, sent_invalid_commands);
2074                 return -EINVAL;
2075         }
2076
2077         chans = READ_ONCE(intf->channel_list)->c;
2078
2079         if ((chans[addr->channel].medium
2080                                 != IPMI_CHANNEL_MEDIUM_8023LAN)
2081                         && (chans[addr->channel].medium
2082                             != IPMI_CHANNEL_MEDIUM_ASYNC)) {
2083                 ipmi_inc_stat(intf, sent_invalid_commands);
2084                 return -EINVAL;
2085         }
2086
2087         /* 11 for the header and 1 for the checksum. */
2088         if ((msg->data_len + 12) > IPMI_MAX_MSG_LENGTH) {
2089                 ipmi_inc_stat(intf, sent_invalid_commands);
2090                 return -EMSGSIZE;
2091         }
2092
2093         lan_addr = (struct ipmi_lan_addr *) addr;
2094         if (lan_addr->lun > 3) {
2095                 ipmi_inc_stat(intf, sent_invalid_commands);
2096                 return -EINVAL;
2097         }
2098
2099         memcpy(&recv_msg->addr, lan_addr, sizeof(*lan_addr));
2100
2101         if (recv_msg->msg.netfn & 0x1) {
2102                 /*
2103                  * It's a response, so use the user's sequence
2104                  * from msgid.
2105                  */
2106                 ipmi_inc_stat(intf, sent_lan_responses);
2107                 format_lan_msg(smi_msg, msg, lan_addr, msgid,
2108                                msgid, source_lun);
2109
2110                 /*
2111                  * Save the receive message so we can use it
2112                  * to deliver the response.
2113                  */
2114                 smi_msg->user_data = recv_msg;
2115         } else {
2116                 /* It's a command, so get a sequence for it. */
2117                 unsigned long flags;
2118
2119                 spin_lock_irqsave(&intf->seq_lock, flags);
2120
2121                 /*
2122                  * Create a sequence number with a 1 second
2123                  * timeout and 4 retries.
2124                  */
2125                 rv = intf_next_seq(intf,
2126                                    recv_msg,
2127                                    retry_time_ms,
2128                                    retries,
2129                                    0,
2130                                    &ipmb_seq,
2131                                    &seqid);
2132                 if (rv)
2133                         /*
2134                          * We have used up all the sequence numbers,
2135                          * probably, so abort.
2136                          */
2137                         goto out_err;
2138
2139                 ipmi_inc_stat(intf, sent_lan_commands);
2140
2141                 /*
2142                  * Store the sequence number in the message,
2143                  * so that when the send message response
2144                  * comes back we can start the timer.
2145                  */
2146                 format_lan_msg(smi_msg, msg, lan_addr,
2147                                STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
2148                                ipmb_seq, source_lun);
2149
2150                 /*
2151                  * Copy the message into the recv message data, so we
2152                  * can retransmit it later if necessary.
2153                  */
2154                 memcpy(recv_msg->msg_data, smi_msg->data,
2155                        smi_msg->data_size);
2156                 recv_msg->msg.data = recv_msg->msg_data;
2157                 recv_msg->msg.data_len = smi_msg->data_size;
2158
2159                 /*
2160                  * We don't unlock until here, because we need
2161                  * to copy the completed message into the
2162                  * recv_msg before we release the lock.
2163                  * Otherwise, race conditions may bite us.  I
2164                  * know that's pretty paranoid, but I prefer
2165                  * to be correct.
2166                  */
2167 out_err:
2168                 spin_unlock_irqrestore(&intf->seq_lock, flags);
2169         }
2170
2171         return rv;
2172 }
2173
2174 /*
2175  * Separate from ipmi_request so that the user does not have to be
2176  * supplied in certain circumstances (mainly at panic time).  If
2177  * messages are supplied, they will be freed, even if an error
2178  * occurs.
2179  */
2180 static int i_ipmi_request(struct ipmi_user     *user,
2181                           struct ipmi_smi      *intf,
2182                           struct ipmi_addr     *addr,
2183                           long                 msgid,
2184                           struct kernel_ipmi_msg *msg,
2185                           void                 *user_msg_data,
2186                           void                 *supplied_smi,
2187                           struct ipmi_recv_msg *supplied_recv,
2188                           int                  priority,
2189                           unsigned char        source_address,
2190                           unsigned char        source_lun,
2191                           int                  retries,
2192                           unsigned int         retry_time_ms)
2193 {
2194         struct ipmi_smi_msg *smi_msg;
2195         struct ipmi_recv_msg *recv_msg;
2196         int rv = 0;
2197
2198         if (supplied_recv)
2199                 recv_msg = supplied_recv;
2200         else {
2201                 recv_msg = ipmi_alloc_recv_msg();
2202                 if (recv_msg == NULL) {
2203                         rv = -ENOMEM;
2204                         goto out;
2205                 }
2206         }
2207         recv_msg->user_msg_data = user_msg_data;
2208
2209         if (supplied_smi)
2210                 smi_msg = (struct ipmi_smi_msg *) supplied_smi;
2211         else {
2212                 smi_msg = ipmi_alloc_smi_msg();
2213                 if (smi_msg == NULL) {
2214                         if (!supplied_recv)
2215                                 ipmi_free_recv_msg(recv_msg);
2216                         rv = -ENOMEM;
2217                         goto out;
2218                 }
2219         }
2220
2221         rcu_read_lock();
2222         if (intf->in_shutdown) {
2223                 rv = -ENODEV;
2224                 goto out_err;
2225         }
2226
2227         recv_msg->user = user;
2228         if (user)
2229                 /* The put happens when the message is freed. */
2230                 kref_get(&user->refcount);
2231         recv_msg->msgid = msgid;
2232         /*
2233          * Store the message to send in the receive message so timeout
2234          * responses can get the proper response data.
2235          */
2236         recv_msg->msg = *msg;
2237
2238         if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
2239                 rv = i_ipmi_req_sysintf(intf, addr, msgid, msg, smi_msg,
2240                                         recv_msg, retries, retry_time_ms);
2241         } else if (is_ipmb_addr(addr) || is_ipmb_bcast_addr(addr)) {
2242                 rv = i_ipmi_req_ipmb(intf, addr, msgid, msg, smi_msg, recv_msg,
2243                                      source_address, source_lun,
2244                                      retries, retry_time_ms);
2245         } else if (is_lan_addr(addr)) {
2246                 rv = i_ipmi_req_lan(intf, addr, msgid, msg, smi_msg, recv_msg,
2247                                     source_lun, retries, retry_time_ms);
2248         } else {
2249             /* Unknown address type. */
2250                 ipmi_inc_stat(intf, sent_invalid_commands);
2251                 rv = -EINVAL;
2252         }
2253
2254         if (rv) {
2255 out_err:
2256                 ipmi_free_smi_msg(smi_msg);
2257                 ipmi_free_recv_msg(recv_msg);
2258         } else {
2259                 pr_debug("Send: %*ph\n", smi_msg->data_size, smi_msg->data);
2260
2261                 smi_send(intf, intf->handlers, smi_msg, priority);
2262         }
2263         rcu_read_unlock();
2264
2265 out:
2266         return rv;
2267 }
2268
2269 static int check_addr(struct ipmi_smi  *intf,
2270                       struct ipmi_addr *addr,
2271                       unsigned char    *saddr,
2272                       unsigned char    *lun)
2273 {
2274         if (addr->channel >= IPMI_MAX_CHANNELS)
2275                 return -EINVAL;
2276         addr->channel = array_index_nospec(addr->channel, IPMI_MAX_CHANNELS);
2277         *lun = intf->addrinfo[addr->channel].lun;
2278         *saddr = intf->addrinfo[addr->channel].address;
2279         return 0;
2280 }
2281
2282 int ipmi_request_settime(struct ipmi_user *user,
2283                          struct ipmi_addr *addr,
2284                          long             msgid,
2285                          struct kernel_ipmi_msg  *msg,
2286                          void             *user_msg_data,
2287                          int              priority,
2288                          int              retries,
2289                          unsigned int     retry_time_ms)
2290 {
2291         unsigned char saddr = 0, lun = 0;
2292         int rv, index;
2293
2294         if (!user)
2295                 return -EINVAL;
2296
2297         user = acquire_ipmi_user(user, &index);
2298         if (!user)
2299                 return -ENODEV;
2300
2301         rv = check_addr(user->intf, addr, &saddr, &lun);
2302         if (!rv)
2303                 rv = i_ipmi_request(user,
2304                                     user->intf,
2305                                     addr,
2306                                     msgid,
2307                                     msg,
2308                                     user_msg_data,
2309                                     NULL, NULL,
2310                                     priority,
2311                                     saddr,
2312                                     lun,
2313                                     retries,
2314                                     retry_time_ms);
2315
2316         release_ipmi_user(user, index);
2317         return rv;
2318 }
2319 EXPORT_SYMBOL(ipmi_request_settime);
2320
2321 int ipmi_request_supply_msgs(struct ipmi_user     *user,
2322                              struct ipmi_addr     *addr,
2323                              long                 msgid,
2324                              struct kernel_ipmi_msg *msg,
2325                              void                 *user_msg_data,
2326                              void                 *supplied_smi,
2327                              struct ipmi_recv_msg *supplied_recv,
2328                              int                  priority)
2329 {
2330         unsigned char saddr = 0, lun = 0;
2331         int rv, index;
2332
2333         if (!user)
2334                 return -EINVAL;
2335
2336         user = acquire_ipmi_user(user, &index);
2337         if (!user)
2338                 return -ENODEV;
2339
2340         rv = check_addr(user->intf, addr, &saddr, &lun);
2341         if (!rv)
2342                 rv = i_ipmi_request(user,
2343                                     user->intf,
2344                                     addr,
2345                                     msgid,
2346                                     msg,
2347                                     user_msg_data,
2348                                     supplied_smi,
2349                                     supplied_recv,
2350                                     priority,
2351                                     saddr,
2352                                     lun,
2353                                     -1, 0);
2354
2355         release_ipmi_user(user, index);
2356         return rv;
2357 }
2358 EXPORT_SYMBOL(ipmi_request_supply_msgs);
2359
2360 static void bmc_device_id_handler(struct ipmi_smi *intf,
2361                                   struct ipmi_recv_msg *msg)
2362 {
2363         int rv;
2364
2365         if ((msg->addr.addr_type != IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
2366                         || (msg->msg.netfn != IPMI_NETFN_APP_RESPONSE)
2367                         || (msg->msg.cmd != IPMI_GET_DEVICE_ID_CMD)) {
2368                 dev_warn(intf->si_dev,
2369                          "invalid device_id msg: addr_type=%d netfn=%x cmd=%x\n",
2370                          msg->addr.addr_type, msg->msg.netfn, msg->msg.cmd);
2371                 return;
2372         }
2373
2374         rv = ipmi_demangle_device_id(msg->msg.netfn, msg->msg.cmd,
2375                         msg->msg.data, msg->msg.data_len, &intf->bmc->fetch_id);
2376         if (rv) {
2377                 dev_warn(intf->si_dev, "device id demangle failed: %d\n", rv);
2378                 intf->bmc->dyn_id_set = 0;
2379         } else {
2380                 /*
2381                  * Make sure the id data is available before setting
2382                  * dyn_id_set.
2383                  */
2384                 smp_wmb();
2385                 intf->bmc->dyn_id_set = 1;
2386         }
2387
2388         wake_up(&intf->waitq);
2389 }
2390
2391 static int
2392 send_get_device_id_cmd(struct ipmi_smi *intf)
2393 {
2394         struct ipmi_system_interface_addr si;
2395         struct kernel_ipmi_msg msg;
2396
2397         si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
2398         si.channel = IPMI_BMC_CHANNEL;
2399         si.lun = 0;
2400
2401         msg.netfn = IPMI_NETFN_APP_REQUEST;
2402         msg.cmd = IPMI_GET_DEVICE_ID_CMD;
2403         msg.data = NULL;
2404         msg.data_len = 0;
2405
2406         return i_ipmi_request(NULL,
2407                               intf,
2408                               (struct ipmi_addr *) &si,
2409                               0,
2410                               &msg,
2411                               intf,
2412                               NULL,
2413                               NULL,
2414                               0,
2415                               intf->addrinfo[0].address,
2416                               intf->addrinfo[0].lun,
2417                               -1, 0);
2418 }
2419
2420 static int __get_device_id(struct ipmi_smi *intf, struct bmc_device *bmc)
2421 {
2422         int rv;
2423
2424         bmc->dyn_id_set = 2;
2425
2426         intf->null_user_handler = bmc_device_id_handler;
2427
2428         rv = send_get_device_id_cmd(intf);
2429         if (rv)
2430                 return rv;
2431
2432         wait_event(intf->waitq, bmc->dyn_id_set != 2);
2433
2434         if (!bmc->dyn_id_set)
2435                 rv = -EIO; /* Something went wrong in the fetch. */
2436
2437         /* dyn_id_set makes the id data available. */
2438         smp_rmb();
2439
2440         intf->null_user_handler = NULL;
2441
2442         return rv;
2443 }
2444
2445 /*
2446  * Fetch the device id for the bmc/interface.  You must pass in either
2447  * bmc or intf, this code will get the other one.  If the data has
2448  * been recently fetched, this will just use the cached data.  Otherwise
2449  * it will run a new fetch.
2450  *
2451  * Except for the first time this is called (in ipmi_add_smi()),
2452  * this will always return good data;
2453  */
2454 static int __bmc_get_device_id(struct ipmi_smi *intf, struct bmc_device *bmc,
2455                                struct ipmi_device_id *id,
2456                                bool *guid_set, guid_t *guid, int intf_num)
2457 {
2458         int rv = 0;
2459         int prev_dyn_id_set, prev_guid_set;
2460         bool intf_set = intf != NULL;
2461
2462         if (!intf) {
2463                 mutex_lock(&bmc->dyn_mutex);
2464 retry_bmc_lock:
2465                 if (list_empty(&bmc->intfs)) {
2466                         mutex_unlock(&bmc->dyn_mutex);
2467                         return -ENOENT;
2468                 }
2469                 intf = list_first_entry(&bmc->intfs, struct ipmi_smi,
2470                                         bmc_link);
2471                 kref_get(&intf->refcount);
2472                 mutex_unlock(&bmc->dyn_mutex);
2473                 mutex_lock(&intf->bmc_reg_mutex);
2474                 mutex_lock(&bmc->dyn_mutex);
2475                 if (intf != list_first_entry(&bmc->intfs, struct ipmi_smi,
2476                                              bmc_link)) {
2477                         mutex_unlock(&intf->bmc_reg_mutex);
2478                         kref_put(&intf->refcount, intf_free);
2479                         goto retry_bmc_lock;
2480                 }
2481         } else {
2482                 mutex_lock(&intf->bmc_reg_mutex);
2483                 bmc = intf->bmc;
2484                 mutex_lock(&bmc->dyn_mutex);
2485                 kref_get(&intf->refcount);
2486         }
2487
2488         /* If we have a valid and current ID, just return that. */
2489         if (intf->in_bmc_register ||
2490             (bmc->dyn_id_set && time_is_after_jiffies(bmc->dyn_id_expiry)))
2491                 goto out_noprocessing;
2492
2493         prev_guid_set = bmc->dyn_guid_set;
2494         __get_guid(intf);
2495
2496         prev_dyn_id_set = bmc->dyn_id_set;
2497         rv = __get_device_id(intf, bmc);
2498         if (rv)
2499                 goto out;
2500
2501         /*
2502          * The guid, device id, manufacturer id, and product id should
2503          * not change on a BMC.  If it does we have to do some dancing.
2504          */
2505         if (!intf->bmc_registered
2506             || (!prev_guid_set && bmc->dyn_guid_set)
2507             || (!prev_dyn_id_set && bmc->dyn_id_set)
2508             || (prev_guid_set && bmc->dyn_guid_set
2509                 && !guid_equal(&bmc->guid, &bmc->fetch_guid))
2510             || bmc->id.device_id != bmc->fetch_id.device_id
2511             || bmc->id.manufacturer_id != bmc->fetch_id.manufacturer_id
2512             || bmc->id.product_id != bmc->fetch_id.product_id) {
2513                 struct ipmi_device_id id = bmc->fetch_id;
2514                 int guid_set = bmc->dyn_guid_set;
2515                 guid_t guid;
2516
2517                 guid = bmc->fetch_guid;
2518                 mutex_unlock(&bmc->dyn_mutex);
2519
2520                 __ipmi_bmc_unregister(intf);
2521                 /* Fill in the temporary BMC for good measure. */
2522                 intf->bmc->id = id;
2523                 intf->bmc->dyn_guid_set = guid_set;
2524                 intf->bmc->guid = guid;
2525                 if (__ipmi_bmc_register(intf, &id, guid_set, &guid, intf_num))
2526                         need_waiter(intf); /* Retry later on an error. */
2527                 else
2528                         __scan_channels(intf, &id);
2529
2530
2531                 if (!intf_set) {
2532                         /*
2533                          * We weren't given the interface on the
2534                          * command line, so restart the operation on
2535                          * the next interface for the BMC.
2536                          */
2537                         mutex_unlock(&intf->bmc_reg_mutex);
2538                         mutex_lock(&bmc->dyn_mutex);
2539                         goto retry_bmc_lock;
2540                 }
2541
2542                 /* We have a new BMC, set it up. */
2543                 bmc = intf->bmc;
2544                 mutex_lock(&bmc->dyn_mutex);
2545                 goto out_noprocessing;
2546         } else if (memcmp(&bmc->fetch_id, &bmc->id, sizeof(bmc->id)))
2547                 /* Version info changes, scan the channels again. */
2548                 __scan_channels(intf, &bmc->fetch_id);
2549
2550         bmc->dyn_id_expiry = jiffies + IPMI_DYN_DEV_ID_EXPIRY;
2551
2552 out:
2553         if (rv && prev_dyn_id_set) {
2554                 rv = 0; /* Ignore failures if we have previous data. */
2555                 bmc->dyn_id_set = prev_dyn_id_set;
2556         }
2557         if (!rv) {
2558                 bmc->id = bmc->fetch_id;
2559                 if (bmc->dyn_guid_set)
2560                         bmc->guid = bmc->fetch_guid;
2561                 else if (prev_guid_set)
2562                         /*
2563                          * The guid used to be valid and it failed to fetch,
2564                          * just use the cached value.
2565                          */
2566                         bmc->dyn_guid_set = prev_guid_set;
2567         }
2568 out_noprocessing:
2569         if (!rv) {
2570                 if (id)
2571                         *id = bmc->id;
2572
2573                 if (guid_set)
2574                         *guid_set = bmc->dyn_guid_set;
2575
2576                 if (guid && bmc->dyn_guid_set)
2577                         *guid =  bmc->guid;
2578         }
2579
2580         mutex_unlock(&bmc->dyn_mutex);
2581         mutex_unlock(&intf->bmc_reg_mutex);
2582
2583         kref_put(&intf->refcount, intf_free);
2584         return rv;
2585 }
2586
2587 static int bmc_get_device_id(struct ipmi_smi *intf, struct bmc_device *bmc,
2588                              struct ipmi_device_id *id,
2589                              bool *guid_set, guid_t *guid)
2590 {
2591         return __bmc_get_device_id(intf, bmc, id, guid_set, guid, -1);
2592 }
2593
2594 static ssize_t device_id_show(struct device *dev,
2595                               struct device_attribute *attr,
2596                               char *buf)
2597 {
2598         struct bmc_device *bmc = to_bmc_device(dev);
2599         struct ipmi_device_id id;
2600         int rv;
2601
2602         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2603         if (rv)
2604                 return rv;
2605
2606         return snprintf(buf, 10, "%u\n", id.device_id);
2607 }
2608 static DEVICE_ATTR_RO(device_id);
2609
2610 static ssize_t provides_device_sdrs_show(struct device *dev,
2611                                          struct device_attribute *attr,
2612                                          char *buf)
2613 {
2614         struct bmc_device *bmc = to_bmc_device(dev);
2615         struct ipmi_device_id id;
2616         int rv;
2617
2618         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2619         if (rv)
2620                 return rv;
2621
2622         return snprintf(buf, 10, "%u\n", (id.device_revision & 0x80) >> 7);
2623 }
2624 static DEVICE_ATTR_RO(provides_device_sdrs);
2625
2626 static ssize_t revision_show(struct device *dev, struct device_attribute *attr,
2627                              char *buf)
2628 {
2629         struct bmc_device *bmc = to_bmc_device(dev);
2630         struct ipmi_device_id id;
2631         int rv;
2632
2633         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2634         if (rv)
2635                 return rv;
2636
2637         return snprintf(buf, 20, "%u\n", id.device_revision & 0x0F);
2638 }
2639 static DEVICE_ATTR_RO(revision);
2640
2641 static ssize_t firmware_revision_show(struct device *dev,
2642                                       struct device_attribute *attr,
2643                                       char *buf)
2644 {
2645         struct bmc_device *bmc = to_bmc_device(dev);
2646         struct ipmi_device_id id;
2647         int rv;
2648
2649         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2650         if (rv)
2651                 return rv;
2652
2653         return snprintf(buf, 20, "%u.%x\n", id.firmware_revision_1,
2654                         id.firmware_revision_2);
2655 }
2656 static DEVICE_ATTR_RO(firmware_revision);
2657
2658 static ssize_t ipmi_version_show(struct device *dev,
2659                                  struct device_attribute *attr,
2660                                  char *buf)
2661 {
2662         struct bmc_device *bmc = to_bmc_device(dev);
2663         struct ipmi_device_id id;
2664         int rv;
2665
2666         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2667         if (rv)
2668                 return rv;
2669
2670         return snprintf(buf, 20, "%u.%u\n",
2671                         ipmi_version_major(&id),
2672                         ipmi_version_minor(&id));
2673 }
2674 static DEVICE_ATTR_RO(ipmi_version);
2675
2676 static ssize_t add_dev_support_show(struct device *dev,
2677                                     struct device_attribute *attr,
2678                                     char *buf)
2679 {
2680         struct bmc_device *bmc = to_bmc_device(dev);
2681         struct ipmi_device_id id;
2682         int rv;
2683
2684         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2685         if (rv)
2686                 return rv;
2687
2688         return snprintf(buf, 10, "0x%02x\n", id.additional_device_support);
2689 }
2690 static DEVICE_ATTR(additional_device_support, S_IRUGO, add_dev_support_show,
2691                    NULL);
2692
2693 static ssize_t manufacturer_id_show(struct device *dev,
2694                                     struct device_attribute *attr,
2695                                     char *buf)
2696 {
2697         struct bmc_device *bmc = to_bmc_device(dev);
2698         struct ipmi_device_id id;
2699         int rv;
2700
2701         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2702         if (rv)
2703                 return rv;
2704
2705         return snprintf(buf, 20, "0x%6.6x\n", id.manufacturer_id);
2706 }
2707 static DEVICE_ATTR_RO(manufacturer_id);
2708
2709 static ssize_t product_id_show(struct device *dev,
2710                                struct device_attribute *attr,
2711                                char *buf)
2712 {
2713         struct bmc_device *bmc = to_bmc_device(dev);
2714         struct ipmi_device_id id;
2715         int rv;
2716
2717         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2718         if (rv)
2719                 return rv;
2720
2721         return snprintf(buf, 10, "0x%4.4x\n", id.product_id);
2722 }
2723 static DEVICE_ATTR_RO(product_id);
2724
2725 static ssize_t aux_firmware_rev_show(struct device *dev,
2726                                      struct device_attribute *attr,
2727                                      char *buf)
2728 {
2729         struct bmc_device *bmc = to_bmc_device(dev);
2730         struct ipmi_device_id id;
2731         int rv;
2732
2733         rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2734         if (rv)
2735                 return rv;
2736
2737         return snprintf(buf, 21, "0x%02x 0x%02x 0x%02x 0x%02x\n",
2738                         id.aux_firmware_revision[3],
2739                         id.aux_firmware_revision[2],
2740                         id.aux_firmware_revision[1],
2741                         id.aux_firmware_revision[0]);
2742 }
2743 static DEVICE_ATTR(aux_firmware_revision, S_IRUGO, aux_firmware_rev_show, NULL);
2744
2745 static ssize_t guid_show(struct device *dev, struct device_attribute *attr,
2746                          char *buf)
2747 {
2748         struct bmc_device *bmc = to_bmc_device(dev);
2749         bool guid_set;
2750         guid_t guid;
2751         int rv;
2752
2753         rv = bmc_get_device_id(NULL, bmc, NULL, &guid_set, &guid);
2754         if (rv)
2755                 return rv;
2756         if (!guid_set)
2757                 return -ENOENT;
2758
2759         return snprintf(buf, UUID_STRING_LEN + 1 + 1, "%pUl\n", &guid);
2760 }
2761 static DEVICE_ATTR_RO(guid);
2762
2763 static struct attribute *bmc_dev_attrs[] = {
2764         &dev_attr_device_id.attr,
2765         &dev_attr_provides_device_sdrs.attr,
2766         &dev_attr_revision.attr,
2767         &dev_attr_firmware_revision.attr,
2768         &dev_attr_ipmi_version.attr,
2769         &dev_attr_additional_device_support.attr,
2770         &dev_attr_manufacturer_id.attr,
2771         &dev_attr_product_id.attr,
2772         &dev_attr_aux_firmware_revision.attr,
2773         &dev_attr_guid.attr,
2774         NULL
2775 };
2776
2777 static umode_t bmc_dev_attr_is_visible(struct kobject *kobj,
2778                                        struct attribute *attr, int idx)
2779 {
2780         struct device *dev = kobj_to_dev(kobj);
2781         struct bmc_device *bmc = to_bmc_device(dev);
2782         umode_t mode = attr->mode;
2783         int rv;
2784
2785         if (attr == &dev_attr_aux_firmware_revision.attr) {
2786                 struct ipmi_device_id id;
2787
2788                 rv = bmc_get_device_id(NULL, bmc, &id, NULL, NULL);
2789                 return (!rv && id.aux_firmware_revision_set) ? mode : 0;
2790         }
2791         if (attr == &dev_attr_guid.attr) {
2792                 bool guid_set;
2793
2794                 rv = bmc_get_device_id(NULL, bmc, NULL, &guid_set, NULL);
2795                 return (!rv && guid_set) ? mode : 0;
2796         }
2797         return mode;
2798 }
2799
2800 static const struct attribute_group bmc_dev_attr_group = {
2801         .attrs          = bmc_dev_attrs,
2802         .is_visible     = bmc_dev_attr_is_visible,
2803 };
2804
2805 static const struct attribute_group *bmc_dev_attr_groups[] = {
2806         &bmc_dev_attr_group,
2807         NULL
2808 };
2809
2810 static const struct device_type bmc_device_type = {
2811         .groups         = bmc_dev_attr_groups,
2812 };
2813
2814 static int __find_bmc_guid(struct device *dev, const void *data)
2815 {
2816         const guid_t *guid = data;
2817         struct bmc_device *bmc;
2818         int rv;
2819
2820         if (dev->type != &bmc_device_type)
2821                 return 0;
2822
2823         bmc = to_bmc_device(dev);
2824         rv = bmc->dyn_guid_set && guid_equal(&bmc->guid, guid);
2825         if (rv)
2826                 rv = kref_get_unless_zero(&bmc->usecount);
2827         return rv;
2828 }
2829
2830 /*
2831  * Returns with the bmc's usecount incremented, if it is non-NULL.
2832  */
2833 static struct bmc_device *ipmi_find_bmc_guid(struct device_driver *drv,
2834                                              guid_t *guid)
2835 {
2836         struct device *dev;
2837         struct bmc_device *bmc = NULL;
2838
2839         dev = driver_find_device(drv, NULL, guid, __find_bmc_guid);
2840         if (dev) {
2841                 bmc = to_bmc_device(dev);
2842                 put_device(dev);
2843         }
2844         return bmc;
2845 }
2846
2847 struct prod_dev_id {
2848         unsigned int  product_id;
2849         unsigned char device_id;
2850 };
2851
2852 static int __find_bmc_prod_dev_id(struct device *dev, const void *data)
2853 {
2854         const struct prod_dev_id *cid = data;
2855         struct bmc_device *bmc;
2856         int rv;
2857
2858         if (dev->type != &bmc_device_type)
2859                 return 0;
2860
2861         bmc = to_bmc_device(dev);
2862         rv = (bmc->id.product_id == cid->product_id
2863               && bmc->id.device_id == cid->device_id);
2864         if (rv)
2865                 rv = kref_get_unless_zero(&bmc->usecount);
2866         return rv;
2867 }
2868
2869 /*
2870  * Returns with the bmc's usecount incremented, if it is non-NULL.
2871  */
2872 static struct bmc_device *ipmi_find_bmc_prod_dev_id(
2873         struct device_driver *drv,
2874         unsigned int product_id, unsigned char device_id)
2875 {
2876         struct prod_dev_id id = {
2877                 .product_id = product_id,
2878                 .device_id = device_id,
2879         };
2880         struct device *dev;
2881         struct bmc_device *bmc = NULL;
2882
2883         dev = driver_find_device(drv, NULL, &id, __find_bmc_prod_dev_id);
2884         if (dev) {
2885                 bmc = to_bmc_device(dev);
2886                 put_device(dev);
2887         }
2888         return bmc;
2889 }
2890
2891 static DEFINE_IDA(ipmi_bmc_ida);
2892
2893 static void
2894 release_bmc_device(struct device *dev)
2895 {
2896         kfree(to_bmc_device(dev));
2897 }
2898
2899 static void cleanup_bmc_work(struct work_struct *work)
2900 {
2901         struct bmc_device *bmc = container_of(work, struct bmc_device,
2902                                               remove_work);
2903         int id = bmc->pdev.id; /* Unregister overwrites id */
2904
2905         platform_device_unregister(&bmc->pdev);
2906         ida_simple_remove(&ipmi_bmc_ida, id);
2907 }
2908
2909 static void
2910 cleanup_bmc_device(struct kref *ref)
2911 {
2912         struct bmc_device *bmc = container_of(ref, struct bmc_device, usecount);
2913
2914         /*
2915          * Remove the platform device in a work queue to avoid issues
2916          * with removing the device attributes while reading a device
2917          * attribute.
2918          */
2919         schedule_work(&bmc->remove_work);
2920 }
2921
2922 /*
2923  * Must be called with intf->bmc_reg_mutex held.
2924  */
2925 static void __ipmi_bmc_unregister(struct ipmi_smi *intf)
2926 {
2927         struct bmc_device *bmc = intf->bmc;
2928
2929         if (!intf->bmc_registered)
2930                 return;
2931
2932         sysfs_remove_link(&intf->si_dev->kobj, "bmc");
2933         sysfs_remove_link(&bmc->pdev.dev.kobj, intf->my_dev_name);
2934         kfree(intf->my_dev_name);
2935         intf->my_dev_name = NULL;
2936
2937         mutex_lock(&bmc->dyn_mutex);
2938         list_del(&intf->bmc_link);
2939         mutex_unlock(&bmc->dyn_mutex);
2940         intf->bmc = &intf->tmp_bmc;
2941         kref_put(&bmc->usecount, cleanup_bmc_device);
2942         intf->bmc_registered = false;
2943 }
2944
2945 static void ipmi_bmc_unregister(struct ipmi_smi *intf)
2946 {
2947         mutex_lock(&intf->bmc_reg_mutex);
2948         __ipmi_bmc_unregister(intf);
2949         mutex_unlock(&intf->bmc_reg_mutex);
2950 }
2951
2952 /*
2953  * Must be called with intf->bmc_reg_mutex held.
2954  */
2955 static int __ipmi_bmc_register(struct ipmi_smi *intf,
2956                                struct ipmi_device_id *id,
2957                                bool guid_set, guid_t *guid, int intf_num)
2958 {
2959         int               rv;
2960         struct bmc_device *bmc;
2961         struct bmc_device *old_bmc;
2962
2963         /*
2964          * platform_device_register() can cause bmc_reg_mutex to
2965          * be claimed because of the is_visible functions of
2966          * the attributes.  Eliminate possible recursion and
2967          * release the lock.
2968          */
2969         intf->in_bmc_register = true;
2970         mutex_unlock(&intf->bmc_reg_mutex);
2971
2972         /*
2973          * Try to find if there is an bmc_device struct
2974          * representing the interfaced BMC already
2975          */
2976         mutex_lock(&ipmidriver_mutex);
2977         if (guid_set)
2978                 old_bmc = ipmi_find_bmc_guid(&ipmidriver.driver, guid);
2979         else
2980                 old_bmc = ipmi_find_bmc_prod_dev_id(&ipmidriver.driver,
2981                                                     id->product_id,
2982                                                     id->device_id);
2983
2984         /*
2985          * If there is already an bmc_device, free the new one,
2986          * otherwise register the new BMC device
2987          */
2988         if (old_bmc) {
2989                 bmc = old_bmc;
2990                 /*
2991                  * Note: old_bmc already has usecount incremented by
2992                  * the BMC find functions.
2993                  */
2994                 intf->bmc = old_bmc;
2995                 mutex_lock(&bmc->dyn_mutex);
2996                 list_add_tail(&intf->bmc_link, &bmc->intfs);
2997                 mutex_unlock(&bmc->dyn_mutex);
2998
2999                 dev_info(intf->si_dev,
3000                          "interfacing existing BMC (man_id: 0x%6.6x, prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n",
3001                          bmc->id.manufacturer_id,
3002                          bmc->id.product_id,
3003                          bmc->id.device_id);
3004         } else {
3005                 bmc = kzalloc(sizeof(*bmc), GFP_KERNEL);
3006                 if (!bmc) {
3007                         rv = -ENOMEM;
3008                         goto out;
3009                 }
3010                 INIT_LIST_HEAD(&bmc->intfs);
3011                 mutex_init(&bmc->dyn_mutex);
3012                 INIT_WORK(&bmc->remove_work, cleanup_bmc_work);
3013
3014                 bmc->id = *id;
3015                 bmc->dyn_id_set = 1;
3016                 bmc->dyn_guid_set = guid_set;
3017                 bmc->guid = *guid;
3018                 bmc->dyn_id_expiry = jiffies + IPMI_DYN_DEV_ID_EXPIRY;
3019
3020                 bmc->pdev.name = "ipmi_bmc";
3021
3022                 rv = ida_simple_get(&ipmi_bmc_ida, 0, 0, GFP_KERNEL);
3023                 if (rv < 0) {
3024                         kfree(bmc);
3025                         goto out;
3026                 }
3027
3028                 bmc->pdev.dev.driver = &ipmidriver.driver;
3029                 bmc->pdev.id = rv;
3030                 bmc->pdev.dev.release = release_bmc_device;
3031                 bmc->pdev.dev.type = &bmc_device_type;
3032                 kref_init(&bmc->usecount);
3033
3034                 intf->bmc = bmc;
3035                 mutex_lock(&bmc->dyn_mutex);
3036                 list_add_tail(&intf->bmc_link, &bmc->intfs);
3037                 mutex_unlock(&bmc->dyn_mutex);
3038
3039                 rv = platform_device_register(&bmc->pdev);
3040                 if (rv) {
3041                         dev_err(intf->si_dev,
3042                                 "Unable to register bmc device: %d\n",
3043                                 rv);
3044                         goto out_list_del;
3045                 }
3046
3047                 dev_info(intf->si_dev,
3048                          "Found new BMC (man_id: 0x%6.6x, prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n",
3049                          bmc->id.manufacturer_id,
3050                          bmc->id.product_id,
3051                          bmc->id.device_id);
3052         }
3053
3054         /*
3055          * create symlink from system interface device to bmc device
3056          * and back.
3057          */
3058         rv = sysfs_create_link(&intf->si_dev->kobj, &bmc->pdev.dev.kobj, "bmc");
3059         if (rv) {
3060                 dev_err(intf->si_dev, "Unable to create bmc symlink: %d\n", rv);
3061                 goto out_put_bmc;
3062         }
3063
3064         if (intf_num == -1)
3065                 intf_num = intf->intf_num;
3066         intf->my_dev_name = kasprintf(GFP_KERNEL, "ipmi%d", intf_num);
3067         if (!intf->my_dev_name) {
3068                 rv = -ENOMEM;
3069                 dev_err(intf->si_dev, "Unable to allocate link from BMC: %d\n",
3070                         rv);
3071                 goto out_unlink1;
3072         }
3073
3074         rv = sysfs_create_link(&bmc->pdev.dev.kobj, &intf->si_dev->kobj,
3075                                intf->my_dev_name);
3076         if (rv) {
3077                 kfree(intf->my_dev_name);
3078                 intf->my_dev_name = NULL;
3079                 dev_err(intf->si_dev, "Unable to create symlink to bmc: %d\n",
3080                         rv);
3081                 goto out_free_my_dev_name;
3082         }
3083
3084         intf->bmc_registered = true;
3085
3086 out:
3087         mutex_unlock(&ipmidriver_mutex);
3088         mutex_lock(&intf->bmc_reg_mutex);
3089         intf->in_bmc_register = false;
3090         return rv;
3091
3092
3093 out_free_my_dev_name:
3094         kfree(intf->my_dev_name);
3095         intf->my_dev_name = NULL;
3096
3097 out_unlink1:
3098         sysfs_remove_link(&intf->si_dev->kobj, "bmc");
3099
3100 out_put_bmc:
3101         mutex_lock(&bmc->dyn_mutex);
3102         list_del(&intf->bmc_link);
3103         mutex_unlock(&bmc->dyn_mutex);
3104         intf->bmc = &intf->tmp_bmc;
3105         kref_put(&bmc->usecount, cleanup_bmc_device);
3106         goto out;
3107
3108 out_list_del:
3109         mutex_lock(&bmc->dyn_mutex);
3110         list_del(&intf->bmc_link);
3111         mutex_unlock(&bmc->dyn_mutex);
3112         intf->bmc = &intf->tmp_bmc;
3113         put_device(&bmc->pdev.dev);
3114         goto out;
3115 }
3116
3117 static int
3118 send_guid_cmd(struct ipmi_smi *intf, int chan)
3119 {
3120         struct kernel_ipmi_msg            msg;
3121         struct ipmi_system_interface_addr si;
3122
3123         si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
3124         si.channel = IPMI_BMC_CHANNEL;
3125         si.lun = 0;
3126
3127         msg.netfn = IPMI_NETFN_APP_REQUEST;
3128         msg.cmd = IPMI_GET_DEVICE_GUID_CMD;
3129         msg.data = NULL;
3130         msg.data_len = 0;
3131         return i_ipmi_request(NULL,
3132                               intf,
3133                               (struct ipmi_addr *) &si,
3134                               0,
3135                               &msg,
3136                               intf,
3137                               NULL,
3138                               NULL,
3139                               0,
3140                               intf->addrinfo[0].address,
3141                               intf->addrinfo[0].lun,
3142                               -1, 0);
3143 }
3144
3145 static void guid_handler(struct ipmi_smi *intf, struct ipmi_recv_msg *msg)
3146 {
3147         struct bmc_device *bmc = intf->bmc;
3148
3149         if ((msg->addr.addr_type != IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
3150             || (msg->msg.netfn != IPMI_NETFN_APP_RESPONSE)
3151             || (msg->msg.cmd != IPMI_GET_DEVICE_GUID_CMD))
3152                 /* Not for me */
3153                 return;
3154
3155         if (msg->msg.data[0] != 0) {
3156                 /* Error from getting the GUID, the BMC doesn't have one. */
3157                 bmc->dyn_guid_set = 0;
3158                 goto out;
3159         }
3160
3161         if (msg->msg.data_len < UUID_SIZE + 1) {
3162                 bmc->dyn_guid_set = 0;
3163                 dev_warn(intf->si_dev,
3164                          "The GUID response from the BMC was too short, it was %d but should have been %d.  Assuming GUID is not available.\n",
3165                          msg->msg.data_len, UUID_SIZE + 1);
3166                 goto out;
3167         }
3168
3169         guid_copy(&bmc->fetch_guid, (guid_t *)(msg->msg.data + 1));
3170         /*
3171          * Make sure the guid data is available before setting
3172          * dyn_guid_set.
3173          */
3174         smp_wmb();
3175         bmc->dyn_guid_set = 1;
3176  out:
3177         wake_up(&intf->waitq);
3178 }
3179
3180 static void __get_guid(struct ipmi_smi *intf)
3181 {
3182         int rv;
3183         struct bmc_device *bmc = intf->bmc;
3184
3185         bmc->dyn_guid_set = 2;
3186         intf->null_user_handler = guid_handler;
3187         rv = send_guid_cmd(intf, 0);
3188         if (rv)
3189                 /* Send failed, no GUID available. */
3190                 bmc->dyn_guid_set = 0;
3191
3192         wait_event(intf->waitq, bmc->dyn_guid_set != 2);
3193
3194         /* dyn_guid_set makes the guid data available. */
3195         smp_rmb();
3196
3197         intf->null_user_handler = NULL;
3198 }
3199
3200 static int
3201 send_channel_info_cmd(struct ipmi_smi *intf, int chan)
3202 {
3203         struct kernel_ipmi_msg            msg;
3204         unsigned char                     data[1];
3205         struct ipmi_system_interface_addr si;
3206
3207         si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
3208         si.channel = IPMI_BMC_CHANNEL;
3209         si.lun = 0;
3210
3211         msg.netfn = IPMI_NETFN_APP_REQUEST;
3212         msg.cmd = IPMI_GET_CHANNEL_INFO_CMD;
3213         msg.data = data;
3214         msg.data_len = 1;
3215         data[0] = chan;
3216         return i_ipmi_request(NULL,
3217                               intf,
3218                               (struct ipmi_addr *) &si,
3219                               0,
3220                               &msg,
3221                               intf,
3222                               NULL,
3223                               NULL,
3224                               0,
3225                               intf->addrinfo[0].address,
3226                               intf->addrinfo[0].lun,
3227                               -1, 0);
3228 }
3229
3230 static void
3231 channel_handler(struct ipmi_smi *intf, struct ipmi_recv_msg *msg)
3232 {
3233         int rv = 0;
3234         int ch;
3235         unsigned int set = intf->curr_working_cset;
3236         struct ipmi_channel *chans;
3237
3238         if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
3239             && (msg->msg.netfn == IPMI_NETFN_APP_RESPONSE)
3240             && (msg->msg.cmd == IPMI_GET_CHANNEL_INFO_CMD)) {
3241                 /* It's the one we want */
3242                 if (msg->msg.data[0] != 0) {
3243                         /* Got an error from the channel, just go on. */
3244
3245                         if (msg->msg.data[0] == IPMI_INVALID_COMMAND_ERR) {
3246                                 /*
3247                                  * If the MC does not support this
3248                                  * command, that is legal.  We just
3249                                  * assume it has one IPMB at channel
3250                                  * zero.
3251                                  */
3252                                 intf->wchannels[set].c[0].medium
3253                                         = IPMI_CHANNEL_MEDIUM_IPMB;
3254                                 intf->wchannels[set].c[0].protocol
3255                                         = IPMI_CHANNEL_PROTOCOL_IPMB;
3256
3257                                 intf->channel_list = intf->wchannels + set;
3258                                 intf->channels_ready = true;
3259                                 wake_up(&intf->waitq);
3260                                 goto out;
3261                         }
3262                         goto next_channel;
3263                 }
3264                 if (msg->msg.data_len < 4) {
3265                         /* Message not big enough, just go on. */
3266                         goto next_channel;
3267                 }
3268                 ch = intf->curr_channel;
3269                 chans = intf->wchannels[set].c;
3270                 chans[ch].medium = msg->msg.data[2] & 0x7f;
3271                 chans[ch].protocol = msg->msg.data[3] & 0x1f;
3272
3273  next_channel:
3274                 intf->curr_channel++;
3275                 if (intf->curr_channel >= IPMI_MAX_CHANNELS) {
3276                         intf->channel_list = intf->wchannels + set;
3277                         intf->channels_ready = true;
3278                         wake_up(&intf->waitq);
3279                 } else {
3280                         intf->channel_list = intf->wchannels + set;
3281                         intf->channels_ready = true;
3282                         rv = send_channel_info_cmd(intf, intf->curr_channel);
3283                 }
3284
3285                 if (rv) {
3286                         /* Got an error somehow, just give up. */
3287                         dev_warn(intf->si_dev,
3288                                  "Error sending channel information for channel %d: %d\n",
3289                                  intf->curr_channel, rv);
3290
3291                         intf->channel_list = intf->wchannels + set;
3292                         intf->channels_ready = true;
3293                         wake_up(&intf->waitq);
3294                 }
3295         }
3296  out:
3297         return;
3298 }
3299
3300 /*
3301  * Must be holding intf->bmc_reg_mutex to call this.
3302  */
3303 static int __scan_channels(struct ipmi_smi *intf, struct ipmi_device_id *id)
3304 {
3305         int rv;
3306
3307         if (ipmi_version_major(id) > 1
3308                         || (ipmi_version_major(id) == 1
3309                             && ipmi_version_minor(id) >= 5)) {
3310                 unsigned int set;
3311
3312                 /*
3313                  * Start scanning the channels to see what is
3314                  * available.
3315                  */
3316                 set = !intf->curr_working_cset;
3317                 intf->curr_working_cset = set;
3318                 memset(&intf->wchannels[set], 0,
3319                        sizeof(struct ipmi_channel_set));
3320
3321                 intf->null_user_handler = channel_handler;
3322                 intf->curr_channel = 0;
3323                 rv = send_channel_info_cmd(intf, 0);
3324                 if (rv) {
3325                         dev_warn(intf->si_dev,
3326                                  "Error sending channel information for channel 0, %d\n",
3327                                  rv);
3328                         return -EIO;
3329                 }
3330
3331                 /* Wait for the channel info to be read. */
3332                 wait_event(intf->waitq, intf->channels_ready);
3333                 intf->null_user_handler = NULL;
3334         } else {
3335                 unsigned int set = intf->curr_working_cset;
3336
3337                 /* Assume a single IPMB channel at zero. */
3338                 intf->wchannels[set].c[0].medium = IPMI_CHANNEL_MEDIUM_IPMB;
3339                 intf->wchannels[set].c[0].protocol = IPMI_CHANNEL_PROTOCOL_IPMB;
3340                 intf->channel_list = intf->wchannels + set;
3341                 intf->channels_ready = true;
3342         }
3343
3344         return 0;
3345 }
3346
3347 static void ipmi_poll(struct ipmi_smi *intf)
3348 {
3349         if (intf->handlers->poll)
3350                 intf->handlers->poll(intf->send_info);
3351         /* In case something came in */
3352         handle_new_recv_msgs(intf);
3353 }
3354
3355 void ipmi_poll_interface(struct ipmi_user *user)
3356 {
3357         ipmi_poll(user->intf);
3358 }
3359 EXPORT_SYMBOL(ipmi_poll_interface);
3360
3361 static void redo_bmc_reg(struct work_struct *work)
3362 {
3363         struct ipmi_smi *intf = container_of(work, struct ipmi_smi,
3364                                              bmc_reg_work);
3365
3366         if (!intf->in_shutdown)
3367                 bmc_get_device_id(intf, NULL, NULL, NULL, NULL);
3368
3369         kref_put(&intf->refcount, intf_free);
3370 }
3371
3372 int ipmi_add_smi(struct module         *owner,
3373                  const struct ipmi_smi_handlers *handlers,
3374                  void                  *send_info,
3375                  struct device         *si_dev,
3376                  unsigned char         slave_addr)
3377 {
3378         int              i, j;
3379         int              rv;
3380         struct ipmi_smi *intf, *tintf;
3381         struct list_head *link;
3382         struct ipmi_device_id id;
3383
3384         /*
3385          * Make sure the driver is actually initialized, this handles
3386          * problems with initialization order.
3387          */
3388         rv = ipmi_init_msghandler();
3389         if (rv)
3390                 return rv;
3391
3392         intf = kzalloc(sizeof(*intf), GFP_KERNEL);
3393         if (!intf)
3394                 return -ENOMEM;
3395
3396         rv = init_srcu_struct(&intf->users_srcu);
3397         if (rv) {
3398                 kfree(intf);
3399                 return rv;
3400         }
3401
3402         intf->owner = owner;
3403         intf->bmc = &intf->tmp_bmc;
3404         INIT_LIST_HEAD(&intf->bmc->intfs);
3405         mutex_init(&intf->bmc->dyn_mutex);
3406         INIT_LIST_HEAD(&intf->bmc_link);
3407         mutex_init(&intf->bmc_reg_mutex);
3408         intf->intf_num = -1; /* Mark it invalid for now. */
3409         kref_init(&intf->refcount);
3410         INIT_WORK(&intf->bmc_reg_work, redo_bmc_reg);
3411         intf->si_dev = si_dev;
3412         for (j = 0; j < IPMI_MAX_CHANNELS; j++) {
3413                 intf->addrinfo[j].address = IPMI_BMC_SLAVE_ADDR;
3414                 intf->addrinfo[j].lun = 2;
3415         }
3416         if (slave_addr != 0)
3417                 intf->addrinfo[0].address = slave_addr;
3418         INIT_LIST_HEAD(&intf->users);
3419         intf->handlers = handlers;
3420         intf->send_info = send_info;
3421         spin_lock_init(&intf->seq_lock);
3422         for (j = 0; j < IPMI_IPMB_NUM_SEQ; j++) {
3423                 intf->seq_table[j].inuse = 0;
3424                 intf->seq_table[j].seqid = 0;
3425         }
3426         intf->curr_seq = 0;
3427         spin_lock_init(&intf->waiting_rcv_msgs_lock);
3428         INIT_LIST_HEAD(&intf->waiting_rcv_msgs);
3429         tasklet_init(&intf->recv_tasklet,
3430                      smi_recv_tasklet,
3431                      (unsigned long) intf);
3432         atomic_set(&intf->watchdog_pretimeouts_to_deliver, 0);
3433         spin_lock_init(&intf->xmit_msgs_lock);
3434         INIT_LIST_HEAD(&intf->xmit_msgs);
3435         INIT_LIST_HEAD(&intf->hp_xmit_msgs);
3436         spin_lock_init(&intf->events_lock);
3437         spin_lock_init(&intf->watch_lock);
3438         atomic_set(&intf->event_waiters, 0);
3439         intf->ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
3440         INIT_LIST_HEAD(&intf->waiting_events);
3441         intf->waiting_events_count = 0;
3442         mutex_init(&intf->cmd_rcvrs_mutex);
3443         spin_lock_init(&intf->maintenance_mode_lock);
3444         INIT_LIST_HEAD(&intf->cmd_rcvrs);
3445         init_waitqueue_head(&intf->waitq);
3446         for (i = 0; i < IPMI_NUM_STATS; i++)
3447                 atomic_set(&intf->stats[i], 0);
3448
3449         mutex_lock(&ipmi_interfaces_mutex);
3450         /* Look for a hole in the numbers. */
3451         i = 0;
3452         link = &ipmi_interfaces;
3453         list_for_each_entry_rcu(tintf, &ipmi_interfaces, link) {
3454                 if (tintf->intf_num != i) {
3455                         link = &tintf->link;
3456                         break;
3457                 }
3458                 i++;
3459         }
3460         /* Add the new interface in numeric order. */
3461         if (i == 0)
3462                 list_add_rcu(&intf->link, &ipmi_interfaces);
3463         else
3464                 list_add_tail_rcu(&intf->link, link);
3465
3466         rv = handlers->start_processing(send_info, intf);
3467         if (rv)
3468                 goto out_err;
3469
3470         rv = __bmc_get_device_id(intf, NULL, &id, NULL, NULL, i);
3471         if (rv) {
3472                 dev_err(si_dev, "Unable to get the device id: %d\n", rv);
3473                 goto out_err_started;
3474         }
3475
3476         mutex_lock(&intf->bmc_reg_mutex);
3477         rv = __scan_channels(intf, &id);
3478         mutex_unlock(&intf->bmc_reg_mutex);
3479         if (rv)
3480                 goto out_err_bmc_reg;
3481
3482         /*
3483          * Keep memory order straight for RCU readers.  Make
3484          * sure everything else is committed to memory before
3485          * setting intf_num to mark the interface valid.
3486          */
3487         smp_wmb();
3488         intf->intf_num = i;
3489         mutex_unlock(&ipmi_interfaces_mutex);
3490
3491         /* After this point the interface is legal to use. */
3492         call_smi_watchers(i, intf->si_dev);
3493
3494         return 0;
3495
3496  out_err_bmc_reg:
3497         ipmi_bmc_unregister(intf);
3498  out_err_started:
3499         if (intf->handlers->shutdown)
3500                 intf->handlers->shutdown(intf->send_info);
3501  out_err:
3502         list_del_rcu(&intf->link);
3503         mutex_unlock(&ipmi_interfaces_mutex);
3504         synchronize_srcu(&ipmi_interfaces_srcu);
3505         cleanup_srcu_struct(&intf->users_srcu);
3506         kref_put(&intf->refcount, intf_free);
3507
3508         return rv;
3509 }
3510 EXPORT_SYMBOL(ipmi_add_smi);
3511
3512 static void deliver_smi_err_response(struct ipmi_smi *intf,
3513                                      struct ipmi_smi_msg *msg,
3514                                      unsigned char err)
3515 {
3516         msg->rsp[0] = msg->data[0] | 4;
3517         msg->rsp[1] = msg->data[1];
3518         msg->rsp[2] = err;
3519         msg->rsp_size = 3;
3520         /* It's an error, so it will never requeue, no need to check return. */
3521         handle_one_recv_msg(intf, msg);
3522 }
3523
3524 static void cleanup_smi_msgs(struct ipmi_smi *intf)
3525 {
3526         int              i;
3527         struct seq_table *ent;
3528         struct ipmi_smi_msg *msg;
3529         struct list_head *entry;
3530         struct list_head tmplist;
3531
3532         /* Clear out our transmit queues and hold the messages. */
3533         INIT_LIST_HEAD(&tmplist);
3534         list_splice_tail(&intf->hp_xmit_msgs, &tmplist);
3535         list_splice_tail(&intf->xmit_msgs, &tmplist);
3536
3537         /* Current message first, to preserve order */
3538         while (intf->curr_msg && !list_empty(&intf->waiting_rcv_msgs)) {
3539                 /* Wait for the message to clear out. */
3540                 schedule_timeout(1);
3541         }
3542
3543         /* No need for locks, the interface is down. */
3544
3545         /*
3546          * Return errors for all pending messages in queue and in the
3547          * tables waiting for remote responses.
3548          */
3549         while (!list_empty(&tmplist)) {
3550                 entry = tmplist.next;
3551                 list_del(entry);
3552                 msg = list_entry(entry, struct ipmi_smi_msg, link);
3553                 deliver_smi_err_response(intf, msg, IPMI_ERR_UNSPECIFIED);
3554         }
3555
3556         for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
3557                 ent = &intf->seq_table[i];
3558                 if (!ent->inuse)
3559                         continue;
3560                 deliver_err_response(intf, ent->recv_msg, IPMI_ERR_UNSPECIFIED);
3561         }
3562 }
3563
3564 void ipmi_unregister_smi(struct ipmi_smi *intf)
3565 {
3566         struct ipmi_smi_watcher *w;
3567         int intf_num = intf->intf_num, index;
3568
3569         mutex_lock(&ipmi_interfaces_mutex);
3570         intf->intf_num = -1;
3571         intf->in_shutdown = true;
3572         list_del_rcu(&intf->link);
3573         mutex_unlock(&ipmi_interfaces_mutex);
3574         synchronize_srcu(&ipmi_interfaces_srcu);
3575
3576         /* At this point no users can be added to the interface. */
3577
3578         /*
3579          * Call all the watcher interfaces to tell them that
3580          * an interface is going away.
3581          */
3582         mutex_lock(&smi_watchers_mutex);
3583         list_for_each_entry(w, &smi_watchers, link)
3584                 w->smi_gone(intf_num);
3585         mutex_unlock(&smi_watchers_mutex);
3586
3587         index = srcu_read_lock(&intf->users_srcu);
3588         while (!list_empty(&intf->users)) {
3589                 struct ipmi_user *user =
3590                         container_of(list_next_rcu(&intf->users),
3591                                      struct ipmi_user, link);
3592
3593                 _ipmi_destroy_user(user);
3594         }
3595         srcu_read_unlock(&intf->users_srcu, index);
3596
3597         if (intf->handlers->shutdown)
3598                 intf->handlers->shutdown(intf->send_info);
3599
3600         cleanup_smi_msgs(intf);
3601
3602         ipmi_bmc_unregister(intf);
3603
3604         cleanup_srcu_struct(&intf->users_srcu);
3605         kref_put(&intf->refcount, intf_free);
3606 }
3607 EXPORT_SYMBOL(ipmi_unregister_smi);
3608
3609 static int handle_ipmb_get_msg_rsp(struct ipmi_smi *intf,
3610                                    struct ipmi_smi_msg *msg)
3611 {
3612         struct ipmi_ipmb_addr ipmb_addr;
3613         struct ipmi_recv_msg  *recv_msg;
3614
3615         /*
3616          * This is 11, not 10, because the response must contain a
3617          * completion code.
3618          */
3619         if (msg->rsp_size < 11) {
3620                 /* Message not big enough, just ignore it. */
3621                 ipmi_inc_stat(intf, invalid_ipmb_responses);
3622                 return 0;
3623         }
3624
3625         if (msg->rsp[2] != 0) {
3626                 /* An error getting the response, just ignore it. */
3627                 return 0;
3628         }
3629
3630         ipmb_addr.addr_type = IPMI_IPMB_ADDR_TYPE;
3631         ipmb_addr.slave_addr = msg->rsp[6];
3632         ipmb_addr.channel = msg->rsp[3] & 0x0f;
3633         ipmb_addr.lun = msg->rsp[7] & 3;
3634
3635         /*
3636          * It's a response from a remote entity.  Look up the sequence
3637          * number and handle the response.
3638          */
3639         if (intf_find_seq(intf,
3640                           msg->rsp[7] >> 2,
3641                           msg->rsp[3] & 0x0f,
3642                           msg->rsp[8],
3643                           (msg->rsp[4] >> 2) & (~1),
3644                           (struct ipmi_addr *) &ipmb_addr,
3645                           &recv_msg)) {
3646                 /*
3647                  * We were unable to find the sequence number,
3648                  * so just nuke the message.
3649                  */
3650                 ipmi_inc_stat(intf, unhandled_ipmb_responses);
3651                 return 0;
3652         }
3653
3654         memcpy(recv_msg->msg_data, &msg->rsp[9], msg->rsp_size - 9);
3655         /*
3656          * The other fields matched, so no need to set them, except
3657          * for netfn, which needs to be the response that was
3658          * returned, not the request value.
3659          */
3660         recv_msg->msg.netfn = msg->rsp[4] >> 2;
3661         recv_msg->msg.data = recv_msg->msg_data;
3662         recv_msg->msg.data_len = msg->rsp_size - 10;
3663         recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
3664         if (deliver_response(intf, recv_msg))
3665                 ipmi_inc_stat(intf, unhandled_ipmb_responses);
3666         else
3667                 ipmi_inc_stat(intf, handled_ipmb_responses);
3668
3669         return 0;
3670 }
3671
3672 static int handle_ipmb_get_msg_cmd(struct ipmi_smi *intf,
3673                                    struct ipmi_smi_msg *msg)
3674 {
3675         struct cmd_rcvr          *rcvr;
3676         int                      rv = 0;
3677         unsigned char            netfn;
3678         unsigned char            cmd;
3679         unsigned char            chan;
3680         struct ipmi_user         *user = NULL;
3681         struct ipmi_ipmb_addr    *ipmb_addr;
3682         struct ipmi_recv_msg     *recv_msg;
3683
3684         if (msg->rsp_size < 10) {
3685                 /* Message not big enough, just ignore it. */
3686                 ipmi_inc_stat(intf, invalid_commands);
3687                 return 0;
3688         }
3689
3690         if (msg->rsp[2] != 0) {
3691                 /* An error getting the response, just ignore it. */
3692                 return 0;
3693         }
3694
3695         netfn = msg->rsp[4] >> 2;
3696         cmd = msg->rsp[8];
3697         chan = msg->rsp[3] & 0xf;
3698
3699         rcu_read_lock();
3700         rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
3701         if (rcvr) {
3702                 user = rcvr->user;
3703                 kref_get(&user->refcount);
3704         } else
3705                 user = NULL;
3706         rcu_read_unlock();
3707
3708         if (user == NULL) {
3709                 /* We didn't find a user, deliver an error response. */
3710                 ipmi_inc_stat(intf, unhandled_commands);
3711
3712                 msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
3713                 msg->data[1] = IPMI_SEND_MSG_CMD;
3714                 msg->data[2] = msg->rsp[3];
3715                 msg->data[3] = msg->rsp[6];
3716                 msg->data[4] = ((netfn + 1) << 2) | (msg->rsp[7] & 0x3);
3717                 msg->data[5] = ipmb_checksum(&msg->data[3], 2);
3718                 msg->data[6] = intf->addrinfo[msg->rsp[3] & 0xf].address;
3719                 /* rqseq/lun */
3720                 msg->data[7] = (msg->rsp[7] & 0xfc) | (msg->rsp[4] & 0x3);
3721                 msg->data[8] = msg->rsp[8]; /* cmd */
3722                 msg->data[9] = IPMI_INVALID_CMD_COMPLETION_CODE;
3723                 msg->data[10] = ipmb_checksum(&msg->data[6], 4);
3724                 msg->data_size = 11;
3725
3726                 pr_debug("Invalid command: %*ph\n", msg->data_size, msg->data);
3727
3728                 rcu_read_lock();
3729                 if (!intf->in_shutdown) {
3730                         smi_send(intf, intf->handlers, msg, 0);
3731                         /*
3732                          * We used the message, so return the value
3733                          * that causes it to not be freed or
3734                          * queued.
3735                          */
3736                         rv = -1;
3737                 }
3738                 rcu_read_unlock();
3739         } else {
3740                 recv_msg = ipmi_alloc_recv_msg();
3741                 if (!recv_msg) {
3742                         /*
3743                          * We couldn't allocate memory for the
3744                          * message, so requeue it for handling
3745                          * later.
3746                          */
3747                         rv = 1;
3748                         kref_put(&user->refcount, free_user);
3749                 } else {
3750                         /* Extract the source address from the data. */
3751                         ipmb_addr = (struct ipmi_ipmb_addr *) &recv_msg->addr;
3752                         ipmb_addr->addr_type = IPMI_IPMB_ADDR_TYPE;
3753                         ipmb_addr->slave_addr = msg->rsp[6];
3754                         ipmb_addr->lun = msg->rsp[7] & 3;
3755                         ipmb_addr->channel = msg->rsp[3] & 0xf;
3756
3757                         /*
3758                          * Extract the rest of the message information
3759                          * from the IPMB header.
3760                          */
3761                         recv_msg->user = user;
3762                         recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
3763                         recv_msg->msgid = msg->rsp[7] >> 2;
3764                         recv_msg->msg.netfn = msg->rsp[4] >> 2;
3765                         recv_msg->msg.cmd = msg->rsp[8];
3766                         recv_msg->msg.data = recv_msg->msg_data;
3767
3768                         /*
3769                          * We chop off 10, not 9 bytes because the checksum
3770                          * at the end also needs to be removed.
3771                          */
3772                         recv_msg->msg.data_len = msg->rsp_size - 10;
3773                         memcpy(recv_msg->msg_data, &msg->rsp[9],
3774                                msg->rsp_size - 10);
3775                         if (deliver_response(intf, recv_msg))
3776                                 ipmi_inc_stat(intf, unhandled_commands);
3777                         else
3778                                 ipmi_inc_stat(intf, handled_commands);
3779                 }
3780         }
3781
3782         return rv;
3783 }
3784
3785 static int handle_lan_get_msg_rsp(struct ipmi_smi *intf,
3786                                   struct ipmi_smi_msg *msg)
3787 {
3788         struct ipmi_lan_addr  lan_addr;
3789         struct ipmi_recv_msg  *recv_msg;
3790
3791
3792         /*
3793          * This is 13, not 12, because the response must contain a
3794          * completion code.
3795          */
3796         if (msg->rsp_size < 13) {
3797                 /* Message not big enough, just ignore it. */
3798                 ipmi_inc_stat(intf, invalid_lan_responses);
3799                 return 0;
3800         }
3801
3802         if (msg->rsp[2] != 0) {
3803                 /* An error getting the response, just ignore it. */
3804                 return 0;
3805         }
3806
3807         lan_addr.addr_type = IPMI_LAN_ADDR_TYPE;
3808         lan_addr.session_handle = msg->rsp[4];
3809         lan_addr.remote_SWID = msg->rsp[8];
3810         lan_addr.local_SWID = msg->rsp[5];
3811         lan_addr.channel = msg->rsp[3] & 0x0f;
3812         lan_addr.privilege = msg->rsp[3] >> 4;
3813         lan_addr.lun = msg->rsp[9] & 3;
3814
3815         /*
3816          * It's a response from a remote entity.  Look up the sequence
3817          * number and handle the response.
3818          */
3819         if (intf_find_seq(intf,
3820                           msg->rsp[9] >> 2,
3821                           msg->rsp[3] & 0x0f,
3822                           msg->rsp[10],
3823                           (msg->rsp[6] >> 2) & (~1),
3824                           (struct ipmi_addr *) &lan_addr,
3825                           &recv_msg)) {
3826                 /*
3827                  * We were unable to find the sequence number,
3828                  * so just nuke the message.
3829                  */
3830                 ipmi_inc_stat(intf, unhandled_lan_responses);
3831                 return 0;
3832         }
3833
3834         memcpy(recv_msg->msg_data, &msg->rsp[11], msg->rsp_size - 11);
3835         /*
3836          * The other fields matched, so no need to set them, except
3837          * for netfn, which needs to be the response that was
3838          * returned, not the request value.
3839          */
3840         recv_msg->msg.netfn = msg->rsp[6] >> 2;
3841         recv_msg->msg.data = recv_msg->msg_data;
3842         recv_msg->msg.data_len = msg->rsp_size - 12;
3843         recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
3844         if (deliver_response(intf, recv_msg))
3845                 ipmi_inc_stat(intf, unhandled_lan_responses);
3846         else
3847                 ipmi_inc_stat(intf, handled_lan_responses);
3848
3849         return 0;
3850 }
3851
3852 static int handle_lan_get_msg_cmd(struct ipmi_smi *intf,
3853                                   struct ipmi_smi_msg *msg)
3854 {
3855         struct cmd_rcvr          *rcvr;
3856         int                      rv = 0;
3857         unsigned char            netfn;
3858         unsigned char            cmd;
3859         unsigned char            chan;
3860         struct ipmi_user         *user = NULL;
3861         struct ipmi_lan_addr     *lan_addr;
3862         struct ipmi_recv_msg     *recv_msg;
3863
3864         if (msg->rsp_size < 12) {
3865                 /* Message not big enough, just ignore it. */
3866                 ipmi_inc_stat(intf, invalid_commands);
3867                 return 0;
3868         }
3869
3870         if (msg->rsp[2] != 0) {
3871                 /* An error getting the response, just ignore it. */
3872                 return 0;
3873         }
3874
3875         netfn = msg->rsp[6] >> 2;
3876         cmd = msg->rsp[10];
3877         chan = msg->rsp[3] & 0xf;
3878
3879         rcu_read_lock();
3880         rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
3881         if (rcvr) {
3882                 user = rcvr->user;
3883                 kref_get(&user->refcount);
3884         } else
3885                 user = NULL;
3886         rcu_read_unlock();
3887
3888         if (user == NULL) {
3889                 /* We didn't find a user, just give up. */
3890                 ipmi_inc_stat(intf, unhandled_commands);
3891
3892                 /*
3893                  * Don't do anything with these messages, just allow
3894                  * them to be freed.
3895                  */
3896                 rv = 0;
3897         } else {
3898                 recv_msg = ipmi_alloc_recv_msg();
3899                 if (!recv_msg) {
3900                         /*
3901                          * We couldn't allocate memory for the
3902                          * message, so requeue it for handling later.
3903                          */
3904                         rv = 1;
3905                         kref_put(&user->refcount, free_user);
3906                 } else {
3907                         /* Extract the source address from the data. */
3908                         lan_addr = (struct ipmi_lan_addr *) &recv_msg->addr;
3909                         lan_addr->addr_type = IPMI_LAN_ADDR_TYPE;
3910                         lan_addr->session_handle = msg->rsp[4];
3911                         lan_addr->remote_SWID = msg->rsp[8];
3912                         lan_addr->local_SWID = msg->rsp[5];
3913                         lan_addr->lun = msg->rsp[9] & 3;
3914                         lan_addr->channel = msg->rsp[3] & 0xf;
3915                         lan_addr->privilege = msg->rsp[3] >> 4;
3916
3917                         /*
3918                          * Extract the rest of the message information
3919                          * from the IPMB header.
3920                          */
3921                         recv_msg->user = user;
3922                         recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
3923                         recv_msg->msgid = msg->rsp[9] >> 2;
3924                         recv_msg->msg.netfn = msg->rsp[6] >> 2;
3925                         recv_msg->msg.cmd = msg->rsp[10];
3926                         recv_msg->msg.data = recv_msg->msg_data;
3927
3928                         /*
3929                          * We chop off 12, not 11 bytes because the checksum
3930                          * at the end also needs to be removed.
3931                          */
3932                         recv_msg->msg.data_len = msg->rsp_size - 12;
3933                         memcpy(recv_msg->msg_data, &msg->rsp[11],
3934                                msg->rsp_size - 12);
3935                         if (deliver_response(intf, recv_msg))
3936                                 ipmi_inc_stat(intf, unhandled_commands);
3937                         else
3938                                 ipmi_inc_stat(intf, handled_commands);
3939                 }
3940         }
3941
3942         return rv;
3943 }
3944
3945 /*
3946  * This routine will handle "Get Message" command responses with
3947  * channels that use an OEM Medium. The message format belongs to
3948  * the OEM.  See IPMI 2.0 specification, Chapter 6 and
3949  * Chapter 22, sections 22.6 and 22.24 for more details.
3950  */
3951 static int handle_oem_get_msg_cmd(struct ipmi_smi *intf,
3952                                   struct ipmi_smi_msg *msg)
3953 {
3954         struct cmd_rcvr       *rcvr;
3955         int                   rv = 0;
3956         unsigned char         netfn;
3957         unsigned char         cmd;
3958         unsigned char         chan;
3959         struct ipmi_user *user = NULL;
3960         struct ipmi_system_interface_addr *smi_addr;
3961         struct ipmi_recv_msg  *recv_msg;
3962
3963         /*
3964          * We expect the OEM SW to perform error checking
3965          * so we just do some basic sanity checks
3966          */
3967         if (msg->rsp_size < 4) {
3968                 /* Message not big enough, just ignore it. */
3969                 ipmi_inc_stat(intf, invalid_commands);
3970                 return 0;
3971         }
3972
3973         if (msg->rsp[2] != 0) {
3974                 /* An error getting the response, just ignore it. */
3975                 return 0;
3976         }
3977
3978         /*
3979          * This is an OEM Message so the OEM needs to know how
3980          * handle the message. We do no interpretation.
3981          */
3982         netfn = msg->rsp[0] >> 2;
3983         cmd = msg->rsp[1];
3984         chan = msg->rsp[3] & 0xf;
3985
3986         rcu_read_lock();
3987         rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
3988         if (rcvr) {
3989                 user = rcvr->user;
3990                 kref_get(&user->refcount);
3991         } else
3992                 user = NULL;
3993         rcu_read_unlock();
3994
3995         if (user == NULL) {
3996                 /* We didn't find a user, just give up. */
3997                 ipmi_inc_stat(intf, unhandled_commands);
3998
3999                 /*
4000                  * Don't do anything with these messages, just allow
4001                  * them to be freed.
4002                  */
4003
4004                 rv = 0;
4005         } else {
4006                 recv_msg = ipmi_alloc_recv_msg();
4007                 if (!recv_msg) {
4008                         /*
4009                          * We couldn't allocate memory for the
4010                          * message, so requeue it for handling
4011                          * later.
4012                          */
4013                         rv = 1;
4014                         kref_put(&user->refcount, free_user);
4015                 } else {
4016                         /*
4017                          * OEM Messages are expected to be delivered via
4018                          * the system interface to SMS software.  We might
4019                          * need to visit this again depending on OEM
4020                          * requirements
4021                          */
4022                         smi_addr = ((struct ipmi_system_interface_addr *)
4023                                     &recv_msg->addr);
4024                         smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
4025                         smi_addr->channel = IPMI_BMC_CHANNEL;
4026                         smi_addr->lun = msg->rsp[0] & 3;
4027
4028                         recv_msg->user = user;
4029                         recv_msg->user_msg_data = NULL;
4030                         recv_msg->recv_type = IPMI_OEM_RECV_TYPE;
4031                         recv_msg->msg.netfn = msg->rsp[0] >> 2;
4032                         recv_msg->msg.cmd = msg->rsp[1];
4033                         recv_msg->msg.data = recv_msg->msg_data;
4034
4035                         /*
4036                          * The message starts at byte 4 which follows the
4037                          * the Channel Byte in the "GET MESSAGE" command
4038                          */
4039                         recv_msg->msg.data_len = msg->rsp_size - 4;
4040                         memcpy(recv_msg->msg_data, &msg->rsp[4],
4041                                msg->rsp_size - 4);
4042                         if (deliver_response(intf, recv_msg))
4043                                 ipmi_inc_stat(intf, unhandled_commands);
4044                         else
4045                                 ipmi_inc_stat(intf, handled_commands);
4046                 }
4047         }
4048
4049         return rv;
4050 }
4051
4052 static void copy_event_into_recv_msg(struct ipmi_recv_msg *recv_msg,
4053                                      struct ipmi_smi_msg  *msg)
4054 {
4055         struct ipmi_system_interface_addr *smi_addr;
4056
4057         recv_msg->msgid = 0;
4058         smi_addr = (struct ipmi_system_interface_addr *) &recv_msg->addr;
4059         smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
4060         smi_addr->channel = IPMI_BMC_CHANNEL;
4061         smi_addr->lun = msg->rsp[0] & 3;
4062         recv_msg->recv_type = IPMI_ASYNC_EVENT_RECV_TYPE;
4063         recv_msg->msg.netfn = msg->rsp[0] >> 2;
4064         recv_msg->msg.cmd = msg->rsp[1];
4065         memcpy(recv_msg->msg_data, &msg->rsp[3], msg->rsp_size - 3);
4066         recv_msg->msg.data = recv_msg->msg_data;
4067         recv_msg->msg.data_len = msg->rsp_size - 3;
4068 }
4069
4070 static int handle_read_event_rsp(struct ipmi_smi *intf,
4071                                  struct ipmi_smi_msg *msg)
4072 {
4073         struct ipmi_recv_msg *recv_msg, *recv_msg2;
4074         struct list_head     msgs;
4075         struct ipmi_user     *user;
4076         int rv = 0, deliver_count = 0, index;
4077         unsigned long        flags;
4078
4079         if (msg->rsp_size < 19) {
4080                 /* Message is too small to be an IPMB event. */
4081                 ipmi_inc_stat(intf, invalid_events);
4082                 return 0;
4083         }
4084
4085         if (msg->rsp[2] != 0) {
4086                 /* An error getting the event, just ignore it. */
4087                 return 0;
4088         }
4089
4090         INIT_LIST_HEAD(&msgs);
4091
4092         spin_lock_irqsave(&intf->events_lock, flags);
4093
4094         ipmi_inc_stat(intf, events);
4095
4096         /*
4097          * Allocate and fill in one message for every user that is
4098          * getting events.
4099          */
4100         index = srcu_read_lock(&intf->users_srcu);
4101         list_for_each_entry_rcu(user, &intf->users, link) {
4102                 if (!user->gets_events)
4103                         continue;
4104
4105                 recv_msg = ipmi_alloc_recv_msg();
4106                 if (!recv_msg) {
4107                         rcu_read_unlock();
4108                         list_for_each_entry_safe(recv_msg, recv_msg2, &msgs,
4109                                                  link) {
4110                                 list_del(&recv_msg->link);
4111                                 ipmi_free_recv_msg(recv_msg);
4112                         }
4113                         /*
4114                          * We couldn't allocate memory for the
4115                          * message, so requeue it for handling
4116                          * later.
4117                          */
4118                         rv = 1;
4119                         goto out;
4120                 }
4121
4122                 deliver_count++;
4123
4124                 copy_event_into_recv_msg(recv_msg, msg);
4125                 recv_msg->user = user;
4126                 kref_get(&user->refcount);
4127                 list_add_tail(&recv_msg->link, &msgs);
4128         }
4129         srcu_read_unlock(&intf->users_srcu, index);
4130
4131         if (deliver_count) {
4132                 /* Now deliver all the messages. */
4133                 list_for_each_entry_safe(recv_msg, recv_msg2, &msgs, link) {
4134                         list_del(&recv_msg->link);
4135                         deliver_local_response(intf, recv_msg);
4136                 }
4137         } else if (intf->waiting_events_count < MAX_EVENTS_IN_QUEUE) {
4138                 /*
4139                  * No one to receive the message, put it in queue if there's
4140                  * not already too many things in the queue.
4141                  */
4142                 recv_msg = ipmi_alloc_recv_msg();
4143                 if (!recv_msg) {
4144                         /*
4145                          * We couldn't allocate memory for the
4146                          * message, so requeue it for handling
4147                          * later.
4148                          */
4149                         rv = 1;
4150                         goto out;
4151                 }
4152
4153                 copy_event_into_recv_msg(recv_msg, msg);
4154                 list_add_tail(&recv_msg->link, &intf->waiting_events);
4155                 intf->waiting_events_count++;
4156         } else if (!intf->event_msg_printed) {
4157                 /*
4158                  * There's too many things in the queue, discard this
4159                  * message.
4160                  */
4161                 dev_warn(intf->si_dev,
4162                          "Event queue full, discarding incoming events\n");
4163                 intf->event_msg_printed = 1;
4164         }
4165
4166  out:
4167         spin_unlock_irqrestore(&intf->events_lock, flags);
4168
4169         return rv;
4170 }
4171
4172 static int handle_bmc_rsp(struct ipmi_smi *intf,
4173                           struct ipmi_smi_msg *msg)
4174 {
4175         struct ipmi_recv_msg *recv_msg;
4176         struct ipmi_system_interface_addr *smi_addr;
4177
4178         recv_msg = (struct ipmi_recv_msg *) msg->user_data;
4179         if (recv_msg == NULL) {
4180                 dev_warn(intf->si_dev,
4181                          "IPMI message received with no owner. This could be because of a malformed message, or because of a hardware error.  Contact your hardware vendor for assistance.\n");
4182                 return 0;
4183         }
4184
4185         recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
4186         recv_msg->msgid = msg->msgid;
4187         smi_addr = ((struct ipmi_system_interface_addr *)
4188                     &recv_msg->addr);
4189         smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
4190         smi_addr->channel = IPMI_BMC_CHANNEL;
4191         smi_addr->lun = msg->rsp[0] & 3;
4192         recv_msg->msg.netfn = msg->rsp[0] >> 2;
4193         recv_msg->msg.cmd = msg->rsp[1];
4194         memcpy(recv_msg->msg_data, &msg->rsp[2], msg->rsp_size - 2);
4195         recv_msg->msg.data = recv_msg->msg_data;
4196         recv_msg->msg.data_len = msg->rsp_size - 2;
4197         deliver_local_response(intf, recv_msg);
4198
4199         return 0;
4200 }
4201
4202 /*
4203  * Handle a received message.  Return 1 if the message should be requeued,
4204  * 0 if the message should be freed, or -1 if the message should not
4205  * be freed or requeued.
4206  */
4207 static int handle_one_recv_msg(struct ipmi_smi *intf,
4208                                struct ipmi_smi_msg *msg)
4209 {
4210         int requeue;
4211         int chan;
4212
4213         pr_debug("Recv: %*ph\n", msg->rsp_size, msg->rsp);
4214
4215         if ((msg->data_size >= 2)
4216             && (msg->data[0] == (IPMI_NETFN_APP_REQUEST << 2))
4217             && (msg->data[1] == IPMI_SEND_MSG_CMD)
4218             && (msg->user_data == NULL)) {
4219
4220                 if (intf->in_shutdown)
4221                         goto free_msg;
4222
4223                 /*
4224                  * This is the local response to a command send, start
4225                  * the timer for these.  The user_data will not be
4226                  * NULL if this is a response send, and we will let
4227                  * response sends just go through.
4228                  */
4229
4230                 /*
4231                  * Check for errors, if we get certain errors (ones
4232                  * that mean basically we can try again later), we
4233                  * ignore them and start the timer.  Otherwise we
4234                  * report the error immediately.
4235                  */
4236                 if ((msg->rsp_size >= 3) && (msg->rsp[2] != 0)
4237                     && (msg->rsp[2] != IPMI_NODE_BUSY_ERR)
4238                     && (msg->rsp[2] != IPMI_LOST_ARBITRATION_ERR)
4239                     && (msg->rsp[2] != IPMI_BUS_ERR)
4240                     && (msg->rsp[2] != IPMI_NAK_ON_WRITE_ERR)) {
4241                         int ch = msg->rsp[3] & 0xf;
4242                         struct ipmi_channel *chans;
4243
4244                         /* Got an error sending the message, handle it. */
4245
4246                         chans = READ_ONCE(intf->channel_list)->c;
4247                         if ((chans[ch].medium == IPMI_CHANNEL_MEDIUM_8023LAN)
4248                             || (chans[ch].medium == IPMI_CHANNEL_MEDIUM_ASYNC))
4249                                 ipmi_inc_stat(intf, sent_lan_command_errs);
4250                         else
4251                                 ipmi_inc_stat(intf, sent_ipmb_command_errs);
4252                         intf_err_seq(intf, msg->msgid, msg->rsp[2]);
4253                 } else
4254                         /* The message was sent, start the timer. */
4255                         intf_start_seq_timer(intf, msg->msgid);
4256 free_msg:
4257                 requeue = 0;
4258                 goto out;
4259
4260         } else if (msg->rsp_size < 2) {
4261                 /* Message is too small to be correct. */
4262                 dev_warn(intf->si_dev,
4263                          "BMC returned too small a message for netfn %x cmd %x, got %d bytes\n",
4264                          (msg->data[0] >> 2) | 1, msg->data[1], msg->rsp_size);
4265
4266                 /* Generate an error response for the message. */
4267                 msg->rsp[0] = msg->data[0] | (1 << 2);
4268                 msg->rsp[1] = msg->data[1];
4269                 msg->rsp[2] = IPMI_ERR_UNSPECIFIED;
4270                 msg->rsp_size = 3;
4271         } else if (((msg->rsp[0] >> 2) != ((msg->data[0] >> 2) | 1))
4272                    || (msg->rsp[1] != msg->data[1])) {
4273                 /*
4274                  * The NetFN and Command in the response is not even
4275                  * marginally correct.
4276                  */
4277                 dev_warn(intf->si_dev,
4278                          "BMC returned incorrect response, expected netfn %x cmd %x, got netfn %x cmd %x\n",
4279                          (msg->data[0] >> 2) | 1, msg->data[1],
4280                          msg->rsp[0] >> 2, msg->rsp[1]);
4281
4282                 /* Generate an error response for the message. */
4283                 msg->rsp[0] = msg->data[0] | (1 << 2);
4284                 msg->rsp[1] = msg->data[1];
4285                 msg->rsp[2] = IPMI_ERR_UNSPECIFIED;
4286                 msg->rsp_size = 3;
4287         }
4288
4289         if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
4290             && (msg->rsp[1] == IPMI_SEND_MSG_CMD)
4291             && (msg->user_data != NULL)) {
4292                 /*
4293                  * It's a response to a response we sent.  For this we
4294                  * deliver a send message response to the user.
4295                  */
4296                 struct ipmi_recv_msg *recv_msg = msg->user_data;
4297
4298                 requeue = 0;
4299                 if (msg->rsp_size < 2)
4300                         /* Message is too small to be correct. */
4301                         goto out;
4302
4303                 chan = msg->data[2] & 0x0f;
4304                 if (chan >= IPMI_MAX_CHANNELS)
4305                         /* Invalid channel number */
4306                         goto out;
4307
4308                 if (!recv_msg)
4309                         goto out;
4310
4311                 recv_msg->recv_type = IPMI_RESPONSE_RESPONSE_TYPE;
4312                 recv_msg->msg.data = recv_msg->msg_data;
4313                 recv_msg->msg.data_len = 1;
4314                 recv_msg->msg_data[0] = msg->rsp[2];
4315                 deliver_local_response(intf, recv_msg);
4316         } else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
4317                    && (msg->rsp[1] == IPMI_GET_MSG_CMD)) {
4318                 struct ipmi_channel   *chans;
4319
4320                 /* It's from the receive queue. */
4321                 chan = msg->rsp[3] & 0xf;
4322                 if (chan >= IPMI_MAX_CHANNELS) {
4323                         /* Invalid channel number */
4324                         requeue = 0;
4325                         goto out;
4326                 }
4327
4328                 /*
4329                  * We need to make sure the channels have been initialized.
4330                  * The channel_handler routine will set the "curr_channel"
4331                  * equal to or greater than IPMI_MAX_CHANNELS when all the
4332                  * channels for this interface have been initialized.
4333                  */
4334                 if (!intf->channels_ready) {
4335                         requeue = 0; /* Throw the message away */
4336                         goto out;
4337                 }
4338
4339                 chans = READ_ONCE(intf->channel_list)->c;
4340
4341                 switch (chans[chan].medium) {
4342                 case IPMI_CHANNEL_MEDIUM_IPMB:
4343                         if (msg->rsp[4] & 0x04) {
4344                                 /*
4345                                  * It's a response, so find the
4346                                  * requesting message and send it up.
4347                                  */
4348                                 requeue = handle_ipmb_get_msg_rsp(intf, msg);
4349                         } else {
4350                                 /*
4351                                  * It's a command to the SMS from some other
4352                                  * entity.  Handle that.
4353                                  */
4354                                 requeue = handle_ipmb_get_msg_cmd(intf, msg);
4355                         }
4356                         break;
4357
4358                 case IPMI_CHANNEL_MEDIUM_8023LAN:
4359                 case IPMI_CHANNEL_MEDIUM_ASYNC:
4360                         if (msg->rsp[6] & 0x04) {
4361                                 /*
4362                                  * It's a response, so find the
4363                                  * requesting message and send it up.
4364                                  */
4365                                 requeue = handle_lan_get_msg_rsp(intf, msg);
4366                         } else {
4367                                 /*
4368                                  * It's a command to the SMS from some other
4369                                  * entity.  Handle that.
4370                                  */
4371                                 requeue = handle_lan_get_msg_cmd(intf, msg);
4372                         }
4373                         break;
4374
4375                 default:
4376                         /* Check for OEM Channels.  Clients had better
4377                            register for these commands. */
4378                         if ((chans[chan].medium >= IPMI_CHANNEL_MEDIUM_OEM_MIN)
4379                             && (chans[chan].medium
4380                                 <= IPMI_CHANNEL_MEDIUM_OEM_MAX)) {
4381                                 requeue = handle_oem_get_msg_cmd(intf, msg);
4382                         } else {
4383                                 /*
4384                                  * We don't handle the channel type, so just
4385                                  * free the message.
4386                                  */
4387                                 requeue = 0;
4388                         }
4389                 }
4390
4391         } else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
4392                    && (msg->rsp[1] == IPMI_READ_EVENT_MSG_BUFFER_CMD)) {
4393                 /* It's an asynchronous event. */
4394                 requeue = handle_read_event_rsp(intf, msg);
4395         } else {
4396                 /* It's a response from the local BMC. */
4397                 requeue = handle_bmc_rsp(intf, msg);
4398         }
4399
4400  out:
4401         return requeue;
4402 }
4403
4404 /*
4405  * If there are messages in the queue or pretimeouts, handle them.
4406  */
4407 static void handle_new_recv_msgs(struct ipmi_smi *intf)
4408 {
4409         struct ipmi_smi_msg  *smi_msg;
4410         unsigned long        flags = 0;
4411         int                  rv;
4412         int                  run_to_completion = intf->run_to_completion;
4413
4414         /* See if any waiting messages need to be processed. */
4415         if (!run_to_completion)
4416                 spin_lock_irqsave(&intf->waiting_rcv_msgs_lock, flags);
4417         while (!list_empty(&intf->waiting_rcv_msgs)) {
4418                 smi_msg = list_entry(intf->waiting_rcv_msgs.next,
4419                                      struct ipmi_smi_msg, link);
4420                 list_del(&smi_msg->link);
4421                 if (!run_to_completion)
4422                         spin_unlock_irqrestore(&intf->waiting_rcv_msgs_lock,
4423                                                flags);
4424                 rv = handle_one_recv_msg(intf, smi_msg);
4425                 if (!run_to_completion)
4426                         spin_lock_irqsave(&intf->waiting_rcv_msgs_lock, flags);
4427                 if (rv > 0) {
4428                         /*
4429                          * To preserve message order, quit if we
4430                          * can't handle a message.  Add the message
4431                          * back at the head, this is safe because this
4432                          * tasklet is the only thing that pulls the
4433                          * messages.
4434                          */
4435                         list_add(&smi_msg->link, &intf->waiting_rcv_msgs);
4436                         break;
4437                 } else {
4438                         if (rv == 0)
4439                                 /* Message handled */
4440                                 ipmi_free_smi_msg(smi_msg);
4441                         /* If rv < 0, fatal error, del but don't free. */
4442                 }
4443         }
4444         if (!run_to_completion)
4445                 spin_unlock_irqrestore(&intf->waiting_rcv_msgs_lock, flags);
4446
4447         /*
4448          * If the pretimout count is non-zero, decrement one from it and
4449          * deliver pretimeouts to all the users.
4450          */
4451         if (atomic_add_unless(&intf->watchdog_pretimeouts_to_deliver, -1, 0)) {
4452                 struct ipmi_user *user;
4453                 int index;
4454
4455                 index = srcu_read_lock(&intf->users_srcu);
4456                 list_for_each_entry_rcu(user, &intf->users, link) {
4457                         if (user->handler->ipmi_watchdog_pretimeout)
4458                                 user->handler->ipmi_watchdog_pretimeout(
4459                                         user->handler_data);
4460                 }
4461                 srcu_read_unlock(&intf->users_srcu, index);
4462         }
4463 }
4464
4465 static void smi_recv_tasklet(unsigned long val)
4466 {
4467         unsigned long flags = 0; /* keep us warning-free. */
4468         struct ipmi_smi *intf = (struct ipmi_smi *) val;
4469         int run_to_completion = intf->run_to_completion;
4470         struct ipmi_smi_msg *newmsg = NULL;
4471
4472         /*
4473          * Start the next message if available.
4474          *
4475          * Do this here, not in the actual receiver, because we may deadlock
4476          * because the lower layer is allowed to hold locks while calling
4477          * message delivery.
4478          */
4479
4480         rcu_read_lock();
4481
4482         if (!run_to_completion)
4483                 spin_lock_irqsave(&intf->xmit_msgs_lock, flags);
4484         if (intf->curr_msg == NULL && !intf->in_shutdown) {
4485                 struct list_head *entry = NULL;
4486
4487                 /* Pick the high priority queue first. */
4488                 if (!list_empty(&intf->hp_xmit_msgs))
4489                         entry = intf->hp_xmit_msgs.next;
4490                 else if (!list_empty(&intf->xmit_msgs))
4491                         entry = intf->xmit_msgs.next;
4492
4493                 if (entry) {
4494                         list_del(entry);
4495                         newmsg = list_entry(entry, struct ipmi_smi_msg, link);
4496                         intf->curr_msg = newmsg;
4497                 }
4498         }
4499
4500         if (!run_to_completion)
4501                 spin_unlock_irqrestore(&intf->xmit_msgs_lock, flags);
4502         if (newmsg)
4503                 intf->handlers->sender(intf->send_info, newmsg);
4504
4505         rcu_read_unlock();
4506
4507         handle_new_recv_msgs(intf);
4508 }
4509
4510 /* Handle a new message from the lower layer. */
4511 void ipmi_smi_msg_received(struct ipmi_smi *intf,
4512                            struct ipmi_smi_msg *msg)
4513 {
4514         unsigned long flags = 0; /* keep us warning-free. */
4515         int run_to_completion = intf->run_to_completion;
4516
4517         /*
4518          * To preserve message order, we keep a queue and deliver from
4519          * a tasklet.
4520          */
4521         if (!run_to_completion)
4522                 spin_lock_irqsave(&intf->waiting_rcv_msgs_lock, flags);
4523         list_add_tail(&msg->link, &intf->waiting_rcv_msgs);
4524         if (!run_to_completion)
4525                 spin_unlock_irqrestore(&intf->waiting_rcv_msgs_lock,
4526                                        flags);
4527
4528         if (!run_to_completion)
4529                 spin_lock_irqsave(&intf->xmit_msgs_lock, flags);
4530         /*
4531          * We can get an asynchronous event or receive message in addition
4532          * to commands we send.
4533          */
4534         if (msg == intf->curr_msg)
4535                 intf->curr_msg = NULL;
4536         if (!run_to_completion)
4537                 spin_unlock_irqrestore(&intf->xmit_msgs_lock, flags);
4538
4539         if (run_to_completion)
4540                 smi_recv_tasklet((unsigned long) intf);
4541         else
4542                 tasklet_schedule(&intf->recv_tasklet);
4543 }
4544 EXPORT_SYMBOL(ipmi_smi_msg_received);
4545
4546 void ipmi_smi_watchdog_pretimeout(struct ipmi_smi *intf)
4547 {
4548         if (intf->in_shutdown)
4549                 return;
4550
4551         atomic_set(&intf->watchdog_pretimeouts_to_deliver, 1);
4552         tasklet_schedule(&intf->recv_tasklet);
4553 }
4554 EXPORT_SYMBOL(ipmi_smi_watchdog_pretimeout);
4555
4556 static struct ipmi_smi_msg *
4557 smi_from_recv_msg(struct ipmi_smi *intf, struct ipmi_recv_msg *recv_msg,
4558                   unsigned char seq, long seqid)
4559 {
4560         struct ipmi_smi_msg *smi_msg = ipmi_alloc_smi_msg();
4561         if (!smi_msg)
4562                 /*
4563                  * If we can't allocate the message, then just return, we
4564                  * get 4 retries, so this should be ok.
4565                  */
4566                 return NULL;
4567
4568         memcpy(smi_msg->data, recv_msg->msg.data, recv_msg->msg.data_len);
4569         smi_msg->data_size = recv_msg->msg.data_len;
4570         smi_msg->msgid = STORE_SEQ_IN_MSGID(seq, seqid);
4571
4572         pr_debug("Resend: %*ph\n", smi_msg->data_size, smi_msg->data);
4573
4574         return smi_msg;
4575 }
4576
4577 static void check_msg_timeout(struct ipmi_smi *intf, struct seq_table *ent,
4578                               struct list_head *timeouts,
4579                               unsigned long timeout_period,
4580                               int slot, unsigned long *flags,
4581                               bool *need_timer)
4582 {
4583         struct ipmi_recv_msg *msg;
4584
4585         if (intf->in_shutdown)
4586                 return;
4587
4588         if (!ent->inuse)
4589                 return;
4590
4591         if (timeout_period < ent->timeout) {
4592                 ent->timeout -= timeout_period;
4593                 *need_timer = true;
4594                 return;
4595         }
4596
4597         if (ent->retries_left == 0) {
4598                 /* The message has used all its retries. */
4599                 ent->inuse = 0;
4600                 smi_remove_watch(intf, IPMI_WATCH_MASK_CHECK_MESSAGES);
4601                 msg = ent->recv_msg;
4602                 list_add_tail(&msg->link, timeouts);
4603                 if (ent->broadcast)
4604                         ipmi_inc_stat(intf, timed_out_ipmb_broadcasts);
4605                 else if (is_lan_addr(&ent->recv_msg->addr))
4606                         ipmi_inc_stat(intf, timed_out_lan_commands);
4607                 else
4608                         ipmi_inc_stat(intf, timed_out_ipmb_commands);
4609         } else {
4610                 struct ipmi_smi_msg *smi_msg;
4611                 /* More retries, send again. */
4612
4613                 *need_timer = true;
4614
4615                 /*
4616                  * Start with the max timer, set to normal timer after
4617                  * the message is sent.
4618                  */
4619                 ent->timeout = MAX_MSG_TIMEOUT;
4620                 ent->retries_left--;
4621                 smi_msg = smi_from_recv_msg(intf, ent->recv_msg, slot,
4622                                             ent->seqid);
4623                 if (!smi_msg) {
4624                         if (is_lan_addr(&ent->recv_msg->addr))
4625                                 ipmi_inc_stat(intf,
4626                                               dropped_rexmit_lan_commands);
4627                         else
4628                                 ipmi_inc_stat(intf,
4629                                               dropped_rexmit_ipmb_commands);
4630                         return;
4631                 }
4632
4633                 spin_unlock_irqrestore(&intf->seq_lock, *flags);
4634
4635                 /*
4636                  * Send the new message.  We send with a zero
4637                  * priority.  It timed out, I doubt time is that
4638                  * critical now, and high priority messages are really
4639                  * only for messages to the local MC, which don't get
4640                  * resent.
4641                  */
4642                 if (intf->handlers) {
4643                         if (is_lan_addr(&ent->recv_msg->addr))
4644                                 ipmi_inc_stat(intf,
4645                                               retransmitted_lan_commands);
4646                         else
4647                                 ipmi_inc_stat(intf,
4648                                               retransmitted_ipmb_commands);
4649
4650                         smi_send(intf, intf->handlers, smi_msg, 0);
4651                 } else
4652                         ipmi_free_smi_msg(smi_msg);
4653
4654                 spin_lock_irqsave(&intf->seq_lock, *flags);
4655         }
4656 }
4657
4658 static bool ipmi_timeout_handler(struct ipmi_smi *intf,
4659                                  unsigned long timeout_period)
4660 {
4661         struct list_head     timeouts;
4662         struct ipmi_recv_msg *msg, *msg2;
4663         unsigned long        flags;
4664         int                  i;
4665         bool                 need_timer = false;
4666
4667         if (!intf->bmc_registered) {
4668                 kref_get(&intf->refcount);
4669                 if (!schedule_work(&intf->bmc_reg_work)) {
4670                         kref_put(&intf->refcount, intf_free);
4671                         need_timer = true;
4672                 }
4673         }
4674
4675         /*
4676          * Go through the seq table and find any messages that
4677          * have timed out, putting them in the timeouts
4678          * list.
4679          */
4680         INIT_LIST_HEAD(&timeouts);
4681         spin_lock_irqsave(&intf->seq_lock, flags);
4682         if (intf->ipmb_maintenance_mode_timeout) {
4683                 if (intf->ipmb_maintenance_mode_timeout <= timeout_period)
4684                         intf->ipmb_maintenance_mode_timeout = 0;
4685                 else
4686                         intf->ipmb_maintenance_mode_timeout -= timeout_period;
4687         }
4688         for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++)
4689                 check_msg_timeout(intf, &intf->seq_table[i],
4690                                   &timeouts, timeout_period, i,
4691                                   &flags, &need_timer);
4692         spin_unlock_irqrestore(&intf->seq_lock, flags);
4693
4694         list_for_each_entry_safe(msg, msg2, &timeouts, link)
4695                 deliver_err_response(intf, msg, IPMI_TIMEOUT_COMPLETION_CODE);
4696
4697         /*
4698          * Maintenance mode handling.  Check the timeout
4699          * optimistically before we claim the lock.  It may
4700          * mean a timeout gets missed occasionally, but that
4701          * only means the timeout gets extended by one period
4702          * in that case.  No big deal, and it avoids the lock
4703          * most of the time.
4704          */
4705         if (intf->auto_maintenance_timeout > 0) {
4706                 spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
4707                 if (intf->auto_maintenance_timeout > 0) {
4708                         intf->auto_maintenance_timeout
4709                                 -= timeout_period;
4710                         if (!intf->maintenance_mode
4711                             && (intf->auto_maintenance_timeout <= 0)) {
4712                                 intf->maintenance_mode_enable = false;
4713                                 maintenance_mode_update(intf);
4714                         }
4715                 }
4716                 spin_unlock_irqrestore(&intf->maintenance_mode_lock,
4717                                        flags);
4718         }
4719
4720         tasklet_schedule(&intf->recv_tasklet);
4721
4722         return need_timer;
4723 }
4724
4725 static void ipmi_request_event(struct ipmi_smi *intf)
4726 {
4727         /* No event requests when in maintenance mode. */
4728         if (intf->maintenance_mode_enable)
4729                 return;
4730
4731         if (!intf->in_shutdown)
4732                 intf->handlers->request_events(intf->send_info);
4733 }
4734
4735 static struct timer_list ipmi_timer;
4736
4737 static atomic_t stop_operation;
4738
4739 static void ipmi_timeout(struct timer_list *unused)
4740 {
4741         struct ipmi_smi *intf;
4742         bool need_timer = false;
4743         int index;
4744
4745         if (atomic_read(&stop_operation))
4746                 return;
4747
4748         index = srcu_read_lock(&ipmi_interfaces_srcu);
4749         list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
4750                 if (atomic_read(&intf->event_waiters)) {
4751                         intf->ticks_to_req_ev--;
4752                         if (intf->ticks_to_req_ev == 0) {
4753                                 ipmi_request_event(intf);
4754                                 intf->ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
4755                         }
4756                         need_timer = true;
4757                 }
4758
4759                 need_timer |= ipmi_timeout_handler(intf, IPMI_TIMEOUT_TIME);
4760         }
4761         srcu_read_unlock(&ipmi_interfaces_srcu, index);
4762
4763         if (need_timer)
4764                 mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
4765 }
4766
4767 static void need_waiter(struct ipmi_smi *intf)
4768 {
4769         /* Racy, but worst case we start the timer twice. */
4770         if (!timer_pending(&ipmi_timer))
4771                 mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
4772 }
4773
4774 static atomic_t smi_msg_inuse_count = ATOMIC_INIT(0);
4775 static atomic_t recv_msg_inuse_count = ATOMIC_INIT(0);
4776
4777 static void free_smi_msg(struct ipmi_smi_msg *msg)
4778 {
4779         atomic_dec(&smi_msg_inuse_count);
4780         kfree(msg);
4781 }
4782
4783 struct ipmi_smi_msg *ipmi_alloc_smi_msg(void)
4784 {
4785         struct ipmi_smi_msg *rv;
4786         rv = kmalloc(sizeof(struct ipmi_smi_msg), GFP_ATOMIC);
4787         if (rv) {
4788                 rv->done = free_smi_msg;
4789                 rv->user_data = NULL;
4790                 atomic_inc(&smi_msg_inuse_count);
4791         }
4792         return rv;
4793 }
4794 EXPORT_SYMBOL(ipmi_alloc_smi_msg);
4795
4796 static void free_recv_msg(struct ipmi_recv_msg *msg)
4797 {
4798         atomic_dec(&recv_msg_inuse_count);
4799         kfree(msg);
4800 }
4801
4802 static struct ipmi_recv_msg *ipmi_alloc_recv_msg(void)
4803 {
4804         struct ipmi_recv_msg *rv;
4805
4806         rv = kmalloc(sizeof(struct ipmi_recv_msg), GFP_ATOMIC);
4807         if (rv) {
4808                 rv->user = NULL;
4809                 rv->done = free_recv_msg;
4810                 atomic_inc(&recv_msg_inuse_count);
4811         }
4812         return rv;
4813 }
4814
4815 void ipmi_free_recv_msg(struct ipmi_recv_msg *msg)
4816 {
4817         if (msg->user)
4818                 kref_put(&msg->user->refcount, free_user);
4819         msg->done(msg);
4820 }
4821 EXPORT_SYMBOL(ipmi_free_recv_msg);
4822
4823 static atomic_t panic_done_count = ATOMIC_INIT(0);
4824
4825 static void dummy_smi_done_handler(struct ipmi_smi_msg *msg)
4826 {
4827         atomic_dec(&panic_done_count);
4828 }
4829
4830 static void dummy_recv_done_handler(struct ipmi_recv_msg *msg)
4831 {
4832         atomic_dec(&panic_done_count);
4833 }
4834
4835 /*
4836  * Inside a panic, send a message and wait for a response.
4837  */
4838 static void ipmi_panic_request_and_wait(struct ipmi_smi *intf,
4839                                         struct ipmi_addr *addr,
4840                                         struct kernel_ipmi_msg *msg)
4841 {
4842         struct ipmi_smi_msg  smi_msg;
4843         struct ipmi_recv_msg recv_msg;
4844         int rv;
4845
4846         smi_msg.done = dummy_smi_done_handler;
4847         recv_msg.done = dummy_recv_done_handler;
4848         atomic_add(2, &panic_done_count);
4849         rv = i_ipmi_request(NULL,
4850                             intf,
4851                             addr,
4852                             0,
4853                             msg,
4854                             intf,
4855                             &smi_msg,
4856                             &recv_msg,
4857                             0,
4858                             intf->addrinfo[0].address,
4859                             intf->addrinfo[0].lun,
4860                             0, 1); /* Don't retry, and don't wait. */
4861         if (rv)
4862                 atomic_sub(2, &panic_done_count);
4863         else if (intf->handlers->flush_messages)
4864                 intf->handlers->flush_messages(intf->send_info);
4865
4866         while (atomic_read(&panic_done_count) != 0)
4867                 ipmi_poll(intf);
4868 }
4869
4870 static void event_receiver_fetcher(struct ipmi_smi *intf,
4871                                    struct ipmi_recv_msg *msg)
4872 {
4873         if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
4874             && (msg->msg.netfn == IPMI_NETFN_SENSOR_EVENT_RESPONSE)
4875             && (msg->msg.cmd == IPMI_GET_EVENT_RECEIVER_CMD)
4876             && (msg->msg.data[0] == IPMI_CC_NO_ERROR)) {
4877                 /* A get event receiver command, save it. */
4878                 intf->event_receiver = msg->msg.data[1];
4879                 intf->event_receiver_lun = msg->msg.data[2] & 0x3;
4880         }
4881 }
4882
4883 static void device_id_fetcher(struct ipmi_smi *intf, struct ipmi_recv_msg *msg)
4884 {
4885         if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
4886             && (msg->msg.netfn == IPMI_NETFN_APP_RESPONSE)
4887             && (msg->msg.cmd == IPMI_GET_DEVICE_ID_CMD)
4888             && (msg->msg.data[0] == IPMI_CC_NO_ERROR)) {
4889                 /*
4890                  * A get device id command, save if we are an event
4891                  * receiver or generator.
4892                  */
4893                 intf->local_sel_device = (msg->msg.data[6] >> 2) & 1;
4894                 intf->local_event_generator = (msg->msg.data[6] >> 5) & 1;
4895         }
4896 }
4897
4898 static void send_panic_events(struct ipmi_smi *intf, char *str)
4899 {
4900         struct kernel_ipmi_msg msg;
4901         unsigned char data[16];
4902         struct ipmi_system_interface_addr *si;
4903         struct ipmi_addr addr;
4904         char *p = str;
4905         struct ipmi_ipmb_addr *ipmb;
4906         int j;
4907
4908         if (ipmi_send_panic_event == IPMI_SEND_PANIC_EVENT_NONE)
4909                 return;
4910
4911         si = (struct ipmi_system_interface_addr *) &addr;
4912         si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
4913         si->channel = IPMI_BMC_CHANNEL;
4914         si->lun = 0;
4915
4916         /* Fill in an event telling that we have failed. */
4917         msg.netfn = 0x04; /* Sensor or Event. */
4918         msg.cmd = 2; /* Platform event command. */
4919         msg.data = data;
4920         msg.data_len = 8;
4921         data[0] = 0x41; /* Kernel generator ID, IPMI table 5-4 */
4922         data[1] = 0x03; /* This is for IPMI 1.0. */
4923         data[2] = 0x20; /* OS Critical Stop, IPMI table 36-3 */
4924         data[4] = 0x6f; /* Sensor specific, IPMI table 36-1 */
4925         data[5] = 0xa1; /* Runtime stop OEM bytes 2 & 3. */
4926
4927         /*
4928          * Put a few breadcrumbs in.  Hopefully later we can add more things
4929          * to make the panic events more useful.
4930          */
4931         if (str) {
4932                 data[3] = str[0];
4933                 data[6] = str[1];
4934                 data[7] = str[2];
4935         }
4936
4937         /* Send the event announcing the panic. */
4938         ipmi_panic_request_and_wait(intf, &addr, &msg);
4939
4940         /*
4941          * On every interface, dump a bunch of OEM event holding the
4942          * string.
4943          */
4944         if (ipmi_send_panic_event != IPMI_SEND_PANIC_EVENT_STRING || !str)
4945                 return;
4946
4947         /*
4948          * intf_num is used as an marker to tell if the
4949          * interface is valid.  Thus we need a read barrier to
4950          * make sure data fetched before checking intf_num
4951          * won't be used.
4952          */
4953         smp_rmb();
4954
4955         /*
4956          * First job here is to figure out where to send the
4957          * OEM events.  There's no way in IPMI to send OEM
4958          * events using an event send command, so we have to
4959          * find the SEL to put them in and stick them in
4960          * there.
4961          */
4962
4963         /* Get capabilities from the get device id. */
4964         intf->local_sel_device = 0;
4965         intf->local_event_generator = 0;
4966         intf->event_receiver = 0;
4967
4968         /* Request the device info from the local MC. */
4969         msg.netfn = IPMI_NETFN_APP_REQUEST;
4970         msg.cmd = IPMI_GET_DEVICE_ID_CMD;
4971         msg.data = NULL;
4972         msg.data_len = 0;
4973         intf->null_user_handler = device_id_fetcher;
4974         ipmi_panic_request_and_wait(intf, &addr, &msg);
4975
4976         if (intf->local_event_generator) {
4977                 /* Request the event receiver from the local MC. */
4978                 msg.netfn = IPMI_NETFN_SENSOR_EVENT_REQUEST;
4979                 msg.cmd = IPMI_GET_EVENT_RECEIVER_CMD;
4980                 msg.data = NULL;
4981                 msg.data_len = 0;
4982                 intf->null_user_handler = event_receiver_fetcher;
4983                 ipmi_panic_request_and_wait(intf, &addr, &msg);
4984         }
4985         intf->null_user_handler = NULL;
4986
4987         /*
4988          * Validate the event receiver.  The low bit must not
4989          * be 1 (it must be a valid IPMB address), it cannot
4990          * be zero, and it must not be my address.
4991          */
4992         if (((intf->event_receiver & 1) == 0)
4993             && (intf->event_receiver != 0)
4994             && (intf->event_receiver != intf->addrinfo[0].address)) {
4995                 /*
4996                  * The event receiver is valid, send an IPMB
4997                  * message.
4998                  */
4999                 ipmb = (struct ipmi_ipmb_addr *) &addr;
5000                 ipmb->addr_type = IPMI_IPMB_ADDR_TYPE;
5001                 ipmb->channel = 0; /* FIXME - is this right? */
5002                 ipmb->lun = intf->event_receiver_lun;
5003                 ipmb->slave_addr = intf->event_receiver;
5004         } else if (intf->local_sel_device) {
5005                 /*
5006                  * The event receiver was not valid (or was
5007                  * me), but I am an SEL device, just dump it
5008                  * in my SEL.
5009                  */
5010                 si = (struct ipmi_system_interface_addr *) &addr;
5011                 si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
5012                 si->channel = IPMI_BMC_CHANNEL;
5013                 si->lun = 0;
5014         } else
5015                 return; /* No where to send the event. */
5016
5017         msg.netfn = IPMI_NETFN_STORAGE_REQUEST; /* Storage. */
5018         msg.cmd = IPMI_ADD_SEL_ENTRY_CMD;
5019         msg.data = data;
5020         msg.data_len = 16;
5021
5022         j = 0;
5023         while (*p) {
5024                 int size = strlen(p);
5025
5026                 if (size > 11)
5027                         size = 11;
5028                 data[0] = 0;
5029                 data[1] = 0;
5030                 data[2] = 0xf0; /* OEM event without timestamp. */
5031                 data[3] = intf->addrinfo[0].address;
5032                 data[4] = j++; /* sequence # */
5033                 /*
5034                  * Always give 11 bytes, so strncpy will fill
5035                  * it with zeroes for me.
5036                  */
5037                 strncpy(data+5, p, 11);
5038                 p += size;
5039
5040                 ipmi_panic_request_and_wait(intf, &addr, &msg);
5041         }
5042 }
5043
5044 static int has_panicked;
5045
5046 static int panic_event(struct notifier_block *this,
5047                        unsigned long         event,
5048                        void                  *ptr)
5049 {
5050         struct ipmi_smi *intf;
5051         struct ipmi_user *user;
5052
5053         if (has_panicked)
5054                 return NOTIFY_DONE;
5055         has_panicked = 1;
5056
5057         /* For every registered interface, set it to run to completion. */
5058         list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
5059                 if (!intf->handlers || intf->intf_num == -1)
5060                         /* Interface is not ready. */
5061                         continue;
5062
5063                 if (!intf->handlers->poll)
5064                         continue;
5065
5066                 /*
5067                  * If we were interrupted while locking xmit_msgs_lock or
5068                  * waiting_rcv_msgs_lock, the corresponding list may be
5069                  * corrupted.  In this case, drop items on the list for
5070                  * the safety.
5071                  */
5072                 if (!spin_trylock(&intf->xmit_msgs_lock)) {
5073                         INIT_LIST_HEAD(&intf->xmit_msgs);
5074                         INIT_LIST_HEAD(&intf->hp_xmit_msgs);
5075                 } else
5076                         spin_unlock(&intf->xmit_msgs_lock);
5077
5078                 if (!spin_trylock(&intf->waiting_rcv_msgs_lock))
5079                         INIT_LIST_HEAD(&intf->waiting_rcv_msgs);
5080                 else
5081                         spin_unlock(&intf->waiting_rcv_msgs_lock);
5082
5083                 intf->run_to_completion = 1;
5084                 if (intf->handlers->set_run_to_completion)
5085                         intf->handlers->set_run_to_completion(intf->send_info,
5086                                                               1);
5087
5088                 list_for_each_entry_rcu(user, &intf->users, link) {
5089                         if (user->handler->ipmi_panic_handler)
5090                                 user->handler->ipmi_panic_handler(
5091                                         user->handler_data);
5092                 }
5093
5094                 send_panic_events(intf, ptr);
5095         }
5096
5097         return NOTIFY_DONE;
5098 }
5099
5100 /* Must be called with ipmi_interfaces_mutex held. */
5101 static int ipmi_register_driver(void)
5102 {
5103         int rv;
5104
5105         if (drvregistered)
5106                 return 0;
5107
5108         rv = driver_register(&ipmidriver.driver);
5109         if (rv)
5110                 pr_err("Could not register IPMI driver\n");
5111         else
5112                 drvregistered = true;
5113         return rv;
5114 }
5115
5116 static struct notifier_block panic_block = {
5117         .notifier_call  = panic_event,
5118         .next           = NULL,
5119         .priority       = 200   /* priority: INT_MAX >= x >= 0 */
5120 };
5121
5122 static int ipmi_init_msghandler(void)
5123 {
5124         int rv;
5125
5126         mutex_lock(&ipmi_interfaces_mutex);
5127         rv = ipmi_register_driver();
5128         if (rv)
5129                 goto out;
5130         if (initialized)
5131                 goto out;
5132
5133         init_srcu_struct(&ipmi_interfaces_srcu);
5134
5135         timer_setup(&ipmi_timer, ipmi_timeout, 0);
5136         mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
5137
5138         atomic_notifier_chain_register(&panic_notifier_list, &panic_block);
5139
5140         initialized = true;
5141
5142 out:
5143         mutex_unlock(&ipmi_interfaces_mutex);
5144         return rv;
5145 }
5146
5147 static int __init ipmi_init_msghandler_mod(void)
5148 {
5149         int rv;
5150
5151         pr_info("version " IPMI_DRIVER_VERSION "\n");
5152
5153         mutex_lock(&ipmi_interfaces_mutex);
5154         rv = ipmi_register_driver();
5155         mutex_unlock(&ipmi_interfaces_mutex);
5156
5157         return rv;
5158 }
5159
5160 static void __exit cleanup_ipmi(void)
5161 {
5162         int count;
5163
5164         if (initialized) {
5165                 atomic_notifier_chain_unregister(&panic_notifier_list,
5166                                                  &panic_block);
5167
5168                 /*
5169                  * This can't be called if any interfaces exist, so no worry
5170                  * about shutting down the interfaces.
5171                  */
5172
5173                 /*
5174                  * Tell the timer to stop, then wait for it to stop.  This
5175                  * avoids problems with race conditions removing the timer
5176                  * here.
5177                  */
5178                 atomic_set(&stop_operation, 1);
5179                 del_timer_sync(&ipmi_timer);
5180
5181                 initialized = false;
5182
5183                 /* Check for buffer leaks. */
5184                 count = atomic_read(&smi_msg_inuse_count);
5185                 if (count != 0)
5186                         pr_warn("SMI message count %d at exit\n", count);
5187                 count = atomic_read(&recv_msg_inuse_count);
5188                 if (count != 0)
5189                         pr_warn("recv message count %d at exit\n", count);
5190
5191                 cleanup_srcu_struct(&ipmi_interfaces_srcu);
5192         }
5193         if (drvregistered)
5194                 driver_unregister(&ipmidriver.driver);
5195 }
5196 module_exit(cleanup_ipmi);
5197
5198 module_init(ipmi_init_msghandler_mod);
5199 MODULE_LICENSE("GPL");
5200 MODULE_AUTHOR("Corey Minyard <[email protected]>");
5201 MODULE_DESCRIPTION("Incoming and outgoing message routing for an IPMI"
5202                    " interface.");
5203 MODULE_VERSION(IPMI_DRIVER_VERSION);
5204 MODULE_SOFTDEP("post: ipmi_devintf");
This page took 0.345046 seconds and 4 git commands to generate.