GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / char / ipmi / ipmi_ssif.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * ipmi_ssif.c
4  *
5  * The interface to the IPMI driver for SMBus access to a SMBus
6  * compliant device.  Called SSIF by the IPMI spec.
7  *
8  * Author: Intel Corporation
9  *         Todd Davis <todd.c.davis@intel.com>
10  *
11  * Rewritten by Corey Minyard <minyard@acm.org> to support the
12  * non-blocking I2C interface, add support for multi-part
13  * transactions, add PEC support, and general clenaup.
14  *
15  * Copyright 2003 Intel Corporation
16  * Copyright 2005 MontaVista Software
17  */
18
19 /*
20  * This file holds the "policy" for the interface to the SSIF state
21  * machine.  It does the configuration, handles timers and interrupts,
22  * and drives the real SSIF state machine.
23  */
24
25 /*
26  * TODO: Figure out how to use SMB alerts.  This will require a new
27  * interface into the I2C driver, I believe.
28  */
29
30 #if defined(MODVERSIONS)
31 #include <linux/modversions.h>
32 #endif
33
34 #include <linux/module.h>
35 #include <linux/moduleparam.h>
36 #include <linux/sched.h>
37 #include <linux/seq_file.h>
38 #include <linux/timer.h>
39 #include <linux/delay.h>
40 #include <linux/errno.h>
41 #include <linux/spinlock.h>
42 #include <linux/slab.h>
43 #include <linux/list.h>
44 #include <linux/i2c.h>
45 #include <linux/ipmi_smi.h>
46 #include <linux/init.h>
47 #include <linux/dmi.h>
48 #include <linux/kthread.h>
49 #include <linux/acpi.h>
50 #include <linux/ctype.h>
51 #include <linux/time64.h>
52 #include "ipmi_si_sm.h"
53 #include "ipmi_dmi.h"
54
55 #define PFX "ipmi_ssif: "
56 #define DEVICE_NAME "ipmi_ssif"
57
58 #define IPMI_GET_SYSTEM_INTERFACE_CAPABILITIES_CMD      0x57
59
60 #define SSIF_IPMI_REQUEST                       2
61 #define SSIF_IPMI_MULTI_PART_REQUEST_START      6
62 #define SSIF_IPMI_MULTI_PART_REQUEST_MIDDLE     7
63 #define SSIF_IPMI_RESPONSE                      3
64 #define SSIF_IPMI_MULTI_PART_RESPONSE_MIDDLE    9
65
66 /* ssif_debug is a bit-field
67  *      SSIF_DEBUG_MSG -        commands and their responses
68  *      SSIF_DEBUG_STATES -     message states
69  *      SSIF_DEBUG_TIMING -      Measure times between events in the driver
70  */
71 #define SSIF_DEBUG_TIMING       4
72 #define SSIF_DEBUG_STATE        2
73 #define SSIF_DEBUG_MSG          1
74 #define SSIF_NODEBUG            0
75 #define SSIF_DEFAULT_DEBUG      (SSIF_NODEBUG)
76
77 /*
78  * Timer values
79  */
80 #define SSIF_MSG_USEC           20000   /* 20ms between message tries. */
81 #define SSIF_MSG_PART_USEC      5000    /* 5ms for a message part */
82
83 /* How many times to we retry sending/receiving the message. */
84 #define SSIF_SEND_RETRIES       5
85 #define SSIF_RECV_RETRIES       250
86
87 #define SSIF_MSG_MSEC           (SSIF_MSG_USEC / 1000)
88 #define SSIF_MSG_JIFFIES        ((SSIF_MSG_USEC * 1000) / TICK_NSEC)
89 #define SSIF_MSG_PART_JIFFIES   ((SSIF_MSG_PART_USEC * 1000) / TICK_NSEC)
90
91 enum ssif_intf_state {
92         SSIF_NORMAL,
93         SSIF_GETTING_FLAGS,
94         SSIF_GETTING_EVENTS,
95         SSIF_CLEARING_FLAGS,
96         SSIF_GETTING_MESSAGES,
97         /* FIXME - add watchdog stuff. */
98 };
99
100 #define SSIF_IDLE(ssif)  ((ssif)->ssif_state == SSIF_NORMAL \
101                           && (ssif)->curr_msg == NULL)
102
103 /*
104  * Indexes into stats[] in ssif_info below.
105  */
106 enum ssif_stat_indexes {
107         /* Number of total messages sent. */
108         SSIF_STAT_sent_messages = 0,
109
110         /*
111          * Number of message parts sent.  Messages may be broken into
112          * parts if they are long.
113          */
114         SSIF_STAT_sent_messages_parts,
115
116         /*
117          * Number of time a message was retried.
118          */
119         SSIF_STAT_send_retries,
120
121         /*
122          * Number of times the send of a message failed.
123          */
124         SSIF_STAT_send_errors,
125
126         /*
127          * Number of message responses received.
128          */
129         SSIF_STAT_received_messages,
130
131         /*
132          * Number of message fragments received.
133          */
134         SSIF_STAT_received_message_parts,
135
136         /*
137          * Number of times the receive of a message was retried.
138          */
139         SSIF_STAT_receive_retries,
140
141         /*
142          * Number of errors receiving messages.
143          */
144         SSIF_STAT_receive_errors,
145
146         /*
147          * Number of times a flag fetch was requested.
148          */
149         SSIF_STAT_flag_fetches,
150
151         /*
152          * Number of times the hardware didn't follow the state machine.
153          */
154         SSIF_STAT_hosed,
155
156         /*
157          * Number of received events.
158          */
159         SSIF_STAT_events,
160
161         /* Number of asyncronous messages received. */
162         SSIF_STAT_incoming_messages,
163
164         /* Number of watchdog pretimeouts. */
165         SSIF_STAT_watchdog_pretimeouts,
166
167         /* Number of alers received. */
168         SSIF_STAT_alerts,
169
170         /* Always add statistics before this value, it must be last. */
171         SSIF_NUM_STATS
172 };
173
174 struct ssif_addr_info {
175         struct i2c_board_info binfo;
176         char *adapter_name;
177         int debug;
178         int slave_addr;
179         enum ipmi_addr_src addr_src;
180         union ipmi_smi_info_union addr_info;
181         struct device *dev;
182         struct i2c_client *client;
183
184         struct i2c_client *added_client;
185
186         struct mutex clients_mutex;
187         struct list_head clients;
188
189         struct list_head link;
190 };
191
192 struct ssif_info;
193
194 typedef void (*ssif_i2c_done)(struct ssif_info *ssif_info, int result,
195                              unsigned char *data, unsigned int len);
196
197 struct ssif_info {
198         struct ipmi_smi     *intf;
199         spinlock_t          lock;
200         struct ipmi_smi_msg *waiting_msg;
201         struct ipmi_smi_msg *curr_msg;
202         enum ssif_intf_state ssif_state;
203         unsigned long       ssif_debug;
204
205         struct ipmi_smi_handlers handlers;
206
207         enum ipmi_addr_src addr_source; /* ACPI, PCI, SMBIOS, hardcode, etc. */
208         union ipmi_smi_info_union addr_info;
209
210         /*
211          * Flags from the last GET_MSG_FLAGS command, used when an ATTN
212          * is set to hold the flags until we are done handling everything
213          * from the flags.
214          */
215 #define RECEIVE_MSG_AVAIL       0x01
216 #define EVENT_MSG_BUFFER_FULL   0x02
217 #define WDT_PRE_TIMEOUT_INT     0x08
218         unsigned char       msg_flags;
219
220         u8                  global_enables;
221         bool                has_event_buffer;
222         bool                supports_alert;
223
224         /*
225          * Used to tell what we should do with alerts.  If we are
226          * waiting on a response, read the data immediately.
227          */
228         bool                got_alert;
229         bool                waiting_alert;
230
231         /*
232          * If set to true, this will request events the next time the
233          * state machine is idle.
234          */
235         bool                req_events;
236
237         /*
238          * If set to true, this will request flags the next time the
239          * state machine is idle.
240          */
241         bool                req_flags;
242
243         /*
244          * Used to perform timer operations when run-to-completion
245          * mode is on.  This is a countdown timer.
246          */
247         int                 rtc_us_timer;
248
249         /* Used for sending/receiving data.  +1 for the length. */
250         unsigned char data[IPMI_MAX_MSG_LENGTH + 1];
251         unsigned int  data_len;
252
253         /* Temp receive buffer, gets copied into data. */
254         unsigned char recv[I2C_SMBUS_BLOCK_MAX];
255
256         struct i2c_client *client;
257         ssif_i2c_done done_handler;
258
259         /* Thread interface handling */
260         struct task_struct *thread;
261         struct completion wake_thread;
262         bool stopping;
263         int i2c_read_write;
264         int i2c_command;
265         unsigned char *i2c_data;
266         unsigned int i2c_size;
267
268         struct timer_list retry_timer;
269         int retries_left;
270
271         /* Info from SSIF cmd */
272         unsigned char max_xmit_msg_size;
273         unsigned char max_recv_msg_size;
274         unsigned int  multi_support;
275         int           supports_pec;
276
277 #define SSIF_NO_MULTI           0
278 #define SSIF_MULTI_2_PART       1
279 #define SSIF_MULTI_n_PART       2
280         unsigned char *multi_data;
281         unsigned int  multi_len;
282         unsigned int  multi_pos;
283
284         atomic_t stats[SSIF_NUM_STATS];
285 };
286
287 #define ssif_inc_stat(ssif, stat) \
288         atomic_inc(&(ssif)->stats[SSIF_STAT_ ## stat])
289 #define ssif_get_stat(ssif, stat) \
290         ((unsigned int) atomic_read(&(ssif)->stats[SSIF_STAT_ ## stat]))
291
292 static bool initialized;
293
294 static void return_hosed_msg(struct ssif_info *ssif_info,
295                              struct ipmi_smi_msg *msg);
296 static void start_next_msg(struct ssif_info *ssif_info, unsigned long *flags);
297 static int start_send(struct ssif_info *ssif_info,
298                       unsigned char   *data,
299                       unsigned int    len);
300
301 static unsigned long *ipmi_ssif_lock_cond(struct ssif_info *ssif_info,
302                                           unsigned long *flags)
303 {
304         spin_lock_irqsave(&ssif_info->lock, *flags);
305         return flags;
306 }
307
308 static void ipmi_ssif_unlock_cond(struct ssif_info *ssif_info,
309                                   unsigned long *flags)
310 {
311         spin_unlock_irqrestore(&ssif_info->lock, *flags);
312 }
313
314 static void deliver_recv_msg(struct ssif_info *ssif_info,
315                              struct ipmi_smi_msg *msg)
316 {
317         if (msg->rsp_size < 0) {
318                 return_hosed_msg(ssif_info, msg);
319                 pr_err(PFX
320                        "Malformed message in deliver_recv_msg: rsp_size = %d\n",
321                        msg->rsp_size);
322         } else {
323                 ipmi_smi_msg_received(ssif_info->intf, msg);
324         }
325 }
326
327 static void return_hosed_msg(struct ssif_info *ssif_info,
328                              struct ipmi_smi_msg *msg)
329 {
330         ssif_inc_stat(ssif_info, hosed);
331
332         /* Make it a response */
333         msg->rsp[0] = msg->data[0] | 4;
334         msg->rsp[1] = msg->data[1];
335         msg->rsp[2] = 0xFF; /* Unknown error. */
336         msg->rsp_size = 3;
337
338         deliver_recv_msg(ssif_info, msg);
339 }
340
341 /*
342  * Must be called with the message lock held.  This will release the
343  * message lock.  Note that the caller will check SSIF_IDLE and start a
344  * new operation, so there is no need to check for new messages to
345  * start in here.
346  */
347 static void start_clear_flags(struct ssif_info *ssif_info, unsigned long *flags)
348 {
349         unsigned char msg[3];
350
351         ssif_info->msg_flags &= ~WDT_PRE_TIMEOUT_INT;
352         ssif_info->ssif_state = SSIF_CLEARING_FLAGS;
353         ipmi_ssif_unlock_cond(ssif_info, flags);
354
355         /* Make sure the watchdog pre-timeout flag is not set at startup. */
356         msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
357         msg[1] = IPMI_CLEAR_MSG_FLAGS_CMD;
358         msg[2] = WDT_PRE_TIMEOUT_INT;
359
360         if (start_send(ssif_info, msg, 3) != 0) {
361                 /* Error, just go to normal state. */
362                 ssif_info->ssif_state = SSIF_NORMAL;
363         }
364 }
365
366 static void start_flag_fetch(struct ssif_info *ssif_info, unsigned long *flags)
367 {
368         unsigned char mb[2];
369
370         ssif_info->req_flags = false;
371         ssif_info->ssif_state = SSIF_GETTING_FLAGS;
372         ipmi_ssif_unlock_cond(ssif_info, flags);
373
374         mb[0] = (IPMI_NETFN_APP_REQUEST << 2);
375         mb[1] = IPMI_GET_MSG_FLAGS_CMD;
376         if (start_send(ssif_info, mb, 2) != 0)
377                 ssif_info->ssif_state = SSIF_NORMAL;
378 }
379
380 static void check_start_send(struct ssif_info *ssif_info, unsigned long *flags,
381                              struct ipmi_smi_msg *msg)
382 {
383         if (start_send(ssif_info, msg->data, msg->data_size) != 0) {
384                 unsigned long oflags;
385
386                 flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
387                 ssif_info->curr_msg = NULL;
388                 ssif_info->ssif_state = SSIF_NORMAL;
389                 ipmi_ssif_unlock_cond(ssif_info, flags);
390                 ipmi_free_smi_msg(msg);
391         }
392 }
393
394 static void start_event_fetch(struct ssif_info *ssif_info, unsigned long *flags)
395 {
396         struct ipmi_smi_msg *msg;
397
398         ssif_info->req_events = false;
399
400         msg = ipmi_alloc_smi_msg();
401         if (!msg) {
402                 ssif_info->ssif_state = SSIF_NORMAL;
403                 ipmi_ssif_unlock_cond(ssif_info, flags);
404                 return;
405         }
406
407         ssif_info->curr_msg = msg;
408         ssif_info->ssif_state = SSIF_GETTING_EVENTS;
409         ipmi_ssif_unlock_cond(ssif_info, flags);
410
411         msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
412         msg->data[1] = IPMI_READ_EVENT_MSG_BUFFER_CMD;
413         msg->data_size = 2;
414
415         check_start_send(ssif_info, flags, msg);
416 }
417
418 static void start_recv_msg_fetch(struct ssif_info *ssif_info,
419                                  unsigned long *flags)
420 {
421         struct ipmi_smi_msg *msg;
422
423         msg = ipmi_alloc_smi_msg();
424         if (!msg) {
425                 ssif_info->ssif_state = SSIF_NORMAL;
426                 ipmi_ssif_unlock_cond(ssif_info, flags);
427                 return;
428         }
429
430         ssif_info->curr_msg = msg;
431         ssif_info->ssif_state = SSIF_GETTING_MESSAGES;
432         ipmi_ssif_unlock_cond(ssif_info, flags);
433
434         msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
435         msg->data[1] = IPMI_GET_MSG_CMD;
436         msg->data_size = 2;
437
438         check_start_send(ssif_info, flags, msg);
439 }
440
441 /*
442  * Must be called with the message lock held.  This will release the
443  * message lock.  Note that the caller will check SSIF_IDLE and start a
444  * new operation, so there is no need to check for new messages to
445  * start in here.
446  */
447 static void handle_flags(struct ssif_info *ssif_info, unsigned long *flags)
448 {
449         if (ssif_info->msg_flags & WDT_PRE_TIMEOUT_INT) {
450                 /* Watchdog pre-timeout */
451                 ssif_inc_stat(ssif_info, watchdog_pretimeouts);
452                 start_clear_flags(ssif_info, flags);
453                 ipmi_smi_watchdog_pretimeout(ssif_info->intf);
454         } else if (ssif_info->msg_flags & RECEIVE_MSG_AVAIL)
455                 /* Messages available. */
456                 start_recv_msg_fetch(ssif_info, flags);
457         else if (ssif_info->msg_flags & EVENT_MSG_BUFFER_FULL)
458                 /* Events available. */
459                 start_event_fetch(ssif_info, flags);
460         else {
461                 ssif_info->ssif_state = SSIF_NORMAL;
462                 ipmi_ssif_unlock_cond(ssif_info, flags);
463         }
464 }
465
466 static int ipmi_ssif_thread(void *data)
467 {
468         struct ssif_info *ssif_info = data;
469
470         while (!kthread_should_stop()) {
471                 int result;
472
473                 /* Wait for something to do */
474                 result = wait_for_completion_interruptible(
475                                                 &ssif_info->wake_thread);
476                 if (ssif_info->stopping)
477                         break;
478                 if (result == -ERESTARTSYS)
479                         continue;
480                 init_completion(&ssif_info->wake_thread);
481
482                 if (ssif_info->i2c_read_write == I2C_SMBUS_WRITE) {
483                         result = i2c_smbus_write_block_data(
484                                 ssif_info->client, ssif_info->i2c_command,
485                                 ssif_info->i2c_data[0],
486                                 ssif_info->i2c_data + 1);
487                         ssif_info->done_handler(ssif_info, result, NULL, 0);
488                 } else {
489                         result = i2c_smbus_read_block_data(
490                                 ssif_info->client, ssif_info->i2c_command,
491                                 ssif_info->i2c_data);
492                         if (result < 0)
493                                 ssif_info->done_handler(ssif_info, result,
494                                                         NULL, 0);
495                         else
496                                 ssif_info->done_handler(ssif_info, 0,
497                                                         ssif_info->i2c_data,
498                                                         result);
499                 }
500         }
501
502         return 0;
503 }
504
505 static int ssif_i2c_send(struct ssif_info *ssif_info,
506                         ssif_i2c_done handler,
507                         int read_write, int command,
508                         unsigned char *data, unsigned int size)
509 {
510         ssif_info->done_handler = handler;
511
512         ssif_info->i2c_read_write = read_write;
513         ssif_info->i2c_command = command;
514         ssif_info->i2c_data = data;
515         ssif_info->i2c_size = size;
516         complete(&ssif_info->wake_thread);
517         return 0;
518 }
519
520
521 static void msg_done_handler(struct ssif_info *ssif_info, int result,
522                              unsigned char *data, unsigned int len);
523
524 static void start_get(struct ssif_info *ssif_info)
525 {
526         int rv;
527
528         ssif_info->rtc_us_timer = 0;
529         ssif_info->multi_pos = 0;
530
531         rv = ssif_i2c_send(ssif_info, msg_done_handler, I2C_SMBUS_READ,
532                           SSIF_IPMI_RESPONSE,
533                           ssif_info->recv, I2C_SMBUS_BLOCK_DATA);
534         if (rv < 0) {
535                 /* request failed, just return the error. */
536                 if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
537                         pr_info("Error from i2c_non_blocking_op(5)\n");
538
539                 msg_done_handler(ssif_info, -EIO, NULL, 0);
540         }
541 }
542
543 static void retry_timeout(struct timer_list *t)
544 {
545         struct ssif_info *ssif_info = from_timer(ssif_info, t, retry_timer);
546         unsigned long oflags, *flags;
547         bool waiting;
548
549         if (ssif_info->stopping)
550                 return;
551
552         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
553         waiting = ssif_info->waiting_alert;
554         ssif_info->waiting_alert = false;
555         ipmi_ssif_unlock_cond(ssif_info, flags);
556
557         if (waiting)
558                 start_get(ssif_info);
559 }
560
561
562 static void ssif_alert(struct i2c_client *client, enum i2c_alert_protocol type,
563                        unsigned int data)
564 {
565         struct ssif_info *ssif_info = i2c_get_clientdata(client);
566         unsigned long oflags, *flags;
567         bool do_get = false;
568
569         if (type != I2C_PROTOCOL_SMBUS_ALERT)
570                 return;
571
572         ssif_inc_stat(ssif_info, alerts);
573
574         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
575         if (ssif_info->waiting_alert) {
576                 ssif_info->waiting_alert = false;
577                 del_timer(&ssif_info->retry_timer);
578                 do_get = true;
579         } else if (ssif_info->curr_msg) {
580                 ssif_info->got_alert = true;
581         }
582         ipmi_ssif_unlock_cond(ssif_info, flags);
583         if (do_get)
584                 start_get(ssif_info);
585 }
586
587 static int start_resend(struct ssif_info *ssif_info);
588
589 static void msg_done_handler(struct ssif_info *ssif_info, int result,
590                              unsigned char *data, unsigned int len)
591 {
592         struct ipmi_smi_msg *msg;
593         unsigned long oflags, *flags;
594         int rv;
595
596         /*
597          * We are single-threaded here, so no need for a lock until we
598          * start messing with driver states or the queues.
599          */
600
601         if (result < 0) {
602                 ssif_info->retries_left--;
603                 if (ssif_info->retries_left > 0) {
604                         ssif_inc_stat(ssif_info, receive_retries);
605
606                         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
607                         ssif_info->waiting_alert = true;
608                         ssif_info->rtc_us_timer = SSIF_MSG_USEC;
609                         if (!ssif_info->stopping)
610                                 mod_timer(&ssif_info->retry_timer,
611                                           jiffies + SSIF_MSG_JIFFIES);
612                         ipmi_ssif_unlock_cond(ssif_info, flags);
613                         return;
614                 }
615
616                 ssif_inc_stat(ssif_info, receive_errors);
617
618                 if  (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
619                         pr_info("Error in msg_done_handler: %d\n", result);
620                 len = 0;
621                 goto continue_op;
622         }
623
624         if ((len > 1) && (ssif_info->multi_pos == 0)
625                                 && (data[0] == 0x00) && (data[1] == 0x01)) {
626                 /* Start of multi-part read.  Start the next transaction. */
627                 int i;
628
629                 ssif_inc_stat(ssif_info, received_message_parts);
630
631                 /* Remove the multi-part read marker. */
632                 len -= 2;
633                 data += 2;
634                 for (i = 0; i < len; i++)
635                         ssif_info->data[i] = data[i];
636                 ssif_info->multi_len = len;
637                 ssif_info->multi_pos = 1;
638
639                 rv = ssif_i2c_send(ssif_info, msg_done_handler, I2C_SMBUS_READ,
640                                   SSIF_IPMI_MULTI_PART_RESPONSE_MIDDLE,
641                                   ssif_info->recv, I2C_SMBUS_BLOCK_DATA);
642                 if (rv < 0) {
643                         if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
644                                 pr_info("Error from i2c_non_blocking_op(1)\n");
645
646                         result = -EIO;
647                 } else
648                         return;
649         } else if (ssif_info->multi_pos) {
650                 /* Middle of multi-part read.  Start the next transaction. */
651                 int i;
652                 unsigned char blocknum;
653
654                 if (len == 0) {
655                         result = -EIO;
656                         if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
657                                 pr_info(PFX "Middle message with no data\n");
658
659                         goto continue_op;
660                 }
661
662                 blocknum = data[0];
663                 len--;
664                 data++;
665
666                 if (blocknum != 0xff && len != 31) {
667                     /* All blocks but the last must have 31 data bytes. */
668                         result = -EIO;
669                         if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
670                                 pr_info("Received middle message <31\n");
671
672                         goto continue_op;
673                 }
674
675                 if (ssif_info->multi_len + len > IPMI_MAX_MSG_LENGTH) {
676                         /* Received message too big, abort the operation. */
677                         result = -E2BIG;
678                         if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
679                                 pr_info("Received message too big\n");
680
681                         goto continue_op;
682                 }
683
684                 for (i = 0; i < len; i++)
685                         ssif_info->data[i + ssif_info->multi_len] = data[i];
686                 ssif_info->multi_len += len;
687                 if (blocknum == 0xff) {
688                         /* End of read */
689                         len = ssif_info->multi_len;
690                         data = ssif_info->data;
691                 } else if (blocknum + 1 != ssif_info->multi_pos) {
692                         /*
693                          * Out of sequence block, just abort.  Block
694                          * numbers start at zero for the second block,
695                          * but multi_pos starts at one, so the +1.
696                          */
697                         if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
698                                 dev_dbg(&ssif_info->client->dev,
699                                         "Received message out of sequence, expected %u, got %u\n",
700                                         ssif_info->multi_pos - 1, blocknum);
701                         result = -EIO;
702                 } else {
703                         ssif_inc_stat(ssif_info, received_message_parts);
704
705                         ssif_info->multi_pos++;
706
707                         rv = ssif_i2c_send(ssif_info, msg_done_handler,
708                                            I2C_SMBUS_READ,
709                                            SSIF_IPMI_MULTI_PART_RESPONSE_MIDDLE,
710                                            ssif_info->recv,
711                                            I2C_SMBUS_BLOCK_DATA);
712                         if (rv < 0) {
713                                 if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
714                                         pr_info(PFX
715                                                 "Error from ssif_i2c_send\n");
716
717                                 result = -EIO;
718                         } else
719                                 return;
720                 }
721         }
722
723  continue_op:
724         if (result < 0) {
725                 ssif_inc_stat(ssif_info, receive_errors);
726         } else {
727                 ssif_inc_stat(ssif_info, received_messages);
728                 ssif_inc_stat(ssif_info, received_message_parts);
729         }
730
731         if (ssif_info->ssif_debug & SSIF_DEBUG_STATE)
732                 pr_info(PFX "DONE 1: state = %d, result=%d.\n",
733                         ssif_info->ssif_state, result);
734
735         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
736         msg = ssif_info->curr_msg;
737         if (msg) {
738                 if (data) {
739                         if (len > IPMI_MAX_MSG_LENGTH)
740                                 len = IPMI_MAX_MSG_LENGTH;
741                         memcpy(msg->rsp, data, len);
742                 } else {
743                         len = 0;
744                 }
745                 msg->rsp_size = len;
746                 ssif_info->curr_msg = NULL;
747         }
748
749         switch (ssif_info->ssif_state) {
750         case SSIF_NORMAL:
751                 ipmi_ssif_unlock_cond(ssif_info, flags);
752                 if (!msg)
753                         break;
754
755                 if (result < 0)
756                         return_hosed_msg(ssif_info, msg);
757                 else
758                         deliver_recv_msg(ssif_info, msg);
759                 break;
760
761         case SSIF_GETTING_FLAGS:
762                 /* We got the flags from the SSIF, now handle them. */
763                 if ((result < 0) || (len < 4) || (data[2] != 0)) {
764                         /*
765                          * Error fetching flags, or invalid length,
766                          * just give up for now.
767                          */
768                         ssif_info->ssif_state = SSIF_NORMAL;
769                         ipmi_ssif_unlock_cond(ssif_info, flags);
770                         pr_warn(PFX "Error getting flags: %d %d, %x\n",
771                                result, len, (len >= 3) ? data[2] : 0);
772                 } else if (data[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2
773                            || data[1] != IPMI_GET_MSG_FLAGS_CMD) {
774                         /*
775                          * Don't abort here, maybe it was a queued
776                          * response to a previous command.
777                          */
778                         ipmi_ssif_unlock_cond(ssif_info, flags);
779                         pr_warn(PFX "Invalid response getting flags: %x %x\n",
780                                 data[0], data[1]);
781                 } else {
782                         ssif_inc_stat(ssif_info, flag_fetches);
783                         ssif_info->msg_flags = data[3];
784                         handle_flags(ssif_info, flags);
785                 }
786                 break;
787
788         case SSIF_CLEARING_FLAGS:
789                 /* We cleared the flags. */
790                 if ((result < 0) || (len < 3) || (data[2] != 0)) {
791                         /* Error clearing flags */
792                         pr_warn(PFX "Error clearing flags: %d %d, %x\n",
793                                result, len, (len >= 3) ? data[2] : 0);
794                 } else if (data[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2
795                            || data[1] != IPMI_CLEAR_MSG_FLAGS_CMD) {
796                         pr_warn(PFX "Invalid response clearing flags: %x %x\n",
797                                 data[0], data[1]);
798                 }
799                 ssif_info->ssif_state = SSIF_NORMAL;
800                 ipmi_ssif_unlock_cond(ssif_info, flags);
801                 break;
802
803         case SSIF_GETTING_EVENTS:
804                 if (!msg) {
805                         /* Should never happen, but just in case. */
806                         dev_warn(&ssif_info->client->dev,
807                                  "No message set while getting events\n");
808                         ipmi_ssif_unlock_cond(ssif_info, flags);
809                         break;
810                 }
811
812                 if ((result < 0) || (len < 3) || (msg->rsp[2] != 0)) {
813                         /* Error getting event, probably done. */
814                         msg->done(msg);
815
816                         /* Take off the event flag. */
817                         ssif_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
818                         handle_flags(ssif_info, flags);
819                 } else if (msg->rsp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2
820                            || msg->rsp[1] != IPMI_READ_EVENT_MSG_BUFFER_CMD) {
821                         pr_warn(PFX "Invalid response getting events: %x %x\n",
822                                 msg->rsp[0], msg->rsp[1]);
823                         msg->done(msg);
824                         /* Take off the event flag. */
825                         ssif_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
826                         handle_flags(ssif_info, flags);
827                 } else {
828                         handle_flags(ssif_info, flags);
829                         ssif_inc_stat(ssif_info, events);
830                         deliver_recv_msg(ssif_info, msg);
831                 }
832                 break;
833
834         case SSIF_GETTING_MESSAGES:
835                 if (!msg) {
836                         /* Should never happen, but just in case. */
837                         dev_warn(&ssif_info->client->dev,
838                                  "No message set while getting messages\n");
839                         ipmi_ssif_unlock_cond(ssif_info, flags);
840                         break;
841                 }
842
843                 if ((result < 0) || (len < 3) || (msg->rsp[2] != 0)) {
844                         /* Error getting event, probably done. */
845                         msg->done(msg);
846
847                         /* Take off the msg flag. */
848                         ssif_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
849                         handle_flags(ssif_info, flags);
850                 } else if (msg->rsp[0] != (IPMI_NETFN_APP_REQUEST | 1) << 2
851                            || msg->rsp[1] != IPMI_GET_MSG_CMD) {
852                         pr_warn(PFX "Invalid response clearing flags: %x %x\n",
853                                 msg->rsp[0], msg->rsp[1]);
854                         msg->done(msg);
855
856                         /* Take off the msg flag. */
857                         ssif_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
858                         handle_flags(ssif_info, flags);
859                 } else {
860                         ssif_inc_stat(ssif_info, incoming_messages);
861                         handle_flags(ssif_info, flags);
862                         deliver_recv_msg(ssif_info, msg);
863                 }
864                 break;
865
866         default:
867                 /* Should never happen, but just in case. */
868                 dev_warn(&ssif_info->client->dev,
869                          "Invalid state in message done handling: %d\n",
870                          ssif_info->ssif_state);
871                 ipmi_ssif_unlock_cond(ssif_info, flags);
872         }
873
874         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
875         if (SSIF_IDLE(ssif_info) && !ssif_info->stopping) {
876                 if (ssif_info->req_events)
877                         start_event_fetch(ssif_info, flags);
878                 else if (ssif_info->req_flags)
879                         start_flag_fetch(ssif_info, flags);
880                 else
881                         start_next_msg(ssif_info, flags);
882         } else
883                 ipmi_ssif_unlock_cond(ssif_info, flags);
884
885         if (ssif_info->ssif_debug & SSIF_DEBUG_STATE)
886                 pr_info(PFX "DONE 2: state = %d.\n", ssif_info->ssif_state);
887 }
888
889 static void msg_written_handler(struct ssif_info *ssif_info, int result,
890                                 unsigned char *data, unsigned int len)
891 {
892         int rv;
893
894         /* We are single-threaded here, so no need for a lock. */
895         if (result < 0) {
896                 ssif_info->retries_left--;
897                 if (ssif_info->retries_left > 0) {
898                         if (!start_resend(ssif_info)) {
899                                 ssif_inc_stat(ssif_info, send_retries);
900                                 return;
901                         }
902                         /* request failed, just return the error. */
903                         ssif_inc_stat(ssif_info, send_errors);
904
905                         if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
906                                 pr_info(PFX
907                                         "Out of retries in msg_written_handler\n");
908                         msg_done_handler(ssif_info, -EIO, NULL, 0);
909                         return;
910                 }
911
912                 ssif_inc_stat(ssif_info, send_errors);
913
914                 /*
915                  * Got an error on transmit, let the done routine
916                  * handle it.
917                  */
918                 if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
919                         pr_info("Error in msg_written_handler: %d\n", result);
920
921                 msg_done_handler(ssif_info, result, NULL, 0);
922                 return;
923         }
924
925         if (ssif_info->multi_data) {
926                 /*
927                  * In the middle of a multi-data write.  See the comment
928                  * in the SSIF_MULTI_n_PART case in the probe function
929                  * for details on the intricacies of this.
930                  */
931                 int left;
932                 unsigned char *data_to_send;
933
934                 ssif_inc_stat(ssif_info, sent_messages_parts);
935
936                 left = ssif_info->multi_len - ssif_info->multi_pos;
937                 if (left > 32)
938                         left = 32;
939                 /* Length byte. */
940                 ssif_info->multi_data[ssif_info->multi_pos] = left;
941                 data_to_send = ssif_info->multi_data + ssif_info->multi_pos;
942                 ssif_info->multi_pos += left;
943                 if (left < 32)
944                         /*
945                          * Write is finished.  Note that we must end
946                          * with a write of less than 32 bytes to
947                          * complete the transaction, even if it is
948                          * zero bytes.
949                          */
950                         ssif_info->multi_data = NULL;
951
952                 rv = ssif_i2c_send(ssif_info, msg_written_handler,
953                                   I2C_SMBUS_WRITE,
954                                   SSIF_IPMI_MULTI_PART_REQUEST_MIDDLE,
955                                   data_to_send,
956                                   I2C_SMBUS_BLOCK_DATA);
957                 if (rv < 0) {
958                         /* request failed, just return the error. */
959                         ssif_inc_stat(ssif_info, send_errors);
960
961                         if (ssif_info->ssif_debug & SSIF_DEBUG_MSG)
962                                 pr_info("Error from i2c_non_blocking_op(3)\n");
963                         msg_done_handler(ssif_info, -EIO, NULL, 0);
964                 }
965         } else {
966                 /* Ready to request the result. */
967                 unsigned long oflags, *flags;
968
969                 ssif_inc_stat(ssif_info, sent_messages);
970                 ssif_inc_stat(ssif_info, sent_messages_parts);
971
972                 flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
973                 if (ssif_info->got_alert) {
974                         /* The result is already ready, just start it. */
975                         ssif_info->got_alert = false;
976                         ipmi_ssif_unlock_cond(ssif_info, flags);
977                         start_get(ssif_info);
978                 } else {
979                         /* Wait a jiffie then request the next message */
980                         ssif_info->waiting_alert = true;
981                         ssif_info->retries_left = SSIF_RECV_RETRIES;
982                         ssif_info->rtc_us_timer = SSIF_MSG_PART_USEC;
983                         if (!ssif_info->stopping)
984                                 mod_timer(&ssif_info->retry_timer,
985                                           jiffies + SSIF_MSG_PART_JIFFIES);
986                         ipmi_ssif_unlock_cond(ssif_info, flags);
987                 }
988         }
989 }
990
991 static int start_resend(struct ssif_info *ssif_info)
992 {
993         int rv;
994         int command;
995
996         ssif_info->got_alert = false;
997
998         if (ssif_info->data_len > 32) {
999                 command = SSIF_IPMI_MULTI_PART_REQUEST_START;
1000                 ssif_info->multi_data = ssif_info->data;
1001                 ssif_info->multi_len = ssif_info->data_len;
1002                 /*
1003                  * Subtle thing, this is 32, not 33, because we will
1004                  * overwrite the thing at position 32 (which was just
1005                  * transmitted) with the new length.
1006                  */
1007                 ssif_info->multi_pos = 32;
1008                 ssif_info->data[0] = 32;
1009         } else {
1010                 ssif_info->multi_data = NULL;
1011                 command = SSIF_IPMI_REQUEST;
1012                 ssif_info->data[0] = ssif_info->data_len;
1013         }
1014
1015         rv = ssif_i2c_send(ssif_info, msg_written_handler, I2C_SMBUS_WRITE,
1016                           command, ssif_info->data, I2C_SMBUS_BLOCK_DATA);
1017         if (rv && (ssif_info->ssif_debug & SSIF_DEBUG_MSG))
1018                 pr_info("Error from i2c_non_blocking_op(4)\n");
1019         return rv;
1020 }
1021
1022 static int start_send(struct ssif_info *ssif_info,
1023                       unsigned char   *data,
1024                       unsigned int    len)
1025 {
1026         if (len > IPMI_MAX_MSG_LENGTH)
1027                 return -E2BIG;
1028         if (len > ssif_info->max_xmit_msg_size)
1029                 return -E2BIG;
1030
1031         ssif_info->retries_left = SSIF_SEND_RETRIES;
1032         memcpy(ssif_info->data + 1, data, len);
1033         ssif_info->data_len = len;
1034         return start_resend(ssif_info);
1035 }
1036
1037 /* Must be called with the message lock held. */
1038 static void start_next_msg(struct ssif_info *ssif_info, unsigned long *flags)
1039 {
1040         struct ipmi_smi_msg *msg;
1041         unsigned long oflags;
1042
1043  restart:
1044         if (!SSIF_IDLE(ssif_info)) {
1045                 ipmi_ssif_unlock_cond(ssif_info, flags);
1046                 return;
1047         }
1048
1049         if (!ssif_info->waiting_msg) {
1050                 ssif_info->curr_msg = NULL;
1051                 ipmi_ssif_unlock_cond(ssif_info, flags);
1052         } else {
1053                 int rv;
1054
1055                 ssif_info->curr_msg = ssif_info->waiting_msg;
1056                 ssif_info->waiting_msg = NULL;
1057                 ipmi_ssif_unlock_cond(ssif_info, flags);
1058                 rv = start_send(ssif_info,
1059                                 ssif_info->curr_msg->data,
1060                                 ssif_info->curr_msg->data_size);
1061                 if (rv) {
1062                         msg = ssif_info->curr_msg;
1063                         ssif_info->curr_msg = NULL;
1064                         return_hosed_msg(ssif_info, msg);
1065                         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
1066                         goto restart;
1067                 }
1068         }
1069 }
1070
1071 static void sender(void                *send_info,
1072                    struct ipmi_smi_msg *msg)
1073 {
1074         struct ssif_info *ssif_info = (struct ssif_info *) send_info;
1075         unsigned long oflags, *flags;
1076
1077         BUG_ON(ssif_info->waiting_msg);
1078         ssif_info->waiting_msg = msg;
1079
1080         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
1081         start_next_msg(ssif_info, flags);
1082
1083         if (ssif_info->ssif_debug & SSIF_DEBUG_TIMING) {
1084                 struct timespec64 t;
1085
1086                 ktime_get_real_ts64(&t);
1087                 pr_info("**Enqueue %02x %02x: %lld.%6.6ld\n",
1088                        msg->data[0], msg->data[1],
1089                        (long long) t.tv_sec, (long) t.tv_nsec / NSEC_PER_USEC);
1090         }
1091 }
1092
1093 static int get_smi_info(void *send_info, struct ipmi_smi_info *data)
1094 {
1095         struct ssif_info *ssif_info = send_info;
1096
1097         data->addr_src = ssif_info->addr_source;
1098         data->dev = &ssif_info->client->dev;
1099         data->addr_info = ssif_info->addr_info;
1100         get_device(data->dev);
1101
1102         return 0;
1103 }
1104
1105 /*
1106  * Instead of having our own timer to periodically check the message
1107  * flags, we let the message handler drive us.
1108  */
1109 static void request_events(void *send_info)
1110 {
1111         struct ssif_info *ssif_info = (struct ssif_info *) send_info;
1112         unsigned long oflags, *flags;
1113
1114         if (!ssif_info->has_event_buffer)
1115                 return;
1116
1117         flags = ipmi_ssif_lock_cond(ssif_info, &oflags);
1118         /*
1119          * Request flags first, not events, because the lower layer
1120          * doesn't have a way to send an attention.  But make sure
1121          * event checking still happens.
1122          */
1123         ssif_info->req_events = true;
1124         if (SSIF_IDLE(ssif_info))
1125                 start_flag_fetch(ssif_info, flags);
1126         else {
1127                 ssif_info->req_flags = true;
1128                 ipmi_ssif_unlock_cond(ssif_info, flags);
1129         }
1130 }
1131
1132 static int ssif_start_processing(void            *send_info,
1133                                  struct ipmi_smi *intf)
1134 {
1135         struct ssif_info *ssif_info = send_info;
1136
1137         ssif_info->intf = intf;
1138
1139         return 0;
1140 }
1141
1142 #define MAX_SSIF_BMCS 4
1143
1144 static unsigned short addr[MAX_SSIF_BMCS];
1145 static int num_addrs;
1146 module_param_array(addr, ushort, &num_addrs, 0);
1147 MODULE_PARM_DESC(addr, "The addresses to scan for IPMI BMCs on the SSIFs.");
1148
1149 static char *adapter_name[MAX_SSIF_BMCS];
1150 static int num_adapter_names;
1151 module_param_array(adapter_name, charp, &num_adapter_names, 0);
1152 MODULE_PARM_DESC(adapter_name, "The string name of the I2C device that has the BMC.  By default all devices are scanned.");
1153
1154 static int slave_addrs[MAX_SSIF_BMCS];
1155 static int num_slave_addrs;
1156 module_param_array(slave_addrs, int, &num_slave_addrs, 0);
1157 MODULE_PARM_DESC(slave_addrs,
1158                  "The default IPMB slave address for the controller.");
1159
1160 static bool alerts_broken;
1161 module_param(alerts_broken, bool, 0);
1162 MODULE_PARM_DESC(alerts_broken, "Don't enable alerts for the controller.");
1163
1164 /*
1165  * Bit 0 enables message debugging, bit 1 enables state debugging, and
1166  * bit 2 enables timing debugging.  This is an array indexed by
1167  * interface number"
1168  */
1169 static int dbg[MAX_SSIF_BMCS];
1170 static int num_dbg;
1171 module_param_array(dbg, int, &num_dbg, 0);
1172 MODULE_PARM_DESC(dbg, "Turn on debugging.");
1173
1174 static bool ssif_dbg_probe;
1175 module_param_named(dbg_probe, ssif_dbg_probe, bool, 0);
1176 MODULE_PARM_DESC(dbg_probe, "Enable debugging of probing of adapters.");
1177
1178 static bool ssif_tryacpi = true;
1179 module_param_named(tryacpi, ssif_tryacpi, bool, 0);
1180 MODULE_PARM_DESC(tryacpi, "Setting this to zero will disable the default scan of the interfaces identified via ACPI");
1181
1182 static bool ssif_trydmi = true;
1183 module_param_named(trydmi, ssif_trydmi, bool, 0);
1184 MODULE_PARM_DESC(trydmi, "Setting this to zero will disable the default scan of the interfaces identified via DMI (SMBIOS)");
1185
1186 static DEFINE_MUTEX(ssif_infos_mutex);
1187 static LIST_HEAD(ssif_infos);
1188
1189 #define IPMI_SSIF_ATTR(name) \
1190 static ssize_t ipmi_##name##_show(struct device *dev,                   \
1191                                   struct device_attribute *attr,        \
1192                                   char *buf)                            \
1193 {                                                                       \
1194         struct ssif_info *ssif_info = dev_get_drvdata(dev);             \
1195                                                                         \
1196         return snprintf(buf, 10, "%u\n", ssif_get_stat(ssif_info, name));\
1197 }                                                                       \
1198 static DEVICE_ATTR(name, S_IRUGO, ipmi_##name##_show, NULL)
1199
1200 static ssize_t ipmi_type_show(struct device *dev,
1201                               struct device_attribute *attr,
1202                               char *buf)
1203 {
1204         return snprintf(buf, 10, "ssif\n");
1205 }
1206 static DEVICE_ATTR(type, S_IRUGO, ipmi_type_show, NULL);
1207
1208 IPMI_SSIF_ATTR(sent_messages);
1209 IPMI_SSIF_ATTR(sent_messages_parts);
1210 IPMI_SSIF_ATTR(send_retries);
1211 IPMI_SSIF_ATTR(send_errors);
1212 IPMI_SSIF_ATTR(received_messages);
1213 IPMI_SSIF_ATTR(received_message_parts);
1214 IPMI_SSIF_ATTR(receive_retries);
1215 IPMI_SSIF_ATTR(receive_errors);
1216 IPMI_SSIF_ATTR(flag_fetches);
1217 IPMI_SSIF_ATTR(hosed);
1218 IPMI_SSIF_ATTR(events);
1219 IPMI_SSIF_ATTR(watchdog_pretimeouts);
1220 IPMI_SSIF_ATTR(alerts);
1221
1222 static struct attribute *ipmi_ssif_dev_attrs[] = {
1223         &dev_attr_type.attr,
1224         &dev_attr_sent_messages.attr,
1225         &dev_attr_sent_messages_parts.attr,
1226         &dev_attr_send_retries.attr,
1227         &dev_attr_send_errors.attr,
1228         &dev_attr_received_messages.attr,
1229         &dev_attr_received_message_parts.attr,
1230         &dev_attr_receive_retries.attr,
1231         &dev_attr_receive_errors.attr,
1232         &dev_attr_flag_fetches.attr,
1233         &dev_attr_hosed.attr,
1234         &dev_attr_events.attr,
1235         &dev_attr_watchdog_pretimeouts.attr,
1236         &dev_attr_alerts.attr,
1237         NULL
1238 };
1239
1240 static const struct attribute_group ipmi_ssif_dev_attr_group = {
1241         .attrs          = ipmi_ssif_dev_attrs,
1242 };
1243
1244 static void shutdown_ssif(void *send_info)
1245 {
1246         struct ssif_info *ssif_info = send_info;
1247
1248         device_remove_group(&ssif_info->client->dev, &ipmi_ssif_dev_attr_group);
1249         dev_set_drvdata(&ssif_info->client->dev, NULL);
1250
1251         /* make sure the driver is not looking for flags any more. */
1252         while (ssif_info->ssif_state != SSIF_NORMAL)
1253                 schedule_timeout(1);
1254
1255         ssif_info->stopping = true;
1256         del_timer_sync(&ssif_info->retry_timer);
1257         if (ssif_info->thread) {
1258                 complete(&ssif_info->wake_thread);
1259                 kthread_stop(ssif_info->thread);
1260         }
1261 }
1262
1263 static int ssif_remove(struct i2c_client *client)
1264 {
1265         struct ssif_info *ssif_info = i2c_get_clientdata(client);
1266         struct ssif_addr_info *addr_info;
1267
1268         if (!ssif_info)
1269                 return 0;
1270
1271         /*
1272          * After this point, we won't deliver anything asychronously
1273          * to the message handler.  We can unregister ourself.
1274          */
1275         ipmi_unregister_smi(ssif_info->intf);
1276
1277         list_for_each_entry(addr_info, &ssif_infos, link) {
1278                 if (addr_info->client == client) {
1279                         addr_info->client = NULL;
1280                         break;
1281                 }
1282         }
1283
1284         kfree(ssif_info);
1285
1286         return 0;
1287 }
1288
1289 static int do_cmd(struct i2c_client *client, int len, unsigned char *msg,
1290                   int *resp_len, unsigned char *resp)
1291 {
1292         int retry_cnt;
1293         int ret;
1294
1295         retry_cnt = SSIF_SEND_RETRIES;
1296  retry1:
1297         ret = i2c_smbus_write_block_data(client, SSIF_IPMI_REQUEST, len, msg);
1298         if (ret) {
1299                 retry_cnt--;
1300                 if (retry_cnt > 0)
1301                         goto retry1;
1302                 return -ENODEV;
1303         }
1304
1305         ret = -ENODEV;
1306         retry_cnt = SSIF_RECV_RETRIES;
1307         while (retry_cnt > 0) {
1308                 ret = i2c_smbus_read_block_data(client, SSIF_IPMI_RESPONSE,
1309                                                 resp);
1310                 if (ret > 0)
1311                         break;
1312                 msleep(SSIF_MSG_MSEC);
1313                 retry_cnt--;
1314                 if (retry_cnt <= 0)
1315                         break;
1316         }
1317
1318         if (ret > 0) {
1319                 /* Validate that the response is correct. */
1320                 if (ret < 3 ||
1321                     (resp[0] != (msg[0] | (1 << 2))) ||
1322                     (resp[1] != msg[1]))
1323                         ret = -EINVAL;
1324                 else {
1325                         *resp_len = ret;
1326                         ret = 0;
1327                 }
1328         }
1329
1330         return ret;
1331 }
1332
1333 static int ssif_detect(struct i2c_client *client, struct i2c_board_info *info)
1334 {
1335         unsigned char *resp;
1336         unsigned char msg[3];
1337         int           rv;
1338         int           len;
1339
1340         resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
1341         if (!resp)
1342                 return -ENOMEM;
1343
1344         /* Do a Get Device ID command, since it is required. */
1345         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1346         msg[1] = IPMI_GET_DEVICE_ID_CMD;
1347         rv = do_cmd(client, 2, msg, &len, resp);
1348         if (rv)
1349                 rv = -ENODEV;
1350         else
1351                 strlcpy(info->type, DEVICE_NAME, I2C_NAME_SIZE);
1352         kfree(resp);
1353         return rv;
1354 }
1355
1356 static int strcmp_nospace(char *s1, char *s2)
1357 {
1358         while (*s1 && *s2) {
1359                 while (isspace(*s1))
1360                         s1++;
1361                 while (isspace(*s2))
1362                         s2++;
1363                 if (*s1 > *s2)
1364                         return 1;
1365                 if (*s1 < *s2)
1366                         return -1;
1367                 s1++;
1368                 s2++;
1369         }
1370         return 0;
1371 }
1372
1373 static struct ssif_addr_info *ssif_info_find(unsigned short addr,
1374                                              char *adapter_name,
1375                                              bool match_null_name)
1376 {
1377         struct ssif_addr_info *info, *found = NULL;
1378
1379 restart:
1380         list_for_each_entry(info, &ssif_infos, link) {
1381                 if (info->binfo.addr == addr) {
1382                         if (info->adapter_name || adapter_name) {
1383                                 if (!info->adapter_name != !adapter_name) {
1384                                         /* One is NULL and one is not */
1385                                         continue;
1386                                 }
1387                                 if (adapter_name &&
1388                                     strcmp_nospace(info->adapter_name,
1389                                                    adapter_name))
1390                                         /* Names do not match */
1391                                         continue;
1392                         }
1393                         found = info;
1394                         break;
1395                 }
1396         }
1397
1398         if (!found && match_null_name) {
1399                 /* Try to get an exact match first, then try with a NULL name */
1400                 adapter_name = NULL;
1401                 match_null_name = false;
1402                 goto restart;
1403         }
1404
1405         return found;
1406 }
1407
1408 static bool check_acpi(struct ssif_info *ssif_info, struct device *dev)
1409 {
1410 #ifdef CONFIG_ACPI
1411         acpi_handle acpi_handle;
1412
1413         acpi_handle = ACPI_HANDLE(dev);
1414         if (acpi_handle) {
1415                 ssif_info->addr_source = SI_ACPI;
1416                 ssif_info->addr_info.acpi_info.acpi_handle = acpi_handle;
1417                 return true;
1418         }
1419 #endif
1420         return false;
1421 }
1422
1423 static int find_slave_address(struct i2c_client *client, int slave_addr)
1424 {
1425 #ifdef CONFIG_IPMI_DMI_DECODE
1426         if (!slave_addr)
1427                 slave_addr = ipmi_dmi_get_slave_addr(
1428                         SI_TYPE_INVALID,
1429                         i2c_adapter_id(client->adapter),
1430                         client->addr);
1431 #endif
1432
1433         return slave_addr;
1434 }
1435
1436 /*
1437  * Global enables we care about.
1438  */
1439 #define GLOBAL_ENABLES_MASK (IPMI_BMC_EVT_MSG_BUFF | IPMI_BMC_RCV_MSG_INTR | \
1440                              IPMI_BMC_EVT_MSG_INTR)
1441
1442 static int ssif_probe(struct i2c_client *client, const struct i2c_device_id *id)
1443 {
1444         unsigned char     msg[3];
1445         unsigned char     *resp;
1446         struct ssif_info   *ssif_info;
1447         int               rv = 0;
1448         int               len;
1449         int               i;
1450         u8                slave_addr = 0;
1451         struct ssif_addr_info *addr_info = NULL;
1452
1453         resp = kmalloc(IPMI_MAX_MSG_LENGTH, GFP_KERNEL);
1454         if (!resp)
1455                 return -ENOMEM;
1456
1457         ssif_info = kzalloc(sizeof(*ssif_info), GFP_KERNEL);
1458         if (!ssif_info) {
1459                 kfree(resp);
1460                 return -ENOMEM;
1461         }
1462
1463         if (!check_acpi(ssif_info, &client->dev)) {
1464                 addr_info = ssif_info_find(client->addr, client->adapter->name,
1465                                            true);
1466                 if (!addr_info) {
1467                         /* Must have come in through sysfs. */
1468                         ssif_info->addr_source = SI_HOTMOD;
1469                 } else {
1470                         ssif_info->addr_source = addr_info->addr_src;
1471                         ssif_info->ssif_debug = addr_info->debug;
1472                         ssif_info->addr_info = addr_info->addr_info;
1473                         addr_info->client = client;
1474                         slave_addr = addr_info->slave_addr;
1475                 }
1476         }
1477
1478         slave_addr = find_slave_address(client, slave_addr);
1479
1480         pr_info(PFX "Trying %s-specified SSIF interface at i2c address 0x%x, adapter %s, slave address 0x%x\n",
1481                ipmi_addr_src_to_str(ssif_info->addr_source),
1482                client->addr, client->adapter->name, slave_addr);
1483
1484         ssif_info->client = client;
1485         i2c_set_clientdata(client, ssif_info);
1486
1487         /* Now check for system interface capabilities */
1488         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1489         msg[1] = IPMI_GET_SYSTEM_INTERFACE_CAPABILITIES_CMD;
1490         msg[2] = 0; /* SSIF */
1491         rv = do_cmd(client, 3, msg, &len, resp);
1492         if (!rv && (len >= 3) && (resp[2] == 0)) {
1493                 if (len < 7) {
1494                         if (ssif_dbg_probe)
1495                                 pr_info(PFX "SSIF info too short: %d\n", len);
1496                         goto no_support;
1497                 }
1498
1499                 /* Got a good SSIF response, handle it. */
1500                 ssif_info->max_xmit_msg_size = resp[5];
1501                 ssif_info->max_recv_msg_size = resp[6];
1502                 ssif_info->multi_support = (resp[4] >> 6) & 0x3;
1503                 ssif_info->supports_pec = (resp[4] >> 3) & 0x1;
1504
1505                 /* Sanitize the data */
1506                 switch (ssif_info->multi_support) {
1507                 case SSIF_NO_MULTI:
1508                         if (ssif_info->max_xmit_msg_size > 32)
1509                                 ssif_info->max_xmit_msg_size = 32;
1510                         if (ssif_info->max_recv_msg_size > 32)
1511                                 ssif_info->max_recv_msg_size = 32;
1512                         break;
1513
1514                 case SSIF_MULTI_2_PART:
1515                         if (ssif_info->max_xmit_msg_size > 63)
1516                                 ssif_info->max_xmit_msg_size = 63;
1517                         if (ssif_info->max_recv_msg_size > 62)
1518                                 ssif_info->max_recv_msg_size = 62;
1519                         break;
1520
1521                 case SSIF_MULTI_n_PART:
1522                         /*
1523                          * The specification is rather confusing at
1524                          * this point, but I think I understand what
1525                          * is meant.  At least I have a workable
1526                          * solution.  With multi-part messages, you
1527                          * cannot send a message that is a multiple of
1528                          * 32-bytes in length, because the start and
1529                          * middle messages are 32-bytes and the end
1530                          * message must be at least one byte.  You
1531                          * can't fudge on an extra byte, that would
1532                          * screw up things like fru data writes.  So
1533                          * we limit the length to 63 bytes.  That way
1534                          * a 32-byte message gets sent as a single
1535                          * part.  A larger message will be a 32-byte
1536                          * start and the next message is always going
1537                          * to be 1-31 bytes in length.  Not ideal, but
1538                          * it should work.
1539                          */
1540                         if (ssif_info->max_xmit_msg_size > 63)
1541                                 ssif_info->max_xmit_msg_size = 63;
1542                         break;
1543
1544                 default:
1545                         /* Data is not sane, just give up. */
1546                         goto no_support;
1547                 }
1548         } else {
1549  no_support:
1550                 /* Assume no multi-part or PEC support */
1551                 pr_info(PFX "Error fetching SSIF: %d %d %2.2x, your system probably doesn't support this command so using defaults\n",
1552                        rv, len, resp[2]);
1553
1554                 ssif_info->max_xmit_msg_size = 32;
1555                 ssif_info->max_recv_msg_size = 32;
1556                 ssif_info->multi_support = SSIF_NO_MULTI;
1557                 ssif_info->supports_pec = 0;
1558         }
1559
1560         /* Make sure the NMI timeout is cleared. */
1561         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1562         msg[1] = IPMI_CLEAR_MSG_FLAGS_CMD;
1563         msg[2] = WDT_PRE_TIMEOUT_INT;
1564         rv = do_cmd(client, 3, msg, &len, resp);
1565         if (rv || (len < 3) || (resp[2] != 0))
1566                 pr_warn(PFX "Unable to clear message flags: %d %d %2.2x\n",
1567                         rv, len, resp[2]);
1568
1569         /* Attempt to enable the event buffer. */
1570         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1571         msg[1] = IPMI_GET_BMC_GLOBAL_ENABLES_CMD;
1572         rv = do_cmd(client, 2, msg, &len, resp);
1573         if (rv || (len < 4) || (resp[2] != 0)) {
1574                 pr_warn(PFX "Error getting global enables: %d %d %2.2x\n",
1575                         rv, len, resp[2]);
1576                 rv = 0; /* Not fatal */
1577                 goto found;
1578         }
1579
1580         ssif_info->global_enables = resp[3];
1581
1582         if (resp[3] & IPMI_BMC_EVT_MSG_BUFF) {
1583                 ssif_info->has_event_buffer = true;
1584                 /* buffer is already enabled, nothing to do. */
1585                 goto found;
1586         }
1587
1588         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1589         msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
1590         msg[2] = ssif_info->global_enables | IPMI_BMC_EVT_MSG_BUFF;
1591         rv = do_cmd(client, 3, msg, &len, resp);
1592         if (rv || (len < 2)) {
1593                 pr_warn(PFX "Error setting global enables: %d %d %2.2x\n",
1594                         rv, len, resp[2]);
1595                 rv = 0; /* Not fatal */
1596                 goto found;
1597         }
1598
1599         if (resp[2] == 0) {
1600                 /* A successful return means the event buffer is supported. */
1601                 ssif_info->has_event_buffer = true;
1602                 ssif_info->global_enables |= IPMI_BMC_EVT_MSG_BUFF;
1603         }
1604
1605         /* Some systems don't behave well if you enable alerts. */
1606         if (alerts_broken)
1607                 goto found;
1608
1609         msg[0] = IPMI_NETFN_APP_REQUEST << 2;
1610         msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
1611         msg[2] = ssif_info->global_enables | IPMI_BMC_RCV_MSG_INTR;
1612         rv = do_cmd(client, 3, msg, &len, resp);
1613         if (rv || (len < 2)) {
1614                 pr_warn(PFX "Error setting global enables: %d %d %2.2x\n",
1615                         rv, len, resp[2]);
1616                 rv = 0; /* Not fatal */
1617                 goto found;
1618         }
1619
1620         if (resp[2] == 0) {
1621                 /* A successful return means the alert is supported. */
1622                 ssif_info->supports_alert = true;
1623                 ssif_info->global_enables |= IPMI_BMC_RCV_MSG_INTR;
1624         }
1625
1626  found:
1627         if (ssif_dbg_probe) {
1628                 pr_info("ssif_probe: i2c_probe found device at i2c address %x\n",
1629                         client->addr);
1630         }
1631
1632         spin_lock_init(&ssif_info->lock);
1633         ssif_info->ssif_state = SSIF_NORMAL;
1634         timer_setup(&ssif_info->retry_timer, retry_timeout, 0);
1635
1636         for (i = 0; i < SSIF_NUM_STATS; i++)
1637                 atomic_set(&ssif_info->stats[i], 0);
1638
1639         if (ssif_info->supports_pec)
1640                 ssif_info->client->flags |= I2C_CLIENT_PEC;
1641
1642         ssif_info->handlers.owner = THIS_MODULE;
1643         ssif_info->handlers.start_processing = ssif_start_processing;
1644         ssif_info->handlers.shutdown = shutdown_ssif;
1645         ssif_info->handlers.get_smi_info = get_smi_info;
1646         ssif_info->handlers.sender = sender;
1647         ssif_info->handlers.request_events = request_events;
1648
1649         {
1650                 unsigned int thread_num;
1651
1652                 thread_num = ((i2c_adapter_id(ssif_info->client->adapter)
1653                                << 8) |
1654                               ssif_info->client->addr);
1655                 init_completion(&ssif_info->wake_thread);
1656                 ssif_info->thread = kthread_run(ipmi_ssif_thread, ssif_info,
1657                                                "kssif%4.4x", thread_num);
1658                 if (IS_ERR(ssif_info->thread)) {
1659                         rv = PTR_ERR(ssif_info->thread);
1660                         dev_notice(&ssif_info->client->dev,
1661                                    "Could not start kernel thread: error %d\n",
1662                                    rv);
1663                         goto out;
1664                 }
1665         }
1666
1667         dev_set_drvdata(&ssif_info->client->dev, ssif_info);
1668         rv = device_add_group(&ssif_info->client->dev,
1669                               &ipmi_ssif_dev_attr_group);
1670         if (rv) {
1671                 dev_err(&ssif_info->client->dev,
1672                         "Unable to add device attributes: error %d\n",
1673                         rv);
1674                 goto out;
1675         }
1676
1677         rv = ipmi_register_smi(&ssif_info->handlers,
1678                                ssif_info,
1679                                &ssif_info->client->dev,
1680                                slave_addr);
1681          if (rv) {
1682                 pr_err(PFX "Unable to register device: error %d\n", rv);
1683                 goto out_remove_attr;
1684         }
1685
1686  out:
1687         if (rv) {
1688                 if (addr_info)
1689                         addr_info->client = NULL;
1690
1691                 dev_err(&client->dev, "Unable to start IPMI SSIF: %d\n", rv);
1692                 kfree(ssif_info);
1693         }
1694         kfree(resp);
1695         return rv;
1696
1697 out_remove_attr:
1698         device_remove_group(&ssif_info->client->dev, &ipmi_ssif_dev_attr_group);
1699         dev_set_drvdata(&ssif_info->client->dev, NULL);
1700         goto out;
1701 }
1702
1703 static int ssif_adapter_handler(struct device *adev, void *opaque)
1704 {
1705         struct ssif_addr_info *addr_info = opaque;
1706
1707         if (adev->type != &i2c_adapter_type)
1708                 return 0;
1709
1710         addr_info->added_client = i2c_new_device(to_i2c_adapter(adev),
1711                                                  &addr_info->binfo);
1712
1713         if (!addr_info->adapter_name)
1714                 return 1; /* Only try the first I2C adapter by default. */
1715         return 0;
1716 }
1717
1718 static int new_ssif_client(int addr, char *adapter_name,
1719                            int debug, int slave_addr,
1720                            enum ipmi_addr_src addr_src,
1721                            struct device *dev)
1722 {
1723         struct ssif_addr_info *addr_info;
1724         int rv = 0;
1725
1726         mutex_lock(&ssif_infos_mutex);
1727         if (ssif_info_find(addr, adapter_name, false)) {
1728                 rv = -EEXIST;
1729                 goto out_unlock;
1730         }
1731
1732         addr_info = kzalloc(sizeof(*addr_info), GFP_KERNEL);
1733         if (!addr_info) {
1734                 rv = -ENOMEM;
1735                 goto out_unlock;
1736         }
1737
1738         if (adapter_name) {
1739                 addr_info->adapter_name = kstrdup(adapter_name, GFP_KERNEL);
1740                 if (!addr_info->adapter_name) {
1741                         kfree(addr_info);
1742                         rv = -ENOMEM;
1743                         goto out_unlock;
1744                 }
1745         }
1746
1747         strncpy(addr_info->binfo.type, DEVICE_NAME,
1748                 sizeof(addr_info->binfo.type));
1749         addr_info->binfo.addr = addr;
1750         addr_info->binfo.platform_data = addr_info;
1751         addr_info->debug = debug;
1752         addr_info->slave_addr = slave_addr;
1753         addr_info->addr_src = addr_src;
1754         addr_info->dev = dev;
1755
1756         if (dev)
1757                 dev_set_drvdata(dev, addr_info);
1758
1759         list_add_tail(&addr_info->link, &ssif_infos);
1760
1761         if (initialized)
1762                 i2c_for_each_dev(addr_info, ssif_adapter_handler);
1763         /* Otherwise address list will get it */
1764
1765 out_unlock:
1766         mutex_unlock(&ssif_infos_mutex);
1767         return rv;
1768 }
1769
1770 static void free_ssif_clients(void)
1771 {
1772         struct ssif_addr_info *info, *tmp;
1773
1774         mutex_lock(&ssif_infos_mutex);
1775         list_for_each_entry_safe(info, tmp, &ssif_infos, link) {
1776                 list_del(&info->link);
1777                 kfree(info->adapter_name);
1778                 kfree(info);
1779         }
1780         mutex_unlock(&ssif_infos_mutex);
1781 }
1782
1783 static unsigned short *ssif_address_list(void)
1784 {
1785         struct ssif_addr_info *info;
1786         unsigned int count = 0, i;
1787         unsigned short *address_list;
1788
1789         list_for_each_entry(info, &ssif_infos, link)
1790                 count++;
1791
1792         address_list = kcalloc(count + 1, sizeof(*address_list),
1793                                GFP_KERNEL);
1794         if (!address_list)
1795                 return NULL;
1796
1797         i = 0;
1798         list_for_each_entry(info, &ssif_infos, link) {
1799                 unsigned short addr = info->binfo.addr;
1800                 int j;
1801
1802                 for (j = 0; j < i; j++) {
1803                         if (address_list[j] == addr)
1804                                 goto skip_addr;
1805                 }
1806                 address_list[i] = addr;
1807 skip_addr:
1808                 i++;
1809         }
1810         address_list[i] = I2C_CLIENT_END;
1811
1812         return address_list;
1813 }
1814
1815 #ifdef CONFIG_ACPI
1816 static const struct acpi_device_id ssif_acpi_match[] = {
1817         { "IPI0001", 0 },
1818         { },
1819 };
1820 MODULE_DEVICE_TABLE(acpi, ssif_acpi_match);
1821 #endif
1822
1823 #ifdef CONFIG_DMI
1824 static int dmi_ipmi_probe(struct platform_device *pdev)
1825 {
1826         u8 slave_addr = 0;
1827         u16 i2c_addr;
1828         int rv;
1829
1830         if (!ssif_trydmi)
1831                 return -ENODEV;
1832
1833         rv = device_property_read_u16(&pdev->dev, "i2c-addr", &i2c_addr);
1834         if (rv) {
1835                 dev_warn(&pdev->dev, PFX "No i2c-addr property\n");
1836                 return -ENODEV;
1837         }
1838
1839         rv = device_property_read_u8(&pdev->dev, "slave-addr", &slave_addr);
1840         if (rv)
1841                 dev_warn(&pdev->dev, "device has no slave-addr property");
1842
1843         return new_ssif_client(i2c_addr, NULL, 0,
1844                                slave_addr, SI_SMBIOS, &pdev->dev);
1845 }
1846 #else
1847 static int dmi_ipmi_probe(struct platform_device *pdev)
1848 {
1849         return -ENODEV;
1850 }
1851 #endif
1852
1853 static const struct i2c_device_id ssif_id[] = {
1854         { DEVICE_NAME, 0 },
1855         { }
1856 };
1857 MODULE_DEVICE_TABLE(i2c, ssif_id);
1858
1859 static struct i2c_driver ssif_i2c_driver = {
1860         .class          = I2C_CLASS_HWMON,
1861         .driver         = {
1862                 .name                   = DEVICE_NAME
1863         },
1864         .probe          = ssif_probe,
1865         .remove         = ssif_remove,
1866         .alert          = ssif_alert,
1867         .id_table       = ssif_id,
1868         .detect         = ssif_detect
1869 };
1870
1871 static int ssif_platform_probe(struct platform_device *dev)
1872 {
1873         return dmi_ipmi_probe(dev);
1874 }
1875
1876 static int ssif_platform_remove(struct platform_device *dev)
1877 {
1878         struct ssif_addr_info *addr_info = dev_get_drvdata(&dev->dev);
1879
1880         if (!addr_info)
1881                 return 0;
1882
1883         mutex_lock(&ssif_infos_mutex);
1884         i2c_unregister_device(addr_info->added_client);
1885
1886         list_del(&addr_info->link);
1887         kfree(addr_info);
1888         mutex_unlock(&ssif_infos_mutex);
1889         return 0;
1890 }
1891
1892 static struct platform_driver ipmi_driver = {
1893         .driver = {
1894                 .name = DEVICE_NAME,
1895         },
1896         .probe          = ssif_platform_probe,
1897         .remove         = ssif_platform_remove,
1898 };
1899
1900 static int init_ipmi_ssif(void)
1901 {
1902         int i;
1903         int rv;
1904
1905         if (initialized)
1906                 return 0;
1907
1908         pr_info("IPMI SSIF Interface driver\n");
1909
1910         /* build list for i2c from addr list */
1911         for (i = 0; i < num_addrs; i++) {
1912                 rv = new_ssif_client(addr[i], adapter_name[i],
1913                                      dbg[i], slave_addrs[i],
1914                                      SI_HARDCODED, NULL);
1915                 if (rv)
1916                         pr_err(PFX
1917                                "Couldn't add hardcoded device at addr 0x%x\n",
1918                                addr[i]);
1919         }
1920
1921         if (ssif_tryacpi)
1922                 ssif_i2c_driver.driver.acpi_match_table =
1923                         ACPI_PTR(ssif_acpi_match);
1924
1925         if (ssif_trydmi) {
1926                 rv = platform_driver_register(&ipmi_driver);
1927                 if (rv)
1928                         pr_err(PFX "Unable to register driver: %d\n", rv);
1929         }
1930
1931         ssif_i2c_driver.address_list = ssif_address_list();
1932
1933         rv = i2c_add_driver(&ssif_i2c_driver);
1934         if (!rv)
1935                 initialized = true;
1936
1937         return rv;
1938 }
1939 module_init(init_ipmi_ssif);
1940
1941 static void cleanup_ipmi_ssif(void)
1942 {
1943         if (!initialized)
1944                 return;
1945
1946         initialized = false;
1947
1948         i2c_del_driver(&ssif_i2c_driver);
1949
1950         platform_driver_unregister(&ipmi_driver);
1951
1952         free_ssif_clients();
1953 }
1954 module_exit(cleanup_ipmi_ssif);
1955
1956 MODULE_ALIAS("platform:dmi-ipmi-ssif");
1957 MODULE_AUTHOR("Todd C Davis <todd.c.davis@intel.com>, Corey Minyard <minyard@acm.org>");
1958 MODULE_DESCRIPTION("IPMI driver for management controllers on a SMBus");
1959 MODULE_LICENSE("GPL");