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