File Index
Files and directories
Sign in
FILE

ipmi_msghandler.c

File preview with syntax highlighting.

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