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