pandora: defconfig: update
[pandora-kernel.git] / drivers / scsi / isci / host.c
1 /*
2  * This file is provided under a dual BSD/GPLv2 license.  When using or
3  * redistributing this file, you may do so under either license.
4  *
5  * GPL LICENSE SUMMARY
6  *
7  * Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of version 2 of the GNU General Public License as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
21  * The full GNU General Public License is included in this distribution
22  * in the file called LICENSE.GPL.
23  *
24  * BSD LICENSE
25  *
26  * Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
27  * All rights reserved.
28  *
29  * Redistribution and use in source and binary forms, with or without
30  * modification, are permitted provided that the following conditions
31  * are met:
32  *
33  *   * Redistributions of source code must retain the above copyright
34  *     notice, this list of conditions and the following disclaimer.
35  *   * Redistributions in binary form must reproduce the above copyright
36  *     notice, this list of conditions and the following disclaimer in
37  *     the documentation and/or other materials provided with the
38  *     distribution.
39  *   * Neither the name of Intel Corporation nor the names of its
40  *     contributors may be used to endorse or promote products derived
41  *     from this software without specific prior written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
44  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
45  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
46  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
47  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
48  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
49  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
50  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
51  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
52  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
53  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
54  */
55 #include <linux/circ_buf.h>
56 #include <linux/device.h>
57 #include <scsi/sas.h>
58 #include "host.h"
59 #include "isci.h"
60 #include "port.h"
61 #include "host.h"
62 #include "probe_roms.h"
63 #include "remote_device.h"
64 #include "request.h"
65 #include "scu_completion_codes.h"
66 #include "scu_event_codes.h"
67 #include "registers.h"
68 #include "scu_remote_node_context.h"
69 #include "scu_task_context.h"
70
71 #define SCU_CONTEXT_RAM_INIT_STALL_TIME      200
72
73 #define smu_max_ports(dcc_value) \
74         (\
75                 (((dcc_value) & SMU_DEVICE_CONTEXT_CAPACITY_MAX_LP_MASK) \
76                  >> SMU_DEVICE_CONTEXT_CAPACITY_MAX_LP_SHIFT) + 1 \
77         )
78
79 #define smu_max_task_contexts(dcc_value)        \
80         (\
81                 (((dcc_value) & SMU_DEVICE_CONTEXT_CAPACITY_MAX_TC_MASK) \
82                  >> SMU_DEVICE_CONTEXT_CAPACITY_MAX_TC_SHIFT) + 1 \
83         )
84
85 #define smu_max_rncs(dcc_value) \
86         (\
87                 (((dcc_value) & SMU_DEVICE_CONTEXT_CAPACITY_MAX_RNC_MASK) \
88                  >> SMU_DEVICE_CONTEXT_CAPACITY_MAX_RNC_SHIFT) + 1 \
89         )
90
91 #define SCIC_SDS_CONTROLLER_PHY_START_TIMEOUT      100
92
93 /**
94  *
95  *
96  * The number of milliseconds to wait while a given phy is consuming power
97  * before allowing another set of phys to consume power. Ultimately, this will
98  * be specified by OEM parameter.
99  */
100 #define SCIC_SDS_CONTROLLER_POWER_CONTROL_INTERVAL 500
101
102 /**
103  * NORMALIZE_PUT_POINTER() -
104  *
105  * This macro will normalize the completion queue put pointer so its value can
106  * be used as an array inde
107  */
108 #define NORMALIZE_PUT_POINTER(x) \
109         ((x) & SMU_COMPLETION_QUEUE_PUT_POINTER_MASK)
110
111
112 /**
113  * NORMALIZE_EVENT_POINTER() -
114  *
115  * This macro will normalize the completion queue event entry so its value can
116  * be used as an index.
117  */
118 #define NORMALIZE_EVENT_POINTER(x) \
119         (\
120                 ((x) & SMU_COMPLETION_QUEUE_GET_EVENT_POINTER_MASK) \
121                 >> SMU_COMPLETION_QUEUE_GET_EVENT_POINTER_SHIFT \
122         )
123
124 /**
125  * NORMALIZE_GET_POINTER() -
126  *
127  * This macro will normalize the completion queue get pointer so its value can
128  * be used as an index into an array
129  */
130 #define NORMALIZE_GET_POINTER(x) \
131         ((x) & SMU_COMPLETION_QUEUE_GET_POINTER_MASK)
132
133 /**
134  * NORMALIZE_GET_POINTER_CYCLE_BIT() -
135  *
136  * This macro will normalize the completion queue cycle pointer so it matches
137  * the completion queue cycle bit
138  */
139 #define NORMALIZE_GET_POINTER_CYCLE_BIT(x) \
140         ((SMU_CQGR_CYCLE_BIT & (x)) << (31 - SMU_COMPLETION_QUEUE_GET_CYCLE_BIT_SHIFT))
141
142 /**
143  * COMPLETION_QUEUE_CYCLE_BIT() -
144  *
145  * This macro will return the cycle bit of the completion queue entry
146  */
147 #define COMPLETION_QUEUE_CYCLE_BIT(x) ((x) & 0x80000000)
148
149 /* Init the state machine and call the state entry function (if any) */
150 void sci_init_sm(struct sci_base_state_machine *sm,
151                  const struct sci_base_state *state_table, u32 initial_state)
152 {
153         sci_state_transition_t handler;
154
155         sm->initial_state_id    = initial_state;
156         sm->previous_state_id   = initial_state;
157         sm->current_state_id    = initial_state;
158         sm->state_table         = state_table;
159
160         handler = sm->state_table[initial_state].enter_state;
161         if (handler)
162                 handler(sm);
163 }
164
165 /* Call the state exit fn, update the current state, call the state entry fn */
166 void sci_change_state(struct sci_base_state_machine *sm, u32 next_state)
167 {
168         sci_state_transition_t handler;
169
170         handler = sm->state_table[sm->current_state_id].exit_state;
171         if (handler)
172                 handler(sm);
173
174         sm->previous_state_id = sm->current_state_id;
175         sm->current_state_id = next_state;
176
177         handler = sm->state_table[sm->current_state_id].enter_state;
178         if (handler)
179                 handler(sm);
180 }
181
182 static bool sci_controller_completion_queue_has_entries(struct isci_host *ihost)
183 {
184         u32 get_value = ihost->completion_queue_get;
185         u32 get_index = get_value & SMU_COMPLETION_QUEUE_GET_POINTER_MASK;
186
187         if (NORMALIZE_GET_POINTER_CYCLE_BIT(get_value) ==
188             COMPLETION_QUEUE_CYCLE_BIT(ihost->completion_queue[get_index]))
189                 return true;
190
191         return false;
192 }
193
194 static bool sci_controller_isr(struct isci_host *ihost)
195 {
196         if (sci_controller_completion_queue_has_entries(ihost)) {
197                 return true;
198         } else {
199                 /*
200                  * we have a spurious interrupt it could be that we have already
201                  * emptied the completion queue from a previous interrupt */
202                 writel(SMU_ISR_COMPLETION, &ihost->smu_registers->interrupt_status);
203
204                 /*
205                  * There is a race in the hardware that could cause us not to be notified
206                  * of an interrupt completion if we do not take this step.  We will mask
207                  * then unmask the interrupts so if there is another interrupt pending
208                  * the clearing of the interrupt source we get the next interrupt message. */
209                 writel(0xFF000000, &ihost->smu_registers->interrupt_mask);
210                 writel(0, &ihost->smu_registers->interrupt_mask);
211         }
212
213         return false;
214 }
215
216 irqreturn_t isci_msix_isr(int vec, void *data)
217 {
218         struct isci_host *ihost = data;
219
220         if (sci_controller_isr(ihost))
221                 tasklet_schedule(&ihost->completion_tasklet);
222
223         return IRQ_HANDLED;
224 }
225
226 static bool sci_controller_error_isr(struct isci_host *ihost)
227 {
228         u32 interrupt_status;
229
230         interrupt_status =
231                 readl(&ihost->smu_registers->interrupt_status);
232         interrupt_status &= (SMU_ISR_QUEUE_ERROR | SMU_ISR_QUEUE_SUSPEND);
233
234         if (interrupt_status != 0) {
235                 /*
236                  * There is an error interrupt pending so let it through and handle
237                  * in the callback */
238                 return true;
239         }
240
241         /*
242          * There is a race in the hardware that could cause us not to be notified
243          * of an interrupt completion if we do not take this step.  We will mask
244          * then unmask the error interrupts so if there was another interrupt
245          * pending we will be notified.
246          * Could we write the value of (SMU_ISR_QUEUE_ERROR | SMU_ISR_QUEUE_SUSPEND)? */
247         writel(0xff, &ihost->smu_registers->interrupt_mask);
248         writel(0, &ihost->smu_registers->interrupt_mask);
249
250         return false;
251 }
252
253 static void sci_controller_task_completion(struct isci_host *ihost, u32 ent)
254 {
255         u32 index = SCU_GET_COMPLETION_INDEX(ent);
256         struct isci_request *ireq = ihost->reqs[index];
257
258         /* Make sure that we really want to process this IO request */
259         if (test_bit(IREQ_ACTIVE, &ireq->flags) &&
260             ireq->io_tag != SCI_CONTROLLER_INVALID_IO_TAG &&
261             ISCI_TAG_SEQ(ireq->io_tag) == ihost->io_request_sequence[index])
262                 /* Yep this is a valid io request pass it along to the
263                  * io request handler
264                  */
265                 sci_io_request_tc_completion(ireq, ent);
266 }
267
268 static void sci_controller_sdma_completion(struct isci_host *ihost, u32 ent)
269 {
270         u32 index;
271         struct isci_request *ireq;
272         struct isci_remote_device *idev;
273
274         index = SCU_GET_COMPLETION_INDEX(ent);
275
276         switch (scu_get_command_request_type(ent)) {
277         case SCU_CONTEXT_COMMAND_REQUEST_TYPE_POST_TC:
278         case SCU_CONTEXT_COMMAND_REQUEST_TYPE_DUMP_TC:
279                 ireq = ihost->reqs[index];
280                 dev_warn(&ihost->pdev->dev, "%s: %x for io request %p\n",
281                          __func__, ent, ireq);
282                 /* @todo For a post TC operation we need to fail the IO
283                  * request
284                  */
285                 break;
286         case SCU_CONTEXT_COMMAND_REQUEST_TYPE_DUMP_RNC:
287         case SCU_CONTEXT_COMMAND_REQUEST_TYPE_OTHER_RNC:
288         case SCU_CONTEXT_COMMAND_REQUEST_TYPE_POST_RNC:
289                 idev = ihost->device_table[index];
290                 dev_warn(&ihost->pdev->dev, "%s: %x for device %p\n",
291                          __func__, ent, idev);
292                 /* @todo For a port RNC operation we need to fail the
293                  * device
294                  */
295                 break;
296         default:
297                 dev_warn(&ihost->pdev->dev, "%s: unknown completion type %x\n",
298                          __func__, ent);
299                 break;
300         }
301 }
302
303 static void sci_controller_unsolicited_frame(struct isci_host *ihost, u32 ent)
304 {
305         u32 index;
306         u32 frame_index;
307
308         struct scu_unsolicited_frame_header *frame_header;
309         struct isci_phy *iphy;
310         struct isci_remote_device *idev;
311
312         enum sci_status result = SCI_FAILURE;
313
314         frame_index = SCU_GET_FRAME_INDEX(ent);
315
316         frame_header = ihost->uf_control.buffers.array[frame_index].header;
317         ihost->uf_control.buffers.array[frame_index].state = UNSOLICITED_FRAME_IN_USE;
318
319         if (SCU_GET_FRAME_ERROR(ent)) {
320                 /*
321                  * / @todo If the IAF frame or SIGNATURE FIS frame has an error will
322                  * /       this cause a problem? We expect the phy initialization will
323                  * /       fail if there is an error in the frame. */
324                 sci_controller_release_frame(ihost, frame_index);
325                 return;
326         }
327
328         if (frame_header->is_address_frame) {
329                 index = SCU_GET_PROTOCOL_ENGINE_INDEX(ent);
330                 iphy = &ihost->phys[index];
331                 result = sci_phy_frame_handler(iphy, frame_index);
332         } else {
333
334                 index = SCU_GET_COMPLETION_INDEX(ent);
335
336                 if (index == SCIC_SDS_REMOTE_NODE_CONTEXT_INVALID_INDEX) {
337                         /*
338                          * This is a signature fis or a frame from a direct attached SATA
339                          * device that has not yet been created.  In either case forwared
340                          * the frame to the PE and let it take care of the frame data. */
341                         index = SCU_GET_PROTOCOL_ENGINE_INDEX(ent);
342                         iphy = &ihost->phys[index];
343                         result = sci_phy_frame_handler(iphy, frame_index);
344                 } else {
345                         if (index < ihost->remote_node_entries)
346                                 idev = ihost->device_table[index];
347                         else
348                                 idev = NULL;
349
350                         if (idev != NULL)
351                                 result = sci_remote_device_frame_handler(idev, frame_index);
352                         else
353                                 sci_controller_release_frame(ihost, frame_index);
354                 }
355         }
356
357         if (result != SCI_SUCCESS) {
358                 /*
359                  * / @todo Is there any reason to report some additional error message
360                  * /       when we get this failure notifiction? */
361         }
362 }
363
364 static void sci_controller_event_completion(struct isci_host *ihost, u32 ent)
365 {
366         struct isci_remote_device *idev;
367         struct isci_request *ireq;
368         struct isci_phy *iphy;
369         u32 index;
370
371         index = SCU_GET_COMPLETION_INDEX(ent);
372
373         switch (scu_get_event_type(ent)) {
374         case SCU_EVENT_TYPE_SMU_COMMAND_ERROR:
375                 /* / @todo The driver did something wrong and we need to fix the condtion. */
376                 dev_err(&ihost->pdev->dev,
377                         "%s: SCIC Controller 0x%p received SMU command error "
378                         "0x%x\n",
379                         __func__,
380                         ihost,
381                         ent);
382                 break;
383
384         case SCU_EVENT_TYPE_SMU_PCQ_ERROR:
385         case SCU_EVENT_TYPE_SMU_ERROR:
386         case SCU_EVENT_TYPE_FATAL_MEMORY_ERROR:
387                 /*
388                  * / @todo This is a hardware failure and its likely that we want to
389                  * /       reset the controller. */
390                 dev_err(&ihost->pdev->dev,
391                         "%s: SCIC Controller 0x%p received fatal controller "
392                         "event  0x%x\n",
393                         __func__,
394                         ihost,
395                         ent);
396                 break;
397
398         case SCU_EVENT_TYPE_TRANSPORT_ERROR:
399                 ireq = ihost->reqs[index];
400                 sci_io_request_event_handler(ireq, ent);
401                 break;
402
403         case SCU_EVENT_TYPE_PTX_SCHEDULE_EVENT:
404                 switch (scu_get_event_specifier(ent)) {
405                 case SCU_EVENT_SPECIFIC_SMP_RESPONSE_NO_PE:
406                 case SCU_EVENT_SPECIFIC_TASK_TIMEOUT:
407                         ireq = ihost->reqs[index];
408                         if (ireq != NULL)
409                                 sci_io_request_event_handler(ireq, ent);
410                         else
411                                 dev_warn(&ihost->pdev->dev,
412                                          "%s: SCIC Controller 0x%p received "
413                                          "event 0x%x for io request object "
414                                          "that doesnt exist.\n",
415                                          __func__,
416                                          ihost,
417                                          ent);
418
419                         break;
420
421                 case SCU_EVENT_SPECIFIC_IT_NEXUS_TIMEOUT:
422                         idev = ihost->device_table[index];
423                         if (idev != NULL)
424                                 sci_remote_device_event_handler(idev, ent);
425                         else
426                                 dev_warn(&ihost->pdev->dev,
427                                          "%s: SCIC Controller 0x%p received "
428                                          "event 0x%x for remote device object "
429                                          "that doesnt exist.\n",
430                                          __func__,
431                                          ihost,
432                                          ent);
433
434                         break;
435                 }
436                 break;
437
438         case SCU_EVENT_TYPE_BROADCAST_CHANGE:
439         /*
440          * direct the broadcast change event to the phy first and then let
441          * the phy redirect the broadcast change to the port object */
442         case SCU_EVENT_TYPE_ERR_CNT_EVENT:
443         /*
444          * direct error counter event to the phy object since that is where
445          * we get the event notification.  This is a type 4 event. */
446         case SCU_EVENT_TYPE_OSSP_EVENT:
447                 index = SCU_GET_PROTOCOL_ENGINE_INDEX(ent);
448                 iphy = &ihost->phys[index];
449                 sci_phy_event_handler(iphy, ent);
450                 break;
451
452         case SCU_EVENT_TYPE_RNC_SUSPEND_TX:
453         case SCU_EVENT_TYPE_RNC_SUSPEND_TX_RX:
454         case SCU_EVENT_TYPE_RNC_OPS_MISC:
455                 if (index < ihost->remote_node_entries) {
456                         idev = ihost->device_table[index];
457
458                         if (idev != NULL)
459                                 sci_remote_device_event_handler(idev, ent);
460                 } else
461                         dev_err(&ihost->pdev->dev,
462                                 "%s: SCIC Controller 0x%p received event 0x%x "
463                                 "for remote device object 0x%0x that doesnt "
464                                 "exist.\n",
465                                 __func__,
466                                 ihost,
467                                 ent,
468                                 index);
469
470                 break;
471
472         default:
473                 dev_warn(&ihost->pdev->dev,
474                          "%s: SCIC Controller received unknown event code %x\n",
475                          __func__,
476                          ent);
477                 break;
478         }
479 }
480
481 static void sci_controller_process_completions(struct isci_host *ihost)
482 {
483         u32 completion_count = 0;
484         u32 ent;
485         u32 get_index;
486         u32 get_cycle;
487         u32 event_get;
488         u32 event_cycle;
489
490         dev_dbg(&ihost->pdev->dev,
491                 "%s: completion queue begining get:0x%08x\n",
492                 __func__,
493                 ihost->completion_queue_get);
494
495         /* Get the component parts of the completion queue */
496         get_index = NORMALIZE_GET_POINTER(ihost->completion_queue_get);
497         get_cycle = SMU_CQGR_CYCLE_BIT & ihost->completion_queue_get;
498
499         event_get = NORMALIZE_EVENT_POINTER(ihost->completion_queue_get);
500         event_cycle = SMU_CQGR_EVENT_CYCLE_BIT & ihost->completion_queue_get;
501
502         while (
503                 NORMALIZE_GET_POINTER_CYCLE_BIT(get_cycle)
504                 == COMPLETION_QUEUE_CYCLE_BIT(ihost->completion_queue[get_index])
505                 ) {
506                 completion_count++;
507
508                 ent = ihost->completion_queue[get_index];
509
510                 /* increment the get pointer and check for rollover to toggle the cycle bit */
511                 get_cycle ^= ((get_index+1) & SCU_MAX_COMPLETION_QUEUE_ENTRIES) <<
512                              (SMU_COMPLETION_QUEUE_GET_CYCLE_BIT_SHIFT - SCU_MAX_COMPLETION_QUEUE_SHIFT);
513                 get_index = (get_index+1) & (SCU_MAX_COMPLETION_QUEUE_ENTRIES-1);
514
515                 dev_dbg(&ihost->pdev->dev,
516                         "%s: completion queue entry:0x%08x\n",
517                         __func__,
518                         ent);
519
520                 switch (SCU_GET_COMPLETION_TYPE(ent)) {
521                 case SCU_COMPLETION_TYPE_TASK:
522                         sci_controller_task_completion(ihost, ent);
523                         break;
524
525                 case SCU_COMPLETION_TYPE_SDMA:
526                         sci_controller_sdma_completion(ihost, ent);
527                         break;
528
529                 case SCU_COMPLETION_TYPE_UFI:
530                         sci_controller_unsolicited_frame(ihost, ent);
531                         break;
532
533                 case SCU_COMPLETION_TYPE_EVENT:
534                         sci_controller_event_completion(ihost, ent);
535                         break;
536
537                 case SCU_COMPLETION_TYPE_NOTIFY: {
538                         event_cycle ^= ((event_get+1) & SCU_MAX_EVENTS) <<
539                                        (SMU_COMPLETION_QUEUE_GET_EVENT_CYCLE_BIT_SHIFT - SCU_MAX_EVENTS_SHIFT);
540                         event_get = (event_get+1) & (SCU_MAX_EVENTS-1);
541
542                         sci_controller_event_completion(ihost, ent);
543                         break;
544                 }
545                 default:
546                         dev_warn(&ihost->pdev->dev,
547                                  "%s: SCIC Controller received unknown "
548                                  "completion type %x\n",
549                                  __func__,
550                                  ent);
551                         break;
552                 }
553         }
554
555         /* Update the get register if we completed one or more entries */
556         if (completion_count > 0) {
557                 ihost->completion_queue_get =
558                         SMU_CQGR_GEN_BIT(ENABLE) |
559                         SMU_CQGR_GEN_BIT(EVENT_ENABLE) |
560                         event_cycle |
561                         SMU_CQGR_GEN_VAL(EVENT_POINTER, event_get) |
562                         get_cycle |
563                         SMU_CQGR_GEN_VAL(POINTER, get_index);
564
565                 writel(ihost->completion_queue_get,
566                        &ihost->smu_registers->completion_queue_get);
567
568         }
569
570         dev_dbg(&ihost->pdev->dev,
571                 "%s: completion queue ending get:0x%08x\n",
572                 __func__,
573                 ihost->completion_queue_get);
574
575 }
576
577 static void sci_controller_error_handler(struct isci_host *ihost)
578 {
579         u32 interrupt_status;
580
581         interrupt_status =
582                 readl(&ihost->smu_registers->interrupt_status);
583
584         if ((interrupt_status & SMU_ISR_QUEUE_SUSPEND) &&
585             sci_controller_completion_queue_has_entries(ihost)) {
586
587                 sci_controller_process_completions(ihost);
588                 writel(SMU_ISR_QUEUE_SUSPEND, &ihost->smu_registers->interrupt_status);
589         } else {
590                 dev_err(&ihost->pdev->dev, "%s: status: %#x\n", __func__,
591                         interrupt_status);
592
593                 sci_change_state(&ihost->sm, SCIC_FAILED);
594
595                 return;
596         }
597
598         /* If we dont process any completions I am not sure that we want to do this.
599          * We are in the middle of a hardware fault and should probably be reset.
600          */
601         writel(0, &ihost->smu_registers->interrupt_mask);
602 }
603
604 irqreturn_t isci_intx_isr(int vec, void *data)
605 {
606         irqreturn_t ret = IRQ_NONE;
607         struct isci_host *ihost = data;
608
609         if (sci_controller_isr(ihost)) {
610                 writel(SMU_ISR_COMPLETION, &ihost->smu_registers->interrupt_status);
611                 tasklet_schedule(&ihost->completion_tasklet);
612                 ret = IRQ_HANDLED;
613         } else if (sci_controller_error_isr(ihost)) {
614                 spin_lock(&ihost->scic_lock);
615                 sci_controller_error_handler(ihost);
616                 spin_unlock(&ihost->scic_lock);
617                 ret = IRQ_HANDLED;
618         }
619
620         return ret;
621 }
622
623 irqreturn_t isci_error_isr(int vec, void *data)
624 {
625         struct isci_host *ihost = data;
626
627         if (sci_controller_error_isr(ihost))
628                 sci_controller_error_handler(ihost);
629
630         return IRQ_HANDLED;
631 }
632
633 /**
634  * isci_host_start_complete() - This function is called by the core library,
635  *    through the ISCI Module, to indicate controller start status.
636  * @isci_host: This parameter specifies the ISCI host object
637  * @completion_status: This parameter specifies the completion status from the
638  *    core library.
639  *
640  */
641 static void isci_host_start_complete(struct isci_host *ihost, enum sci_status completion_status)
642 {
643         if (completion_status != SCI_SUCCESS)
644                 dev_info(&ihost->pdev->dev,
645                         "controller start timed out, continuing...\n");
646         isci_host_change_state(ihost, isci_ready);
647         clear_bit(IHOST_START_PENDING, &ihost->flags);
648         wake_up(&ihost->eventq);
649 }
650
651 int isci_host_scan_finished(struct Scsi_Host *shost, unsigned long time)
652 {
653         struct isci_host *ihost = SHOST_TO_SAS_HA(shost)->lldd_ha;
654
655         if (test_bit(IHOST_START_PENDING, &ihost->flags))
656                 return 0;
657
658         /* todo: use sas_flush_discovery once it is upstream */
659         scsi_flush_work(shost);
660
661         scsi_flush_work(shost);
662
663         dev_dbg(&ihost->pdev->dev,
664                 "%s: ihost->status = %d, time = %ld\n",
665                  __func__, isci_host_get_state(ihost), time);
666
667         return 1;
668
669 }
670
671 /**
672  * sci_controller_get_suggested_start_timeout() - This method returns the
673  *    suggested sci_controller_start() timeout amount.  The user is free to
674  *    use any timeout value, but this method provides the suggested minimum
675  *    start timeout value.  The returned value is based upon empirical
676  *    information determined as a result of interoperability testing.
677  * @controller: the handle to the controller object for which to return the
678  *    suggested start timeout.
679  *
680  * This method returns the number of milliseconds for the suggested start
681  * operation timeout.
682  */
683 static u32 sci_controller_get_suggested_start_timeout(struct isci_host *ihost)
684 {
685         /* Validate the user supplied parameters. */
686         if (!ihost)
687                 return 0;
688
689         /*
690          * The suggested minimum timeout value for a controller start operation:
691          *
692          *     Signature FIS Timeout
693          *   + Phy Start Timeout
694          *   + Number of Phy Spin Up Intervals
695          *   ---------------------------------
696          *   Number of milliseconds for the controller start operation.
697          *
698          * NOTE: The number of phy spin up intervals will be equivalent
699          *       to the number of phys divided by the number phys allowed
700          *       per interval - 1 (once OEM parameters are supported).
701          *       Currently we assume only 1 phy per interval. */
702
703         return SCIC_SDS_SIGNATURE_FIS_TIMEOUT
704                 + SCIC_SDS_CONTROLLER_PHY_START_TIMEOUT
705                 + ((SCI_MAX_PHYS - 1) * SCIC_SDS_CONTROLLER_POWER_CONTROL_INTERVAL);
706 }
707
708 static void sci_controller_enable_interrupts(struct isci_host *ihost)
709 {
710         BUG_ON(ihost->smu_registers == NULL);
711         writel(0, &ihost->smu_registers->interrupt_mask);
712 }
713
714 void sci_controller_disable_interrupts(struct isci_host *ihost)
715 {
716         BUG_ON(ihost->smu_registers == NULL);
717         writel(0xffffffff, &ihost->smu_registers->interrupt_mask);
718 }
719
720 static void sci_controller_enable_port_task_scheduler(struct isci_host *ihost)
721 {
722         u32 port_task_scheduler_value;
723
724         port_task_scheduler_value =
725                 readl(&ihost->scu_registers->peg0.ptsg.control);
726         port_task_scheduler_value |=
727                 (SCU_PTSGCR_GEN_BIT(ETM_ENABLE) |
728                  SCU_PTSGCR_GEN_BIT(PTSG_ENABLE));
729         writel(port_task_scheduler_value,
730                &ihost->scu_registers->peg0.ptsg.control);
731 }
732
733 static void sci_controller_assign_task_entries(struct isci_host *ihost)
734 {
735         u32 task_assignment;
736
737         /*
738          * Assign all the TCs to function 0
739          * TODO: Do we actually need to read this register to write it back?
740          */
741
742         task_assignment =
743                 readl(&ihost->smu_registers->task_context_assignment[0]);
744
745         task_assignment |= (SMU_TCA_GEN_VAL(STARTING, 0)) |
746                 (SMU_TCA_GEN_VAL(ENDING,  ihost->task_context_entries - 1)) |
747                 (SMU_TCA_GEN_BIT(RANGE_CHECK_ENABLE));
748
749         writel(task_assignment,
750                 &ihost->smu_registers->task_context_assignment[0]);
751
752 }
753
754 static void sci_controller_initialize_completion_queue(struct isci_host *ihost)
755 {
756         u32 index;
757         u32 completion_queue_control_value;
758         u32 completion_queue_get_value;
759         u32 completion_queue_put_value;
760
761         ihost->completion_queue_get = 0;
762
763         completion_queue_control_value =
764                 (SMU_CQC_QUEUE_LIMIT_SET(SCU_MAX_COMPLETION_QUEUE_ENTRIES - 1) |
765                  SMU_CQC_EVENT_LIMIT_SET(SCU_MAX_EVENTS - 1));
766
767         writel(completion_queue_control_value,
768                &ihost->smu_registers->completion_queue_control);
769
770
771         /* Set the completion queue get pointer and enable the queue */
772         completion_queue_get_value = (
773                 (SMU_CQGR_GEN_VAL(POINTER, 0))
774                 | (SMU_CQGR_GEN_VAL(EVENT_POINTER, 0))
775                 | (SMU_CQGR_GEN_BIT(ENABLE))
776                 | (SMU_CQGR_GEN_BIT(EVENT_ENABLE))
777                 );
778
779         writel(completion_queue_get_value,
780                &ihost->smu_registers->completion_queue_get);
781
782         /* Set the completion queue put pointer */
783         completion_queue_put_value = (
784                 (SMU_CQPR_GEN_VAL(POINTER, 0))
785                 | (SMU_CQPR_GEN_VAL(EVENT_POINTER, 0))
786                 );
787
788         writel(completion_queue_put_value,
789                &ihost->smu_registers->completion_queue_put);
790
791         /* Initialize the cycle bit of the completion queue entries */
792         for (index = 0; index < SCU_MAX_COMPLETION_QUEUE_ENTRIES; index++) {
793                 /*
794                  * If get.cycle_bit != completion_queue.cycle_bit
795                  * its not a valid completion queue entry
796                  * so at system start all entries are invalid */
797                 ihost->completion_queue[index] = 0x80000000;
798         }
799 }
800
801 static void sci_controller_initialize_unsolicited_frame_queue(struct isci_host *ihost)
802 {
803         u32 frame_queue_control_value;
804         u32 frame_queue_get_value;
805         u32 frame_queue_put_value;
806
807         /* Write the queue size */
808         frame_queue_control_value =
809                 SCU_UFQC_GEN_VAL(QUEUE_SIZE, SCU_MAX_UNSOLICITED_FRAMES);
810
811         writel(frame_queue_control_value,
812                &ihost->scu_registers->sdma.unsolicited_frame_queue_control);
813
814         /* Setup the get pointer for the unsolicited frame queue */
815         frame_queue_get_value = (
816                 SCU_UFQGP_GEN_VAL(POINTER, 0)
817                 |  SCU_UFQGP_GEN_BIT(ENABLE_BIT)
818                 );
819
820         writel(frame_queue_get_value,
821                &ihost->scu_registers->sdma.unsolicited_frame_get_pointer);
822         /* Setup the put pointer for the unsolicited frame queue */
823         frame_queue_put_value = SCU_UFQPP_GEN_VAL(POINTER, 0);
824         writel(frame_queue_put_value,
825                &ihost->scu_registers->sdma.unsolicited_frame_put_pointer);
826 }
827
828 static void sci_controller_transition_to_ready(struct isci_host *ihost, enum sci_status status)
829 {
830         if (ihost->sm.current_state_id == SCIC_STARTING) {
831                 /*
832                  * We move into the ready state, because some of the phys/ports
833                  * may be up and operational.
834                  */
835                 sci_change_state(&ihost->sm, SCIC_READY);
836
837                 isci_host_start_complete(ihost, status);
838         }
839 }
840
841 static bool is_phy_starting(struct isci_phy *iphy)
842 {
843         enum sci_phy_states state;
844
845         state = iphy->sm.current_state_id;
846         switch (state) {
847         case SCI_PHY_STARTING:
848         case SCI_PHY_SUB_INITIAL:
849         case SCI_PHY_SUB_AWAIT_SAS_SPEED_EN:
850         case SCI_PHY_SUB_AWAIT_IAF_UF:
851         case SCI_PHY_SUB_AWAIT_SAS_POWER:
852         case SCI_PHY_SUB_AWAIT_SATA_POWER:
853         case SCI_PHY_SUB_AWAIT_SATA_PHY_EN:
854         case SCI_PHY_SUB_AWAIT_SATA_SPEED_EN:
855         case SCI_PHY_SUB_AWAIT_SIG_FIS_UF:
856         case SCI_PHY_SUB_FINAL:
857                 return true;
858         default:
859                 return false;
860         }
861 }
862
863 /**
864  * sci_controller_start_next_phy - start phy
865  * @scic: controller
866  *
867  * If all the phys have been started, then attempt to transition the
868  * controller to the READY state and inform the user
869  * (sci_cb_controller_start_complete()).
870  */
871 static enum sci_status sci_controller_start_next_phy(struct isci_host *ihost)
872 {
873         struct sci_oem_params *oem = &ihost->oem_parameters;
874         struct isci_phy *iphy;
875         enum sci_status status;
876
877         status = SCI_SUCCESS;
878
879         if (ihost->phy_startup_timer_pending)
880                 return status;
881
882         if (ihost->next_phy_to_start >= SCI_MAX_PHYS) {
883                 bool is_controller_start_complete = true;
884                 u32 state;
885                 u8 index;
886
887                 for (index = 0; index < SCI_MAX_PHYS; index++) {
888                         iphy = &ihost->phys[index];
889                         state = iphy->sm.current_state_id;
890
891                         if (!phy_get_non_dummy_port(iphy))
892                                 continue;
893
894                         /* The controller start operation is complete iff:
895                          * - all links have been given an opportunity to start
896                          * - have no indication of a connected device
897                          * - have an indication of a connected device and it has
898                          *   finished the link training process.
899                          */
900                         if ((iphy->is_in_link_training == false && state == SCI_PHY_INITIAL) ||
901                             (iphy->is_in_link_training == false && state == SCI_PHY_STOPPED) ||
902                             (iphy->is_in_link_training == true && is_phy_starting(iphy))) {
903                                 is_controller_start_complete = false;
904                                 break;
905                         }
906                 }
907
908                 /*
909                  * The controller has successfully finished the start process.
910                  * Inform the SCI Core user and transition to the READY state. */
911                 if (is_controller_start_complete == true) {
912                         sci_controller_transition_to_ready(ihost, SCI_SUCCESS);
913                         sci_del_timer(&ihost->phy_timer);
914                         ihost->phy_startup_timer_pending = false;
915                 }
916         } else {
917                 iphy = &ihost->phys[ihost->next_phy_to_start];
918
919                 if (oem->controller.mode_type == SCIC_PORT_MANUAL_CONFIGURATION_MODE) {
920                         if (phy_get_non_dummy_port(iphy) == NULL) {
921                                 ihost->next_phy_to_start++;
922
923                                 /* Caution recursion ahead be forwarned
924                                  *
925                                  * The PHY was never added to a PORT in MPC mode
926                                  * so start the next phy in sequence This phy
927                                  * will never go link up and will not draw power
928                                  * the OEM parameters either configured the phy
929                                  * incorrectly for the PORT or it was never
930                                  * assigned to a PORT
931                                  */
932                                 return sci_controller_start_next_phy(ihost);
933                         }
934                 }
935
936                 status = sci_phy_start(iphy);
937
938                 if (status == SCI_SUCCESS) {
939                         sci_mod_timer(&ihost->phy_timer,
940                                       SCIC_SDS_CONTROLLER_PHY_START_TIMEOUT);
941                         ihost->phy_startup_timer_pending = true;
942                 } else {
943                         dev_warn(&ihost->pdev->dev,
944                                  "%s: Controller stop operation failed "
945                                  "to stop phy %d because of status "
946                                  "%d.\n",
947                                  __func__,
948                                  ihost->phys[ihost->next_phy_to_start].phy_index,
949                                  status);
950                 }
951
952                 ihost->next_phy_to_start++;
953         }
954
955         return status;
956 }
957
958 static void phy_startup_timeout(unsigned long data)
959 {
960         struct sci_timer *tmr = (struct sci_timer *)data;
961         struct isci_host *ihost = container_of(tmr, typeof(*ihost), phy_timer);
962         unsigned long flags;
963         enum sci_status status;
964
965         spin_lock_irqsave(&ihost->scic_lock, flags);
966
967         if (tmr->cancel)
968                 goto done;
969
970         ihost->phy_startup_timer_pending = false;
971
972         do {
973                 status = sci_controller_start_next_phy(ihost);
974         } while (status != SCI_SUCCESS);
975
976 done:
977         spin_unlock_irqrestore(&ihost->scic_lock, flags);
978 }
979
980 static u16 isci_tci_active(struct isci_host *ihost)
981 {
982         return CIRC_CNT(ihost->tci_head, ihost->tci_tail, SCI_MAX_IO_REQUESTS);
983 }
984
985 static enum sci_status sci_controller_start(struct isci_host *ihost,
986                                              u32 timeout)
987 {
988         enum sci_status result;
989         u16 index;
990
991         if (ihost->sm.current_state_id != SCIC_INITIALIZED) {
992                 dev_warn(&ihost->pdev->dev,
993                          "SCIC Controller start operation requested in "
994                          "invalid state\n");
995                 return SCI_FAILURE_INVALID_STATE;
996         }
997
998         /* Build the TCi free pool */
999         BUILD_BUG_ON(SCI_MAX_IO_REQUESTS > 1 << sizeof(ihost->tci_pool[0]) * 8);
1000         ihost->tci_head = 0;
1001         ihost->tci_tail = 0;
1002         for (index = 0; index < ihost->task_context_entries; index++)
1003                 isci_tci_free(ihost, index);
1004
1005         /* Build the RNi free pool */
1006         sci_remote_node_table_initialize(&ihost->available_remote_nodes,
1007                                          ihost->remote_node_entries);
1008
1009         /*
1010          * Before anything else lets make sure we will not be
1011          * interrupted by the hardware.
1012          */
1013         sci_controller_disable_interrupts(ihost);
1014
1015         /* Enable the port task scheduler */
1016         sci_controller_enable_port_task_scheduler(ihost);
1017
1018         /* Assign all the task entries to ihost physical function */
1019         sci_controller_assign_task_entries(ihost);
1020
1021         /* Now initialize the completion queue */
1022         sci_controller_initialize_completion_queue(ihost);
1023
1024         /* Initialize the unsolicited frame queue for use */
1025         sci_controller_initialize_unsolicited_frame_queue(ihost);
1026
1027         /* Start all of the ports on this controller */
1028         for (index = 0; index < ihost->logical_port_entries; index++) {
1029                 struct isci_port *iport = &ihost->ports[index];
1030
1031                 result = sci_port_start(iport);
1032                 if (result)
1033                         return result;
1034         }
1035
1036         sci_controller_start_next_phy(ihost);
1037
1038         sci_mod_timer(&ihost->timer, timeout);
1039
1040         sci_change_state(&ihost->sm, SCIC_STARTING);
1041
1042         return SCI_SUCCESS;
1043 }
1044
1045 void isci_host_scan_start(struct Scsi_Host *shost)
1046 {
1047         struct isci_host *ihost = SHOST_TO_SAS_HA(shost)->lldd_ha;
1048         unsigned long tmo = sci_controller_get_suggested_start_timeout(ihost);
1049
1050         set_bit(IHOST_START_PENDING, &ihost->flags);
1051
1052         spin_lock_irq(&ihost->scic_lock);
1053         sci_controller_start(ihost, tmo);
1054         sci_controller_enable_interrupts(ihost);
1055         spin_unlock_irq(&ihost->scic_lock);
1056 }
1057
1058 static void isci_host_stop_complete(struct isci_host *ihost, enum sci_status completion_status)
1059 {
1060         isci_host_change_state(ihost, isci_stopped);
1061         sci_controller_disable_interrupts(ihost);
1062         clear_bit(IHOST_STOP_PENDING, &ihost->flags);
1063         wake_up(&ihost->eventq);
1064 }
1065
1066 static void sci_controller_completion_handler(struct isci_host *ihost)
1067 {
1068         /* Empty out the completion queue */
1069         if (sci_controller_completion_queue_has_entries(ihost))
1070                 sci_controller_process_completions(ihost);
1071
1072         /* Clear the interrupt and enable all interrupts again */
1073         writel(SMU_ISR_COMPLETION, &ihost->smu_registers->interrupt_status);
1074         /* Could we write the value of SMU_ISR_COMPLETION? */
1075         writel(0xFF000000, &ihost->smu_registers->interrupt_mask);
1076         writel(0, &ihost->smu_registers->interrupt_mask);
1077 }
1078
1079 /**
1080  * isci_host_completion_routine() - This function is the delayed service
1081  *    routine that calls the sci core library's completion handler. It's
1082  *    scheduled as a tasklet from the interrupt service routine when interrupts
1083  *    in use, or set as the timeout function in polled mode.
1084  * @data: This parameter specifies the ISCI host object
1085  *
1086  */
1087 static void isci_host_completion_routine(unsigned long data)
1088 {
1089         struct isci_host *ihost = (struct isci_host *)data;
1090         struct list_head    completed_request_list;
1091         struct list_head    errored_request_list;
1092         struct list_head    *current_position;
1093         struct list_head    *next_position;
1094         struct isci_request *request;
1095         struct isci_request *next_request;
1096         struct sas_task     *task;
1097         u16 active;
1098
1099         INIT_LIST_HEAD(&completed_request_list);
1100         INIT_LIST_HEAD(&errored_request_list);
1101
1102         spin_lock_irq(&ihost->scic_lock);
1103
1104         sci_controller_completion_handler(ihost);
1105
1106         /* Take the lists of completed I/Os from the host. */
1107
1108         list_splice_init(&ihost->requests_to_complete,
1109                          &completed_request_list);
1110
1111         /* Take the list of errored I/Os from the host. */
1112         list_splice_init(&ihost->requests_to_errorback,
1113                          &errored_request_list);
1114
1115         spin_unlock_irq(&ihost->scic_lock);
1116
1117         /* Process any completions in the lists. */
1118         list_for_each_safe(current_position, next_position,
1119                            &completed_request_list) {
1120
1121                 request = list_entry(current_position, struct isci_request,
1122                                      completed_node);
1123                 task = isci_request_access_task(request);
1124
1125                 /* Normal notification (task_done) */
1126                 dev_dbg(&ihost->pdev->dev,
1127                         "%s: Normal - request/task = %p/%p\n",
1128                         __func__,
1129                         request,
1130                         task);
1131
1132                 /* Return the task to libsas */
1133                 if (task != NULL) {
1134
1135                         task->lldd_task = NULL;
1136                         if (!(task->task_state_flags & SAS_TASK_STATE_ABORTED)) {
1137
1138                                 /* If the task is already in the abort path,
1139                                 * the task_done callback cannot be called.
1140                                 */
1141                                 task->task_done(task);
1142                         }
1143                 }
1144
1145                 spin_lock_irq(&ihost->scic_lock);
1146                 isci_free_tag(ihost, request->io_tag);
1147                 spin_unlock_irq(&ihost->scic_lock);
1148         }
1149         list_for_each_entry_safe(request, next_request, &errored_request_list,
1150                                  completed_node) {
1151
1152                 task = isci_request_access_task(request);
1153
1154                 /* Use sas_task_abort */
1155                 dev_warn(&ihost->pdev->dev,
1156                          "%s: Error - request/task = %p/%p\n",
1157                          __func__,
1158                          request,
1159                          task);
1160
1161                 if (task != NULL) {
1162
1163                         /* Put the task into the abort path if it's not there
1164                          * already.
1165                          */
1166                         if (!(task->task_state_flags & SAS_TASK_STATE_ABORTED))
1167                                 sas_task_abort(task);
1168
1169                 } else {
1170                         /* This is a case where the request has completed with a
1171                          * status such that it needed further target servicing,
1172                          * but the sas_task reference has already been removed
1173                          * from the request.  Since it was errored, it was not
1174                          * being aborted, so there is nothing to do except free
1175                          * it.
1176                          */
1177
1178                         spin_lock_irq(&ihost->scic_lock);
1179                         /* Remove the request from the remote device's list
1180                         * of pending requests.
1181                         */
1182                         list_del_init(&request->dev_node);
1183                         isci_free_tag(ihost, request->io_tag);
1184                         spin_unlock_irq(&ihost->scic_lock);
1185                 }
1186         }
1187
1188         /* the coalesence timeout doubles at each encoding step, so
1189          * update it based on the ilog2 value of the outstanding requests
1190          */
1191         active = isci_tci_active(ihost);
1192         writel(SMU_ICC_GEN_VAL(NUMBER, active) |
1193                SMU_ICC_GEN_VAL(TIMER, ISCI_COALESCE_BASE + ilog2(active)),
1194                &ihost->smu_registers->interrupt_coalesce_control);
1195 }
1196
1197 /**
1198  * sci_controller_stop() - This method will stop an individual controller
1199  *    object.This method will invoke the associated user callback upon
1200  *    completion.  The completion callback is called when the following
1201  *    conditions are met: -# the method return status is SCI_SUCCESS. -# the
1202  *    controller has been quiesced. This method will ensure that all IO
1203  *    requests are quiesced, phys are stopped, and all additional operation by
1204  *    the hardware is halted.
1205  * @controller: the handle to the controller object to stop.
1206  * @timeout: This parameter specifies the number of milliseconds in which the
1207  *    stop operation should complete.
1208  *
1209  * The controller must be in the STARTED or STOPPED state. Indicate if the
1210  * controller stop method succeeded or failed in some way. SCI_SUCCESS if the
1211  * stop operation successfully began. SCI_WARNING_ALREADY_IN_STATE if the
1212  * controller is already in the STOPPED state. SCI_FAILURE_INVALID_STATE if the
1213  * controller is not either in the STARTED or STOPPED states.
1214  */
1215 static enum sci_status sci_controller_stop(struct isci_host *ihost, u32 timeout)
1216 {
1217         if (ihost->sm.current_state_id != SCIC_READY) {
1218                 dev_warn(&ihost->pdev->dev,
1219                          "SCIC Controller stop operation requested in "
1220                          "invalid state\n");
1221                 return SCI_FAILURE_INVALID_STATE;
1222         }
1223
1224         sci_mod_timer(&ihost->timer, timeout);
1225         sci_change_state(&ihost->sm, SCIC_STOPPING);
1226         return SCI_SUCCESS;
1227 }
1228
1229 /**
1230  * sci_controller_reset() - This method will reset the supplied core
1231  *    controller regardless of the state of said controller.  This operation is
1232  *    considered destructive.  In other words, all current operations are wiped
1233  *    out.  No IO completions for outstanding devices occur.  Outstanding IO
1234  *    requests are not aborted or completed at the actual remote device.
1235  * @controller: the handle to the controller object to reset.
1236  *
1237  * Indicate if the controller reset method succeeded or failed in some way.
1238  * SCI_SUCCESS if the reset operation successfully started. SCI_FATAL_ERROR if
1239  * the controller reset operation is unable to complete.
1240  */
1241 static enum sci_status sci_controller_reset(struct isci_host *ihost)
1242 {
1243         switch (ihost->sm.current_state_id) {
1244         case SCIC_RESET:
1245         case SCIC_READY:
1246         case SCIC_STOPPED:
1247         case SCIC_FAILED:
1248                 /*
1249                  * The reset operation is not a graceful cleanup, just
1250                  * perform the state transition.
1251                  */
1252                 sci_change_state(&ihost->sm, SCIC_RESETTING);
1253                 return SCI_SUCCESS;
1254         default:
1255                 dev_warn(&ihost->pdev->dev,
1256                          "SCIC Controller reset operation requested in "
1257                          "invalid state\n");
1258                 return SCI_FAILURE_INVALID_STATE;
1259         }
1260 }
1261
1262 void isci_host_deinit(struct isci_host *ihost)
1263 {
1264         int i;
1265
1266         /* disable output data selects */
1267         for (i = 0; i < isci_gpio_count(ihost); i++)
1268                 writel(SGPIO_HW_CONTROL, &ihost->scu_registers->peg0.sgpio.output_data_select[i]);
1269
1270         isci_host_change_state(ihost, isci_stopping);
1271         for (i = 0; i < SCI_MAX_PORTS; i++) {
1272                 struct isci_port *iport = &ihost->ports[i];
1273                 struct isci_remote_device *idev, *d;
1274
1275                 list_for_each_entry_safe(idev, d, &iport->remote_dev_list, node) {
1276                         if (test_bit(IDEV_ALLOCATED, &idev->flags))
1277                                 isci_remote_device_stop(ihost, idev);
1278                 }
1279         }
1280
1281         set_bit(IHOST_STOP_PENDING, &ihost->flags);
1282
1283         spin_lock_irq(&ihost->scic_lock);
1284         sci_controller_stop(ihost, SCIC_CONTROLLER_STOP_TIMEOUT);
1285         spin_unlock_irq(&ihost->scic_lock);
1286
1287         wait_for_stop(ihost);
1288
1289         /* disable sgpio: where the above wait should give time for the
1290          * enclosure to sample the gpios going inactive
1291          */
1292         writel(0, &ihost->scu_registers->peg0.sgpio.interface_control);
1293
1294         sci_controller_reset(ihost);
1295
1296         /* Cancel any/all outstanding port timers */
1297         for (i = 0; i < ihost->logical_port_entries; i++) {
1298                 struct isci_port *iport = &ihost->ports[i];
1299                 del_timer_sync(&iport->timer.timer);
1300         }
1301
1302         /* Cancel any/all outstanding phy timers */
1303         for (i = 0; i < SCI_MAX_PHYS; i++) {
1304                 struct isci_phy *iphy = &ihost->phys[i];
1305                 del_timer_sync(&iphy->sata_timer.timer);
1306         }
1307
1308         del_timer_sync(&ihost->port_agent.timer.timer);
1309
1310         del_timer_sync(&ihost->power_control.timer.timer);
1311
1312         del_timer_sync(&ihost->timer.timer);
1313
1314         del_timer_sync(&ihost->phy_timer.timer);
1315 }
1316
1317 static void __iomem *scu_base(struct isci_host *isci_host)
1318 {
1319         struct pci_dev *pdev = isci_host->pdev;
1320         int id = isci_host->id;
1321
1322         return pcim_iomap_table(pdev)[SCI_SCU_BAR * 2] + SCI_SCU_BAR_SIZE * id;
1323 }
1324
1325 static void __iomem *smu_base(struct isci_host *isci_host)
1326 {
1327         struct pci_dev *pdev = isci_host->pdev;
1328         int id = isci_host->id;
1329
1330         return pcim_iomap_table(pdev)[SCI_SMU_BAR * 2] + SCI_SMU_BAR_SIZE * id;
1331 }
1332
1333 static void isci_user_parameters_get(struct sci_user_parameters *u)
1334 {
1335         int i;
1336
1337         for (i = 0; i < SCI_MAX_PHYS; i++) {
1338                 struct sci_phy_user_params *u_phy = &u->phys[i];
1339
1340                 u_phy->max_speed_generation = phy_gen;
1341
1342                 /* we are not exporting these for now */
1343                 u_phy->align_insertion_frequency = 0x7f;
1344                 u_phy->in_connection_align_insertion_frequency = 0xff;
1345                 u_phy->notify_enable_spin_up_insertion_frequency = 0x33;
1346         }
1347
1348         u->stp_inactivity_timeout = stp_inactive_to;
1349         u->ssp_inactivity_timeout = ssp_inactive_to;
1350         u->stp_max_occupancy_timeout = stp_max_occ_to;
1351         u->ssp_max_occupancy_timeout = ssp_max_occ_to;
1352         u->no_outbound_task_timeout = no_outbound_task_to;
1353         u->max_concurr_spinup = max_concurr_spinup;
1354 }
1355
1356 static void sci_controller_initial_state_enter(struct sci_base_state_machine *sm)
1357 {
1358         struct isci_host *ihost = container_of(sm, typeof(*ihost), sm);
1359
1360         sci_change_state(&ihost->sm, SCIC_RESET);
1361 }
1362
1363 static inline void sci_controller_starting_state_exit(struct sci_base_state_machine *sm)
1364 {
1365         struct isci_host *ihost = container_of(sm, typeof(*ihost), sm);
1366
1367         sci_del_timer(&ihost->timer);
1368 }
1369
1370 #define INTERRUPT_COALESCE_TIMEOUT_BASE_RANGE_LOWER_BOUND_NS 853
1371 #define INTERRUPT_COALESCE_TIMEOUT_BASE_RANGE_UPPER_BOUND_NS 1280
1372 #define INTERRUPT_COALESCE_TIMEOUT_MAX_US                    2700000
1373 #define INTERRUPT_COALESCE_NUMBER_MAX                        256
1374 #define INTERRUPT_COALESCE_TIMEOUT_ENCODE_MIN                7
1375 #define INTERRUPT_COALESCE_TIMEOUT_ENCODE_MAX                28
1376
1377 /**
1378  * sci_controller_set_interrupt_coalescence() - This method allows the user to
1379  *    configure the interrupt coalescence.
1380  * @controller: This parameter represents the handle to the controller object
1381  *    for which its interrupt coalesce register is overridden.
1382  * @coalesce_number: Used to control the number of entries in the Completion
1383  *    Queue before an interrupt is generated. If the number of entries exceed
1384  *    this number, an interrupt will be generated. The valid range of the input
1385  *    is [0, 256]. A setting of 0 results in coalescing being disabled.
1386  * @coalesce_timeout: Timeout value in microseconds. The valid range of the
1387  *    input is [0, 2700000] . A setting of 0 is allowed and results in no
1388  *    interrupt coalescing timeout.
1389  *
1390  * Indicate if the user successfully set the interrupt coalesce parameters.
1391  * SCI_SUCCESS The user successfully updated the interrutp coalescence.
1392  * SCI_FAILURE_INVALID_PARAMETER_VALUE The user input value is out of range.
1393  */
1394 static enum sci_status
1395 sci_controller_set_interrupt_coalescence(struct isci_host *ihost,
1396                                          u32 coalesce_number,
1397                                          u32 coalesce_timeout)
1398 {
1399         u8 timeout_encode = 0;
1400         u32 min = 0;
1401         u32 max = 0;
1402
1403         /* Check if the input parameters fall in the range. */
1404         if (coalesce_number > INTERRUPT_COALESCE_NUMBER_MAX)
1405                 return SCI_FAILURE_INVALID_PARAMETER_VALUE;
1406
1407         /*
1408          *  Defined encoding for interrupt coalescing timeout:
1409          *              Value   Min      Max     Units
1410          *              -----   ---      ---     -----
1411          *              0       -        -       Disabled
1412          *              1       13.3     20.0    ns
1413          *              2       26.7     40.0
1414          *              3       53.3     80.0
1415          *              4       106.7    160.0
1416          *              5       213.3    320.0
1417          *              6       426.7    640.0
1418          *              7       853.3    1280.0
1419          *              8       1.7      2.6     us
1420          *              9       3.4      5.1
1421          *              10      6.8      10.2
1422          *              11      13.7     20.5
1423          *              12      27.3     41.0
1424          *              13      54.6     81.9
1425          *              14      109.2    163.8
1426          *              15      218.5    327.7
1427          *              16      436.9    655.4
1428          *              17      873.8    1310.7
1429          *              18      1.7      2.6     ms
1430          *              19      3.5      5.2
1431          *              20      7.0      10.5
1432          *              21      14.0     21.0
1433          *              22      28.0     41.9
1434          *              23      55.9     83.9
1435          *              24      111.8    167.8
1436          *              25      223.7    335.5
1437          *              26      447.4    671.1
1438          *              27      894.8    1342.2
1439          *              28      1.8      2.7     s
1440          *              Others Undefined */
1441
1442         /*
1443          * Use the table above to decide the encode of interrupt coalescing timeout
1444          * value for register writing. */
1445         if (coalesce_timeout == 0)
1446                 timeout_encode = 0;
1447         else{
1448                 /* make the timeout value in unit of (10 ns). */
1449                 coalesce_timeout = coalesce_timeout * 100;
1450                 min = INTERRUPT_COALESCE_TIMEOUT_BASE_RANGE_LOWER_BOUND_NS / 10;
1451                 max = INTERRUPT_COALESCE_TIMEOUT_BASE_RANGE_UPPER_BOUND_NS / 10;
1452
1453                 /* get the encode of timeout for register writing. */
1454                 for (timeout_encode = INTERRUPT_COALESCE_TIMEOUT_ENCODE_MIN;
1455                       timeout_encode <= INTERRUPT_COALESCE_TIMEOUT_ENCODE_MAX;
1456                       timeout_encode++) {
1457                         if (min <= coalesce_timeout &&  max > coalesce_timeout)
1458                                 break;
1459                         else if (coalesce_timeout >= max && coalesce_timeout < min * 2
1460                                  && coalesce_timeout <= INTERRUPT_COALESCE_TIMEOUT_MAX_US * 100) {
1461                                 if ((coalesce_timeout - max) < (2 * min - coalesce_timeout))
1462                                         break;
1463                                 else{
1464                                         timeout_encode++;
1465                                         break;
1466                                 }
1467                         } else {
1468                                 max = max * 2;
1469                                 min = min * 2;
1470                         }
1471                 }
1472
1473                 if (timeout_encode == INTERRUPT_COALESCE_TIMEOUT_ENCODE_MAX + 1)
1474                         /* the value is out of range. */
1475                         return SCI_FAILURE_INVALID_PARAMETER_VALUE;
1476         }
1477
1478         writel(SMU_ICC_GEN_VAL(NUMBER, coalesce_number) |
1479                SMU_ICC_GEN_VAL(TIMER, timeout_encode),
1480                &ihost->smu_registers->interrupt_coalesce_control);
1481
1482
1483         ihost->interrupt_coalesce_number = (u16)coalesce_number;
1484         ihost->interrupt_coalesce_timeout = coalesce_timeout / 100;
1485
1486         return SCI_SUCCESS;
1487 }
1488
1489
1490 static void sci_controller_ready_state_enter(struct sci_base_state_machine *sm)
1491 {
1492         struct isci_host *ihost = container_of(sm, typeof(*ihost), sm);
1493
1494         /* set the default interrupt coalescence number and timeout value. */
1495         sci_controller_set_interrupt_coalescence(ihost, 0, 0);
1496 }
1497
1498 static void sci_controller_ready_state_exit(struct sci_base_state_machine *sm)
1499 {
1500         struct isci_host *ihost = container_of(sm, typeof(*ihost), sm);
1501
1502         /* disable interrupt coalescence. */
1503         sci_controller_set_interrupt_coalescence(ihost, 0, 0);
1504 }
1505
1506 static enum sci_status sci_controller_stop_phys(struct isci_host *ihost)
1507 {
1508         u32 index;
1509         enum sci_status status;
1510         enum sci_status phy_status;
1511
1512         status = SCI_SUCCESS;
1513
1514         for (index = 0; index < SCI_MAX_PHYS; index++) {
1515                 phy_status = sci_phy_stop(&ihost->phys[index]);
1516
1517                 if (phy_status != SCI_SUCCESS &&
1518                     phy_status != SCI_FAILURE_INVALID_STATE) {
1519                         status = SCI_FAILURE;
1520
1521                         dev_warn(&ihost->pdev->dev,
1522                                  "%s: Controller stop operation failed to stop "
1523                                  "phy %d because of status %d.\n",
1524                                  __func__,
1525                                  ihost->phys[index].phy_index, phy_status);
1526                 }
1527         }
1528
1529         return status;
1530 }
1531
1532 static enum sci_status sci_controller_stop_ports(struct isci_host *ihost)
1533 {
1534         u32 index;
1535         enum sci_status port_status;
1536         enum sci_status status = SCI_SUCCESS;
1537
1538         for (index = 0; index < ihost->logical_port_entries; index++) {
1539                 struct isci_port *iport = &ihost->ports[index];
1540
1541                 port_status = sci_port_stop(iport);
1542
1543                 if ((port_status != SCI_SUCCESS) &&
1544                     (port_status != SCI_FAILURE_INVALID_STATE)) {
1545                         status = SCI_FAILURE;
1546
1547                         dev_warn(&ihost->pdev->dev,
1548                                  "%s: Controller stop operation failed to "
1549                                  "stop port %d because of status %d.\n",
1550                                  __func__,
1551                                  iport->logical_port_index,
1552                                  port_status);
1553                 }
1554         }
1555
1556         return status;
1557 }
1558
1559 static enum sci_status sci_controller_stop_devices(struct isci_host *ihost)
1560 {
1561         u32 index;
1562         enum sci_status status;
1563         enum sci_status device_status;
1564
1565         status = SCI_SUCCESS;
1566
1567         for (index = 0; index < ihost->remote_node_entries; index++) {
1568                 if (ihost->device_table[index] != NULL) {
1569                         /* / @todo What timeout value do we want to provide to this request? */
1570                         device_status = sci_remote_device_stop(ihost->device_table[index], 0);
1571
1572                         if ((device_status != SCI_SUCCESS) &&
1573                             (device_status != SCI_FAILURE_INVALID_STATE)) {
1574                                 dev_warn(&ihost->pdev->dev,
1575                                          "%s: Controller stop operation failed "
1576                                          "to stop device 0x%p because of "
1577                                          "status %d.\n",
1578                                          __func__,
1579                                          ihost->device_table[index], device_status);
1580                         }
1581                 }
1582         }
1583
1584         return status;
1585 }
1586
1587 static void sci_controller_stopping_state_enter(struct sci_base_state_machine *sm)
1588 {
1589         struct isci_host *ihost = container_of(sm, typeof(*ihost), sm);
1590
1591         /* Stop all of the components for this controller */
1592         sci_controller_stop_phys(ihost);
1593         sci_controller_stop_ports(ihost);
1594         sci_controller_stop_devices(ihost);
1595 }
1596
1597 static void sci_controller_stopping_state_exit(struct sci_base_state_machine *sm)
1598 {
1599         struct isci_host *ihost = container_of(sm, typeof(*ihost), sm);
1600
1601         sci_del_timer(&ihost->timer);
1602 }
1603
1604 static void sci_controller_reset_hardware(struct isci_host *ihost)
1605 {
1606         /* Disable interrupts so we dont take any spurious interrupts */
1607         sci_controller_disable_interrupts(ihost);
1608
1609         /* Reset the SCU */
1610         writel(0xFFFFFFFF, &ihost->smu_registers->soft_reset_control);
1611
1612         /* Delay for 1ms to before clearing the CQP and UFQPR. */
1613         udelay(1000);
1614
1615         /* The write to the CQGR clears the CQP */
1616         writel(0x00000000, &ihost->smu_registers->completion_queue_get);
1617
1618         /* The write to the UFQGP clears the UFQPR */
1619         writel(0, &ihost->scu_registers->sdma.unsolicited_frame_get_pointer);
1620 }
1621
1622 static void sci_controller_resetting_state_enter(struct sci_base_state_machine *sm)
1623 {
1624         struct isci_host *ihost = container_of(sm, typeof(*ihost), sm);
1625
1626         sci_controller_reset_hardware(ihost);
1627         sci_change_state(&ihost->sm, SCIC_RESET);
1628 }
1629
1630 static const struct sci_base_state sci_controller_state_table[] = {
1631         [SCIC_INITIAL] = {
1632                 .enter_state = sci_controller_initial_state_enter,
1633         },
1634         [SCIC_RESET] = {},
1635         [SCIC_INITIALIZING] = {},
1636         [SCIC_INITIALIZED] = {},
1637         [SCIC_STARTING] = {
1638                 .exit_state  = sci_controller_starting_state_exit,
1639         },
1640         [SCIC_READY] = {
1641                 .enter_state = sci_controller_ready_state_enter,
1642                 .exit_state  = sci_controller_ready_state_exit,
1643         },
1644         [SCIC_RESETTING] = {
1645                 .enter_state = sci_controller_resetting_state_enter,
1646         },
1647         [SCIC_STOPPING] = {
1648                 .enter_state = sci_controller_stopping_state_enter,
1649                 .exit_state = sci_controller_stopping_state_exit,
1650         },
1651         [SCIC_STOPPED] = {},
1652         [SCIC_FAILED] = {}
1653 };
1654
1655 static void sci_controller_set_default_config_parameters(struct isci_host *ihost)
1656 {
1657         /* these defaults are overridden by the platform / firmware */
1658         u16 index;
1659
1660         /* Default to APC mode. */
1661         ihost->oem_parameters.controller.mode_type = SCIC_PORT_AUTOMATIC_CONFIGURATION_MODE;
1662
1663         /* Default to APC mode. */
1664         ihost->oem_parameters.controller.max_concurr_spin_up = 1;
1665
1666         /* Default to no SSC operation. */
1667         ihost->oem_parameters.controller.do_enable_ssc = false;
1668
1669         /* Initialize all of the port parameter information to narrow ports. */
1670         for (index = 0; index < SCI_MAX_PORTS; index++) {
1671                 ihost->oem_parameters.ports[index].phy_mask = 0;
1672         }
1673
1674         /* Initialize all of the phy parameter information. */
1675         for (index = 0; index < SCI_MAX_PHYS; index++) {
1676                 /* Default to 6G (i.e. Gen 3) for now. */
1677                 ihost->user_parameters.phys[index].max_speed_generation = 3;
1678
1679                 /* the frequencies cannot be 0 */
1680                 ihost->user_parameters.phys[index].align_insertion_frequency = 0x7f;
1681                 ihost->user_parameters.phys[index].in_connection_align_insertion_frequency = 0xff;
1682                 ihost->user_parameters.phys[index].notify_enable_spin_up_insertion_frequency = 0x33;
1683
1684                 /*
1685                  * Previous Vitesse based expanders had a arbitration issue that
1686                  * is worked around by having the upper 32-bits of SAS address
1687                  * with a value greater then the Vitesse company identifier.
1688                  * Hence, usage of 0x5FCFFFFF. */
1689                 ihost->oem_parameters.phys[index].sas_address.low = 0x1 + ihost->id;
1690                 ihost->oem_parameters.phys[index].sas_address.high = 0x5FCFFFFF;
1691         }
1692
1693         ihost->user_parameters.stp_inactivity_timeout = 5;
1694         ihost->user_parameters.ssp_inactivity_timeout = 5;
1695         ihost->user_parameters.stp_max_occupancy_timeout = 5;
1696         ihost->user_parameters.ssp_max_occupancy_timeout = 20;
1697         ihost->user_parameters.no_outbound_task_timeout = 20;
1698 }
1699
1700 static void controller_timeout(unsigned long data)
1701 {
1702         struct sci_timer *tmr = (struct sci_timer *)data;
1703         struct isci_host *ihost = container_of(tmr, typeof(*ihost), timer);
1704         struct sci_base_state_machine *sm = &ihost->sm;
1705         unsigned long flags;
1706
1707         spin_lock_irqsave(&ihost->scic_lock, flags);
1708
1709         if (tmr->cancel)
1710                 goto done;
1711
1712         if (sm->current_state_id == SCIC_STARTING)
1713                 sci_controller_transition_to_ready(ihost, SCI_FAILURE_TIMEOUT);
1714         else if (sm->current_state_id == SCIC_STOPPING) {
1715                 sci_change_state(sm, SCIC_FAILED);
1716                 isci_host_stop_complete(ihost, SCI_FAILURE_TIMEOUT);
1717         } else  /* / @todo Now what do we want to do in this case? */
1718                 dev_err(&ihost->pdev->dev,
1719                         "%s: Controller timer fired when controller was not "
1720                         "in a state being timed.\n",
1721                         __func__);
1722
1723 done:
1724         spin_unlock_irqrestore(&ihost->scic_lock, flags);
1725 }
1726
1727 static enum sci_status sci_controller_construct(struct isci_host *ihost,
1728                                                 void __iomem *scu_base,
1729                                                 void __iomem *smu_base)
1730 {
1731         u8 i;
1732
1733         sci_init_sm(&ihost->sm, sci_controller_state_table, SCIC_INITIAL);
1734
1735         ihost->scu_registers = scu_base;
1736         ihost->smu_registers = smu_base;
1737
1738         sci_port_configuration_agent_construct(&ihost->port_agent);
1739
1740         /* Construct the ports for this controller */
1741         for (i = 0; i < SCI_MAX_PORTS; i++)
1742                 sci_port_construct(&ihost->ports[i], i, ihost);
1743         sci_port_construct(&ihost->ports[i], SCIC_SDS_DUMMY_PORT, ihost);
1744
1745         /* Construct the phys for this controller */
1746         for (i = 0; i < SCI_MAX_PHYS; i++) {
1747                 /* Add all the PHYs to the dummy port */
1748                 sci_phy_construct(&ihost->phys[i],
1749                                   &ihost->ports[SCI_MAX_PORTS], i);
1750         }
1751
1752         ihost->invalid_phy_mask = 0;
1753
1754         sci_init_timer(&ihost->timer, controller_timeout);
1755
1756         /* Initialize the User and OEM parameters to default values. */
1757         sci_controller_set_default_config_parameters(ihost);
1758
1759         return sci_controller_reset(ihost);
1760 }
1761
1762 int sci_oem_parameters_validate(struct sci_oem_params *oem)
1763 {
1764         int i;
1765
1766         for (i = 0; i < SCI_MAX_PORTS; i++)
1767                 if (oem->ports[i].phy_mask > SCIC_SDS_PARM_PHY_MASK_MAX)
1768                         return -EINVAL;
1769
1770         for (i = 0; i < SCI_MAX_PHYS; i++)
1771                 if (oem->phys[i].sas_address.high == 0 &&
1772                     oem->phys[i].sas_address.low == 0)
1773                         return -EINVAL;
1774
1775         if (oem->controller.mode_type == SCIC_PORT_AUTOMATIC_CONFIGURATION_MODE) {
1776                 for (i = 0; i < SCI_MAX_PHYS; i++)
1777                         if (oem->ports[i].phy_mask != 0)
1778                                 return -EINVAL;
1779         } else if (oem->controller.mode_type == SCIC_PORT_MANUAL_CONFIGURATION_MODE) {
1780                 u8 phy_mask = 0;
1781
1782                 for (i = 0; i < SCI_MAX_PHYS; i++)
1783                         phy_mask |= oem->ports[i].phy_mask;
1784
1785                 if (phy_mask == 0)
1786                         return -EINVAL;
1787         } else
1788                 return -EINVAL;
1789
1790         if (oem->controller.max_concurr_spin_up > MAX_CONCURRENT_DEVICE_SPIN_UP_COUNT ||
1791             oem->controller.max_concurr_spin_up < 1)
1792                 return -EINVAL;
1793
1794         return 0;
1795 }
1796
1797 static enum sci_status sci_oem_parameters_set(struct isci_host *ihost)
1798 {
1799         u32 state = ihost->sm.current_state_id;
1800
1801         if (state == SCIC_RESET ||
1802             state == SCIC_INITIALIZING ||
1803             state == SCIC_INITIALIZED) {
1804
1805                 if (sci_oem_parameters_validate(&ihost->oem_parameters))
1806                         return SCI_FAILURE_INVALID_PARAMETER_VALUE;
1807
1808                 return SCI_SUCCESS;
1809         }
1810
1811         return SCI_FAILURE_INVALID_STATE;
1812 }
1813
1814 static u8 max_spin_up(struct isci_host *ihost)
1815 {
1816         if (ihost->user_parameters.max_concurr_spinup)
1817                 return min_t(u8, ihost->user_parameters.max_concurr_spinup,
1818                              MAX_CONCURRENT_DEVICE_SPIN_UP_COUNT);
1819         else
1820                 return min_t(u8, ihost->oem_parameters.controller.max_concurr_spin_up,
1821                              MAX_CONCURRENT_DEVICE_SPIN_UP_COUNT);
1822 }
1823
1824 static void power_control_timeout(unsigned long data)
1825 {
1826         struct sci_timer *tmr = (struct sci_timer *)data;
1827         struct isci_host *ihost = container_of(tmr, typeof(*ihost), power_control.timer);
1828         struct isci_phy *iphy;
1829         unsigned long flags;
1830         u8 i;
1831
1832         spin_lock_irqsave(&ihost->scic_lock, flags);
1833
1834         if (tmr->cancel)
1835                 goto done;
1836
1837         ihost->power_control.phys_granted_power = 0;
1838
1839         if (ihost->power_control.phys_waiting == 0) {
1840                 ihost->power_control.timer_started = false;
1841                 goto done;
1842         }
1843
1844         for (i = 0; i < SCI_MAX_PHYS; i++) {
1845
1846                 if (ihost->power_control.phys_waiting == 0)
1847                         break;
1848
1849                 iphy = ihost->power_control.requesters[i];
1850                 if (iphy == NULL)
1851                         continue;
1852
1853                 if (ihost->power_control.phys_granted_power >= max_spin_up(ihost))
1854                         break;
1855
1856                 ihost->power_control.requesters[i] = NULL;
1857                 ihost->power_control.phys_waiting--;
1858                 ihost->power_control.phys_granted_power++;
1859                 sci_phy_consume_power_handler(iphy);
1860         }
1861
1862         /*
1863          * It doesn't matter if the power list is empty, we need to start the
1864          * timer in case another phy becomes ready.
1865          */
1866         sci_mod_timer(tmr, SCIC_SDS_CONTROLLER_POWER_CONTROL_INTERVAL);
1867         ihost->power_control.timer_started = true;
1868
1869 done:
1870         spin_unlock_irqrestore(&ihost->scic_lock, flags);
1871 }
1872
1873 void sci_controller_power_control_queue_insert(struct isci_host *ihost,
1874                                                struct isci_phy *iphy)
1875 {
1876         BUG_ON(iphy == NULL);
1877
1878         if (ihost->power_control.phys_granted_power < max_spin_up(ihost)) {
1879                 ihost->power_control.phys_granted_power++;
1880                 sci_phy_consume_power_handler(iphy);
1881
1882                 /*
1883                  * stop and start the power_control timer. When the timer fires, the
1884                  * no_of_phys_granted_power will be set to 0
1885                  */
1886                 if (ihost->power_control.timer_started)
1887                         sci_del_timer(&ihost->power_control.timer);
1888
1889                 sci_mod_timer(&ihost->power_control.timer,
1890                                  SCIC_SDS_CONTROLLER_POWER_CONTROL_INTERVAL);
1891                 ihost->power_control.timer_started = true;
1892
1893         } else {
1894                 /* Add the phy in the waiting list */
1895                 ihost->power_control.requesters[iphy->phy_index] = iphy;
1896                 ihost->power_control.phys_waiting++;
1897         }
1898 }
1899
1900 void sci_controller_power_control_queue_remove(struct isci_host *ihost,
1901                                                struct isci_phy *iphy)
1902 {
1903         BUG_ON(iphy == NULL);
1904
1905         if (ihost->power_control.requesters[iphy->phy_index])
1906                 ihost->power_control.phys_waiting--;
1907
1908         ihost->power_control.requesters[iphy->phy_index] = NULL;
1909 }
1910
1911 #define AFE_REGISTER_WRITE_DELAY 10
1912
1913 /* Initialize the AFE for this phy index. We need to read the AFE setup from
1914  * the OEM parameters
1915  */
1916 static void sci_controller_afe_initialization(struct isci_host *ihost)
1917 {
1918         const struct sci_oem_params *oem = &ihost->oem_parameters;
1919         struct pci_dev *pdev = ihost->pdev;
1920         u32 afe_status;
1921         u32 phy_id;
1922
1923         /* Clear DFX Status registers */
1924         writel(0x0081000f, &ihost->scu_registers->afe.afe_dfx_master_control0);
1925         udelay(AFE_REGISTER_WRITE_DELAY);
1926
1927         if (is_b0(pdev)) {
1928                 /* PM Rx Equalization Save, PM SPhy Rx Acknowledgement
1929                  * Timer, PM Stagger Timer */
1930                 writel(0x0007BFFF, &ihost->scu_registers->afe.afe_pmsn_master_control2);
1931                 udelay(AFE_REGISTER_WRITE_DELAY);
1932         }
1933
1934         /* Configure bias currents to normal */
1935         if (is_a2(pdev))
1936                 writel(0x00005A00, &ihost->scu_registers->afe.afe_bias_control);
1937         else if (is_b0(pdev) || is_c0(pdev))
1938                 writel(0x00005F00, &ihost->scu_registers->afe.afe_bias_control);
1939
1940         udelay(AFE_REGISTER_WRITE_DELAY);
1941
1942         /* Enable PLL */
1943         if (is_b0(pdev) || is_c0(pdev))
1944                 writel(0x80040A08, &ihost->scu_registers->afe.afe_pll_control0);
1945         else
1946                 writel(0x80040908, &ihost->scu_registers->afe.afe_pll_control0);
1947
1948         udelay(AFE_REGISTER_WRITE_DELAY);
1949
1950         /* Wait for the PLL to lock */
1951         do {
1952                 afe_status = readl(&ihost->scu_registers->afe.afe_common_block_status);
1953                 udelay(AFE_REGISTER_WRITE_DELAY);
1954         } while ((afe_status & 0x00001000) == 0);
1955
1956         if (is_a2(pdev)) {
1957                 /* Shorten SAS SNW lock time (RxLock timer value from 76 us to 50 us) */
1958                 writel(0x7bcc96ad, &ihost->scu_registers->afe.afe_pmsn_master_control0);
1959                 udelay(AFE_REGISTER_WRITE_DELAY);
1960         }
1961
1962         for (phy_id = 0; phy_id < SCI_MAX_PHYS; phy_id++) {
1963                 const struct sci_phy_oem_params *oem_phy = &oem->phys[phy_id];
1964
1965                 if (is_b0(pdev)) {
1966                          /* Configure transmitter SSC parameters */
1967                         writel(0x00030000, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_ssc_control);
1968                         udelay(AFE_REGISTER_WRITE_DELAY);
1969                 } else if (is_c0(pdev)) {
1970                          /* Configure transmitter SSC parameters */
1971                         writel(0x0003000, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_ssc_control);
1972                         udelay(AFE_REGISTER_WRITE_DELAY);
1973
1974                         /*
1975                          * All defaults, except the Receive Word Alignament/Comma Detect
1976                          * Enable....(0xe800) */
1977                         writel(0x00004500, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control0);
1978                         udelay(AFE_REGISTER_WRITE_DELAY);
1979                 } else {
1980                         /*
1981                          * All defaults, except the Receive Word Alignament/Comma Detect
1982                          * Enable....(0xe800) */
1983                         writel(0x00004512, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control0);
1984                         udelay(AFE_REGISTER_WRITE_DELAY);
1985
1986                         writel(0x0050100F, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control1);
1987                         udelay(AFE_REGISTER_WRITE_DELAY);
1988                 }
1989
1990                 /*
1991                  * Power up TX and RX out from power down (PWRDNTX and PWRDNRX)
1992                  * & increase TX int & ext bias 20%....(0xe85c) */
1993                 if (is_a2(pdev))
1994                         writel(0x000003F0, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
1995                 else if (is_b0(pdev)) {
1996                          /* Power down TX and RX (PWRDNTX and PWRDNRX) */
1997                         writel(0x000003D7, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
1998                         udelay(AFE_REGISTER_WRITE_DELAY);
1999
2000                         /*
2001                          * Power up TX and RX out from power down (PWRDNTX and PWRDNRX)
2002                          * & increase TX int & ext bias 20%....(0xe85c) */
2003                         writel(0x000003D4, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2004                 } else {
2005                         writel(0x000001E7, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2006                         udelay(AFE_REGISTER_WRITE_DELAY);
2007
2008                         /*
2009                          * Power up TX and RX out from power down (PWRDNTX and PWRDNRX)
2010                          * & increase TX int & ext bias 20%....(0xe85c) */
2011                         writel(0x000001E4, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2012                 }
2013                 udelay(AFE_REGISTER_WRITE_DELAY);
2014
2015                 if (is_a2(pdev)) {
2016                         /* Enable TX equalization (0xe824) */
2017                         writel(0x00040000, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_control);
2018                         udelay(AFE_REGISTER_WRITE_DELAY);
2019                 }
2020
2021                 /*
2022                  * RDPI=0x0(RX Power On), RXOOBDETPDNC=0x0, TPD=0x0(TX Power On),
2023                  * RDD=0x0(RX Detect Enabled) ....(0xe800) */
2024                 writel(0x00004100, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control0);
2025                 udelay(AFE_REGISTER_WRITE_DELAY);
2026
2027                 /* Leave DFE/FFE on */
2028                 if (is_a2(pdev))
2029                         writel(0x3F11103F, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control0);
2030                 else if (is_b0(pdev)) {
2031                         writel(0x3F11103F, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control0);
2032                         udelay(AFE_REGISTER_WRITE_DELAY);
2033                         /* Enable TX equalization (0xe824) */
2034                         writel(0x00040000, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_control);
2035                 } else {
2036                         writel(0x0140DF0F, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control1);
2037                         udelay(AFE_REGISTER_WRITE_DELAY);
2038
2039                         writel(0x3F6F103F, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control0);
2040                         udelay(AFE_REGISTER_WRITE_DELAY);
2041
2042                         /* Enable TX equalization (0xe824) */
2043                         writel(0x00040000, &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_control);
2044                 }
2045
2046                 udelay(AFE_REGISTER_WRITE_DELAY);
2047
2048                 writel(oem_phy->afe_tx_amp_control0,
2049                         &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control0);
2050                 udelay(AFE_REGISTER_WRITE_DELAY);
2051
2052                 writel(oem_phy->afe_tx_amp_control1,
2053                         &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control1);
2054                 udelay(AFE_REGISTER_WRITE_DELAY);
2055
2056                 writel(oem_phy->afe_tx_amp_control2,
2057                         &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control2);
2058                 udelay(AFE_REGISTER_WRITE_DELAY);
2059
2060                 writel(oem_phy->afe_tx_amp_control3,
2061                         &ihost->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control3);
2062                 udelay(AFE_REGISTER_WRITE_DELAY);
2063         }
2064
2065         /* Transfer control to the PEs */
2066         writel(0x00010f00, &ihost->scu_registers->afe.afe_dfx_master_control0);
2067         udelay(AFE_REGISTER_WRITE_DELAY);
2068 }
2069
2070 static void sci_controller_initialize_power_control(struct isci_host *ihost)
2071 {
2072         sci_init_timer(&ihost->power_control.timer, power_control_timeout);
2073
2074         memset(ihost->power_control.requesters, 0,
2075                sizeof(ihost->power_control.requesters));
2076
2077         ihost->power_control.phys_waiting = 0;
2078         ihost->power_control.phys_granted_power = 0;
2079 }
2080
2081 static enum sci_status sci_controller_initialize(struct isci_host *ihost)
2082 {
2083         struct sci_base_state_machine *sm = &ihost->sm;
2084         enum sci_status result = SCI_FAILURE;
2085         unsigned long i, state, val;
2086
2087         if (ihost->sm.current_state_id != SCIC_RESET) {
2088                 dev_warn(&ihost->pdev->dev,
2089                          "SCIC Controller initialize operation requested "
2090                          "in invalid state\n");
2091                 return SCI_FAILURE_INVALID_STATE;
2092         }
2093
2094         sci_change_state(sm, SCIC_INITIALIZING);
2095
2096         sci_init_timer(&ihost->phy_timer, phy_startup_timeout);
2097
2098         ihost->next_phy_to_start = 0;
2099         ihost->phy_startup_timer_pending = false;
2100
2101         sci_controller_initialize_power_control(ihost);
2102
2103         /*
2104          * There is nothing to do here for B0 since we do not have to
2105          * program the AFE registers.
2106          * / @todo The AFE settings are supposed to be correct for the B0 but
2107          * /       presently they seem to be wrong. */
2108         sci_controller_afe_initialization(ihost);
2109
2110
2111         /* Take the hardware out of reset */
2112         writel(0, &ihost->smu_registers->soft_reset_control);
2113
2114         /*
2115          * / @todo Provide meaningfull error code for hardware failure
2116          * result = SCI_FAILURE_CONTROLLER_HARDWARE; */
2117         for (i = 100; i >= 1; i--) {
2118                 u32 status;
2119
2120                 /* Loop until the hardware reports success */
2121                 udelay(SCU_CONTEXT_RAM_INIT_STALL_TIME);
2122                 status = readl(&ihost->smu_registers->control_status);
2123
2124                 if ((status & SCU_RAM_INIT_COMPLETED) == SCU_RAM_INIT_COMPLETED)
2125                         break;
2126         }
2127         if (i == 0)
2128                 goto out;
2129
2130         /*
2131          * Determine what are the actaul device capacities that the
2132          * hardware will support */
2133         val = readl(&ihost->smu_registers->device_context_capacity);
2134
2135         /* Record the smaller of the two capacity values */
2136         ihost->logical_port_entries = min(smu_max_ports(val), SCI_MAX_PORTS);
2137         ihost->task_context_entries = min(smu_max_task_contexts(val), SCI_MAX_IO_REQUESTS);
2138         ihost->remote_node_entries = min(smu_max_rncs(val), SCI_MAX_REMOTE_DEVICES);
2139
2140         /*
2141          * Make all PEs that are unassigned match up with the
2142          * logical ports
2143          */
2144         for (i = 0; i < ihost->logical_port_entries; i++) {
2145                 struct scu_port_task_scheduler_group_registers __iomem
2146                         *ptsg = &ihost->scu_registers->peg0.ptsg;
2147
2148                 writel(i, &ptsg->protocol_engine[i]);
2149         }
2150
2151         /* Initialize hardware PCI Relaxed ordering in DMA engines */
2152         val = readl(&ihost->scu_registers->sdma.pdma_configuration);
2153         val |= SCU_PDMACR_GEN_BIT(PCI_RELAXED_ORDERING_ENABLE);
2154         writel(val, &ihost->scu_registers->sdma.pdma_configuration);
2155
2156         val = readl(&ihost->scu_registers->sdma.cdma_configuration);
2157         val |= SCU_CDMACR_GEN_BIT(PCI_RELAXED_ORDERING_ENABLE);
2158         writel(val, &ihost->scu_registers->sdma.cdma_configuration);
2159
2160         /*
2161          * Initialize the PHYs before the PORTs because the PHY registers
2162          * are accessed during the port initialization.
2163          */
2164         for (i = 0; i < SCI_MAX_PHYS; i++) {
2165                 result = sci_phy_initialize(&ihost->phys[i],
2166                                             &ihost->scu_registers->peg0.pe[i].tl,
2167                                             &ihost->scu_registers->peg0.pe[i].ll);
2168                 if (result != SCI_SUCCESS)
2169                         goto out;
2170         }
2171
2172         for (i = 0; i < ihost->logical_port_entries; i++) {
2173                 struct isci_port *iport = &ihost->ports[i];
2174
2175                 iport->port_task_scheduler_registers = &ihost->scu_registers->peg0.ptsg.port[i];
2176                 iport->port_pe_configuration_register = &ihost->scu_registers->peg0.ptsg.protocol_engine[0];
2177                 iport->viit_registers = &ihost->scu_registers->peg0.viit[i];
2178         }
2179
2180         result = sci_port_configuration_agent_initialize(ihost, &ihost->port_agent);
2181
2182  out:
2183         /* Advance the controller state machine */
2184         if (result == SCI_SUCCESS)
2185                 state = SCIC_INITIALIZED;
2186         else
2187                 state = SCIC_FAILED;
2188         sci_change_state(sm, state);
2189
2190         return result;
2191 }
2192
2193 static enum sci_status sci_user_parameters_set(struct isci_host *ihost,
2194                                                struct sci_user_parameters *sci_parms)
2195 {
2196         u32 state = ihost->sm.current_state_id;
2197
2198         if (state == SCIC_RESET ||
2199             state == SCIC_INITIALIZING ||
2200             state == SCIC_INITIALIZED) {
2201                 u16 index;
2202
2203                 /*
2204                  * Validate the user parameters.  If they are not legal, then
2205                  * return a failure.
2206                  */
2207                 for (index = 0; index < SCI_MAX_PHYS; index++) {
2208                         struct sci_phy_user_params *user_phy;
2209
2210                         user_phy = &sci_parms->phys[index];
2211
2212                         if (!((user_phy->max_speed_generation <=
2213                                                 SCIC_SDS_PARM_MAX_SPEED) &&
2214                               (user_phy->max_speed_generation >
2215                                                 SCIC_SDS_PARM_NO_SPEED)))
2216                                 return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2217
2218                         if (user_phy->in_connection_align_insertion_frequency <
2219                                         3)
2220                                 return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2221
2222                         if ((user_phy->in_connection_align_insertion_frequency <
2223                                                 3) ||
2224                             (user_phy->align_insertion_frequency == 0) ||
2225                             (user_phy->
2226                                 notify_enable_spin_up_insertion_frequency ==
2227                                                 0))
2228                                 return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2229                 }
2230
2231                 if ((sci_parms->stp_inactivity_timeout == 0) ||
2232                     (sci_parms->ssp_inactivity_timeout == 0) ||
2233                     (sci_parms->stp_max_occupancy_timeout == 0) ||
2234                     (sci_parms->ssp_max_occupancy_timeout == 0) ||
2235                     (sci_parms->no_outbound_task_timeout == 0))
2236                         return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2237
2238                 memcpy(&ihost->user_parameters, sci_parms, sizeof(*sci_parms));
2239
2240                 return SCI_SUCCESS;
2241         }
2242
2243         return SCI_FAILURE_INVALID_STATE;
2244 }
2245
2246 static int sci_controller_mem_init(struct isci_host *ihost)
2247 {
2248         struct device *dev = &ihost->pdev->dev;
2249         dma_addr_t dma;
2250         size_t size;
2251         int err;
2252
2253         size = SCU_MAX_COMPLETION_QUEUE_ENTRIES * sizeof(u32);
2254         ihost->completion_queue = dmam_alloc_coherent(dev, size, &dma, GFP_KERNEL);
2255         if (!ihost->completion_queue)
2256                 return -ENOMEM;
2257
2258         writel(lower_32_bits(dma), &ihost->smu_registers->completion_queue_lower);
2259         writel(upper_32_bits(dma), &ihost->smu_registers->completion_queue_upper);
2260
2261         size = ihost->remote_node_entries * sizeof(union scu_remote_node_context);
2262         ihost->remote_node_context_table = dmam_alloc_coherent(dev, size, &dma,
2263                                                                GFP_KERNEL);
2264         if (!ihost->remote_node_context_table)
2265                 return -ENOMEM;
2266
2267         writel(lower_32_bits(dma), &ihost->smu_registers->remote_node_context_lower);
2268         writel(upper_32_bits(dma), &ihost->smu_registers->remote_node_context_upper);
2269
2270         size = ihost->task_context_entries * sizeof(struct scu_task_context),
2271         ihost->task_context_table = dmam_alloc_coherent(dev, size, &dma, GFP_KERNEL);
2272         if (!ihost->task_context_table)
2273                 return -ENOMEM;
2274
2275         ihost->task_context_dma = dma;
2276         writel(lower_32_bits(dma), &ihost->smu_registers->host_task_table_lower);
2277         writel(upper_32_bits(dma), &ihost->smu_registers->host_task_table_upper);
2278
2279         err = sci_unsolicited_frame_control_construct(ihost);
2280         if (err)
2281                 return err;
2282
2283         /*
2284          * Inform the silicon as to the location of the UF headers and
2285          * address table.
2286          */
2287         writel(lower_32_bits(ihost->uf_control.headers.physical_address),
2288                 &ihost->scu_registers->sdma.uf_header_base_address_lower);
2289         writel(upper_32_bits(ihost->uf_control.headers.physical_address),
2290                 &ihost->scu_registers->sdma.uf_header_base_address_upper);
2291
2292         writel(lower_32_bits(ihost->uf_control.address_table.physical_address),
2293                 &ihost->scu_registers->sdma.uf_address_table_lower);
2294         writel(upper_32_bits(ihost->uf_control.address_table.physical_address),
2295                 &ihost->scu_registers->sdma.uf_address_table_upper);
2296
2297         return 0;
2298 }
2299
2300 int isci_host_init(struct isci_host *ihost)
2301 {
2302         int err = 0, i;
2303         enum sci_status status;
2304         struct sci_user_parameters sci_user_params;
2305         struct isci_pci_info *pci_info = to_pci_info(ihost->pdev);
2306
2307         spin_lock_init(&ihost->state_lock);
2308         spin_lock_init(&ihost->scic_lock);
2309         init_waitqueue_head(&ihost->eventq);
2310
2311         isci_host_change_state(ihost, isci_starting);
2312
2313         status = sci_controller_construct(ihost, scu_base(ihost),
2314                                           smu_base(ihost));
2315
2316         if (status != SCI_SUCCESS) {
2317                 dev_err(&ihost->pdev->dev,
2318                         "%s: sci_controller_construct failed - status = %x\n",
2319                         __func__,
2320                         status);
2321                 return -ENODEV;
2322         }
2323
2324         ihost->sas_ha.dev = &ihost->pdev->dev;
2325         ihost->sas_ha.lldd_ha = ihost;
2326
2327         /*
2328          * grab initial values stored in the controller object for OEM and USER
2329          * parameters
2330          */
2331         isci_user_parameters_get(&sci_user_params);
2332         status = sci_user_parameters_set(ihost, &sci_user_params);
2333         if (status != SCI_SUCCESS) {
2334                 dev_warn(&ihost->pdev->dev,
2335                          "%s: sci_user_parameters_set failed\n",
2336                          __func__);
2337                 return -ENODEV;
2338         }
2339
2340         /* grab any OEM parameters specified in orom */
2341         if (pci_info->orom) {
2342                 status = isci_parse_oem_parameters(&ihost->oem_parameters,
2343                                                    pci_info->orom,
2344                                                    ihost->id);
2345                 if (status != SCI_SUCCESS) {
2346                         dev_warn(&ihost->pdev->dev,
2347                                  "parsing firmware oem parameters failed\n");
2348                         return -EINVAL;
2349                 }
2350         }
2351
2352         status = sci_oem_parameters_set(ihost);
2353         if (status != SCI_SUCCESS) {
2354                 dev_warn(&ihost->pdev->dev,
2355                                 "%s: sci_oem_parameters_set failed\n",
2356                                 __func__);
2357                 return -ENODEV;
2358         }
2359
2360         tasklet_init(&ihost->completion_tasklet,
2361                      isci_host_completion_routine, (unsigned long)ihost);
2362
2363         INIT_LIST_HEAD(&ihost->requests_to_complete);
2364         INIT_LIST_HEAD(&ihost->requests_to_errorback);
2365
2366         spin_lock_irq(&ihost->scic_lock);
2367         status = sci_controller_initialize(ihost);
2368         spin_unlock_irq(&ihost->scic_lock);
2369         if (status != SCI_SUCCESS) {
2370                 dev_warn(&ihost->pdev->dev,
2371                          "%s: sci_controller_initialize failed -"
2372                          " status = 0x%x\n",
2373                          __func__, status);
2374                 return -ENODEV;
2375         }
2376
2377         err = sci_controller_mem_init(ihost);
2378         if (err)
2379                 return err;
2380
2381         for (i = 0; i < SCI_MAX_PORTS; i++)
2382                 isci_port_init(&ihost->ports[i], ihost, i);
2383
2384         for (i = 0; i < SCI_MAX_PHYS; i++)
2385                 isci_phy_init(&ihost->phys[i], ihost, i);
2386
2387         /* enable sgpio */
2388         writel(1, &ihost->scu_registers->peg0.sgpio.interface_control);
2389         for (i = 0; i < isci_gpio_count(ihost); i++)
2390                 writel(SGPIO_HW_CONTROL, &ihost->scu_registers->peg0.sgpio.output_data_select[i]);
2391         writel(0, &ihost->scu_registers->peg0.sgpio.vendor_specific_code);
2392
2393         for (i = 0; i < SCI_MAX_REMOTE_DEVICES; i++) {
2394                 struct isci_remote_device *idev = &ihost->devices[i];
2395
2396                 INIT_LIST_HEAD(&idev->reqs_in_process);
2397                 INIT_LIST_HEAD(&idev->node);
2398         }
2399
2400         for (i = 0; i < SCI_MAX_IO_REQUESTS; i++) {
2401                 struct isci_request *ireq;
2402                 dma_addr_t dma;
2403
2404                 ireq = dmam_alloc_coherent(&ihost->pdev->dev,
2405                                            sizeof(struct isci_request), &dma,
2406                                            GFP_KERNEL);
2407                 if (!ireq)
2408                         return -ENOMEM;
2409
2410                 ireq->tc = &ihost->task_context_table[i];
2411                 ireq->owning_controller = ihost;
2412                 spin_lock_init(&ireq->state_lock);
2413                 ireq->request_daddr = dma;
2414                 ireq->isci_host = ihost;
2415                 ihost->reqs[i] = ireq;
2416         }
2417
2418         return 0;
2419 }
2420
2421 void sci_controller_link_up(struct isci_host *ihost, struct isci_port *iport,
2422                             struct isci_phy *iphy)
2423 {
2424         switch (ihost->sm.current_state_id) {
2425         case SCIC_STARTING:
2426                 sci_del_timer(&ihost->phy_timer);
2427                 ihost->phy_startup_timer_pending = false;
2428                 ihost->port_agent.link_up_handler(ihost, &ihost->port_agent,
2429                                                   iport, iphy);
2430                 sci_controller_start_next_phy(ihost);
2431                 break;
2432         case SCIC_READY:
2433                 ihost->port_agent.link_up_handler(ihost, &ihost->port_agent,
2434                                                   iport, iphy);
2435                 break;
2436         default:
2437                 dev_dbg(&ihost->pdev->dev,
2438                         "%s: SCIC Controller linkup event from phy %d in "
2439                         "unexpected state %d\n", __func__, iphy->phy_index,
2440                         ihost->sm.current_state_id);
2441         }
2442 }
2443
2444 void sci_controller_link_down(struct isci_host *ihost, struct isci_port *iport,
2445                               struct isci_phy *iphy)
2446 {
2447         switch (ihost->sm.current_state_id) {
2448         case SCIC_STARTING:
2449         case SCIC_READY:
2450                 ihost->port_agent.link_down_handler(ihost, &ihost->port_agent,
2451                                                    iport, iphy);
2452                 break;
2453         default:
2454                 dev_dbg(&ihost->pdev->dev,
2455                         "%s: SCIC Controller linkdown event from phy %d in "
2456                         "unexpected state %d\n",
2457                         __func__,
2458                         iphy->phy_index,
2459                         ihost->sm.current_state_id);
2460         }
2461 }
2462
2463 static bool sci_controller_has_remote_devices_stopping(struct isci_host *ihost)
2464 {
2465         u32 index;
2466
2467         for (index = 0; index < ihost->remote_node_entries; index++) {
2468                 if ((ihost->device_table[index] != NULL) &&
2469                    (ihost->device_table[index]->sm.current_state_id == SCI_DEV_STOPPING))
2470                         return true;
2471         }
2472
2473         return false;
2474 }
2475
2476 void sci_controller_remote_device_stopped(struct isci_host *ihost,
2477                                           struct isci_remote_device *idev)
2478 {
2479         if (ihost->sm.current_state_id != SCIC_STOPPING) {
2480                 dev_dbg(&ihost->pdev->dev,
2481                         "SCIC Controller 0x%p remote device stopped event "
2482                         "from device 0x%p in unexpected state %d\n",
2483                         ihost, idev,
2484                         ihost->sm.current_state_id);
2485                 return;
2486         }
2487
2488         if (!sci_controller_has_remote_devices_stopping(ihost))
2489                 sci_change_state(&ihost->sm, SCIC_STOPPED);
2490 }
2491
2492 void sci_controller_post_request(struct isci_host *ihost, u32 request)
2493 {
2494         dev_dbg(&ihost->pdev->dev, "%s[%d]: %#x\n",
2495                 __func__, ihost->id, request);
2496
2497         writel(request, &ihost->smu_registers->post_context_port);
2498 }
2499
2500 struct isci_request *sci_request_by_tag(struct isci_host *ihost, u16 io_tag)
2501 {
2502         u16 task_index;
2503         u16 task_sequence;
2504
2505         task_index = ISCI_TAG_TCI(io_tag);
2506
2507         if (task_index < ihost->task_context_entries) {
2508                 struct isci_request *ireq = ihost->reqs[task_index];
2509
2510                 if (test_bit(IREQ_ACTIVE, &ireq->flags)) {
2511                         task_sequence = ISCI_TAG_SEQ(io_tag);
2512
2513                         if (task_sequence == ihost->io_request_sequence[task_index])
2514                                 return ireq;
2515                 }
2516         }
2517
2518         return NULL;
2519 }
2520
2521 /**
2522  * This method allocates remote node index and the reserves the remote node
2523  *    context space for use. This method can fail if there are no more remote
2524  *    node index available.
2525  * @scic: This is the controller object which contains the set of
2526  *    free remote node ids
2527  * @sci_dev: This is the device object which is requesting the a remote node
2528  *    id
2529  * @node_id: This is the remote node id that is assinged to the device if one
2530  *    is available
2531  *
2532  * enum sci_status SCI_FAILURE_OUT_OF_RESOURCES if there are no available remote
2533  * node index available.
2534  */
2535 enum sci_status sci_controller_allocate_remote_node_context(struct isci_host *ihost,
2536                                                             struct isci_remote_device *idev,
2537                                                             u16 *node_id)
2538 {
2539         u16 node_index;
2540         u32 remote_node_count = sci_remote_device_node_count(idev);
2541
2542         node_index = sci_remote_node_table_allocate_remote_node(
2543                 &ihost->available_remote_nodes, remote_node_count
2544                 );
2545
2546         if (node_index != SCIC_SDS_REMOTE_NODE_CONTEXT_INVALID_INDEX) {
2547                 ihost->device_table[node_index] = idev;
2548
2549                 *node_id = node_index;
2550
2551                 return SCI_SUCCESS;
2552         }
2553
2554         return SCI_FAILURE_INSUFFICIENT_RESOURCES;
2555 }
2556
2557 void sci_controller_free_remote_node_context(struct isci_host *ihost,
2558                                              struct isci_remote_device *idev,
2559                                              u16 node_id)
2560 {
2561         u32 remote_node_count = sci_remote_device_node_count(idev);
2562
2563         if (ihost->device_table[node_id] == idev) {
2564                 ihost->device_table[node_id] = NULL;
2565
2566                 sci_remote_node_table_release_remote_node_index(
2567                         &ihost->available_remote_nodes, remote_node_count, node_id
2568                         );
2569         }
2570 }
2571
2572 void sci_controller_copy_sata_response(void *response_buffer,
2573                                        void *frame_header,
2574                                        void *frame_buffer)
2575 {
2576         /* XXX type safety? */
2577         memcpy(response_buffer, frame_header, sizeof(u32));
2578
2579         memcpy(response_buffer + sizeof(u32),
2580                frame_buffer,
2581                sizeof(struct dev_to_host_fis) - sizeof(u32));
2582 }
2583
2584 void sci_controller_release_frame(struct isci_host *ihost, u32 frame_index)
2585 {
2586         if (sci_unsolicited_frame_control_release_frame(&ihost->uf_control, frame_index))
2587                 writel(ihost->uf_control.get,
2588                         &ihost->scu_registers->sdma.unsolicited_frame_get_pointer);
2589 }
2590
2591 void isci_tci_free(struct isci_host *ihost, u16 tci)
2592 {
2593         u16 tail = ihost->tci_tail & (SCI_MAX_IO_REQUESTS-1);
2594
2595         ihost->tci_pool[tail] = tci;
2596         ihost->tci_tail = tail + 1;
2597 }
2598
2599 static u16 isci_tci_alloc(struct isci_host *ihost)
2600 {
2601         u16 head = ihost->tci_head & (SCI_MAX_IO_REQUESTS-1);
2602         u16 tci = ihost->tci_pool[head];
2603
2604         ihost->tci_head = head + 1;
2605         return tci;
2606 }
2607
2608 static u16 isci_tci_space(struct isci_host *ihost)
2609 {
2610         return CIRC_SPACE(ihost->tci_head, ihost->tci_tail, SCI_MAX_IO_REQUESTS);
2611 }
2612
2613 u16 isci_alloc_tag(struct isci_host *ihost)
2614 {
2615         if (isci_tci_space(ihost)) {
2616                 u16 tci = isci_tci_alloc(ihost);
2617                 u8 seq = ihost->io_request_sequence[tci];
2618
2619                 return ISCI_TAG(seq, tci);
2620         }
2621
2622         return SCI_CONTROLLER_INVALID_IO_TAG;
2623 }
2624
2625 enum sci_status isci_free_tag(struct isci_host *ihost, u16 io_tag)
2626 {
2627         u16 tci = ISCI_TAG_TCI(io_tag);
2628         u16 seq = ISCI_TAG_SEQ(io_tag);
2629
2630         /* prevent tail from passing head */
2631         if (isci_tci_active(ihost) == 0)
2632                 return SCI_FAILURE_INVALID_IO_TAG;
2633
2634         if (seq == ihost->io_request_sequence[tci]) {
2635                 ihost->io_request_sequence[tci] = (seq+1) & (SCI_MAX_SEQ-1);
2636
2637                 isci_tci_free(ihost, tci);
2638
2639                 return SCI_SUCCESS;
2640         }
2641         return SCI_FAILURE_INVALID_IO_TAG;
2642 }
2643
2644 enum sci_status sci_controller_start_io(struct isci_host *ihost,
2645                                         struct isci_remote_device *idev,
2646                                         struct isci_request *ireq)
2647 {
2648         enum sci_status status;
2649
2650         if (ihost->sm.current_state_id != SCIC_READY) {
2651                 dev_warn(&ihost->pdev->dev, "invalid state to start I/O");
2652                 return SCI_FAILURE_INVALID_STATE;
2653         }
2654
2655         status = sci_remote_device_start_io(ihost, idev, ireq);
2656         if (status != SCI_SUCCESS)
2657                 return status;
2658
2659         set_bit(IREQ_ACTIVE, &ireq->flags);
2660         sci_controller_post_request(ihost, ireq->post_context);
2661         return SCI_SUCCESS;
2662 }
2663
2664 enum sci_status sci_controller_terminate_request(struct isci_host *ihost,
2665                                                  struct isci_remote_device *idev,
2666                                                  struct isci_request *ireq)
2667 {
2668         /* terminate an ongoing (i.e. started) core IO request.  This does not
2669          * abort the IO request at the target, but rather removes the IO
2670          * request from the host controller.
2671          */
2672         enum sci_status status;
2673
2674         if (ihost->sm.current_state_id != SCIC_READY) {
2675                 dev_warn(&ihost->pdev->dev,
2676                          "invalid state to terminate request\n");
2677                 return SCI_FAILURE_INVALID_STATE;
2678         }
2679
2680         status = sci_io_request_terminate(ireq);
2681         if (status != SCI_SUCCESS)
2682                 return status;
2683
2684         /*
2685          * Utilize the original post context command and or in the POST_TC_ABORT
2686          * request sub-type.
2687          */
2688         sci_controller_post_request(ihost,
2689                                     ireq->post_context | SCU_CONTEXT_COMMAND_REQUEST_POST_TC_ABORT);
2690         return SCI_SUCCESS;
2691 }
2692
2693 /**
2694  * sci_controller_complete_io() - This method will perform core specific
2695  *    completion operations for an IO request.  After this method is invoked,
2696  *    the user should consider the IO request as invalid until it is properly
2697  *    reused (i.e. re-constructed).
2698  * @ihost: The handle to the controller object for which to complete the
2699  *    IO request.
2700  * @idev: The handle to the remote device object for which to complete
2701  *    the IO request.
2702  * @ireq: the handle to the io request object to complete.
2703  */
2704 enum sci_status sci_controller_complete_io(struct isci_host *ihost,
2705                                            struct isci_remote_device *idev,
2706                                            struct isci_request *ireq)
2707 {
2708         enum sci_status status;
2709         u16 index;
2710
2711         switch (ihost->sm.current_state_id) {
2712         case SCIC_STOPPING:
2713                 /* XXX: Implement this function */
2714                 return SCI_FAILURE;
2715         case SCIC_READY:
2716                 status = sci_remote_device_complete_io(ihost, idev, ireq);
2717                 if (status != SCI_SUCCESS)
2718                         return status;
2719
2720                 index = ISCI_TAG_TCI(ireq->io_tag);
2721                 clear_bit(IREQ_ACTIVE, &ireq->flags);
2722                 return SCI_SUCCESS;
2723         default:
2724                 dev_warn(&ihost->pdev->dev, "invalid state to complete I/O");
2725                 return SCI_FAILURE_INVALID_STATE;
2726         }
2727
2728 }
2729
2730 enum sci_status sci_controller_continue_io(struct isci_request *ireq)
2731 {
2732         struct isci_host *ihost = ireq->owning_controller;
2733
2734         if (ihost->sm.current_state_id != SCIC_READY) {
2735                 dev_warn(&ihost->pdev->dev, "invalid state to continue I/O");
2736                 return SCI_FAILURE_INVALID_STATE;
2737         }
2738
2739         set_bit(IREQ_ACTIVE, &ireq->flags);
2740         sci_controller_post_request(ihost, ireq->post_context);
2741         return SCI_SUCCESS;
2742 }
2743
2744 /**
2745  * sci_controller_start_task() - This method is called by the SCIC user to
2746  *    send/start a framework task management request.
2747  * @controller: the handle to the controller object for which to start the task
2748  *    management request.
2749  * @remote_device: the handle to the remote device object for which to start
2750  *    the task management request.
2751  * @task_request: the handle to the task request object to start.
2752  */
2753 enum sci_task_status sci_controller_start_task(struct isci_host *ihost,
2754                                                struct isci_remote_device *idev,
2755                                                struct isci_request *ireq)
2756 {
2757         enum sci_status status;
2758
2759         if (ihost->sm.current_state_id != SCIC_READY) {
2760                 dev_warn(&ihost->pdev->dev,
2761                          "%s: SCIC Controller starting task from invalid "
2762                          "state\n",
2763                          __func__);
2764                 return SCI_TASK_FAILURE_INVALID_STATE;
2765         }
2766
2767         status = sci_remote_device_start_task(ihost, idev, ireq);
2768         switch (status) {
2769         case SCI_FAILURE_RESET_DEVICE_PARTIAL_SUCCESS:
2770                 set_bit(IREQ_ACTIVE, &ireq->flags);
2771
2772                 /*
2773                  * We will let framework know this task request started successfully,
2774                  * although core is still woring on starting the request (to post tc when
2775                  * RNC is resumed.)
2776                  */
2777                 return SCI_SUCCESS;
2778         case SCI_SUCCESS:
2779                 set_bit(IREQ_ACTIVE, &ireq->flags);
2780                 sci_controller_post_request(ihost, ireq->post_context);
2781                 break;
2782         default:
2783                 break;
2784         }
2785
2786         return status;
2787 }
2788
2789 static int sci_write_gpio_tx_gp(struct isci_host *ihost, u8 reg_index, u8 reg_count, u8 *write_data)
2790 {
2791         int d;
2792
2793         /* no support for TX_GP_CFG */
2794         if (reg_index == 0)
2795                 return -EINVAL;
2796
2797         for (d = 0; d < isci_gpio_count(ihost); d++) {
2798                 u32 val = 0x444; /* all ODx.n clear */
2799                 int i;
2800
2801                 for (i = 0; i < 3; i++) {
2802                         int bit = (i << 2) + 2;
2803
2804                         bit = try_test_sas_gpio_gp_bit(to_sas_gpio_od(d, i),
2805                                                        write_data, reg_index,
2806                                                        reg_count);
2807                         if (bit < 0)
2808                                 break;
2809
2810                         /* if od is set, clear the 'invert' bit */
2811                         val &= ~(bit << ((i << 2) + 2));
2812                 }
2813
2814                 if (i < 3)
2815                         break;
2816                 writel(val, &ihost->scu_registers->peg0.sgpio.output_data_select[d]);
2817         }
2818
2819         /* unless reg_index is > 1, we should always be able to write at
2820          * least one register
2821          */
2822         return d > 0;
2823 }
2824
2825 int isci_gpio_write(struct sas_ha_struct *sas_ha, u8 reg_type, u8 reg_index,
2826                     u8 reg_count, u8 *write_data)
2827 {
2828         struct isci_host *ihost = sas_ha->lldd_ha;
2829         int written;
2830
2831         switch (reg_type) {
2832         case SAS_GPIO_REG_TX_GP:
2833                 written = sci_write_gpio_tx_gp(ihost, reg_index, reg_count, write_data);
2834                 break;
2835         default:
2836                 written = -EINVAL;
2837         }
2838
2839         return written;
2840 }