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