isci: Added support for C0 to SCU Driver
[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() || is_c0())
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() || is_c0())
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 if (is_c0()) {
2106                          /* Configure transmitter SSC parameters */
2107                         writel(0x0003000, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_ssc_control);
2108                         udelay(AFE_REGISTER_WRITE_DELAY);
2109
2110                         /*
2111                          * All defaults, except the Receive Word Alignament/Comma Detect
2112                          * Enable....(0xe800) */
2113                         writel(0x00004500, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control0);
2114                         udelay(AFE_REGISTER_WRITE_DELAY);
2115                 } else {
2116                         /*
2117                          * All defaults, except the Receive Word Alignament/Comma Detect
2118                          * Enable....(0xe800) */
2119                         writel(0x00004512, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control0);
2120                         udelay(AFE_REGISTER_WRITE_DELAY);
2121
2122                         writel(0x0050100F, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control1);
2123                         udelay(AFE_REGISTER_WRITE_DELAY);
2124                 }
2125
2126                 /*
2127                  * Power up TX and RX out from power down (PWRDNTX and PWRDNRX)
2128                  * & increase TX int & ext bias 20%....(0xe85c) */
2129                 if (is_a0())
2130                         writel(0x000003D4, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2131                 else if (is_a2())
2132                         writel(0x000003F0, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2133                 else if (is_b0()) {
2134                          /* Power down TX and RX (PWRDNTX and PWRDNRX) */
2135                         writel(0x000003D7, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2136                         udelay(AFE_REGISTER_WRITE_DELAY);
2137
2138                         /*
2139                          * Power up TX and RX out from power down (PWRDNTX and PWRDNRX)
2140                          * & increase TX int & ext bias 20%....(0xe85c) */
2141                         writel(0x000003D4, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2142                 } else {
2143                         writel(0x000001E7, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2144                         udelay(AFE_REGISTER_WRITE_DELAY);
2145
2146                         /*
2147                          * Power up TX and RX out from power down (PWRDNTX and PWRDNRX)
2148                          * & increase TX int & ext bias 20%....(0xe85c) */
2149                         writel(0x000001E4, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_channel_control);
2150                 }
2151                 udelay(AFE_REGISTER_WRITE_DELAY);
2152
2153                 if (is_a0() || is_a2()) {
2154                         /* Enable TX equalization (0xe824) */
2155                         writel(0x00040000, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_control);
2156                         udelay(AFE_REGISTER_WRITE_DELAY);
2157                 }
2158
2159                 /*
2160                  * RDPI=0x0(RX Power On), RXOOBDETPDNC=0x0, TPD=0x0(TX Power On),
2161                  * RDD=0x0(RX Detect Enabled) ....(0xe800) */
2162                 writel(0x00004100, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_xcvr_control0);
2163                 udelay(AFE_REGISTER_WRITE_DELAY);
2164
2165                 /* Leave DFE/FFE on */
2166                 if (is_a0())
2167                         writel(0x3F09983F, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control0);
2168                 else if (is_a2())
2169                         writel(0x3F11103F, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control0);
2170                 else if (is_b0()) {
2171                         writel(0x3F11103F, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control0);
2172                         udelay(AFE_REGISTER_WRITE_DELAY);
2173                         /* Enable TX equalization (0xe824) */
2174                         writel(0x00040000, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_control);
2175                 } else {
2176                         writel(0x0140DF0F, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control1);
2177                         udelay(AFE_REGISTER_WRITE_DELAY);
2178
2179                         writel(0x3F6F103F, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_rx_ssc_control0);
2180                         udelay(AFE_REGISTER_WRITE_DELAY);
2181
2182                         /* Enable TX equalization (0xe824) */
2183                         writel(0x00040000, &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_control);
2184                 }
2185
2186                 udelay(AFE_REGISTER_WRITE_DELAY);
2187
2188                 writel(oem_phy->afe_tx_amp_control0,
2189                         &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control0);
2190                 udelay(AFE_REGISTER_WRITE_DELAY);
2191
2192                 writel(oem_phy->afe_tx_amp_control1,
2193                         &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control1);
2194                 udelay(AFE_REGISTER_WRITE_DELAY);
2195
2196                 writel(oem_phy->afe_tx_amp_control2,
2197                         &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control2);
2198                 udelay(AFE_REGISTER_WRITE_DELAY);
2199
2200                 writel(oem_phy->afe_tx_amp_control3,
2201                         &scic->scu_registers->afe.scu_afe_xcvr[phy_id].afe_tx_amp_control3);
2202                 udelay(AFE_REGISTER_WRITE_DELAY);
2203         }
2204
2205         /* Transfer control to the PEs */
2206         writel(0x00010f00, &scic->scu_registers->afe.afe_dfx_master_control0);
2207         udelay(AFE_REGISTER_WRITE_DELAY);
2208 }
2209
2210 static enum sci_status scic_controller_set_mode(struct scic_sds_controller *scic,
2211                                                 enum sci_controller_mode operating_mode)
2212 {
2213         enum sci_status status          = SCI_SUCCESS;
2214
2215         if ((scic->sm.current_state_id == SCIC_INITIALIZING) ||
2216             (scic->sm.current_state_id == SCIC_INITIALIZED)) {
2217                 switch (operating_mode) {
2218                 case SCI_MODE_SPEED:
2219                         scic->remote_node_entries      = SCI_MAX_REMOTE_DEVICES;
2220                         scic->task_context_entries     = SCU_IO_REQUEST_COUNT;
2221                         scic->uf_control.buffers.count =
2222                                 SCU_UNSOLICITED_FRAME_COUNT;
2223                         scic->completion_event_entries = SCU_EVENT_COUNT;
2224                         scic->completion_queue_entries =
2225                                 SCU_COMPLETION_QUEUE_COUNT;
2226                         break;
2227
2228                 case SCI_MODE_SIZE:
2229                         scic->remote_node_entries      = SCI_MIN_REMOTE_DEVICES;
2230                         scic->task_context_entries     = SCI_MIN_IO_REQUESTS;
2231                         scic->uf_control.buffers.count =
2232                                 SCU_MIN_UNSOLICITED_FRAMES;
2233                         scic->completion_event_entries = SCU_MIN_EVENTS;
2234                         scic->completion_queue_entries =
2235                                 SCU_MIN_COMPLETION_QUEUE_ENTRIES;
2236                         break;
2237
2238                 default:
2239                         status = SCI_FAILURE_INVALID_PARAMETER_VALUE;
2240                         break;
2241                 }
2242         } else
2243                 status = SCI_FAILURE_INVALID_STATE;
2244
2245         return status;
2246 }
2247
2248 static void scic_sds_controller_initialize_power_control(struct scic_sds_controller *scic)
2249 {
2250         sci_init_timer(&scic->power_control.timer, power_control_timeout);
2251
2252         memset(scic->power_control.requesters, 0,
2253                sizeof(scic->power_control.requesters));
2254
2255         scic->power_control.phys_waiting = 0;
2256         scic->power_control.phys_granted_power = 0;
2257 }
2258
2259 static enum sci_status scic_controller_initialize(struct scic_sds_controller *scic)
2260 {
2261         struct sci_base_state_machine *sm = &scic->sm;
2262         enum sci_status result = SCI_SUCCESS;
2263         struct isci_host *ihost = scic_to_ihost(scic);
2264         u32 index, state;
2265
2266         if (scic->sm.current_state_id != SCIC_RESET) {
2267                 dev_warn(scic_to_dev(scic),
2268                          "SCIC Controller initialize operation requested "
2269                          "in invalid state\n");
2270                 return SCI_FAILURE_INVALID_STATE;
2271         }
2272
2273         sci_change_state(sm, SCIC_INITIALIZING);
2274
2275         sci_init_timer(&scic->phy_timer, phy_startup_timeout);
2276
2277         scic->next_phy_to_start = 0;
2278         scic->phy_startup_timer_pending = false;
2279
2280         scic_sds_controller_initialize_power_control(scic);
2281
2282         /*
2283          * There is nothing to do here for B0 since we do not have to
2284          * program the AFE registers.
2285          * / @todo The AFE settings are supposed to be correct for the B0 but
2286          * /       presently they seem to be wrong. */
2287         scic_sds_controller_afe_initialization(scic);
2288
2289         if (result == SCI_SUCCESS) {
2290                 u32 status;
2291                 u32 terminate_loop;
2292
2293                 /* Take the hardware out of reset */
2294                 writel(0, &scic->smu_registers->soft_reset_control);
2295
2296                 /*
2297                  * / @todo Provide meaningfull error code for hardware failure
2298                  * result = SCI_FAILURE_CONTROLLER_HARDWARE; */
2299                 result = SCI_FAILURE;
2300                 terminate_loop = 100;
2301
2302                 while (terminate_loop-- && (result != SCI_SUCCESS)) {
2303                         /* Loop until the hardware reports success */
2304                         udelay(SCU_CONTEXT_RAM_INIT_STALL_TIME);
2305                         status = readl(&scic->smu_registers->control_status);
2306
2307                         if ((status & SCU_RAM_INIT_COMPLETED) ==
2308                                         SCU_RAM_INIT_COMPLETED)
2309                                 result = SCI_SUCCESS;
2310                 }
2311         }
2312
2313         if (result == SCI_SUCCESS) {
2314                 u32 max_supported_ports;
2315                 u32 max_supported_devices;
2316                 u32 max_supported_io_requests;
2317                 u32 device_context_capacity;
2318
2319                 /*
2320                  * Determine what are the actaul device capacities that the
2321                  * hardware will support */
2322                 device_context_capacity =
2323                         readl(&scic->smu_registers->device_context_capacity);
2324
2325
2326                 max_supported_ports = smu_dcc_get_max_ports(device_context_capacity);
2327                 max_supported_devices = smu_dcc_get_max_remote_node_context(device_context_capacity);
2328                 max_supported_io_requests = smu_dcc_get_max_task_context(device_context_capacity);
2329
2330                 /*
2331                  * Make all PEs that are unassigned match up with the
2332                  * logical ports
2333                  */
2334                 for (index = 0; index < max_supported_ports; index++) {
2335                         struct scu_port_task_scheduler_group_registers __iomem
2336                                 *ptsg = &scic->scu_registers->peg0.ptsg;
2337
2338                         writel(index, &ptsg->protocol_engine[index]);
2339                 }
2340
2341                 /* Record the smaller of the two capacity values */
2342                 scic->logical_port_entries =
2343                         min(max_supported_ports, scic->logical_port_entries);
2344
2345                 scic->task_context_entries =
2346                         min(max_supported_io_requests,
2347                             scic->task_context_entries);
2348
2349                 scic->remote_node_entries =
2350                         min(max_supported_devices, scic->remote_node_entries);
2351
2352                 /*
2353                  * Now that we have the correct hardware reported minimum values
2354                  * build the MDL for the controller.  Default to a performance
2355                  * configuration.
2356                  */
2357                 scic_controller_set_mode(scic, SCI_MODE_SPEED);
2358         }
2359
2360         /* Initialize hardware PCI Relaxed ordering in DMA engines */
2361         if (result == SCI_SUCCESS) {
2362                 u32 dma_configuration;
2363
2364                 /* Configure the payload DMA */
2365                 dma_configuration =
2366                         readl(&scic->scu_registers->sdma.pdma_configuration);
2367                 dma_configuration |=
2368                         SCU_PDMACR_GEN_BIT(PCI_RELAXED_ORDERING_ENABLE);
2369                 writel(dma_configuration,
2370                         &scic->scu_registers->sdma.pdma_configuration);
2371
2372                 /* Configure the control DMA */
2373                 dma_configuration =
2374                         readl(&scic->scu_registers->sdma.cdma_configuration);
2375                 dma_configuration |=
2376                         SCU_CDMACR_GEN_BIT(PCI_RELAXED_ORDERING_ENABLE);
2377                 writel(dma_configuration,
2378                         &scic->scu_registers->sdma.cdma_configuration);
2379         }
2380
2381         /*
2382          * Initialize the PHYs before the PORTs because the PHY registers
2383          * are accessed during the port initialization.
2384          */
2385         if (result == SCI_SUCCESS) {
2386                 /* Initialize the phys */
2387                 for (index = 0;
2388                      (result == SCI_SUCCESS) && (index < SCI_MAX_PHYS);
2389                      index++) {
2390                         result = scic_sds_phy_initialize(
2391                                 &ihost->phys[index].sci,
2392                                 &scic->scu_registers->peg0.pe[index].tl,
2393                                 &scic->scu_registers->peg0.pe[index].ll);
2394                 }
2395         }
2396
2397         if (result == SCI_SUCCESS) {
2398                 /* Initialize the logical ports */
2399                 for (index = 0;
2400                      (index < scic->logical_port_entries) &&
2401                      (result == SCI_SUCCESS);
2402                      index++) {
2403                         result = scic_sds_port_initialize(
2404                                 &ihost->ports[index].sci,
2405                                 &scic->scu_registers->peg0.ptsg.port[index],
2406                                 &scic->scu_registers->peg0.ptsg.protocol_engine,
2407                                 &scic->scu_registers->peg0.viit[index]);
2408                 }
2409         }
2410
2411         if (result == SCI_SUCCESS)
2412                 result = scic_sds_port_configuration_agent_initialize(
2413                                 scic,
2414                                 &scic->port_agent);
2415
2416         /* Advance the controller state machine */
2417         if (result == SCI_SUCCESS)
2418                 state = SCIC_INITIALIZED;
2419         else
2420                 state = SCIC_FAILED;
2421         sci_change_state(sm, state);
2422
2423         return result;
2424 }
2425
2426 static enum sci_status scic_user_parameters_set(
2427         struct scic_sds_controller *scic,
2428         union scic_user_parameters *scic_parms)
2429 {
2430         u32 state = scic->sm.current_state_id;
2431
2432         if (state == SCIC_RESET ||
2433             state == SCIC_INITIALIZING ||
2434             state == SCIC_INITIALIZED) {
2435                 u16 index;
2436
2437                 /*
2438                  * Validate the user parameters.  If they are not legal, then
2439                  * return a failure.
2440                  */
2441                 for (index = 0; index < SCI_MAX_PHYS; index++) {
2442                         struct sci_phy_user_params *user_phy;
2443
2444                         user_phy = &scic_parms->sds1.phys[index];
2445
2446                         if (!((user_phy->max_speed_generation <=
2447                                                 SCIC_SDS_PARM_MAX_SPEED) &&
2448                               (user_phy->max_speed_generation >
2449                                                 SCIC_SDS_PARM_NO_SPEED)))
2450                                 return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2451
2452                         if (user_phy->in_connection_align_insertion_frequency <
2453                                         3)
2454                                 return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2455
2456                         if ((user_phy->in_connection_align_insertion_frequency <
2457                                                 3) ||
2458                             (user_phy->align_insertion_frequency == 0) ||
2459                             (user_phy->
2460                                 notify_enable_spin_up_insertion_frequency ==
2461                                                 0))
2462                                 return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2463                 }
2464
2465                 if ((scic_parms->sds1.stp_inactivity_timeout == 0) ||
2466                     (scic_parms->sds1.ssp_inactivity_timeout == 0) ||
2467                     (scic_parms->sds1.stp_max_occupancy_timeout == 0) ||
2468                     (scic_parms->sds1.ssp_max_occupancy_timeout == 0) ||
2469                     (scic_parms->sds1.no_outbound_task_timeout == 0))
2470                         return SCI_FAILURE_INVALID_PARAMETER_VALUE;
2471
2472                 memcpy(&scic->user_parameters, scic_parms, sizeof(*scic_parms));
2473
2474                 return SCI_SUCCESS;
2475         }
2476
2477         return SCI_FAILURE_INVALID_STATE;
2478 }
2479
2480 static int scic_controller_mem_init(struct scic_sds_controller *scic)
2481 {
2482         struct device *dev = scic_to_dev(scic);
2483         dma_addr_t dma_handle;
2484         enum sci_status result;
2485
2486         scic->completion_queue = dmam_alloc_coherent(dev,
2487                         scic->completion_queue_entries * sizeof(u32),
2488                         &dma_handle, GFP_KERNEL);
2489         if (!scic->completion_queue)
2490                 return -ENOMEM;
2491
2492         writel(lower_32_bits(dma_handle),
2493                 &scic->smu_registers->completion_queue_lower);
2494         writel(upper_32_bits(dma_handle),
2495                 &scic->smu_registers->completion_queue_upper);
2496
2497         scic->remote_node_context_table = dmam_alloc_coherent(dev,
2498                         scic->remote_node_entries *
2499                                 sizeof(union scu_remote_node_context),
2500                         &dma_handle, GFP_KERNEL);
2501         if (!scic->remote_node_context_table)
2502                 return -ENOMEM;
2503
2504         writel(lower_32_bits(dma_handle),
2505                 &scic->smu_registers->remote_node_context_lower);
2506         writel(upper_32_bits(dma_handle),
2507                 &scic->smu_registers->remote_node_context_upper);
2508
2509         scic->task_context_table = dmam_alloc_coherent(dev,
2510                         scic->task_context_entries *
2511                                 sizeof(struct scu_task_context),
2512                         &dma_handle, GFP_KERNEL);
2513         if (!scic->task_context_table)
2514                 return -ENOMEM;
2515
2516         writel(lower_32_bits(dma_handle),
2517                 &scic->smu_registers->host_task_table_lower);
2518         writel(upper_32_bits(dma_handle),
2519                 &scic->smu_registers->host_task_table_upper);
2520
2521         result = scic_sds_unsolicited_frame_control_construct(scic);
2522         if (result)
2523                 return result;
2524
2525         /*
2526          * Inform the silicon as to the location of the UF headers and
2527          * address table.
2528          */
2529         writel(lower_32_bits(scic->uf_control.headers.physical_address),
2530                 &scic->scu_registers->sdma.uf_header_base_address_lower);
2531         writel(upper_32_bits(scic->uf_control.headers.physical_address),
2532                 &scic->scu_registers->sdma.uf_header_base_address_upper);
2533
2534         writel(lower_32_bits(scic->uf_control.address_table.physical_address),
2535                 &scic->scu_registers->sdma.uf_address_table_lower);
2536         writel(upper_32_bits(scic->uf_control.address_table.physical_address),
2537                 &scic->scu_registers->sdma.uf_address_table_upper);
2538
2539         return 0;
2540 }
2541
2542 int isci_host_init(struct isci_host *isci_host)
2543 {
2544         int err = 0, i;
2545         enum sci_status status;
2546         union scic_oem_parameters oem;
2547         union scic_user_parameters scic_user_params;
2548         struct isci_pci_info *pci_info = to_pci_info(isci_host->pdev);
2549
2550         spin_lock_init(&isci_host->state_lock);
2551         spin_lock_init(&isci_host->scic_lock);
2552         spin_lock_init(&isci_host->queue_lock);
2553         init_waitqueue_head(&isci_host->eventq);
2554
2555         isci_host_change_state(isci_host, isci_starting);
2556         isci_host->can_queue = ISCI_CAN_QUEUE_VAL;
2557
2558         status = scic_controller_construct(&isci_host->sci, scu_base(isci_host),
2559                                            smu_base(isci_host));
2560
2561         if (status != SCI_SUCCESS) {
2562                 dev_err(&isci_host->pdev->dev,
2563                         "%s: scic_controller_construct failed - status = %x\n",
2564                         __func__,
2565                         status);
2566                 return -ENODEV;
2567         }
2568
2569         isci_host->sas_ha.dev = &isci_host->pdev->dev;
2570         isci_host->sas_ha.lldd_ha = isci_host;
2571
2572         /*
2573          * grab initial values stored in the controller object for OEM and USER
2574          * parameters
2575          */
2576         isci_user_parameters_get(isci_host, &scic_user_params);
2577         status = scic_user_parameters_set(&isci_host->sci,
2578                                           &scic_user_params);
2579         if (status != SCI_SUCCESS) {
2580                 dev_warn(&isci_host->pdev->dev,
2581                          "%s: scic_user_parameters_set failed\n",
2582                          __func__);
2583                 return -ENODEV;
2584         }
2585
2586         scic_oem_parameters_get(&isci_host->sci, &oem);
2587
2588         /* grab any OEM parameters specified in orom */
2589         if (pci_info->orom) {
2590                 status = isci_parse_oem_parameters(&oem,
2591                                                    pci_info->orom,
2592                                                    isci_host->id);
2593                 if (status != SCI_SUCCESS) {
2594                         dev_warn(&isci_host->pdev->dev,
2595                                  "parsing firmware oem parameters failed\n");
2596                         return -EINVAL;
2597                 }
2598         }
2599
2600         status = scic_oem_parameters_set(&isci_host->sci, &oem);
2601         if (status != SCI_SUCCESS) {
2602                 dev_warn(&isci_host->pdev->dev,
2603                                 "%s: scic_oem_parameters_set failed\n",
2604                                 __func__);
2605                 return -ENODEV;
2606         }
2607
2608         tasklet_init(&isci_host->completion_tasklet,
2609                      isci_host_completion_routine, (unsigned long)isci_host);
2610
2611         INIT_LIST_HEAD(&isci_host->requests_to_complete);
2612         INIT_LIST_HEAD(&isci_host->requests_to_errorback);
2613
2614         spin_lock_irq(&isci_host->scic_lock);
2615         status = scic_controller_initialize(&isci_host->sci);
2616         spin_unlock_irq(&isci_host->scic_lock);
2617         if (status != SCI_SUCCESS) {
2618                 dev_warn(&isci_host->pdev->dev,
2619                          "%s: scic_controller_initialize failed -"
2620                          " status = 0x%x\n",
2621                          __func__, status);
2622                 return -ENODEV;
2623         }
2624
2625         err = scic_controller_mem_init(&isci_host->sci);
2626         if (err)
2627                 return err;
2628
2629         isci_host->dma_pool = dmam_pool_create(DRV_NAME, &isci_host->pdev->dev,
2630                                                sizeof(struct isci_request),
2631                                                SLAB_HWCACHE_ALIGN, 0);
2632
2633         if (!isci_host->dma_pool)
2634                 return -ENOMEM;
2635
2636         for (i = 0; i < SCI_MAX_PORTS; i++)
2637                 isci_port_init(&isci_host->ports[i], isci_host, i);
2638
2639         for (i = 0; i < SCI_MAX_PHYS; i++)
2640                 isci_phy_init(&isci_host->phys[i], isci_host, i);
2641
2642         for (i = 0; i < SCI_MAX_REMOTE_DEVICES; i++) {
2643                 struct isci_remote_device *idev = &isci_host->devices[i];
2644
2645                 INIT_LIST_HEAD(&idev->reqs_in_process);
2646                 INIT_LIST_HEAD(&idev->node);
2647                 spin_lock_init(&idev->state_lock);
2648         }
2649
2650         return 0;
2651 }
2652
2653 void scic_sds_controller_link_up(struct scic_sds_controller *scic,
2654                 struct scic_sds_port *port, struct scic_sds_phy *phy)
2655 {
2656         switch (scic->sm.current_state_id) {
2657         case SCIC_STARTING:
2658                 sci_del_timer(&scic->phy_timer);
2659                 scic->phy_startup_timer_pending = false;
2660                 scic->port_agent.link_up_handler(scic, &scic->port_agent,
2661                                                  port, phy);
2662                 scic_sds_controller_start_next_phy(scic);
2663                 break;
2664         case SCIC_READY:
2665                 scic->port_agent.link_up_handler(scic, &scic->port_agent,
2666                                                  port, phy);
2667                 break;
2668         default:
2669                 dev_dbg(scic_to_dev(scic),
2670                         "%s: SCIC Controller linkup event from phy %d in "
2671                         "unexpected state %d\n", __func__, phy->phy_index,
2672                         scic->sm.current_state_id);
2673         }
2674 }
2675
2676 void scic_sds_controller_link_down(struct scic_sds_controller *scic,
2677                 struct scic_sds_port *port, struct scic_sds_phy *phy)
2678 {
2679         switch (scic->sm.current_state_id) {
2680         case SCIC_STARTING:
2681         case SCIC_READY:
2682                 scic->port_agent.link_down_handler(scic, &scic->port_agent,
2683                                                    port, phy);
2684                 break;
2685         default:
2686                 dev_dbg(scic_to_dev(scic),
2687                         "%s: SCIC Controller linkdown event from phy %d in "
2688                         "unexpected state %d\n",
2689                         __func__,
2690                         phy->phy_index,
2691                         scic->sm.current_state_id);
2692         }
2693 }
2694
2695 /**
2696  * This is a helper method to determine if any remote devices on this
2697  * controller are still in the stopping state.
2698  *
2699  */
2700 static bool scic_sds_controller_has_remote_devices_stopping(
2701         struct scic_sds_controller *controller)
2702 {
2703         u32 index;
2704
2705         for (index = 0; index < controller->remote_node_entries; index++) {
2706                 if ((controller->device_table[index] != NULL) &&
2707                    (controller->device_table[index]->sm.current_state_id == SCI_DEV_STOPPING))
2708                         return true;
2709         }
2710
2711         return false;
2712 }
2713
2714 /**
2715  * This method is called by the remote device to inform the controller
2716  * object that the remote device has stopped.
2717  */
2718 void scic_sds_controller_remote_device_stopped(struct scic_sds_controller *scic,
2719                                                struct scic_sds_remote_device *sci_dev)
2720 {
2721         if (scic->sm.current_state_id != SCIC_STOPPING) {
2722                 dev_dbg(scic_to_dev(scic),
2723                         "SCIC Controller 0x%p remote device stopped event "
2724                         "from device 0x%p in unexpected state %d\n",
2725                         scic, sci_dev,
2726                         scic->sm.current_state_id);
2727                 return;
2728         }
2729
2730         if (!scic_sds_controller_has_remote_devices_stopping(scic)) {
2731                 sci_change_state(&scic->sm, SCIC_STOPPED);
2732         }
2733 }
2734
2735 /**
2736  * This method will write to the SCU PCP register the request value. The method
2737  *    is used to suspend/resume ports, devices, and phys.
2738  * @scic:
2739  *
2740  *
2741  */
2742 void scic_sds_controller_post_request(
2743         struct scic_sds_controller *scic,
2744         u32 request)
2745 {
2746         dev_dbg(scic_to_dev(scic),
2747                 "%s: SCIC Controller 0x%p post request 0x%08x\n",
2748                 __func__,
2749                 scic,
2750                 request);
2751
2752         writel(request, &scic->smu_registers->post_context_port);
2753 }
2754
2755 /**
2756  * This method will copy the soft copy of the task context into the physical
2757  *    memory accessible by the controller.
2758  * @scic: This parameter specifies the controller for which to copy
2759  *    the task context.
2760  * @sci_req: This parameter specifies the request for which the task
2761  *    context is being copied.
2762  *
2763  * After this call is made the SCIC_SDS_IO_REQUEST object will always point to
2764  * the physical memory version of the task context. Thus, all subsequent
2765  * updates to the task context are performed in the TC table (i.e. DMAable
2766  * memory). none
2767  */
2768 void scic_sds_controller_copy_task_context(
2769         struct scic_sds_controller *scic,
2770         struct scic_sds_request *sci_req)
2771 {
2772         struct scu_task_context *task_context_buffer;
2773
2774         task_context_buffer = scic_sds_controller_get_task_context_buffer(
2775                 scic, sci_req->io_tag);
2776
2777         memcpy(task_context_buffer,
2778                sci_req->task_context_buffer,
2779                offsetof(struct scu_task_context, sgl_snapshot_ac));
2780
2781         /*
2782          * Now that the soft copy of the TC has been copied into the TC
2783          * table accessible by the silicon.  Thus, any further changes to
2784          * the TC (e.g. TC termination) occur in the appropriate location. */
2785         sci_req->task_context_buffer = task_context_buffer;
2786 }
2787
2788 /**
2789  * This method returns the task context buffer for the given io tag.
2790  * @scic:
2791  * @io_tag:
2792  *
2793  * struct scu_task_context*
2794  */
2795 struct scu_task_context *scic_sds_controller_get_task_context_buffer(
2796         struct scic_sds_controller *scic,
2797         u16 io_tag
2798         ) {
2799         u16 task_index = scic_sds_io_tag_get_index(io_tag);
2800
2801         if (task_index < scic->task_context_entries) {
2802                 return &scic->task_context_table[task_index];
2803         }
2804
2805         return NULL;
2806 }
2807
2808 struct scic_sds_request *scic_request_by_tag(struct scic_sds_controller *scic,
2809                                              u16 io_tag)
2810 {
2811         u16 task_index;
2812         u16 task_sequence;
2813
2814         task_index = scic_sds_io_tag_get_index(io_tag);
2815
2816         if (task_index  < scic->task_context_entries) {
2817                 if (scic->io_request_table[task_index] != NULL) {
2818                         task_sequence = scic_sds_io_tag_get_sequence(io_tag);
2819
2820                         if (task_sequence == scic->io_request_sequence[task_index]) {
2821                                 return scic->io_request_table[task_index];
2822                         }
2823                 }
2824         }
2825
2826         return NULL;
2827 }
2828
2829 /**
2830  * This method allocates remote node index and the reserves the remote node
2831  *    context space for use. This method can fail if there are no more remote
2832  *    node index available.
2833  * @scic: This is the controller object which contains the set of
2834  *    free remote node ids
2835  * @sci_dev: This is the device object which is requesting the a remote node
2836  *    id
2837  * @node_id: This is the remote node id that is assinged to the device if one
2838  *    is available
2839  *
2840  * enum sci_status SCI_FAILURE_OUT_OF_RESOURCES if there are no available remote
2841  * node index available.
2842  */
2843 enum sci_status scic_sds_controller_allocate_remote_node_context(
2844         struct scic_sds_controller *scic,
2845         struct scic_sds_remote_device *sci_dev,
2846         u16 *node_id)
2847 {
2848         u16 node_index;
2849         u32 remote_node_count = scic_sds_remote_device_node_count(sci_dev);
2850
2851         node_index = scic_sds_remote_node_table_allocate_remote_node(
2852                 &scic->available_remote_nodes, remote_node_count
2853                 );
2854
2855         if (node_index != SCIC_SDS_REMOTE_NODE_CONTEXT_INVALID_INDEX) {
2856                 scic->device_table[node_index] = sci_dev;
2857
2858                 *node_id = node_index;
2859
2860                 return SCI_SUCCESS;
2861         }
2862
2863         return SCI_FAILURE_INSUFFICIENT_RESOURCES;
2864 }
2865
2866 /**
2867  * This method frees the remote node index back to the available pool.  Once
2868  *    this is done the remote node context buffer is no longer valid and can
2869  *    not be used.
2870  * @scic:
2871  * @sci_dev:
2872  * @node_id:
2873  *
2874  */
2875 void scic_sds_controller_free_remote_node_context(
2876         struct scic_sds_controller *scic,
2877         struct scic_sds_remote_device *sci_dev,
2878         u16 node_id)
2879 {
2880         u32 remote_node_count = scic_sds_remote_device_node_count(sci_dev);
2881
2882         if (scic->device_table[node_id] == sci_dev) {
2883                 scic->device_table[node_id] = NULL;
2884
2885                 scic_sds_remote_node_table_release_remote_node_index(
2886                         &scic->available_remote_nodes, remote_node_count, node_id
2887                         );
2888         }
2889 }
2890
2891 /**
2892  * This method returns the union scu_remote_node_context for the specified remote
2893  *    node id.
2894  * @scic:
2895  * @node_id:
2896  *
2897  * union scu_remote_node_context*
2898  */
2899 union scu_remote_node_context *scic_sds_controller_get_remote_node_context_buffer(
2900         struct scic_sds_controller *scic,
2901         u16 node_id
2902         ) {
2903         if (
2904                 (node_id < scic->remote_node_entries)
2905                 && (scic->device_table[node_id] != NULL)
2906                 ) {
2907                 return &scic->remote_node_context_table[node_id];
2908         }
2909
2910         return NULL;
2911 }
2912
2913 /**
2914  *
2915  * @resposne_buffer: This is the buffer into which the D2H register FIS will be
2916  *    constructed.
2917  * @frame_header: This is the frame header returned by the hardware.
2918  * @frame_buffer: This is the frame buffer returned by the hardware.
2919  *
2920  * This method will combind the frame header and frame buffer to create a SATA
2921  * D2H register FIS none
2922  */
2923 void scic_sds_controller_copy_sata_response(
2924         void *response_buffer,
2925         void *frame_header,
2926         void *frame_buffer)
2927 {
2928         memcpy(response_buffer, frame_header, sizeof(u32));
2929
2930         memcpy(response_buffer + sizeof(u32),
2931                frame_buffer,
2932                sizeof(struct dev_to_host_fis) - sizeof(u32));
2933 }
2934
2935 /**
2936  * This method releases the frame once this is done the frame is available for
2937  *    re-use by the hardware.  The data contained in the frame header and frame
2938  *    buffer is no longer valid. The UF queue get pointer is only updated if UF
2939  *    control indicates this is appropriate.
2940  * @scic:
2941  * @frame_index:
2942  *
2943  */
2944 void scic_sds_controller_release_frame(
2945         struct scic_sds_controller *scic,
2946         u32 frame_index)
2947 {
2948         if (scic_sds_unsolicited_frame_control_release_frame(
2949                     &scic->uf_control, frame_index) == true)
2950                 writel(scic->uf_control.get,
2951                         &scic->scu_registers->sdma.unsolicited_frame_get_pointer);
2952 }
2953
2954 /**
2955  * scic_controller_start_io() - This method is called by the SCI user to
2956  *    send/start an IO request. If the method invocation is successful, then
2957  *    the IO request has been queued to the hardware for processing.
2958  * @controller: the handle to the controller object for which to start an IO
2959  *    request.
2960  * @remote_device: the handle to the remote device object for which to start an
2961  *    IO request.
2962  * @io_request: the handle to the io request object to start.
2963  * @io_tag: This parameter specifies a previously allocated IO tag that the
2964  *    user desires to be utilized for this request. This parameter is optional.
2965  *     The user is allowed to supply SCI_CONTROLLER_INVALID_IO_TAG as the value
2966  *    for this parameter.
2967  *
2968  * - IO tags are a protected resource.  It is incumbent upon the SCI Core user
2969  * to ensure that each of the methods that may allocate or free available IO
2970  * tags are handled in a mutually exclusive manner.  This method is one of said
2971  * methods requiring proper critical code section protection (e.g. semaphore,
2972  * spin-lock, etc.). - For SATA, the user is required to manage NCQ tags.  As a
2973  * result, it is expected the user will have set the NCQ tag field in the host
2974  * to device register FIS prior to calling this method.  There is also a
2975  * requirement for the user to call scic_stp_io_set_ncq_tag() prior to invoking
2976  * the scic_controller_start_io() method. scic_controller_allocate_tag() for
2977  * more information on allocating a tag. Indicate if the controller
2978  * successfully started the IO request. SCI_SUCCESS if the IO request was
2979  * successfully started. Determine the failure situations and return values.
2980  */
2981 enum sci_status scic_controller_start_io(
2982         struct scic_sds_controller *scic,
2983         struct scic_sds_remote_device *rdev,
2984         struct scic_sds_request *req,
2985         u16 io_tag)
2986 {
2987         enum sci_status status;
2988
2989         if (scic->sm.current_state_id != SCIC_READY) {
2990                 dev_warn(scic_to_dev(scic), "invalid state to start I/O");
2991                 return SCI_FAILURE_INVALID_STATE;
2992         }
2993
2994         status = scic_sds_remote_device_start_io(scic, rdev, req);
2995         if (status != SCI_SUCCESS)
2996                 return status;
2997
2998         scic->io_request_table[scic_sds_io_tag_get_index(req->io_tag)] = req;
2999         scic_sds_controller_post_request(scic, scic_sds_request_get_post_context(req));
3000         return SCI_SUCCESS;
3001 }
3002
3003 /**
3004  * scic_controller_terminate_request() - This method is called by the SCI Core
3005  *    user to terminate an ongoing (i.e. started) core IO request.  This does
3006  *    not abort the IO request at the target, but rather removes the IO request
3007  *    from the host controller.
3008  * @controller: the handle to the controller object for which to terminate a
3009  *    request.
3010  * @remote_device: the handle to the remote device object for which to
3011  *    terminate a request.
3012  * @request: the handle to the io or task management request object to
3013  *    terminate.
3014  *
3015  * Indicate if the controller successfully began the terminate process for the
3016  * IO request. SCI_SUCCESS if the terminate process was successfully started
3017  * for the request. Determine the failure situations and return values.
3018  */
3019 enum sci_status scic_controller_terminate_request(
3020         struct scic_sds_controller *scic,
3021         struct scic_sds_remote_device *rdev,
3022         struct scic_sds_request *req)
3023 {
3024         enum sci_status status;
3025
3026         if (scic->sm.current_state_id != SCIC_READY) {
3027                 dev_warn(scic_to_dev(scic),
3028                          "invalid state to terminate request\n");
3029                 return SCI_FAILURE_INVALID_STATE;
3030         }
3031
3032         status = scic_sds_io_request_terminate(req);
3033         if (status != SCI_SUCCESS)
3034                 return status;
3035
3036         /*
3037          * Utilize the original post context command and or in the POST_TC_ABORT
3038          * request sub-type.
3039          */
3040         scic_sds_controller_post_request(scic,
3041                 scic_sds_request_get_post_context(req) |
3042                 SCU_CONTEXT_COMMAND_REQUEST_POST_TC_ABORT);
3043         return SCI_SUCCESS;
3044 }
3045
3046 /**
3047  * scic_controller_complete_io() - This method will perform core specific
3048  *    completion operations for an IO request.  After this method is invoked,
3049  *    the user should consider the IO request as invalid until it is properly
3050  *    reused (i.e. re-constructed).
3051  * @controller: The handle to the controller object for which to complete the
3052  *    IO request.
3053  * @remote_device: The handle to the remote device object for which to complete
3054  *    the IO request.
3055  * @io_request: the handle to the io request object to complete.
3056  *
3057  * - IO tags are a protected resource.  It is incumbent upon the SCI Core user
3058  * to ensure that each of the methods that may allocate or free available IO
3059  * tags are handled in a mutually exclusive manner.  This method is one of said
3060  * methods requiring proper critical code section protection (e.g. semaphore,
3061  * spin-lock, etc.). - If the IO tag for a request was allocated, by the SCI
3062  * Core user, using the scic_controller_allocate_io_tag() method, then it is
3063  * the responsibility of the caller to invoke the scic_controller_free_io_tag()
3064  * method to free the tag (i.e. this method will not free the IO tag). Indicate
3065  * if the controller successfully completed the IO request. SCI_SUCCESS if the
3066  * completion process was successful.
3067  */
3068 enum sci_status scic_controller_complete_io(
3069         struct scic_sds_controller *scic,
3070         struct scic_sds_remote_device *rdev,
3071         struct scic_sds_request *request)
3072 {
3073         enum sci_status status;
3074         u16 index;
3075
3076         switch (scic->sm.current_state_id) {
3077         case SCIC_STOPPING:
3078                 /* XXX: Implement this function */
3079                 return SCI_FAILURE;
3080         case SCIC_READY:
3081                 status = scic_sds_remote_device_complete_io(scic, rdev, request);
3082                 if (status != SCI_SUCCESS)
3083                         return status;
3084
3085                 index = scic_sds_io_tag_get_index(request->io_tag);
3086                 scic->io_request_table[index] = NULL;
3087                 return SCI_SUCCESS;
3088         default:
3089                 dev_warn(scic_to_dev(scic), "invalid state to complete I/O");
3090                 return SCI_FAILURE_INVALID_STATE;
3091         }
3092
3093 }
3094
3095 enum sci_status scic_controller_continue_io(struct scic_sds_request *sci_req)
3096 {
3097         struct scic_sds_controller *scic = sci_req->owning_controller;
3098
3099         if (scic->sm.current_state_id != SCIC_READY) {
3100                 dev_warn(scic_to_dev(scic), "invalid state to continue I/O");
3101                 return SCI_FAILURE_INVALID_STATE;
3102         }
3103
3104         scic->io_request_table[scic_sds_io_tag_get_index(sci_req->io_tag)] = sci_req;
3105         scic_sds_controller_post_request(scic, scic_sds_request_get_post_context(sci_req));
3106         return SCI_SUCCESS;
3107 }
3108
3109 /**
3110  * scic_controller_start_task() - This method is called by the SCIC user to
3111  *    send/start a framework task management request.
3112  * @controller: the handle to the controller object for which to start the task
3113  *    management request.
3114  * @remote_device: the handle to the remote device object for which to start
3115  *    the task management request.
3116  * @task_request: the handle to the task request object to start.
3117  * @io_tag: This parameter specifies a previously allocated IO tag that the
3118  *    user desires to be utilized for this request.  Note this not the io_tag
3119  *    of the request being managed.  It is to be utilized for the task request
3120  *    itself. This parameter is optional.  The user is allowed to supply
3121  *    SCI_CONTROLLER_INVALID_IO_TAG as the value for this parameter.
3122  *
3123  * - IO tags are a protected resource.  It is incumbent upon the SCI Core user
3124  * to ensure that each of the methods that may allocate or free available IO
3125  * tags are handled in a mutually exclusive manner.  This method is one of said
3126  * methods requiring proper critical code section protection (e.g. semaphore,
3127  * spin-lock, etc.). - The user must synchronize this task with completion
3128  * queue processing.  If they are not synchronized then it is possible for the
3129  * io requests that are being managed by the task request can complete before
3130  * starting the task request. scic_controller_allocate_tag() for more
3131  * information on allocating a tag. Indicate if the controller successfully
3132  * started the IO request. SCI_TASK_SUCCESS if the task request was
3133  * successfully started. SCI_TASK_FAILURE_REQUIRES_SCSI_ABORT This value is
3134  * returned if there is/are task(s) outstanding that require termination or
3135  * completion before this request can succeed.
3136  */
3137 enum sci_task_status scic_controller_start_task(
3138         struct scic_sds_controller *scic,
3139         struct scic_sds_remote_device *rdev,
3140         struct scic_sds_request *req,
3141         u16 task_tag)
3142 {
3143         enum sci_status status;
3144
3145         if (scic->sm.current_state_id != SCIC_READY) {
3146                 dev_warn(scic_to_dev(scic),
3147                          "%s: SCIC Controller starting task from invalid "
3148                          "state\n",
3149                          __func__);
3150                 return SCI_TASK_FAILURE_INVALID_STATE;
3151         }
3152
3153         status = scic_sds_remote_device_start_task(scic, rdev, req);
3154         switch (status) {
3155         case SCI_FAILURE_RESET_DEVICE_PARTIAL_SUCCESS:
3156                 scic->io_request_table[scic_sds_io_tag_get_index(req->io_tag)] = req;
3157
3158                 /*
3159                  * We will let framework know this task request started successfully,
3160                  * although core is still woring on starting the request (to post tc when
3161                  * RNC is resumed.)
3162                  */
3163                 return SCI_SUCCESS;
3164         case SCI_SUCCESS:
3165                 scic->io_request_table[scic_sds_io_tag_get_index(req->io_tag)] = req;
3166
3167                 scic_sds_controller_post_request(scic,
3168                         scic_sds_request_get_post_context(req));
3169                 break;
3170         default:
3171                 break;
3172         }
3173
3174         return status;
3175 }
3176
3177 /**
3178  * scic_controller_allocate_io_tag() - This method will allocate a tag from the
3179  *    pool of free IO tags. Direct allocation of IO tags by the SCI Core user
3180  *    is optional. The scic_controller_start_io() method will allocate an IO
3181  *    tag if this method is not utilized and the tag is not supplied to the IO
3182  *    construct routine.  Direct allocation of IO tags may provide additional
3183  *    performance improvements in environments capable of supporting this usage
3184  *    model.  Additionally, direct allocation of IO tags also provides
3185  *    additional flexibility to the SCI Core user.  Specifically, the user may
3186  *    retain IO tags across the lives of multiple IO requests.
3187  * @controller: the handle to the controller object for which to allocate the
3188  *    tag.
3189  *
3190  * IO tags are a protected resource.  It is incumbent upon the SCI Core user to
3191  * ensure that each of the methods that may allocate or free available IO tags
3192  * are handled in a mutually exclusive manner.  This method is one of said
3193  * methods requiring proper critical code section protection (e.g. semaphore,
3194  * spin-lock, etc.). An unsigned integer representing an available IO tag.
3195  * SCI_CONTROLLER_INVALID_IO_TAG This value is returned if there are no
3196  * currently available tags to be allocated. All return other values indicate a
3197  * legitimate tag.
3198  */
3199 u16 scic_controller_allocate_io_tag(
3200         struct scic_sds_controller *scic)
3201 {
3202         u16 task_context;
3203         u16 sequence_count;
3204
3205         if (!sci_pool_empty(scic->tci_pool)) {
3206                 sci_pool_get(scic->tci_pool, task_context);
3207
3208                 sequence_count = scic->io_request_sequence[task_context];
3209
3210                 return scic_sds_io_tag_construct(sequence_count, task_context);
3211         }
3212
3213         return SCI_CONTROLLER_INVALID_IO_TAG;
3214 }
3215
3216 /**
3217  * scic_controller_free_io_tag() - This method will free an IO tag to the pool
3218  *    of free IO tags. This method provides the SCI Core user more flexibility
3219  *    with regards to IO tags.  The user may desire to keep an IO tag after an
3220  *    IO request has completed, because they plan on re-using the tag for a
3221  *    subsequent IO request.  This method is only legal if the tag was
3222  *    allocated via scic_controller_allocate_io_tag().
3223  * @controller: This parameter specifies the handle to the controller object
3224  *    for which to free/return the tag.
3225  * @io_tag: This parameter represents the tag to be freed to the pool of
3226  *    available tags.
3227  *
3228  * - IO tags are a protected resource.  It is incumbent upon the SCI Core user
3229  * to ensure that each of the methods that may allocate or free available IO
3230  * tags are handled in a mutually exclusive manner.  This method is one of said
3231  * methods requiring proper critical code section protection (e.g. semaphore,
3232  * spin-lock, etc.). - If the IO tag for a request was allocated, by the SCI
3233  * Core user, using the scic_controller_allocate_io_tag() method, then it is
3234  * the responsibility of the caller to invoke this method to free the tag. This
3235  * method returns an indication of whether the tag was successfully put back
3236  * (freed) to the pool of available tags. SCI_SUCCESS This return value
3237  * indicates the tag was successfully placed into the pool of available IO
3238  * tags. SCI_FAILURE_INVALID_IO_TAG This value is returned if the supplied tag
3239  * is not a valid IO tag value.
3240  */
3241 enum sci_status scic_controller_free_io_tag(
3242         struct scic_sds_controller *scic,
3243         u16 io_tag)
3244 {
3245         u16 sequence;
3246         u16 index;
3247
3248         BUG_ON(io_tag == SCI_CONTROLLER_INVALID_IO_TAG);
3249
3250         sequence = scic_sds_io_tag_get_sequence(io_tag);
3251         index    = scic_sds_io_tag_get_index(io_tag);
3252
3253         if (!sci_pool_full(scic->tci_pool)) {
3254                 if (sequence == scic->io_request_sequence[index]) {
3255                         scic_sds_io_sequence_increment(
3256                                 scic->io_request_sequence[index]);
3257
3258                         sci_pool_put(scic->tci_pool, index);
3259
3260                         return SCI_SUCCESS;
3261                 }
3262         }
3263
3264         return SCI_FAILURE_INVALID_IO_TAG;
3265 }
3266
3267