Linux-2.6.12-rc2
[linux-2.6.git] / drivers / message / fusion / mptbase.c
1 /*
2  *  linux/drivers/message/fusion/mptbase.c
3  *      High performance SCSI + LAN / Fibre Channel device drivers.
4  *      This is the Fusion MPT base driver which supports multiple
5  *      (SCSI + LAN) specialized protocol drivers.
6  *      For use with PCI chip/adapter(s):
7  *          LSIFC9xx/LSI409xx Fibre Channel
8  *      running LSI Logic Fusion MPT (Message Passing Technology) firmware.
9  *
10  *  Credits:
11  *      There are lots of people not mentioned below that deserve credit
12  *      and thanks but won't get it here - sorry in advance that you
13  *      got overlooked.
14  *
15  *      This driver would not exist if not for Alan Cox's development
16  *      of the linux i2o driver.
17  *
18  *      A special thanks to Noah Romer (LSI Logic) for tons of work
19  *      and tough debugging on the LAN driver, especially early on;-)
20  *      And to Roger Hickerson (LSI Logic) for tirelessly supporting
21  *      this driver project.
22  *
23  *      A special thanks to Pamela Delaney (LSI Logic) for tons of work
24  *      and countless enhancements while adding support for the 1030
25  *      chip family.  Pam has been instrumental in the development of
26  *      of the 2.xx.xx series fusion drivers, and her contributions are
27  *      far too numerous to hope to list in one place.
28  *
29  *      All manner of help from Stephen Shirron (LSI Logic):
30  *      low-level FC analysis, debug + various fixes in FCxx firmware,
31  *      initial port to alpha platform, various driver code optimizations,
32  *      being a faithful sounding board on all sorts of issues & ideas,
33  *      etc.
34  *
35  *      A huge debt of gratitude is owed to David S. Miller (DaveM)
36  *      for fixing much of the stupid and broken stuff in the early
37  *      driver while porting to sparc64 platform.  THANK YOU!
38  *
39  *      Special thanks goes to the I2O LAN driver people at the
40  *      University of Helsinki, who, unbeknownst to them, provided
41  *      the inspiration and initial structure for this driver.
42  *
43  *      A really huge debt of gratitude is owed to Eddie C. Dost
44  *      for gobs of hard work fixing and optimizing LAN code.
45  *      THANK YOU!
46  *
47  *  Copyright (c) 1999-2004 LSI Logic Corporation
48  *  Originally By: Steven J. Ralston
49  *  (mailto:sjralston1@netscape.net)
50  *  (mailto:mpt_linux_developer@lsil.com)
51  *
52  *  $Id: mptbase.c,v 1.126 2002/12/16 15:28:45 pdelaney Exp $
53  */
54 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
55 /*
56     This program is free software; you can redistribute it and/or modify
57     it under the terms of the GNU General Public License as published by
58     the Free Software Foundation; version 2 of the License.
59
60     This program is distributed in the hope that it will be useful,
61     but WITHOUT ANY WARRANTY; without even the implied warranty of
62     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
63     GNU General Public License for more details.
64
65     NO WARRANTY
66     THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
67     CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
68     LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
69     MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
70     solely responsible for determining the appropriateness of using and
71     distributing the Program and assumes all risks associated with its
72     exercise of rights under this Agreement, including but not limited to
73     the risks and costs of program errors, damage to or loss of data,
74     programs or equipment, and unavailability or interruption of operations.
75
76     DISCLAIMER OF LIABILITY
77     NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
78     DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
79     DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
80     ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
81     TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
82     USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
83     HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
84
85     You should have received a copy of the GNU General Public License
86     along with this program; if not, write to the Free Software
87     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
88 */
89 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
90
91 #include <linux/config.h>
92 #include <linux/version.h>
93 #include <linux/kernel.h>
94 #include <linux/module.h>
95 #include <linux/errno.h>
96 #include <linux/init.h>
97 #include <linux/slab.h>
98 #include <linux/types.h>
99 #include <linux/pci.h>
100 #include <linux/kdev_t.h>
101 #include <linux/blkdev.h>
102 #include <linux/delay.h>
103 #include <linux/interrupt.h>            /* needed for in_interrupt() proto */
104 #include <asm/io.h>
105 #ifdef CONFIG_MTRR
106 #include <asm/mtrr.h>
107 #endif
108 #ifdef __sparc__
109 #include <asm/irq.h>                    /* needed for __irq_itoa() proto */
110 #endif
111
112 #include "mptbase.h"
113
114 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
115 #define my_NAME         "Fusion MPT base driver"
116 #define my_VERSION      MPT_LINUX_VERSION_COMMON
117 #define MYNAM           "mptbase"
118
119 MODULE_AUTHOR(MODULEAUTHOR);
120 MODULE_DESCRIPTION(my_NAME);
121 MODULE_LICENSE("GPL");
122
123 /*
124  *  cmd line parameters
125  */
126 #ifdef MFCNT
127 static int mfcounter = 0;
128 #define PRINT_MF_COUNT 20000
129 #endif
130
131 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
132 /*
133  *  Public data...
134  */
135 int mpt_lan_index = -1;
136 int mpt_stm_index = -1;
137
138 struct proc_dir_entry *mpt_proc_root_dir;
139
140 #define WHOINIT_UNKNOWN         0xAA
141
142 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
143 /*
144  *  Private data...
145  */
146                                         /* Adapter link list */
147 LIST_HEAD(ioc_list);
148                                         /* Callback lookup table */
149 static MPT_CALLBACK              MptCallbacks[MPT_MAX_PROTOCOL_DRIVERS];
150                                         /* Protocol driver class lookup table */
151 static int                       MptDriverClass[MPT_MAX_PROTOCOL_DRIVERS];
152                                         /* Event handler lookup table */
153 static MPT_EVHANDLER             MptEvHandlers[MPT_MAX_PROTOCOL_DRIVERS];
154                                         /* Reset handler lookup table */
155 static MPT_RESETHANDLER          MptResetHandlers[MPT_MAX_PROTOCOL_DRIVERS];
156 static struct mpt_pci_driver    *MptDeviceDriverHandlers[MPT_MAX_PROTOCOL_DRIVERS];
157
158 static int      mpt_base_index = -1;
159 static int      last_drv_idx = -1;
160
161 static DECLARE_WAIT_QUEUE_HEAD(mpt_waitq);
162
163 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
164 /*
165  *  Forward protos...
166  */
167 static irqreturn_t mpt_interrupt(int irq, void *bus_id, struct pt_regs *r);
168 static int      mpt_base_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *req, MPT_FRAME_HDR *reply);
169 static int      mpt_handshake_req_reply_wait(MPT_ADAPTER *ioc, int reqBytes,
170                         u32 *req, int replyBytes, u16 *u16reply, int maxwait,
171                         int sleepFlag);
172 static int      mpt_do_ioc_recovery(MPT_ADAPTER *ioc, u32 reason, int sleepFlag);
173 static void     mpt_detect_bound_ports(MPT_ADAPTER *ioc, struct pci_dev *pdev);
174 static void     mpt_adapter_disable(MPT_ADAPTER *ioc);
175 static void     mpt_adapter_dispose(MPT_ADAPTER *ioc);
176
177 static void     MptDisplayIocCapabilities(MPT_ADAPTER *ioc);
178 static int      MakeIocReady(MPT_ADAPTER *ioc, int force, int sleepFlag);
179 //static u32    mpt_GetIocState(MPT_ADAPTER *ioc, int cooked);
180 static int      GetIocFacts(MPT_ADAPTER *ioc, int sleepFlag, int reason);
181 static int      GetPortFacts(MPT_ADAPTER *ioc, int portnum, int sleepFlag);
182 static int      SendIocInit(MPT_ADAPTER *ioc, int sleepFlag);
183 static int      SendPortEnable(MPT_ADAPTER *ioc, int portnum, int sleepFlag);
184 static int      mpt_do_upload(MPT_ADAPTER *ioc, int sleepFlag);
185 static int      mpt_downloadboot(MPT_ADAPTER *ioc, int sleepFlag);
186 static int      mpt_diag_reset(MPT_ADAPTER *ioc, int ignore, int sleepFlag);
187 static int      KickStart(MPT_ADAPTER *ioc, int ignore, int sleepFlag);
188 static int      SendIocReset(MPT_ADAPTER *ioc, u8 reset_type, int sleepFlag);
189 static int      PrimeIocFifos(MPT_ADAPTER *ioc);
190 static int      WaitForDoorbellAck(MPT_ADAPTER *ioc, int howlong, int sleepFlag);
191 static int      WaitForDoorbellInt(MPT_ADAPTER *ioc, int howlong, int sleepFlag);
192 static int      WaitForDoorbellReply(MPT_ADAPTER *ioc, int howlong, int sleepFlag);
193 static int      GetLanConfigPages(MPT_ADAPTER *ioc);
194 static int      GetFcPortPage0(MPT_ADAPTER *ioc, int portnum);
195 static int      GetIoUnitPage2(MPT_ADAPTER *ioc);
196 static int      mpt_GetScsiPortSettings(MPT_ADAPTER *ioc, int portnum);
197 static int      mpt_readScsiDevicePageHeaders(MPT_ADAPTER *ioc, int portnum);
198 static void     mpt_read_ioc_pg_1(MPT_ADAPTER *ioc);
199 static void     mpt_read_ioc_pg_4(MPT_ADAPTER *ioc);
200 static void     mpt_timer_expired(unsigned long data);
201 static int      SendEventNotification(MPT_ADAPTER *ioc, u8 EvSwitch);
202 static int      SendEventAck(MPT_ADAPTER *ioc, EventNotificationReply_t *evnp);
203
204 #ifdef CONFIG_PROC_FS
205 static int      procmpt_summary_read(char *buf, char **start, off_t offset,
206                                 int request, int *eof, void *data);
207 static int      procmpt_version_read(char *buf, char **start, off_t offset,
208                                 int request, int *eof, void *data);
209 static int      procmpt_iocinfo_read(char *buf, char **start, off_t offset,
210                                 int request, int *eof, void *data);
211 #endif
212 static void     mpt_get_fw_exp_ver(char *buf, MPT_ADAPTER *ioc);
213
214 //int           mpt_HardResetHandler(MPT_ADAPTER *ioc, int sleepFlag);
215 static int      ProcessEventNotification(MPT_ADAPTER *ioc, EventNotificationReply_t *evReply, int *evHandlers);
216 static void     mpt_sp_ioc_info(MPT_ADAPTER *ioc, u32 ioc_status, MPT_FRAME_HDR *mf);
217 static void     mpt_fc_log_info(MPT_ADAPTER *ioc, u32 log_info);
218 static void     mpt_sp_log_info(MPT_ADAPTER *ioc, u32 log_info);
219
220 /* module entry point */
221 static int  __devinit mptbase_probe (struct pci_dev *, const struct pci_device_id *);
222 static void __devexit mptbase_remove(struct pci_dev *);
223 static void mptbase_shutdown(struct device * );
224 static int  __init    fusion_init  (void);
225 static void __exit    fusion_exit  (void);
226
227 /****************************************************************************
228  * Supported hardware
229  */
230
231 static struct pci_device_id mptbase_pci_table[] = {
232         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FC909,
233                 PCI_ANY_ID, PCI_ANY_ID },
234         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FC929,
235                 PCI_ANY_ID, PCI_ANY_ID },
236         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FC919,
237                 PCI_ANY_ID, PCI_ANY_ID },
238         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FC929X,
239                 PCI_ANY_ID, PCI_ANY_ID },
240         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FC919X,
241                 PCI_ANY_ID, PCI_ANY_ID },
242         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_53C1030,
243                 PCI_ANY_ID, PCI_ANY_ID },
244         { PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_1030_53C1035,
245                 PCI_ANY_ID, PCI_ANY_ID },
246         {0}     /* Terminating entry */
247 };
248 MODULE_DEVICE_TABLE(pci, mptbase_pci_table);
249
250 #define CHIPREG_READ32(addr)            readl_relaxed(addr)
251 #define CHIPREG_READ32_dmasync(addr)    readl(addr)
252 #define CHIPREG_WRITE32(addr,val)       writel(val, addr)
253 #define CHIPREG_PIO_WRITE32(addr,val)   outl(val, (unsigned long)addr)
254 #define CHIPREG_PIO_READ32(addr)        inl((unsigned long)addr)
255
256 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
257 /*
258  *      mpt_interrupt - MPT adapter (IOC) specific interrupt handler.
259  *      @irq: irq number (not used)
260  *      @bus_id: bus identifier cookie == pointer to MPT_ADAPTER structure
261  *      @r: pt_regs pointer (not used)
262  *
263  *      This routine is registered via the request_irq() kernel API call,
264  *      and handles all interrupts generated from a specific MPT adapter
265  *      (also referred to as a IO Controller or IOC).
266  *      This routine must clear the interrupt from the adapter and does
267  *      so by reading the reply FIFO.  Multiple replies may be processed
268  *      per single call to this routine; up to MPT_MAX_REPLIES_PER_ISR
269  *      which is currently set to 32 in mptbase.h.
270  *
271  *      This routine handles register-level access of the adapter but
272  *      dispatches (calls) a protocol-specific callback routine to handle
273  *      the protocol-specific details of the MPT request completion.
274  */
275 static irqreturn_t
276 mpt_interrupt(int irq, void *bus_id, struct pt_regs *r)
277 {
278         MPT_ADAPTER     *ioc;
279         MPT_FRAME_HDR   *mf;
280         MPT_FRAME_HDR   *mr;
281         u32              pa;
282         int              req_idx;
283         int              cb_idx;
284         int              type;
285         int              freeme;
286
287         ioc = (MPT_ADAPTER *)bus_id;
288
289         /*
290          *  Drain the reply FIFO!
291          *
292          * NOTES: I've seen up to 10 replies processed in this loop, so far...
293          * Update: I've seen up to 9182 replies processed in this loop! ??
294          * Update: Limit ourselves to processing max of N replies
295          *      (bottom of loop).
296          */
297         while (1) {
298
299                 if ((pa = CHIPREG_READ32_dmasync(&ioc->chip->ReplyFifo)) == 0xFFFFFFFF)
300                         return IRQ_HANDLED;
301
302                 cb_idx = 0;
303                 freeme = 0;
304
305                 /*
306                  *  Check for non-TURBO reply!
307                  */
308                 if (pa & MPI_ADDRESS_REPLY_A_BIT) {
309                         u32 reply_dma_low;
310                         u16 ioc_stat;
311
312                         /* non-TURBO reply!  Hmmm, something may be up...
313                          *  Newest turbo reply mechanism; get address
314                          *  via left shift 1 (get rid of MPI_ADDRESS_REPLY_A_BIT)!
315                          */
316
317                         /* Map DMA address of reply header to cpu address.
318                          * pa is 32 bits - but the dma address may be 32 or 64 bits
319                          * get offset based only only the low addresses
320                          */
321                         reply_dma_low = (pa = (pa << 1));
322                         mr = (MPT_FRAME_HDR *)((u8 *)ioc->reply_frames +
323                                          (reply_dma_low - ioc->reply_frames_low_dma));
324
325                         req_idx = le16_to_cpu(mr->u.frame.hwhdr.msgctxu.fld.req_idx);
326                         cb_idx = mr->u.frame.hwhdr.msgctxu.fld.cb_idx;
327                         mf = MPT_INDEX_2_MFPTR(ioc, req_idx);
328
329                         dmfprintk((MYIOC_s_INFO_FMT "Got non-TURBO reply=%p req_idx=%x\n",
330                                         ioc->name, mr, req_idx));
331                         DBG_DUMP_REPLY_FRAME(mr)
332
333                         /* NEW!  20010301 -sralston
334                          *  Check/log IOC log info
335                          */
336                         ioc_stat = le16_to_cpu(mr->u.reply.IOCStatus);
337                         if (ioc_stat & MPI_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
338                                 u32      log_info = le32_to_cpu(mr->u.reply.IOCLogInfo);
339                                 if (ioc->bus_type == FC)
340                                         mpt_fc_log_info(ioc, log_info);
341                                 else if (ioc->bus_type == SCSI)
342                                         mpt_sp_log_info(ioc, log_info);
343                         }
344                         if (ioc_stat & MPI_IOCSTATUS_MASK) {
345                                 if (ioc->bus_type == SCSI)
346                                         mpt_sp_ioc_info(ioc, (u32)ioc_stat, mf);
347                         }
348                 } else {
349                         /*
350                          *  Process turbo (context) reply...
351                          */
352                         dmfprintk((MYIOC_s_INFO_FMT "Got TURBO reply req_idx=%08x\n", ioc->name, pa));
353                         type = (pa >> MPI_CONTEXT_REPLY_TYPE_SHIFT);
354                         if (type == MPI_CONTEXT_REPLY_TYPE_SCSI_TARGET) {
355                                 cb_idx = mpt_stm_index;
356                                 mf = NULL;
357                                 mr = (MPT_FRAME_HDR *) CAST_U32_TO_PTR(pa);
358                         } else if (type == MPI_CONTEXT_REPLY_TYPE_LAN) {
359                                 cb_idx = mpt_lan_index;
360                                 /*
361                                  * BUG FIX!  20001218 -sralston
362                                  *  Blind set of mf to NULL here was fatal
363                                  *  after lan_reply says "freeme"
364                                  *  Fix sort of combined with an optimization here;
365                                  *  added explicit check for case where lan_reply
366                                  *  was just returning 1 and doing nothing else.
367                                  *  For this case skip the callback, but set up
368                                  *  proper mf value first here:-)
369                                  */
370                                 if ((pa & 0x58000000) == 0x58000000) {
371                                         req_idx = pa & 0x0000FFFF;
372                                         mf = MPT_INDEX_2_MFPTR(ioc, req_idx);
373                                         freeme = 1;
374                                         /*
375                                          *  IMPORTANT!  Invalidate the callback!
376                                          */
377                                         cb_idx = 0;
378                                 } else {
379                                         mf = NULL;
380                                 }
381                                 mr = (MPT_FRAME_HDR *) CAST_U32_TO_PTR(pa);
382                         } else {
383                                 req_idx = pa & 0x0000FFFF;
384                                 cb_idx = (pa & 0x00FF0000) >> 16;
385                                 mf = MPT_INDEX_2_MFPTR(ioc, req_idx);
386                                 mr = NULL;
387                         }
388                         pa = 0;                                 /* No reply flush! */
389                 }
390
391 #ifdef MPT_DEBUG_IRQ
392                 if (ioc->bus_type == SCSI) {
393                         /* Verify mf, mr are reasonable.
394                          */
395                         if ((mf) && ((mf >= MPT_INDEX_2_MFPTR(ioc, ioc->req_depth))
396                                 || (mf < ioc->req_frames)) ) {
397                                 printk(MYIOC_s_WARN_FMT
398                                         "mpt_interrupt: Invalid mf (%p) req_idx (%d)!\n", ioc->name, (void *)mf, req_idx);
399                                 cb_idx = 0;
400                                 pa = 0;
401                                 freeme = 0;
402                         }
403                         if ((pa) && (mr) && ((mr >= MPT_INDEX_2_RFPTR(ioc, ioc->req_depth))
404                                 || (mr < ioc->reply_frames)) ) {
405                                 printk(MYIOC_s_WARN_FMT
406                                         "mpt_interrupt: Invalid rf (%p)!\n", ioc->name, (void *)mr);
407                                 cb_idx = 0;
408                                 pa = 0;
409                                 freeme = 0;
410                         }
411                         if (cb_idx > (MPT_MAX_PROTOCOL_DRIVERS-1)) {
412                                 printk(MYIOC_s_WARN_FMT
413                                         "mpt_interrupt: Invalid cb_idx (%d)!\n", ioc->name, cb_idx);
414                                 cb_idx = 0;
415                                 pa = 0;
416                                 freeme = 0;
417                         }
418                 }
419 #endif
420
421                 /*  Check for (valid) IO callback!  */
422                 if (cb_idx) {
423                         /*  Do the callback!  */
424                         freeme = (*(MptCallbacks[cb_idx]))(ioc, mf, mr);
425                 }
426
427                 if (pa) {
428                         /*  Flush (non-TURBO) reply with a WRITE!  */
429                         CHIPREG_WRITE32(&ioc->chip->ReplyFifo, pa);
430                 }
431
432                 if (freeme) {
433                         unsigned long flags;
434
435                         /*  Put Request back on FreeQ!  */
436                         spin_lock_irqsave(&ioc->FreeQlock, flags);
437                         list_add_tail(&mf->u.frame.linkage.list, &ioc->FreeQ);
438 #ifdef MFCNT
439                         ioc->mfcnt--;
440 #endif
441                         spin_unlock_irqrestore(&ioc->FreeQlock, flags);
442                 }
443
444                 mb();
445         }       /* drain reply FIFO */
446
447         return IRQ_HANDLED;
448 }
449
450 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
451 /*
452  *      mpt_base_reply - MPT base driver's callback routine; all base driver
453  *      "internal" request/reply processing is routed here.
454  *      Currently used for EventNotification and EventAck handling.
455  *      @ioc: Pointer to MPT_ADAPTER structure
456  *      @mf: Pointer to original MPT request frame
457  *      @reply: Pointer to MPT reply frame (NULL if TurboReply)
458  *
459         *       Returns 1 indicating original alloc'd request frame ptr
460  *      should be freed, or 0 if it shouldn't.
461  */
462 static int
463 mpt_base_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *reply)
464 {
465         int freereq = 1;
466         u8 func;
467
468         dprintk((MYIOC_s_INFO_FMT "mpt_base_reply() called\n", ioc->name));
469
470         if ((mf == NULL) ||
471             (mf >= MPT_INDEX_2_MFPTR(ioc, ioc->req_depth))) {
472                 printk(MYIOC_s_ERR_FMT "NULL or BAD request frame ptr! (=%p)\n",
473                                 ioc->name, (void *)mf);
474                 return 1;
475         }
476
477         if (reply == NULL) {
478                 dprintk((MYIOC_s_ERR_FMT "Unexpected NULL Event (turbo?) reply!\n",
479                                 ioc->name));
480                 return 1;
481         }
482
483         if (!(reply->u.hdr.MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY)) {
484                 dmfprintk((KERN_INFO MYNAM ": Original request frame (@%p) header\n", mf));
485                 DBG_DUMP_REQUEST_FRAME_HDR(mf)
486         }
487
488         func = reply->u.hdr.Function;
489         dprintk((MYIOC_s_INFO_FMT "mpt_base_reply, Function=%02Xh\n",
490                         ioc->name, func));
491
492         if (func == MPI_FUNCTION_EVENT_NOTIFICATION) {
493                 EventNotificationReply_t *pEvReply = (EventNotificationReply_t *) reply;
494                 int evHandlers = 0;
495                 int results;
496
497                 results = ProcessEventNotification(ioc, pEvReply, &evHandlers);
498                 if (results != evHandlers) {
499                         /* CHECKME! Any special handling needed here? */
500                         devtprintk((MYIOC_s_WARN_FMT "Called %d event handlers, sum results = %d\n",
501                                         ioc->name, evHandlers, results));
502                 }
503
504                 /*
505                  *      Hmmm...  It seems that EventNotificationReply is an exception
506                  *      to the rule of one reply per request.
507                  */
508                 if (pEvReply->MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY)
509                         freereq = 0;
510
511 #ifdef CONFIG_PROC_FS
512 //              LogEvent(ioc, pEvReply);
513 #endif
514
515         } else if (func == MPI_FUNCTION_EVENT_ACK) {
516                 dprintk((MYIOC_s_INFO_FMT "mpt_base_reply, EventAck reply received\n",
517                                 ioc->name));
518         } else if (func == MPI_FUNCTION_CONFIG ||
519                    func == MPI_FUNCTION_TOOLBOX) {
520                 CONFIGPARMS *pCfg;
521                 unsigned long flags;
522
523                 dcprintk((MYIOC_s_INFO_FMT "config_complete (mf=%p,mr=%p)\n",
524                                 ioc->name, mf, reply));
525
526                 pCfg = * ((CONFIGPARMS **)((u8 *) mf + ioc->req_sz - sizeof(void *)));
527
528                 if (pCfg) {
529                         /* disable timer and remove from linked list */
530                         del_timer(&pCfg->timer);
531
532                         spin_lock_irqsave(&ioc->FreeQlock, flags);
533                         list_del(&pCfg->linkage);
534                         spin_unlock_irqrestore(&ioc->FreeQlock, flags);
535
536                         /*
537                          *      If IOC Status is SUCCESS, save the header
538                          *      and set the status code to GOOD.
539                          */
540                         pCfg->status = MPT_CONFIG_ERROR;
541                         if (reply) {
542                                 ConfigReply_t   *pReply = (ConfigReply_t *)reply;
543                                 u16              status;
544
545                                 status = le16_to_cpu(pReply->IOCStatus) & MPI_IOCSTATUS_MASK;
546                                 dcprintk((KERN_NOTICE "  IOCStatus=%04xh, IOCLogInfo=%08xh\n",
547                                      status, le32_to_cpu(pReply->IOCLogInfo)));
548
549                                 pCfg->status = status;
550                                 if (status == MPI_IOCSTATUS_SUCCESS) {
551                                         pCfg->hdr->PageVersion = pReply->Header.PageVersion;
552                                         pCfg->hdr->PageLength = pReply->Header.PageLength;
553                                         pCfg->hdr->PageNumber = pReply->Header.PageNumber;
554                                         pCfg->hdr->PageType = pReply->Header.PageType;
555                                 }
556                         }
557
558                         /*
559                          *      Wake up the original calling thread
560                          */
561                         pCfg->wait_done = 1;
562                         wake_up(&mpt_waitq);
563                 }
564         } else {
565                 printk(MYIOC_s_ERR_FMT "Unexpected msg function (=%02Xh) reply received!\n",
566                                 ioc->name, func);
567         }
568
569         /*
570          *      Conditionally tell caller to free the original
571          *      EventNotification/EventAck/unexpected request frame!
572          */
573         return freereq;
574 }
575
576 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
577 /**
578  *      mpt_register - Register protocol-specific main callback handler.
579  *      @cbfunc: callback function pointer
580  *      @dclass: Protocol driver's class (%MPT_DRIVER_CLASS enum value)
581  *
582  *      This routine is called by a protocol-specific driver (SCSI host,
583  *      LAN, SCSI target) to register it's reply callback routine.  Each
584  *      protocol-specific driver must do this before it will be able to
585  *      use any IOC resources, such as obtaining request frames.
586  *
587  *      NOTES: The SCSI protocol driver currently calls this routine thrice
588  *      in order to register separate callbacks; one for "normal" SCSI IO;
589  *      one for MptScsiTaskMgmt requests; one for Scan/DV requests.
590  *
591  *      Returns a positive integer valued "handle" in the
592  *      range (and S.O.D. order) {N,...,7,6,5,...,1} if successful.
593  *      Any non-positive return value (including zero!) should be considered
594  *      an error by the caller.
595  */
596 int
597 mpt_register(MPT_CALLBACK cbfunc, MPT_DRIVER_CLASS dclass)
598 {
599         int i;
600
601         last_drv_idx = -1;
602
603         /*
604          *  Search for empty callback slot in this order: {N,...,7,6,5,...,1}
605          *  (slot/handle 0 is reserved!)
606          */
607         for (i = MPT_MAX_PROTOCOL_DRIVERS-1; i; i--) {
608                 if (MptCallbacks[i] == NULL) {
609                         MptCallbacks[i] = cbfunc;
610                         MptDriverClass[i] = dclass;
611                         MptEvHandlers[i] = NULL;
612                         last_drv_idx = i;
613                         break;
614                 }
615         }
616
617         return last_drv_idx;
618 }
619
620 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
621 /**
622  *      mpt_deregister - Deregister a protocol drivers resources.
623  *      @cb_idx: previously registered callback handle
624  *
625  *      Each protocol-specific driver should call this routine when it's
626  *      module is unloaded.
627  */
628 void
629 mpt_deregister(int cb_idx)
630 {
631         if ((cb_idx >= 0) && (cb_idx < MPT_MAX_PROTOCOL_DRIVERS)) {
632                 MptCallbacks[cb_idx] = NULL;
633                 MptDriverClass[cb_idx] = MPTUNKNOWN_DRIVER;
634                 MptEvHandlers[cb_idx] = NULL;
635
636                 last_drv_idx++;
637         }
638 }
639
640 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
641 /**
642  *      mpt_event_register - Register protocol-specific event callback
643  *      handler.
644  *      @cb_idx: previously registered (via mpt_register) callback handle
645  *      @ev_cbfunc: callback function
646  *
647  *      This routine can be called by one or more protocol-specific drivers
648  *      if/when they choose to be notified of MPT events.
649  *
650  *      Returns 0 for success.
651  */
652 int
653 mpt_event_register(int cb_idx, MPT_EVHANDLER ev_cbfunc)
654 {
655         if (cb_idx < 1 || cb_idx >= MPT_MAX_PROTOCOL_DRIVERS)
656                 return -1;
657
658         MptEvHandlers[cb_idx] = ev_cbfunc;
659         return 0;
660 }
661
662 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
663 /**
664  *      mpt_event_deregister - Deregister protocol-specific event callback
665  *      handler.
666  *      @cb_idx: previously registered callback handle
667  *
668  *      Each protocol-specific driver should call this routine
669  *      when it does not (or can no longer) handle events,
670  *      or when it's module is unloaded.
671  */
672 void
673 mpt_event_deregister(int cb_idx)
674 {
675         if (cb_idx < 1 || cb_idx >= MPT_MAX_PROTOCOL_DRIVERS)
676                 return;
677
678         MptEvHandlers[cb_idx] = NULL;
679 }
680
681 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
682 /**
683  *      mpt_reset_register - Register protocol-specific IOC reset handler.
684  *      @cb_idx: previously registered (via mpt_register) callback handle
685  *      @reset_func: reset function
686  *
687  *      This routine can be called by one or more protocol-specific drivers
688  *      if/when they choose to be notified of IOC resets.
689  *
690  *      Returns 0 for success.
691  */
692 int
693 mpt_reset_register(int cb_idx, MPT_RESETHANDLER reset_func)
694 {
695         if (cb_idx < 1 || cb_idx >= MPT_MAX_PROTOCOL_DRIVERS)
696                 return -1;
697
698         MptResetHandlers[cb_idx] = reset_func;
699         return 0;
700 }
701
702 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
703 /**
704  *      mpt_reset_deregister - Deregister protocol-specific IOC reset handler.
705  *      @cb_idx: previously registered callback handle
706  *
707  *      Each protocol-specific driver should call this routine
708  *      when it does not (or can no longer) handle IOC reset handling,
709  *      or when it's module is unloaded.
710  */
711 void
712 mpt_reset_deregister(int cb_idx)
713 {
714         if (cb_idx < 1 || cb_idx >= MPT_MAX_PROTOCOL_DRIVERS)
715                 return;
716
717         MptResetHandlers[cb_idx] = NULL;
718 }
719
720 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
721 /**
722  *      mpt_device_driver_register - Register device driver hooks
723  */
724 int
725 mpt_device_driver_register(struct mpt_pci_driver * dd_cbfunc, int cb_idx)
726 {
727         MPT_ADAPTER     *ioc;
728         int             error=0;
729
730         if (cb_idx < 1 || cb_idx >= MPT_MAX_PROTOCOL_DRIVERS) {
731                 error= -EINVAL;
732                 return error;
733         }
734
735         MptDeviceDriverHandlers[cb_idx] = dd_cbfunc;
736
737         /* call per pci device probe entry point */
738         list_for_each_entry(ioc, &ioc_list, list) {
739                 if(dd_cbfunc->probe) {
740                         error = dd_cbfunc->probe(ioc->pcidev,
741                           ioc->pcidev->driver->id_table);
742                         if(error != 0)
743                                 return error;
744                 }
745          }
746
747         return error;
748 }
749
750 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
751 /**
752  *      mpt_device_driver_deregister - DeRegister device driver hooks
753  */
754 void
755 mpt_device_driver_deregister(int cb_idx)
756 {
757         struct mpt_pci_driver *dd_cbfunc;
758         MPT_ADAPTER     *ioc;
759
760         if (cb_idx < 1 || cb_idx >= MPT_MAX_PROTOCOL_DRIVERS)
761                 return;
762
763         dd_cbfunc = MptDeviceDriverHandlers[cb_idx];
764
765         list_for_each_entry(ioc, &ioc_list, list) {
766                 if (dd_cbfunc->remove)
767                         dd_cbfunc->remove(ioc->pcidev);
768         }
769         
770         MptDeviceDriverHandlers[cb_idx] = NULL;
771 }
772
773
774 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
775 /**
776  *      mpt_get_msg_frame - Obtain a MPT request frame from the pool (of 1024)
777  *      allocated per MPT adapter.
778  *      @handle: Handle of registered MPT protocol driver
779  *      @ioc: Pointer to MPT adapter structure
780  *
781  *      Returns pointer to a MPT request frame or %NULL if none are available
782  *      or IOC is not active.
783  */
784 MPT_FRAME_HDR*
785 mpt_get_msg_frame(int handle, MPT_ADAPTER *ioc)
786 {
787         MPT_FRAME_HDR *mf;
788         unsigned long flags;
789         u16      req_idx;       /* Request index */
790
791         /* validate handle and ioc identifier */
792
793 #ifdef MFCNT
794         if (!ioc->active)
795                 printk(KERN_WARNING "IOC Not Active! mpt_get_msg_frame returning NULL!\n");
796 #endif
797
798         /* If interrupts are not attached, do not return a request frame */
799         if (!ioc->active)
800                 return NULL;
801
802         spin_lock_irqsave(&ioc->FreeQlock, flags);
803         if (!list_empty(&ioc->FreeQ)) {
804                 int req_offset;
805
806                 mf = list_entry(ioc->FreeQ.next, MPT_FRAME_HDR,
807                                 u.frame.linkage.list);
808                 list_del(&mf->u.frame.linkage.list);
809                 mf->u.frame.hwhdr.msgctxu.fld.cb_idx = handle;  /* byte */
810                 req_offset = (u8 *)mf - (u8 *)ioc->req_frames;
811                                                                 /* u16! */
812                 req_idx = cpu_to_le16(req_offset / ioc->req_sz);
813                 mf->u.frame.hwhdr.msgctxu.fld.req_idx = req_idx;
814                 mf->u.frame.hwhdr.msgctxu.fld.rsvd = 0;
815                 ioc->RequestNB[req_idx] = ioc->NB_for_64_byte_frame; /* Default, will be changed if necessary in SG generation */
816 #ifdef MFCNT
817                 ioc->mfcnt++;
818 #endif
819         }
820         else
821                 mf = NULL;
822         spin_unlock_irqrestore(&ioc->FreeQlock, flags);
823
824 #ifdef MFCNT
825         if (mf == NULL)
826                 printk(KERN_WARNING "IOC Active. No free Msg Frames! Count 0x%x Max 0x%x\n", ioc->mfcnt, ioc->req_depth);
827         mfcounter++;
828         if (mfcounter == PRINT_MF_COUNT)
829                 printk(KERN_INFO "MF Count 0x%x Max 0x%x \n", ioc->mfcnt, ioc->req_depth);
830 #endif
831
832         dmfprintk((KERN_INFO MYNAM ": %s: mpt_get_msg_frame(%d,%d), got mf=%p\n",
833                         ioc->name, handle, ioc->id, mf));
834         return mf;
835 }
836
837 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
838 /**
839  *      mpt_put_msg_frame - Send a protocol specific MPT request frame
840  *      to a IOC.
841  *      @handle: Handle of registered MPT protocol driver
842  *      @ioc: Pointer to MPT adapter structure
843  *      @mf: Pointer to MPT request frame
844  *
845  *      This routine posts a MPT request frame to the request post FIFO of a
846  *      specific MPT adapter.
847  */
848 void
849 mpt_put_msg_frame(int handle, MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)
850 {
851         u32 mf_dma_addr;
852         int req_offset;
853         u16      req_idx;       /* Request index */
854
855         /* ensure values are reset properly! */
856         mf->u.frame.hwhdr.msgctxu.fld.cb_idx = handle;          /* byte */
857         req_offset = (u8 *)mf - (u8 *)ioc->req_frames;
858                                                                 /* u16! */
859         req_idx = cpu_to_le16(req_offset / ioc->req_sz);
860         mf->u.frame.hwhdr.msgctxu.fld.req_idx = req_idx;
861         mf->u.frame.hwhdr.msgctxu.fld.rsvd = 0;
862
863 #ifdef MPT_DEBUG_MSG_FRAME
864         {
865                 u32     *m = mf->u.frame.hwhdr.__hdr;
866                 int      ii, n;
867
868                 printk(KERN_INFO MYNAM ": %s: About to Put msg frame @ %p:\n" KERN_INFO " ",
869                                 ioc->name, m);
870                 n = ioc->req_sz/4 - 1;
871                 while (m[n] == 0)
872                         n--;
873                 for (ii=0; ii<=n; ii++) {
874                         if (ii && ((ii%8)==0))
875                                 printk("\n" KERN_INFO " ");
876                         printk(" %08x", le32_to_cpu(m[ii]));
877                 }
878                 printk("\n");
879         }
880 #endif
881
882         mf_dma_addr = (ioc->req_frames_low_dma + req_offset) | ioc->RequestNB[req_idx];  
883         dsgprintk((MYIOC_s_INFO_FMT "mf_dma_addr=%x req_idx=%d RequestNB=%x\n", ioc->name, mf_dma_addr, req_idx, ioc->RequestNB[req_idx]));
884         CHIPREG_WRITE32(&ioc->chip->RequestFifo, mf_dma_addr);
885 }
886
887 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
888 /**
889  *      mpt_free_msg_frame - Place MPT request frame back on FreeQ.
890  *      @handle: Handle of registered MPT protocol driver
891  *      @ioc: Pointer to MPT adapter structure
892  *      @mf: Pointer to MPT request frame
893  *
894  *      This routine places a MPT request frame back on the MPT adapter's
895  *      FreeQ.
896  */
897 void
898 mpt_free_msg_frame(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)
899 {
900         unsigned long flags;
901
902         /*  Put Request back on FreeQ!  */
903         spin_lock_irqsave(&ioc->FreeQlock, flags);
904         list_add_tail(&mf->u.frame.linkage.list, &ioc->FreeQ);
905 #ifdef MFCNT
906         ioc->mfcnt--;
907 #endif
908         spin_unlock_irqrestore(&ioc->FreeQlock, flags);
909 }
910
911 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
912 /**
913  *      mpt_add_sge - Place a simple SGE at address pAddr.
914  *      @pAddr: virtual address for SGE
915  *      @flagslength: SGE flags and data transfer length
916  *      @dma_addr: Physical address
917  *
918  *      This routine places a MPT request frame back on the MPT adapter's
919  *      FreeQ.
920  */
921 void
922 mpt_add_sge(char *pAddr, u32 flagslength, dma_addr_t dma_addr)
923 {
924         if (sizeof(dma_addr_t) == sizeof(u64)) {
925                 SGESimple64_t *pSge = (SGESimple64_t *) pAddr;
926                 u32 tmp = dma_addr & 0xFFFFFFFF;
927
928                 pSge->FlagsLength = cpu_to_le32(flagslength);
929                 pSge->Address.Low = cpu_to_le32(tmp);
930                 tmp = (u32) ((u64)dma_addr >> 32);
931                 pSge->Address.High = cpu_to_le32(tmp);
932
933         } else {
934                 SGESimple32_t *pSge = (SGESimple32_t *) pAddr;
935                 pSge->FlagsLength = cpu_to_le32(flagslength);
936                 pSge->Address = cpu_to_le32(dma_addr);
937         }
938 }
939
940 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
941 /**
942  *      mpt_send_handshake_request - Send MPT request via doorbell
943  *      handshake method.
944  *      @handle: Handle of registered MPT protocol driver
945  *      @ioc: Pointer to MPT adapter structure
946  *      @reqBytes: Size of the request in bytes
947  *      @req: Pointer to MPT request frame
948  *      @sleepFlag: Use schedule if CAN_SLEEP else use udelay.
949  *
950  *      This routine is used exclusively to send MptScsiTaskMgmt
951  *      requests since they are required to be sent via doorbell handshake.
952  *
953  *      NOTE: It is the callers responsibility to byte-swap fields in the
954  *      request which are greater than 1 byte in size.
955  *
956  *      Returns 0 for success, non-zero for failure.
957  */
958 int
959 mpt_send_handshake_request(int handle, MPT_ADAPTER *ioc, int reqBytes, u32 *req, int sleepFlag)
960 {
961         int              r = 0;
962         u8      *req_as_bytes;
963         int      ii;
964
965         /* State is known to be good upon entering
966          * this function so issue the bus reset
967          * request.
968          */
969
970         /*
971          * Emulate what mpt_put_msg_frame() does /wrt to sanity
972          * setting cb_idx/req_idx.  But ONLY if this request
973          * is in proper (pre-alloc'd) request buffer range...
974          */
975         ii = MFPTR_2_MPT_INDEX(ioc,(MPT_FRAME_HDR*)req);
976         if (reqBytes >= 12 && ii >= 0 && ii < ioc->req_depth) {
977                 MPT_FRAME_HDR *mf = (MPT_FRAME_HDR*)req;
978                 mf->u.frame.hwhdr.msgctxu.fld.req_idx = cpu_to_le16(ii);
979                 mf->u.frame.hwhdr.msgctxu.fld.cb_idx = handle;
980         }
981
982         /* Make sure there are no doorbells */
983         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
984         
985         CHIPREG_WRITE32(&ioc->chip->Doorbell,
986                         ((MPI_FUNCTION_HANDSHAKE<<MPI_DOORBELL_FUNCTION_SHIFT) |
987                          ((reqBytes/4)<<MPI_DOORBELL_ADD_DWORDS_SHIFT)));
988
989         /* Wait for IOC doorbell int */
990         if ((ii = WaitForDoorbellInt(ioc, 5, sleepFlag)) < 0) {
991                 return ii;
992         }
993
994         /* Read doorbell and check for active bit */
995         if (!(CHIPREG_READ32(&ioc->chip->Doorbell) & MPI_DOORBELL_ACTIVE))
996                 return -5;
997
998         dhsprintk((KERN_INFO MYNAM ": %s: mpt_send_handshake_request start, WaitCnt=%d\n",
999                         ioc->name, ii));
1000
1001         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
1002
1003         if ((r = WaitForDoorbellAck(ioc, 5, sleepFlag)) < 0) {
1004                 return -2;
1005         }
1006                 
1007         /* Send request via doorbell handshake */
1008         req_as_bytes = (u8 *) req;
1009         for (ii = 0; ii < reqBytes/4; ii++) {
1010                 u32 word;
1011
1012                 word = ((req_as_bytes[(ii*4) + 0] <<  0) |
1013                         (req_as_bytes[(ii*4) + 1] <<  8) |
1014                         (req_as_bytes[(ii*4) + 2] << 16) |
1015                         (req_as_bytes[(ii*4) + 3] << 24));
1016                 CHIPREG_WRITE32(&ioc->chip->Doorbell, word);
1017                 if ((r = WaitForDoorbellAck(ioc, 5, sleepFlag)) < 0) {
1018                         r = -3;
1019                         break;
1020                 }
1021         }
1022
1023         if (r >= 0 && WaitForDoorbellInt(ioc, 10, sleepFlag) >= 0)
1024                 r = 0;
1025         else
1026                 r = -4;
1027
1028         /* Make sure there are no doorbells */
1029         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
1030         
1031         return r;
1032 }
1033
1034 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1035 /**
1036  *      mpt_verify_adapter - Given a unique IOC identifier, set pointer to
1037  *      the associated MPT adapter structure.
1038  *      @iocid: IOC unique identifier (integer)
1039  *      @iocpp: Pointer to pointer to IOC adapter
1040  *
1041  *      Returns iocid and sets iocpp.
1042  */
1043 int
1044 mpt_verify_adapter(int iocid, MPT_ADAPTER **iocpp)
1045 {
1046         MPT_ADAPTER *ioc;
1047
1048         list_for_each_entry(ioc,&ioc_list,list) {
1049                 if (ioc->id == iocid) {
1050                         *iocpp =ioc;
1051                         return iocid;
1052                 } 
1053         }
1054         
1055         *iocpp = NULL;
1056         return -1;
1057 }
1058
1059 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1060 /*
1061  *      mptbase_probe - Install a PCI intelligent MPT adapter.
1062  *      @pdev: Pointer to pci_dev structure
1063  *
1064  *      This routine performs all the steps necessary to bring the IOC of
1065  *      a MPT adapter to a OPERATIONAL state.  This includes registering
1066  *      memory regions, registering the interrupt, and allocating request
1067  *      and reply memory pools.
1068  *
1069  *      This routine also pre-fetches the LAN MAC address of a Fibre Channel
1070  *      MPT adapter.
1071  *
1072  *      Returns 0 for success, non-zero for failure.
1073  *
1074  *      TODO: Add support for polled controllers
1075  */
1076 static int __devinit
1077 mptbase_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1078 {
1079         MPT_ADAPTER     *ioc;
1080         u8              __iomem *mem;
1081         unsigned long    mem_phys;
1082         unsigned long    port;
1083         u32              msize;
1084         u32              psize;
1085         int              ii;
1086         int              r = -ENODEV;
1087         u64              mask = 0xffffffffffffffffULL;
1088         u8               revision;
1089         u8               pcixcmd;
1090         static int       mpt_ids = 0;
1091 #ifdef CONFIG_PROC_FS
1092         struct proc_dir_entry *dent, *ent;
1093 #endif
1094
1095         if (pci_enable_device(pdev))
1096                 return r;
1097         
1098         dinitprintk((KERN_WARNING MYNAM ": mpt_adapter_install\n"));
1099         
1100         if (!pci_set_dma_mask(pdev, mask)) {
1101                 dprintk((KERN_INFO MYNAM
1102                         ": 64 BIT PCI BUS DMA ADDRESSING SUPPORTED\n"));
1103         } else if (pci_set_dma_mask(pdev, (u64) 0xffffffff)) {
1104                 printk(KERN_WARNING MYNAM ": 32 BIT PCI BUS DMA ADDRESSING NOT SUPPORTED\n");
1105                 return r;
1106         }
1107
1108         if (!pci_set_consistent_dma_mask(pdev, mask))
1109                 dprintk((KERN_INFO MYNAM
1110                         ": Using 64 bit consistent mask\n"));
1111         else
1112                 dprintk((KERN_INFO MYNAM
1113                         ": Not using 64 bit consistent mask\n"));
1114
1115         ioc = kmalloc(sizeof(MPT_ADAPTER), GFP_ATOMIC);
1116         if (ioc == NULL) {
1117                 printk(KERN_ERR MYNAM ": ERROR - Insufficient memory to add adapter!\n");
1118                 return -ENOMEM;
1119         }
1120         memset(ioc, 0, sizeof(MPT_ADAPTER));
1121         ioc->alloc_total = sizeof(MPT_ADAPTER);
1122         ioc->req_sz = MPT_DEFAULT_FRAME_SIZE;           /* avoid div by zero! */
1123         ioc->reply_sz = MPT_REPLY_FRAME_SIZE;
1124         
1125         ioc->pcidev = pdev;
1126         ioc->diagPending = 0;
1127         spin_lock_init(&ioc->diagLock);
1128
1129         /* Initialize the event logging.
1130          */
1131         ioc->eventTypes = 0;    /* None */
1132         ioc->eventContext = 0;
1133         ioc->eventLogSize = 0;
1134         ioc->events = NULL;
1135
1136 #ifdef MFCNT
1137         ioc->mfcnt = 0;
1138 #endif
1139
1140         ioc->cached_fw = NULL;
1141
1142         /* Initilize SCSI Config Data structure
1143          */
1144         memset(&ioc->spi_data, 0, sizeof(ScsiCfgData));
1145
1146         /* Initialize the running configQ head.
1147          */
1148         INIT_LIST_HEAD(&ioc->configQ);
1149
1150         /* Find lookup slot. */
1151         INIT_LIST_HEAD(&ioc->list);
1152         ioc->id = mpt_ids++;
1153         
1154         mem_phys = msize = 0;
1155         port = psize = 0;
1156         for (ii=0; ii < DEVICE_COUNT_RESOURCE; ii++) {
1157                 if (pci_resource_flags(pdev, ii) & PCI_BASE_ADDRESS_SPACE_IO) {
1158                         /* Get I/O space! */
1159                         port = pci_resource_start(pdev, ii);
1160                         psize = pci_resource_len(pdev,ii);
1161                 } else {
1162                         /* Get memmap */
1163                         mem_phys = pci_resource_start(pdev, ii);
1164                         msize = pci_resource_len(pdev,ii);
1165                         break;
1166                 }
1167         }
1168         ioc->mem_size = msize;
1169
1170         if (ii == DEVICE_COUNT_RESOURCE) {
1171                 printk(KERN_ERR MYNAM ": ERROR - MPT adapter has no memory regions defined!\n");
1172                 kfree(ioc);
1173                 return -EINVAL;
1174         }
1175
1176         dinitprintk((KERN_INFO MYNAM ": MPT adapter @ %lx, msize=%dd bytes\n", mem_phys, msize));
1177         dinitprintk((KERN_INFO MYNAM ": (port i/o @ %lx, psize=%dd bytes)\n", port, psize));
1178
1179         mem = NULL;
1180         /* Get logical ptr for PciMem0 space */
1181         /*mem = ioremap(mem_phys, msize);*/
1182         mem = ioremap(mem_phys, 0x100);
1183         if (mem == NULL) {
1184                 printk(KERN_ERR MYNAM ": ERROR - Unable to map adapter memory!\n");
1185                 kfree(ioc);
1186                 return -EINVAL;
1187         }
1188         ioc->memmap = mem;
1189         dinitprintk((KERN_INFO MYNAM ": mem = %p, mem_phys = %lx\n", mem, mem_phys));
1190
1191         dinitprintk((KERN_INFO MYNAM ": facts @ %p, pfacts[0] @ %p\n",
1192                         &ioc->facts, &ioc->pfacts[0]));
1193
1194         ioc->mem_phys = mem_phys;
1195         ioc->chip = (SYSIF_REGS __iomem *)mem;
1196
1197         /* Save Port IO values in case we need to do downloadboot */
1198         {
1199                 u8 *pmem = (u8*)port;
1200                 ioc->pio_mem_phys = port;
1201                 ioc->pio_chip = (SYSIF_REGS __iomem *)pmem;
1202         }
1203
1204         if (pdev->device == MPI_MANUFACTPAGE_DEVICEID_FC909) {
1205                 ioc->prod_name = "LSIFC909";
1206                 ioc->bus_type = FC;
1207         }
1208         if (pdev->device == MPI_MANUFACTPAGE_DEVICEID_FC929) {
1209                 ioc->prod_name = "LSIFC929";
1210                 ioc->bus_type = FC;
1211         }
1212         else if (pdev->device == MPI_MANUFACTPAGE_DEVICEID_FC919) {
1213                 ioc->prod_name = "LSIFC919";
1214                 ioc->bus_type = FC;
1215         }
1216         else if (pdev->device == MPI_MANUFACTPAGE_DEVICEID_FC929X) {
1217                 pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
1218                 ioc->bus_type = FC;
1219                 if (revision < XL_929) {
1220                         ioc->prod_name = "LSIFC929X";
1221                         /* 929X Chip Fix. Set Split transactions level
1222                         * for PCIX. Set MOST bits to zero.
1223                         */
1224                         pci_read_config_byte(pdev, 0x6a, &pcixcmd);
1225                         pcixcmd &= 0x8F;
1226                         pci_write_config_byte(pdev, 0x6a, pcixcmd);
1227                 } else {
1228                         ioc->prod_name = "LSIFC929XL";
1229                         /* 929XL Chip Fix. Set MMRBC to 0x08.
1230                         */
1231                         pci_read_config_byte(pdev, 0x6a, &pcixcmd);
1232                         pcixcmd |= 0x08;
1233                         pci_write_config_byte(pdev, 0x6a, pcixcmd);
1234                 }
1235         }
1236         else if (pdev->device == MPI_MANUFACTPAGE_DEVICEID_FC919X) {
1237                 ioc->prod_name = "LSIFC919X";
1238                 ioc->bus_type = FC;
1239                 /* 919X Chip Fix. Set Split transactions level
1240                  * for PCIX. Set MOST bits to zero.
1241                  */
1242                 pci_read_config_byte(pdev, 0x6a, &pcixcmd);
1243                 pcixcmd &= 0x8F;
1244                 pci_write_config_byte(pdev, 0x6a, pcixcmd);
1245         }
1246         else if (pdev->device == MPI_MANUFACTPAGE_DEVID_53C1030) {
1247                 ioc->prod_name = "LSI53C1030";
1248                 ioc->bus_type = SCSI;
1249                 /* 1030 Chip Fix. Disable Split transactions
1250                  * for PCIX. Set MOST bits to zero if Rev < C0( = 8).
1251                  */
1252                 pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
1253                 if (revision < C0_1030) {
1254                         pci_read_config_byte(pdev, 0x6a, &pcixcmd);
1255                         pcixcmd &= 0x8F;
1256                         pci_write_config_byte(pdev, 0x6a, pcixcmd);
1257                 }
1258         }
1259         else if (pdev->device == MPI_MANUFACTPAGE_DEVID_1030_53C1035) {
1260                 ioc->prod_name = "LSI53C1035";
1261                 ioc->bus_type = SCSI;
1262         }
1263
1264         sprintf(ioc->name, "ioc%d", ioc->id);
1265
1266         spin_lock_init(&ioc->FreeQlock);
1267
1268         /* Disable all! */
1269         CHIPREG_WRITE32(&ioc->chip->IntMask, 0xFFFFFFFF);
1270         ioc->active = 0;
1271         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
1272
1273         /* Set lookup ptr. */
1274         list_add_tail(&ioc->list, &ioc_list);
1275
1276         ioc->pci_irq = -1;
1277         if (pdev->irq) {
1278                 r = request_irq(pdev->irq, mpt_interrupt, SA_SHIRQ, ioc->name, ioc);
1279
1280                 if (r < 0) {
1281 #ifndef __sparc__
1282                         printk(MYIOC_s_ERR_FMT "Unable to allocate interrupt %d!\n",
1283                                         ioc->name, pdev->irq);
1284 #else
1285                         printk(MYIOC_s_ERR_FMT "Unable to allocate interrupt %s!\n",
1286                                         ioc->name, __irq_itoa(pdev->irq));
1287 #endif
1288                         list_del(&ioc->list);
1289                         iounmap(mem);
1290                         kfree(ioc);
1291                         return -EBUSY;
1292                 }
1293
1294                 ioc->pci_irq = pdev->irq;
1295
1296                 pci_set_master(pdev);                   /* ?? */
1297                 pci_set_drvdata(pdev, ioc);
1298
1299 #ifndef __sparc__
1300                 dprintk((KERN_INFO MYNAM ": %s installed at interrupt %d\n", ioc->name, pdev->irq));
1301 #else
1302                 dprintk((KERN_INFO MYNAM ": %s installed at interrupt %s\n", ioc->name, __irq_itoa(pdev->irq)));
1303 #endif
1304         }
1305
1306         /* NEW!  20010220 -sralston
1307          * Check for "bound ports" (929, 929X, 1030, 1035) to reduce redundant resets.
1308          */
1309         mpt_detect_bound_ports(ioc, pdev);
1310
1311         if ((r = mpt_do_ioc_recovery(ioc,
1312           MPT_HOSTEVENT_IOC_BRINGUP, CAN_SLEEP)) != 0) {
1313                 printk(KERN_WARNING MYNAM
1314                   ": WARNING - %s did not initialize properly! (%d)\n",
1315                   ioc->name, r);
1316
1317                 list_del(&ioc->list);
1318                 free_irq(ioc->pci_irq, ioc);
1319                 iounmap(mem);
1320                 kfree(ioc);
1321                 pci_set_drvdata(pdev, NULL);
1322                 return r;
1323         }
1324
1325         /* call per device driver probe entry point */
1326         for(ii=0; ii<MPT_MAX_PROTOCOL_DRIVERS; ii++) {
1327                 if(MptDeviceDriverHandlers[ii] &&
1328                   MptDeviceDriverHandlers[ii]->probe) {
1329                         MptDeviceDriverHandlers[ii]->probe(pdev,id);
1330                 }
1331         }
1332
1333 #ifdef CONFIG_PROC_FS
1334         /*
1335          *  Create "/proc/mpt/iocN" subdirectory entry for each MPT adapter.
1336          */
1337         dent = proc_mkdir(ioc->name, mpt_proc_root_dir);
1338         if (dent) {
1339                 ent = create_proc_entry("info", S_IFREG|S_IRUGO, dent);
1340                 if (ent) {
1341                         ent->read_proc = procmpt_iocinfo_read;
1342                         ent->data = ioc;
1343                 }
1344                 ent = create_proc_entry("summary", S_IFREG|S_IRUGO, dent);
1345                 if (ent) {
1346                         ent->read_proc = procmpt_summary_read;
1347                         ent->data = ioc;
1348                 }
1349         }
1350 #endif
1351
1352         return 0;
1353 }
1354
1355 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1356 /*
1357  *      mptbase_remove - Remove a PCI intelligent MPT adapter.
1358  *      @pdev: Pointer to pci_dev structure
1359  *
1360  */
1361
1362 static void __devexit
1363 mptbase_remove(struct pci_dev *pdev)
1364 {
1365         MPT_ADAPTER     *ioc = pci_get_drvdata(pdev);
1366         char pname[32];
1367         int ii;
1368
1369         sprintf(pname, MPT_PROCFS_MPTBASEDIR "/%s/summary", ioc->name);
1370         remove_proc_entry(pname, NULL);
1371         sprintf(pname, MPT_PROCFS_MPTBASEDIR "/%s/info", ioc->name);
1372         remove_proc_entry(pname, NULL);
1373         sprintf(pname, MPT_PROCFS_MPTBASEDIR "/%s", ioc->name);
1374         remove_proc_entry(pname, NULL);
1375         
1376         /* call per device driver remove entry point */
1377         for(ii=0; ii<MPT_MAX_PROTOCOL_DRIVERS; ii++) {
1378                 if(MptDeviceDriverHandlers[ii] &&
1379                   MptDeviceDriverHandlers[ii]->remove) {
1380                         MptDeviceDriverHandlers[ii]->remove(pdev);
1381                 }
1382         }
1383         
1384         /* Disable interrupts! */
1385         CHIPREG_WRITE32(&ioc->chip->IntMask, 0xFFFFFFFF);
1386
1387         ioc->active = 0;
1388         synchronize_irq(pdev->irq);
1389
1390         /* Clear any lingering interrupt */
1391         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
1392
1393         CHIPREG_READ32(&ioc->chip->IntStatus);
1394
1395         mpt_adapter_dispose(ioc);
1396
1397         pci_set_drvdata(pdev, NULL);
1398 }
1399
1400 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1401 /*
1402  *      mptbase_shutdown -
1403  *
1404  */
1405 static void
1406 mptbase_shutdown(struct device * dev)
1407 {
1408         int ii;
1409
1410         /* call per device driver shutdown entry point */
1411         for(ii=0; ii<MPT_MAX_PROTOCOL_DRIVERS; ii++) {
1412                 if(MptDeviceDriverHandlers[ii] &&
1413                   MptDeviceDriverHandlers[ii]->shutdown) {
1414                         MptDeviceDriverHandlers[ii]->shutdown(dev);
1415                 }
1416         }
1417
1418 }
1419
1420
1421 /**************************************************************************
1422  * Power Management
1423  */
1424 #ifdef CONFIG_PM
1425 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1426 /*
1427  *      mptbase_suspend - Fusion MPT base driver suspend routine.
1428  *
1429  *
1430  */
1431 static int
1432 mptbase_suspend(struct pci_dev *pdev, u32 state)
1433 {
1434         u32 device_state;
1435         MPT_ADAPTER *ioc = pci_get_drvdata(pdev);
1436         int ii;
1437
1438         switch(state)
1439         {
1440                 case 1: /* S1 */
1441                         device_state=1; /* D1 */;
1442                         break;
1443                 case 3: /* S3 */
1444                 case 4: /* S4 */
1445                         device_state=3; /* D3 */;
1446                         break;
1447                 default:
1448                         return -EAGAIN /*FIXME*/;
1449                         break;
1450         }
1451
1452         printk(MYIOC_s_INFO_FMT
1453         "pci-suspend: pdev=0x%p, slot=%s, Entering operating state [D%d]\n",
1454                 ioc->name, pdev, pci_name(pdev), device_state);
1455
1456         /* call per device driver suspend entry point */
1457         for(ii=0; ii<MPT_MAX_PROTOCOL_DRIVERS; ii++) {
1458                 if(MptDeviceDriverHandlers[ii] &&
1459                   MptDeviceDriverHandlers[ii]->suspend) {
1460                         MptDeviceDriverHandlers[ii]->suspend(pdev, state);
1461                 }
1462         }
1463
1464         pci_save_state(pdev);
1465
1466         /* put ioc into READY_STATE */
1467         if(SendIocReset(ioc, MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET, CAN_SLEEP)) {
1468                 printk(MYIOC_s_ERR_FMT
1469                 "pci-suspend:  IOC msg unit reset failed!\n", ioc->name);
1470         }
1471
1472         /* disable interrupts */
1473         CHIPREG_WRITE32(&ioc->chip->IntMask, 0xFFFFFFFF);
1474         ioc->active = 0;
1475
1476         /* Clear any lingering interrupt */
1477         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
1478
1479         pci_disable_device(pdev);
1480         pci_set_power_state(pdev, device_state);
1481
1482         return 0;
1483 }
1484
1485 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1486 /*
1487  *      mptbase_resume - Fusion MPT base driver resume routine.
1488  *
1489  *
1490  */
1491 static int
1492 mptbase_resume(struct pci_dev *pdev)
1493 {
1494         MPT_ADAPTER *ioc = pci_get_drvdata(pdev);
1495         u32 device_state = pdev->current_state;
1496         int recovery_state;
1497         int ii;
1498
1499         printk(MYIOC_s_INFO_FMT
1500         "pci-resume: pdev=0x%p, slot=%s, Previous operating state [D%d]\n",
1501                 ioc->name, pdev, pci_name(pdev), device_state);
1502
1503         pci_set_power_state(pdev, 0);
1504         pci_restore_state(pdev);
1505         pci_enable_device(pdev);
1506
1507         /* enable interrupts */
1508         CHIPREG_WRITE32(&ioc->chip->IntMask, ~(MPI_HIM_RIM));
1509         ioc->active = 1;
1510
1511         /* F/W not running */
1512         if(!CHIPREG_READ32(&ioc->chip->Doorbell)) {
1513                 /* enable domain validation flags */
1514                 for (ii=0; ii < MPT_MAX_SCSI_DEVICES; ii++) {
1515                         ioc->spi_data.dvStatus[ii] |= MPT_SCSICFG_NEED_DV;
1516                 }
1517         }
1518
1519         printk(MYIOC_s_INFO_FMT
1520                 "pci-resume: ioc-state=0x%x,doorbell=0x%x\n",
1521                 ioc->name,
1522                 (mpt_GetIocState(ioc, 1) >> MPI_IOC_STATE_SHIFT),
1523                 CHIPREG_READ32(&ioc->chip->Doorbell));
1524
1525         /* bring ioc to operational state */
1526         if ((recovery_state = mpt_do_ioc_recovery(ioc,
1527             MPT_HOSTEVENT_IOC_RECOVER, CAN_SLEEP)) != 0) {
1528                 printk(MYIOC_s_INFO_FMT
1529                         "pci-resume: Cannot recover, error:[%x]\n",
1530                         ioc->name, recovery_state);
1531         } else {
1532                 printk(MYIOC_s_INFO_FMT
1533                         "pci-resume: success\n", ioc->name);
1534         }
1535
1536         /* call per device driver resume entry point */
1537         for(ii=0; ii<MPT_MAX_PROTOCOL_DRIVERS; ii++) {
1538                 if(MptDeviceDriverHandlers[ii] &&
1539                   MptDeviceDriverHandlers[ii]->resume) {
1540                         MptDeviceDriverHandlers[ii]->resume(pdev);
1541                 }
1542         }
1543
1544         return 0;
1545 }
1546 #endif
1547
1548 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1549 /*
1550  *      mpt_do_ioc_recovery - Initialize or recover MPT adapter.
1551  *      @ioc: Pointer to MPT adapter structure
1552  *      @reason: Event word / reason
1553  *      @sleepFlag: Use schedule if CAN_SLEEP else use udelay.
1554  *
1555  *      This routine performs all the steps necessary to bring the IOC
1556  *      to a OPERATIONAL state.
1557  *
1558  *      This routine also pre-fetches the LAN MAC address of a Fibre Channel
1559  *      MPT adapter.
1560  *
1561  *      Returns:
1562  *               0 for success
1563  *              -1 if failed to get board READY
1564  *              -2 if READY but IOCFacts Failed
1565  *              -3 if READY but PrimeIOCFifos Failed
1566  *              -4 if READY but IOCInit Failed
1567  */
1568 static int
1569 mpt_do_ioc_recovery(MPT_ADAPTER *ioc, u32 reason, int sleepFlag)
1570 {
1571         int      hard_reset_done = 0;
1572         int      alt_ioc_ready = 0;
1573         int      hard;
1574         int      rc=0;
1575         int      ii;
1576         int      handlers;
1577         int      ret = 0;
1578         int      reset_alt_ioc_active = 0;
1579
1580         printk(KERN_INFO MYNAM ": Initiating %s %s\n",
1581                         ioc->name, reason==MPT_HOSTEVENT_IOC_BRINGUP ? "bringup" : "recovery");
1582
1583         /* Disable reply interrupts (also blocks FreeQ) */
1584         CHIPREG_WRITE32(&ioc->chip->IntMask, 0xFFFFFFFF);
1585         ioc->active = 0;
1586
1587         if (ioc->alt_ioc) {
1588                 if (ioc->alt_ioc->active)
1589                         reset_alt_ioc_active = 1;
1590
1591                 /* Disable alt-IOC's reply interrupts (and FreeQ) for a bit ... */
1592                 CHIPREG_WRITE32(&ioc->alt_ioc->chip->IntMask, 0xFFFFFFFF);
1593                 ioc->alt_ioc->active = 0;
1594         }
1595
1596         hard = 1;
1597         if (reason == MPT_HOSTEVENT_IOC_BRINGUP)
1598                 hard = 0;
1599
1600         if ((hard_reset_done = MakeIocReady(ioc, hard, sleepFlag)) < 0) {
1601                 if (hard_reset_done == -4) {
1602                         printk(KERN_WARNING MYNAM ": %s Owned by PEER..skipping!\n",
1603                                         ioc->name);
1604
1605                         if (reset_alt_ioc_active && ioc->alt_ioc) {
1606                                 /* (re)Enable alt-IOC! (reply interrupt, FreeQ) */
1607                                 dprintk((KERN_INFO MYNAM ": alt-%s reply irq re-enabled\n",
1608                                                 ioc->alt_ioc->name));
1609                                 CHIPREG_WRITE32(&ioc->alt_ioc->chip->IntMask, ~(MPI_HIM_RIM));
1610                                 ioc->alt_ioc->active = 1;
1611                         }
1612
1613                 } else {
1614                         printk(KERN_WARNING MYNAM ": %s NOT READY WARNING!\n",
1615                                         ioc->name);
1616                 }
1617                 return -1;
1618         }
1619
1620         /* hard_reset_done = 0 if a soft reset was performed
1621          * and 1 if a hard reset was performed.
1622          */
1623         if (hard_reset_done && reset_alt_ioc_active && ioc->alt_ioc) {
1624                 if ((rc = MakeIocReady(ioc->alt_ioc, 0, sleepFlag)) == 0)
1625                         alt_ioc_ready = 1;
1626                 else
1627                         printk(KERN_WARNING MYNAM
1628                                         ": alt-%s: Not ready WARNING!\n",
1629                                         ioc->alt_ioc->name);
1630         }
1631
1632         for (ii=0; ii<5; ii++) {
1633                 /* Get IOC facts! Allow 5 retries */
1634                 if ((rc = GetIocFacts(ioc, sleepFlag, reason)) == 0)
1635                         break;
1636         }
1637         
1638
1639         if (ii == 5) {
1640                 dinitprintk((MYIOC_s_INFO_FMT "Retry IocFacts failed rc=%x\n", ioc->name, rc));
1641                 ret = -2;
1642         } else if (reason == MPT_HOSTEVENT_IOC_BRINGUP) {
1643                 MptDisplayIocCapabilities(ioc);
1644         }
1645         
1646         if (alt_ioc_ready) {
1647                 if ((rc = GetIocFacts(ioc->alt_ioc, sleepFlag, reason)) != 0) {
1648                         dinitprintk((MYIOC_s_INFO_FMT "Initial Alt IocFacts failed rc=%x\n", ioc->name, rc));
1649                         /* Retry - alt IOC was initialized once
1650                          */
1651                         rc = GetIocFacts(ioc->alt_ioc, sleepFlag, reason);
1652                 }
1653                 if (rc) {
1654                         dinitprintk((MYIOC_s_INFO_FMT "Retry Alt IocFacts failed rc=%x\n", ioc->name, rc));
1655                         alt_ioc_ready = 0;
1656                         reset_alt_ioc_active = 0;
1657                 } else if (reason == MPT_HOSTEVENT_IOC_BRINGUP) {
1658                         MptDisplayIocCapabilities(ioc->alt_ioc);
1659                 }
1660         }
1661
1662         /* Prime reply & request queues!
1663          * (mucho alloc's) Must be done prior to
1664          * init as upper addresses are needed for init.
1665          * If fails, continue with alt-ioc processing
1666          */
1667         if ((ret == 0) && ((rc = PrimeIocFifos(ioc)) != 0))
1668                 ret = -3;
1669
1670         /* May need to check/upload firmware & data here!
1671          * If fails, continue with alt-ioc processing
1672          */
1673         if ((ret == 0) && ((rc = SendIocInit(ioc, sleepFlag)) != 0))
1674                 ret = -4;
1675 // NEW!
1676         if (alt_ioc_ready && ((rc = PrimeIocFifos(ioc->alt_ioc)) != 0)) {
1677                 printk(KERN_WARNING MYNAM ": alt-%s: (%d) FIFO mgmt alloc WARNING!\n",
1678                                 ioc->alt_ioc->name, rc);
1679                 alt_ioc_ready = 0;
1680                 reset_alt_ioc_active = 0;
1681         }
1682
1683         if (alt_ioc_ready) {
1684                 if ((rc = SendIocInit(ioc->alt_ioc, sleepFlag)) != 0) {
1685                         alt_ioc_ready = 0;
1686                         reset_alt_ioc_active = 0;
1687                         printk(KERN_WARNING MYNAM
1688                                 ": alt-%s: (%d) init failure WARNING!\n",
1689                                         ioc->alt_ioc->name, rc);
1690                 }
1691         }
1692
1693         if (reason == MPT_HOSTEVENT_IOC_BRINGUP){
1694                 if (ioc->upload_fw) {
1695                         ddlprintk((MYIOC_s_INFO_FMT
1696                                 "firmware upload required!\n", ioc->name));
1697
1698                         /* Controller is not operational, cannot do upload
1699                          */
1700                         if (ret == 0) {
1701                                 rc = mpt_do_upload(ioc, sleepFlag);
1702                                 if (rc != 0)
1703                                         printk(KERN_WARNING MYNAM ": firmware upload failure!\n");
1704                         }
1705                 }
1706         }
1707
1708         if (ret == 0) {
1709                 /* Enable! (reply interrupt) */
1710                 CHIPREG_WRITE32(&ioc->chip->IntMask, ~(MPI_HIM_RIM));
1711                 ioc->active = 1;
1712         }
1713
1714         if (reset_alt_ioc_active && ioc->alt_ioc) {
1715                 /* (re)Enable alt-IOC! (reply interrupt) */
1716                 dprintk((KERN_INFO MYNAM ": alt-%s reply irq re-enabled\n",
1717                                 ioc->alt_ioc->name));
1718                 CHIPREG_WRITE32(&ioc->alt_ioc->chip->IntMask, ~(MPI_HIM_RIM));
1719                 ioc->alt_ioc->active = 1;
1720         }
1721
1722         /* NEW!  20010120 -sralston
1723          *  Enable MPT base driver management of EventNotification
1724          *  and EventAck handling.
1725          */
1726         if ((ret == 0) && (!ioc->facts.EventState))
1727                 (void) SendEventNotification(ioc, 1);   /* 1=Enable EventNotification */
1728
1729         if (ioc->alt_ioc && alt_ioc_ready && !ioc->alt_ioc->facts.EventState)
1730                 (void) SendEventNotification(ioc->alt_ioc, 1);  /* 1=Enable EventNotification */
1731
1732         /* (Bugzilla:fibrebugs, #513)
1733          * Bug fix (part 2)!  20010905 -sralston
1734          *      Add additional "reason" check before call to GetLanConfigPages
1735          *      (combined with GetIoUnitPage2 call).  This prevents a somewhat
1736          *      recursive scenario; GetLanConfigPages times out, timer expired
1737          *      routine calls HardResetHandler, which calls into here again,
1738          *      and we try GetLanConfigPages again...
1739          */
1740         if ((ret == 0) && (reason == MPT_HOSTEVENT_IOC_BRINGUP)) {
1741                 if (ioc->bus_type == FC) {
1742                         /*
1743                          *  Pre-fetch FC port WWN and stuff...
1744                          *  (FCPortPage0_t stuff)
1745                          */
1746                         for (ii=0; ii < ioc->facts.NumberOfPorts; ii++) {
1747                                 (void) GetFcPortPage0(ioc, ii);
1748                         }
1749
1750                         if ((ioc->pfacts[0].ProtocolFlags & MPI_PORTFACTS_PROTOCOL_LAN) &&
1751                             (ioc->lan_cnfg_page0.Header.PageLength == 0)) {
1752                                 /*
1753                                  *  Pre-fetch the ports LAN MAC address!
1754                                  *  (LANPage1_t stuff)
1755                                  */
1756                                 (void) GetLanConfigPages(ioc);
1757 #ifdef MPT_DEBUG
1758                                 {
1759                                         u8 *a = (u8*)&ioc->lan_cnfg_page1.HardwareAddressLow;
1760                                         dprintk((MYIOC_s_INFO_FMT "LanAddr = %02X:%02X:%02X:%02X:%02X:%02X\n",
1761                                                         ioc->name, a[5], a[4], a[3], a[2], a[1], a[0] ));
1762                                 }
1763 #endif
1764                         }
1765                 } else {
1766                         /* Get NVRAM and adapter maximums from SPP 0 and 2
1767                          */
1768                         mpt_GetScsiPortSettings(ioc, 0);
1769
1770                         /* Get version and length of SDP 1
1771                          */
1772                         mpt_readScsiDevicePageHeaders(ioc, 0);
1773
1774                         /* Find IM volumes
1775                          */
1776                         if (ioc->facts.MsgVersion >= 0x0102)
1777                                 mpt_findImVolumes(ioc);
1778
1779                         /* Check, and possibly reset, the coalescing value
1780                          */
1781                         mpt_read_ioc_pg_1(ioc);
1782
1783                         mpt_read_ioc_pg_4(ioc);
1784                 }
1785
1786                 GetIoUnitPage2(ioc);
1787         }
1788
1789         /*
1790          * Call each currently registered protocol IOC reset handler
1791          * with post-reset indication.
1792          * NOTE: If we're doing _IOC_BRINGUP, there can be no
1793          * MptResetHandlers[] registered yet.
1794          */
1795         if (hard_reset_done) {
1796                 rc = handlers = 0;
1797                 for (ii=MPT_MAX_PROTOCOL_DRIVERS-1; ii; ii--) {
1798                         if ((ret == 0) && MptResetHandlers[ii]) {
1799                                 dprintk((MYIOC_s_INFO_FMT "Calling IOC post_reset handler #%d\n",
1800                                                 ioc->name, ii));
1801                                 rc += (*(MptResetHandlers[ii]))(ioc, MPT_IOC_POST_RESET);
1802                                 handlers++;
1803                         }
1804
1805                         if (alt_ioc_ready && MptResetHandlers[ii]) {
1806                                 dprintk((MYIOC_s_INFO_FMT "Calling alt-%s post_reset handler #%d\n",
1807                                                 ioc->name, ioc->alt_ioc->name, ii));
1808                                 rc += (*(MptResetHandlers[ii]))(ioc->alt_ioc, MPT_IOC_POST_RESET);
1809                                 handlers++;
1810                         }
1811                 }
1812                 /* FIXME?  Examine results here? */
1813         }
1814
1815         return ret;
1816 }
1817
1818 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1819 /*
1820  *      mpt_detect_bound_ports - Search for PCI bus/dev_function
1821  *      which matches PCI bus/dev_function (+/-1) for newly discovered 929,
1822  *      929X, 1030 or 1035.
1823  *      @ioc: Pointer to MPT adapter structure
1824  *      @pdev: Pointer to (struct pci_dev) structure
1825  *
1826  *      If match on PCI dev_function +/-1 is found, bind the two MPT adapters
1827  *      using alt_ioc pointer fields in their %MPT_ADAPTER structures.
1828  */
1829 static void
1830 mpt_detect_bound_ports(MPT_ADAPTER *ioc, struct pci_dev *pdev)
1831 {
1832         unsigned int match_lo, match_hi;
1833         MPT_ADAPTER *ioc_srch;
1834
1835         match_lo = pdev->devfn-1;
1836         match_hi = pdev->devfn+1;
1837         dprintk((MYIOC_s_INFO_FMT "PCI bus/devfn=%x/%x, searching for devfn match on %x or %x\n",
1838                         ioc->name, pdev->bus->number, pdev->devfn, match_lo, match_hi));
1839
1840         list_for_each_entry(ioc_srch, &ioc_list, list) {
1841                 struct pci_dev *_pcidev = ioc_srch->pcidev;
1842
1843                 if ((_pcidev->device == pdev->device) &&
1844                     (_pcidev->bus->number == pdev->bus->number) &&
1845                     (_pcidev->devfn == match_lo || _pcidev->devfn == match_hi) ) {
1846                         /* Paranoia checks */
1847                         if (ioc->alt_ioc != NULL) {
1848                                 printk(KERN_WARNING MYNAM ": Oops, already bound (%s <==> %s)!\n",
1849                                                 ioc->name, ioc->alt_ioc->name);
1850                                 break;
1851                         } else if (ioc_srch->alt_ioc != NULL) {
1852                                 printk(KERN_WARNING MYNAM ": Oops, already bound (%s <==> %s)!\n",
1853                                                 ioc_srch->name, ioc_srch->alt_ioc->name);
1854                                 break;
1855                         }
1856                         dprintk((KERN_INFO MYNAM ": FOUND! binding %s <==> %s\n",
1857                                         ioc->name, ioc_srch->name));
1858                         ioc_srch->alt_ioc = ioc;
1859                         ioc->alt_ioc = ioc_srch;
1860                         break;
1861                 }
1862         }
1863 }
1864
1865 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1866 /*
1867  *      mpt_adapter_disable - Disable misbehaving MPT adapter.
1868  *      @this: Pointer to MPT adapter structure
1869  */
1870 static void
1871 mpt_adapter_disable(MPT_ADAPTER *ioc)
1872 {
1873         int sz;
1874         int ret;
1875
1876         if (ioc->cached_fw != NULL) {
1877                 ddlprintk((KERN_INFO MYNAM ": mpt_adapter_disable: Pushing FW onto adapter\n"));
1878                 if ((ret = mpt_downloadboot(ioc, NO_SLEEP)) < 0) {
1879                         printk(KERN_WARNING MYNAM
1880                                 ": firmware downloadboot failure (%d)!\n", ret);
1881                 }
1882         }
1883
1884         /* Disable adapter interrupts! */
1885         CHIPREG_WRITE32(&ioc->chip->IntMask, 0xFFFFFFFF);
1886         ioc->active = 0;
1887         /* Clear any lingering interrupt */
1888         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
1889
1890         if (ioc->alloc != NULL) {
1891                 sz = ioc->alloc_sz;
1892                 dexitprintk((KERN_INFO MYNAM ": %s.free  @ %p, sz=%d bytes\n",
1893                         ioc->name, ioc->alloc, ioc->alloc_sz));
1894                 pci_free_consistent(ioc->pcidev, sz,
1895                                 ioc->alloc, ioc->alloc_dma);
1896                 ioc->reply_frames = NULL;
1897                 ioc->req_frames = NULL;
1898                 ioc->alloc = NULL;
1899                 ioc->alloc_total -= sz;
1900         }
1901
1902         if (ioc->sense_buf_pool != NULL) {
1903                 sz = (ioc->req_depth * MPT_SENSE_BUFFER_ALLOC);
1904                 pci_free_consistent(ioc->pcidev, sz,
1905                                 ioc->sense_buf_pool, ioc->sense_buf_pool_dma);
1906                 ioc->sense_buf_pool = NULL;
1907                 ioc->alloc_total -= sz;
1908         }
1909
1910         if (ioc->events != NULL){
1911                 sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS);
1912                 kfree(ioc->events);
1913                 ioc->events = NULL;
1914                 ioc->alloc_total -= sz;
1915         }
1916
1917         if (ioc->cached_fw != NULL) {
1918                 sz = ioc->facts.FWImageSize;
1919                 pci_free_consistent(ioc->pcidev, sz,
1920                         ioc->cached_fw, ioc->cached_fw_dma);
1921                 ioc->cached_fw = NULL;
1922                 ioc->alloc_total -= sz;
1923         }
1924
1925         if (ioc->spi_data.nvram != NULL) {
1926                 kfree(ioc->spi_data.nvram);
1927                 ioc->spi_data.nvram = NULL;
1928         }
1929
1930         if (ioc->spi_data.pIocPg3 != NULL) {
1931                 kfree(ioc->spi_data.pIocPg3);
1932                 ioc->spi_data.pIocPg3 = NULL;
1933         }
1934
1935         if (ioc->spi_data.pIocPg4 != NULL) {
1936                 sz = ioc->spi_data.IocPg4Sz;
1937                 pci_free_consistent(ioc->pcidev, sz, 
1938                         ioc->spi_data.pIocPg4,
1939                         ioc->spi_data.IocPg4_dma);
1940                 ioc->spi_data.pIocPg4 = NULL;
1941                 ioc->alloc_total -= sz;
1942         }
1943
1944         if (ioc->ReqToChain != NULL) {
1945                 kfree(ioc->ReqToChain);
1946                 kfree(ioc->RequestNB);
1947                 ioc->ReqToChain = NULL;
1948         }
1949
1950         if (ioc->ChainToChain != NULL) {
1951                 kfree(ioc->ChainToChain);
1952                 ioc->ChainToChain = NULL;
1953         }
1954 }
1955
1956 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
1957 /*
1958  *      mpt_adapter_dispose - Free all resources associated with a MPT
1959  *      adapter.
1960  *      @ioc: Pointer to MPT adapter structure
1961  *
1962  *      This routine unregisters h/w resources and frees all alloc'd memory
1963  *      associated with a MPT adapter structure.
1964  */
1965 static void
1966 mpt_adapter_dispose(MPT_ADAPTER *ioc)
1967 {
1968         if (ioc != NULL) {
1969                 int sz_first, sz_last;
1970
1971                 sz_first = ioc->alloc_total;
1972
1973                 mpt_adapter_disable(ioc);
1974
1975                 if (ioc->pci_irq != -1) {
1976                         free_irq(ioc->pci_irq, ioc);
1977                         ioc->pci_irq = -1;
1978                 }
1979
1980                 if (ioc->memmap != NULL)
1981                         iounmap(ioc->memmap);
1982
1983 #if defined(CONFIG_MTRR) && 0
1984                 if (ioc->mtrr_reg > 0) {
1985                         mtrr_del(ioc->mtrr_reg, 0, 0);
1986                         dprintk((KERN_INFO MYNAM ": %s: MTRR region de-registered\n", ioc->name));
1987                 }
1988 #endif
1989
1990                 /*  Zap the adapter lookup ptr!  */
1991                 list_del(&ioc->list);
1992
1993                 sz_last = ioc->alloc_total;
1994                 dprintk((KERN_INFO MYNAM ": %s: free'd %d of %d bytes\n",
1995                                 ioc->name, sz_first-sz_last+(int)sizeof(*ioc), sz_first));
1996                 kfree(ioc);
1997         }
1998 }
1999
2000 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2001 /*
2002  *      MptDisplayIocCapabilities - Disply IOC's capacilities.
2003  *      @ioc: Pointer to MPT adapter structure
2004  */
2005 static void
2006 MptDisplayIocCapabilities(MPT_ADAPTER *ioc)
2007 {
2008         int i = 0;
2009
2010         printk(KERN_INFO "%s: ", ioc->name);
2011         if (ioc->prod_name && strlen(ioc->prod_name) > 3)
2012                 printk("%s: ", ioc->prod_name+3);
2013         printk("Capabilities={");
2014
2015         if (ioc->pfacts[0].ProtocolFlags & MPI_PORTFACTS_PROTOCOL_INITIATOR) {
2016                 printk("Initiator");
2017                 i++;
2018         }
2019
2020         if (ioc->pfacts[0].ProtocolFlags & MPI_PORTFACTS_PROTOCOL_TARGET) {
2021                 printk("%sTarget", i ? "," : "");
2022                 i++;
2023         }
2024
2025         if (ioc->pfacts[0].ProtocolFlags & MPI_PORTFACTS_PROTOCOL_LAN) {
2026                 printk("%sLAN", i ? "," : "");
2027                 i++;
2028         }
2029
2030 #if 0
2031         /*
2032          *  This would probably evoke more questions than it's worth
2033          */
2034         if (ioc->pfacts[0].ProtocolFlags & MPI_PORTFACTS_PROTOCOL_TARGET) {
2035                 printk("%sLogBusAddr", i ? "," : "");
2036                 i++;
2037         }
2038 #endif
2039
2040         printk("}\n");
2041 }
2042
2043 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2044 /*
2045  *      MakeIocReady - Get IOC to a READY state, using KickStart if needed.
2046  *      @ioc: Pointer to MPT_ADAPTER structure
2047  *      @force: Force hard KickStart of IOC
2048  *      @sleepFlag: Specifies whether the process can sleep
2049  *
2050  *      Returns:
2051  *               1 - DIAG reset and READY
2052  *               0 - READY initially OR soft reset and READY
2053  *              -1 - Any failure on KickStart
2054  *              -2 - Msg Unit Reset Failed
2055  *              -3 - IO Unit Reset Failed
2056  *              -4 - IOC owned by a PEER
2057  */
2058 static int
2059 MakeIocReady(MPT_ADAPTER *ioc, int force, int sleepFlag)
2060 {
2061         u32      ioc_state;
2062         int      statefault = 0;
2063         int      cntdn;
2064         int      hard_reset_done = 0;
2065         int      r;
2066         int      ii;
2067         int      whoinit;
2068
2069         /* Get current [raw] IOC state  */
2070         ioc_state = mpt_GetIocState(ioc, 0);
2071         dhsprintk((KERN_INFO MYNAM "::MakeIocReady, %s [raw] state=%08x\n", ioc->name, ioc_state));
2072
2073         /*
2074          *      Check to see if IOC got left/stuck in doorbell handshake
2075          *      grip of death.  If so, hard reset the IOC.
2076          */
2077         if (ioc_state & MPI_DOORBELL_ACTIVE) {
2078                 statefault = 1;
2079                 printk(MYIOC_s_WARN_FMT "Unexpected doorbell active!\n",
2080                                 ioc->name);
2081         }
2082
2083         /* Is it already READY? */
2084         if (!statefault && (ioc_state & MPI_IOC_STATE_MASK) == MPI_IOC_STATE_READY) 
2085                 return 0;
2086
2087         /*
2088          *      Check to see if IOC is in FAULT state.
2089          */
2090         if ((ioc_state & MPI_IOC_STATE_MASK) == MPI_IOC_STATE_FAULT) {
2091                 statefault = 2;
2092                 printk(MYIOC_s_WARN_FMT "IOC is in FAULT state!!!\n",
2093                                 ioc->name);
2094                 printk(KERN_WARNING "           FAULT code = %04xh\n",
2095                                 ioc_state & MPI_DOORBELL_DATA_MASK);
2096         }
2097
2098         /*
2099          *      Hmmm...  Did it get left operational?
2100          */
2101         if ((ioc_state & MPI_IOC_STATE_MASK) == MPI_IOC_STATE_OPERATIONAL) {
2102                 dinitprintk((MYIOC_s_WARN_FMT "IOC operational unexpected\n",
2103                                 ioc->name));
2104
2105                 /* Check WhoInit.
2106                  * If PCI Peer, exit.
2107                  * Else, if no fault conditions are present, issue a MessageUnitReset
2108                  * Else, fall through to KickStart case
2109                  */
2110                 whoinit = (ioc_state & MPI_DOORBELL_WHO_INIT_MASK) >> MPI_DOORBELL_WHO_INIT_SHIFT;
2111                 dprintk((KERN_WARNING MYNAM
2112                         ": whoinit 0x%x\n statefault %d force %d\n",
2113                         whoinit, statefault, force));
2114                 if (whoinit == MPI_WHOINIT_PCI_PEER)
2115                         return -4;
2116                 else {
2117                         if ((statefault == 0 ) && (force == 0)) {
2118                                 if ((r = SendIocReset(ioc, MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET, sleepFlag)) == 0)
2119                                         return 0;
2120                         }
2121                         statefault = 3;
2122                 }
2123         }
2124
2125         hard_reset_done = KickStart(ioc, statefault||force, sleepFlag);
2126         if (hard_reset_done < 0)
2127                 return -1;
2128
2129         /*
2130          *  Loop here waiting for IOC to come READY.
2131          */
2132         ii = 0;
2133         cntdn = ((sleepFlag == CAN_SLEEP) ? HZ : 1000) * 15;    /* 15 seconds */
2134
2135         while ((ioc_state = mpt_GetIocState(ioc, 1)) != MPI_IOC_STATE_READY) {
2136                 if (ioc_state == MPI_IOC_STATE_OPERATIONAL) {
2137                         /*
2138                          *  BIOS or previous driver load left IOC in OP state.
2139                          *  Reset messaging FIFOs.
2140                          */
2141                         if ((r = SendIocReset(ioc, MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET, sleepFlag)) != 0) {
2142                                 printk(MYIOC_s_ERR_FMT "IOC msg unit reset failed!\n", ioc->name);
2143                                 return -2;
2144                         }
2145                 } else if (ioc_state == MPI_IOC_STATE_RESET) {
2146                         /*
2147                          *  Something is wrong.  Try to get IOC back
2148                          *  to a known state.
2149                          */
2150                         if ((r = SendIocReset(ioc, MPI_FUNCTION_IO_UNIT_RESET, sleepFlag)) != 0) {
2151                                 printk(MYIOC_s_ERR_FMT "IO unit reset failed!\n", ioc->name);
2152                                 return -3;
2153                         }
2154                 }
2155
2156                 ii++; cntdn--;
2157                 if (!cntdn) {
2158                         printk(MYIOC_s_ERR_FMT "Wait IOC_READY state timeout(%d)!\n",
2159                                         ioc->name, (int)((ii+5)/HZ));
2160                         return -ETIME;
2161                 }
2162
2163                 if (sleepFlag == CAN_SLEEP) {
2164                         msleep_interruptible(1);
2165                 } else {
2166                         mdelay (1);     /* 1 msec delay */
2167                 }
2168
2169         }
2170
2171         if (statefault < 3) {
2172                 printk(MYIOC_s_INFO_FMT "Recovered from %s\n",
2173                                 ioc->name,
2174                                 statefault==1 ? "stuck handshake" : "IOC FAULT");
2175         }
2176
2177         return hard_reset_done;
2178 }
2179
2180 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2181 /*
2182  *      mpt_GetIocState - Get the current state of a MPT adapter.
2183  *      @ioc: Pointer to MPT_ADAPTER structure
2184  *      @cooked: Request raw or cooked IOC state
2185  *
2186  *      Returns all IOC Doorbell register bits if cooked==0, else just the
2187  *      Doorbell bits in MPI_IOC_STATE_MASK.
2188  */
2189 u32
2190 mpt_GetIocState(MPT_ADAPTER *ioc, int cooked)
2191 {
2192         u32 s, sc;
2193
2194         /*  Get!  */
2195         s = CHIPREG_READ32(&ioc->chip->Doorbell);
2196 //      dprintk((MYIOC_s_INFO_FMT "raw state = %08x\n", ioc->name, s));
2197         sc = s & MPI_IOC_STATE_MASK;
2198
2199         /*  Save!  */
2200         ioc->last_state = sc;
2201
2202         return cooked ? sc : s;
2203 }
2204
2205 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2206 /*
2207  *      GetIocFacts - Send IOCFacts request to MPT adapter.
2208  *      @ioc: Pointer to MPT_ADAPTER structure
2209  *      @sleepFlag: Specifies whether the process can sleep
2210  *      @reason: If recovery, only update facts.
2211  *
2212  *      Returns 0 for success, non-zero for failure.
2213  */
2214 static int
2215 GetIocFacts(MPT_ADAPTER *ioc, int sleepFlag, int reason)
2216 {
2217         IOCFacts_t               get_facts;
2218         IOCFactsReply_t         *facts;
2219         int                      r;
2220         int                      req_sz;
2221         int                      reply_sz;
2222         int                      sz;
2223         u32                      status, vv;
2224         u8                       shiftFactor=1;
2225
2226         /* IOC *must* NOT be in RESET state! */
2227         if (ioc->last_state == MPI_IOC_STATE_RESET) {
2228                 printk(KERN_ERR MYNAM ": ERROR - Can't get IOCFacts, %s NOT READY! (%08x)\n",
2229                                 ioc->name,
2230                                 ioc->last_state );
2231                 return -44;
2232         }
2233
2234         facts = &ioc->facts;
2235
2236         /* Destination (reply area)... */
2237         reply_sz = sizeof(*facts);
2238         memset(facts, 0, reply_sz);
2239
2240         /* Request area (get_facts on the stack right now!) */
2241         req_sz = sizeof(get_facts);
2242         memset(&get_facts, 0, req_sz);
2243
2244         get_facts.Function = MPI_FUNCTION_IOC_FACTS;
2245         /* Assert: All other get_facts fields are zero! */
2246
2247         dinitprintk((MYIOC_s_INFO_FMT 
2248             "Sending get IocFacts request req_sz=%d reply_sz=%d\n", 
2249             ioc->name, req_sz, reply_sz));
2250
2251         /* No non-zero fields in the get_facts request are greater than
2252          * 1 byte in size, so we can just fire it off as is.
2253          */
2254         r = mpt_handshake_req_reply_wait(ioc, req_sz, (u32*)&get_facts,
2255                         reply_sz, (u16*)facts, 5 /*seconds*/, sleepFlag);
2256         if (r != 0)
2257                 return r;
2258
2259         /*
2260          * Now byte swap (GRRR) the necessary fields before any further
2261          * inspection of reply contents.
2262          *
2263          * But need to do some sanity checks on MsgLength (byte) field
2264          * to make sure we don't zero IOC's req_sz!
2265          */
2266         /* Did we get a valid reply? */
2267         if (facts->MsgLength > offsetof(IOCFactsReply_t, RequestFrameSize)/sizeof(u32)) {
2268                 if (reason == MPT_HOSTEVENT_IOC_BRINGUP) {
2269                         /*
2270                          * If not been here, done that, save off first WhoInit value
2271                          */
2272                         if (ioc->FirstWhoInit == WHOINIT_UNKNOWN)
2273                                 ioc->FirstWhoInit = facts->WhoInit;
2274                 }
2275
2276                 facts->MsgVersion = le16_to_cpu(facts->MsgVersion);
2277                 facts->MsgContext = le32_to_cpu(facts->MsgContext);
2278                 facts->IOCExceptions = le16_to_cpu(facts->IOCExceptions);
2279                 facts->IOCStatus = le16_to_cpu(facts->IOCStatus);
2280                 facts->IOCLogInfo = le32_to_cpu(facts->IOCLogInfo);
2281                 status = facts->IOCStatus & MPI_IOCSTATUS_MASK;
2282                 /* CHECKME! IOCStatus, IOCLogInfo */
2283
2284                 facts->ReplyQueueDepth = le16_to_cpu(facts->ReplyQueueDepth);
2285                 facts->RequestFrameSize = le16_to_cpu(facts->RequestFrameSize);
2286
2287                 /*
2288                  * FC f/w version changed between 1.1 and 1.2
2289                  *      Old: u16{Major(4),Minor(4),SubMinor(8)}
2290                  *      New: u32{Major(8),Minor(8),Unit(8),Dev(8)}
2291                  */
2292                 if (facts->MsgVersion < 0x0102) {
2293                         /*
2294                          *      Handle old FC f/w style, convert to new...
2295                          */
2296                         u16      oldv = le16_to_cpu(facts->Reserved_0101_FWVersion);
2297                         facts->FWVersion.Word =
2298                                         ((oldv<<12) & 0xFF000000) |
2299                                         ((oldv<<8)  & 0x000FFF00);
2300                 } else
2301                         facts->FWVersion.Word = le32_to_cpu(facts->FWVersion.Word);
2302
2303                 facts->ProductID = le16_to_cpu(facts->ProductID);
2304                 facts->CurrentHostMfaHighAddr =
2305                                 le32_to_cpu(facts->CurrentHostMfaHighAddr);
2306                 facts->GlobalCredits = le16_to_cpu(facts->GlobalCredits);
2307                 facts->CurrentSenseBufferHighAddr =
2308                                 le32_to_cpu(facts->CurrentSenseBufferHighAddr);
2309                 facts->CurReplyFrameSize =
2310                                 le16_to_cpu(facts->CurReplyFrameSize);
2311
2312                 /*
2313                  * Handle NEW (!) IOCFactsReply fields in MPI-1.01.xx
2314                  * Older MPI-1.00.xx struct had 13 dwords, and enlarged
2315                  * to 14 in MPI-1.01.0x.
2316                  */
2317                 if (facts->MsgLength >= (offsetof(IOCFactsReply_t,FWImageSize) + 7)/4 &&
2318                     facts->MsgVersion > 0x0100) {
2319                         facts->FWImageSize = le32_to_cpu(facts->FWImageSize);
2320                 }
2321
2322                 sz = facts->FWImageSize;
2323                 if ( sz & 0x01 )
2324                         sz += 1;
2325                 if ( sz & 0x02 )
2326                         sz += 2;
2327                 facts->FWImageSize = sz;
2328                 
2329                 if (!facts->RequestFrameSize) {
2330                         /*  Something is wrong!  */
2331                         printk(MYIOC_s_ERR_FMT "IOC reported invalid 0 request size!\n",
2332                                         ioc->name);
2333                         return -55;
2334                 }
2335
2336                 r = sz = le32_to_cpu(facts->BlockSize);
2337                 vv = ((63 / (sz * 4)) + 1) & 0x03;
2338                 ioc->NB_for_64_byte_frame = vv;
2339                 while ( sz )
2340                 {
2341                         shiftFactor++;
2342                         sz = sz >> 1;
2343                 }
2344                 ioc->NBShiftFactor  = shiftFactor;
2345                 dinitprintk((MYIOC_s_INFO_FMT "NB_for_64_byte_frame=%x NBShiftFactor=%x BlockSize=%x\n",
2346                                         ioc->name, vv, shiftFactor, r));
2347     
2348                 if (reason == MPT_HOSTEVENT_IOC_BRINGUP) {
2349                         /*
2350                          * Set values for this IOC's request & reply frame sizes,
2351                          * and request & reply queue depths...
2352                          */
2353                         ioc->req_sz = min(MPT_DEFAULT_FRAME_SIZE, facts->RequestFrameSize * 4);
2354                         ioc->req_depth = min_t(int, MPT_MAX_REQ_DEPTH, facts->GlobalCredits);
2355                         ioc->reply_sz = MPT_REPLY_FRAME_SIZE;
2356                         ioc->reply_depth = min_t(int, MPT_DEFAULT_REPLY_DEPTH, facts->ReplyQueueDepth);
2357
2358                         dinitprintk((MYIOC_s_INFO_FMT "reply_sz=%3d, reply_depth=%4d\n",
2359                                 ioc->name, ioc->reply_sz, ioc->reply_depth));
2360                         dinitprintk((MYIOC_s_INFO_FMT "req_sz  =%3d, req_depth  =%4d\n",
2361                                 ioc->name, ioc->req_sz, ioc->req_depth));
2362
2363                         /* Get port facts! */
2364                         if ( (r = GetPortFacts(ioc, 0, sleepFlag)) != 0 )
2365                                 return r;
2366                 }
2367         } else {
2368                 printk(MYIOC_s_ERR_FMT 
2369                      "Invalid IOC facts reply, msgLength=%d offsetof=%zd!\n",
2370                      ioc->name, facts->MsgLength, (offsetof(IOCFactsReply_t,
2371                      RequestFrameSize)/sizeof(u32)));
2372                 return -66;
2373         }
2374
2375         return 0;
2376 }
2377
2378 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2379 /*
2380  *      GetPortFacts - Send PortFacts request to MPT adapter.
2381  *      @ioc: Pointer to MPT_ADAPTER structure
2382  *      @portnum: Port number
2383  *      @sleepFlag: Specifies whether the process can sleep
2384  *
2385  *      Returns 0 for success, non-zero for failure.
2386  */
2387 static int
2388 GetPortFacts(MPT_ADAPTER *ioc, int portnum, int sleepFlag)
2389 {
2390         PortFacts_t              get_pfacts;
2391         PortFactsReply_t        *pfacts;
2392         int                      ii;
2393         int                      req_sz;
2394         int                      reply_sz;
2395
2396         /* IOC *must* NOT be in RESET state! */
2397         if (ioc->last_state == MPI_IOC_STATE_RESET) {
2398                 printk(KERN_ERR MYNAM ": ERROR - Can't get PortFacts, %s NOT READY! (%08x)\n",
2399                                 ioc->name,
2400                                 ioc->last_state );
2401                 return -4;
2402         }
2403
2404         pfacts = &ioc->pfacts[portnum];
2405
2406         /* Destination (reply area)...  */
2407         reply_sz = sizeof(*pfacts);
2408         memset(pfacts, 0, reply_sz);
2409
2410         /* Request area (get_pfacts on the stack right now!) */
2411         req_sz = sizeof(get_pfacts);
2412         memset(&get_pfacts, 0, req_sz);
2413
2414         get_pfacts.Function = MPI_FUNCTION_PORT_FACTS;
2415         get_pfacts.PortNumber = portnum;
2416         /* Assert: All other get_pfacts fields are zero! */
2417
2418         dinitprintk((MYIOC_s_INFO_FMT "Sending get PortFacts(%d) request\n",
2419                         ioc->name, portnum));
2420
2421         /* No non-zero fields in the get_pfacts request are greater than
2422          * 1 byte in size, so we can just fire it off as is.
2423          */
2424         ii = mpt_handshake_req_reply_wait(ioc, req_sz, (u32*)&get_pfacts,
2425                                 reply_sz, (u16*)pfacts, 5 /*seconds*/, sleepFlag);
2426         if (ii != 0)
2427                 return ii;
2428
2429         /* Did we get a valid reply? */
2430
2431         /* Now byte swap the necessary fields in the response. */
2432         pfacts->MsgContext = le32_to_cpu(pfacts->MsgContext);
2433         pfacts->IOCStatus = le16_to_cpu(pfacts->IOCStatus);
2434         pfacts->IOCLogInfo = le32_to_cpu(pfacts->IOCLogInfo);
2435         pfacts->MaxDevices = le16_to_cpu(pfacts->MaxDevices);
2436         pfacts->PortSCSIID = le16_to_cpu(pfacts->PortSCSIID);
2437         pfacts->ProtocolFlags = le16_to_cpu(pfacts->ProtocolFlags);
2438         pfacts->MaxPostedCmdBuffers = le16_to_cpu(pfacts->MaxPostedCmdBuffers);
2439         pfacts->MaxPersistentIDs = le16_to_cpu(pfacts->MaxPersistentIDs);
2440         pfacts->MaxLanBuckets = le16_to_cpu(pfacts->MaxLanBuckets);
2441
2442         return 0;
2443 }
2444
2445 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2446 /*
2447  *      SendIocInit - Send IOCInit request to MPT adapter.
2448  *      @ioc: Pointer to MPT_ADAPTER structure
2449  *      @sleepFlag: Specifies whether the process can sleep
2450  *
2451  *      Send IOCInit followed by PortEnable to bring IOC to OPERATIONAL state.
2452  *
2453  *      Returns 0 for success, non-zero for failure.
2454  */
2455 static int
2456 SendIocInit(MPT_ADAPTER *ioc, int sleepFlag)
2457 {
2458         IOCInit_t                ioc_init;
2459         MPIDefaultReply_t        init_reply;
2460         u32                      state;
2461         int                      r;
2462         int                      count;
2463         int                      cntdn;
2464
2465         memset(&ioc_init, 0, sizeof(ioc_init));
2466         memset(&init_reply, 0, sizeof(init_reply));
2467
2468         ioc_init.WhoInit = MPI_WHOINIT_HOST_DRIVER;
2469         ioc_init.Function = MPI_FUNCTION_IOC_INIT;
2470
2471         /* If we are in a recovery mode and we uploaded the FW image,
2472          * then this pointer is not NULL. Skip the upload a second time.
2473          * Set this flag if cached_fw set for either IOC.
2474          */
2475         if (ioc->facts.Flags & MPI_IOCFACTS_FLAGS_FW_DOWNLOAD_BOOT)
2476                 ioc->upload_fw = 1;
2477         else
2478                 ioc->upload_fw = 0;
2479         ddlprintk((MYIOC_s_INFO_FMT "upload_fw %d facts.Flags=%x\n",
2480                    ioc->name, ioc->upload_fw, ioc->facts.Flags));
2481
2482         if (ioc->bus_type == FC)
2483                 ioc_init.MaxDevices = MPT_MAX_FC_DEVICES;
2484         else
2485                 ioc_init.MaxDevices = MPT_MAX_SCSI_DEVICES;
2486         
2487         ioc_init.MaxBuses = MPT_MAX_BUS;
2488
2489         ioc_init.ReplyFrameSize = cpu_to_le16(ioc->reply_sz);   /* in BYTES */
2490
2491         if (sizeof(dma_addr_t) == sizeof(u64)) {
2492                 /* Save the upper 32-bits of the request
2493                  * (reply) and sense buffers.
2494                  */
2495                 ioc_init.HostMfaHighAddr = cpu_to_le32((u32)((u64)ioc->alloc_dma >> 32));
2496                 ioc_init.SenseBufferHighAddr = cpu_to_le32((u32)((u64)ioc->sense_buf_pool_dma >> 32));
2497         } else {
2498                 /* Force 32-bit addressing */
2499                 ioc_init.HostMfaHighAddr = cpu_to_le32(0);
2500                 ioc_init.SenseBufferHighAddr = cpu_to_le32(0);
2501         }
2502                 
2503         ioc->facts.CurrentHostMfaHighAddr = ioc_init.HostMfaHighAddr;
2504         ioc->facts.CurrentSenseBufferHighAddr = ioc_init.SenseBufferHighAddr;
2505
2506         dhsprintk((MYIOC_s_INFO_FMT "Sending IOCInit (req @ %p)\n",
2507                         ioc->name, &ioc_init));
2508
2509         r = mpt_handshake_req_reply_wait(ioc, sizeof(IOCInit_t), (u32*)&ioc_init,
2510                                 sizeof(MPIDefaultReply_t), (u16*)&init_reply, 10 /*seconds*/, sleepFlag);
2511         if (r != 0)
2512                 return r;
2513
2514         /* No need to byte swap the multibyte fields in the reply
2515          * since we don't even look at it's contents.
2516          */
2517
2518         dhsprintk((MYIOC_s_INFO_FMT "Sending PortEnable (req @ %p)\n",
2519                         ioc->name, &ioc_init));
2520         
2521         if ((r = SendPortEnable(ioc, 0, sleepFlag)) != 0)
2522                 return r;
2523
2524         /* YIKES!  SUPER IMPORTANT!!!
2525          *  Poll IocState until _OPERATIONAL while IOC is doing
2526          *  LoopInit and TargetDiscovery!
2527          */
2528         count = 0;
2529         cntdn = ((sleepFlag == CAN_SLEEP) ? HZ : 1000) * 60;    /* 60 seconds */
2530         state = mpt_GetIocState(ioc, 1);
2531         while (state != MPI_IOC_STATE_OPERATIONAL && --cntdn) {
2532                 if (sleepFlag == CAN_SLEEP) {
2533                         msleep_interruptible(1);
2534                 } else {
2535                         mdelay(1);
2536                 }
2537
2538                 if (!cntdn) {
2539                         printk(MYIOC_s_ERR_FMT "Wait IOC_OP state timeout(%d)!\n",
2540                                         ioc->name, (int)((count+5)/HZ));
2541                         return -9;
2542                 }
2543
2544                 state = mpt_GetIocState(ioc, 1);
2545                 count++;
2546         }
2547         dhsprintk((MYIOC_s_INFO_FMT "INFO - Wait IOC_OPERATIONAL state (cnt=%d)\n",
2548                         ioc->name, count));
2549
2550         return r;
2551 }
2552
2553 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2554 /*
2555  *      SendPortEnable - Send PortEnable request to MPT adapter port.
2556  *      @ioc: Pointer to MPT_ADAPTER structure
2557  *      @portnum: Port number to enable
2558  *      @sleepFlag: Specifies whether the process can sleep
2559  *
2560  *      Send PortEnable to bring IOC to OPERATIONAL state.
2561  *
2562  *      Returns 0 for success, non-zero for failure.
2563  */
2564 static int
2565 SendPortEnable(MPT_ADAPTER *ioc, int portnum, int sleepFlag)
2566 {
2567         PortEnable_t             port_enable;
2568         MPIDefaultReply_t        reply_buf;
2569         int      ii;
2570         int      req_sz;
2571         int      reply_sz;
2572
2573         /*  Destination...  */
2574         reply_sz = sizeof(MPIDefaultReply_t);
2575         memset(&reply_buf, 0, reply_sz);
2576
2577         req_sz = sizeof(PortEnable_t);
2578         memset(&port_enable, 0, req_sz);
2579
2580         port_enable.Function = MPI_FUNCTION_PORT_ENABLE;
2581         port_enable.PortNumber = portnum;
2582 /*      port_enable.ChainOffset = 0;            */
2583 /*      port_enable.MsgFlags = 0;               */
2584 /*      port_enable.MsgContext = 0;             */
2585
2586         dinitprintk((MYIOC_s_INFO_FMT "Sending Port(%d)Enable (req @ %p)\n",
2587                         ioc->name, portnum, &port_enable));
2588
2589         /* RAID FW may take a long time to enable
2590          */
2591         if (ioc->bus_type == FC) {
2592                 ii = mpt_handshake_req_reply_wait(ioc, req_sz, (u32*)&port_enable,
2593                                 reply_sz, (u16*)&reply_buf, 65 /*seconds*/, sleepFlag);
2594         } else {
2595                 ii = mpt_handshake_req_reply_wait(ioc, req_sz, (u32*)&port_enable,
2596                                 reply_sz, (u16*)&reply_buf, 300 /*seconds*/, sleepFlag);
2597         }
2598
2599         if (ii != 0)
2600                 return ii;
2601
2602         /* We do not even look at the reply, so we need not
2603          * swap the multi-byte fields.
2604          */
2605
2606         return 0;
2607 }
2608
2609 /*
2610  *      ioc: Pointer to MPT_ADAPTER structure
2611  *      size - total FW bytes
2612  */
2613 void
2614 mpt_alloc_fw_memory(MPT_ADAPTER *ioc, int size)
2615 {
2616         if (ioc->cached_fw)
2617                 return;  /* use already allocated memory */
2618         if (ioc->alt_ioc && ioc->alt_ioc->cached_fw) {
2619                 ioc->cached_fw = ioc->alt_ioc->cached_fw;  /* use alt_ioc's memory */
2620                 ioc->cached_fw_dma = ioc->alt_ioc->cached_fw_dma;
2621         } else {
2622                 if ( (ioc->cached_fw = pci_alloc_consistent(ioc->pcidev, size, &ioc->cached_fw_dma) ) )
2623                         ioc->alloc_total += size;
2624         }
2625 }
2626 /*
2627  * If alt_img is NULL, delete from ioc structure.
2628  * Else, delete a secondary image in same format.
2629  */
2630 void
2631 mpt_free_fw_memory(MPT_ADAPTER *ioc)
2632 {
2633         int sz;
2634
2635         sz = ioc->facts.FWImageSize;
2636         dinitprintk((KERN_WARNING MYNAM "free_fw_memory: FW Image  @ %p[%p], sz=%d[%x] bytes\n",
2637                  ioc->cached_fw, (void *)(ulong)ioc->cached_fw_dma, sz, sz));
2638         pci_free_consistent(ioc->pcidev, sz,
2639                         ioc->cached_fw, ioc->cached_fw_dma);
2640         ioc->cached_fw = NULL;
2641
2642         return;
2643 }
2644
2645
2646 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2647 /*
2648  *      mpt_do_upload - Construct and Send FWUpload request to MPT adapter port.
2649  *      @ioc: Pointer to MPT_ADAPTER structure
2650  *      @sleepFlag: Specifies whether the process can sleep
2651  *
2652  *      Returns 0 for success, >0 for handshake failure
2653  *              <0 for fw upload failure.
2654  *
2655  *      Remark: If bound IOC and a successful FWUpload was performed
2656  *      on the bound IOC, the second image is discarded
2657  *      and memory is free'd. Both channels must upload to prevent
2658  *      IOC from running in degraded mode.
2659  */
2660 static int
2661 mpt_do_upload(MPT_ADAPTER *ioc, int sleepFlag)
2662 {
2663         u8                       request[ioc->req_sz];
2664         u8                       reply[sizeof(FWUploadReply_t)];
2665         FWUpload_t              *prequest;
2666         FWUploadReply_t         *preply;
2667         FWUploadTCSGE_t         *ptcsge;
2668         int                      sgeoffset;
2669         u32                      flagsLength;
2670         int                      ii, sz, reply_sz;
2671         int                      cmdStatus;
2672
2673         /* If the image size is 0, we are done.
2674          */
2675         if ((sz = ioc->facts.FWImageSize) == 0)
2676                 return 0;
2677
2678         mpt_alloc_fw_memory(ioc, sz);
2679
2680         dinitprintk((KERN_WARNING MYNAM ": FW Image  @ %p[%p], sz=%d[%x] bytes\n",
2681                  ioc->cached_fw, (void *)(ulong)ioc->cached_fw_dma, sz, sz));
2682         
2683         if (ioc->cached_fw == NULL) {
2684                 /* Major Failure.
2685                  */
2686                 return -ENOMEM;
2687         }
2688
2689         prequest = (FWUpload_t *)&request;
2690         preply = (FWUploadReply_t *)&reply;
2691
2692         /*  Destination...  */
2693         memset(prequest, 0, ioc->req_sz);
2694
2695         reply_sz = sizeof(reply);
2696         memset(preply, 0, reply_sz);
2697
2698         prequest->ImageType = MPI_FW_UPLOAD_ITYPE_FW_IOC_MEM;
2699         prequest->Function = MPI_FUNCTION_FW_UPLOAD;
2700
2701         ptcsge = (FWUploadTCSGE_t *) &prequest->SGL;
2702         ptcsge->DetailsLength = 12;
2703         ptcsge->Flags = MPI_SGE_FLAGS_TRANSACTION_ELEMENT;
2704         ptcsge->ImageSize = cpu_to_le32(sz);
2705
2706         sgeoffset = sizeof(FWUpload_t) - sizeof(SGE_MPI_UNION) + sizeof(FWUploadTCSGE_t);
2707
2708         flagsLength = MPT_SGE_FLAGS_SSIMPLE_READ | sz;
2709         mpt_add_sge(&request[sgeoffset], flagsLength, ioc->cached_fw_dma);
2710
2711         sgeoffset += sizeof(u32) + sizeof(dma_addr_t);
2712         dinitprintk((KERN_WARNING MYNAM "Sending FW Upload (req @ %p) sgeoffset=%d \n",
2713                         prequest, sgeoffset));
2714         DBG_DUMP_FW_REQUEST_FRAME(prequest)
2715
2716         ii = mpt_handshake_req_reply_wait(ioc, sgeoffset, (u32*)prequest,
2717                                 reply_sz, (u16*)preply, 65 /*seconds*/, sleepFlag);
2718
2719         dinitprintk((KERN_WARNING MYNAM "FW Upload completed rc=%x \n", ii));
2720
2721         cmdStatus = -EFAULT;
2722         if (ii == 0) {
2723                 /* Handshake transfer was complete and successful.
2724                  * Check the Reply Frame.
2725                  */
2726                 int status, transfer_sz;
2727                 status = le16_to_cpu(preply->IOCStatus);
2728                 if (status == MPI_IOCSTATUS_SUCCESS) {
2729                         transfer_sz = le32_to_cpu(preply->ActualImageSize);
2730                         if (transfer_sz == sz)
2731                                 cmdStatus = 0;
2732                 }
2733         }
2734         dinitprintk((MYIOC_s_INFO_FMT ": do_upload status %d \n",
2735                         ioc->name, cmdStatus));
2736
2737         
2738         if (cmdStatus) {
2739
2740                 ddlprintk((MYIOC_s_INFO_FMT ": fw upload failed, freeing image \n",
2741                         ioc->name));
2742                 mpt_free_fw_memory(ioc);
2743         }
2744
2745         return cmdStatus;
2746 }
2747
2748 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2749 /*
2750  *      mpt_downloadboot - DownloadBoot code
2751  *      @ioc: Pointer to MPT_ADAPTER structure
2752  *      @flag: Specify which part of IOC memory is to be uploaded.
2753  *      @sleepFlag: Specifies whether the process can sleep
2754  *
2755  *      FwDownloadBoot requires Programmed IO access.
2756  *
2757  *      Returns 0 for success
2758  *              -1 FW Image size is 0
2759  *              -2 No valid cached_fw Pointer
2760  *              <0 for fw upload failure.
2761  */
2762 static int
2763 mpt_downloadboot(MPT_ADAPTER *ioc, int sleepFlag)
2764 {
2765         MpiFwHeader_t           *pFwHeader;
2766         MpiExtImageHeader_t     *pExtImage;
2767         u32                      fwSize;
2768         u32                      diag0val;
2769         int                      count;
2770         u32                     *ptrFw;
2771         u32                      diagRwData;
2772         u32                      nextImage;
2773         u32                      load_addr;
2774         u32                      ioc_state=0;
2775
2776         ddlprintk((MYIOC_s_INFO_FMT "downloadboot: fw size 0x%x, ioc FW Ptr %p\n",
2777                                 ioc->name, ioc->facts.FWImageSize, ioc->cached_fw));
2778
2779         if ( ioc->facts.FWImageSize == 0 )
2780                 return -1;
2781
2782         if (ioc->cached_fw == NULL)
2783                 return -2;
2784
2785         /* prevent a second downloadboot and memory free with alt_ioc */
2786         if (ioc->alt_ioc && ioc->alt_ioc->cached_fw)
2787                 ioc->alt_ioc->cached_fw = NULL;
2788         
2789         CHIPREG_WRITE32(&ioc->chip->WriteSequence, 0xFF);
2790         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_1ST_KEY_VALUE);
2791         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_2ND_KEY_VALUE);
2792         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_3RD_KEY_VALUE);
2793         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_4TH_KEY_VALUE);
2794         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_5TH_KEY_VALUE);
2795
2796         CHIPREG_WRITE32(&ioc->chip->Diagnostic, (MPI_DIAG_PREVENT_IOC_BOOT | MPI_DIAG_DISABLE_ARM));
2797
2798         /* wait 1 msec */
2799         if (sleepFlag == CAN_SLEEP) {
2800                 msleep_interruptible(1);
2801         } else {
2802                 mdelay (1);
2803         }
2804
2805         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
2806         CHIPREG_WRITE32(&ioc->chip->Diagnostic, diag0val | MPI_DIAG_RESET_ADAPTER);
2807
2808         for (count = 0; count < 30; count ++) {
2809                 diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
2810                 if (!(diag0val & MPI_DIAG_RESET_ADAPTER)) {
2811                         ddlprintk((MYIOC_s_INFO_FMT "RESET_ADAPTER cleared, count=%d\n",
2812                                 ioc->name, count));
2813                         break;
2814                 }
2815                 /* wait 1 sec */
2816                 if (sleepFlag == CAN_SLEEP) {
2817                         msleep_interruptible (1000);
2818                 } else {
2819                         mdelay (1000);
2820                 }
2821         }
2822
2823         if ( count == 30 ) {
2824                 ddlprintk((MYIOC_s_INFO_FMT "downloadboot failed! Unable to RESET_ADAPTER diag0val=%x\n",
2825                 ioc->name, diag0val));
2826                 return -3;
2827         }
2828
2829         CHIPREG_WRITE32(&ioc->chip->WriteSequence, 0xFF);
2830         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_1ST_KEY_VALUE);
2831         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_2ND_KEY_VALUE);
2832         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_3RD_KEY_VALUE);
2833         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_4TH_KEY_VALUE);
2834         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_5TH_KEY_VALUE);
2835
2836         /* Set the DiagRwEn and Disable ARM bits */
2837         CHIPREG_WRITE32(&ioc->chip->Diagnostic, (MPI_DIAG_RW_ENABLE | MPI_DIAG_DISABLE_ARM));
2838
2839         pFwHeader = (MpiFwHeader_t *) ioc->cached_fw;
2840         fwSize = (pFwHeader->ImageSize + 3)/4;
2841         ptrFw = (u32 *) pFwHeader;
2842
2843         /* Write the LoadStartAddress to the DiagRw Address Register
2844          * using Programmed IO
2845          */
2846         CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwAddress, pFwHeader->LoadStartAddress);
2847         ddlprintk((MYIOC_s_INFO_FMT "LoadStart addr written 0x%x \n",
2848                 ioc->name, pFwHeader->LoadStartAddress));
2849
2850         ddlprintk((MYIOC_s_INFO_FMT "Write FW Image: 0x%x bytes @ %p\n",
2851                                 ioc->name, fwSize*4, ptrFw));
2852         while (fwSize--) {
2853                 CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwData, *ptrFw++);
2854         }
2855
2856         nextImage = pFwHeader->NextImageHeaderOffset;
2857         while (nextImage) {
2858                 pExtImage = (MpiExtImageHeader_t *) ((char *)pFwHeader + nextImage);
2859
2860                 load_addr = pExtImage->LoadStartAddress;
2861
2862                 fwSize = (pExtImage->ImageSize + 3) >> 2;
2863                 ptrFw = (u32 *)pExtImage;
2864
2865                 ddlprintk((MYIOC_s_INFO_FMT "Write Ext Image: 0x%x bytes @ %p load_addr=%x\n",
2866                                                 ioc->name, fwSize*4, ptrFw, load_addr));
2867                 CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwAddress, load_addr);
2868
2869                 while (fwSize--) {
2870                         CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwData, *ptrFw++);
2871                 }
2872                 nextImage = pExtImage->NextImageHeaderOffset;
2873         }
2874
2875         /* Write the IopResetVectorRegAddr */
2876         ddlprintk((MYIOC_s_INFO_FMT "Write IopResetVector Addr=%x! \n", ioc->name,      pFwHeader->IopResetRegAddr));
2877         CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwAddress, pFwHeader->IopResetRegAddr);
2878
2879         /* Write the IopResetVectorValue */
2880         ddlprintk((MYIOC_s_INFO_FMT "Write IopResetVector Value=%x! \n", ioc->name, pFwHeader->IopResetVectorValue));
2881         CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwData, pFwHeader->IopResetVectorValue);
2882
2883         /* Clear the internal flash bad bit - autoincrementing register,
2884          * so must do two writes.
2885          */
2886         CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwAddress, 0x3F000000);
2887         diagRwData = CHIPREG_PIO_READ32(&ioc->pio_chip->DiagRwData);
2888         diagRwData |= 0x4000000;
2889         CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwAddress, 0x3F000000);
2890         CHIPREG_PIO_WRITE32(&ioc->pio_chip->DiagRwData, diagRwData);
2891
2892         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
2893         ddlprintk((MYIOC_s_INFO_FMT "downloadboot diag0val=%x, turning off PREVENT_IOC_BOOT, DISABLE_ARM\n",
2894                 ioc->name, diag0val));
2895         diag0val &= ~(MPI_DIAG_PREVENT_IOC_BOOT | MPI_DIAG_DISABLE_ARM);
2896         ddlprintk((MYIOC_s_INFO_FMT "downloadboot now diag0val=%x\n",
2897                 ioc->name, diag0val));
2898         CHIPREG_WRITE32(&ioc->chip->Diagnostic, diag0val);
2899
2900         /* Write 0xFF to reset the sequencer */
2901         CHIPREG_WRITE32(&ioc->chip->WriteSequence, 0xFF);
2902
2903         for (count=0; count<HZ*20; count++) {
2904                 if ((ioc_state = mpt_GetIocState(ioc, 0)) & MPI_IOC_STATE_READY) {
2905                         ddlprintk((MYIOC_s_INFO_FMT "downloadboot successful! (count=%d) IocState=%x\n",
2906                                         ioc->name, count, ioc_state));
2907                         if ((SendIocInit(ioc, sleepFlag)) != 0) {
2908                                 ddlprintk((MYIOC_s_INFO_FMT "downloadboot: SendIocInit failed\n",
2909                                         ioc->name));
2910                                 return -EFAULT;
2911                         }
2912                         ddlprintk((MYIOC_s_INFO_FMT "downloadboot: SendIocInit successful\n",
2913                                         ioc->name));
2914                         return 0;
2915                 }
2916                 if (sleepFlag == CAN_SLEEP) {
2917                         msleep_interruptible (10);
2918                 } else {
2919                         mdelay (10);
2920                 }
2921         }
2922         ddlprintk((MYIOC_s_INFO_FMT "downloadboot failed! IocState=%x\n",
2923                 ioc->name, ioc_state));
2924         return -EFAULT;
2925 }
2926
2927 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
2928 /*
2929  *      KickStart - Perform hard reset of MPT adapter.
2930  *      @ioc: Pointer to MPT_ADAPTER structure
2931  *      @force: Force hard reset
2932  *      @sleepFlag: Specifies whether the process can sleep
2933  *
2934  *      This routine places MPT adapter in diagnostic mode via the
2935  *      WriteSequence register, and then performs a hard reset of adapter
2936  *      via the Diagnostic register.
2937  *
2938  *      Inputs:   sleepflag - CAN_SLEEP (non-interrupt thread)
2939  *                      or NO_SLEEP (interrupt thread, use mdelay)
2940  *                force - 1 if doorbell active, board fault state
2941  *                              board operational, IOC_RECOVERY or
2942  *                              IOC_BRINGUP and there is an alt_ioc.
2943  *                        0 else
2944  *
2945  *      Returns:
2946  *               1 - hard reset, READY  
2947  *               0 - no reset due to History bit, READY 
2948  *              -1 - no reset due to History bit but not READY  
2949  *                   OR reset but failed to come READY
2950  *              -2 - no reset, could not enter DIAG mode
2951  *              -3 - reset but bad FW bit
2952  */
2953 static int
2954 KickStart(MPT_ADAPTER *ioc, int force, int sleepFlag)
2955 {
2956         int hard_reset_done = 0;
2957         u32 ioc_state=0;
2958         int cnt,cntdn;
2959
2960         dinitprintk((KERN_WARNING MYNAM ": KickStarting %s!\n", ioc->name));
2961         if (ioc->bus_type == SCSI) {
2962                 /* Always issue a Msg Unit Reset first. This will clear some
2963                  * SCSI bus hang conditions.
2964                  */
2965                 SendIocReset(ioc, MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET, sleepFlag);
2966
2967                 if (sleepFlag == CAN_SLEEP) {
2968                         msleep_interruptible (1000);
2969                 } else {
2970                         mdelay (1000);
2971                 }
2972         }
2973
2974         hard_reset_done = mpt_diag_reset(ioc, force, sleepFlag);
2975         if (hard_reset_done < 0)
2976                 return hard_reset_done;
2977
2978         dinitprintk((MYIOC_s_INFO_FMT "Diagnostic reset successful!\n",
2979                         ioc->name));
2980
2981         cntdn = ((sleepFlag == CAN_SLEEP) ? HZ : 1000) * 2;     /* 2 seconds */
2982         for (cnt=0; cnt<cntdn; cnt++) {
2983                 ioc_state = mpt_GetIocState(ioc, 1);
2984                 if ((ioc_state == MPI_IOC_STATE_READY) || (ioc_state == MPI_IOC_STATE_OPERATIONAL)) {
2985                         dinitprintk((MYIOC_s_INFO_FMT "KickStart successful! (cnt=%d)\n",
2986                                         ioc->name, cnt));
2987                         return hard_reset_done;
2988                 }
2989                 if (sleepFlag == CAN_SLEEP) {
2990                         msleep_interruptible (10);
2991                 } else {
2992                         mdelay (10);
2993                 }
2994         }
2995
2996         printk(MYIOC_s_ERR_FMT "Failed to come READY after reset! IocState=%x\n",
2997                         ioc->name, ioc_state);
2998         return -1;
2999 }
3000
3001 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
3002 /*
3003  *      mpt_diag_reset - Perform hard reset of the adapter.
3004  *      @ioc: Pointer to MPT_ADAPTER structure
3005  *      @ignore: Set if to honor and clear to ignore
3006  *              the reset history bit
3007  *      @sleepflag: CAN_SLEEP if called in a non-interrupt thread,
3008  *              else set to NO_SLEEP (use mdelay instead)
3009  *
3010  *      This routine places the adapter in diagnostic mode via the
3011  *      WriteSequence register and then performs a hard reset of adapter
3012  *      via the Diagnostic register. Adapter should be in ready state
3013  *      upon successful completion.
3014  *
3015  *      Returns:  1  hard reset successful
3016  *                0  no reset performed because reset history bit set
3017  *               -2  enabling diagnostic mode failed
3018  *               -3  diagnostic reset failed
3019  */
3020 static int
3021 mpt_diag_reset(MPT_ADAPTER *ioc, int ignore, int sleepFlag)
3022 {
3023         u32 diag0val;
3024         u32 doorbell;
3025         int hard_reset_done = 0;
3026         int count = 0;
3027 #ifdef MPT_DEBUG
3028         u32 diag1val = 0;
3029 #endif
3030
3031         /* Clear any existing interrupts */
3032         CHIPREG_WRITE32(&ioc->chip->IntStatus, 0);
3033
3034         /* Use "Diagnostic reset" method! (only thing available!) */
3035         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3036
3037 #ifdef MPT_DEBUG
3038         if (ioc->alt_ioc)
3039                 diag1val = CHIPREG_READ32(&ioc->alt_ioc->chip->Diagnostic);
3040         dprintk((MYIOC_s_INFO_FMT "DbG1: diag0=%08x, diag1=%08x\n",
3041                         ioc->name, diag0val, diag1val));
3042 #endif
3043
3044         /* Do the reset if we are told to ignore the reset history
3045          * or if the reset history is 0
3046          */
3047         if (ignore || !(diag0val & MPI_DIAG_RESET_HISTORY)) {
3048                 while ((diag0val & MPI_DIAG_DRWE) == 0) {
3049                         /* Write magic sequence to WriteSequence register
3050                          * Loop until in diagnostic mode
3051                          */
3052                         CHIPREG_WRITE32(&ioc->chip->WriteSequence, 0xFF);
3053                         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_1ST_KEY_VALUE);
3054                         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_2ND_KEY_VALUE);
3055                         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_3RD_KEY_VALUE);
3056                         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_4TH_KEY_VALUE);
3057                         CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_5TH_KEY_VALUE);
3058
3059                         /* wait 100 msec */
3060                         if (sleepFlag == CAN_SLEEP) {
3061                                 msleep_interruptible (100);
3062                         } else {
3063                                 mdelay (100);
3064                         }
3065
3066                         count++;
3067                         if (count > 20) {
3068                                 printk(MYIOC_s_ERR_FMT "Enable Diagnostic mode FAILED! (%02xh)\n",
3069                                                 ioc->name, diag0val);
3070                                 return -2;
3071
3072                         }
3073
3074                         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3075
3076                         dprintk((MYIOC_s_INFO_FMT "Wrote magic DiagWriteEn sequence (%x)\n",
3077                                         ioc->name, diag0val));
3078                 }
3079
3080 #ifdef MPT_DEBUG
3081                 if (ioc->alt_ioc)
3082                         diag1val = CHIPREG_READ32(&ioc->alt_ioc->chip->Diagnostic);
3083                 dprintk((MYIOC_s_INFO_FMT "DbG2: diag0=%08x, diag1=%08x\n",
3084                                 ioc->name, diag0val, diag1val));
3085 #endif
3086                 /*
3087                  * Disable the ARM (Bug fix)
3088                  *
3089                  */
3090                 CHIPREG_WRITE32(&ioc->chip->Diagnostic, diag0val | MPI_DIAG_DISABLE_ARM);
3091                 mdelay (1);
3092
3093                 /*
3094                  * Now hit the reset bit in the Diagnostic register
3095                  * (THE BIG HAMMER!) (Clears DRWE bit).
3096                  */
3097                 CHIPREG_WRITE32(&ioc->chip->Diagnostic, diag0val | MPI_DIAG_RESET_ADAPTER);
3098                 hard_reset_done = 1;
3099                 dprintk((MYIOC_s_INFO_FMT "Diagnostic reset performed\n",
3100                                 ioc->name));
3101
3102                 /*
3103                  * Call each currently registered protocol IOC reset handler
3104                  * with pre-reset indication.
3105                  * NOTE: If we're doing _IOC_BRINGUP, there can be no
3106                  * MptResetHandlers[] registered yet.
3107                  */
3108                 {
3109                         int      ii;
3110                         int      r = 0;
3111
3112                         for (ii=MPT_MAX_PROTOCOL_DRIVERS-1; ii; ii--) {
3113                                 if (MptResetHandlers[ii]) {
3114                                         dprintk((MYIOC_s_INFO_FMT "Calling IOC pre_reset handler #%d\n",
3115                                                         ioc->name, ii));
3116                                         r += (*(MptResetHandlers[ii]))(ioc, MPT_IOC_PRE_RESET);
3117                                         if (ioc->alt_ioc) {
3118                                                 dprintk((MYIOC_s_INFO_FMT "Calling alt-%s pre_reset handler #%d\n",
3119                                                                 ioc->name, ioc->alt_ioc->name, ii));
3120                                                 r += (*(MptResetHandlers[ii]))(ioc->alt_ioc, MPT_IOC_PRE_RESET);
3121                                         }
3122                                 }
3123                         }
3124                         /* FIXME?  Examine results here? */
3125                 }
3126
3127                 if (ioc->cached_fw) {
3128                         /* If the DownloadBoot operation fails, the
3129                          * IOC will be left unusable. This is a fatal error
3130                          * case.  _diag_reset will return < 0
3131                          */
3132                         for (count = 0; count < 30; count ++) {
3133                                 diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3134                                 if (!(diag0val & MPI_DIAG_RESET_ADAPTER)) {
3135                                         break;
3136                                 }
3137
3138                                 /* wait 1 sec */
3139                                 if (sleepFlag == CAN_SLEEP) {
3140                                         ssleep(1);
3141                                 } else {
3142                                         mdelay (1000);
3143                                 }
3144                         }
3145                         if ((count = mpt_downloadboot(ioc, sleepFlag)) < 0) {
3146                                 printk(KERN_WARNING MYNAM
3147                                         ": firmware downloadboot failure (%d)!\n", count);
3148                         }
3149
3150                 } else {
3151                         /* Wait for FW to reload and for board
3152                          * to go to the READY state.
3153                          * Maximum wait is 60 seconds.
3154                          * If fail, no error will check again
3155                          * with calling program.
3156                          */
3157                         for (count = 0; count < 60; count ++) {
3158                                 doorbell = CHIPREG_READ32(&ioc->chip->Doorbell);
3159                                 doorbell &= MPI_IOC_STATE_MASK;
3160
3161                                 if (doorbell == MPI_IOC_STATE_READY) {
3162                                         break;
3163                                 }
3164
3165                                 /* wait 1 sec */
3166                                 if (sleepFlag == CAN_SLEEP) {
3167                                         msleep_interruptible (1000);
3168                                 } else {
3169                                         mdelay (1000);
3170                                 }
3171                         }
3172                 }
3173         }
3174
3175         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3176 #ifdef MPT_DEBUG
3177         if (ioc->alt_ioc)
3178                 diag1val = CHIPREG_READ32(&ioc->alt_ioc->chip->Diagnostic);
3179         dprintk((MYIOC_s_INFO_FMT "DbG3: diag0=%08x, diag1=%08x\n",
3180                 ioc->name, diag0val, diag1val));
3181 #endif
3182
3183         /* Clear RESET_HISTORY bit!  Place board in the
3184          * diagnostic mode to update the diag register.
3185          */
3186         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3187         count = 0;
3188         while ((diag0val & MPI_DIAG_DRWE) == 0) {
3189                 /* Write magic sequence to WriteSequence register
3190                  * Loop until in diagnostic mode
3191                  */
3192                 CHIPREG_WRITE32(&ioc->chip->WriteSequence, 0xFF);
3193                 CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_1ST_KEY_VALUE);
3194                 CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_2ND_KEY_VALUE);
3195                 CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_3RD_KEY_VALUE);
3196                 CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_4TH_KEY_VALUE);
3197                 CHIPREG_WRITE32(&ioc->chip->WriteSequence, MPI_WRSEQ_5TH_KEY_VALUE);
3198
3199                 /* wait 100 msec */
3200                 if (sleepFlag == CAN_SLEEP) {
3201                         msleep_interruptible (100);
3202                 } else {
3203                         mdelay (100);
3204                 }
3205
3206                 count++;
3207                 if (count > 20) {
3208                         printk(MYIOC_s_ERR_FMT "Enable Diagnostic mode FAILED! (%02xh)\n",
3209                                         ioc->name, diag0val);
3210                         break;
3211                 }
3212                 diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3213         }
3214         diag0val &= ~MPI_DIAG_RESET_HISTORY;
3215         CHIPREG_WRITE32(&ioc->chip->Diagnostic, diag0val);
3216         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3217         if (diag0val & MPI_DIAG_RESET_HISTORY) {
3218                 printk(MYIOC_s_WARN_FMT "ResetHistory bit failed to clear!\n",
3219                                 ioc->name);
3220         }
3221
3222         /* Disable Diagnostic Mode
3223          */
3224         CHIPREG_WRITE32(&ioc->chip->WriteSequence, 0xFFFFFFFF);
3225
3226         /* Check FW reload status flags.
3227          */
3228         diag0val = CHIPREG_READ32(&ioc->chip->Diagnostic);
3229         if (diag0val & (MPI_DIAG_FLASH_BAD_SIG | MPI_DIAG_RESET_ADAPTER | MPI_DIAG_DISABLE_ARM)) {
3230                 printk(MYIOC_s_ERR_FMT "Diagnostic reset FAILED! (%02xh)\n",
3231                                 ioc->name, diag0val);
3232                 return -3;
3233         }
3234
3235 #ifdef MPT_DEBUG
3236         if (ioc->alt_ioc)
3237                 diag1val = CHIPREG_READ32(&ioc->alt_ioc->chip->Diagnostic);
3238         dprintk((MYIOC_s_INFO_FMT "DbG4: diag0=%08x, diag1=%08x\n",
3239                         ioc->name, diag0val, diag1val));
3240 #endif
3241
3242         /*
3243          * Reset flag that says we've enabled event notification
3244          */
3245         ioc->facts.EventState = 0;
3246
3247         if (ioc->alt_ioc)
3248                 ioc->alt_ioc->facts.EventState = 0;
3249
3250         return hard_reset_done;
3251 }
3252
3253 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
3254 /*
3255  *      SendIocReset - Send IOCReset request to MPT adapter.
3256  *      @ioc: Pointer to MPT_ADAPTER structure
3257  *      @reset_type: reset type, expected values are
3258  *      %MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET or %MPI_FUNCTION_IO_UNIT_RESET
3259  *
3260  *      Send IOCReset request to the MPT adapter.
3261  *
3262  *      Returns 0 for success, non-zero for failure.
3263  */
3264 static int
3265 SendIocReset(MPT_ADAPTER *ioc, u8 reset_type, int sleepFlag)
3266 {
3267         int r;
3268         u32 state;
3269         int cntdn, count;
3270
3271         drsprintk((KERN_WARNING MYNAM ": %s: Sending IOC reset(0x%02x)!\n",
3272                         ioc->name, reset_type));
3273         CHIPREG_WRITE32(&ioc->chip->Doorbell, reset_type<<MPI_DOORBELL_FUNCTION_SHIFT);
3274         if ((r = WaitForDoorbellAck(ioc, 5, sleepFlag)) < 0)
3275                 return r;
3276
3277         /* FW ACK'd request, wait for READY state
3278          */
3279         count = 0;
3280         cntdn = ((sleepFlag == CAN_SLEEP) ? HZ : 1000) * 15;    /* 15 seconds */
3281
3282         while ((state = mpt_GetIocState(ioc, 1)) != MPI_IOC_STATE_READY) {
3283                 cntdn--;
3284                 count++;
3285                 if (!cntdn) {
3286                         if (sleepFlag != CAN_SLEEP)
3287                                 count *= 10;
3288
3289                         printk(KERN_ERR MYNAM ": %s: ERROR - Wait IOC_READY state timeout(%d)!\n",
3290                                         ioc->name, (int)((count+5)/HZ));
3291                         return -ETIME;
3292                 }
3293
3294                 if (sleepFlag == CAN_SLEEP) {
3295                         msleep_interruptible(1);
3296                 } else {
3297                         mdelay (1);     /* 1 msec delay */
3298                 }
3299         }
3300
3301         /* TODO!
3302          *  Cleanup all event stuff for this IOC; re-issue EventNotification
3303          *  request if needed.
3304          */
3305         if (ioc->facts.Function)
3306                 ioc->facts.EventState = 0;
3307
3308         return 0;
3309 }
3310
3311 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
3312 /*
3313  *      initChainBuffers - Allocate memory for and initialize
3314  *      chain buffers, chain buffer control arrays and spinlock.
3315  *      @hd: Pointer to MPT_SCSI_HOST structure
3316  *      @init: If set, initialize the spin lock.
3317  */
3318 static int
3319 initChainBuffers(MPT_ADAPTER *ioc)
3320 {
3321         u8              *mem;
3322         int             sz, ii, num_chain;
3323         int             scale, num_sge, numSGE;
3324
3325         /* ReqToChain size must equal the req_depth
3326          * index = req_idx
3327          */
3328         if (ioc->ReqToChain == NULL) {
3329                 sz = ioc->req_depth * sizeof(int);
3330                 mem = kmalloc(sz, GFP_ATOMIC);
3331                 if (mem == NULL)
3332                         return -1;
3333
3334                 ioc->ReqToChain = (int *) mem;
3335                 dinitprintk((KERN_INFO MYNAM ": %s ReqToChain alloc  @ %p, sz=%d bytes\n",
3336                                 ioc->name, mem, sz));
3337                 mem = kmalloc(sz, GFP_ATOMIC);
3338                 if (mem == NULL)
3339                         return -1;
3340
3341                 ioc->RequestNB = (int *) mem;
3342                 dinitprintk((KERN_INFO MYNAM ": %s RequestNB alloc  @ %p, sz=%d bytes\n",
3343                                 ioc->name, mem, sz));
3344         }
3345         for (ii = 0; ii < ioc->req_depth; ii++) {
3346                 ioc->ReqToChain[ii] = MPT_HOST_NO_CHAIN;
3347         }
3348
3349         /* ChainToChain size must equal the total number
3350          * of chain buffers to be allocated.
3351          * index = chain_idx
3352          *
3353          * Calculate the number of chain buffers needed(plus 1) per I/O
3354          * then multiply the the maximum number of simultaneous cmds
3355          *
3356          * num_sge = num sge in request frame + last chain buffer
3357          * scale = num sge per chain buffer if no chain element
3358          */
3359         scale = ioc->req_sz/(sizeof(dma_addr_t) + sizeof(u32));
3360         if (sizeof(dma_addr_t) == sizeof(u64))
3361                 num_sge =  scale + (ioc->req_sz - 60) / (sizeof(dma_addr_t) + sizeof(u32));
3362         else
3363                 num_sge =  1+ scale + (ioc->req_sz - 64) / (sizeof(dma_addr_t) + sizeof(u32));
3364
3365         if (sizeof(dma_addr_t) == sizeof(u64)) {
3366                 numSGE = (scale - 1) * (ioc->facts.MaxChainDepth-1) + scale +
3367                         (ioc->req_sz - 60) / (sizeof(dma_addr_t) + sizeof(u32));
3368         } else {
3369                 numSGE = 1 + (scale - 1) * (ioc->facts.MaxChainDepth-1) + scale +
3370                         (ioc->req_sz - 64) / (sizeof(dma_addr_t) + sizeof(u32));
3371         }
3372         dinitprintk((KERN_INFO MYNAM ": %s num_sge=%d numSGE=%d\n",
3373                 ioc->name, num_sge, numSGE));
3374
3375         if ( numSGE > MPT_SCSI_SG_DEPTH )
3376                 numSGE = MPT_SCSI_SG_DEPTH;
3377
3378         num_chain = 1;
3379         while (numSGE - num_sge > 0) {
3380                 num_chain++;
3381                 num_sge += (scale - 1);
3382         }
3383         num_chain++;
3384
3385         dinitprintk((KERN_INFO MYNAM ": %s Now numSGE=%d num_sge=%d num_chain=%d\n",
3386                 ioc->name, numSGE, num_sge, num_chain));
3387
3388         if (ioc->bus_type == SCSI)
3389                 num_chain *= MPT_SCSI_CAN_QUEUE;
3390         else
3391                 num_chain *= MPT_FC_CAN_QUEUE;
3392
3393         ioc->num_chain = num_chain;
3394
3395         sz = num_chain * sizeof(int);
3396         if (ioc->ChainToChain == NULL) {
3397                 mem = kmalloc(sz, GFP_ATOMIC);
3398                 if (mem == NULL)
3399                         return -1;
3400
3401                 ioc->ChainToChain = (int *) mem;
3402                 dinitprintk((KERN_INFO MYNAM ": %s ChainToChain alloc @ %p, sz=%d bytes\n",
3403                                 ioc->name, mem, sz));
3404         } else {
3405                 mem = (u8 *) ioc->ChainToChain;
3406         }
3407         memset(mem, 0xFF, sz);
3408         return num_chain;
3409 }
3410
3411 /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
3412 /*
3413  *      PrimeIocFifos - Initialize IOC request and reply FIFOs.
3414  *      @ioc: Pointer to MPT_ADAPTER structure
3415  *
3416  *      This routine allocates memory for the MPT reply and request frame
3417  *      pools (if necessary), and primes the IOC reply FIFO with
3418  *      reply frames.
3419  *
3420  *      Returns 0 for success, non-zero for failure.
3421  */
3422 static int
3423 PrimeIocFifos(MPT_ADAPTER *ioc)
3424 {
3425         MPT_FRAME_HDR *mf;
3426         unsigned long flags;
3427         dma_addr_t alloc_dma;
3428         u8 *mem;
3429         int i, reply_sz, sz, total_size, num_chain;
3430
3431         /*  Prime reply FIFO...  */
3432
3433         if (ioc->reply_frames == NULL) {
3434                 if ( (num_chain = initChainBuffers(ioc)) < 0)
3435                         return -1;
3436
3437                 total_size = reply_sz = (ioc->reply_sz * ioc->reply_depth);
3438                 dinitprintk((KERN_INFO MYNAM ": %s.ReplyBuffer sz=%d bytes, ReplyDepth=%d\n",
3439                                 ioc->name, ioc->reply_sz, ioc->reply_depth));
3440                 dinitprintk((KERN_INFO MYNAM ": %s.ReplyBuffer sz=%d[%x] bytes\n",
3441                                 ioc->name, reply_sz, reply_sz));
3442
3443                 sz = (ioc->req_sz * ioc->req_depth);
3444                 dinitprintk((KERN_INFO MYNAM ": %s.RequestBuffer sz=%d bytes, RequestDepth=%d\n",
3445                                 ioc->name, ioc->req_sz, ioc->req_depth));
3446                 dinitprintk((KERN_INFO MYNAM ": %s.RequestBuffer sz=%d[%x] bytes\n",
3447                                 ioc->name, sz, sz));
3448                 total_size += sz;
3449
3450                 sz = num_chain * ioc->req_sz; /* chain buffer pool size */
3451                 dinitprintk((KERN_INFO MYNAM ": %s.ChainBuffer sz=%d bytes, ChainDepth=%d\n",
3452                                 ioc->name, ioc->req_sz, num_chain));
3453                 dinitprintk((KERN_INFO MYNAM ": %s.ChainBuffer sz=%d[%x] bytes num_chain=%d\n",
3454                                 ioc->name, sz, sz, num_chain));
3455
3456                 total_size += sz;
3457                 mem = pci_alloc_consistent(ioc->pcidev, total_size, &alloc_dma);
3458                 if (mem == NULL) {
3459                         printk(MYIOC_s_ERR_FMT "Unable to allocate Reply, Request, Chain Buffers!\n",
3460                                 ioc->name);
3461                         goto out_fail;
3462                 }
3463
3464                 dinitprintk((KERN_INFO MYNAM ": %s.Total alloc @ %p[%p], sz=%d[%x] bytes\n",
3465                                 ioc->name, mem, (void *)(ulong)alloc_dma, total_size, total_size));
3466
3467                 memset(mem, 0, total_size);
3468                 ioc->alloc_total += total_size;
3469                 ioc->alloc = mem;
3470                 ioc->alloc_dma = alloc_dma;
3471                 ioc->alloc_sz = total_size;
3472                 ioc->reply_frames = (MPT_FRAME_HDR *) mem;
3473                 ioc->reply_frames_low_dma = (u32) (alloc_dma & 0xFFFFFFFF);
3474
3475                 alloc_dma += reply_sz;
3476                 mem += reply_sz;
3477
3478                 /*  Request FIFO - WE manage this!  */
3479
3480                 ioc->req_frames = (MPT_FRAME_HDR *) mem;
3481                 ioc->req_frames_dma = alloc_dma;
3482
3483                 dinitprintk((KERN_INFO MYNAM ": %s.RequestBuffers @ %p[%p]\n",
3484                                 ioc->name, mem, (void *)(ulong)alloc_dma));
3485
3486                 ioc->req_frames_low_dma = (u32) (alloc_dma & 0xFFFFFFFF);
3487
3488 #if defined(CONFIG_MTRR) && 0
3489                 /*
3490                  *  Enable Write Combining MTRR for IOC's memory region.
3491                  *  (at least as much as we can; "size and base must be
3492                  *  multiples of 4 kiB"
3493                  */
3494                 ioc->mtrr_reg = mtrr_add(ioc->req_frames_dma,
3495                                          sz,
3496                                          MTRR_TYPE_WRCOMB, 1);
3497                 dprintk((MYIOC_s_INFO_FMT "MTRR region registered (base:size=%08x:%x)\n",
3498                                 ioc->name, ioc->req_frames_dma, sz));
3499 #endif
3500
3501                 for (i = 0; i < ioc->req_depth; i++) {
3502                         alloc_dma += ioc->req_sz;
3503                         mem += ioc->req_sz;
3504                 }
3505
3506                 ioc->ChainBuffer = mem;
3507                 ioc->ChainBufferDMA = alloc_dma;
3508
3509                 dinitprintk((KERN_INFO MYNAM " :%s.ChainBuffers @ %p(%p)\n",
3510                         ioc->name, ioc->ChainBuffer, (void *)(ulong)ioc->ChainBufferDMA));
3511
3512                 /* Initialize the free chain Q.
3513                 */
3514
3515                 INIT_LIST_HEAD(&ioc->FreeChainQ);
3516
3517                 /* Post the chain buffers to the FreeChainQ.
3518                 */
3519                 mem = (u8 *)ioc->ChainBuffer;
3520                 for (i=0; i < num_chain; i++) {
3521                         mf = (MPT_FRAME_HDR *) mem;
3522                         list_add_tail(&mf->u.frame.linkage.list, &ioc->FreeChainQ);
3523                         mem += ioc->req_sz;
3524                 }
3525
3526                 /* Initialize Request frames linked list