scsi: smartpqi: Align code with oob driver
[linux-2.6-block.git] / drivers / scsi / smartpqi / smartpqi_init.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *    driver for Microsemi PQI-based storage controllers
4  *    Copyright (c) 2019-2020 Microchip Technology Inc. and its subsidiaries
5  *    Copyright (c) 2016-2018 Microsemi Corporation
6  *    Copyright (c) 2016 PMC-Sierra, Inc.
7  *
8  *    Questions/Comments/Bugfixes to storagedev@microchip.com
9  *
10  */
11
12 #include <linux/module.h>
13 #include <linux/kernel.h>
14 #include <linux/pci.h>
15 #include <linux/delay.h>
16 #include <linux/interrupt.h>
17 #include <linux/sched.h>
18 #include <linux/rtc.h>
19 #include <linux/bcd.h>
20 #include <linux/reboot.h>
21 #include <linux/cciss_ioctl.h>
22 #include <linux/blk-mq-pci.h>
23 #include <scsi/scsi_host.h>
24 #include <scsi/scsi_cmnd.h>
25 #include <scsi/scsi_device.h>
26 #include <scsi/scsi_eh.h>
27 #include <scsi/scsi_transport_sas.h>
28 #include <asm/unaligned.h>
29 #include "smartpqi.h"
30 #include "smartpqi_sis.h"
31
32 #if !defined(BUILD_TIMESTAMP)
33 #define BUILD_TIMESTAMP
34 #endif
35
36 #define DRIVER_VERSION          "1.2.16-012"
37 #define DRIVER_MAJOR            1
38 #define DRIVER_MINOR            2
39 #define DRIVER_RELEASE          16
40 #define DRIVER_REVISION         12
41
42 #define DRIVER_NAME             "Microsemi PQI Driver (v" \
43                                 DRIVER_VERSION BUILD_TIMESTAMP ")"
44 #define DRIVER_NAME_SHORT       "smartpqi"
45
46 #define PQI_EXTRA_SGL_MEMORY    (12 * sizeof(struct pqi_sg_descriptor))
47
48 MODULE_AUTHOR("Microsemi");
49 MODULE_DESCRIPTION("Driver for Microsemi Smart Family Controller version "
50         DRIVER_VERSION);
51 MODULE_SUPPORTED_DEVICE("Microsemi Smart Family Controllers");
52 MODULE_VERSION(DRIVER_VERSION);
53 MODULE_LICENSE("GPL");
54
55 static void pqi_take_ctrl_offline(struct pqi_ctrl_info *ctrl_info);
56 static void pqi_ctrl_offline_worker(struct work_struct *work);
57 static void pqi_retry_raid_bypass_requests(struct pqi_ctrl_info *ctrl_info);
58 static int pqi_scan_scsi_devices(struct pqi_ctrl_info *ctrl_info);
59 static void pqi_scan_start(struct Scsi_Host *shost);
60 static void pqi_start_io(struct pqi_ctrl_info *ctrl_info,
61         struct pqi_queue_group *queue_group, enum pqi_io_path path,
62         struct pqi_io_request *io_request);
63 static int pqi_submit_raid_request_synchronous(struct pqi_ctrl_info *ctrl_info,
64         struct pqi_iu_header *request, unsigned int flags,
65         struct pqi_raid_error_info *error_info, unsigned long timeout_msecs);
66 static int pqi_aio_submit_io(struct pqi_ctrl_info *ctrl_info,
67         struct scsi_cmnd *scmd, u32 aio_handle, u8 *cdb,
68         unsigned int cdb_length, struct pqi_queue_group *queue_group,
69         struct pqi_encryption_info *encryption_info, bool raid_bypass);
70 static  int pqi_aio_submit_r1_write_io(struct pqi_ctrl_info *ctrl_info,
71         struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
72         struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
73         struct pqi_scsi_dev_raid_map_data *rmd);
74 static int pqi_aio_submit_r56_write_io(struct pqi_ctrl_info *ctrl_info,
75         struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
76         struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
77         struct pqi_scsi_dev_raid_map_data *rmd);
78 static void pqi_ofa_ctrl_quiesce(struct pqi_ctrl_info *ctrl_info);
79 static void pqi_ofa_ctrl_unquiesce(struct pqi_ctrl_info *ctrl_info);
80 static int pqi_ofa_ctrl_restart(struct pqi_ctrl_info *ctrl_info);
81 static void pqi_ofa_setup_host_buffer(struct pqi_ctrl_info *ctrl_info,
82         u32 bytes_requested);
83 static void pqi_ofa_free_host_buffer(struct pqi_ctrl_info *ctrl_info);
84 static int pqi_ofa_host_memory_update(struct pqi_ctrl_info *ctrl_info);
85 static int pqi_device_wait_for_pending_io(struct pqi_ctrl_info *ctrl_info,
86         struct pqi_scsi_dev *device, unsigned long timeout_secs);
87
88 /* for flags argument to pqi_submit_raid_request_synchronous() */
89 #define PQI_SYNC_FLAGS_INTERRUPTABLE    0x1
90
91 static struct scsi_transport_template *pqi_sas_transport_template;
92
93 static atomic_t pqi_controller_count = ATOMIC_INIT(0);
94
95 enum pqi_lockup_action {
96         NONE,
97         REBOOT,
98         PANIC
99 };
100
101 static enum pqi_lockup_action pqi_lockup_action = NONE;
102
103 static struct {
104         enum pqi_lockup_action  action;
105         char                    *name;
106 } pqi_lockup_actions[] = {
107         {
108                 .action = NONE,
109                 .name = "none",
110         },
111         {
112                 .action = REBOOT,
113                 .name = "reboot",
114         },
115         {
116                 .action = PANIC,
117                 .name = "panic",
118         },
119 };
120
121 static unsigned int pqi_supported_event_types[] = {
122         PQI_EVENT_TYPE_HOTPLUG,
123         PQI_EVENT_TYPE_HARDWARE,
124         PQI_EVENT_TYPE_PHYSICAL_DEVICE,
125         PQI_EVENT_TYPE_LOGICAL_DEVICE,
126         PQI_EVENT_TYPE_OFA,
127         PQI_EVENT_TYPE_AIO_STATE_CHANGE,
128         PQI_EVENT_TYPE_AIO_CONFIG_CHANGE,
129 };
130
131 static int pqi_disable_device_id_wildcards;
132 module_param_named(disable_device_id_wildcards,
133         pqi_disable_device_id_wildcards, int, 0644);
134 MODULE_PARM_DESC(disable_device_id_wildcards,
135         "Disable device ID wildcards.");
136
137 static int pqi_disable_heartbeat;
138 module_param_named(disable_heartbeat,
139         pqi_disable_heartbeat, int, 0644);
140 MODULE_PARM_DESC(disable_heartbeat,
141         "Disable heartbeat.");
142
143 static int pqi_disable_ctrl_shutdown;
144 module_param_named(disable_ctrl_shutdown,
145         pqi_disable_ctrl_shutdown, int, 0644);
146 MODULE_PARM_DESC(disable_ctrl_shutdown,
147         "Disable controller shutdown when controller locked up.");
148
149 static char *pqi_lockup_action_param;
150 module_param_named(lockup_action,
151         pqi_lockup_action_param, charp, 0644);
152 MODULE_PARM_DESC(lockup_action, "Action to take when controller locked up.\n"
153         "\t\tSupported: none, reboot, panic\n"
154         "\t\tDefault: none");
155
156 static int pqi_expose_ld_first;
157 module_param_named(expose_ld_first,
158         pqi_expose_ld_first, int, 0644);
159 MODULE_PARM_DESC(expose_ld_first, "Expose logical drives before physical drives.");
160
161 static int pqi_hide_vsep;
162 module_param_named(hide_vsep,
163         pqi_hide_vsep, int, 0644);
164 MODULE_PARM_DESC(hide_vsep, "Hide the virtual SEP for direct attached drives.");
165
166 static char *raid_levels[] = {
167         "RAID-0",
168         "RAID-4",
169         "RAID-1(1+0)",
170         "RAID-5",
171         "RAID-5+1",
172         "RAID-6",
173         "RAID-1(Triple)",
174 };
175
176 static char *pqi_raid_level_to_string(u8 raid_level)
177 {
178         if (raid_level < ARRAY_SIZE(raid_levels))
179                 return raid_levels[raid_level];
180
181         return "RAID UNKNOWN";
182 }
183
184 #define SA_RAID_0               0
185 #define SA_RAID_4               1
186 #define SA_RAID_1               2       /* also used for RAID 10 */
187 #define SA_RAID_5               3       /* also used for RAID 50 */
188 #define SA_RAID_51              4
189 #define SA_RAID_6               5       /* also used for RAID 60 */
190 #define SA_RAID_TRIPLE          6       /* also used for RAID 1+0 Triple */
191 #define SA_RAID_MAX             SA_RAID_TRIPLE
192 #define SA_RAID_UNKNOWN         0xff
193
194 static inline void pqi_scsi_done(struct scsi_cmnd *scmd)
195 {
196         pqi_prep_for_scsi_done(scmd);
197         scmd->scsi_done(scmd);
198 }
199
200 static inline void pqi_disable_write_same(struct scsi_device *sdev)
201 {
202         sdev->no_write_same = 1;
203 }
204
205 static inline bool pqi_scsi3addr_equal(u8 *scsi3addr1, u8 *scsi3addr2)
206 {
207         return memcmp(scsi3addr1, scsi3addr2, 8) == 0;
208 }
209
210 static inline bool pqi_is_logical_device(struct pqi_scsi_dev *device)
211 {
212         return !device->is_physical_device;
213 }
214
215 static inline bool pqi_is_external_raid_addr(u8 *scsi3addr)
216 {
217         return scsi3addr[2] != 0;
218 }
219
220 static inline bool pqi_ctrl_offline(struct pqi_ctrl_info *ctrl_info)
221 {
222         return !ctrl_info->controller_online;
223 }
224
225 static inline void pqi_check_ctrl_health(struct pqi_ctrl_info *ctrl_info)
226 {
227         if (ctrl_info->controller_online)
228                 if (!sis_is_firmware_running(ctrl_info))
229                         pqi_take_ctrl_offline(ctrl_info);
230 }
231
232 static inline bool pqi_is_hba_lunid(u8 *scsi3addr)
233 {
234         return pqi_scsi3addr_equal(scsi3addr, RAID_CTLR_LUNID);
235 }
236
237 static inline enum pqi_ctrl_mode pqi_get_ctrl_mode(struct pqi_ctrl_info *ctrl_info)
238 {
239         return sis_read_driver_scratch(ctrl_info);
240 }
241
242 static inline void pqi_save_ctrl_mode(struct pqi_ctrl_info *ctrl_info,
243         enum pqi_ctrl_mode mode)
244 {
245         sis_write_driver_scratch(ctrl_info, mode);
246 }
247
248 static inline void pqi_ctrl_block_device_reset(struct pqi_ctrl_info *ctrl_info)
249 {
250         ctrl_info->block_device_reset = true;
251 }
252
253 static inline bool pqi_device_reset_blocked(struct pqi_ctrl_info *ctrl_info)
254 {
255         return ctrl_info->block_device_reset;
256 }
257
258 static inline bool pqi_ctrl_blocked(struct pqi_ctrl_info *ctrl_info)
259 {
260         return ctrl_info->block_requests;
261 }
262
263 static inline void pqi_ctrl_block_requests(struct pqi_ctrl_info *ctrl_info)
264 {
265         ctrl_info->block_requests = true;
266         scsi_block_requests(ctrl_info->scsi_host);
267 }
268
269 static inline void pqi_ctrl_unblock_requests(struct pqi_ctrl_info *ctrl_info)
270 {
271         ctrl_info->block_requests = false;
272         wake_up_all(&ctrl_info->block_requests_wait);
273         pqi_retry_raid_bypass_requests(ctrl_info);
274         scsi_unblock_requests(ctrl_info->scsi_host);
275 }
276
277 static unsigned long pqi_wait_if_ctrl_blocked(struct pqi_ctrl_info *ctrl_info,
278         unsigned long timeout_msecs)
279 {
280         unsigned long remaining_msecs;
281
282         if (!pqi_ctrl_blocked(ctrl_info))
283                 return timeout_msecs;
284
285         atomic_inc(&ctrl_info->num_blocked_threads);
286
287         if (timeout_msecs == NO_TIMEOUT) {
288                 wait_event(ctrl_info->block_requests_wait,
289                         !pqi_ctrl_blocked(ctrl_info));
290                 remaining_msecs = timeout_msecs;
291         } else {
292                 unsigned long remaining_jiffies;
293
294                 remaining_jiffies =
295                         wait_event_timeout(ctrl_info->block_requests_wait,
296                                 !pqi_ctrl_blocked(ctrl_info),
297                                 msecs_to_jiffies(timeout_msecs));
298                 remaining_msecs = jiffies_to_msecs(remaining_jiffies);
299         }
300
301         atomic_dec(&ctrl_info->num_blocked_threads);
302
303         return remaining_msecs;
304 }
305
306 static inline void pqi_ctrl_wait_until_quiesced(struct pqi_ctrl_info *ctrl_info)
307 {
308         while (atomic_read(&ctrl_info->num_busy_threads) >
309                 atomic_read(&ctrl_info->num_blocked_threads))
310                 usleep_range(1000, 2000);
311 }
312
313 static inline bool pqi_device_offline(struct pqi_scsi_dev *device)
314 {
315         return device->device_offline;
316 }
317
318 static inline void pqi_device_reset_start(struct pqi_scsi_dev *device)
319 {
320         device->in_reset = true;
321 }
322
323 static inline void pqi_device_reset_done(struct pqi_scsi_dev *device)
324 {
325         device->in_reset = false;
326 }
327
328 static inline bool pqi_device_in_reset(struct pqi_scsi_dev *device)
329 {
330         return device->in_reset;
331 }
332
333 static inline void pqi_ctrl_ofa_start(struct pqi_ctrl_info *ctrl_info)
334 {
335         ctrl_info->in_ofa = true;
336 }
337
338 static inline void pqi_ctrl_ofa_done(struct pqi_ctrl_info *ctrl_info)
339 {
340         ctrl_info->in_ofa = false;
341 }
342
343 static inline bool pqi_ctrl_in_ofa(struct pqi_ctrl_info *ctrl_info)
344 {
345         return ctrl_info->in_ofa;
346 }
347
348 static inline void pqi_device_remove_start(struct pqi_scsi_dev *device)
349 {
350         device->in_remove = true;
351 }
352
353 static inline bool pqi_device_in_remove(struct pqi_scsi_dev *device)
354 {
355         return device->in_remove;
356 }
357
358 static inline void pqi_ctrl_shutdown_start(struct pqi_ctrl_info *ctrl_info)
359 {
360         ctrl_info->in_shutdown = true;
361 }
362
363 static inline bool pqi_ctrl_in_shutdown(struct pqi_ctrl_info *ctrl_info)
364 {
365         return ctrl_info->in_shutdown;
366 }
367
368 static inline void pqi_schedule_rescan_worker_with_delay(struct pqi_ctrl_info *ctrl_info,
369         unsigned long delay)
370 {
371         if (pqi_ctrl_offline(ctrl_info))
372                 return;
373         if (pqi_ctrl_in_ofa(ctrl_info))
374                 return;
375
376         schedule_delayed_work(&ctrl_info->rescan_work, delay);
377 }
378
379 static inline void pqi_schedule_rescan_worker(struct pqi_ctrl_info *ctrl_info)
380 {
381         pqi_schedule_rescan_worker_with_delay(ctrl_info, 0);
382 }
383
384 #define PQI_RESCAN_WORK_DELAY   (10 * PQI_HZ)
385
386 static inline void pqi_schedule_rescan_worker_delayed(struct pqi_ctrl_info *ctrl_info)
387 {
388         pqi_schedule_rescan_worker_with_delay(ctrl_info, PQI_RESCAN_WORK_DELAY);
389 }
390
391 static inline void pqi_cancel_rescan_worker(struct pqi_ctrl_info *ctrl_info)
392 {
393         cancel_delayed_work_sync(&ctrl_info->rescan_work);
394 }
395
396 static inline void pqi_cancel_event_worker(struct pqi_ctrl_info *ctrl_info)
397 {
398         cancel_work_sync(&ctrl_info->event_work);
399 }
400
401 static inline u32 pqi_read_heartbeat_counter(struct pqi_ctrl_info *ctrl_info)
402 {
403         if (!ctrl_info->heartbeat_counter)
404                 return 0;
405
406         return readl(ctrl_info->heartbeat_counter);
407 }
408
409 static inline u8 pqi_read_soft_reset_status(struct pqi_ctrl_info *ctrl_info)
410 {
411         if (!ctrl_info->soft_reset_status)
412                 return 0;
413
414         return readb(ctrl_info->soft_reset_status);
415 }
416
417 static inline void pqi_clear_soft_reset_status(struct pqi_ctrl_info *ctrl_info, u8 clear)
418 {
419         u8 status;
420
421         if (!ctrl_info->soft_reset_status)
422                 return;
423
424         status = pqi_read_soft_reset_status(ctrl_info);
425         status &= ~clear;
426         writeb(status, ctrl_info->soft_reset_status);
427 }
428
429 static int pqi_map_single(struct pci_dev *pci_dev,
430         struct pqi_sg_descriptor *sg_descriptor, void *buffer,
431         size_t buffer_length, enum dma_data_direction data_direction)
432 {
433         dma_addr_t bus_address;
434
435         if (!buffer || buffer_length == 0 || data_direction == DMA_NONE)
436                 return 0;
437
438         bus_address = dma_map_single(&pci_dev->dev, buffer, buffer_length,
439                 data_direction);
440         if (dma_mapping_error(&pci_dev->dev, bus_address))
441                 return -ENOMEM;
442
443         put_unaligned_le64((u64)bus_address, &sg_descriptor->address);
444         put_unaligned_le32(buffer_length, &sg_descriptor->length);
445         put_unaligned_le32(CISS_SG_LAST, &sg_descriptor->flags);
446
447         return 0;
448 }
449
450 static void pqi_pci_unmap(struct pci_dev *pci_dev,
451         struct pqi_sg_descriptor *descriptors, int num_descriptors,
452         enum dma_data_direction data_direction)
453 {
454         int i;
455
456         if (data_direction == DMA_NONE)
457                 return;
458
459         for (i = 0; i < num_descriptors; i++)
460                 dma_unmap_single(&pci_dev->dev,
461                         (dma_addr_t)get_unaligned_le64(&descriptors[i].address),
462                         get_unaligned_le32(&descriptors[i].length),
463                         data_direction);
464 }
465
466 static int pqi_build_raid_path_request(struct pqi_ctrl_info *ctrl_info,
467         struct pqi_raid_path_request *request, u8 cmd,
468         u8 *scsi3addr, void *buffer, size_t buffer_length,
469         u16 vpd_page, enum dma_data_direction *dir)
470 {
471         u8 *cdb;
472         size_t cdb_length = buffer_length;
473
474         memset(request, 0, sizeof(*request));
475
476         request->header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
477         put_unaligned_le16(offsetof(struct pqi_raid_path_request,
478                 sg_descriptors[1]) - PQI_REQUEST_HEADER_LENGTH,
479                 &request->header.iu_length);
480         put_unaligned_le32(buffer_length, &request->buffer_length);
481         memcpy(request->lun_number, scsi3addr, sizeof(request->lun_number));
482         request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
483         request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
484
485         cdb = request->cdb;
486
487         switch (cmd) {
488         case INQUIRY:
489                 request->data_direction = SOP_READ_FLAG;
490                 cdb[0] = INQUIRY;
491                 if (vpd_page & VPD_PAGE) {
492                         cdb[1] = 0x1;
493                         cdb[2] = (u8)vpd_page;
494                 }
495                 cdb[4] = (u8)cdb_length;
496                 break;
497         case CISS_REPORT_LOG:
498         case CISS_REPORT_PHYS:
499                 request->data_direction = SOP_READ_FLAG;
500                 cdb[0] = cmd;
501                 if (cmd == CISS_REPORT_PHYS)
502                         cdb[1] = CISS_REPORT_PHYS_FLAG_OTHER;
503                 else
504                         cdb[1] = ctrl_info->ciss_report_log_flags;
505                 put_unaligned_be32(cdb_length, &cdb[6]);
506                 break;
507         case CISS_GET_RAID_MAP:
508                 request->data_direction = SOP_READ_FLAG;
509                 cdb[0] = CISS_READ;
510                 cdb[1] = CISS_GET_RAID_MAP;
511                 put_unaligned_be32(cdb_length, &cdb[6]);
512                 break;
513         case SA_FLUSH_CACHE:
514                 request->data_direction = SOP_WRITE_FLAG;
515                 cdb[0] = BMIC_WRITE;
516                 cdb[6] = BMIC_FLUSH_CACHE;
517                 put_unaligned_be16(cdb_length, &cdb[7]);
518                 break;
519         case BMIC_SENSE_DIAG_OPTIONS:
520                 cdb_length = 0;
521                 fallthrough;
522         case BMIC_IDENTIFY_CONTROLLER:
523         case BMIC_IDENTIFY_PHYSICAL_DEVICE:
524         case BMIC_SENSE_SUBSYSTEM_INFORMATION:
525         case BMIC_SENSE_FEATURE:
526                 request->data_direction = SOP_READ_FLAG;
527                 cdb[0] = BMIC_READ;
528                 cdb[6] = cmd;
529                 put_unaligned_be16(cdb_length, &cdb[7]);
530                 break;
531         case BMIC_SET_DIAG_OPTIONS:
532                 cdb_length = 0;
533                 fallthrough;
534         case BMIC_WRITE_HOST_WELLNESS:
535                 request->data_direction = SOP_WRITE_FLAG;
536                 cdb[0] = BMIC_WRITE;
537                 cdb[6] = cmd;
538                 put_unaligned_be16(cdb_length, &cdb[7]);
539                 break;
540         case BMIC_CSMI_PASSTHRU:
541                 request->data_direction = SOP_BIDIRECTIONAL;
542                 cdb[0] = BMIC_WRITE;
543                 cdb[5] = CSMI_CC_SAS_SMP_PASSTHRU;
544                 cdb[6] = cmd;
545                 put_unaligned_be16(cdb_length, &cdb[7]);
546                 break;
547         default:
548                 dev_err(&ctrl_info->pci_dev->dev, "unknown command 0x%c\n", cmd);
549                 break;
550         }
551
552         switch (request->data_direction) {
553         case SOP_READ_FLAG:
554                 *dir = DMA_FROM_DEVICE;
555                 break;
556         case SOP_WRITE_FLAG:
557                 *dir = DMA_TO_DEVICE;
558                 break;
559         case SOP_NO_DIRECTION_FLAG:
560                 *dir = DMA_NONE;
561                 break;
562         default:
563                 *dir = DMA_BIDIRECTIONAL;
564                 break;
565         }
566
567         return pqi_map_single(ctrl_info->pci_dev, &request->sg_descriptors[0],
568                 buffer, buffer_length, *dir);
569 }
570
571 static inline void pqi_reinit_io_request(struct pqi_io_request *io_request)
572 {
573         io_request->scmd = NULL;
574         io_request->status = 0;
575         io_request->error_info = NULL;
576         io_request->raid_bypass = false;
577 }
578
579 static struct pqi_io_request *pqi_alloc_io_request(
580         struct pqi_ctrl_info *ctrl_info)
581 {
582         struct pqi_io_request *io_request;
583         u16 i = ctrl_info->next_io_request_slot;        /* benignly racy */
584
585         while (1) {
586                 io_request = &ctrl_info->io_request_pool[i];
587                 if (atomic_inc_return(&io_request->refcount) == 1)
588                         break;
589                 atomic_dec(&io_request->refcount);
590                 i = (i + 1) % ctrl_info->max_io_slots;
591         }
592
593         /* benignly racy */
594         ctrl_info->next_io_request_slot = (i + 1) % ctrl_info->max_io_slots;
595
596         pqi_reinit_io_request(io_request);
597
598         return io_request;
599 }
600
601 static void pqi_free_io_request(struct pqi_io_request *io_request)
602 {
603         atomic_dec(&io_request->refcount);
604 }
605
606 static int pqi_send_scsi_raid_request(struct pqi_ctrl_info *ctrl_info, u8 cmd,
607         u8 *scsi3addr, void *buffer, size_t buffer_length, u16 vpd_page,
608         struct pqi_raid_error_info *error_info, unsigned long timeout_msecs)
609 {
610         int rc;
611         struct pqi_raid_path_request request;
612         enum dma_data_direction dir;
613
614         rc = pqi_build_raid_path_request(ctrl_info, &request, cmd, scsi3addr,
615                 buffer, buffer_length, vpd_page, &dir);
616         if (rc)
617                 return rc;
618
619         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0,
620                 error_info, timeout_msecs);
621
622         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1, dir);
623
624         return rc;
625 }
626
627 /* helper functions for pqi_send_scsi_raid_request */
628
629 static inline int pqi_send_ctrl_raid_request(struct pqi_ctrl_info *ctrl_info,
630         u8 cmd, void *buffer, size_t buffer_length)
631 {
632         return pqi_send_scsi_raid_request(ctrl_info, cmd, RAID_CTLR_LUNID,
633                 buffer, buffer_length, 0, NULL, NO_TIMEOUT);
634 }
635
636 static inline int pqi_send_ctrl_raid_with_error(struct pqi_ctrl_info *ctrl_info,
637         u8 cmd, void *buffer, size_t buffer_length,
638         struct pqi_raid_error_info *error_info)
639 {
640         return pqi_send_scsi_raid_request(ctrl_info, cmd, RAID_CTLR_LUNID,
641                 buffer, buffer_length, 0, error_info, NO_TIMEOUT);
642 }
643
644 static inline int pqi_identify_controller(struct pqi_ctrl_info *ctrl_info,
645         struct bmic_identify_controller *buffer)
646 {
647         return pqi_send_ctrl_raid_request(ctrl_info, BMIC_IDENTIFY_CONTROLLER,
648                 buffer, sizeof(*buffer));
649 }
650
651 static inline int pqi_sense_subsystem_info(struct  pqi_ctrl_info *ctrl_info,
652         struct bmic_sense_subsystem_info *sense_info)
653 {
654         return pqi_send_ctrl_raid_request(ctrl_info,
655                 BMIC_SENSE_SUBSYSTEM_INFORMATION, sense_info,
656                 sizeof(*sense_info));
657 }
658
659 static inline int pqi_scsi_inquiry(struct pqi_ctrl_info *ctrl_info,
660         u8 *scsi3addr, u16 vpd_page, void *buffer, size_t buffer_length)
661 {
662         return pqi_send_scsi_raid_request(ctrl_info, INQUIRY, scsi3addr,
663                 buffer, buffer_length, vpd_page, NULL, NO_TIMEOUT);
664 }
665
666 static int pqi_identify_physical_device(struct pqi_ctrl_info *ctrl_info,
667         struct pqi_scsi_dev *device,
668         struct bmic_identify_physical_device *buffer, size_t buffer_length)
669 {
670         int rc;
671         enum dma_data_direction dir;
672         u16 bmic_device_index;
673         struct pqi_raid_path_request request;
674
675         rc = pqi_build_raid_path_request(ctrl_info, &request,
676                 BMIC_IDENTIFY_PHYSICAL_DEVICE, RAID_CTLR_LUNID, buffer,
677                 buffer_length, 0, &dir);
678         if (rc)
679                 return rc;
680
681         bmic_device_index = CISS_GET_DRIVE_NUMBER(device->scsi3addr);
682         request.cdb[2] = (u8)bmic_device_index;
683         request.cdb[9] = (u8)(bmic_device_index >> 8);
684
685         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
686                 0, NULL, NO_TIMEOUT);
687
688         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1, dir);
689
690         return rc;
691 }
692
693 static inline u32 pqi_aio_limit_to_bytes(__le16 *limit)
694 {
695         u32 bytes;
696
697         bytes = get_unaligned_le16(limit);
698         if (bytes == 0)
699                 bytes = ~0;
700         else
701                 bytes *= 1024;
702
703         return bytes;
704 }
705
706 #pragma pack(1)
707
708 struct bmic_sense_feature_buffer {
709         struct bmic_sense_feature_buffer_header header;
710         struct bmic_sense_feature_io_page_aio_subpage aio_subpage;
711 };
712
713 #pragma pack()
714
715 #define MINIMUM_AIO_SUBPAGE_BUFFER_LENGTH       \
716         offsetofend(struct bmic_sense_feature_buffer, \
717                 aio_subpage.max_write_raid_1_10_3drive)
718
719 #define MINIMUM_AIO_SUBPAGE_LENGTH      \
720         (offsetofend(struct bmic_sense_feature_io_page_aio_subpage, \
721                 max_write_raid_1_10_3drive) - \
722                 sizeof_field(struct bmic_sense_feature_io_page_aio_subpage, header))
723
724 static int pqi_get_advanced_raid_bypass_config(struct pqi_ctrl_info *ctrl_info)
725 {
726         int rc;
727         enum dma_data_direction dir;
728         struct pqi_raid_path_request request;
729         struct bmic_sense_feature_buffer *buffer;
730
731         buffer = kmalloc(sizeof(*buffer), GFP_KERNEL);
732         if (!buffer)
733                 return -ENOMEM;
734
735         rc = pqi_build_raid_path_request(ctrl_info, &request, BMIC_SENSE_FEATURE, RAID_CTLR_LUNID,
736                 buffer, sizeof(*buffer), 0, &dir);
737         if (rc)
738                 goto error;
739
740         request.cdb[2] = BMIC_SENSE_FEATURE_IO_PAGE;
741         request.cdb[3] = BMIC_SENSE_FEATURE_IO_PAGE_AIO_SUBPAGE;
742
743         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, NULL, NO_TIMEOUT);
744
745         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1, dir);
746
747         if (rc)
748                 goto error;
749
750         if (buffer->header.page_code != BMIC_SENSE_FEATURE_IO_PAGE ||
751                 buffer->header.subpage_code !=
752                         BMIC_SENSE_FEATURE_IO_PAGE_AIO_SUBPAGE ||
753                 get_unaligned_le16(&buffer->header.buffer_length) <
754                         MINIMUM_AIO_SUBPAGE_BUFFER_LENGTH ||
755                 buffer->aio_subpage.header.page_code !=
756                         BMIC_SENSE_FEATURE_IO_PAGE ||
757                 buffer->aio_subpage.header.subpage_code !=
758                         BMIC_SENSE_FEATURE_IO_PAGE_AIO_SUBPAGE ||
759                 get_unaligned_le16(&buffer->aio_subpage.header.page_length) <
760                         MINIMUM_AIO_SUBPAGE_LENGTH) {
761                 goto error;
762         }
763
764         ctrl_info->max_transfer_encrypted_sas_sata =
765                 pqi_aio_limit_to_bytes(
766                         &buffer->aio_subpage.max_transfer_encrypted_sas_sata);
767
768         ctrl_info->max_transfer_encrypted_nvme =
769                 pqi_aio_limit_to_bytes(
770                         &buffer->aio_subpage.max_transfer_encrypted_nvme);
771
772         ctrl_info->max_write_raid_5_6 =
773                 pqi_aio_limit_to_bytes(
774                         &buffer->aio_subpage.max_write_raid_5_6);
775
776         ctrl_info->max_write_raid_1_10_2drive =
777                 pqi_aio_limit_to_bytes(
778                         &buffer->aio_subpage.max_write_raid_1_10_2drive);
779
780         ctrl_info->max_write_raid_1_10_3drive =
781                 pqi_aio_limit_to_bytes(
782                         &buffer->aio_subpage.max_write_raid_1_10_3drive);
783
784 error:
785         kfree(buffer);
786
787         return rc;
788 }
789
790 static int pqi_flush_cache(struct pqi_ctrl_info *ctrl_info,
791         enum bmic_flush_cache_shutdown_event shutdown_event)
792 {
793         int rc;
794         struct bmic_flush_cache *flush_cache;
795
796         /*
797          * Don't bother trying to flush the cache if the controller is
798          * locked up.
799          */
800         if (pqi_ctrl_offline(ctrl_info))
801                 return -ENXIO;
802
803         flush_cache = kzalloc(sizeof(*flush_cache), GFP_KERNEL);
804         if (!flush_cache)
805                 return -ENOMEM;
806
807         flush_cache->shutdown_event = shutdown_event;
808
809         rc = pqi_send_ctrl_raid_request(ctrl_info, SA_FLUSH_CACHE, flush_cache,
810                 sizeof(*flush_cache));
811
812         kfree(flush_cache);
813
814         return rc;
815 }
816
817 int pqi_csmi_smp_passthru(struct pqi_ctrl_info *ctrl_info,
818         struct bmic_csmi_smp_passthru_buffer *buffer, size_t buffer_length,
819         struct pqi_raid_error_info *error_info)
820 {
821         return pqi_send_ctrl_raid_with_error(ctrl_info, BMIC_CSMI_PASSTHRU,
822                 buffer, buffer_length, error_info);
823 }
824
825 #define PQI_FETCH_PTRAID_DATA           (1 << 31)
826
827 static int pqi_set_diag_rescan(struct pqi_ctrl_info *ctrl_info)
828 {
829         int rc;
830         struct bmic_diag_options *diag;
831
832         diag = kzalloc(sizeof(*diag), GFP_KERNEL);
833         if (!diag)
834                 return -ENOMEM;
835
836         rc = pqi_send_ctrl_raid_request(ctrl_info, BMIC_SENSE_DIAG_OPTIONS,
837                 diag, sizeof(*diag));
838         if (rc)
839                 goto out;
840
841         diag->options |= cpu_to_le32(PQI_FETCH_PTRAID_DATA);
842
843         rc = pqi_send_ctrl_raid_request(ctrl_info, BMIC_SET_DIAG_OPTIONS, diag,
844                 sizeof(*diag));
845
846 out:
847         kfree(diag);
848
849         return rc;
850 }
851
852 static inline int pqi_write_host_wellness(struct pqi_ctrl_info *ctrl_info,
853         void *buffer, size_t buffer_length)
854 {
855         return pqi_send_ctrl_raid_request(ctrl_info, BMIC_WRITE_HOST_WELLNESS,
856                 buffer, buffer_length);
857 }
858
859 #pragma pack(1)
860
861 struct bmic_host_wellness_driver_version {
862         u8      start_tag[4];
863         u8      driver_version_tag[2];
864         __le16  driver_version_length;
865         char    driver_version[32];
866         u8      dont_write_tag[2];
867         u8      end_tag[2];
868 };
869
870 #pragma pack()
871
872 static int pqi_write_driver_version_to_host_wellness(
873         struct pqi_ctrl_info *ctrl_info)
874 {
875         int rc;
876         struct bmic_host_wellness_driver_version *buffer;
877         size_t buffer_length;
878
879         buffer_length = sizeof(*buffer);
880
881         buffer = kmalloc(buffer_length, GFP_KERNEL);
882         if (!buffer)
883                 return -ENOMEM;
884
885         buffer->start_tag[0] = '<';
886         buffer->start_tag[1] = 'H';
887         buffer->start_tag[2] = 'W';
888         buffer->start_tag[3] = '>';
889         buffer->driver_version_tag[0] = 'D';
890         buffer->driver_version_tag[1] = 'V';
891         put_unaligned_le16(sizeof(buffer->driver_version),
892                 &buffer->driver_version_length);
893         strncpy(buffer->driver_version, "Linux " DRIVER_VERSION,
894                 sizeof(buffer->driver_version) - 1);
895         buffer->driver_version[sizeof(buffer->driver_version) - 1] = '\0';
896         buffer->dont_write_tag[0] = 'D';
897         buffer->dont_write_tag[1] = 'W';
898         buffer->end_tag[0] = 'Z';
899         buffer->end_tag[1] = 'Z';
900
901         rc = pqi_write_host_wellness(ctrl_info, buffer, buffer_length);
902
903         kfree(buffer);
904
905         return rc;
906 }
907
908 #pragma pack(1)
909
910 struct bmic_host_wellness_time {
911         u8      start_tag[4];
912         u8      time_tag[2];
913         __le16  time_length;
914         u8      time[8];
915         u8      dont_write_tag[2];
916         u8      end_tag[2];
917 };
918
919 #pragma pack()
920
921 static int pqi_write_current_time_to_host_wellness(
922         struct pqi_ctrl_info *ctrl_info)
923 {
924         int rc;
925         struct bmic_host_wellness_time *buffer;
926         size_t buffer_length;
927         time64_t local_time;
928         unsigned int year;
929         struct tm tm;
930
931         buffer_length = sizeof(*buffer);
932
933         buffer = kmalloc(buffer_length, GFP_KERNEL);
934         if (!buffer)
935                 return -ENOMEM;
936
937         buffer->start_tag[0] = '<';
938         buffer->start_tag[1] = 'H';
939         buffer->start_tag[2] = 'W';
940         buffer->start_tag[3] = '>';
941         buffer->time_tag[0] = 'T';
942         buffer->time_tag[1] = 'D';
943         put_unaligned_le16(sizeof(buffer->time),
944                 &buffer->time_length);
945
946         local_time = ktime_get_real_seconds();
947         time64_to_tm(local_time, -sys_tz.tz_minuteswest * 60, &tm);
948         year = tm.tm_year + 1900;
949
950         buffer->time[0] = bin2bcd(tm.tm_hour);
951         buffer->time[1] = bin2bcd(tm.tm_min);
952         buffer->time[2] = bin2bcd(tm.tm_sec);
953         buffer->time[3] = 0;
954         buffer->time[4] = bin2bcd(tm.tm_mon + 1);
955         buffer->time[5] = bin2bcd(tm.tm_mday);
956         buffer->time[6] = bin2bcd(year / 100);
957         buffer->time[7] = bin2bcd(year % 100);
958
959         buffer->dont_write_tag[0] = 'D';
960         buffer->dont_write_tag[1] = 'W';
961         buffer->end_tag[0] = 'Z';
962         buffer->end_tag[1] = 'Z';
963
964         rc = pqi_write_host_wellness(ctrl_info, buffer, buffer_length);
965
966         kfree(buffer);
967
968         return rc;
969 }
970
971 #define PQI_UPDATE_TIME_WORK_INTERVAL   (24UL * 60 * 60 * PQI_HZ)
972
973 static void pqi_update_time_worker(struct work_struct *work)
974 {
975         int rc;
976         struct pqi_ctrl_info *ctrl_info;
977
978         ctrl_info = container_of(to_delayed_work(work), struct pqi_ctrl_info,
979                 update_time_work);
980
981         if (pqi_ctrl_offline(ctrl_info))
982                 return;
983
984         rc = pqi_write_current_time_to_host_wellness(ctrl_info);
985         if (rc)
986                 dev_warn(&ctrl_info->pci_dev->dev,
987                         "error updating time on controller\n");
988
989         schedule_delayed_work(&ctrl_info->update_time_work,
990                 PQI_UPDATE_TIME_WORK_INTERVAL);
991 }
992
993 static inline void pqi_schedule_update_time_worker(struct pqi_ctrl_info *ctrl_info)
994 {
995         schedule_delayed_work(&ctrl_info->update_time_work, 0);
996 }
997
998 static inline void pqi_cancel_update_time_worker(struct pqi_ctrl_info *ctrl_info)
999 {
1000         cancel_delayed_work_sync(&ctrl_info->update_time_work);
1001 }
1002
1003 static inline int pqi_report_luns(struct pqi_ctrl_info *ctrl_info, u8 cmd, void *buffer,
1004         size_t buffer_length)
1005 {
1006         return pqi_send_ctrl_raid_request(ctrl_info, cmd, buffer, buffer_length);
1007 }
1008
1009 static int pqi_report_phys_logical_luns(struct pqi_ctrl_info *ctrl_info, u8 cmd, void **buffer)
1010 {
1011         int rc;
1012         size_t lun_list_length;
1013         size_t lun_data_length;
1014         size_t new_lun_list_length;
1015         void *lun_data = NULL;
1016         struct report_lun_header *report_lun_header;
1017
1018         report_lun_header = kmalloc(sizeof(*report_lun_header), GFP_KERNEL);
1019         if (!report_lun_header) {
1020                 rc = -ENOMEM;
1021                 goto out;
1022         }
1023
1024         rc = pqi_report_luns(ctrl_info, cmd, report_lun_header, sizeof(*report_lun_header));
1025         if (rc)
1026                 goto out;
1027
1028         lun_list_length = get_unaligned_be32(&report_lun_header->list_length);
1029
1030 again:
1031         lun_data_length = sizeof(struct report_lun_header) + lun_list_length;
1032
1033         lun_data = kmalloc(lun_data_length, GFP_KERNEL);
1034         if (!lun_data) {
1035                 rc = -ENOMEM;
1036                 goto out;
1037         }
1038
1039         if (lun_list_length == 0) {
1040                 memcpy(lun_data, report_lun_header, sizeof(*report_lun_header));
1041                 goto out;
1042         }
1043
1044         rc = pqi_report_luns(ctrl_info, cmd, lun_data, lun_data_length);
1045         if (rc)
1046                 goto out;
1047
1048         new_lun_list_length =
1049                 get_unaligned_be32(&((struct report_lun_header *)lun_data)->list_length);
1050
1051         if (new_lun_list_length > lun_list_length) {
1052                 lun_list_length = new_lun_list_length;
1053                 kfree(lun_data);
1054                 goto again;
1055         }
1056
1057 out:
1058         kfree(report_lun_header);
1059
1060         if (rc) {
1061                 kfree(lun_data);
1062                 lun_data = NULL;
1063         }
1064
1065         *buffer = lun_data;
1066
1067         return rc;
1068 }
1069
1070 static inline int pqi_report_phys_luns(struct pqi_ctrl_info *ctrl_info, void **buffer)
1071 {
1072         return pqi_report_phys_logical_luns(ctrl_info, CISS_REPORT_PHYS, buffer);
1073 }
1074
1075 static inline int pqi_report_logical_luns(struct pqi_ctrl_info *ctrl_info, void **buffer)
1076 {
1077         return pqi_report_phys_logical_luns(ctrl_info, CISS_REPORT_LOG, buffer);
1078 }
1079
1080 static int pqi_get_device_lists(struct pqi_ctrl_info *ctrl_info,
1081         struct report_phys_lun_extended **physdev_list,
1082         struct report_log_lun_extended **logdev_list)
1083 {
1084         int rc;
1085         size_t logdev_list_length;
1086         size_t logdev_data_length;
1087         struct report_log_lun_extended *internal_logdev_list;
1088         struct report_log_lun_extended *logdev_data;
1089         struct report_lun_header report_lun_header;
1090
1091         rc = pqi_report_phys_luns(ctrl_info, (void **)physdev_list);
1092         if (rc)
1093                 dev_err(&ctrl_info->pci_dev->dev,
1094                         "report physical LUNs failed\n");
1095
1096         rc = pqi_report_logical_luns(ctrl_info, (void **)logdev_list);
1097         if (rc)
1098                 dev_err(&ctrl_info->pci_dev->dev,
1099                         "report logical LUNs failed\n");
1100
1101         /*
1102          * Tack the controller itself onto the end of the logical device list.
1103          */
1104
1105         logdev_data = *logdev_list;
1106
1107         if (logdev_data) {
1108                 logdev_list_length =
1109                         get_unaligned_be32(&logdev_data->header.list_length);
1110         } else {
1111                 memset(&report_lun_header, 0, sizeof(report_lun_header));
1112                 logdev_data =
1113                         (struct report_log_lun_extended *)&report_lun_header;
1114                 logdev_list_length = 0;
1115         }
1116
1117         logdev_data_length = sizeof(struct report_lun_header) +
1118                 logdev_list_length;
1119
1120         internal_logdev_list = kmalloc(logdev_data_length +
1121                 sizeof(struct report_log_lun_extended), GFP_KERNEL);
1122         if (!internal_logdev_list) {
1123                 kfree(*logdev_list);
1124                 *logdev_list = NULL;
1125                 return -ENOMEM;
1126         }
1127
1128         memcpy(internal_logdev_list, logdev_data, logdev_data_length);
1129         memset((u8 *)internal_logdev_list + logdev_data_length, 0,
1130                 sizeof(struct report_log_lun_extended_entry));
1131         put_unaligned_be32(logdev_list_length +
1132                 sizeof(struct report_log_lun_extended_entry),
1133                 &internal_logdev_list->header.list_length);
1134
1135         kfree(*logdev_list);
1136         *logdev_list = internal_logdev_list;
1137
1138         return 0;
1139 }
1140
1141 static inline void pqi_set_bus_target_lun(struct pqi_scsi_dev *device,
1142         int bus, int target, int lun)
1143 {
1144         device->bus = bus;
1145         device->target = target;
1146         device->lun = lun;
1147 }
1148
1149 static void pqi_assign_bus_target_lun(struct pqi_scsi_dev *device)
1150 {
1151         u8 *scsi3addr;
1152         u32 lunid;
1153         int bus;
1154         int target;
1155         int lun;
1156
1157         scsi3addr = device->scsi3addr;
1158         lunid = get_unaligned_le32(scsi3addr);
1159
1160         if (pqi_is_hba_lunid(scsi3addr)) {
1161                 /* The specified device is the controller. */
1162                 pqi_set_bus_target_lun(device, PQI_HBA_BUS, 0, lunid & 0x3fff);
1163                 device->target_lun_valid = true;
1164                 return;
1165         }
1166
1167         if (pqi_is_logical_device(device)) {
1168                 if (device->is_external_raid_device) {
1169                         bus = PQI_EXTERNAL_RAID_VOLUME_BUS;
1170                         target = (lunid >> 16) & 0x3fff;
1171                         lun = lunid & 0xff;
1172                 } else {
1173                         bus = PQI_RAID_VOLUME_BUS;
1174                         target = 0;
1175                         lun = lunid & 0x3fff;
1176                 }
1177                 pqi_set_bus_target_lun(device, bus, target, lun);
1178                 device->target_lun_valid = true;
1179                 return;
1180         }
1181
1182         /*
1183          * Defer target and LUN assignment for non-controller physical devices
1184          * because the SAS transport layer will make these assignments later.
1185          */
1186         pqi_set_bus_target_lun(device, PQI_PHYSICAL_DEVICE_BUS, 0, 0);
1187 }
1188
1189 static void pqi_get_raid_level(struct pqi_ctrl_info *ctrl_info,
1190         struct pqi_scsi_dev *device)
1191 {
1192         int rc;
1193         u8 raid_level;
1194         u8 *buffer;
1195
1196         raid_level = SA_RAID_UNKNOWN;
1197
1198         buffer = kmalloc(64, GFP_KERNEL);
1199         if (buffer) {
1200                 rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1201                         VPD_PAGE | CISS_VPD_LV_DEVICE_GEOMETRY, buffer, 64);
1202                 if (rc == 0) {
1203                         raid_level = buffer[8];
1204                         if (raid_level > SA_RAID_MAX)
1205                                 raid_level = SA_RAID_UNKNOWN;
1206                 }
1207                 kfree(buffer);
1208         }
1209
1210         device->raid_level = raid_level;
1211 }
1212
1213 static int pqi_validate_raid_map(struct pqi_ctrl_info *ctrl_info,
1214         struct pqi_scsi_dev *device, struct raid_map *raid_map)
1215 {
1216         char *err_msg;
1217         u32 raid_map_size;
1218         u32 r5or6_blocks_per_row;
1219
1220         raid_map_size = get_unaligned_le32(&raid_map->structure_size);
1221
1222         if (raid_map_size < offsetof(struct raid_map, disk_data)) {
1223                 err_msg = "RAID map too small";
1224                 goto bad_raid_map;
1225         }
1226
1227         if (device->raid_level == SA_RAID_1) {
1228                 if (get_unaligned_le16(&raid_map->layout_map_count) != 2) {
1229                         err_msg = "invalid RAID-1 map";
1230                         goto bad_raid_map;
1231                 }
1232         } else if (device->raid_level == SA_RAID_TRIPLE) {
1233                 if (get_unaligned_le16(&raid_map->layout_map_count) != 3) {
1234                         err_msg = "invalid RAID-1(Triple) map";
1235                         goto bad_raid_map;
1236                 }
1237         } else if ((device->raid_level == SA_RAID_5 ||
1238                 device->raid_level == SA_RAID_6) &&
1239                 get_unaligned_le16(&raid_map->layout_map_count) > 1) {
1240                 /* RAID 50/60 */
1241                 r5or6_blocks_per_row =
1242                         get_unaligned_le16(&raid_map->strip_size) *
1243                         get_unaligned_le16(&raid_map->data_disks_per_row);
1244                 if (r5or6_blocks_per_row == 0) {
1245                         err_msg = "invalid RAID-5 or RAID-6 map";
1246                         goto bad_raid_map;
1247                 }
1248         }
1249
1250         return 0;
1251
1252 bad_raid_map:
1253         dev_warn(&ctrl_info->pci_dev->dev,
1254                 "logical device %08x%08x %s\n",
1255                 *((u32 *)&device->scsi3addr),
1256                 *((u32 *)&device->scsi3addr[4]), err_msg);
1257
1258         return -EINVAL;
1259 }
1260
1261 static int pqi_get_raid_map(struct pqi_ctrl_info *ctrl_info,
1262         struct pqi_scsi_dev *device)
1263 {
1264         int rc;
1265         u32 raid_map_size;
1266         struct raid_map *raid_map;
1267
1268         raid_map = kmalloc(sizeof(*raid_map), GFP_KERNEL);
1269         if (!raid_map)
1270                 return -ENOMEM;
1271
1272         rc = pqi_send_scsi_raid_request(ctrl_info, CISS_GET_RAID_MAP,
1273                 device->scsi3addr, raid_map, sizeof(*raid_map),
1274                 0, NULL, NO_TIMEOUT);
1275
1276         if (rc)
1277                 goto error;
1278
1279         raid_map_size = get_unaligned_le32(&raid_map->structure_size);
1280
1281         if (raid_map_size > sizeof(*raid_map)) {
1282
1283                 kfree(raid_map);
1284
1285                 raid_map = kmalloc(raid_map_size, GFP_KERNEL);
1286                 if (!raid_map)
1287                         return -ENOMEM;
1288
1289                 rc = pqi_send_scsi_raid_request(ctrl_info, CISS_GET_RAID_MAP,
1290                         device->scsi3addr, raid_map, raid_map_size,
1291                         0, NULL, NO_TIMEOUT);
1292                 if (rc)
1293                         goto error;
1294
1295                 if (get_unaligned_le32(&raid_map->structure_size)
1296                         != raid_map_size) {
1297                         dev_warn(&ctrl_info->pci_dev->dev,
1298                                 "requested %u bytes, received %u bytes\n",
1299                                 raid_map_size,
1300                                 get_unaligned_le32(&raid_map->structure_size));
1301                         goto error;
1302                 }
1303         }
1304
1305         rc = pqi_validate_raid_map(ctrl_info, device, raid_map);
1306         if (rc)
1307                 goto error;
1308
1309         device->raid_map = raid_map;
1310
1311         return 0;
1312
1313 error:
1314         kfree(raid_map);
1315
1316         return rc;
1317 }
1318
1319 static void pqi_set_max_transfer_encrypted(struct pqi_ctrl_info *ctrl_info,
1320         struct pqi_scsi_dev *device)
1321 {
1322         if (!ctrl_info->lv_drive_type_mix_valid) {
1323                 device->max_transfer_encrypted = ~0;
1324                 return;
1325         }
1326
1327         switch (LV_GET_DRIVE_TYPE_MIX(device->scsi3addr)) {
1328         case LV_DRIVE_TYPE_MIX_SAS_HDD_ONLY:
1329         case LV_DRIVE_TYPE_MIX_SATA_HDD_ONLY:
1330         case LV_DRIVE_TYPE_MIX_SAS_OR_SATA_SSD_ONLY:
1331         case LV_DRIVE_TYPE_MIX_SAS_SSD_ONLY:
1332         case LV_DRIVE_TYPE_MIX_SATA_SSD_ONLY:
1333         case LV_DRIVE_TYPE_MIX_SAS_ONLY:
1334         case LV_DRIVE_TYPE_MIX_SATA_ONLY:
1335                 device->max_transfer_encrypted =
1336                         ctrl_info->max_transfer_encrypted_sas_sata;
1337                 break;
1338         case LV_DRIVE_TYPE_MIX_NVME_ONLY:
1339                 device->max_transfer_encrypted =
1340                         ctrl_info->max_transfer_encrypted_nvme;
1341                 break;
1342         case LV_DRIVE_TYPE_MIX_UNKNOWN:
1343         case LV_DRIVE_TYPE_MIX_NO_RESTRICTION:
1344         default:
1345                 device->max_transfer_encrypted =
1346                         min(ctrl_info->max_transfer_encrypted_sas_sata,
1347                                 ctrl_info->max_transfer_encrypted_nvme);
1348                 break;
1349         }
1350 }
1351
1352 static void pqi_get_raid_bypass_status(struct pqi_ctrl_info *ctrl_info,
1353         struct pqi_scsi_dev *device)
1354 {
1355         int rc;
1356         u8 *buffer;
1357         u8 bypass_status;
1358
1359         buffer = kmalloc(64, GFP_KERNEL);
1360         if (!buffer)
1361                 return;
1362
1363         rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1364                 VPD_PAGE | CISS_VPD_LV_BYPASS_STATUS, buffer, 64);
1365         if (rc)
1366                 goto out;
1367
1368 #define RAID_BYPASS_STATUS              4
1369 #define RAID_BYPASS_CONFIGURED          0x1
1370 #define RAID_BYPASS_ENABLED             0x2
1371
1372         bypass_status = buffer[RAID_BYPASS_STATUS];
1373         device->raid_bypass_configured =
1374                 (bypass_status & RAID_BYPASS_CONFIGURED) != 0;
1375         if (device->raid_bypass_configured &&
1376                 (bypass_status & RAID_BYPASS_ENABLED) &&
1377                 pqi_get_raid_map(ctrl_info, device) == 0) {
1378                 device->raid_bypass_enabled = true;
1379                 if (get_unaligned_le16(&device->raid_map->flags) &
1380                         RAID_MAP_ENCRYPTION_ENABLED)
1381                         pqi_set_max_transfer_encrypted(ctrl_info, device);
1382         }
1383
1384 out:
1385         kfree(buffer);
1386 }
1387
1388 /*
1389  * Use vendor-specific VPD to determine online/offline status of a volume.
1390  */
1391
1392 static void pqi_get_volume_status(struct pqi_ctrl_info *ctrl_info,
1393         struct pqi_scsi_dev *device)
1394 {
1395         int rc;
1396         size_t page_length;
1397         u8 volume_status = CISS_LV_STATUS_UNAVAILABLE;
1398         bool volume_offline = true;
1399         u32 volume_flags;
1400         struct ciss_vpd_logical_volume_status *vpd;
1401
1402         vpd = kmalloc(sizeof(*vpd), GFP_KERNEL);
1403         if (!vpd)
1404                 goto no_buffer;
1405
1406         rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1407                 VPD_PAGE | CISS_VPD_LV_STATUS, vpd, sizeof(*vpd));
1408         if (rc)
1409                 goto out;
1410
1411         if (vpd->page_code != CISS_VPD_LV_STATUS)
1412                 goto out;
1413
1414         page_length = offsetof(struct ciss_vpd_logical_volume_status,
1415                 volume_status) + vpd->page_length;
1416         if (page_length < sizeof(*vpd))
1417                 goto out;
1418
1419         volume_status = vpd->volume_status;
1420         volume_flags = get_unaligned_be32(&vpd->flags);
1421         volume_offline = (volume_flags & CISS_LV_FLAGS_NO_HOST_IO) != 0;
1422
1423 out:
1424         kfree(vpd);
1425 no_buffer:
1426         device->volume_status = volume_status;
1427         device->volume_offline = volume_offline;
1428 }
1429
1430 static int pqi_get_physical_device_info(struct pqi_ctrl_info *ctrl_info,
1431         struct pqi_scsi_dev *device,
1432         struct bmic_identify_physical_device *id_phys)
1433 {
1434         int rc;
1435
1436         memset(id_phys, 0, sizeof(*id_phys));
1437
1438         rc = pqi_identify_physical_device(ctrl_info, device,
1439                 id_phys, sizeof(*id_phys));
1440         if (rc) {
1441                 device->queue_depth = PQI_PHYSICAL_DISK_DEFAULT_MAX_QUEUE_DEPTH;
1442                 return rc;
1443         }
1444
1445         scsi_sanitize_inquiry_string(&id_phys->model[0], 8);
1446         scsi_sanitize_inquiry_string(&id_phys->model[8], 16);
1447
1448         memcpy(device->vendor, &id_phys->model[0], sizeof(device->vendor));
1449         memcpy(device->model, &id_phys->model[8], sizeof(device->model));
1450
1451         device->box_index = id_phys->box_index;
1452         device->phys_box_on_bus = id_phys->phys_box_on_bus;
1453         device->phy_connected_dev_type = id_phys->phy_connected_dev_type[0];
1454         device->queue_depth =
1455                 get_unaligned_le16(&id_phys->current_queue_depth_limit);
1456         device->active_path_index = id_phys->active_path_number;
1457         device->path_map = id_phys->redundant_path_present_map;
1458         memcpy(&device->box,
1459                 &id_phys->alternate_paths_phys_box_on_port,
1460                 sizeof(device->box));
1461         memcpy(&device->phys_connector,
1462                 &id_phys->alternate_paths_phys_connector,
1463                 sizeof(device->phys_connector));
1464         device->bay = id_phys->phys_bay_in_box;
1465
1466         return 0;
1467 }
1468
1469 static int pqi_get_logical_device_info(struct pqi_ctrl_info *ctrl_info,
1470         struct pqi_scsi_dev *device)
1471 {
1472         int rc;
1473         u8 *buffer;
1474
1475         buffer = kmalloc(64, GFP_KERNEL);
1476         if (!buffer)
1477                 return -ENOMEM;
1478
1479         /* Send an inquiry to the device to see what it is. */
1480         rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr, 0, buffer, 64);
1481         if (rc)
1482                 goto out;
1483
1484         scsi_sanitize_inquiry_string(&buffer[8], 8);
1485         scsi_sanitize_inquiry_string(&buffer[16], 16);
1486
1487         device->devtype = buffer[0] & 0x1f;
1488         memcpy(device->vendor, &buffer[8], sizeof(device->vendor));
1489         memcpy(device->model, &buffer[16], sizeof(device->model));
1490
1491         if (device->devtype == TYPE_DISK) {
1492                 if (device->is_external_raid_device) {
1493                         device->raid_level = SA_RAID_UNKNOWN;
1494                         device->volume_status = CISS_LV_OK;
1495                         device->volume_offline = false;
1496                 } else {
1497                         pqi_get_raid_level(ctrl_info, device);
1498                         pqi_get_raid_bypass_status(ctrl_info, device);
1499                         pqi_get_volume_status(ctrl_info, device);
1500                 }
1501         }
1502
1503 out:
1504         kfree(buffer);
1505
1506         return rc;
1507 }
1508
1509 static int pqi_get_device_info(struct pqi_ctrl_info *ctrl_info,
1510         struct pqi_scsi_dev *device,
1511         struct bmic_identify_physical_device *id_phys)
1512 {
1513         int rc;
1514
1515         if (device->is_expander_smp_device)
1516                 return 0;
1517
1518         if (pqi_is_logical_device(device))
1519                 rc = pqi_get_logical_device_info(ctrl_info, device);
1520         else
1521                 rc = pqi_get_physical_device_info(ctrl_info, device, id_phys);
1522
1523         return rc;
1524 }
1525
1526 static void pqi_show_volume_status(struct pqi_ctrl_info *ctrl_info,
1527         struct pqi_scsi_dev *device)
1528 {
1529         char *status;
1530         static const char unknown_state_str[] =
1531                 "Volume is in an unknown state (%u)";
1532         char unknown_state_buffer[sizeof(unknown_state_str) + 10];
1533
1534         switch (device->volume_status) {
1535         case CISS_LV_OK:
1536                 status = "Volume online";
1537                 break;
1538         case CISS_LV_FAILED:
1539                 status = "Volume failed";
1540                 break;
1541         case CISS_LV_NOT_CONFIGURED:
1542                 status = "Volume not configured";
1543                 break;
1544         case CISS_LV_DEGRADED:
1545                 status = "Volume degraded";
1546                 break;
1547         case CISS_LV_READY_FOR_RECOVERY:
1548                 status = "Volume ready for recovery operation";
1549                 break;
1550         case CISS_LV_UNDERGOING_RECOVERY:
1551                 status = "Volume undergoing recovery";
1552                 break;
1553         case CISS_LV_WRONG_PHYSICAL_DRIVE_REPLACED:
1554                 status = "Wrong physical drive was replaced";
1555                 break;
1556         case CISS_LV_PHYSICAL_DRIVE_CONNECTION_PROBLEM:
1557                 status = "A physical drive not properly connected";
1558                 break;
1559         case CISS_LV_HARDWARE_OVERHEATING:
1560                 status = "Hardware is overheating";
1561                 break;
1562         case CISS_LV_HARDWARE_HAS_OVERHEATED:
1563                 status = "Hardware has overheated";
1564                 break;
1565         case CISS_LV_UNDERGOING_EXPANSION:
1566                 status = "Volume undergoing expansion";
1567                 break;
1568         case CISS_LV_NOT_AVAILABLE:
1569                 status = "Volume waiting for transforming volume";
1570                 break;
1571         case CISS_LV_QUEUED_FOR_EXPANSION:
1572                 status = "Volume queued for expansion";
1573                 break;
1574         case CISS_LV_DISABLED_SCSI_ID_CONFLICT:
1575                 status = "Volume disabled due to SCSI ID conflict";
1576                 break;
1577         case CISS_LV_EJECTED:
1578                 status = "Volume has been ejected";
1579                 break;
1580         case CISS_LV_UNDERGOING_ERASE:
1581                 status = "Volume undergoing background erase";
1582                 break;
1583         case CISS_LV_READY_FOR_PREDICTIVE_SPARE_REBUILD:
1584                 status = "Volume ready for predictive spare rebuild";
1585                 break;
1586         case CISS_LV_UNDERGOING_RPI:
1587                 status = "Volume undergoing rapid parity initialization";
1588                 break;
1589         case CISS_LV_PENDING_RPI:
1590                 status = "Volume queued for rapid parity initialization";
1591                 break;
1592         case CISS_LV_ENCRYPTED_NO_KEY:
1593                 status = "Encrypted volume inaccessible - key not present";
1594                 break;
1595         case CISS_LV_UNDERGOING_ENCRYPTION:
1596                 status = "Volume undergoing encryption process";
1597                 break;
1598         case CISS_LV_UNDERGOING_ENCRYPTION_REKEYING:
1599                 status = "Volume undergoing encryption re-keying process";
1600                 break;
1601         case CISS_LV_ENCRYPTED_IN_NON_ENCRYPTED_CONTROLLER:
1602                 status = "Volume encrypted but encryption is disabled";
1603                 break;
1604         case CISS_LV_PENDING_ENCRYPTION:
1605                 status = "Volume pending migration to encrypted state";
1606                 break;
1607         case CISS_LV_PENDING_ENCRYPTION_REKEYING:
1608                 status = "Volume pending encryption rekeying";
1609                 break;
1610         case CISS_LV_NOT_SUPPORTED:
1611                 status = "Volume not supported on this controller";
1612                 break;
1613         case CISS_LV_STATUS_UNAVAILABLE:
1614                 status = "Volume status not available";
1615                 break;
1616         default:
1617                 snprintf(unknown_state_buffer, sizeof(unknown_state_buffer),
1618                         unknown_state_str, device->volume_status);
1619                 status = unknown_state_buffer;
1620                 break;
1621         }
1622
1623         dev_info(&ctrl_info->pci_dev->dev,
1624                 "scsi %d:%d:%d:%d %s\n",
1625                 ctrl_info->scsi_host->host_no,
1626                 device->bus, device->target, device->lun, status);
1627 }
1628
1629 static void pqi_rescan_worker(struct work_struct *work)
1630 {
1631         struct pqi_ctrl_info *ctrl_info;
1632
1633         ctrl_info = container_of(to_delayed_work(work), struct pqi_ctrl_info,
1634                 rescan_work);
1635
1636         pqi_scan_scsi_devices(ctrl_info);
1637 }
1638
1639 static int pqi_add_device(struct pqi_ctrl_info *ctrl_info,
1640         struct pqi_scsi_dev *device)
1641 {
1642         int rc;
1643
1644         if (pqi_is_logical_device(device))
1645                 rc = scsi_add_device(ctrl_info->scsi_host, device->bus,
1646                         device->target, device->lun);
1647         else
1648                 rc = pqi_add_sas_device(ctrl_info->sas_host, device);
1649
1650         return rc;
1651 }
1652
1653 #define PQI_PENDING_IO_TIMEOUT_SECS     20
1654
1655 static inline void pqi_remove_device(struct pqi_ctrl_info *ctrl_info, struct pqi_scsi_dev *device)
1656 {
1657         int rc;
1658
1659         pqi_device_remove_start(device);
1660
1661         rc = pqi_device_wait_for_pending_io(ctrl_info, device, PQI_PENDING_IO_TIMEOUT_SECS);
1662         if (rc)
1663                 dev_err(&ctrl_info->pci_dev->dev,
1664                         "scsi %d:%d:%d:%d removing device with %d outstanding command(s)\n",
1665                         ctrl_info->scsi_host->host_no, device->bus,
1666                         device->target, device->lun,
1667                         atomic_read(&device->scsi_cmds_outstanding));
1668
1669         if (pqi_is_logical_device(device))
1670                 scsi_remove_device(device->sdev);
1671         else
1672                 pqi_remove_sas_device(device);
1673 }
1674
1675 /* Assumes the SCSI device list lock is held. */
1676
1677 static struct pqi_scsi_dev *pqi_find_scsi_dev(struct pqi_ctrl_info *ctrl_info,
1678         int bus, int target, int lun)
1679 {
1680         struct pqi_scsi_dev *device;
1681
1682         list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry)
1683                 if (device->bus == bus && device->target == target && device->lun == lun)
1684                         return device;
1685
1686         return NULL;
1687 }
1688
1689 static inline bool pqi_device_equal(struct pqi_scsi_dev *dev1, struct pqi_scsi_dev *dev2)
1690 {
1691         if (dev1->is_physical_device != dev2->is_physical_device)
1692                 return false;
1693
1694         if (dev1->is_physical_device)
1695                 return dev1->wwid == dev2->wwid;
1696
1697         return memcmp(dev1->volume_id, dev2->volume_id, sizeof(dev1->volume_id)) == 0;
1698 }
1699
1700 enum pqi_find_result {
1701         DEVICE_NOT_FOUND,
1702         DEVICE_CHANGED,
1703         DEVICE_SAME,
1704 };
1705
1706 static enum pqi_find_result pqi_scsi_find_entry(struct pqi_ctrl_info *ctrl_info,
1707         struct pqi_scsi_dev *device_to_find, struct pqi_scsi_dev **matching_device)
1708 {
1709         struct pqi_scsi_dev *device;
1710
1711         list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry) {
1712                 if (pqi_scsi3addr_equal(device_to_find->scsi3addr, device->scsi3addr)) {
1713                         *matching_device = device;
1714                         if (pqi_device_equal(device_to_find, device)) {
1715                                 if (device_to_find->volume_offline)
1716                                         return DEVICE_CHANGED;
1717                                 return DEVICE_SAME;
1718                         }
1719                         return DEVICE_CHANGED;
1720                 }
1721         }
1722
1723         return DEVICE_NOT_FOUND;
1724 }
1725
1726 static inline const char *pqi_device_type(struct pqi_scsi_dev *device)
1727 {
1728         if (device->is_expander_smp_device)
1729                 return "Enclosure SMP    ";
1730
1731         return scsi_device_type(device->devtype);
1732 }
1733
1734 #define PQI_DEV_INFO_BUFFER_LENGTH      128
1735
1736 static void pqi_dev_info(struct pqi_ctrl_info *ctrl_info,
1737         char *action, struct pqi_scsi_dev *device)
1738 {
1739         ssize_t count;
1740         char buffer[PQI_DEV_INFO_BUFFER_LENGTH];
1741
1742         count = snprintf(buffer, PQI_DEV_INFO_BUFFER_LENGTH,
1743                 "%d:%d:", ctrl_info->scsi_host->host_no, device->bus);
1744
1745         if (device->target_lun_valid)
1746                 count += scnprintf(buffer + count,
1747                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1748                         "%d:%d",
1749                         device->target,
1750                         device->lun);
1751         else
1752                 count += scnprintf(buffer + count,
1753                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1754                         "-:-");
1755
1756         if (pqi_is_logical_device(device))
1757                 count += scnprintf(buffer + count,
1758                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1759                         " %08x%08x",
1760                         *((u32 *)&device->scsi3addr),
1761                         *((u32 *)&device->scsi3addr[4]));
1762         else
1763                 count += scnprintf(buffer + count,
1764                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1765                         " %016llx", device->sas_address);
1766
1767         count += scnprintf(buffer + count, PQI_DEV_INFO_BUFFER_LENGTH - count,
1768                 " %s %.8s %.16s ",
1769                 pqi_device_type(device),
1770                 device->vendor,
1771                 device->model);
1772
1773         if (pqi_is_logical_device(device)) {
1774                 if (device->devtype == TYPE_DISK)
1775                         count += scnprintf(buffer + count,
1776                                 PQI_DEV_INFO_BUFFER_LENGTH - count,
1777                                 "SSDSmartPathCap%c En%c %-12s",
1778                                 device->raid_bypass_configured ? '+' : '-',
1779                                 device->raid_bypass_enabled ? '+' : '-',
1780                                 pqi_raid_level_to_string(device->raid_level));
1781         } else {
1782                 count += scnprintf(buffer + count,
1783                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1784                         "AIO%c", device->aio_enabled ? '+' : '-');
1785                 if (device->devtype == TYPE_DISK ||
1786                         device->devtype == TYPE_ZBC)
1787                         count += scnprintf(buffer + count,
1788                                 PQI_DEV_INFO_BUFFER_LENGTH - count,
1789                                 " qd=%-6d", device->queue_depth);
1790         }
1791
1792         dev_info(&ctrl_info->pci_dev->dev, "%s %s\n", action, buffer);
1793 }
1794
1795 /* Assumes the SCSI device list lock is held. */
1796
1797 static void pqi_scsi_update_device(struct pqi_scsi_dev *existing_device,
1798         struct pqi_scsi_dev *new_device)
1799 {
1800         existing_device->devtype = new_device->devtype;
1801         existing_device->device_type = new_device->device_type;
1802         existing_device->bus = new_device->bus;
1803         if (new_device->target_lun_valid) {
1804                 existing_device->target = new_device->target;
1805                 existing_device->lun = new_device->lun;
1806                 existing_device->target_lun_valid = true;
1807         }
1808
1809         if ((existing_device->volume_status == CISS_LV_QUEUED_FOR_EXPANSION ||
1810                 existing_device->volume_status == CISS_LV_UNDERGOING_EXPANSION) &&
1811                 new_device->volume_status == CISS_LV_OK)
1812                 existing_device->rescan = true;
1813
1814         /* By definition, the scsi3addr and wwid fields are already the same. */
1815
1816         existing_device->is_physical_device = new_device->is_physical_device;
1817         existing_device->is_external_raid_device =
1818                 new_device->is_external_raid_device;
1819         existing_device->is_expander_smp_device =
1820                 new_device->is_expander_smp_device;
1821         existing_device->aio_enabled = new_device->aio_enabled;
1822         memcpy(existing_device->vendor, new_device->vendor,
1823                 sizeof(existing_device->vendor));
1824         memcpy(existing_device->model, new_device->model,
1825                 sizeof(existing_device->model));
1826         existing_device->sas_address = new_device->sas_address;
1827         existing_device->raid_level = new_device->raid_level;
1828         existing_device->queue_depth = new_device->queue_depth;
1829         existing_device->aio_handle = new_device->aio_handle;
1830         existing_device->volume_status = new_device->volume_status;
1831         existing_device->active_path_index = new_device->active_path_index;
1832         existing_device->path_map = new_device->path_map;
1833         existing_device->bay = new_device->bay;
1834         existing_device->box_index = new_device->box_index;
1835         existing_device->phys_box_on_bus = new_device->phys_box_on_bus;
1836         existing_device->phy_connected_dev_type = new_device->phy_connected_dev_type;
1837         memcpy(existing_device->box, new_device->box,
1838                 sizeof(existing_device->box));
1839         memcpy(existing_device->phys_connector, new_device->phys_connector,
1840                 sizeof(existing_device->phys_connector));
1841         existing_device->next_bypass_group = 0;
1842         kfree(existing_device->raid_map);
1843         existing_device->raid_map = new_device->raid_map;
1844         existing_device->raid_bypass_configured =
1845                 new_device->raid_bypass_configured;
1846         existing_device->raid_bypass_enabled =
1847                 new_device->raid_bypass_enabled;
1848         existing_device->device_offline = false;
1849
1850         /* To prevent this from being freed later. */
1851         new_device->raid_map = NULL;
1852 }
1853
1854 static inline void pqi_free_device(struct pqi_scsi_dev *device)
1855 {
1856         if (device) {
1857                 kfree(device->raid_map);
1858                 kfree(device);
1859         }
1860 }
1861
1862 /*
1863  * Called when exposing a new device to the OS fails in order to re-adjust
1864  * our internal SCSI device list to match the SCSI ML's view.
1865  */
1866
1867 static inline void pqi_fixup_botched_add(struct pqi_ctrl_info *ctrl_info,
1868         struct pqi_scsi_dev *device)
1869 {
1870         unsigned long flags;
1871
1872         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1873         list_del(&device->scsi_device_list_entry);
1874         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
1875
1876         /* Allow the device structure to be freed later. */
1877         device->keep_device = false;
1878 }
1879
1880 static inline bool pqi_is_device_added(struct pqi_scsi_dev *device)
1881 {
1882         if (device->is_expander_smp_device)
1883                 return device->sas_port != NULL;
1884
1885         return device->sdev != NULL;
1886 }
1887
1888 static void pqi_update_device_list(struct pqi_ctrl_info *ctrl_info,
1889         struct pqi_scsi_dev *new_device_list[], unsigned int num_new_devices)
1890 {
1891         int rc;
1892         unsigned int i;
1893         unsigned long flags;
1894         enum pqi_find_result find_result;
1895         struct pqi_scsi_dev *device;
1896         struct pqi_scsi_dev *next;
1897         struct pqi_scsi_dev *matching_device;
1898         LIST_HEAD(add_list);
1899         LIST_HEAD(delete_list);
1900
1901         /*
1902          * The idea here is to do as little work as possible while holding the
1903          * spinlock.  That's why we go to great pains to defer anything other
1904          * than updating the internal device list until after we release the
1905          * spinlock.
1906          */
1907
1908         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1909
1910         /* Assume that all devices in the existing list have gone away. */
1911         list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry)
1912                 device->device_gone = true;
1913
1914         for (i = 0; i < num_new_devices; i++) {
1915                 device = new_device_list[i];
1916
1917                 find_result = pqi_scsi_find_entry(ctrl_info, device,
1918                         &matching_device);
1919
1920                 switch (find_result) {
1921                 case DEVICE_SAME:
1922                         /*
1923                          * The newly found device is already in the existing
1924                          * device list.
1925                          */
1926                         device->new_device = false;
1927                         matching_device->device_gone = false;
1928                         pqi_scsi_update_device(matching_device, device);
1929                         break;
1930                 case DEVICE_NOT_FOUND:
1931                         /*
1932                          * The newly found device is NOT in the existing device
1933                          * list.
1934                          */
1935                         device->new_device = true;
1936                         break;
1937                 case DEVICE_CHANGED:
1938                         /*
1939                          * The original device has gone away and we need to add
1940                          * the new device.
1941                          */
1942                         device->new_device = true;
1943                         break;
1944                 }
1945         }
1946
1947         /* Process all devices that have gone away. */
1948         list_for_each_entry_safe(device, next, &ctrl_info->scsi_device_list,
1949                 scsi_device_list_entry) {
1950                 if (device->device_gone) {
1951                         list_del_init(&device->scsi_device_list_entry);
1952                         list_add_tail(&device->delete_list_entry, &delete_list);
1953                 }
1954         }
1955
1956         /* Process all new devices. */
1957         for (i = 0; i < num_new_devices; i++) {
1958                 device = new_device_list[i];
1959                 if (!device->new_device)
1960                         continue;
1961                 if (device->volume_offline)
1962                         continue;
1963                 list_add_tail(&device->scsi_device_list_entry,
1964                         &ctrl_info->scsi_device_list);
1965                 list_add_tail(&device->add_list_entry, &add_list);
1966                 /* To prevent this device structure from being freed later. */
1967                 device->keep_device = true;
1968         }
1969
1970         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
1971
1972         if (pqi_ctrl_in_ofa(ctrl_info))
1973                 pqi_ctrl_ofa_done(ctrl_info);
1974
1975         /* Remove all devices that have gone away. */
1976         list_for_each_entry_safe(device, next, &delete_list, delete_list_entry) {
1977                 if (device->volume_offline) {
1978                         pqi_dev_info(ctrl_info, "offline", device);
1979                         pqi_show_volume_status(ctrl_info, device);
1980                 }
1981                 list_del(&device->delete_list_entry);
1982                 if (pqi_is_device_added(device)) {
1983                         pqi_remove_device(ctrl_info, device);
1984                 } else {
1985                         if (!device->volume_offline)
1986                                 pqi_dev_info(ctrl_info, "removed", device);
1987                         pqi_free_device(device);
1988                 }
1989         }
1990
1991         /*
1992          * Notify the SCSI ML if the queue depth of any existing device has
1993          * changed.
1994          */
1995         list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry) {
1996                 if (device->sdev && device->queue_depth != device->advertised_queue_depth) {
1997                         device->advertised_queue_depth = device->queue_depth;
1998                         scsi_change_queue_depth(device->sdev, device->advertised_queue_depth);
1999                         if (device->rescan) {
2000                                 scsi_rescan_device(&device->sdev->sdev_gendev);
2001                                 device->rescan = false;
2002                         }
2003                 }
2004         }
2005
2006         /* Expose any new devices. */
2007         list_for_each_entry_safe(device, next, &add_list, add_list_entry) {
2008                 if (!pqi_is_device_added(device)) {
2009                         rc = pqi_add_device(ctrl_info, device);
2010                         if (rc == 0) {
2011                                 pqi_dev_info(ctrl_info, "added", device);
2012                         } else {
2013                                 dev_warn(&ctrl_info->pci_dev->dev,
2014                                         "scsi %d:%d:%d:%d addition failed, device not added\n",
2015                                         ctrl_info->scsi_host->host_no,
2016                                         device->bus, device->target,
2017                                         device->lun);
2018                                 pqi_fixup_botched_add(ctrl_info, device);
2019                         }
2020                 }
2021         }
2022 }
2023
2024 static inline bool pqi_is_supported_device(struct pqi_scsi_dev *device)
2025 {
2026         /*
2027          * Only support the HBA controller itself as a RAID
2028          * controller.  If it's a RAID controller other than
2029          * the HBA itself (an external RAID controller, for
2030          * example), we don't support it.
2031          */
2032         if (device->device_type == SA_DEVICE_TYPE_CONTROLLER &&
2033                 !pqi_is_hba_lunid(device->scsi3addr))
2034                         return false;
2035
2036         return true;
2037 }
2038
2039 static inline bool pqi_skip_device(u8 *scsi3addr)
2040 {
2041         /* Ignore all masked devices. */
2042         if (MASKED_DEVICE(scsi3addr))
2043                 return true;
2044
2045         return false;
2046 }
2047
2048 static inline void pqi_mask_device(u8 *scsi3addr)
2049 {
2050         scsi3addr[3] |= 0xc0;
2051 }
2052
2053 static inline bool pqi_is_device_with_sas_address(struct pqi_scsi_dev *device)
2054 {
2055         switch (device->device_type) {
2056         case SA_DEVICE_TYPE_SAS:
2057         case SA_DEVICE_TYPE_EXPANDER_SMP:
2058         case SA_DEVICE_TYPE_SES:
2059                 return true;
2060         }
2061
2062         return false;
2063 }
2064
2065 static inline bool pqi_expose_device(struct pqi_scsi_dev *device)
2066 {
2067         return !device->is_physical_device || !pqi_skip_device(device->scsi3addr);
2068 }
2069
2070 static int pqi_update_scsi_devices(struct pqi_ctrl_info *ctrl_info)
2071 {
2072         int i;
2073         int rc;
2074         LIST_HEAD(new_device_list_head);
2075         struct report_phys_lun_extended *physdev_list = NULL;
2076         struct report_log_lun_extended *logdev_list = NULL;
2077         struct report_phys_lun_extended_entry *phys_lun_ext_entry;
2078         struct report_log_lun_extended_entry *log_lun_ext_entry;
2079         struct bmic_identify_physical_device *id_phys = NULL;
2080         u32 num_physicals;
2081         u32 num_logicals;
2082         struct pqi_scsi_dev **new_device_list = NULL;
2083         struct pqi_scsi_dev *device;
2084         struct pqi_scsi_dev *next;
2085         unsigned int num_new_devices;
2086         unsigned int num_valid_devices;
2087         bool is_physical_device;
2088         u8 *scsi3addr;
2089         unsigned int physical_index;
2090         unsigned int logical_index;
2091         static char *out_of_memory_msg =
2092                 "failed to allocate memory, device discovery stopped";
2093
2094         rc = pqi_get_device_lists(ctrl_info, &physdev_list, &logdev_list);
2095         if (rc)
2096                 goto out;
2097
2098         if (physdev_list)
2099                 num_physicals =
2100                         get_unaligned_be32(&physdev_list->header.list_length)
2101                                 / sizeof(physdev_list->lun_entries[0]);
2102         else
2103                 num_physicals = 0;
2104
2105         if (logdev_list)
2106                 num_logicals =
2107                         get_unaligned_be32(&logdev_list->header.list_length)
2108                                 / sizeof(logdev_list->lun_entries[0]);
2109         else
2110                 num_logicals = 0;
2111
2112         if (num_physicals) {
2113                 /*
2114                  * We need this buffer for calls to pqi_get_physical_disk_info()
2115                  * below.  We allocate it here instead of inside
2116                  * pqi_get_physical_disk_info() because it's a fairly large
2117                  * buffer.
2118                  */
2119                 id_phys = kmalloc(sizeof(*id_phys), GFP_KERNEL);
2120                 if (!id_phys) {
2121                         dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2122                                 out_of_memory_msg);
2123                         rc = -ENOMEM;
2124                         goto out;
2125                 }
2126
2127                 if (pqi_hide_vsep) {
2128                         for (i = num_physicals - 1; i >= 0; i--) {
2129                                 phys_lun_ext_entry =
2130                                                 &physdev_list->lun_entries[i];
2131                                 if (CISS_GET_DRIVE_NUMBER(phys_lun_ext_entry->lunid) == PQI_VSEP_CISS_BTL) {
2132                                         pqi_mask_device(phys_lun_ext_entry->lunid);
2133                                         break;
2134                                 }
2135                         }
2136                 }
2137         }
2138
2139         if (num_logicals &&
2140                 (logdev_list->header.flags & CISS_REPORT_LOG_FLAG_DRIVE_TYPE_MIX))
2141                 ctrl_info->lv_drive_type_mix_valid = true;
2142
2143         num_new_devices = num_physicals + num_logicals;
2144
2145         new_device_list = kmalloc_array(num_new_devices,
2146                                         sizeof(*new_device_list),
2147                                         GFP_KERNEL);
2148         if (!new_device_list) {
2149                 dev_warn(&ctrl_info->pci_dev->dev, "%s\n", out_of_memory_msg);
2150                 rc = -ENOMEM;
2151                 goto out;
2152         }
2153
2154         for (i = 0; i < num_new_devices; i++) {
2155                 device = kzalloc(sizeof(*device), GFP_KERNEL);
2156                 if (!device) {
2157                         dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2158                                 out_of_memory_msg);
2159                         rc = -ENOMEM;
2160                         goto out;
2161                 }
2162                 list_add_tail(&device->new_device_list_entry,
2163                         &new_device_list_head);
2164         }
2165
2166         device = NULL;
2167         num_valid_devices = 0;
2168         physical_index = 0;
2169         logical_index = 0;
2170
2171         for (i = 0; i < num_new_devices; i++) {
2172
2173                 if ((!pqi_expose_ld_first && i < num_physicals) ||
2174                         (pqi_expose_ld_first && i >= num_logicals)) {
2175                         is_physical_device = true;
2176                         phys_lun_ext_entry =
2177                                 &physdev_list->lun_entries[physical_index++];
2178                         log_lun_ext_entry = NULL;
2179                         scsi3addr = phys_lun_ext_entry->lunid;
2180                 } else {
2181                         is_physical_device = false;
2182                         phys_lun_ext_entry = NULL;
2183                         log_lun_ext_entry =
2184                                 &logdev_list->lun_entries[logical_index++];
2185                         scsi3addr = log_lun_ext_entry->lunid;
2186                 }
2187
2188                 if (is_physical_device && pqi_skip_device(scsi3addr))
2189                         continue;
2190
2191                 if (device)
2192                         device = list_next_entry(device, new_device_list_entry);
2193                 else
2194                         device = list_first_entry(&new_device_list_head,
2195                                 struct pqi_scsi_dev, new_device_list_entry);
2196
2197                 memcpy(device->scsi3addr, scsi3addr, sizeof(device->scsi3addr));
2198                 device->is_physical_device = is_physical_device;
2199                 if (is_physical_device) {
2200                         device->device_type = phys_lun_ext_entry->device_type;
2201                         if (device->device_type == SA_DEVICE_TYPE_EXPANDER_SMP)
2202                                 device->is_expander_smp_device = true;
2203                 } else {
2204                         device->is_external_raid_device =
2205                                 pqi_is_external_raid_addr(scsi3addr);
2206                 }
2207
2208                 if (!pqi_is_supported_device(device))
2209                         continue;
2210
2211                 /* Gather information about the device. */
2212                 rc = pqi_get_device_info(ctrl_info, device, id_phys);
2213                 if (rc == -ENOMEM) {
2214                         dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2215                                 out_of_memory_msg);
2216                         goto out;
2217                 }
2218                 if (rc) {
2219                         if (device->is_physical_device)
2220                                 dev_warn(&ctrl_info->pci_dev->dev,
2221                                         "obtaining device info failed, skipping physical device %016llx\n",
2222                                         get_unaligned_be64(&phys_lun_ext_entry->wwid));
2223                         else
2224                                 dev_warn(&ctrl_info->pci_dev->dev,
2225                                         "obtaining device info failed, skipping logical device %08x%08x\n",
2226                                         *((u32 *)&device->scsi3addr),
2227                                         *((u32 *)&device->scsi3addr[4]));
2228                         rc = 0;
2229                         continue;
2230                 }
2231
2232                 pqi_assign_bus_target_lun(device);
2233
2234                 if (device->is_physical_device) {
2235                         device->wwid = phys_lun_ext_entry->wwid;
2236                         if ((phys_lun_ext_entry->device_flags &
2237                                 CISS_REPORT_PHYS_DEV_FLAG_AIO_ENABLED) &&
2238                                 phys_lun_ext_entry->aio_handle) {
2239                                         device->aio_enabled = true;
2240                                         device->aio_handle =
2241                                                 phys_lun_ext_entry->aio_handle;
2242                         }
2243                 } else {
2244                         memcpy(device->volume_id, log_lun_ext_entry->volume_id,
2245                                 sizeof(device->volume_id));
2246                 }
2247
2248                 if (pqi_is_device_with_sas_address(device))
2249                         device->sas_address = get_unaligned_be64(&device->wwid);
2250
2251                 new_device_list[num_valid_devices++] = device;
2252         }
2253
2254         pqi_update_device_list(ctrl_info, new_device_list, num_valid_devices);
2255
2256 out:
2257         list_for_each_entry_safe(device, next, &new_device_list_head,
2258                 new_device_list_entry) {
2259                 if (device->keep_device)
2260                         continue;
2261                 list_del(&device->new_device_list_entry);
2262                 pqi_free_device(device);
2263         }
2264
2265         kfree(new_device_list);
2266         kfree(physdev_list);
2267         kfree(logdev_list);
2268         kfree(id_phys);
2269
2270         return rc;
2271 }
2272
2273 static int pqi_scan_scsi_devices(struct pqi_ctrl_info *ctrl_info)
2274 {
2275         int rc = 0;
2276
2277         if (pqi_ctrl_offline(ctrl_info))
2278                 return -ENXIO;
2279
2280         if (!mutex_trylock(&ctrl_info->scan_mutex)) {
2281                 pqi_schedule_rescan_worker_delayed(ctrl_info);
2282                 rc = -EINPROGRESS;
2283         } else {
2284                 rc = pqi_update_scsi_devices(ctrl_info);
2285                 if (rc)
2286                         pqi_schedule_rescan_worker_delayed(ctrl_info);
2287                 mutex_unlock(&ctrl_info->scan_mutex);
2288         }
2289
2290         return rc;
2291 }
2292
2293 static void pqi_scan_start(struct Scsi_Host *shost)
2294 {
2295         struct pqi_ctrl_info *ctrl_info;
2296
2297         ctrl_info = shost_to_hba(shost);
2298         if (pqi_ctrl_in_ofa(ctrl_info))
2299                 return;
2300
2301         pqi_scan_scsi_devices(ctrl_info);
2302 }
2303
2304 /* Returns TRUE if scan is finished. */
2305
2306 static int pqi_scan_finished(struct Scsi_Host *shost,
2307         unsigned long elapsed_time)
2308 {
2309         struct pqi_ctrl_info *ctrl_info;
2310
2311         ctrl_info = shost_priv(shost);
2312
2313         return !mutex_is_locked(&ctrl_info->scan_mutex);
2314 }
2315
2316 static void pqi_wait_until_scan_finished(struct pqi_ctrl_info *ctrl_info)
2317 {
2318         mutex_lock(&ctrl_info->scan_mutex);
2319         mutex_unlock(&ctrl_info->scan_mutex);
2320 }
2321
2322 static void pqi_wait_until_lun_reset_finished(struct pqi_ctrl_info *ctrl_info)
2323 {
2324         mutex_lock(&ctrl_info->lun_reset_mutex);
2325         mutex_unlock(&ctrl_info->lun_reset_mutex);
2326 }
2327
2328 static void pqi_wait_until_ofa_finished(struct pqi_ctrl_info *ctrl_info)
2329 {
2330         mutex_lock(&ctrl_info->ofa_mutex);
2331         mutex_unlock(&ctrl_info->ofa_mutex);
2332 }
2333
2334 static inline void pqi_set_encryption_info(struct pqi_encryption_info *encryption_info,
2335         struct raid_map *raid_map, u64 first_block)
2336 {
2337         u32 volume_blk_size;
2338
2339         /*
2340          * Set the encryption tweak values based on logical block address.
2341          * If the block size is 512, the tweak value is equal to the LBA.
2342          * For other block sizes, tweak value is (LBA * block size) / 512.
2343          */
2344         volume_blk_size = get_unaligned_le32(&raid_map->volume_blk_size);
2345         if (volume_blk_size != 512)
2346                 first_block = (first_block * volume_blk_size) / 512;
2347
2348         encryption_info->data_encryption_key_index =
2349                 get_unaligned_le16(&raid_map->data_encryption_key_index);
2350         encryption_info->encrypt_tweak_lower = lower_32_bits(first_block);
2351         encryption_info->encrypt_tweak_upper = upper_32_bits(first_block);
2352 }
2353
2354 /*
2355  * Attempt to perform RAID bypass mapping for a logical volume I/O.
2356  */
2357
2358 static bool pqi_aio_raid_level_supported(struct pqi_ctrl_info *ctrl_info,
2359         struct pqi_scsi_dev_raid_map_data *rmd)
2360 {
2361         bool is_supported = true;
2362
2363         switch (rmd->raid_level) {
2364         case SA_RAID_0:
2365                 break;
2366         case SA_RAID_1:
2367                 if (rmd->is_write && (!ctrl_info->enable_r1_writes ||
2368                         rmd->data_length > ctrl_info->max_write_raid_1_10_2drive))
2369                         is_supported = false;
2370                 break;
2371         case SA_RAID_TRIPLE:
2372                 if (rmd->is_write && (!ctrl_info->enable_r1_writes ||
2373                         rmd->data_length > ctrl_info->max_write_raid_1_10_3drive))
2374                         is_supported = false;
2375                 break;
2376         case SA_RAID_5:
2377                 if (rmd->is_write && (!ctrl_info->enable_r5_writes ||
2378                         rmd->data_length > ctrl_info->max_write_raid_5_6))
2379                         is_supported = false;
2380                 break;
2381         case SA_RAID_6:
2382                 if (rmd->is_write && (!ctrl_info->enable_r6_writes ||
2383                         rmd->data_length > ctrl_info->max_write_raid_5_6))
2384                         is_supported = false;
2385                 break;
2386         default:
2387                 is_supported = false;
2388                 break;
2389         }
2390
2391         return is_supported;
2392 }
2393
2394 #define PQI_RAID_BYPASS_INELIGIBLE      1
2395
2396 static int pqi_get_aio_lba_and_block_count(struct scsi_cmnd *scmd,
2397         struct pqi_scsi_dev_raid_map_data *rmd)
2398 {
2399         /* Check for valid opcode, get LBA and block count. */
2400         switch (scmd->cmnd[0]) {
2401         case WRITE_6:
2402                 rmd->is_write = true;
2403                 fallthrough;
2404         case READ_6:
2405                 rmd->first_block = (u64)(((scmd->cmnd[1] & 0x1f) << 16) |
2406                         (scmd->cmnd[2] << 8) | scmd->cmnd[3]);
2407                 rmd->block_cnt = (u32)scmd->cmnd[4];
2408                 if (rmd->block_cnt == 0)
2409                         rmd->block_cnt = 256;
2410                 break;
2411         case WRITE_10:
2412                 rmd->is_write = true;
2413                 fallthrough;
2414         case READ_10:
2415                 rmd->first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2416                 rmd->block_cnt = (u32)get_unaligned_be16(&scmd->cmnd[7]);
2417                 break;
2418         case WRITE_12:
2419                 rmd->is_write = true;
2420                 fallthrough;
2421         case READ_12:
2422                 rmd->first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2423                 rmd->block_cnt = get_unaligned_be32(&scmd->cmnd[6]);
2424                 break;
2425         case WRITE_16:
2426                 rmd->is_write = true;
2427                 fallthrough;
2428         case READ_16:
2429                 rmd->first_block = get_unaligned_be64(&scmd->cmnd[2]);
2430                 rmd->block_cnt = get_unaligned_be32(&scmd->cmnd[10]);
2431                 break;
2432         default:
2433                 /* Process via normal I/O path. */
2434                 return PQI_RAID_BYPASS_INELIGIBLE;
2435         }
2436
2437         put_unaligned_le32(scsi_bufflen(scmd), &rmd->data_length);
2438
2439         return 0;
2440 }
2441
2442 static int pci_get_aio_common_raid_map_values(struct pqi_ctrl_info *ctrl_info,
2443         struct pqi_scsi_dev_raid_map_data *rmd, struct raid_map *raid_map)
2444 {
2445 #if BITS_PER_LONG == 32
2446         u64 tmpdiv;
2447 #endif
2448
2449         rmd->last_block = rmd->first_block + rmd->block_cnt - 1;
2450
2451         /* Check for invalid block or wraparound. */
2452         if (rmd->last_block >=
2453                 get_unaligned_le64(&raid_map->volume_blk_cnt) ||
2454                 rmd->last_block < rmd->first_block)
2455                 return PQI_RAID_BYPASS_INELIGIBLE;
2456
2457         rmd->data_disks_per_row =
2458                 get_unaligned_le16(&raid_map->data_disks_per_row);
2459         rmd->strip_size = get_unaligned_le16(&raid_map->strip_size);
2460         rmd->layout_map_count = get_unaligned_le16(&raid_map->layout_map_count);
2461
2462         /* Calculate stripe information for the request. */
2463         rmd->blocks_per_row = rmd->data_disks_per_row * rmd->strip_size;
2464 #if BITS_PER_LONG == 32
2465         tmpdiv = rmd->first_block;
2466         do_div(tmpdiv, rmd->blocks_per_row);
2467         rmd->first_row = tmpdiv;
2468         tmpdiv = rmd->last_block;
2469         do_div(tmpdiv, rmd->blocks_per_row);
2470         rmd->last_row = tmpdiv;
2471         rmd->first_row_offset = (u32)(rmd->first_block - (rmd->first_row * rmd->blocks_per_row));
2472         rmd->last_row_offset = (u32)(rmd->last_block - (rmd->last_row * rmd->blocks_per_row));
2473         tmpdiv = rmd->first_row_offset;
2474         do_div(tmpdiv, rmd->strip_size);
2475         rmd->first_column = tmpdiv;
2476         tmpdiv = rmd->last_row_offset;
2477         do_div(tmpdiv, rmd->strip_size);
2478         rmd->last_column = tmpdiv;
2479 #else
2480         rmd->first_row = rmd->first_block / rmd->blocks_per_row;
2481         rmd->last_row = rmd->last_block / rmd->blocks_per_row;
2482         rmd->first_row_offset = (u32)(rmd->first_block -
2483                 (rmd->first_row * rmd->blocks_per_row));
2484         rmd->last_row_offset = (u32)(rmd->last_block - (rmd->last_row *
2485                 rmd->blocks_per_row));
2486         rmd->first_column = rmd->first_row_offset / rmd->strip_size;
2487         rmd->last_column = rmd->last_row_offset / rmd->strip_size;
2488 #endif
2489
2490         /* If this isn't a single row/column then give to the controller. */
2491         if (rmd->first_row != rmd->last_row ||
2492                 rmd->first_column != rmd->last_column)
2493                 return PQI_RAID_BYPASS_INELIGIBLE;
2494
2495         /* Proceeding with driver mapping. */
2496         rmd->total_disks_per_row = rmd->data_disks_per_row +
2497                 get_unaligned_le16(&raid_map->metadata_disks_per_row);
2498         rmd->map_row = ((u32)(rmd->first_row >>
2499                 raid_map->parity_rotation_shift)) %
2500                 get_unaligned_le16(&raid_map->row_cnt);
2501         rmd->map_index = (rmd->map_row * rmd->total_disks_per_row) +
2502                 rmd->first_column;
2503
2504         return 0;
2505 }
2506
2507 static int pqi_calc_aio_r5_or_r6(struct pqi_scsi_dev_raid_map_data *rmd,
2508         struct raid_map *raid_map)
2509 {
2510 #if BITS_PER_LONG == 32
2511         u64 tmpdiv;
2512 #endif
2513         /* RAID 50/60 */
2514         /* Verify first and last block are in same RAID group. */
2515         rmd->stripesize = rmd->blocks_per_row * rmd->layout_map_count;
2516 #if BITS_PER_LONG == 32
2517         tmpdiv = rmd->first_block;
2518         rmd->first_group = do_div(tmpdiv, rmd->stripesize);
2519         tmpdiv = rmd->first_group;
2520         do_div(tmpdiv, rmd->blocks_per_row);
2521         rmd->first_group = tmpdiv;
2522         tmpdiv = rmd->last_block;
2523         rmd->last_group = do_div(tmpdiv, rmd->stripesize);
2524         tmpdiv = rmd->last_group;
2525         do_div(tmpdiv, rmd->blocks_per_row);
2526         rmd->last_group = tmpdiv;
2527 #else
2528         rmd->first_group = (rmd->first_block % rmd->stripesize) / rmd->blocks_per_row;
2529         rmd->last_group = (rmd->last_block % rmd->stripesize) / rmd->blocks_per_row;
2530 #endif
2531         if (rmd->first_group != rmd->last_group)
2532                 return PQI_RAID_BYPASS_INELIGIBLE;
2533
2534         /* Verify request is in a single row of RAID 5/6. */
2535 #if BITS_PER_LONG == 32
2536         tmpdiv = rmd->first_block;
2537         do_div(tmpdiv, rmd->stripesize);
2538         rmd->first_row = tmpdiv;
2539         rmd->r5or6_first_row = tmpdiv;
2540         tmpdiv = rmd->last_block;
2541         do_div(tmpdiv, rmd->stripesize);
2542         rmd->r5or6_last_row = tmpdiv;
2543 #else
2544         rmd->first_row = rmd->r5or6_first_row =
2545                 rmd->first_block / rmd->stripesize;
2546         rmd->r5or6_last_row = rmd->last_block / rmd->stripesize;
2547 #endif
2548         if (rmd->r5or6_first_row != rmd->r5or6_last_row)
2549                 return PQI_RAID_BYPASS_INELIGIBLE;
2550
2551         /* Verify request is in a single column. */
2552 #if BITS_PER_LONG == 32
2553         tmpdiv = rmd->first_block;
2554         rmd->first_row_offset = do_div(tmpdiv, rmd->stripesize);
2555         tmpdiv = rmd->first_row_offset;
2556         rmd->first_row_offset = (u32)do_div(tmpdiv, rmd->blocks_per_row);
2557         rmd->r5or6_first_row_offset = rmd->first_row_offset;
2558         tmpdiv = rmd->last_block;
2559         rmd->r5or6_last_row_offset = do_div(tmpdiv, rmd->stripesize);
2560         tmpdiv = rmd->r5or6_last_row_offset;
2561         rmd->r5or6_last_row_offset = do_div(tmpdiv, rmd->blocks_per_row);
2562         tmpdiv = rmd->r5or6_first_row_offset;
2563         do_div(tmpdiv, rmd->strip_size);
2564         rmd->first_column = rmd->r5or6_first_column = tmpdiv;
2565         tmpdiv = rmd->r5or6_last_row_offset;
2566         do_div(tmpdiv, rmd->strip_size);
2567         rmd->r5or6_last_column = tmpdiv;
2568 #else
2569         rmd->first_row_offset = rmd->r5or6_first_row_offset =
2570                 (u32)((rmd->first_block % rmd->stripesize) %
2571                 rmd->blocks_per_row);
2572
2573         rmd->r5or6_last_row_offset =
2574                 (u32)((rmd->last_block % rmd->stripesize) %
2575                 rmd->blocks_per_row);
2576
2577         rmd->first_column =
2578                 rmd->r5or6_first_row_offset / rmd->strip_size;
2579         rmd->r5or6_first_column = rmd->first_column;
2580         rmd->r5or6_last_column = rmd->r5or6_last_row_offset / rmd->strip_size;
2581 #endif
2582         if (rmd->r5or6_first_column != rmd->r5or6_last_column)
2583                 return PQI_RAID_BYPASS_INELIGIBLE;
2584
2585         /* Request is eligible. */
2586         rmd->map_row =
2587                 ((u32)(rmd->first_row >> raid_map->parity_rotation_shift)) %
2588                 get_unaligned_le16(&raid_map->row_cnt);
2589
2590         rmd->map_index = (rmd->first_group *
2591                 (get_unaligned_le16(&raid_map->row_cnt) *
2592                 rmd->total_disks_per_row)) +
2593                 (rmd->map_row * rmd->total_disks_per_row) + rmd->first_column;
2594
2595         if (rmd->is_write) {
2596                 u32 index;
2597
2598                 /*
2599                  * p_parity_it_nexus and q_parity_it_nexus are pointers to the
2600                  * parity entries inside the device's raid_map.
2601                  *
2602                  * A device's RAID map is bounded by: number of RAID disks squared.
2603                  *
2604                  * The devices RAID map size is checked during device
2605                  * initialization.
2606                  */
2607                 index = DIV_ROUND_UP(rmd->map_index + 1, rmd->total_disks_per_row);
2608                 index *= rmd->total_disks_per_row;
2609                 index -= get_unaligned_le16(&raid_map->metadata_disks_per_row);
2610
2611                 rmd->p_parity_it_nexus = raid_map->disk_data[index].aio_handle;
2612                 if (rmd->raid_level == SA_RAID_6) {
2613                         rmd->q_parity_it_nexus = raid_map->disk_data[index + 1].aio_handle;
2614                         rmd->xor_mult = raid_map->disk_data[rmd->map_index].xor_mult[1];
2615                 }
2616                 if (rmd->blocks_per_row == 0)
2617                         return PQI_RAID_BYPASS_INELIGIBLE;
2618 #if BITS_PER_LONG == 32
2619                 tmpdiv = rmd->first_block;
2620                 do_div(tmpdiv, rmd->blocks_per_row);
2621                 rmd->row = tmpdiv;
2622 #else
2623                 rmd->row = rmd->first_block / rmd->blocks_per_row;
2624 #endif
2625         }
2626
2627         return 0;
2628 }
2629
2630 static void pqi_set_aio_cdb(struct pqi_scsi_dev_raid_map_data *rmd)
2631 {
2632         /* Build the new CDB for the physical disk I/O. */
2633         if (rmd->disk_block > 0xffffffff) {
2634                 rmd->cdb[0] = rmd->is_write ? WRITE_16 : READ_16;
2635                 rmd->cdb[1] = 0;
2636                 put_unaligned_be64(rmd->disk_block, &rmd->cdb[2]);
2637                 put_unaligned_be32(rmd->disk_block_cnt, &rmd->cdb[10]);
2638                 rmd->cdb[14] = 0;
2639                 rmd->cdb[15] = 0;
2640                 rmd->cdb_length = 16;
2641         } else {
2642                 rmd->cdb[0] = rmd->is_write ? WRITE_10 : READ_10;
2643                 rmd->cdb[1] = 0;
2644                 put_unaligned_be32((u32)rmd->disk_block, &rmd->cdb[2]);
2645                 rmd->cdb[6] = 0;
2646                 put_unaligned_be16((u16)rmd->disk_block_cnt, &rmd->cdb[7]);
2647                 rmd->cdb[9] = 0;
2648                 rmd->cdb_length = 10;
2649         }
2650 }
2651
2652 static void pqi_calc_aio_r1_nexus(struct raid_map *raid_map,
2653         struct pqi_scsi_dev_raid_map_data *rmd)
2654 {
2655         u32 index;
2656         u32 group;
2657
2658         group = rmd->map_index / rmd->data_disks_per_row;
2659
2660         index = rmd->map_index - (group * rmd->data_disks_per_row);
2661         rmd->it_nexus[0] = raid_map->disk_data[index].aio_handle;
2662         index += rmd->data_disks_per_row;
2663         rmd->it_nexus[1] = raid_map->disk_data[index].aio_handle;
2664         if (rmd->layout_map_count > 2) {
2665                 index += rmd->data_disks_per_row;
2666                 rmd->it_nexus[2] = raid_map->disk_data[index].aio_handle;
2667         }
2668
2669         rmd->num_it_nexus_entries = rmd->layout_map_count;
2670 }
2671
2672 static int pqi_raid_bypass_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
2673         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
2674         struct pqi_queue_group *queue_group)
2675 {
2676         int rc;
2677         struct raid_map *raid_map;
2678         u32 group;
2679         u32 next_bypass_group;
2680         struct pqi_encryption_info *encryption_info_ptr;
2681         struct pqi_encryption_info encryption_info;
2682         struct pqi_scsi_dev_raid_map_data rmd = { 0 };
2683
2684         rc = pqi_get_aio_lba_and_block_count(scmd, &rmd);
2685         if (rc)
2686                 return PQI_RAID_BYPASS_INELIGIBLE;
2687
2688         rmd.raid_level = device->raid_level;
2689
2690         if (!pqi_aio_raid_level_supported(ctrl_info, &rmd))
2691                 return PQI_RAID_BYPASS_INELIGIBLE;
2692
2693         if (unlikely(rmd.block_cnt == 0))
2694                 return PQI_RAID_BYPASS_INELIGIBLE;
2695
2696         raid_map = device->raid_map;
2697
2698         rc = pci_get_aio_common_raid_map_values(ctrl_info, &rmd, raid_map);
2699         if (rc)
2700                 return PQI_RAID_BYPASS_INELIGIBLE;
2701
2702         if (device->raid_level == SA_RAID_1 ||
2703                 device->raid_level == SA_RAID_TRIPLE) {
2704                 if (rmd.is_write) {
2705                         pqi_calc_aio_r1_nexus(raid_map, &rmd);
2706                 } else {
2707                         group = device->next_bypass_group;
2708                         next_bypass_group = group + 1;
2709                         if (next_bypass_group >= rmd.layout_map_count)
2710                                 next_bypass_group = 0;
2711                         device->next_bypass_group = next_bypass_group;
2712                         rmd.map_index += group * rmd.data_disks_per_row;
2713                 }
2714         } else if ((device->raid_level == SA_RAID_5 ||
2715                 device->raid_level == SA_RAID_6) &&
2716                 (rmd.layout_map_count > 1 || rmd.is_write)) {
2717                 rc = pqi_calc_aio_r5_or_r6(&rmd, raid_map);
2718                 if (rc)
2719                         return PQI_RAID_BYPASS_INELIGIBLE;
2720         }
2721
2722         if (unlikely(rmd.map_index >= RAID_MAP_MAX_ENTRIES))
2723                 return PQI_RAID_BYPASS_INELIGIBLE;
2724
2725         rmd.aio_handle = raid_map->disk_data[rmd.map_index].aio_handle;
2726         rmd.disk_block = get_unaligned_le64(&raid_map->disk_starting_blk) +
2727                 rmd.first_row * rmd.strip_size +
2728                 (rmd.first_row_offset - rmd.first_column * rmd.strip_size);
2729         rmd.disk_block_cnt = rmd.block_cnt;
2730
2731         /* Handle differing logical/physical block sizes. */
2732         if (raid_map->phys_blk_shift) {
2733                 rmd.disk_block <<= raid_map->phys_blk_shift;
2734                 rmd.disk_block_cnt <<= raid_map->phys_blk_shift;
2735         }
2736
2737         if (unlikely(rmd.disk_block_cnt > 0xffff))
2738                 return PQI_RAID_BYPASS_INELIGIBLE;
2739
2740         pqi_set_aio_cdb(&rmd);
2741
2742         if (get_unaligned_le16(&raid_map->flags) & RAID_MAP_ENCRYPTION_ENABLED) {
2743                 if (rmd.data_length > device->max_transfer_encrypted)
2744                         return PQI_RAID_BYPASS_INELIGIBLE;
2745                 pqi_set_encryption_info(&encryption_info, raid_map, rmd.first_block);
2746                 encryption_info_ptr = &encryption_info;
2747         } else {
2748                 encryption_info_ptr = NULL;
2749         }
2750
2751         if (rmd.is_write) {
2752                 switch (device->raid_level) {
2753                 case SA_RAID_1:
2754                 case SA_RAID_TRIPLE:
2755                         return pqi_aio_submit_r1_write_io(ctrl_info, scmd, queue_group,
2756                                 encryption_info_ptr, device, &rmd);
2757                 case SA_RAID_5:
2758                 case SA_RAID_6:
2759                         return pqi_aio_submit_r56_write_io(ctrl_info, scmd, queue_group,
2760                                 encryption_info_ptr, device, &rmd);
2761                 }
2762         }
2763
2764         return pqi_aio_submit_io(ctrl_info, scmd, rmd.aio_handle,
2765                 rmd.cdb, rmd.cdb_length, queue_group,
2766                 encryption_info_ptr, true);
2767 }
2768
2769 #define PQI_STATUS_IDLE         0x0
2770
2771 #define PQI_CREATE_ADMIN_QUEUE_PAIR     1
2772 #define PQI_DELETE_ADMIN_QUEUE_PAIR     2
2773
2774 #define PQI_DEVICE_STATE_POWER_ON_AND_RESET             0x0
2775 #define PQI_DEVICE_STATE_STATUS_AVAILABLE               0x1
2776 #define PQI_DEVICE_STATE_ALL_REGISTERS_READY            0x2
2777 #define PQI_DEVICE_STATE_ADMIN_QUEUE_PAIR_READY         0x3
2778 #define PQI_DEVICE_STATE_ERROR                          0x4
2779
2780 #define PQI_MODE_READY_TIMEOUT_SECS             30
2781 #define PQI_MODE_READY_POLL_INTERVAL_MSECS      1
2782
2783 static int pqi_wait_for_pqi_mode_ready(struct pqi_ctrl_info *ctrl_info)
2784 {
2785         struct pqi_device_registers __iomem *pqi_registers;
2786         unsigned long timeout;
2787         u64 signature;
2788         u8 status;
2789
2790         pqi_registers = ctrl_info->pqi_registers;
2791         timeout = (PQI_MODE_READY_TIMEOUT_SECS * PQI_HZ) + jiffies;
2792
2793         while (1) {
2794                 signature = readq(&pqi_registers->signature);
2795                 if (memcmp(&signature, PQI_DEVICE_SIGNATURE,
2796                         sizeof(signature)) == 0)
2797                         break;
2798                 if (time_after(jiffies, timeout)) {
2799                         dev_err(&ctrl_info->pci_dev->dev,
2800                                 "timed out waiting for PQI signature\n");
2801                         return -ETIMEDOUT;
2802                 }
2803                 msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2804         }
2805
2806         while (1) {
2807                 status = readb(&pqi_registers->function_and_status_code);
2808                 if (status == PQI_STATUS_IDLE)
2809                         break;
2810                 if (time_after(jiffies, timeout)) {
2811                         dev_err(&ctrl_info->pci_dev->dev,
2812                                 "timed out waiting for PQI IDLE\n");
2813                         return -ETIMEDOUT;
2814                 }
2815                 msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2816         }
2817
2818         while (1) {
2819                 if (readl(&pqi_registers->device_status) ==
2820                         PQI_DEVICE_STATE_ALL_REGISTERS_READY)
2821                         break;
2822                 if (time_after(jiffies, timeout)) {
2823                         dev_err(&ctrl_info->pci_dev->dev,
2824                                 "timed out waiting for PQI all registers ready\n");
2825                         return -ETIMEDOUT;
2826                 }
2827                 msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2828         }
2829
2830         return 0;
2831 }
2832
2833 static inline void pqi_aio_path_disabled(struct pqi_io_request *io_request)
2834 {
2835         struct pqi_scsi_dev *device;
2836
2837         device = io_request->scmd->device->hostdata;
2838         device->raid_bypass_enabled = false;
2839         device->aio_enabled = false;
2840 }
2841
2842 static inline void pqi_take_device_offline(struct scsi_device *sdev, char *path)
2843 {
2844         struct pqi_ctrl_info *ctrl_info;
2845         struct pqi_scsi_dev *device;
2846
2847         device = sdev->hostdata;
2848         if (device->device_offline)
2849                 return;
2850
2851         device->device_offline = true;
2852         ctrl_info = shost_to_hba(sdev->host);
2853         pqi_schedule_rescan_worker(ctrl_info);
2854         dev_err(&ctrl_info->pci_dev->dev, "re-scanning %s scsi %d:%d:%d:%d\n",
2855                 path, ctrl_info->scsi_host->host_no, device->bus,
2856                 device->target, device->lun);
2857 }
2858
2859 static void pqi_process_raid_io_error(struct pqi_io_request *io_request)
2860 {
2861         u8 scsi_status;
2862         u8 host_byte;
2863         struct scsi_cmnd *scmd;
2864         struct pqi_raid_error_info *error_info;
2865         size_t sense_data_length;
2866         int residual_count;
2867         int xfer_count;
2868         struct scsi_sense_hdr sshdr;
2869
2870         scmd = io_request->scmd;
2871         if (!scmd)
2872                 return;
2873
2874         error_info = io_request->error_info;
2875         scsi_status = error_info->status;
2876         host_byte = DID_OK;
2877
2878         switch (error_info->data_out_result) {
2879         case PQI_DATA_IN_OUT_GOOD:
2880                 break;
2881         case PQI_DATA_IN_OUT_UNDERFLOW:
2882                 xfer_count =
2883                         get_unaligned_le32(&error_info->data_out_transferred);
2884                 residual_count = scsi_bufflen(scmd) - xfer_count;
2885                 scsi_set_resid(scmd, residual_count);
2886                 if (xfer_count < scmd->underflow)
2887                         host_byte = DID_SOFT_ERROR;
2888                 break;
2889         case PQI_DATA_IN_OUT_UNSOLICITED_ABORT:
2890         case PQI_DATA_IN_OUT_ABORTED:
2891                 host_byte = DID_ABORT;
2892                 break;
2893         case PQI_DATA_IN_OUT_TIMEOUT:
2894                 host_byte = DID_TIME_OUT;
2895                 break;
2896         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW:
2897         case PQI_DATA_IN_OUT_PROTOCOL_ERROR:
2898         case PQI_DATA_IN_OUT_BUFFER_ERROR:
2899         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_DESCRIPTOR_AREA:
2900         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_BRIDGE:
2901         case PQI_DATA_IN_OUT_ERROR:
2902         case PQI_DATA_IN_OUT_HARDWARE_ERROR:
2903         case PQI_DATA_IN_OUT_PCIE_FABRIC_ERROR:
2904         case PQI_DATA_IN_OUT_PCIE_COMPLETION_TIMEOUT:
2905         case PQI_DATA_IN_OUT_PCIE_COMPLETER_ABORT_RECEIVED:
2906         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST_RECEIVED:
2907         case PQI_DATA_IN_OUT_PCIE_ECRC_CHECK_FAILED:
2908         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST:
2909         case PQI_DATA_IN_OUT_PCIE_ACS_VIOLATION:
2910         case PQI_DATA_IN_OUT_PCIE_TLP_PREFIX_BLOCKED:
2911         case PQI_DATA_IN_OUT_PCIE_POISONED_MEMORY_READ:
2912         default:
2913                 host_byte = DID_ERROR;
2914                 break;
2915         }
2916
2917         sense_data_length = get_unaligned_le16(&error_info->sense_data_length);
2918         if (sense_data_length == 0)
2919                 sense_data_length =
2920                         get_unaligned_le16(&error_info->response_data_length);
2921         if (sense_data_length) {
2922                 if (sense_data_length > sizeof(error_info->data))
2923                         sense_data_length = sizeof(error_info->data);
2924
2925                 if (scsi_status == SAM_STAT_CHECK_CONDITION &&
2926                         scsi_normalize_sense(error_info->data,
2927                                 sense_data_length, &sshdr) &&
2928                                 sshdr.sense_key == HARDWARE_ERROR &&
2929                                 sshdr.asc == 0x3e) {
2930                         struct pqi_ctrl_info *ctrl_info = shost_to_hba(scmd->device->host);
2931                         struct pqi_scsi_dev *device = scmd->device->hostdata;
2932
2933                         switch (sshdr.ascq) {
2934                         case 0x1: /* LOGICAL UNIT FAILURE */
2935                                 if (printk_ratelimit())
2936                                         scmd_printk(KERN_ERR, scmd, "received 'logical unit failure' from controller for scsi %d:%d:%d:%d\n",
2937                                                 ctrl_info->scsi_host->host_no, device->bus, device->target, device->lun);
2938                                 pqi_take_device_offline(scmd->device, "RAID");
2939                                 host_byte = DID_NO_CONNECT;
2940                                 break;
2941
2942                         default: /* See http://www.t10.org/lists/asc-num.htm#ASC_3E */
2943                                 if (printk_ratelimit())
2944                                         scmd_printk(KERN_ERR, scmd, "received unhandled error %d from controller for scsi %d:%d:%d:%d\n",
2945                                                 sshdr.ascq, ctrl_info->scsi_host->host_no, device->bus, device->target, device->lun);
2946                                 break;
2947                         }
2948                 }
2949
2950                 if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
2951                         sense_data_length = SCSI_SENSE_BUFFERSIZE;
2952                 memcpy(scmd->sense_buffer, error_info->data,
2953                         sense_data_length);
2954         }
2955
2956         scmd->result = scsi_status;
2957         set_host_byte(scmd, host_byte);
2958 }
2959
2960 static void pqi_process_aio_io_error(struct pqi_io_request *io_request)
2961 {
2962         u8 scsi_status;
2963         u8 host_byte;
2964         struct scsi_cmnd *scmd;
2965         struct pqi_aio_error_info *error_info;
2966         size_t sense_data_length;
2967         int residual_count;
2968         int xfer_count;
2969         bool device_offline;
2970
2971         scmd = io_request->scmd;
2972         error_info = io_request->error_info;
2973         host_byte = DID_OK;
2974         sense_data_length = 0;
2975         device_offline = false;
2976
2977         switch (error_info->service_response) {
2978         case PQI_AIO_SERV_RESPONSE_COMPLETE:
2979                 scsi_status = error_info->status;
2980                 break;
2981         case PQI_AIO_SERV_RESPONSE_FAILURE:
2982                 switch (error_info->status) {
2983                 case PQI_AIO_STATUS_IO_ABORTED:
2984                         scsi_status = SAM_STAT_TASK_ABORTED;
2985                         break;
2986                 case PQI_AIO_STATUS_UNDERRUN:
2987                         scsi_status = SAM_STAT_GOOD;
2988                         residual_count = get_unaligned_le32(
2989                                                 &error_info->residual_count);
2990                         scsi_set_resid(scmd, residual_count);
2991                         xfer_count = scsi_bufflen(scmd) - residual_count;
2992                         if (xfer_count < scmd->underflow)
2993                                 host_byte = DID_SOFT_ERROR;
2994                         break;
2995                 case PQI_AIO_STATUS_OVERRUN:
2996                         scsi_status = SAM_STAT_GOOD;
2997                         break;
2998                 case PQI_AIO_STATUS_AIO_PATH_DISABLED:
2999                         pqi_aio_path_disabled(io_request);
3000                         scsi_status = SAM_STAT_GOOD;
3001                         io_request->status = -EAGAIN;
3002                         break;
3003                 case PQI_AIO_STATUS_NO_PATH_TO_DEVICE:
3004                 case PQI_AIO_STATUS_INVALID_DEVICE:
3005                         if (!io_request->raid_bypass) {
3006                                 device_offline = true;
3007                                 pqi_take_device_offline(scmd->device, "AIO");
3008                                 host_byte = DID_NO_CONNECT;
3009                         }
3010                         scsi_status = SAM_STAT_CHECK_CONDITION;
3011                         break;
3012                 case PQI_AIO_STATUS_IO_ERROR:
3013                 default:
3014                         scsi_status = SAM_STAT_CHECK_CONDITION;
3015                         break;
3016                 }
3017                 break;
3018         case PQI_AIO_SERV_RESPONSE_TMF_COMPLETE:
3019         case PQI_AIO_SERV_RESPONSE_TMF_SUCCEEDED:
3020                 scsi_status = SAM_STAT_GOOD;
3021                 break;
3022         case PQI_AIO_SERV_RESPONSE_TMF_REJECTED:
3023         case PQI_AIO_SERV_RESPONSE_TMF_INCORRECT_LUN:
3024         default:
3025                 scsi_status = SAM_STAT_CHECK_CONDITION;
3026                 break;
3027         }
3028
3029         if (error_info->data_present) {
3030                 sense_data_length =
3031                         get_unaligned_le16(&error_info->data_length);
3032                 if (sense_data_length) {
3033                         if (sense_data_length > sizeof(error_info->data))
3034                                 sense_data_length = sizeof(error_info->data);
3035                         if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
3036                                 sense_data_length = SCSI_SENSE_BUFFERSIZE;
3037                         memcpy(scmd->sense_buffer, error_info->data,
3038                                 sense_data_length);
3039                 }
3040         }
3041
3042         if (device_offline && sense_data_length == 0)
3043                 scsi_build_sense_buffer(0, scmd->sense_buffer, HARDWARE_ERROR,
3044                         0x3e, 0x1);
3045
3046         scmd->result = scsi_status;
3047         set_host_byte(scmd, host_byte);
3048 }
3049
3050 static void pqi_process_io_error(unsigned int iu_type,
3051         struct pqi_io_request *io_request)
3052 {
3053         switch (iu_type) {
3054         case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
3055                 pqi_process_raid_io_error(io_request);
3056                 break;
3057         case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
3058                 pqi_process_aio_io_error(io_request);
3059                 break;
3060         }
3061 }
3062
3063 static int pqi_interpret_task_management_response(
3064         struct pqi_task_management_response *response)
3065 {
3066         int rc;
3067
3068         switch (response->response_code) {
3069         case SOP_TMF_COMPLETE:
3070         case SOP_TMF_FUNCTION_SUCCEEDED:
3071                 rc = 0;
3072                 break;
3073         case SOP_TMF_REJECTED:
3074                 rc = -EAGAIN;
3075                 break;
3076         default:
3077                 rc = -EIO;
3078                 break;
3079         }
3080
3081         return rc;
3082 }
3083
3084 static inline void pqi_invalid_response(struct pqi_ctrl_info *ctrl_info)
3085 {
3086         pqi_take_ctrl_offline(ctrl_info);
3087 }
3088
3089 static int pqi_process_io_intr(struct pqi_ctrl_info *ctrl_info, struct pqi_queue_group *queue_group)
3090 {
3091         int num_responses;
3092         pqi_index_t oq_pi;
3093         pqi_index_t oq_ci;
3094         struct pqi_io_request *io_request;
3095         struct pqi_io_response *response;
3096         u16 request_id;
3097
3098         num_responses = 0;
3099         oq_ci = queue_group->oq_ci_copy;
3100
3101         while (1) {
3102                 oq_pi = readl(queue_group->oq_pi);
3103                 if (oq_pi >= ctrl_info->num_elements_per_oq) {
3104                         pqi_invalid_response(ctrl_info);
3105                         dev_err(&ctrl_info->pci_dev->dev,
3106                                 "I/O interrupt: producer index (%u) out of range (0-%u): consumer index: %u\n",
3107                                 oq_pi, ctrl_info->num_elements_per_oq - 1, oq_ci);
3108                         return -1;
3109                 }
3110                 if (oq_pi == oq_ci)
3111                         break;
3112
3113                 num_responses++;
3114                 response = queue_group->oq_element_array +
3115                         (oq_ci * PQI_OPERATIONAL_OQ_ELEMENT_LENGTH);
3116
3117                 request_id = get_unaligned_le16(&response->request_id);
3118                 if (request_id >= ctrl_info->max_io_slots) {
3119                         pqi_invalid_response(ctrl_info);
3120                         dev_err(&ctrl_info->pci_dev->dev,
3121                                 "request ID in response (%u) out of range (0-%u): producer index: %u  consumer index: %u\n",
3122                                 request_id, ctrl_info->max_io_slots - 1, oq_pi, oq_ci);
3123                         return -1;
3124                 }
3125
3126                 io_request = &ctrl_info->io_request_pool[request_id];
3127                 if (atomic_read(&io_request->refcount) == 0) {
3128                         pqi_invalid_response(ctrl_info);
3129                         dev_err(&ctrl_info->pci_dev->dev,
3130                                 "request ID in response (%u) does not match an outstanding I/O request: producer index: %u  consumer index: %u\n",
3131                                 request_id, oq_pi, oq_ci);
3132                         return -1;
3133                 }
3134
3135                 switch (response->header.iu_type) {
3136                 case PQI_RESPONSE_IU_RAID_PATH_IO_SUCCESS:
3137                 case PQI_RESPONSE_IU_AIO_PATH_IO_SUCCESS:
3138                         if (io_request->scmd)
3139                                 io_request->scmd->result = 0;
3140                         fallthrough;
3141                 case PQI_RESPONSE_IU_GENERAL_MANAGEMENT:
3142                         break;
3143                 case PQI_RESPONSE_IU_VENDOR_GENERAL:
3144                         io_request->status =
3145                                 get_unaligned_le16(
3146                                 &((struct pqi_vendor_general_response *)response)->status);
3147                         break;
3148                 case PQI_RESPONSE_IU_TASK_MANAGEMENT:
3149                         io_request->status =
3150                                 pqi_interpret_task_management_response(
3151                                         (void *)response);
3152                         break;
3153                 case PQI_RESPONSE_IU_AIO_PATH_DISABLED:
3154                         pqi_aio_path_disabled(io_request);
3155                         io_request->status = -EAGAIN;
3156                         break;
3157                 case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
3158                 case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
3159                         io_request->error_info = ctrl_info->error_buffer +
3160                                 (get_unaligned_le16(&response->error_index) *
3161                                 PQI_ERROR_BUFFER_ELEMENT_LENGTH);
3162                         pqi_process_io_error(response->header.iu_type, io_request);
3163                         break;
3164                 default:
3165                         pqi_invalid_response(ctrl_info);
3166                         dev_err(&ctrl_info->pci_dev->dev,
3167                                 "unexpected IU type: 0x%x: producer index: %u  consumer index: %u\n",
3168                                 response->header.iu_type, oq_pi, oq_ci);
3169                         return -1;
3170                 }
3171
3172                 io_request->io_complete_callback(io_request, io_request->context);
3173
3174                 /*
3175                  * Note that the I/O request structure CANNOT BE TOUCHED after
3176                  * returning from the I/O completion callback!
3177                  */
3178                 oq_ci = (oq_ci + 1) % ctrl_info->num_elements_per_oq;
3179         }
3180
3181         if (num_responses) {
3182                 queue_group->oq_ci_copy = oq_ci;
3183                 writel(oq_ci, queue_group->oq_ci);
3184         }
3185
3186         return num_responses;
3187 }
3188
3189 static inline unsigned int pqi_num_elements_free(unsigned int pi,
3190         unsigned int ci, unsigned int elements_in_queue)
3191 {
3192         unsigned int num_elements_used;
3193
3194         if (pi >= ci)
3195                 num_elements_used = pi - ci;
3196         else
3197                 num_elements_used = elements_in_queue - ci + pi;
3198
3199         return elements_in_queue - num_elements_used - 1;
3200 }
3201
3202 static void pqi_send_event_ack(struct pqi_ctrl_info *ctrl_info,
3203         struct pqi_event_acknowledge_request *iu, size_t iu_length)
3204 {
3205         pqi_index_t iq_pi;
3206         pqi_index_t iq_ci;
3207         unsigned long flags;
3208         void *next_element;
3209         struct pqi_queue_group *queue_group;
3210
3211         queue_group = &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP];
3212         put_unaligned_le16(queue_group->oq_id, &iu->header.response_queue_id);
3213
3214         while (1) {
3215                 spin_lock_irqsave(&queue_group->submit_lock[RAID_PATH], flags);
3216
3217                 iq_pi = queue_group->iq_pi_copy[RAID_PATH];
3218                 iq_ci = readl(queue_group->iq_ci[RAID_PATH]);
3219
3220                 if (pqi_num_elements_free(iq_pi, iq_ci,
3221                         ctrl_info->num_elements_per_iq))
3222                         break;
3223
3224                 spin_unlock_irqrestore(
3225                         &queue_group->submit_lock[RAID_PATH], flags);
3226
3227                 if (pqi_ctrl_offline(ctrl_info))
3228                         return;
3229         }
3230
3231         next_element = queue_group->iq_element_array[RAID_PATH] +
3232                 (iq_pi * PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
3233
3234         memcpy(next_element, iu, iu_length);
3235
3236         iq_pi = (iq_pi + 1) % ctrl_info->num_elements_per_iq;
3237         queue_group->iq_pi_copy[RAID_PATH] = iq_pi;
3238
3239         /*
3240          * This write notifies the controller that an IU is available to be
3241          * processed.
3242          */
3243         writel(iq_pi, queue_group->iq_pi[RAID_PATH]);
3244
3245         spin_unlock_irqrestore(&queue_group->submit_lock[RAID_PATH], flags);
3246 }
3247
3248 static void pqi_acknowledge_event(struct pqi_ctrl_info *ctrl_info,
3249         struct pqi_event *event)
3250 {
3251         struct pqi_event_acknowledge_request request;
3252
3253         memset(&request, 0, sizeof(request));
3254
3255         request.header.iu_type = PQI_REQUEST_IU_ACKNOWLEDGE_VENDOR_EVENT;
3256         put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
3257                 &request.header.iu_length);
3258         request.event_type = event->event_type;
3259         request.event_id = event->event_id;
3260         request.additional_event_id = event->additional_event_id;
3261
3262         pqi_send_event_ack(ctrl_info, &request, sizeof(request));
3263 }
3264
3265 #define PQI_SOFT_RESET_STATUS_TIMEOUT_SECS              30
3266 #define PQI_SOFT_RESET_STATUS_POLL_INTERVAL_SECS        1
3267
3268 static enum pqi_soft_reset_status pqi_poll_for_soft_reset_status(
3269         struct pqi_ctrl_info *ctrl_info)
3270 {
3271         u8 status;
3272         unsigned long timeout;
3273
3274         timeout = (PQI_SOFT_RESET_STATUS_TIMEOUT_SECS * PQI_HZ) + jiffies;
3275
3276         while (1) {
3277                 status = pqi_read_soft_reset_status(ctrl_info);
3278                 if (status & PQI_SOFT_RESET_INITIATE)
3279                         return RESET_INITIATE_DRIVER;
3280
3281                 if (status & PQI_SOFT_RESET_ABORT)
3282                         return RESET_ABORT;
3283
3284                 if (time_after(jiffies, timeout)) {
3285                         dev_err(&ctrl_info->pci_dev->dev,
3286                                 "timed out waiting for soft reset status\n");
3287                         return RESET_TIMEDOUT;
3288                 }
3289
3290                 if (!sis_is_firmware_running(ctrl_info))
3291                         return RESET_NORESPONSE;
3292
3293                 ssleep(PQI_SOFT_RESET_STATUS_POLL_INTERVAL_SECS);
3294         }
3295 }
3296
3297 static void pqi_process_soft_reset(struct pqi_ctrl_info *ctrl_info,
3298         enum pqi_soft_reset_status reset_status)
3299 {
3300         int rc;
3301
3302         switch (reset_status) {
3303         case RESET_INITIATE_DRIVER:
3304         case RESET_TIMEDOUT:
3305                 dev_info(&ctrl_info->pci_dev->dev,
3306                         "resetting controller %u\n", ctrl_info->ctrl_id);
3307                 sis_soft_reset(ctrl_info);
3308                 fallthrough;
3309         case RESET_INITIATE_FIRMWARE:
3310                 rc = pqi_ofa_ctrl_restart(ctrl_info);
3311                 pqi_ofa_free_host_buffer(ctrl_info);
3312                 dev_info(&ctrl_info->pci_dev->dev,
3313                         "Online Firmware Activation for controller %u: %s\n",
3314                         ctrl_info->ctrl_id, rc == 0 ? "SUCCESS" : "FAILED");
3315                 break;
3316         case RESET_ABORT:
3317                 pqi_ofa_ctrl_unquiesce(ctrl_info);
3318                 dev_info(&ctrl_info->pci_dev->dev,
3319                         "Online Firmware Activation for controller %u: %s\n",
3320                         ctrl_info->ctrl_id, "ABORTED");
3321                 break;
3322         case RESET_NORESPONSE:
3323                 pqi_ofa_free_host_buffer(ctrl_info);
3324                 pqi_take_ctrl_offline(ctrl_info);
3325                 break;
3326         }
3327 }
3328
3329 static void pqi_ofa_process_event(struct pqi_ctrl_info *ctrl_info,
3330         struct pqi_event *event)
3331 {
3332         u16 event_id;
3333         enum pqi_soft_reset_status status;
3334
3335         event_id = get_unaligned_le16(&event->event_id);
3336
3337         mutex_lock(&ctrl_info->ofa_mutex);
3338
3339         if (event_id == PQI_EVENT_OFA_QUIESCE) {
3340                 dev_info(&ctrl_info->pci_dev->dev,
3341                         "Received Online Firmware Activation quiesce event for controller %u\n",
3342                         ctrl_info->ctrl_id);
3343                 pqi_ofa_ctrl_quiesce(ctrl_info);
3344                 pqi_acknowledge_event(ctrl_info, event);
3345                 if (ctrl_info->soft_reset_handshake_supported) {
3346                         status = pqi_poll_for_soft_reset_status(ctrl_info);
3347                         pqi_process_soft_reset(ctrl_info, status);
3348                 } else {
3349                         pqi_process_soft_reset(ctrl_info,
3350                                         RESET_INITIATE_FIRMWARE);
3351                 }
3352
3353         } else if (event_id == PQI_EVENT_OFA_MEMORY_ALLOCATION) {
3354                 pqi_acknowledge_event(ctrl_info, event);
3355                 pqi_ofa_setup_host_buffer(ctrl_info,
3356                         le32_to_cpu(event->ofa_bytes_requested));
3357                 pqi_ofa_host_memory_update(ctrl_info);
3358         } else if (event_id == PQI_EVENT_OFA_CANCELED) {
3359                 pqi_ofa_free_host_buffer(ctrl_info);
3360                 pqi_acknowledge_event(ctrl_info, event);
3361                 dev_info(&ctrl_info->pci_dev->dev,
3362                         "Online Firmware Activation(%u) cancel reason : %u\n",
3363                         ctrl_info->ctrl_id, event->ofa_cancel_reason);
3364         }
3365
3366         mutex_unlock(&ctrl_info->ofa_mutex);
3367 }
3368
3369 static void pqi_event_worker(struct work_struct *work)
3370 {
3371         unsigned int i;
3372         struct pqi_ctrl_info *ctrl_info;
3373         struct pqi_event *event;
3374
3375         ctrl_info = container_of(work, struct pqi_ctrl_info, event_work);
3376
3377         pqi_ctrl_busy(ctrl_info);
3378         pqi_wait_if_ctrl_blocked(ctrl_info, NO_TIMEOUT);
3379         if (pqi_ctrl_offline(ctrl_info))
3380                 goto out;
3381
3382         pqi_schedule_rescan_worker_delayed(ctrl_info);
3383
3384         event = ctrl_info->events;
3385         for (i = 0; i < PQI_NUM_SUPPORTED_EVENTS; i++) {
3386                 if (event->pending) {
3387                         event->pending = false;
3388                         if (event->event_type == PQI_EVENT_TYPE_OFA) {
3389                                 pqi_ctrl_unbusy(ctrl_info);
3390                                 pqi_ofa_process_event(ctrl_info, event);
3391                                 return;
3392                         }
3393                         pqi_acknowledge_event(ctrl_info, event);
3394                 }
3395                 event++;
3396         }
3397
3398 out:
3399         pqi_ctrl_unbusy(ctrl_info);
3400 }
3401
3402 #define PQI_HEARTBEAT_TIMER_INTERVAL    (10 * PQI_HZ)
3403
3404 static void pqi_heartbeat_timer_handler(struct timer_list *t)
3405 {
3406         int num_interrupts;
3407         u32 heartbeat_count;
3408         struct pqi_ctrl_info *ctrl_info = from_timer(ctrl_info, t, heartbeat_timer);
3409
3410         pqi_check_ctrl_health(ctrl_info);
3411         if (pqi_ctrl_offline(ctrl_info))
3412                 return;
3413
3414         num_interrupts = atomic_read(&ctrl_info->num_interrupts);
3415         heartbeat_count = pqi_read_heartbeat_counter(ctrl_info);
3416
3417         if (num_interrupts == ctrl_info->previous_num_interrupts) {
3418                 if (heartbeat_count == ctrl_info->previous_heartbeat_count) {
3419                         dev_err(&ctrl_info->pci_dev->dev,
3420                                 "no heartbeat detected - last heartbeat count: %u\n",
3421                                 heartbeat_count);
3422                         pqi_take_ctrl_offline(ctrl_info);
3423                         return;
3424                 }
3425         } else {
3426                 ctrl_info->previous_num_interrupts = num_interrupts;
3427         }
3428
3429         ctrl_info->previous_heartbeat_count = heartbeat_count;
3430         mod_timer(&ctrl_info->heartbeat_timer,
3431                 jiffies + PQI_HEARTBEAT_TIMER_INTERVAL);
3432 }
3433
3434 static void pqi_start_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
3435 {
3436         if (!ctrl_info->heartbeat_counter)
3437                 return;
3438
3439         ctrl_info->previous_num_interrupts =
3440                 atomic_read(&ctrl_info->num_interrupts);
3441         ctrl_info->previous_heartbeat_count =
3442                 pqi_read_heartbeat_counter(ctrl_info);
3443
3444         ctrl_info->heartbeat_timer.expires =
3445                 jiffies + PQI_HEARTBEAT_TIMER_INTERVAL;
3446         add_timer(&ctrl_info->heartbeat_timer);
3447 }
3448
3449 static inline void pqi_stop_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
3450 {
3451         del_timer_sync(&ctrl_info->heartbeat_timer);
3452 }
3453
3454 static inline int pqi_event_type_to_event_index(unsigned int event_type)
3455 {
3456         int index;
3457
3458         for (index = 0; index < ARRAY_SIZE(pqi_supported_event_types); index++)
3459                 if (event_type == pqi_supported_event_types[index])
3460                         return index;
3461
3462         return -1;
3463 }
3464
3465 static inline bool pqi_is_supported_event(unsigned int event_type)
3466 {
3467         return pqi_event_type_to_event_index(event_type) != -1;
3468 }
3469
3470 static void pqi_ofa_capture_event_payload(struct pqi_event *event,
3471         struct pqi_event_response *response)
3472 {
3473         u16 event_id;
3474
3475         event_id = get_unaligned_le16(&event->event_id);
3476
3477         if (event->event_type == PQI_EVENT_TYPE_OFA) {
3478                 if (event_id == PQI_EVENT_OFA_MEMORY_ALLOCATION) {
3479                         event->ofa_bytes_requested =
3480                         response->data.ofa_memory_allocation.bytes_requested;
3481                 } else if (event_id == PQI_EVENT_OFA_CANCELED) {
3482                         event->ofa_cancel_reason =
3483                         response->data.ofa_cancelled.reason;
3484                 }
3485         }
3486 }
3487
3488 static int pqi_process_event_intr(struct pqi_ctrl_info *ctrl_info)
3489 {
3490         int num_events;
3491         pqi_index_t oq_pi;
3492         pqi_index_t oq_ci;
3493         struct pqi_event_queue *event_queue;
3494         struct pqi_event_response *response;
3495         struct pqi_event *event;
3496         int event_index;
3497
3498         event_queue = &ctrl_info->event_queue;
3499         num_events = 0;
3500         oq_ci = event_queue->oq_ci_copy;
3501
3502         while (1) {
3503                 oq_pi = readl(event_queue->oq_pi);
3504                 if (oq_pi >= PQI_NUM_EVENT_QUEUE_ELEMENTS) {
3505                         pqi_invalid_response(ctrl_info);
3506                         dev_err(&ctrl_info->pci_dev->dev,
3507                                 "event interrupt: producer index (%u) out of range (0-%u): consumer index: %u\n",
3508                                 oq_pi, PQI_NUM_EVENT_QUEUE_ELEMENTS - 1, oq_ci);
3509                         return -1;
3510                 }
3511
3512                 if (oq_pi == oq_ci)
3513                         break;
3514
3515                 num_events++;
3516                 response = event_queue->oq_element_array + (oq_ci * PQI_EVENT_OQ_ELEMENT_LENGTH);
3517
3518                 event_index = pqi_event_type_to_event_index(response->event_type);
3519
3520                 if (event_index >= 0 && response->request_acknowledge) {
3521                         event = &ctrl_info->events[event_index];
3522                         event->pending = true;
3523                         event->event_type = response->event_type;
3524                         event->event_id = response->event_id;
3525                         event->additional_event_id = response->additional_event_id;
3526                         if (event->event_type == PQI_EVENT_TYPE_OFA)
3527                                 pqi_ofa_capture_event_payload(event, response);
3528                 }
3529
3530                 oq_ci = (oq_ci + 1) % PQI_NUM_EVENT_QUEUE_ELEMENTS;
3531         }
3532
3533         if (num_events) {
3534                 event_queue->oq_ci_copy = oq_ci;
3535                 writel(oq_ci, event_queue->oq_ci);
3536                 schedule_work(&ctrl_info->event_work);
3537         }
3538
3539         return num_events;
3540 }
3541
3542 #define PQI_LEGACY_INTX_MASK    0x1
3543
3544 static inline void pqi_configure_legacy_intx(struct pqi_ctrl_info *ctrl_info, bool enable_intx)
3545 {
3546         u32 intx_mask;
3547         struct pqi_device_registers __iomem *pqi_registers;
3548         volatile void __iomem *register_addr;
3549
3550         pqi_registers = ctrl_info->pqi_registers;
3551
3552         if (enable_intx)
3553                 register_addr = &pqi_registers->legacy_intx_mask_clear;
3554         else
3555                 register_addr = &pqi_registers->legacy_intx_mask_set;
3556
3557         intx_mask = readl(register_addr);
3558         intx_mask |= PQI_LEGACY_INTX_MASK;
3559         writel(intx_mask, register_addr);
3560 }
3561
3562 static void pqi_change_irq_mode(struct pqi_ctrl_info *ctrl_info,
3563         enum pqi_irq_mode new_mode)
3564 {
3565         switch (ctrl_info->irq_mode) {
3566         case IRQ_MODE_MSIX:
3567                 switch (new_mode) {
3568                 case IRQ_MODE_MSIX:
3569                         break;
3570                 case IRQ_MODE_INTX:
3571                         pqi_configure_legacy_intx(ctrl_info, true);
3572                         sis_enable_intx(ctrl_info);
3573                         break;
3574                 case IRQ_MODE_NONE:
3575                         break;
3576                 }
3577                 break;
3578         case IRQ_MODE_INTX:
3579                 switch (new_mode) {
3580                 case IRQ_MODE_MSIX:
3581                         pqi_configure_legacy_intx(ctrl_info, false);
3582                         sis_enable_msix(ctrl_info);
3583                         break;
3584                 case IRQ_MODE_INTX:
3585                         break;
3586                 case IRQ_MODE_NONE:
3587                         pqi_configure_legacy_intx(ctrl_info, false);
3588                         break;
3589                 }
3590                 break;
3591         case IRQ_MODE_NONE:
3592                 switch (new_mode) {
3593                 case IRQ_MODE_MSIX:
3594                         sis_enable_msix(ctrl_info);
3595                         break;
3596                 case IRQ_MODE_INTX:
3597                         pqi_configure_legacy_intx(ctrl_info, true);
3598                         sis_enable_intx(ctrl_info);
3599                         break;
3600                 case IRQ_MODE_NONE:
3601                         break;
3602                 }
3603                 break;
3604         }
3605
3606         ctrl_info->irq_mode = new_mode;
3607 }
3608
3609 #define PQI_LEGACY_INTX_PENDING         0x1
3610
3611 static inline bool pqi_is_valid_irq(struct pqi_ctrl_info *ctrl_info)
3612 {
3613         bool valid_irq;
3614         u32 intx_status;
3615
3616         switch (ctrl_info->irq_mode) {
3617         case IRQ_MODE_MSIX:
3618                 valid_irq = true;
3619                 break;
3620         case IRQ_MODE_INTX:
3621                 intx_status = readl(&ctrl_info->pqi_registers->legacy_intx_status);
3622                 if (intx_status & PQI_LEGACY_INTX_PENDING)
3623                         valid_irq = true;
3624                 else
3625                         valid_irq = false;
3626                 break;
3627         case IRQ_MODE_NONE:
3628         default:
3629                 valid_irq = false;
3630                 break;
3631         }
3632
3633         return valid_irq;
3634 }
3635
3636 static irqreturn_t pqi_irq_handler(int irq, void *data)
3637 {
3638         struct pqi_ctrl_info *ctrl_info;
3639         struct pqi_queue_group *queue_group;
3640         int num_io_responses_handled;
3641         int num_events_handled;
3642
3643         queue_group = data;
3644         ctrl_info = queue_group->ctrl_info;
3645
3646         if (!pqi_is_valid_irq(ctrl_info))
3647                 return IRQ_NONE;
3648
3649         num_io_responses_handled = pqi_process_io_intr(ctrl_info, queue_group);
3650         if (num_io_responses_handled < 0)
3651                 goto out;
3652
3653         if (irq == ctrl_info->event_irq) {
3654                 num_events_handled = pqi_process_event_intr(ctrl_info);
3655                 if (num_events_handled < 0)
3656                         goto out;
3657         } else {
3658                 num_events_handled = 0;
3659         }
3660
3661         if (num_io_responses_handled + num_events_handled > 0)
3662                 atomic_inc(&ctrl_info->num_interrupts);
3663
3664         pqi_start_io(ctrl_info, queue_group, RAID_PATH, NULL);
3665         pqi_start_io(ctrl_info, queue_group, AIO_PATH, NULL);
3666
3667 out:
3668         return IRQ_HANDLED;
3669 }
3670
3671 static int pqi_request_irqs(struct pqi_ctrl_info *ctrl_info)
3672 {
3673         struct pci_dev *pci_dev = ctrl_info->pci_dev;
3674         int i;
3675         int rc;
3676
3677         ctrl_info->event_irq = pci_irq_vector(pci_dev, 0);
3678
3679         for (i = 0; i < ctrl_info->num_msix_vectors_enabled; i++) {
3680                 rc = request_irq(pci_irq_vector(pci_dev, i), pqi_irq_handler, 0,
3681                         DRIVER_NAME_SHORT, &ctrl_info->queue_groups[i]);
3682                 if (rc) {
3683                         dev_err(&pci_dev->dev,
3684                                 "irq %u init failed with error %d\n",
3685                                 pci_irq_vector(pci_dev, i), rc);
3686                         return rc;
3687                 }
3688                 ctrl_info->num_msix_vectors_initialized++;
3689         }
3690
3691         return 0;
3692 }
3693
3694 static void pqi_free_irqs(struct pqi_ctrl_info *ctrl_info)
3695 {
3696         int i;
3697
3698         for (i = 0; i < ctrl_info->num_msix_vectors_initialized; i++)
3699                 free_irq(pci_irq_vector(ctrl_info->pci_dev, i),
3700                         &ctrl_info->queue_groups[i]);
3701
3702         ctrl_info->num_msix_vectors_initialized = 0;
3703 }
3704
3705 static int pqi_enable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3706 {
3707         int num_vectors_enabled;
3708
3709         num_vectors_enabled = pci_alloc_irq_vectors(ctrl_info->pci_dev,
3710                         PQI_MIN_MSIX_VECTORS, ctrl_info->num_queue_groups,
3711                         PCI_IRQ_MSIX | PCI_IRQ_AFFINITY);
3712         if (num_vectors_enabled < 0) {
3713                 dev_err(&ctrl_info->pci_dev->dev,
3714                         "MSI-X init failed with error %d\n",
3715                         num_vectors_enabled);
3716                 return num_vectors_enabled;
3717         }
3718
3719         ctrl_info->num_msix_vectors_enabled = num_vectors_enabled;
3720         ctrl_info->irq_mode = IRQ_MODE_MSIX;
3721         return 0;
3722 }
3723
3724 static void pqi_disable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3725 {
3726         if (ctrl_info->num_msix_vectors_enabled) {
3727                 pci_free_irq_vectors(ctrl_info->pci_dev);
3728                 ctrl_info->num_msix_vectors_enabled = 0;
3729         }
3730 }
3731
3732 static int pqi_alloc_operational_queues(struct pqi_ctrl_info *ctrl_info)
3733 {
3734         unsigned int i;
3735         size_t alloc_length;
3736         size_t element_array_length_per_iq;
3737         size_t element_array_length_per_oq;
3738         void *element_array;
3739         void __iomem *next_queue_index;
3740         void *aligned_pointer;
3741         unsigned int num_inbound_queues;
3742         unsigned int num_outbound_queues;
3743         unsigned int num_queue_indexes;
3744         struct pqi_queue_group *queue_group;
3745
3746         element_array_length_per_iq =
3747                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH *
3748                 ctrl_info->num_elements_per_iq;
3749         element_array_length_per_oq =
3750                 PQI_OPERATIONAL_OQ_ELEMENT_LENGTH *
3751                 ctrl_info->num_elements_per_oq;
3752         num_inbound_queues = ctrl_info->num_queue_groups * 2;
3753         num_outbound_queues = ctrl_info->num_queue_groups;
3754         num_queue_indexes = (ctrl_info->num_queue_groups * 3) + 1;
3755
3756         aligned_pointer = NULL;
3757
3758         for (i = 0; i < num_inbound_queues; i++) {
3759                 aligned_pointer = PTR_ALIGN(aligned_pointer,
3760                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3761                 aligned_pointer += element_array_length_per_iq;
3762         }
3763
3764         for (i = 0; i < num_outbound_queues; i++) {
3765                 aligned_pointer = PTR_ALIGN(aligned_pointer,
3766                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3767                 aligned_pointer += element_array_length_per_oq;
3768         }
3769
3770         aligned_pointer = PTR_ALIGN(aligned_pointer,
3771                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3772         aligned_pointer += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3773                 PQI_EVENT_OQ_ELEMENT_LENGTH;
3774
3775         for (i = 0; i < num_queue_indexes; i++) {
3776                 aligned_pointer = PTR_ALIGN(aligned_pointer,
3777                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3778                 aligned_pointer += sizeof(pqi_index_t);
3779         }
3780
3781         alloc_length = (size_t)aligned_pointer +
3782                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
3783
3784         alloc_length += PQI_EXTRA_SGL_MEMORY;
3785
3786         ctrl_info->queue_memory_base =
3787                 dma_alloc_coherent(&ctrl_info->pci_dev->dev, alloc_length,
3788                                    &ctrl_info->queue_memory_base_dma_handle,
3789                                    GFP_KERNEL);
3790
3791         if (!ctrl_info->queue_memory_base)
3792                 return -ENOMEM;
3793
3794         ctrl_info->queue_memory_length = alloc_length;
3795
3796         element_array = PTR_ALIGN(ctrl_info->queue_memory_base,
3797                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3798
3799         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3800                 queue_group = &ctrl_info->queue_groups[i];
3801                 queue_group->iq_element_array[RAID_PATH] = element_array;
3802                 queue_group->iq_element_array_bus_addr[RAID_PATH] =
3803                         ctrl_info->queue_memory_base_dma_handle +
3804                                 (element_array - ctrl_info->queue_memory_base);
3805                 element_array += element_array_length_per_iq;
3806                 element_array = PTR_ALIGN(element_array,
3807                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3808                 queue_group->iq_element_array[AIO_PATH] = element_array;
3809                 queue_group->iq_element_array_bus_addr[AIO_PATH] =
3810                         ctrl_info->queue_memory_base_dma_handle +
3811                         (element_array - ctrl_info->queue_memory_base);
3812                 element_array += element_array_length_per_iq;
3813                 element_array = PTR_ALIGN(element_array,
3814                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3815         }
3816
3817         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3818                 queue_group = &ctrl_info->queue_groups[i];
3819                 queue_group->oq_element_array = element_array;
3820                 queue_group->oq_element_array_bus_addr =
3821                         ctrl_info->queue_memory_base_dma_handle +
3822                         (element_array - ctrl_info->queue_memory_base);
3823                 element_array += element_array_length_per_oq;
3824                 element_array = PTR_ALIGN(element_array,
3825                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3826         }
3827
3828         ctrl_info->event_queue.oq_element_array = element_array;
3829         ctrl_info->event_queue.oq_element_array_bus_addr =
3830                 ctrl_info->queue_memory_base_dma_handle +
3831                 (element_array - ctrl_info->queue_memory_base);
3832         element_array += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3833                 PQI_EVENT_OQ_ELEMENT_LENGTH;
3834
3835         next_queue_index = (void __iomem *)PTR_ALIGN(element_array,
3836                 PQI_OPERATIONAL_INDEX_ALIGNMENT);
3837
3838         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3839                 queue_group = &ctrl_info->queue_groups[i];
3840                 queue_group->iq_ci[RAID_PATH] = next_queue_index;
3841                 queue_group->iq_ci_bus_addr[RAID_PATH] =
3842                         ctrl_info->queue_memory_base_dma_handle +
3843                         (next_queue_index -
3844                         (void __iomem *)ctrl_info->queue_memory_base);
3845                 next_queue_index += sizeof(pqi_index_t);
3846                 next_queue_index = PTR_ALIGN(next_queue_index,
3847                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3848                 queue_group->iq_ci[AIO_PATH] = next_queue_index;
3849                 queue_group->iq_ci_bus_addr[AIO_PATH] =
3850                         ctrl_info->queue_memory_base_dma_handle +
3851                         (next_queue_index -
3852                         (void __iomem *)ctrl_info->queue_memory_base);
3853                 next_queue_index += sizeof(pqi_index_t);
3854                 next_queue_index = PTR_ALIGN(next_queue_index,
3855                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3856                 queue_group->oq_pi = next_queue_index;
3857                 queue_group->oq_pi_bus_addr =
3858                         ctrl_info->queue_memory_base_dma_handle +
3859                         (next_queue_index -
3860                         (void __iomem *)ctrl_info->queue_memory_base);
3861                 next_queue_index += sizeof(pqi_index_t);
3862                 next_queue_index = PTR_ALIGN(next_queue_index,
3863                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3864         }
3865
3866         ctrl_info->event_queue.oq_pi = next_queue_index;
3867         ctrl_info->event_queue.oq_pi_bus_addr =
3868                 ctrl_info->queue_memory_base_dma_handle +
3869                 (next_queue_index -
3870                 (void __iomem *)ctrl_info->queue_memory_base);
3871
3872         return 0;
3873 }
3874
3875 static void pqi_init_operational_queues(struct pqi_ctrl_info *ctrl_info)
3876 {
3877         unsigned int i;
3878         u16 next_iq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3879         u16 next_oq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3880
3881         /*
3882          * Initialize the backpointers to the controller structure in
3883          * each operational queue group structure.
3884          */
3885         for (i = 0; i < ctrl_info->num_queue_groups; i++)
3886                 ctrl_info->queue_groups[i].ctrl_info = ctrl_info;
3887
3888         /*
3889          * Assign IDs to all operational queues.  Note that the IDs
3890          * assigned to operational IQs are independent of the IDs
3891          * assigned to operational OQs.
3892          */
3893         ctrl_info->event_queue.oq_id = next_oq_id++;
3894         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3895                 ctrl_info->queue_groups[i].iq_id[RAID_PATH] = next_iq_id++;
3896                 ctrl_info->queue_groups[i].iq_id[AIO_PATH] = next_iq_id++;
3897                 ctrl_info->queue_groups[i].oq_id = next_oq_id++;
3898         }
3899
3900         /*
3901          * Assign MSI-X table entry indexes to all queues.  Note that the
3902          * interrupt for the event queue is shared with the first queue group.
3903          */
3904         ctrl_info->event_queue.int_msg_num = 0;
3905         for (i = 0; i < ctrl_info->num_queue_groups; i++)
3906                 ctrl_info->queue_groups[i].int_msg_num = i;
3907
3908         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3909                 spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[0]);
3910                 spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[1]);
3911                 INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[0]);
3912                 INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[1]);
3913         }
3914 }
3915
3916 static int pqi_alloc_admin_queues(struct pqi_ctrl_info *ctrl_info)
3917 {
3918         size_t alloc_length;
3919         struct pqi_admin_queues_aligned *admin_queues_aligned;
3920         struct pqi_admin_queues *admin_queues;
3921
3922         alloc_length = sizeof(struct pqi_admin_queues_aligned) +
3923                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
3924
3925         ctrl_info->admin_queue_memory_base =
3926                 dma_alloc_coherent(&ctrl_info->pci_dev->dev, alloc_length,
3927                                    &ctrl_info->admin_queue_memory_base_dma_handle,
3928                                    GFP_KERNEL);
3929
3930         if (!ctrl_info->admin_queue_memory_base)
3931                 return -ENOMEM;
3932
3933         ctrl_info->admin_queue_memory_length = alloc_length;
3934
3935         admin_queues = &ctrl_info->admin_queues;
3936         admin_queues_aligned = PTR_ALIGN(ctrl_info->admin_queue_memory_base,
3937                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3938         admin_queues->iq_element_array =
3939                 &admin_queues_aligned->iq_element_array;
3940         admin_queues->oq_element_array =
3941                 &admin_queues_aligned->oq_element_array;
3942         admin_queues->iq_ci =
3943                 (pqi_index_t __iomem *)&admin_queues_aligned->iq_ci;
3944         admin_queues->oq_pi =
3945                 (pqi_index_t __iomem *)&admin_queues_aligned->oq_pi;
3946
3947         admin_queues->iq_element_array_bus_addr =
3948                 ctrl_info->admin_queue_memory_base_dma_handle +
3949                 (admin_queues->iq_element_array -
3950                 ctrl_info->admin_queue_memory_base);
3951         admin_queues->oq_element_array_bus_addr =
3952                 ctrl_info->admin_queue_memory_base_dma_handle +
3953                 (admin_queues->oq_element_array -
3954                 ctrl_info->admin_queue_memory_base);
3955         admin_queues->iq_ci_bus_addr =
3956                 ctrl_info->admin_queue_memory_base_dma_handle +
3957                 ((void __iomem *)admin_queues->iq_ci -
3958                 (void __iomem *)ctrl_info->admin_queue_memory_base);
3959         admin_queues->oq_pi_bus_addr =
3960                 ctrl_info->admin_queue_memory_base_dma_handle +
3961                 ((void __iomem *)admin_queues->oq_pi -
3962                 (void __iomem *)ctrl_info->admin_queue_memory_base);
3963
3964         return 0;
3965 }
3966
3967 #define PQI_ADMIN_QUEUE_CREATE_TIMEOUT_JIFFIES          PQI_HZ
3968 #define PQI_ADMIN_QUEUE_CREATE_POLL_INTERVAL_MSECS      1
3969
3970 static int pqi_create_admin_queues(struct pqi_ctrl_info *ctrl_info)
3971 {
3972         struct pqi_device_registers __iomem *pqi_registers;
3973         struct pqi_admin_queues *admin_queues;
3974         unsigned long timeout;
3975         u8 status;
3976         u32 reg;
3977
3978         pqi_registers = ctrl_info->pqi_registers;
3979         admin_queues = &ctrl_info->admin_queues;
3980
3981         writeq((u64)admin_queues->iq_element_array_bus_addr,
3982                 &pqi_registers->admin_iq_element_array_addr);
3983         writeq((u64)admin_queues->oq_element_array_bus_addr,
3984                 &pqi_registers->admin_oq_element_array_addr);
3985         writeq((u64)admin_queues->iq_ci_bus_addr,
3986                 &pqi_registers->admin_iq_ci_addr);
3987         writeq((u64)admin_queues->oq_pi_bus_addr,
3988                 &pqi_registers->admin_oq_pi_addr);
3989
3990         reg = PQI_ADMIN_IQ_NUM_ELEMENTS |
3991                 (PQI_ADMIN_OQ_NUM_ELEMENTS << 8) |
3992                 (admin_queues->int_msg_num << 16);
3993         writel(reg, &pqi_registers->admin_iq_num_elements);
3994
3995         writel(PQI_CREATE_ADMIN_QUEUE_PAIR,
3996                 &pqi_registers->function_and_status_code);
3997
3998         timeout = PQI_ADMIN_QUEUE_CREATE_TIMEOUT_JIFFIES + jiffies;
3999         while (1) {
4000                 status = readb(&pqi_registers->function_and_status_code);
4001                 if (status == PQI_STATUS_IDLE)
4002                         break;
4003                 if (time_after(jiffies, timeout))
4004                         return -ETIMEDOUT;
4005                 msleep(PQI_ADMIN_QUEUE_CREATE_POLL_INTERVAL_MSECS);
4006         }
4007
4008         /*
4009          * The offset registers are not initialized to the correct
4010          * offsets until *after* the create admin queue pair command
4011          * completes successfully.
4012          */
4013         admin_queues->iq_pi = ctrl_info->iomem_base +
4014                 PQI_DEVICE_REGISTERS_OFFSET +
4015                 readq(&pqi_registers->admin_iq_pi_offset);
4016         admin_queues->oq_ci = ctrl_info->iomem_base +
4017                 PQI_DEVICE_REGISTERS_OFFSET +
4018                 readq(&pqi_registers->admin_oq_ci_offset);
4019
4020         return 0;
4021 }
4022
4023 static void pqi_submit_admin_request(struct pqi_ctrl_info *ctrl_info,
4024         struct pqi_general_admin_request *request)
4025 {
4026         struct pqi_admin_queues *admin_queues;
4027         void *next_element;
4028         pqi_index_t iq_pi;
4029
4030         admin_queues = &ctrl_info->admin_queues;
4031         iq_pi = admin_queues->iq_pi_copy;
4032
4033         next_element = admin_queues->iq_element_array +
4034                 (iq_pi * PQI_ADMIN_IQ_ELEMENT_LENGTH);
4035
4036         memcpy(next_element, request, sizeof(*request));
4037
4038         iq_pi = (iq_pi + 1) % PQI_ADMIN_IQ_NUM_ELEMENTS;
4039         admin_queues->iq_pi_copy = iq_pi;
4040
4041         /*
4042          * This write notifies the controller that an IU is available to be
4043          * processed.
4044          */
4045         writel(iq_pi, admin_queues->iq_pi);
4046 }
4047
4048 #define PQI_ADMIN_REQUEST_TIMEOUT_SECS  60
4049
4050 static int pqi_poll_for_admin_response(struct pqi_ctrl_info *ctrl_info,
4051         struct pqi_general_admin_response *response)
4052 {
4053         struct pqi_admin_queues *admin_queues;
4054         pqi_index_t oq_pi;
4055         pqi_index_t oq_ci;
4056         unsigned long timeout;
4057
4058         admin_queues = &ctrl_info->admin_queues;
4059         oq_ci = admin_queues->oq_ci_copy;
4060
4061         timeout = (PQI_ADMIN_REQUEST_TIMEOUT_SECS * PQI_HZ) + jiffies;
4062
4063         while (1) {
4064                 oq_pi = readl(admin_queues->oq_pi);
4065                 if (oq_pi != oq_ci)
4066                         break;
4067                 if (time_after(jiffies, timeout)) {
4068                         dev_err(&ctrl_info->pci_dev->dev,
4069                                 "timed out waiting for admin response\n");
4070                         return -ETIMEDOUT;
4071                 }
4072                 if (!sis_is_firmware_running(ctrl_info))
4073                         return -ENXIO;
4074                 usleep_range(1000, 2000);
4075         }
4076
4077         memcpy(response, admin_queues->oq_element_array +
4078                 (oq_ci * PQI_ADMIN_OQ_ELEMENT_LENGTH), sizeof(*response));
4079
4080         oq_ci = (oq_ci + 1) % PQI_ADMIN_OQ_NUM_ELEMENTS;
4081         admin_queues->oq_ci_copy = oq_ci;
4082         writel(oq_ci, admin_queues->oq_ci);
4083
4084         return 0;
4085 }
4086
4087 static void pqi_start_io(struct pqi_ctrl_info *ctrl_info,
4088         struct pqi_queue_group *queue_group, enum pqi_io_path path,
4089         struct pqi_io_request *io_request)
4090 {
4091         struct pqi_io_request *next;
4092         void *next_element;
4093         pqi_index_t iq_pi;
4094         pqi_index_t iq_ci;
4095         size_t iu_length;
4096         unsigned long flags;
4097         unsigned int num_elements_needed;
4098         unsigned int num_elements_to_end_of_queue;
4099         size_t copy_count;
4100         struct pqi_iu_header *request;
4101
4102         spin_lock_irqsave(&queue_group->submit_lock[path], flags);
4103
4104         if (io_request) {
4105                 io_request->queue_group = queue_group;
4106                 list_add_tail(&io_request->request_list_entry,
4107                         &queue_group->request_list[path]);
4108         }
4109
4110         iq_pi = queue_group->iq_pi_copy[path];
4111
4112         list_for_each_entry_safe(io_request, next,
4113                 &queue_group->request_list[path], request_list_entry) {
4114
4115                 request = io_request->iu;
4116
4117                 iu_length = get_unaligned_le16(&request->iu_length) +
4118                         PQI_REQUEST_HEADER_LENGTH;
4119                 num_elements_needed =
4120                         DIV_ROUND_UP(iu_length,
4121                                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4122
4123                 iq_ci = readl(queue_group->iq_ci[path]);
4124
4125                 if (num_elements_needed > pqi_num_elements_free(iq_pi, iq_ci,
4126                         ctrl_info->num_elements_per_iq))
4127                         break;
4128
4129                 put_unaligned_le16(queue_group->oq_id,
4130                         &request->response_queue_id);
4131
4132                 next_element = queue_group->iq_element_array[path] +
4133                         (iq_pi * PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4134
4135                 num_elements_to_end_of_queue =
4136                         ctrl_info->num_elements_per_iq - iq_pi;
4137
4138                 if (num_elements_needed <= num_elements_to_end_of_queue) {
4139                         memcpy(next_element, request, iu_length);
4140                 } else {
4141                         copy_count = num_elements_to_end_of_queue *
4142                                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH;
4143                         memcpy(next_element, request, copy_count);
4144                         memcpy(queue_group->iq_element_array[path],
4145                                 (u8 *)request + copy_count,
4146                                 iu_length - copy_count);
4147                 }
4148
4149                 iq_pi = (iq_pi + num_elements_needed) %
4150                         ctrl_info->num_elements_per_iq;
4151
4152                 list_del(&io_request->request_list_entry);
4153         }
4154
4155         if (iq_pi != queue_group->iq_pi_copy[path]) {
4156                 queue_group->iq_pi_copy[path] = iq_pi;
4157                 /*
4158                  * This write notifies the controller that one or more IUs are
4159                  * available to be processed.
4160                  */
4161                 writel(iq_pi, queue_group->iq_pi[path]);
4162         }
4163
4164         spin_unlock_irqrestore(&queue_group->submit_lock[path], flags);
4165 }
4166
4167 #define PQI_WAIT_FOR_COMPLETION_IO_TIMEOUT_SECS         10
4168
4169 static int pqi_wait_for_completion_io(struct pqi_ctrl_info *ctrl_info,
4170         struct completion *wait)
4171 {
4172         int rc;
4173
4174         while (1) {
4175                 if (wait_for_completion_io_timeout(wait,
4176                         PQI_WAIT_FOR_COMPLETION_IO_TIMEOUT_SECS * PQI_HZ)) {
4177                         rc = 0;
4178                         break;
4179                 }
4180
4181                 pqi_check_ctrl_health(ctrl_info);
4182                 if (pqi_ctrl_offline(ctrl_info)) {
4183                         rc = -ENXIO;
4184                         break;
4185                 }
4186         }
4187
4188         return rc;
4189 }
4190
4191 static void pqi_raid_synchronous_complete(struct pqi_io_request *io_request,
4192         void *context)
4193 {
4194         struct completion *waiting = context;
4195
4196         complete(waiting);
4197 }
4198
4199 static int pqi_process_raid_io_error_synchronous(
4200         struct pqi_raid_error_info *error_info)
4201 {
4202         int rc = -EIO;
4203
4204         switch (error_info->data_out_result) {
4205         case PQI_DATA_IN_OUT_GOOD:
4206                 if (error_info->status == SAM_STAT_GOOD)
4207                         rc = 0;
4208                 break;
4209         case PQI_DATA_IN_OUT_UNDERFLOW:
4210                 if (error_info->status == SAM_STAT_GOOD ||
4211                         error_info->status == SAM_STAT_CHECK_CONDITION)
4212                         rc = 0;
4213                 break;
4214         case PQI_DATA_IN_OUT_ABORTED:
4215                 rc = PQI_CMD_STATUS_ABORTED;
4216                 break;
4217         }
4218
4219         return rc;
4220 }
4221
4222 static int pqi_submit_raid_request_synchronous(struct pqi_ctrl_info *ctrl_info,
4223         struct pqi_iu_header *request, unsigned int flags,
4224         struct pqi_raid_error_info *error_info, unsigned long timeout_msecs)
4225 {
4226         int rc = 0;
4227         struct pqi_io_request *io_request;
4228         unsigned long start_jiffies;
4229         unsigned long msecs_blocked;
4230         size_t iu_length;
4231         DECLARE_COMPLETION_ONSTACK(wait);
4232
4233         /*
4234          * Note that specifying PQI_SYNC_FLAGS_INTERRUPTABLE and a timeout value
4235          * are mutually exclusive.
4236          */
4237
4238         if (flags & PQI_SYNC_FLAGS_INTERRUPTABLE) {
4239                 if (down_interruptible(&ctrl_info->sync_request_sem))
4240                         return -ERESTARTSYS;
4241         } else {
4242                 if (timeout_msecs == NO_TIMEOUT) {
4243                         down(&ctrl_info->sync_request_sem);
4244                 } else {
4245                         start_jiffies = jiffies;
4246                         if (down_timeout(&ctrl_info->sync_request_sem,
4247                                 msecs_to_jiffies(timeout_msecs)))
4248                                 return -ETIMEDOUT;
4249                         msecs_blocked =
4250                                 jiffies_to_msecs(jiffies - start_jiffies);
4251                         if (msecs_blocked >= timeout_msecs) {
4252                                 rc = -ETIMEDOUT;
4253                                 goto out;
4254                         }
4255                         timeout_msecs -= msecs_blocked;
4256                 }
4257         }
4258
4259         pqi_ctrl_busy(ctrl_info);
4260         timeout_msecs = pqi_wait_if_ctrl_blocked(ctrl_info, timeout_msecs);
4261         if (timeout_msecs == 0) {
4262                 pqi_ctrl_unbusy(ctrl_info);
4263                 rc = -ETIMEDOUT;
4264                 goto out;
4265         }
4266
4267         if (pqi_ctrl_offline(ctrl_info)) {
4268                 pqi_ctrl_unbusy(ctrl_info);
4269                 rc = -ENXIO;
4270                 goto out;
4271         }
4272
4273         atomic_inc(&ctrl_info->sync_cmds_outstanding);
4274
4275         io_request = pqi_alloc_io_request(ctrl_info);
4276
4277         put_unaligned_le16(io_request->index,
4278                 &(((struct pqi_raid_path_request *)request)->request_id));
4279
4280         if (request->iu_type == PQI_REQUEST_IU_RAID_PATH_IO)
4281                 ((struct pqi_raid_path_request *)request)->error_index =
4282                         ((struct pqi_raid_path_request *)request)->request_id;
4283
4284         iu_length = get_unaligned_le16(&request->iu_length) +
4285                 PQI_REQUEST_HEADER_LENGTH;
4286         memcpy(io_request->iu, request, iu_length);
4287
4288         io_request->io_complete_callback = pqi_raid_synchronous_complete;
4289         io_request->context = &wait;
4290
4291         pqi_start_io(ctrl_info, &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP], RAID_PATH,
4292                 io_request);
4293
4294         pqi_ctrl_unbusy(ctrl_info);
4295
4296         if (timeout_msecs == NO_TIMEOUT) {
4297                 pqi_wait_for_completion_io(ctrl_info, &wait);
4298         } else {
4299                 if (!wait_for_completion_io_timeout(&wait,
4300                         msecs_to_jiffies(timeout_msecs))) {
4301                         dev_warn(&ctrl_info->pci_dev->dev,
4302                                 "command timed out\n");
4303                         rc = -ETIMEDOUT;
4304                 }
4305         }
4306
4307         if (error_info) {
4308                 if (io_request->error_info)
4309                         memcpy(error_info, io_request->error_info, sizeof(*error_info));
4310                 else
4311                         memset(error_info, 0, sizeof(*error_info));
4312         } else if (rc == 0 && io_request->error_info) {
4313                 rc = pqi_process_raid_io_error_synchronous(io_request->error_info);
4314         }
4315
4316         pqi_free_io_request(io_request);
4317
4318         atomic_dec(&ctrl_info->sync_cmds_outstanding);
4319 out:
4320         up(&ctrl_info->sync_request_sem);
4321
4322         return rc;
4323 }
4324
4325 static int pqi_validate_admin_response(
4326         struct pqi_general_admin_response *response, u8 expected_function_code)
4327 {
4328         if (response->header.iu_type != PQI_RESPONSE_IU_GENERAL_ADMIN)
4329                 return -EINVAL;
4330
4331         if (get_unaligned_le16(&response->header.iu_length) !=
4332                 PQI_GENERAL_ADMIN_IU_LENGTH)
4333                 return -EINVAL;
4334
4335         if (response->function_code != expected_function_code)
4336                 return -EINVAL;
4337
4338         if (response->status != PQI_GENERAL_ADMIN_STATUS_SUCCESS)
4339                 return -EINVAL;
4340
4341         return 0;
4342 }
4343
4344 static int pqi_submit_admin_request_synchronous(
4345         struct pqi_ctrl_info *ctrl_info,
4346         struct pqi_general_admin_request *request,
4347         struct pqi_general_admin_response *response)
4348 {
4349         int rc;
4350
4351         pqi_submit_admin_request(ctrl_info, request);
4352
4353         rc = pqi_poll_for_admin_response(ctrl_info, response);
4354
4355         if (rc == 0)
4356                 rc = pqi_validate_admin_response(response,
4357                         request->function_code);
4358
4359         return rc;
4360 }
4361
4362 static int pqi_report_device_capability(struct pqi_ctrl_info *ctrl_info)
4363 {
4364         int rc;
4365         struct pqi_general_admin_request request;
4366         struct pqi_general_admin_response response;
4367         struct pqi_device_capability *capability;
4368         struct pqi_iu_layer_descriptor *sop_iu_layer_descriptor;
4369
4370         capability = kmalloc(sizeof(*capability), GFP_KERNEL);
4371         if (!capability)
4372                 return -ENOMEM;
4373
4374         memset(&request, 0, sizeof(request));
4375
4376         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4377         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4378                 &request.header.iu_length);
4379         request.function_code =
4380                 PQI_GENERAL_ADMIN_FUNCTION_REPORT_DEVICE_CAPABILITY;
4381         put_unaligned_le32(sizeof(*capability),
4382                 &request.data.report_device_capability.buffer_length);
4383
4384         rc = pqi_map_single(ctrl_info->pci_dev,
4385                 &request.data.report_device_capability.sg_descriptor,
4386                 capability, sizeof(*capability),
4387                 DMA_FROM_DEVICE);
4388         if (rc)
4389                 goto out;
4390
4391         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request, &response);
4392
4393         pqi_pci_unmap(ctrl_info->pci_dev,
4394                 &request.data.report_device_capability.sg_descriptor, 1,
4395                 DMA_FROM_DEVICE);
4396
4397         if (rc)
4398                 goto out;
4399
4400         if (response.status != PQI_GENERAL_ADMIN_STATUS_SUCCESS) {
4401                 rc = -EIO;
4402                 goto out;
4403         }
4404
4405         ctrl_info->max_inbound_queues =
4406                 get_unaligned_le16(&capability->max_inbound_queues);
4407         ctrl_info->max_elements_per_iq =
4408                 get_unaligned_le16(&capability->max_elements_per_iq);
4409         ctrl_info->max_iq_element_length =
4410                 get_unaligned_le16(&capability->max_iq_element_length)
4411                 * 16;
4412         ctrl_info->max_outbound_queues =
4413                 get_unaligned_le16(&capability->max_outbound_queues);
4414         ctrl_info->max_elements_per_oq =
4415                 get_unaligned_le16(&capability->max_elements_per_oq);
4416         ctrl_info->max_oq_element_length =
4417                 get_unaligned_le16(&capability->max_oq_element_length)
4418                 * 16;
4419
4420         sop_iu_layer_descriptor =
4421                 &capability->iu_layer_descriptors[PQI_PROTOCOL_SOP];
4422
4423         ctrl_info->max_inbound_iu_length_per_firmware =
4424                 get_unaligned_le16(
4425                         &sop_iu_layer_descriptor->max_inbound_iu_length);
4426         ctrl_info->inbound_spanning_supported =
4427                 sop_iu_layer_descriptor->inbound_spanning_supported;
4428         ctrl_info->outbound_spanning_supported =
4429                 sop_iu_layer_descriptor->outbound_spanning_supported;
4430
4431 out:
4432         kfree(capability);
4433
4434         return rc;
4435 }
4436
4437 static int pqi_validate_device_capability(struct pqi_ctrl_info *ctrl_info)
4438 {
4439         if (ctrl_info->max_iq_element_length <
4440                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) {
4441                 dev_err(&ctrl_info->pci_dev->dev,
4442                         "max. inbound queue element length of %d is less than the required length of %d\n",
4443                         ctrl_info->max_iq_element_length,
4444                         PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4445                 return -EINVAL;
4446         }
4447
4448         if (ctrl_info->max_oq_element_length <
4449                 PQI_OPERATIONAL_OQ_ELEMENT_LENGTH) {
4450                 dev_err(&ctrl_info->pci_dev->dev,
4451                         "max. outbound queue element length of %d is less than the required length of %d\n",
4452                         ctrl_info->max_oq_element_length,
4453                         PQI_OPERATIONAL_OQ_ELEMENT_LENGTH);
4454                 return -EINVAL;
4455         }
4456
4457         if (ctrl_info->max_inbound_iu_length_per_firmware <
4458                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) {
4459                 dev_err(&ctrl_info->pci_dev->dev,
4460                         "max. inbound IU length of %u is less than the min. required length of %d\n",
4461                         ctrl_info->max_inbound_iu_length_per_firmware,
4462                         PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4463                 return -EINVAL;
4464         }
4465
4466         if (!ctrl_info->inbound_spanning_supported) {
4467                 dev_err(&ctrl_info->pci_dev->dev,
4468                         "the controller does not support inbound spanning\n");
4469                 return -EINVAL;
4470         }
4471
4472         if (ctrl_info->outbound_spanning_supported) {
4473                 dev_err(&ctrl_info->pci_dev->dev,
4474                         "the controller supports outbound spanning but this driver does not\n");
4475                 return -EINVAL;
4476         }
4477
4478         return 0;
4479 }
4480
4481 static int pqi_create_event_queue(struct pqi_ctrl_info *ctrl_info)
4482 {
4483         int rc;
4484         struct pqi_event_queue *event_queue;
4485         struct pqi_general_admin_request request;
4486         struct pqi_general_admin_response response;
4487
4488         event_queue = &ctrl_info->event_queue;
4489
4490         /*
4491          * Create OQ (Outbound Queue - device to host queue) to dedicate
4492          * to events.
4493          */
4494         memset(&request, 0, sizeof(request));
4495         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4496         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4497                 &request.header.iu_length);
4498         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_OQ;
4499         put_unaligned_le16(event_queue->oq_id,
4500                 &request.data.create_operational_oq.queue_id);
4501         put_unaligned_le64((u64)event_queue->oq_element_array_bus_addr,
4502                 &request.data.create_operational_oq.element_array_addr);
4503         put_unaligned_le64((u64)event_queue->oq_pi_bus_addr,
4504                 &request.data.create_operational_oq.pi_addr);
4505         put_unaligned_le16(PQI_NUM_EVENT_QUEUE_ELEMENTS,
4506                 &request.data.create_operational_oq.num_elements);
4507         put_unaligned_le16(PQI_EVENT_OQ_ELEMENT_LENGTH / 16,
4508                 &request.data.create_operational_oq.element_length);
4509         request.data.create_operational_oq.queue_protocol = PQI_PROTOCOL_SOP;
4510         put_unaligned_le16(event_queue->int_msg_num,
4511                 &request.data.create_operational_oq.int_msg_num);
4512
4513         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4514                 &response);
4515         if (rc)
4516                 return rc;
4517
4518         event_queue->oq_ci = ctrl_info->iomem_base +
4519                 PQI_DEVICE_REGISTERS_OFFSET +
4520                 get_unaligned_le64(
4521                         &response.data.create_operational_oq.oq_ci_offset);
4522
4523         return 0;
4524 }
4525
4526 static int pqi_create_queue_group(struct pqi_ctrl_info *ctrl_info,
4527         unsigned int group_number)
4528 {
4529         int rc;
4530         struct pqi_queue_group *queue_group;
4531         struct pqi_general_admin_request request;
4532         struct pqi_general_admin_response response;
4533
4534         queue_group = &ctrl_info->queue_groups[group_number];
4535
4536         /*
4537          * Create IQ (Inbound Queue - host to device queue) for
4538          * RAID path.
4539          */
4540         memset(&request, 0, sizeof(request));
4541         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4542         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4543                 &request.header.iu_length);
4544         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_IQ;
4545         put_unaligned_le16(queue_group->iq_id[RAID_PATH],
4546                 &request.data.create_operational_iq.queue_id);
4547         put_unaligned_le64(
4548                 (u64)queue_group->iq_element_array_bus_addr[RAID_PATH],
4549                 &request.data.create_operational_iq.element_array_addr);
4550         put_unaligned_le64((u64)queue_group->iq_ci_bus_addr[RAID_PATH],
4551                 &request.data.create_operational_iq.ci_addr);
4552         put_unaligned_le16(ctrl_info->num_elements_per_iq,
4553                 &request.data.create_operational_iq.num_elements);
4554         put_unaligned_le16(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH / 16,
4555                 &request.data.create_operational_iq.element_length);
4556         request.data.create_operational_iq.queue_protocol = PQI_PROTOCOL_SOP;
4557
4558         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4559                 &response);
4560         if (rc) {
4561                 dev_err(&ctrl_info->pci_dev->dev,
4562                         "error creating inbound RAID queue\n");
4563                 return rc;
4564         }
4565
4566         queue_group->iq_pi[RAID_PATH] = ctrl_info->iomem_base +
4567                 PQI_DEVICE_REGISTERS_OFFSET +
4568                 get_unaligned_le64(
4569                         &response.data.create_operational_iq.iq_pi_offset);
4570
4571         /*
4572          * Create IQ (Inbound Queue - host to device queue) for
4573          * Advanced I/O (AIO) path.
4574          */
4575         memset(&request, 0, sizeof(request));
4576         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4577         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4578                 &request.header.iu_length);
4579         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_IQ;
4580         put_unaligned_le16(queue_group->iq_id[AIO_PATH],
4581                 &request.data.create_operational_iq.queue_id);
4582         put_unaligned_le64((u64)queue_group->
4583                 iq_element_array_bus_addr[AIO_PATH],
4584                 &request.data.create_operational_iq.element_array_addr);
4585         put_unaligned_le64((u64)queue_group->iq_ci_bus_addr[AIO_PATH],
4586                 &request.data.create_operational_iq.ci_addr);
4587         put_unaligned_le16(ctrl_info->num_elements_per_iq,
4588                 &request.data.create_operational_iq.num_elements);
4589         put_unaligned_le16(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH / 16,
4590                 &request.data.create_operational_iq.element_length);
4591         request.data.create_operational_iq.queue_protocol = PQI_PROTOCOL_SOP;
4592
4593         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4594                 &response);
4595         if (rc) {
4596                 dev_err(&ctrl_info->pci_dev->dev,
4597                         "error creating inbound AIO queue\n");
4598                 return rc;
4599         }
4600
4601         queue_group->iq_pi[AIO_PATH] = ctrl_info->iomem_base +
4602                 PQI_DEVICE_REGISTERS_OFFSET +
4603                 get_unaligned_le64(
4604                         &response.data.create_operational_iq.iq_pi_offset);
4605
4606         /*
4607          * Designate the 2nd IQ as the AIO path.  By default, all IQs are
4608          * assumed to be for RAID path I/O unless we change the queue's
4609          * property.
4610          */
4611         memset(&request, 0, sizeof(request));
4612         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4613         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4614                 &request.header.iu_length);
4615         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CHANGE_IQ_PROPERTY;
4616         put_unaligned_le16(queue_group->iq_id[AIO_PATH],
4617                 &request.data.change_operational_iq_properties.queue_id);
4618         put_unaligned_le32(PQI_IQ_PROPERTY_IS_AIO_QUEUE,
4619                 &request.data.change_operational_iq_properties.vendor_specific);
4620
4621         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4622                 &response);
4623         if (rc) {
4624                 dev_err(&ctrl_info->pci_dev->dev,
4625                         "error changing queue property\n");
4626                 return rc;
4627         }
4628
4629         /*
4630          * Create OQ (Outbound Queue - device to host queue).
4631          */
4632         memset(&request, 0, sizeof(request));
4633         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4634         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4635                 &request.header.iu_length);
4636         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_OQ;
4637         put_unaligned_le16(queue_group->oq_id,
4638                 &request.data.create_operational_oq.queue_id);
4639         put_unaligned_le64((u64)queue_group->oq_element_array_bus_addr,
4640                 &request.data.create_operational_oq.element_array_addr);
4641         put_unaligned_le64((u64)queue_group->oq_pi_bus_addr,
4642                 &request.data.create_operational_oq.pi_addr);
4643         put_unaligned_le16(ctrl_info->num_elements_per_oq,
4644                 &request.data.create_operational_oq.num_elements);
4645         put_unaligned_le16(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH / 16,
4646                 &request.data.create_operational_oq.element_length);
4647         request.data.create_operational_oq.queue_protocol = PQI_PROTOCOL_SOP;
4648         put_unaligned_le16(queue_group->int_msg_num,
4649                 &request.data.create_operational_oq.int_msg_num);
4650
4651         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4652                 &response);
4653         if (rc) {
4654                 dev_err(&ctrl_info->pci_dev->dev,
4655                         "error creating outbound queue\n");
4656                 return rc;
4657         }
4658
4659         queue_group->oq_ci = ctrl_info->iomem_base +
4660                 PQI_DEVICE_REGISTERS_OFFSET +
4661                 get_unaligned_le64(
4662                         &response.data.create_operational_oq.oq_ci_offset);
4663
4664         return 0;
4665 }
4666
4667 static int pqi_create_queues(struct pqi_ctrl_info *ctrl_info)
4668 {
4669         int rc;
4670         unsigned int i;
4671
4672         rc = pqi_create_event_queue(ctrl_info);
4673         if (rc) {
4674                 dev_err(&ctrl_info->pci_dev->dev,
4675                         "error creating event queue\n");
4676                 return rc;
4677         }
4678
4679         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
4680                 rc = pqi_create_queue_group(ctrl_info, i);
4681                 if (rc) {
4682                         dev_err(&ctrl_info->pci_dev->dev,
4683                                 "error creating queue group number %u/%u\n",
4684                                 i, ctrl_info->num_queue_groups);
4685                         return rc;
4686                 }
4687         }
4688
4689         return 0;
4690 }
4691
4692 #define PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH   \
4693         (offsetof(struct pqi_event_config, descriptors) + \
4694         (PQI_MAX_EVENT_DESCRIPTORS * sizeof(struct pqi_event_descriptor)))
4695
4696 static int pqi_configure_events(struct pqi_ctrl_info *ctrl_info,
4697         bool enable_events)
4698 {
4699         int rc;
4700         unsigned int i;
4701         struct pqi_event_config *event_config;
4702         struct pqi_event_descriptor *event_descriptor;
4703         struct pqi_general_management_request request;
4704
4705         event_config = kmalloc(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4706                 GFP_KERNEL);
4707         if (!event_config)
4708                 return -ENOMEM;
4709
4710         memset(&request, 0, sizeof(request));
4711
4712         request.header.iu_type = PQI_REQUEST_IU_REPORT_VENDOR_EVENT_CONFIG;
4713         put_unaligned_le16(offsetof(struct pqi_general_management_request,
4714                 data.report_event_configuration.sg_descriptors[1]) -
4715                 PQI_REQUEST_HEADER_LENGTH, &request.header.iu_length);
4716         put_unaligned_le32(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4717                 &request.data.report_event_configuration.buffer_length);
4718
4719         rc = pqi_map_single(ctrl_info->pci_dev,
4720                 request.data.report_event_configuration.sg_descriptors,
4721                 event_config, PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4722                 DMA_FROM_DEVICE);
4723         if (rc)
4724                 goto out;
4725
4726         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
4727                 0, NULL, NO_TIMEOUT);
4728
4729         pqi_pci_unmap(ctrl_info->pci_dev,
4730                 request.data.report_event_configuration.sg_descriptors, 1,
4731                 DMA_FROM_DEVICE);
4732
4733         if (rc)
4734                 goto out;
4735
4736         for (i = 0; i < event_config->num_event_descriptors; i++) {
4737                 event_descriptor = &event_config->descriptors[i];
4738                 if (enable_events &&
4739                         pqi_is_supported_event(event_descriptor->event_type))
4740                                 put_unaligned_le16(ctrl_info->event_queue.oq_id,
4741                                         &event_descriptor->oq_id);
4742                 else
4743                         put_unaligned_le16(0, &event_descriptor->oq_id);
4744         }
4745
4746         memset(&request, 0, sizeof(request));
4747
4748         request.header.iu_type = PQI_REQUEST_IU_SET_VENDOR_EVENT_CONFIG;
4749         put_unaligned_le16(offsetof(struct pqi_general_management_request,
4750                 data.report_event_configuration.sg_descriptors[1]) -
4751                 PQI_REQUEST_HEADER_LENGTH, &request.header.iu_length);
4752         put_unaligned_le32(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4753                 &request.data.report_event_configuration.buffer_length);
4754
4755         rc = pqi_map_single(ctrl_info->pci_dev,
4756                 request.data.report_event_configuration.sg_descriptors,
4757                 event_config, PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4758                 DMA_TO_DEVICE);
4759         if (rc)
4760                 goto out;
4761
4762         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0,
4763                 NULL, NO_TIMEOUT);
4764
4765         pqi_pci_unmap(ctrl_info->pci_dev,
4766                 request.data.report_event_configuration.sg_descriptors, 1,
4767                 DMA_TO_DEVICE);
4768
4769 out:
4770         kfree(event_config);
4771
4772         return rc;
4773 }
4774
4775 static inline int pqi_enable_events(struct pqi_ctrl_info *ctrl_info)
4776 {
4777         return pqi_configure_events(ctrl_info, true);
4778 }
4779
4780 static inline int pqi_disable_events(struct pqi_ctrl_info *ctrl_info)
4781 {
4782         return pqi_configure_events(ctrl_info, false);
4783 }
4784
4785 static void pqi_free_all_io_requests(struct pqi_ctrl_info *ctrl_info)
4786 {
4787         unsigned int i;
4788         struct device *dev;
4789         size_t sg_chain_buffer_length;
4790         struct pqi_io_request *io_request;
4791
4792         if (!ctrl_info->io_request_pool)
4793                 return;
4794
4795         dev = &ctrl_info->pci_dev->dev;
4796         sg_chain_buffer_length = ctrl_info->sg_chain_buffer_length;
4797         io_request = ctrl_info->io_request_pool;
4798
4799         for (i = 0; i < ctrl_info->max_io_slots; i++) {
4800                 kfree(io_request->iu);
4801                 if (!io_request->sg_chain_buffer)
4802                         break;
4803                 dma_free_coherent(dev, sg_chain_buffer_length,
4804                         io_request->sg_chain_buffer,
4805                         io_request->sg_chain_buffer_dma_handle);
4806                 io_request++;
4807         }
4808
4809         kfree(ctrl_info->io_request_pool);
4810         ctrl_info->io_request_pool = NULL;
4811 }
4812
4813 static inline int pqi_alloc_error_buffer(struct pqi_ctrl_info *ctrl_info)
4814 {
4815         ctrl_info->error_buffer = dma_alloc_coherent(&ctrl_info->pci_dev->dev,
4816                                      ctrl_info->error_buffer_length,
4817                                      &ctrl_info->error_buffer_dma_handle,
4818                                      GFP_KERNEL);
4819         if (!ctrl_info->error_buffer)
4820                 return -ENOMEM;
4821
4822         return 0;
4823 }
4824
4825 static int pqi_alloc_io_resources(struct pqi_ctrl_info *ctrl_info)
4826 {
4827         unsigned int i;
4828         void *sg_chain_buffer;
4829         size_t sg_chain_buffer_length;
4830         dma_addr_t sg_chain_buffer_dma_handle;
4831         struct device *dev;
4832         struct pqi_io_request *io_request;
4833
4834         ctrl_info->io_request_pool = kcalloc(ctrl_info->max_io_slots,
4835                 sizeof(ctrl_info->io_request_pool[0]), GFP_KERNEL);
4836
4837         if (!ctrl_info->io_request_pool) {
4838                 dev_err(&ctrl_info->pci_dev->dev,
4839                         "failed to allocate I/O request pool\n");
4840                 goto error;
4841         }
4842
4843         dev = &ctrl_info->pci_dev->dev;
4844         sg_chain_buffer_length = ctrl_info->sg_chain_buffer_length;
4845         io_request = ctrl_info->io_request_pool;
4846
4847         for (i = 0; i < ctrl_info->max_io_slots; i++) {
4848                 io_request->iu = kmalloc(ctrl_info->max_inbound_iu_length, GFP_KERNEL);
4849
4850                 if (!io_request->iu) {
4851                         dev_err(&ctrl_info->pci_dev->dev,
4852                                 "failed to allocate IU buffers\n");
4853                         goto error;
4854                 }
4855
4856                 sg_chain_buffer = dma_alloc_coherent(dev,
4857                         sg_chain_buffer_length, &sg_chain_buffer_dma_handle,
4858                         GFP_KERNEL);
4859
4860                 if (!sg_chain_buffer) {
4861                         dev_err(&ctrl_info->pci_dev->dev,
4862                                 "failed to allocate PQI scatter-gather chain buffers\n");
4863                         goto error;
4864                 }
4865
4866                 io_request->index = i;
4867                 io_request->sg_chain_buffer = sg_chain_buffer;
4868                 io_request->sg_chain_buffer_dma_handle = sg_chain_buffer_dma_handle;
4869                 io_request++;
4870         }
4871
4872         return 0;
4873
4874 error:
4875         pqi_free_all_io_requests(ctrl_info);
4876
4877         return -ENOMEM;
4878 }
4879
4880 /*
4881  * Calculate required resources that are sized based on max. outstanding
4882  * requests and max. transfer size.
4883  */
4884
4885 static void pqi_calculate_io_resources(struct pqi_ctrl_info *ctrl_info)
4886 {
4887         u32 max_transfer_size;
4888         u32 max_sg_entries;
4889
4890         ctrl_info->scsi_ml_can_queue =
4891                 ctrl_info->max_outstanding_requests - PQI_RESERVED_IO_SLOTS;
4892         ctrl_info->max_io_slots = ctrl_info->max_outstanding_requests;
4893
4894         ctrl_info->error_buffer_length =
4895                 ctrl_info->max_io_slots * PQI_ERROR_BUFFER_ELEMENT_LENGTH;
4896
4897         if (reset_devices)
4898                 max_transfer_size = min(ctrl_info->max_transfer_size,
4899                         PQI_MAX_TRANSFER_SIZE_KDUMP);
4900         else
4901                 max_transfer_size = min(ctrl_info->max_transfer_size,
4902                         PQI_MAX_TRANSFER_SIZE);
4903
4904         max_sg_entries = max_transfer_size / PAGE_SIZE;
4905
4906         /* +1 to cover when the buffer is not page-aligned. */
4907         max_sg_entries++;
4908
4909         max_sg_entries = min(ctrl_info->max_sg_entries, max_sg_entries);
4910
4911         max_transfer_size = (max_sg_entries - 1) * PAGE_SIZE;
4912
4913         ctrl_info->sg_chain_buffer_length =
4914                 (max_sg_entries * sizeof(struct pqi_sg_descriptor)) +
4915                 PQI_EXTRA_SGL_MEMORY;
4916         ctrl_info->sg_tablesize = max_sg_entries;
4917         ctrl_info->max_sectors = max_transfer_size / 512;
4918 }
4919
4920 static void pqi_calculate_queue_resources(struct pqi_ctrl_info *ctrl_info)
4921 {
4922         int num_queue_groups;
4923         u16 num_elements_per_iq;
4924         u16 num_elements_per_oq;
4925
4926         if (reset_devices) {
4927                 num_queue_groups = 1;
4928         } else {
4929                 int num_cpus;
4930                 int max_queue_groups;
4931
4932                 max_queue_groups = min(ctrl_info->max_inbound_queues / 2,
4933                         ctrl_info->max_outbound_queues - 1);
4934                 max_queue_groups = min(max_queue_groups, PQI_MAX_QUEUE_GROUPS);
4935
4936                 num_cpus = num_online_cpus();
4937                 num_queue_groups = min(num_cpus, ctrl_info->max_msix_vectors);
4938                 num_queue_groups = min(num_queue_groups, max_queue_groups);
4939         }
4940
4941         ctrl_info->num_queue_groups = num_queue_groups;
4942         ctrl_info->max_hw_queue_index = num_queue_groups - 1;
4943
4944         /*
4945          * Make sure that the max. inbound IU length is an even multiple
4946          * of our inbound element length.
4947          */
4948         ctrl_info->max_inbound_iu_length =
4949                 (ctrl_info->max_inbound_iu_length_per_firmware /
4950                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) *
4951                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH;
4952
4953         num_elements_per_iq =
4954                 (ctrl_info->max_inbound_iu_length /
4955                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4956
4957         /* Add one because one element in each queue is unusable. */
4958         num_elements_per_iq++;
4959
4960         num_elements_per_iq = min(num_elements_per_iq,
4961                 ctrl_info->max_elements_per_iq);
4962
4963         num_elements_per_oq = ((num_elements_per_iq - 1) * 2) + 1;
4964         num_elements_per_oq = min(num_elements_per_oq,
4965                 ctrl_info->max_elements_per_oq);
4966
4967         ctrl_info->num_elements_per_iq = num_elements_per_iq;
4968         ctrl_info->num_elements_per_oq = num_elements_per_oq;
4969
4970         ctrl_info->max_sg_per_iu =
4971                 ((ctrl_info->max_inbound_iu_length -
4972                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) /
4973                 sizeof(struct pqi_sg_descriptor)) +
4974                 PQI_MAX_EMBEDDED_SG_DESCRIPTORS;
4975
4976         ctrl_info->max_sg_per_r56_iu =
4977                 ((ctrl_info->max_inbound_iu_length -
4978                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) /
4979                 sizeof(struct pqi_sg_descriptor)) +
4980                 PQI_MAX_EMBEDDED_R56_SG_DESCRIPTORS;
4981 }
4982
4983 static inline void pqi_set_sg_descriptor(struct pqi_sg_descriptor *sg_descriptor,
4984         struct scatterlist *sg)
4985 {
4986         u64 address = (u64)sg_dma_address(sg);
4987         unsigned int length = sg_dma_len(sg);
4988
4989         put_unaligned_le64(address, &sg_descriptor->address);
4990         put_unaligned_le32(length, &sg_descriptor->length);
4991         put_unaligned_le32(0, &sg_descriptor->flags);
4992 }
4993
4994 static unsigned int pqi_build_sg_list(struct pqi_sg_descriptor *sg_descriptor,
4995         struct scatterlist *sg, int sg_count, struct pqi_io_request *io_request,
4996         int max_sg_per_iu, bool *chained)
4997 {
4998         int i;
4999         unsigned int num_sg_in_iu;
5000
5001         *chained = false;
5002         i = 0;
5003         num_sg_in_iu = 0;
5004         max_sg_per_iu--;        /* Subtract 1 to leave room for chain marker. */
5005
5006         while (1) {
5007                 pqi_set_sg_descriptor(sg_descriptor, sg);
5008                 if (!*chained)
5009                         num_sg_in_iu++;
5010                 i++;
5011                 if (i == sg_count)
5012                         break;
5013                 sg_descriptor++;
5014                 if (i == max_sg_per_iu) {
5015                         put_unaligned_le64((u64)io_request->sg_chain_buffer_dma_handle,
5016                                 &sg_descriptor->address);
5017                         put_unaligned_le32((sg_count - num_sg_in_iu) * sizeof(*sg_descriptor),
5018                                 &sg_descriptor->length);
5019                         put_unaligned_le32(CISS_SG_CHAIN, &sg_descriptor->flags);
5020                         *chained = true;
5021                         num_sg_in_iu++;
5022                         sg_descriptor = io_request->sg_chain_buffer;
5023                 }
5024                 sg = sg_next(sg);
5025         }
5026
5027         put_unaligned_le32(CISS_SG_LAST, &sg_descriptor->flags);
5028
5029         return num_sg_in_iu;
5030 }
5031
5032 static int pqi_build_raid_sg_list(struct pqi_ctrl_info *ctrl_info,
5033         struct pqi_raid_path_request *request, struct scsi_cmnd *scmd,
5034         struct pqi_io_request *io_request)
5035 {
5036         u16 iu_length;
5037         int sg_count;
5038         bool chained;
5039         unsigned int num_sg_in_iu;
5040         struct scatterlist *sg;
5041         struct pqi_sg_descriptor *sg_descriptor;
5042
5043         sg_count = scsi_dma_map(scmd);
5044         if (sg_count < 0)
5045                 return sg_count;
5046
5047         iu_length = offsetof(struct pqi_raid_path_request, sg_descriptors) -
5048                 PQI_REQUEST_HEADER_LENGTH;
5049
5050         if (sg_count == 0)
5051                 goto out;
5052
5053         sg = scsi_sglist(scmd);
5054         sg_descriptor = request->sg_descriptors;
5055
5056         num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5057                 ctrl_info->max_sg_per_iu, &chained);
5058
5059         request->partial = chained;
5060         iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5061
5062 out:
5063         put_unaligned_le16(iu_length, &request->header.iu_length);
5064
5065         return 0;
5066 }
5067
5068 static int pqi_build_aio_r1_sg_list(struct pqi_ctrl_info *ctrl_info,
5069         struct pqi_aio_r1_path_request *request, struct scsi_cmnd *scmd,
5070         struct pqi_io_request *io_request)
5071 {
5072         u16 iu_length;
5073         int sg_count;
5074         bool chained;
5075         unsigned int num_sg_in_iu;
5076         struct scatterlist *sg;
5077         struct pqi_sg_descriptor *sg_descriptor;
5078
5079         sg_count = scsi_dma_map(scmd);
5080         if (sg_count < 0)
5081                 return sg_count;
5082
5083         iu_length = offsetof(struct pqi_aio_r1_path_request, sg_descriptors) -
5084                 PQI_REQUEST_HEADER_LENGTH;
5085         num_sg_in_iu = 0;
5086
5087         if (sg_count == 0)
5088                 goto out;
5089
5090         sg = scsi_sglist(scmd);
5091         sg_descriptor = request->sg_descriptors;
5092
5093         num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5094                 ctrl_info->max_sg_per_iu, &chained);
5095
5096         request->partial = chained;
5097         iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5098
5099 out:
5100         put_unaligned_le16(iu_length, &request->header.iu_length);
5101         request->num_sg_descriptors = num_sg_in_iu;
5102
5103         return 0;
5104 }
5105
5106 static int pqi_build_aio_r56_sg_list(struct pqi_ctrl_info *ctrl_info,
5107         struct pqi_aio_r56_path_request *request, struct scsi_cmnd *scmd,
5108         struct pqi_io_request *io_request)
5109 {
5110         u16 iu_length;
5111         int sg_count;
5112         bool chained;
5113         unsigned int num_sg_in_iu;
5114         struct scatterlist *sg;
5115         struct pqi_sg_descriptor *sg_descriptor;
5116
5117         sg_count = scsi_dma_map(scmd);
5118         if (sg_count < 0)
5119                 return sg_count;
5120
5121         iu_length = offsetof(struct pqi_aio_r56_path_request, sg_descriptors) -
5122                 PQI_REQUEST_HEADER_LENGTH;
5123         num_sg_in_iu = 0;
5124
5125         if (sg_count != 0) {
5126                 sg = scsi_sglist(scmd);
5127                 sg_descriptor = request->sg_descriptors;
5128
5129                 num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5130                         ctrl_info->max_sg_per_r56_iu, &chained);
5131
5132                 request->partial = chained;
5133                 iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5134         }
5135
5136         put_unaligned_le16(iu_length, &request->header.iu_length);
5137         request->num_sg_descriptors = num_sg_in_iu;
5138
5139         return 0;
5140 }
5141
5142 static int pqi_build_aio_sg_list(struct pqi_ctrl_info *ctrl_info,
5143         struct pqi_aio_path_request *request, struct scsi_cmnd *scmd,
5144         struct pqi_io_request *io_request)
5145 {
5146         u16 iu_length;
5147         int sg_count;
5148         bool chained;
5149         unsigned int num_sg_in_iu;
5150         struct scatterlist *sg;
5151         struct pqi_sg_descriptor *sg_descriptor;
5152
5153         sg_count = scsi_dma_map(scmd);
5154         if (sg_count < 0)
5155                 return sg_count;
5156
5157         iu_length = offsetof(struct pqi_aio_path_request, sg_descriptors) -
5158                 PQI_REQUEST_HEADER_LENGTH;
5159         num_sg_in_iu = 0;
5160
5161         if (sg_count == 0)
5162                 goto out;
5163
5164         sg = scsi_sglist(scmd);
5165         sg_descriptor = request->sg_descriptors;
5166
5167         num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5168                 ctrl_info->max_sg_per_iu, &chained);
5169
5170         request->partial = chained;
5171         iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5172
5173 out:
5174         put_unaligned_le16(iu_length, &request->header.iu_length);
5175         request->num_sg_descriptors = num_sg_in_iu;
5176
5177         return 0;
5178 }
5179
5180 static void pqi_raid_io_complete(struct pqi_io_request *io_request,
5181         void *context)
5182 {
5183         struct scsi_cmnd *scmd;
5184
5185         scmd = io_request->scmd;
5186         pqi_free_io_request(io_request);
5187         scsi_dma_unmap(scmd);
5188         pqi_scsi_done(scmd);
5189 }
5190
5191 static int pqi_raid_submit_scsi_cmd_with_io_request(
5192         struct pqi_ctrl_info *ctrl_info, struct pqi_io_request *io_request,
5193         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
5194         struct pqi_queue_group *queue_group)
5195 {
5196         int rc;
5197         size_t cdb_length;
5198         struct pqi_raid_path_request *request;
5199
5200         io_request->io_complete_callback = pqi_raid_io_complete;
5201         io_request->scmd = scmd;
5202
5203         request = io_request->iu;
5204         memset(request, 0, offsetof(struct pqi_raid_path_request, sg_descriptors));
5205
5206         request->header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
5207         put_unaligned_le32(scsi_bufflen(scmd), &request->buffer_length);
5208         request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5209         put_unaligned_le16(io_request->index, &request->request_id);
5210         request->error_index = request->request_id;
5211         memcpy(request->lun_number, device->scsi3addr, sizeof(request->lun_number));
5212
5213         cdb_length = min_t(size_t, scmd->cmd_len, sizeof(request->cdb));
5214         memcpy(request->cdb, scmd->cmnd, cdb_length);
5215
5216         switch (cdb_length) {
5217         case 6:
5218         case 10:
5219         case 12:
5220         case 16:
5221                 request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
5222                 break;
5223         case 20:
5224                 request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_4;
5225                 break;
5226         case 24:
5227                 request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_8;
5228                 break;
5229         case 28:
5230                 request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_12;
5231                 break;
5232         case 32:
5233         default:
5234                 request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_16;
5235                 break;
5236         }
5237
5238         switch (scmd->sc_data_direction) {
5239         case DMA_TO_DEVICE:
5240                 request->data_direction = SOP_READ_FLAG;
5241                 break;
5242         case DMA_FROM_DEVICE:
5243                 request->data_direction = SOP_WRITE_FLAG;
5244                 break;
5245         case DMA_NONE:
5246                 request->data_direction = SOP_NO_DIRECTION_FLAG;
5247                 break;
5248         case DMA_BIDIRECTIONAL:
5249                 request->data_direction = SOP_BIDIRECTIONAL;
5250                 break;
5251         default:
5252                 dev_err(&ctrl_info->pci_dev->dev,
5253                         "unknown data direction: %d\n",
5254                         scmd->sc_data_direction);
5255                 break;
5256         }
5257
5258         rc = pqi_build_raid_sg_list(ctrl_info, request, scmd, io_request);
5259         if (rc) {
5260                 pqi_free_io_request(io_request);
5261                 return SCSI_MLQUEUE_HOST_BUSY;
5262         }
5263
5264         pqi_start_io(ctrl_info, queue_group, RAID_PATH, io_request);
5265
5266         return 0;
5267 }
5268
5269 static inline int pqi_raid_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
5270         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
5271         struct pqi_queue_group *queue_group)
5272 {
5273         struct pqi_io_request *io_request;
5274
5275         io_request = pqi_alloc_io_request(ctrl_info);
5276
5277         return pqi_raid_submit_scsi_cmd_with_io_request(ctrl_info, io_request,
5278                 device, scmd, queue_group);
5279 }
5280
5281 static inline void pqi_schedule_bypass_retry(struct pqi_ctrl_info *ctrl_info)
5282 {
5283         if (!pqi_ctrl_blocked(ctrl_info))
5284                 schedule_work(&ctrl_info->raid_bypass_retry_work);
5285 }
5286
5287 static bool pqi_raid_bypass_retry_needed(struct pqi_io_request *io_request)
5288 {
5289         struct scsi_cmnd *scmd;
5290         struct pqi_scsi_dev *device;
5291         struct pqi_ctrl_info *ctrl_info;
5292
5293         if (!io_request->raid_bypass)
5294                 return false;
5295
5296         scmd = io_request->scmd;
5297         if ((scmd->result & 0xff) == SAM_STAT_GOOD)
5298                 return false;
5299         if (host_byte(scmd->result) == DID_NO_CONNECT)
5300                 return false;
5301
5302         device = scmd->device->hostdata;
5303         if (pqi_device_offline(device))
5304                 return false;
5305
5306         ctrl_info = shost_to_hba(scmd->device->host);
5307         if (pqi_ctrl_offline(ctrl_info))
5308                 return false;
5309
5310         return true;
5311 }
5312
5313 static inline void pqi_add_to_raid_bypass_retry_list(
5314         struct pqi_ctrl_info *ctrl_info,
5315         struct pqi_io_request *io_request, bool at_head)
5316 {
5317         unsigned long flags;
5318
5319         spin_lock_irqsave(&ctrl_info->raid_bypass_retry_list_lock, flags);
5320         if (at_head)
5321                 list_add(&io_request->request_list_entry,
5322                         &ctrl_info->raid_bypass_retry_list);
5323         else
5324                 list_add_tail(&io_request->request_list_entry,
5325                         &ctrl_info->raid_bypass_retry_list);
5326         spin_unlock_irqrestore(&ctrl_info->raid_bypass_retry_list_lock, flags);
5327 }
5328
5329 static void pqi_queued_raid_bypass_complete(struct pqi_io_request *io_request,
5330         void *context)
5331 {
5332         struct scsi_cmnd *scmd;
5333
5334         scmd = io_request->scmd;
5335         pqi_free_io_request(io_request);
5336         pqi_scsi_done(scmd);
5337 }
5338
5339 static void pqi_queue_raid_bypass_retry(struct pqi_io_request *io_request)
5340 {
5341         struct scsi_cmnd *scmd;
5342         struct pqi_ctrl_info *ctrl_info;
5343
5344         io_request->io_complete_callback = pqi_queued_raid_bypass_complete;
5345         scmd = io_request->scmd;
5346         scmd->result = 0;
5347         ctrl_info = shost_to_hba(scmd->device->host);
5348
5349         pqi_add_to_raid_bypass_retry_list(ctrl_info, io_request, false);
5350         pqi_schedule_bypass_retry(ctrl_info);
5351 }
5352
5353 static int pqi_retry_raid_bypass(struct pqi_io_request *io_request)
5354 {
5355         struct scsi_cmnd *scmd;
5356         struct pqi_scsi_dev *device;
5357         struct pqi_ctrl_info *ctrl_info;
5358         struct pqi_queue_group *queue_group;
5359
5360         scmd = io_request->scmd;
5361         device = scmd->device->hostdata;
5362         if (pqi_device_in_reset(device)) {
5363                 pqi_free_io_request(io_request);
5364                 set_host_byte(scmd, DID_RESET);
5365                 pqi_scsi_done(scmd);
5366                 return 0;
5367         }
5368
5369         ctrl_info = shost_to_hba(scmd->device->host);
5370         queue_group = io_request->queue_group;
5371
5372         pqi_reinit_io_request(io_request);
5373
5374         return pqi_raid_submit_scsi_cmd_with_io_request(ctrl_info, io_request,
5375                 device, scmd, queue_group);
5376 }
5377
5378 static inline struct pqi_io_request *pqi_next_queued_raid_bypass_request(
5379         struct pqi_ctrl_info *ctrl_info)
5380 {
5381         unsigned long flags;
5382         struct pqi_io_request *io_request;
5383
5384         spin_lock_irqsave(&ctrl_info->raid_bypass_retry_list_lock, flags);
5385         io_request = list_first_entry_or_null(
5386                 &ctrl_info->raid_bypass_retry_list,
5387                 struct pqi_io_request, request_list_entry);
5388         if (io_request)
5389                 list_del(&io_request->request_list_entry);
5390         spin_unlock_irqrestore(&ctrl_info->raid_bypass_retry_list_lock, flags);
5391
5392         return io_request;
5393 }
5394
5395 static void pqi_retry_raid_bypass_requests(struct pqi_ctrl_info *ctrl_info)
5396 {
5397         int rc;
5398         struct pqi_io_request *io_request;
5399
5400         pqi_ctrl_busy(ctrl_info);
5401
5402         while (1) {
5403                 if (pqi_ctrl_blocked(ctrl_info))
5404                         break;
5405                 io_request = pqi_next_queued_raid_bypass_request(ctrl_info);
5406                 if (!io_request)
5407                         break;
5408                 rc = pqi_retry_raid_bypass(io_request);
5409                 if (rc) {
5410                         pqi_add_to_raid_bypass_retry_list(ctrl_info, io_request,
5411                                 true);
5412                         pqi_schedule_bypass_retry(ctrl_info);
5413                         break;
5414                 }
5415         }
5416
5417         pqi_ctrl_unbusy(ctrl_info);
5418 }
5419
5420 static void pqi_raid_bypass_retry_worker(struct work_struct *work)
5421 {
5422         struct pqi_ctrl_info *ctrl_info;
5423
5424         ctrl_info = container_of(work, struct pqi_ctrl_info,
5425                 raid_bypass_retry_work);
5426         pqi_retry_raid_bypass_requests(ctrl_info);
5427 }
5428
5429 static void pqi_clear_all_queued_raid_bypass_retries(
5430         struct pqi_ctrl_info *ctrl_info)
5431 {
5432         unsigned long flags;
5433
5434         spin_lock_irqsave(&ctrl_info->raid_bypass_retry_list_lock, flags);
5435         INIT_LIST_HEAD(&ctrl_info->raid_bypass_retry_list);
5436         spin_unlock_irqrestore(&ctrl_info->raid_bypass_retry_list_lock, flags);
5437 }
5438
5439 static void pqi_aio_io_complete(struct pqi_io_request *io_request,
5440         void *context)
5441 {
5442         struct scsi_cmnd *scmd;
5443
5444         scmd = io_request->scmd;
5445         scsi_dma_unmap(scmd);
5446         if (io_request->status == -EAGAIN)
5447                 set_host_byte(scmd, DID_IMM_RETRY);
5448         else if (pqi_raid_bypass_retry_needed(io_request)) {
5449                 pqi_queue_raid_bypass_retry(io_request);
5450                 return;
5451         }
5452         pqi_free_io_request(io_request);
5453         pqi_scsi_done(scmd);
5454 }
5455
5456 static inline int pqi_aio_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
5457         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
5458         struct pqi_queue_group *queue_group)
5459 {
5460         return pqi_aio_submit_io(ctrl_info, scmd, device->aio_handle,
5461                 scmd->cmnd, scmd->cmd_len, queue_group, NULL, false);
5462 }
5463
5464 static int pqi_aio_submit_io(struct pqi_ctrl_info *ctrl_info,
5465         struct scsi_cmnd *scmd, u32 aio_handle, u8 *cdb,
5466         unsigned int cdb_length, struct pqi_queue_group *queue_group,
5467         struct pqi_encryption_info *encryption_info, bool raid_bypass)
5468 {
5469         int rc;
5470         struct pqi_io_request *io_request;
5471         struct pqi_aio_path_request *request;
5472
5473         io_request = pqi_alloc_io_request(ctrl_info);
5474         io_request->io_complete_callback = pqi_aio_io_complete;
5475         io_request->scmd = scmd;
5476         io_request->raid_bypass = raid_bypass;
5477
5478         request = io_request->iu;
5479         memset(request, 0, offsetof(struct pqi_raid_path_request, sg_descriptors));
5480
5481         request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_IO;
5482         put_unaligned_le32(aio_handle, &request->nexus_id);
5483         put_unaligned_le32(scsi_bufflen(scmd), &request->buffer_length);
5484         request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5485         put_unaligned_le16(io_request->index, &request->request_id);
5486         request->error_index = request->request_id;
5487         if (cdb_length > sizeof(request->cdb))
5488                 cdb_length = sizeof(request->cdb);
5489         request->cdb_length = cdb_length;
5490         memcpy(request->cdb, cdb, cdb_length);
5491
5492         switch (scmd->sc_data_direction) {
5493         case DMA_TO_DEVICE:
5494                 request->data_direction = SOP_READ_FLAG;
5495                 break;
5496         case DMA_FROM_DEVICE:
5497                 request->data_direction = SOP_WRITE_FLAG;
5498                 break;
5499         case DMA_NONE:
5500                 request->data_direction = SOP_NO_DIRECTION_FLAG;
5501                 break;
5502         case DMA_BIDIRECTIONAL:
5503                 request->data_direction = SOP_BIDIRECTIONAL;
5504                 break;
5505         default:
5506                 dev_err(&ctrl_info->pci_dev->dev,
5507                         "unknown data direction: %d\n",
5508                         scmd->sc_data_direction);
5509                 break;
5510         }
5511
5512         if (encryption_info) {
5513                 request->encryption_enable = true;
5514                 put_unaligned_le16(encryption_info->data_encryption_key_index,
5515                         &request->data_encryption_key_index);
5516                 put_unaligned_le32(encryption_info->encrypt_tweak_lower,
5517                         &request->encrypt_tweak_lower);
5518                 put_unaligned_le32(encryption_info->encrypt_tweak_upper,
5519                         &request->encrypt_tweak_upper);
5520         }
5521
5522         rc = pqi_build_aio_sg_list(ctrl_info, request, scmd, io_request);
5523         if (rc) {
5524                 pqi_free_io_request(io_request);
5525                 return SCSI_MLQUEUE_HOST_BUSY;
5526         }
5527
5528         pqi_start_io(ctrl_info, queue_group, AIO_PATH, io_request);
5529
5530         return 0;
5531 }
5532
5533 static  int pqi_aio_submit_r1_write_io(struct pqi_ctrl_info *ctrl_info,
5534         struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
5535         struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
5536         struct pqi_scsi_dev_raid_map_data *rmd)
5537 {
5538         int rc;
5539         struct pqi_io_request *io_request;
5540         struct pqi_aio_r1_path_request *r1_request;
5541
5542         io_request = pqi_alloc_io_request(ctrl_info);
5543         io_request->io_complete_callback = pqi_aio_io_complete;
5544         io_request->scmd = scmd;
5545         io_request->raid_bypass = true;
5546
5547         r1_request = io_request->iu;
5548         memset(r1_request, 0, offsetof(struct pqi_aio_r1_path_request, sg_descriptors));
5549
5550         r1_request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_RAID1_IO;
5551         put_unaligned_le16(*(u16 *)device->scsi3addr & 0x3fff, &r1_request->volume_id);
5552         r1_request->num_drives = rmd->num_it_nexus_entries;
5553         put_unaligned_le32(rmd->it_nexus[0], &r1_request->it_nexus_1);
5554         put_unaligned_le32(rmd->it_nexus[1], &r1_request->it_nexus_2);
5555         if (rmd->num_it_nexus_entries == 3)
5556                 put_unaligned_le32(rmd->it_nexus[2], &r1_request->it_nexus_3);
5557
5558         put_unaligned_le32(scsi_bufflen(scmd), &r1_request->data_length);
5559         r1_request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5560         put_unaligned_le16(io_request->index, &r1_request->request_id);
5561         r1_request->error_index = r1_request->request_id;
5562         if (rmd->cdb_length > sizeof(r1_request->cdb))
5563                 rmd->cdb_length = sizeof(r1_request->cdb);
5564         r1_request->cdb_length = rmd->cdb_length;
5565         memcpy(r1_request->cdb, rmd->cdb, rmd->cdb_length);
5566
5567         /* The direction is always write. */
5568         r1_request->data_direction = SOP_READ_FLAG;
5569
5570         if (encryption_info) {
5571                 r1_request->encryption_enable = true;
5572                 put_unaligned_le16(encryption_info->data_encryption_key_index,
5573                                 &r1_request->data_encryption_key_index);
5574                 put_unaligned_le32(encryption_info->encrypt_tweak_lower,
5575                                 &r1_request->encrypt_tweak_lower);
5576                 put_unaligned_le32(encryption_info->encrypt_tweak_upper,
5577                                 &r1_request->encrypt_tweak_upper);
5578         }
5579
5580         rc = pqi_build_aio_r1_sg_list(ctrl_info, r1_request, scmd, io_request);
5581         if (rc) {
5582                 pqi_free_io_request(io_request);
5583                 return SCSI_MLQUEUE_HOST_BUSY;
5584         }
5585
5586         pqi_start_io(ctrl_info, queue_group, AIO_PATH, io_request);
5587
5588         return 0;
5589 }
5590
5591 static int pqi_aio_submit_r56_write_io(struct pqi_ctrl_info *ctrl_info,
5592         struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
5593         struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
5594         struct pqi_scsi_dev_raid_map_data *rmd)
5595 {
5596         int rc;
5597         struct pqi_io_request *io_request;
5598         struct pqi_aio_r56_path_request *r56_request;
5599
5600         io_request = pqi_alloc_io_request(ctrl_info);
5601         io_request->io_complete_callback = pqi_aio_io_complete;
5602         io_request->scmd = scmd;
5603         io_request->raid_bypass = true;
5604
5605         r56_request = io_request->iu;
5606         memset(r56_request, 0, offsetof(struct pqi_aio_r56_path_request, sg_descriptors));
5607
5608         if (device->raid_level == SA_RAID_5 || device->raid_level == SA_RAID_51)
5609                 r56_request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_RAID5_IO;
5610         else
5611                 r56_request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_RAID6_IO;
5612
5613         put_unaligned_le16(*(u16 *)device->scsi3addr & 0x3fff, &r56_request->volume_id);
5614         put_unaligned_le32(rmd->aio_handle, &r56_request->data_it_nexus);
5615         put_unaligned_le32(rmd->p_parity_it_nexus, &r56_request->p_parity_it_nexus);
5616         if (rmd->raid_level == SA_RAID_6) {
5617                 put_unaligned_le32(rmd->q_parity_it_nexus, &r56_request->q_parity_it_nexus);
5618                 r56_request->xor_multiplier = rmd->xor_mult;
5619         }
5620         put_unaligned_le32(scsi_bufflen(scmd), &r56_request->data_length);
5621         r56_request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5622         put_unaligned_le64(rmd->row, &r56_request->row);
5623
5624         put_unaligned_le16(io_request->index, &r56_request->request_id);
5625         r56_request->error_index = r56_request->request_id;
5626
5627         if (rmd->cdb_length > sizeof(r56_request->cdb))
5628                 rmd->cdb_length = sizeof(r56_request->cdb);
5629         r56_request->cdb_length = rmd->cdb_length;
5630         memcpy(r56_request->cdb, rmd->cdb, rmd->cdb_length);
5631
5632         /* The direction is always write. */
5633         r56_request->data_direction = SOP_READ_FLAG;
5634
5635         if (encryption_info) {
5636                 r56_request->encryption_enable = true;
5637                 put_unaligned_le16(encryption_info->data_encryption_key_index,
5638                                 &r56_request->data_encryption_key_index);
5639                 put_unaligned_le32(encryption_info->encrypt_tweak_lower,
5640                                 &r56_request->encrypt_tweak_lower);
5641                 put_unaligned_le32(encryption_info->encrypt_tweak_upper,
5642                                 &r56_request->encrypt_tweak_upper);
5643         }
5644
5645         rc = pqi_build_aio_r56_sg_list(ctrl_info, r56_request, scmd, io_request);
5646         if (rc) {
5647                 pqi_free_io_request(io_request);
5648                 return SCSI_MLQUEUE_HOST_BUSY;
5649         }
5650
5651         pqi_start_io(ctrl_info, queue_group, AIO_PATH, io_request);
5652
5653         return 0;
5654 }
5655
5656 static inline u16 pqi_get_hw_queue(struct pqi_ctrl_info *ctrl_info,
5657         struct scsi_cmnd *scmd)
5658 {
5659         u16 hw_queue;
5660
5661         hw_queue = blk_mq_unique_tag_to_hwq(blk_mq_unique_tag(scmd->request));
5662         if (hw_queue > ctrl_info->max_hw_queue_index)
5663                 hw_queue = 0;
5664
5665         return hw_queue;
5666 }
5667
5668 /*
5669  * This function gets called just before we hand the completed SCSI request
5670  * back to the SML.
5671  */
5672
5673 void pqi_prep_for_scsi_done(struct scsi_cmnd *scmd)
5674 {
5675         struct pqi_scsi_dev *device;
5676
5677         if (!scmd->device) {
5678                 set_host_byte(scmd, DID_NO_CONNECT);
5679                 return;
5680         }
5681
5682         device = scmd->device->hostdata;
5683         if (!device) {
5684                 set_host_byte(scmd, DID_NO_CONNECT);
5685                 return;
5686         }
5687
5688         atomic_dec(&device->scsi_cmds_outstanding);
5689 }
5690
5691 static int pqi_scsi_queue_command(struct Scsi_Host *shost,
5692         struct scsi_cmnd *scmd)
5693 {
5694         int rc;
5695         struct pqi_ctrl_info *ctrl_info;
5696         struct pqi_scsi_dev *device;
5697         u16 hw_queue;
5698         struct pqi_queue_group *queue_group;
5699         bool raid_bypassed;
5700
5701         device = scmd->device->hostdata;
5702
5703         if (!device) {
5704                 set_host_byte(scmd, DID_NO_CONNECT);
5705                 pqi_scsi_done(scmd);
5706                 return 0;
5707         }
5708
5709         atomic_inc(&device->scsi_cmds_outstanding);
5710
5711         ctrl_info = shost_to_hba(shost);
5712
5713         if (pqi_ctrl_offline(ctrl_info) || pqi_device_in_remove(device)) {
5714                 set_host_byte(scmd, DID_NO_CONNECT);
5715                 pqi_scsi_done(scmd);
5716                 return 0;
5717         }
5718
5719         pqi_ctrl_busy(ctrl_info);
5720         if (pqi_ctrl_blocked(ctrl_info) || pqi_device_in_reset(device) ||
5721             pqi_ctrl_in_ofa(ctrl_info) || pqi_ctrl_in_shutdown(ctrl_info)) {
5722                 rc = SCSI_MLQUEUE_HOST_BUSY;
5723                 goto out;
5724         }
5725
5726         /*
5727          * This is necessary because the SML doesn't zero out this field during
5728          * error recovery.
5729          */
5730         scmd->result = 0;
5731
5732         hw_queue = pqi_get_hw_queue(ctrl_info, scmd);
5733         queue_group = &ctrl_info->queue_groups[hw_queue];
5734
5735         if (pqi_is_logical_device(device)) {
5736                 raid_bypassed = false;
5737                 if (device->raid_bypass_enabled &&
5738                         !blk_rq_is_passthrough(scmd->request)) {
5739                         rc = pqi_raid_bypass_submit_scsi_cmd(ctrl_info, device,
5740                                 scmd, queue_group);
5741                         if (rc == 0 || rc == SCSI_MLQUEUE_HOST_BUSY) {
5742                                 raid_bypassed = true;
5743                                 atomic_inc(&device->raid_bypass_cnt);
5744                         }
5745                 }
5746                 if (!raid_bypassed)
5747                         rc = pqi_raid_submit_scsi_cmd(ctrl_info, device, scmd, queue_group);
5748         } else {
5749                 if (device->aio_enabled)
5750                         rc = pqi_aio_submit_scsi_cmd(ctrl_info, device, scmd, queue_group);
5751                 else
5752                         rc = pqi_raid_submit_scsi_cmd(ctrl_info, device, scmd, queue_group);
5753         }
5754
5755 out:
5756         pqi_ctrl_unbusy(ctrl_info);
5757         if (rc)
5758                 atomic_dec(&device->scsi_cmds_outstanding);
5759
5760         return rc;
5761 }
5762
5763 static int pqi_wait_until_queued_io_drained(struct pqi_ctrl_info *ctrl_info,
5764         struct pqi_queue_group *queue_group)
5765 {
5766         unsigned int path;
5767         unsigned long flags;
5768         bool list_is_empty;
5769
5770         for (path = 0; path < 2; path++) {
5771                 while (1) {
5772                         spin_lock_irqsave(
5773                                 &queue_group->submit_lock[path], flags);
5774                         list_is_empty =
5775                                 list_empty(&queue_group->request_list[path]);
5776                         spin_unlock_irqrestore(
5777                                 &queue_group->submit_lock[path], flags);
5778                         if (list_is_empty)
5779                                 break;
5780                         pqi_check_ctrl_health(ctrl_info);
5781                         if (pqi_ctrl_offline(ctrl_info))
5782                                 return -ENXIO;
5783                         usleep_range(1000, 2000);
5784                 }
5785         }
5786
5787         return 0;
5788 }
5789
5790 static int pqi_wait_until_inbound_queues_empty(struct pqi_ctrl_info *ctrl_info)
5791 {
5792         int rc;
5793         unsigned int i;
5794         unsigned int path;
5795         struct pqi_queue_group *queue_group;
5796         pqi_index_t iq_pi;
5797         pqi_index_t iq_ci;
5798
5799         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
5800                 queue_group = &ctrl_info->queue_groups[i];
5801
5802                 rc = pqi_wait_until_queued_io_drained(ctrl_info, queue_group);
5803                 if (rc)
5804                         return rc;
5805
5806                 for (path = 0; path < 2; path++) {
5807                         iq_pi = queue_group->iq_pi_copy[path];
5808
5809                         while (1) {
5810                                 iq_ci = readl(queue_group->iq_ci[path]);
5811                                 if (iq_ci == iq_pi)
5812                                         break;
5813                                 pqi_check_ctrl_health(ctrl_info);
5814                                 if (pqi_ctrl_offline(ctrl_info))
5815                                         return -ENXIO;
5816                                 usleep_range(1000, 2000);
5817                         }
5818                 }
5819         }
5820
5821         return 0;
5822 }
5823
5824 static void pqi_fail_io_queued_for_device(struct pqi_ctrl_info *ctrl_info,
5825         struct pqi_scsi_dev *device)
5826 {
5827         unsigned int i;
5828         unsigned int path;
5829         struct pqi_queue_group *queue_group;
5830         unsigned long flags;
5831         struct pqi_io_request *io_request;
5832         struct pqi_io_request *next;
5833         struct scsi_cmnd *scmd;
5834         struct pqi_scsi_dev *scsi_device;
5835
5836         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
5837                 queue_group = &ctrl_info->queue_groups[i];
5838
5839                 for (path = 0; path < 2; path++) {
5840                         spin_lock_irqsave(
5841                                 &queue_group->submit_lock[path], flags);
5842
5843                         list_for_each_entry_safe(io_request, next,
5844                                 &queue_group->request_list[path],
5845                                 request_list_entry) {
5846
5847                                 scmd = io_request->scmd;
5848                                 if (!scmd)
5849                                         continue;
5850
5851                                 scsi_device = scmd->device->hostdata;
5852                                 if (scsi_device != device)
5853                                         continue;
5854
5855                                 list_del(&io_request->request_list_entry);
5856                                 set_host_byte(scmd, DID_RESET);
5857                                 pqi_free_io_request(io_request);
5858                                 scsi_dma_unmap(scmd);
5859                                 pqi_scsi_done(scmd);
5860                         }
5861
5862                         spin_unlock_irqrestore(
5863                                 &queue_group->submit_lock[path], flags);
5864                 }
5865         }
5866 }
5867
5868 static void pqi_fail_io_queued_for_all_devices(struct pqi_ctrl_info *ctrl_info)
5869 {
5870         unsigned int i;
5871         unsigned int path;
5872         struct pqi_queue_group *queue_group;
5873         unsigned long flags;
5874         struct pqi_io_request *io_request;
5875         struct pqi_io_request *next;
5876         struct scsi_cmnd *scmd;
5877
5878         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
5879                 queue_group = &ctrl_info->queue_groups[i];
5880
5881                 for (path = 0; path < 2; path++) {
5882                         spin_lock_irqsave(&queue_group->submit_lock[path],
5883                                                 flags);
5884
5885                         list_for_each_entry_safe(io_request, next,
5886                                 &queue_group->request_list[path],
5887                                 request_list_entry) {
5888
5889                                 scmd = io_request->scmd;
5890                                 if (!scmd)
5891                                         continue;
5892
5893                                 list_del(&io_request->request_list_entry);
5894                                 set_host_byte(scmd, DID_RESET);
5895                                 pqi_free_io_request(io_request);
5896                                 scsi_dma_unmap(scmd);
5897                                 pqi_scsi_done(scmd);
5898                         }
5899
5900                         spin_unlock_irqrestore(
5901                                 &queue_group->submit_lock[path], flags);
5902                 }
5903         }
5904 }
5905
5906 static int pqi_device_wait_for_pending_io(struct pqi_ctrl_info *ctrl_info,
5907         struct pqi_scsi_dev *device, unsigned long timeout_secs)
5908 {
5909         unsigned long timeout;
5910
5911         timeout = (timeout_secs * PQI_HZ) + jiffies;
5912
5913         while (atomic_read(&device->scsi_cmds_outstanding)) {
5914                 pqi_check_ctrl_health(ctrl_info);
5915                 if (pqi_ctrl_offline(ctrl_info))
5916                         return -ENXIO;
5917                 if (timeout_secs != NO_TIMEOUT) {
5918                         if (time_after(jiffies, timeout)) {
5919                                 dev_err(&ctrl_info->pci_dev->dev,
5920                                         "timed out waiting for pending IO\n");
5921                                 return -ETIMEDOUT;
5922                         }
5923                 }
5924                 usleep_range(1000, 2000);
5925         }
5926
5927         return 0;
5928 }
5929
5930 static int pqi_ctrl_wait_for_pending_io(struct pqi_ctrl_info *ctrl_info,
5931         unsigned long timeout_secs)
5932 {
5933         bool io_pending;
5934         unsigned long flags;
5935         unsigned long timeout;
5936         struct pqi_scsi_dev *device;
5937
5938         timeout = (timeout_secs * PQI_HZ) + jiffies;
5939         while (1) {
5940                 io_pending = false;
5941
5942                 spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
5943                 list_for_each_entry(device, &ctrl_info->scsi_device_list,
5944                         scsi_device_list_entry) {
5945                         if (atomic_read(&device->scsi_cmds_outstanding)) {
5946                                 io_pending = true;
5947                                 break;
5948                         }
5949                 }
5950                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock,
5951                                         flags);
5952
5953                 if (!io_pending)
5954                         break;
5955
5956                 pqi_check_ctrl_health(ctrl_info);
5957                 if (pqi_ctrl_offline(ctrl_info))
5958                         return -ENXIO;
5959
5960                 if (timeout_secs != NO_TIMEOUT) {
5961                         if (time_after(jiffies, timeout)) {
5962                                 dev_err(&ctrl_info->pci_dev->dev,
5963                                         "timed out waiting for pending IO\n");
5964                                 return -ETIMEDOUT;
5965                         }
5966                 }
5967                 usleep_range(1000, 2000);
5968         }
5969
5970         return 0;
5971 }
5972
5973 static int pqi_ctrl_wait_for_pending_sync_cmds(struct pqi_ctrl_info *ctrl_info)
5974 {
5975         while (atomic_read(&ctrl_info->sync_cmds_outstanding)) {
5976                 pqi_check_ctrl_health(ctrl_info);
5977                 if (pqi_ctrl_offline(ctrl_info))
5978                         return -ENXIO;
5979                 usleep_range(1000, 2000);
5980         }
5981
5982         return 0;
5983 }
5984
5985 static void pqi_lun_reset_complete(struct pqi_io_request *io_request,
5986         void *context)
5987 {
5988         struct completion *waiting = context;
5989
5990         complete(waiting);
5991 }
5992
5993 #define PQI_LUN_RESET_TIMEOUT_SECS              30
5994 #define PQI_LUN_RESET_POLL_COMPLETION_SECS      10
5995
5996 static int pqi_wait_for_lun_reset_completion(struct pqi_ctrl_info *ctrl_info,
5997         struct pqi_scsi_dev *device, struct completion *wait)
5998 {
5999         int rc;
6000
6001         while (1) {
6002                 if (wait_for_completion_io_timeout(wait,
6003                         PQI_LUN_RESET_POLL_COMPLETION_SECS * PQI_HZ)) {
6004                         rc = 0;
6005                         break;
6006                 }
6007
6008                 pqi_check_ctrl_health(ctrl_info);
6009                 if (pqi_ctrl_offline(ctrl_info)) {
6010                         rc = -ENXIO;
6011                         break;
6012                 }
6013         }
6014
6015         return rc;
6016 }
6017
6018 static int pqi_lun_reset(struct pqi_ctrl_info *ctrl_info,
6019         struct pqi_scsi_dev *device)
6020 {
6021         int rc;
6022         struct pqi_io_request *io_request;
6023         DECLARE_COMPLETION_ONSTACK(wait);
6024         struct pqi_task_management_request *request;
6025
6026         io_request = pqi_alloc_io_request(ctrl_info);
6027         io_request->io_complete_callback = pqi_lun_reset_complete;
6028         io_request->context = &wait;
6029
6030         request = io_request->iu;
6031         memset(request, 0, sizeof(*request));
6032
6033         request->header.iu_type = PQI_REQUEST_IU_TASK_MANAGEMENT;
6034         put_unaligned_le16(sizeof(*request) - PQI_REQUEST_HEADER_LENGTH,
6035                 &request->header.iu_length);
6036         put_unaligned_le16(io_request->index, &request->request_id);
6037         memcpy(request->lun_number, device->scsi3addr,
6038                 sizeof(request->lun_number));
6039         request->task_management_function = SOP_TASK_MANAGEMENT_LUN_RESET;
6040         if (ctrl_info->tmf_iu_timeout_supported)
6041                 put_unaligned_le16(PQI_LUN_RESET_TIMEOUT_SECS,
6042                                         &request->timeout);
6043
6044         pqi_start_io(ctrl_info, &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP], RAID_PATH,
6045                 io_request);
6046
6047         rc = pqi_wait_for_lun_reset_completion(ctrl_info, device, &wait);
6048         if (rc == 0)
6049                 rc = io_request->status;
6050
6051         pqi_free_io_request(io_request);
6052
6053         return rc;
6054 }
6055
6056 /* Performs a reset at the LUN level. */
6057
6058 #define PQI_LUN_RESET_RETRIES                   3
6059 #define PQI_LUN_RESET_RETRY_INTERVAL_MSECS      10000
6060 #define PQI_LUN_RESET_PENDING_IO_TIMEOUT_SECS   120
6061
6062 static int _pqi_device_reset(struct pqi_ctrl_info *ctrl_info,
6063         struct pqi_scsi_dev *device)
6064 {
6065         int rc;
6066         unsigned int retries;
6067         unsigned long timeout_secs;
6068
6069         for (retries = 0;;) {
6070                 rc = pqi_lun_reset(ctrl_info, device);
6071                 if (rc == 0 || ++retries > PQI_LUN_RESET_RETRIES)
6072                         break;
6073                 msleep(PQI_LUN_RESET_RETRY_INTERVAL_MSECS);
6074         }
6075
6076         timeout_secs = rc ? PQI_LUN_RESET_PENDING_IO_TIMEOUT_SECS : NO_TIMEOUT;
6077
6078         rc |= pqi_device_wait_for_pending_io(ctrl_info, device, timeout_secs);
6079
6080         return rc == 0 ? SUCCESS : FAILED;
6081 }
6082
6083 static int pqi_device_reset(struct pqi_ctrl_info *ctrl_info,
6084         struct pqi_scsi_dev *device)
6085 {
6086         int rc;
6087
6088         mutex_lock(&ctrl_info->lun_reset_mutex);
6089
6090         pqi_ctrl_block_requests(ctrl_info);
6091         pqi_ctrl_wait_until_quiesced(ctrl_info);
6092         pqi_fail_io_queued_for_device(ctrl_info, device);
6093         rc = pqi_wait_until_inbound_queues_empty(ctrl_info);
6094         pqi_device_reset_start(device);
6095         pqi_ctrl_unblock_requests(ctrl_info);
6096
6097         if (rc)
6098                 rc = FAILED;
6099         else
6100                 rc = _pqi_device_reset(ctrl_info, device);
6101
6102         pqi_device_reset_done(device);
6103
6104         mutex_unlock(&ctrl_info->lun_reset_mutex);
6105
6106         return rc;
6107 }
6108
6109 static int pqi_eh_device_reset_handler(struct scsi_cmnd *scmd)
6110 {
6111         int rc;
6112         struct Scsi_Host *shost;
6113         struct pqi_ctrl_info *ctrl_info;
6114         struct pqi_scsi_dev *device;
6115
6116         shost = scmd->device->host;
6117         ctrl_info = shost_to_hba(shost);
6118         device = scmd->device->hostdata;
6119
6120         dev_err(&ctrl_info->pci_dev->dev,
6121                 "resetting scsi %d:%d:%d:%d\n",
6122                 shost->host_no, device->bus, device->target, device->lun);
6123
6124         pqi_check_ctrl_health(ctrl_info);
6125         if (pqi_ctrl_offline(ctrl_info) ||
6126                 pqi_device_reset_blocked(ctrl_info)) {
6127                 rc = FAILED;
6128                 goto out;
6129         }
6130
6131         pqi_wait_until_ofa_finished(ctrl_info);
6132
6133         atomic_inc(&ctrl_info->sync_cmds_outstanding);
6134         rc = pqi_device_reset(ctrl_info, device);
6135         atomic_dec(&ctrl_info->sync_cmds_outstanding);
6136
6137 out:
6138         dev_err(&ctrl_info->pci_dev->dev,
6139                 "reset of scsi %d:%d:%d:%d: %s\n",
6140                 shost->host_no, device->bus, device->target, device->lun,
6141                 rc == SUCCESS ? "SUCCESS" : "FAILED");
6142
6143         return rc;
6144 }
6145
6146 static int pqi_slave_alloc(struct scsi_device *sdev)
6147 {
6148         struct pqi_scsi_dev *device;
6149         unsigned long flags;
6150         struct pqi_ctrl_info *ctrl_info;
6151         struct scsi_target *starget;
6152         struct sas_rphy *rphy;
6153
6154         ctrl_info = shost_to_hba(sdev->host);
6155
6156         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6157
6158         if (sdev_channel(sdev) == PQI_PHYSICAL_DEVICE_BUS) {
6159                 starget = scsi_target(sdev);
6160                 rphy = target_to_rphy(starget);
6161                 device = pqi_find_device_by_sas_rphy(ctrl_info, rphy);
6162                 if (device) {
6163                         device->target = sdev_id(sdev);
6164                         device->lun = sdev->lun;
6165                         device->target_lun_valid = true;
6166                 }
6167         } else {
6168                 device = pqi_find_scsi_dev(ctrl_info, sdev_channel(sdev),
6169                         sdev_id(sdev), sdev->lun);
6170         }
6171
6172         if (device) {
6173                 sdev->hostdata = device;
6174                 device->sdev = sdev;
6175                 if (device->queue_depth) {
6176                         device->advertised_queue_depth = device->queue_depth;
6177                         scsi_change_queue_depth(sdev,
6178                                 device->advertised_queue_depth);
6179                 }
6180                 if (pqi_is_logical_device(device))
6181                         pqi_disable_write_same(sdev);
6182                 else
6183                         sdev->allow_restart = 1;
6184         }
6185
6186         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6187
6188         return 0;
6189 }
6190
6191 static int pqi_map_queues(struct Scsi_Host *shost)
6192 {
6193         struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6194
6195         return blk_mq_pci_map_queues(&shost->tag_set.map[HCTX_TYPE_DEFAULT],
6196                                         ctrl_info->pci_dev, 0);
6197 }
6198
6199 static int pqi_slave_configure(struct scsi_device *sdev)
6200 {
6201         struct pqi_scsi_dev *device;
6202
6203         device = sdev->hostdata;
6204         device->devtype = sdev->type;
6205
6206         return 0;
6207 }
6208
6209 static void pqi_slave_destroy(struct scsi_device *sdev)
6210 {
6211         unsigned long flags;
6212         struct pqi_scsi_dev *device;
6213         struct pqi_ctrl_info *ctrl_info;
6214
6215         ctrl_info = shost_to_hba(sdev->host);
6216
6217         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6218
6219         device = sdev->hostdata;
6220         if (device) {
6221                 sdev->hostdata = NULL;
6222                 if (!list_empty(&device->scsi_device_list_entry))
6223                         list_del(&device->scsi_device_list_entry);
6224         }
6225
6226         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6227
6228         if (device) {
6229                 pqi_dev_info(ctrl_info, "removed", device);
6230                 pqi_free_device(device);
6231         }
6232 }
6233
6234 static int pqi_getpciinfo_ioctl(struct pqi_ctrl_info *ctrl_info, void __user *arg)
6235 {
6236         struct pci_dev *pci_dev;
6237         u32 subsystem_vendor;
6238         u32 subsystem_device;
6239         cciss_pci_info_struct pciinfo;
6240
6241         if (!arg)
6242                 return -EINVAL;
6243
6244         pci_dev = ctrl_info->pci_dev;
6245
6246         pciinfo.domain = pci_domain_nr(pci_dev->bus);
6247         pciinfo.bus = pci_dev->bus->number;
6248         pciinfo.dev_fn = pci_dev->devfn;
6249         subsystem_vendor = pci_dev->subsystem_vendor;
6250         subsystem_device = pci_dev->subsystem_device;
6251         pciinfo.board_id = ((subsystem_device << 16) & 0xffff0000) | subsystem_vendor;
6252
6253         if (copy_to_user(arg, &pciinfo, sizeof(pciinfo)))
6254                 return -EFAULT;
6255
6256         return 0;
6257 }
6258
6259 static int pqi_getdrivver_ioctl(void __user *arg)
6260 {
6261         u32 version;
6262
6263         if (!arg)
6264                 return -EINVAL;
6265
6266         version = (DRIVER_MAJOR << 28) | (DRIVER_MINOR << 24) |
6267                 (DRIVER_RELEASE << 16) | DRIVER_REVISION;
6268
6269         if (copy_to_user(arg, &version, sizeof(version)))
6270                 return -EFAULT;
6271
6272         return 0;
6273 }
6274
6275 struct ciss_error_info {
6276         u8      scsi_status;
6277         int     command_status;
6278         size_t  sense_data_length;
6279 };
6280
6281 static void pqi_error_info_to_ciss(struct pqi_raid_error_info *pqi_error_info,
6282         struct ciss_error_info *ciss_error_info)
6283 {
6284         int ciss_cmd_status;
6285         size_t sense_data_length;
6286
6287         switch (pqi_error_info->data_out_result) {
6288         case PQI_DATA_IN_OUT_GOOD:
6289                 ciss_cmd_status = CISS_CMD_STATUS_SUCCESS;
6290                 break;
6291         case PQI_DATA_IN_OUT_UNDERFLOW:
6292                 ciss_cmd_status = CISS_CMD_STATUS_DATA_UNDERRUN;
6293                 break;
6294         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW:
6295                 ciss_cmd_status = CISS_CMD_STATUS_DATA_OVERRUN;
6296                 break;
6297         case PQI_DATA_IN_OUT_PROTOCOL_ERROR:
6298         case PQI_DATA_IN_OUT_BUFFER_ERROR:
6299         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_DESCRIPTOR_AREA:
6300         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_BRIDGE:
6301         case PQI_DATA_IN_OUT_ERROR:
6302                 ciss_cmd_status = CISS_CMD_STATUS_PROTOCOL_ERROR;
6303                 break;
6304         case PQI_DATA_IN_OUT_HARDWARE_ERROR:
6305         case PQI_DATA_IN_OUT_PCIE_FABRIC_ERROR:
6306         case PQI_DATA_IN_OUT_PCIE_COMPLETION_TIMEOUT:
6307         case PQI_DATA_IN_OUT_PCIE_COMPLETER_ABORT_RECEIVED:
6308         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST_RECEIVED:
6309         case PQI_DATA_IN_OUT_PCIE_ECRC_CHECK_FAILED:
6310         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST:
6311         case PQI_DATA_IN_OUT_PCIE_ACS_VIOLATION:
6312         case PQI_DATA_IN_OUT_PCIE_TLP_PREFIX_BLOCKED:
6313         case PQI_DATA_IN_OUT_PCIE_POISONED_MEMORY_READ:
6314                 ciss_cmd_status = CISS_CMD_STATUS_HARDWARE_ERROR;
6315                 break;
6316         case PQI_DATA_IN_OUT_UNSOLICITED_ABORT:
6317                 ciss_cmd_status = CISS_CMD_STATUS_UNSOLICITED_ABORT;
6318                 break;
6319         case PQI_DATA_IN_OUT_ABORTED:
6320                 ciss_cmd_status = CISS_CMD_STATUS_ABORTED;
6321                 break;
6322         case PQI_DATA_IN_OUT_TIMEOUT:
6323                 ciss_cmd_status = CISS_CMD_STATUS_TIMEOUT;
6324                 break;
6325         default:
6326                 ciss_cmd_status = CISS_CMD_STATUS_TARGET_STATUS;
6327                 break;
6328         }
6329
6330         sense_data_length =
6331                 get_unaligned_le16(&pqi_error_info->sense_data_length);
6332         if (sense_data_length == 0)
6333                 sense_data_length =
6334                 get_unaligned_le16(&pqi_error_info->response_data_length);
6335         if (sense_data_length)
6336                 if (sense_data_length > sizeof(pqi_error_info->data))
6337                         sense_data_length = sizeof(pqi_error_info->data);
6338
6339         ciss_error_info->scsi_status = pqi_error_info->status;
6340         ciss_error_info->command_status = ciss_cmd_status;
6341         ciss_error_info->sense_data_length = sense_data_length;
6342 }
6343
6344 static int pqi_passthru_ioctl(struct pqi_ctrl_info *ctrl_info, void __user *arg)
6345 {
6346         int rc;
6347         char *kernel_buffer = NULL;
6348         u16 iu_length;
6349         size_t sense_data_length;
6350         IOCTL_Command_struct iocommand;
6351         struct pqi_raid_path_request request;
6352         struct pqi_raid_error_info pqi_error_info;
6353         struct ciss_error_info ciss_error_info;
6354
6355         if (pqi_ctrl_offline(ctrl_info))
6356                 return -ENXIO;
6357         if (!arg)
6358                 return -EINVAL;
6359         if (!capable(CAP_SYS_RAWIO))
6360                 return -EPERM;
6361         if (copy_from_user(&iocommand, arg, sizeof(iocommand)))
6362                 return -EFAULT;
6363         if (iocommand.buf_size < 1 &&
6364                 iocommand.Request.Type.Direction != XFER_NONE)
6365                 return -EINVAL;
6366         if (iocommand.Request.CDBLen > sizeof(request.cdb))
6367                 return -EINVAL;
6368         if (iocommand.Request.Type.Type != TYPE_CMD)
6369                 return -EINVAL;
6370
6371         switch (iocommand.Request.Type.Direction) {
6372         case XFER_NONE:
6373         case XFER_WRITE:
6374         case XFER_READ:
6375         case XFER_READ | XFER_WRITE:
6376                 break;
6377         default:
6378                 return -EINVAL;
6379         }
6380
6381         if (iocommand.buf_size > 0) {
6382                 kernel_buffer = kmalloc(iocommand.buf_size, GFP_KERNEL);
6383                 if (!kernel_buffer)
6384                         return -ENOMEM;
6385                 if (iocommand.Request.Type.Direction & XFER_WRITE) {
6386                         if (copy_from_user(kernel_buffer, iocommand.buf,
6387                                 iocommand.buf_size)) {
6388                                 rc = -EFAULT;
6389                                 goto out;
6390                         }
6391                 } else {
6392                         memset(kernel_buffer, 0, iocommand.buf_size);
6393                 }
6394         }
6395
6396         memset(&request, 0, sizeof(request));
6397
6398         request.header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
6399         iu_length = offsetof(struct pqi_raid_path_request, sg_descriptors) -
6400                 PQI_REQUEST_HEADER_LENGTH;
6401         memcpy(request.lun_number, iocommand.LUN_info.LunAddrBytes,
6402                 sizeof(request.lun_number));
6403         memcpy(request.cdb, iocommand.Request.CDB, iocommand.Request.CDBLen);
6404         request.additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
6405
6406         switch (iocommand.Request.Type.Direction) {
6407         case XFER_NONE:
6408                 request.data_direction = SOP_NO_DIRECTION_FLAG;
6409                 break;
6410         case XFER_WRITE:
6411                 request.data_direction = SOP_WRITE_FLAG;
6412                 break;
6413         case XFER_READ:
6414                 request.data_direction = SOP_READ_FLAG;
6415                 break;
6416         case XFER_READ | XFER_WRITE:
6417                 request.data_direction = SOP_BIDIRECTIONAL;
6418                 break;
6419         }
6420
6421         request.task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
6422
6423         if (iocommand.buf_size > 0) {
6424                 put_unaligned_le32(iocommand.buf_size, &request.buffer_length);
6425
6426                 rc = pqi_map_single(ctrl_info->pci_dev,
6427                         &request.sg_descriptors[0], kernel_buffer,
6428                         iocommand.buf_size, DMA_BIDIRECTIONAL);
6429                 if (rc)
6430                         goto out;
6431
6432                 iu_length += sizeof(request.sg_descriptors[0]);
6433         }
6434
6435         put_unaligned_le16(iu_length, &request.header.iu_length);
6436
6437         if (ctrl_info->raid_iu_timeout_supported)
6438                 put_unaligned_le32(iocommand.Request.Timeout, &request.timeout);
6439
6440         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
6441                 PQI_SYNC_FLAGS_INTERRUPTABLE, &pqi_error_info, NO_TIMEOUT);
6442
6443         if (iocommand.buf_size > 0)
6444                 pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
6445                         DMA_BIDIRECTIONAL);
6446
6447         memset(&iocommand.error_info, 0, sizeof(iocommand.error_info));
6448
6449         if (rc == 0) {
6450                 pqi_error_info_to_ciss(&pqi_error_info, &ciss_error_info);
6451                 iocommand.error_info.ScsiStatus = ciss_error_info.scsi_status;
6452                 iocommand.error_info.CommandStatus =
6453                         ciss_error_info.command_status;
6454                 sense_data_length = ciss_error_info.sense_data_length;
6455                 if (sense_data_length) {
6456                         if (sense_data_length >
6457                                 sizeof(iocommand.error_info.SenseInfo))
6458                                 sense_data_length =
6459                                         sizeof(iocommand.error_info.SenseInfo);
6460                         memcpy(iocommand.error_info.SenseInfo,
6461                                 pqi_error_info.data, sense_data_length);
6462                         iocommand.error_info.SenseLen = sense_data_length;
6463                 }
6464         }
6465
6466         if (copy_to_user(arg, &iocommand, sizeof(iocommand))) {
6467                 rc = -EFAULT;
6468                 goto out;
6469         }
6470
6471         if (rc == 0 && iocommand.buf_size > 0 &&
6472                 (iocommand.Request.Type.Direction & XFER_READ)) {
6473                 if (copy_to_user(iocommand.buf, kernel_buffer,
6474                         iocommand.buf_size)) {
6475                         rc = -EFAULT;
6476                 }
6477         }
6478
6479 out:
6480         kfree(kernel_buffer);
6481
6482         return rc;
6483 }
6484
6485 static int pqi_ioctl(struct scsi_device *sdev, unsigned int cmd,
6486                      void __user *arg)
6487 {
6488         int rc;
6489         struct pqi_ctrl_info *ctrl_info;
6490
6491         ctrl_info = shost_to_hba(sdev->host);
6492
6493         if (pqi_ctrl_in_ofa(ctrl_info) || pqi_ctrl_in_shutdown(ctrl_info))
6494                 return -EBUSY;
6495
6496         switch (cmd) {
6497         case CCISS_DEREGDISK:
6498         case CCISS_REGNEWDISK:
6499         case CCISS_REGNEWD:
6500                 rc = pqi_scan_scsi_devices(ctrl_info);
6501                 break;
6502         case CCISS_GETPCIINFO:
6503                 rc = pqi_getpciinfo_ioctl(ctrl_info, arg);
6504                 break;
6505         case CCISS_GETDRIVVER:
6506                 rc = pqi_getdrivver_ioctl(arg);
6507                 break;
6508         case CCISS_PASSTHRU:
6509                 rc = pqi_passthru_ioctl(ctrl_info, arg);
6510                 break;
6511         default:
6512                 rc = -EINVAL;
6513                 break;
6514         }
6515
6516         return rc;
6517 }
6518
6519 static ssize_t pqi_firmware_version_show(struct device *dev,
6520         struct device_attribute *attr, char *buffer)
6521 {
6522         struct Scsi_Host *shost;
6523         struct pqi_ctrl_info *ctrl_info;
6524
6525         shost = class_to_shost(dev);
6526         ctrl_info = shost_to_hba(shost);
6527
6528         return snprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->firmware_version);
6529 }
6530
6531 static ssize_t pqi_driver_version_show(struct device *dev,
6532         struct device_attribute *attr, char *buffer)
6533 {
6534         return snprintf(buffer, PAGE_SIZE, "%s\n",
6535                         DRIVER_VERSION BUILD_TIMESTAMP);
6536 }
6537
6538 static ssize_t pqi_serial_number_show(struct device *dev,
6539         struct device_attribute *attr, char *buffer)
6540 {
6541         struct Scsi_Host *shost;
6542         struct pqi_ctrl_info *ctrl_info;
6543
6544         shost = class_to_shost(dev);
6545         ctrl_info = shost_to_hba(shost);
6546
6547         return snprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->serial_number);
6548 }
6549
6550 static ssize_t pqi_model_show(struct device *dev,
6551         struct device_attribute *attr, char *buffer)
6552 {
6553         struct Scsi_Host *shost;
6554         struct pqi_ctrl_info *ctrl_info;
6555
6556         shost = class_to_shost(dev);
6557         ctrl_info = shost_to_hba(shost);
6558
6559         return snprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->model);
6560 }
6561
6562 static ssize_t pqi_vendor_show(struct device *dev,
6563         struct device_attribute *attr, char *buffer)
6564 {
6565         struct Scsi_Host *shost;
6566         struct pqi_ctrl_info *ctrl_info;
6567
6568         shost = class_to_shost(dev);
6569         ctrl_info = shost_to_hba(shost);
6570
6571         return snprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->vendor);
6572 }
6573
6574 static ssize_t pqi_host_rescan_store(struct device *dev,
6575         struct device_attribute *attr, const char *buffer, size_t count)
6576 {
6577         struct Scsi_Host *shost = class_to_shost(dev);
6578
6579         pqi_scan_start(shost);
6580
6581         return count;
6582 }
6583
6584 static ssize_t pqi_lockup_action_show(struct device *dev,
6585         struct device_attribute *attr, char *buffer)
6586 {
6587         int count = 0;
6588         unsigned int i;
6589
6590         for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
6591                 if (pqi_lockup_actions[i].action == pqi_lockup_action)
6592                         count += scnprintf(buffer + count, PAGE_SIZE - count,
6593                                 "[%s] ", pqi_lockup_actions[i].name);
6594                 else
6595                         count += scnprintf(buffer + count, PAGE_SIZE - count,
6596                                 "%s ", pqi_lockup_actions[i].name);
6597         }
6598
6599         count += scnprintf(buffer + count, PAGE_SIZE - count, "\n");
6600
6601         return count;
6602 }
6603
6604 static ssize_t pqi_lockup_action_store(struct device *dev,
6605         struct device_attribute *attr, const char *buffer, size_t count)
6606 {
6607         unsigned int i;
6608         char *action_name;
6609         char action_name_buffer[32];
6610
6611         strlcpy(action_name_buffer, buffer, sizeof(action_name_buffer));
6612         action_name = strstrip(action_name_buffer);
6613
6614         for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
6615                 if (strcmp(action_name, pqi_lockup_actions[i].name) == 0) {
6616                         pqi_lockup_action = pqi_lockup_actions[i].action;
6617                         return count;
6618                 }
6619         }
6620
6621         return -EINVAL;
6622 }
6623
6624 static ssize_t pqi_host_enable_r5_writes_show(struct device *dev,
6625         struct device_attribute *attr, char *buffer)
6626 {
6627         struct Scsi_Host *shost = class_to_shost(dev);
6628         struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6629
6630         return scnprintf(buffer, 10, "%x\n", ctrl_info->enable_r5_writes);
6631 }
6632
6633 static ssize_t pqi_host_enable_r5_writes_store(struct device *dev,
6634         struct device_attribute *attr, const char *buffer, size_t count)
6635 {
6636         struct Scsi_Host *shost = class_to_shost(dev);
6637         struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6638         u8 set_r5_writes = 0;
6639
6640         if (kstrtou8(buffer, 0, &set_r5_writes))
6641                 return -EINVAL;
6642
6643         if (set_r5_writes > 0)
6644                 set_r5_writes = 1;
6645
6646         ctrl_info->enable_r5_writes = set_r5_writes;
6647
6648         return count;
6649 }
6650
6651 static ssize_t pqi_host_enable_r6_writes_show(struct device *dev,
6652         struct device_attribute *attr, char *buffer)
6653 {
6654         struct Scsi_Host *shost = class_to_shost(dev);
6655         struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6656
6657         return scnprintf(buffer, 10, "%x\n", ctrl_info->enable_r6_writes);
6658 }
6659
6660 static ssize_t pqi_host_enable_r6_writes_store(struct device *dev,
6661         struct device_attribute *attr, const char *buffer, size_t count)
6662 {
6663         struct Scsi_Host *shost = class_to_shost(dev);
6664         struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6665         u8 set_r6_writes = 0;
6666
6667         if (kstrtou8(buffer, 0, &set_r6_writes))
6668                 return -EINVAL;
6669
6670         if (set_r6_writes > 0)
6671                 set_r6_writes = 1;
6672
6673         ctrl_info->enable_r6_writes = set_r6_writes;
6674
6675         return count;
6676 }
6677
6678 static DEVICE_ATTR(driver_version, 0444, pqi_driver_version_show, NULL);
6679 static DEVICE_ATTR(firmware_version, 0444, pqi_firmware_version_show, NULL);
6680 static DEVICE_ATTR(model, 0444, pqi_model_show, NULL);
6681 static DEVICE_ATTR(serial_number, 0444, pqi_serial_number_show, NULL);
6682 static DEVICE_ATTR(vendor, 0444, pqi_vendor_show, NULL);
6683 static DEVICE_ATTR(rescan, 0200, NULL, pqi_host_rescan_store);
6684 static DEVICE_ATTR(lockup_action, 0644, pqi_lockup_action_show,
6685         pqi_lockup_action_store);
6686 static DEVICE_ATTR(enable_r5_writes, 0644,
6687         pqi_host_enable_r5_writes_show, pqi_host_enable_r5_writes_store);
6688 static DEVICE_ATTR(enable_r6_writes, 0644,
6689         pqi_host_enable_r6_writes_show, pqi_host_enable_r6_writes_store);
6690
6691 static struct device_attribute *pqi_shost_attrs[] = {
6692         &dev_attr_driver_version,
6693         &dev_attr_firmware_version,
6694         &dev_attr_model,
6695         &dev_attr_serial_number,
6696         &dev_attr_vendor,
6697         &dev_attr_rescan,
6698         &dev_attr_lockup_action,
6699         &dev_attr_enable_r5_writes,
6700         &dev_attr_enable_r6_writes,
6701         NULL
6702 };
6703
6704 static ssize_t pqi_unique_id_show(struct device *dev,
6705         struct device_attribute *attr, char *buffer)
6706 {
6707         struct pqi_ctrl_info *ctrl_info;
6708         struct scsi_device *sdev;
6709         struct pqi_scsi_dev *device;
6710         unsigned long flags;
6711         u8 unique_id[16];
6712
6713         sdev = to_scsi_device(dev);
6714         ctrl_info = shost_to_hba(sdev->host);
6715
6716         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6717
6718         device = sdev->hostdata;
6719         if (!device) {
6720                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6721                 return -ENODEV;
6722         }
6723
6724         if (device->is_physical_device) {
6725                 memset(unique_id, 0, 8);
6726                 memcpy(unique_id + 8, &device->wwid, sizeof(device->wwid));
6727         } else {
6728                 memcpy(unique_id, device->volume_id, sizeof(device->volume_id));
6729         }
6730
6731         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6732
6733         return snprintf(buffer, PAGE_SIZE,
6734                 "%02X%02X%02X%02X%02X%02X%02X%02X"
6735                 "%02X%02X%02X%02X%02X%02X%02X%02X\n",
6736                 unique_id[0], unique_id[1], unique_id[2], unique_id[3],
6737                 unique_id[4], unique_id[5], unique_id[6], unique_id[7],
6738                 unique_id[8], unique_id[9], unique_id[10], unique_id[11],
6739                 unique_id[12], unique_id[13], unique_id[14], unique_id[15]);
6740 }
6741
6742 static ssize_t pqi_lunid_show(struct device *dev,
6743         struct device_attribute *attr, char *buffer)
6744 {
6745         struct pqi_ctrl_info *ctrl_info;
6746         struct scsi_device *sdev;
6747         struct pqi_scsi_dev *device;
6748         unsigned long flags;
6749         u8 lunid[8];
6750
6751         sdev = to_scsi_device(dev);
6752         ctrl_info = shost_to_hba(sdev->host);
6753
6754         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6755
6756         device = sdev->hostdata;
6757         if (!device) {
6758                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6759                 return -ENODEV;
6760         }
6761
6762         memcpy(lunid, device->scsi3addr, sizeof(lunid));
6763
6764         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6765
6766         return snprintf(buffer, PAGE_SIZE, "0x%8phN\n", lunid);
6767 }
6768
6769 #define MAX_PATHS       8
6770
6771 static ssize_t pqi_path_info_show(struct device *dev,
6772         struct device_attribute *attr, char *buf)
6773 {
6774         struct pqi_ctrl_info *ctrl_info;
6775         struct scsi_device *sdev;
6776         struct pqi_scsi_dev *device;
6777         unsigned long flags;
6778         int i;
6779         int output_len = 0;
6780         u8 box;
6781         u8 bay;
6782         u8 path_map_index;
6783         char *active;
6784         u8 phys_connector[2];
6785
6786         sdev = to_scsi_device(dev);
6787         ctrl_info = shost_to_hba(sdev->host);
6788
6789         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6790
6791         device = sdev->hostdata;
6792         if (!device) {
6793                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6794                 return -ENODEV;
6795         }
6796
6797         bay = device->bay;
6798         for (i = 0; i < MAX_PATHS; i++) {
6799                 path_map_index = 1 << i;
6800                 if (i == device->active_path_index)
6801                         active = "Active";
6802                 else if (device->path_map & path_map_index)
6803                         active = "Inactive";
6804                 else
6805                         continue;
6806
6807                 output_len += scnprintf(buf + output_len,
6808                                         PAGE_SIZE - output_len,
6809                                         "[%d:%d:%d:%d] %20.20s ",
6810                                         ctrl_info->scsi_host->host_no,
6811                                         device->bus, device->target,
6812                                         device->lun,
6813                                         scsi_device_type(device->devtype));
6814
6815                 if (device->devtype == TYPE_RAID ||
6816                         pqi_is_logical_device(device))
6817                         goto end_buffer;
6818
6819                 memcpy(&phys_connector, &device->phys_connector[i],
6820                         sizeof(phys_connector));
6821                 if (phys_connector[0] < '0')
6822                         phys_connector[0] = '0';
6823                 if (phys_connector[1] < '0')
6824                         phys_connector[1] = '0';
6825
6826                 output_len += scnprintf(buf + output_len,
6827                                         PAGE_SIZE - output_len,
6828                                         "PORT: %.2s ", phys_connector);
6829
6830                 box = device->box[i];
6831                 if (box != 0 && box != 0xFF)
6832                         output_len += scnprintf(buf + output_len,
6833                                                 PAGE_SIZE - output_len,
6834                                                 "BOX: %hhu ", box);
6835
6836                 if ((device->devtype == TYPE_DISK ||
6837                         device->devtype == TYPE_ZBC) &&
6838                         pqi_expose_device(device))
6839                         output_len += scnprintf(buf + output_len,
6840                                                 PAGE_SIZE - output_len,
6841                                                 "BAY: %hhu ", bay);
6842
6843 end_buffer:
6844                 output_len += scnprintf(buf + output_len,
6845                                         PAGE_SIZE - output_len,
6846                                         "%s\n", active);
6847         }
6848
6849         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6850
6851         return output_len;
6852 }
6853
6854 static ssize_t pqi_sas_address_show(struct device *dev,
6855         struct device_attribute *attr, char *buffer)
6856 {
6857         struct pqi_ctrl_info *ctrl_info;
6858         struct scsi_device *sdev;
6859         struct pqi_scsi_dev *device;
6860         unsigned long flags;
6861         u64 sas_address;
6862
6863         sdev = to_scsi_device(dev);
6864         ctrl_info = shost_to_hba(sdev->host);
6865
6866         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6867
6868         device = sdev->hostdata;
6869         if (!device || !pqi_is_device_with_sas_address(device)) {
6870                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6871                 return -ENODEV;
6872         }
6873
6874         sas_address = device->sas_address;
6875
6876         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6877
6878         return snprintf(buffer, PAGE_SIZE, "0x%016llx\n", sas_address);
6879 }
6880
6881 static ssize_t pqi_ssd_smart_path_enabled_show(struct device *dev,
6882         struct device_attribute *attr, char *buffer)
6883 {
6884         struct pqi_ctrl_info *ctrl_info;
6885         struct scsi_device *sdev;
6886         struct pqi_scsi_dev *device;
6887         unsigned long flags;
6888
6889         sdev = to_scsi_device(dev);
6890         ctrl_info = shost_to_hba(sdev->host);
6891
6892         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6893
6894         device = sdev->hostdata;
6895         if (!device) {
6896                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6897                 return -ENODEV;
6898         }
6899
6900         buffer[0] = device->raid_bypass_enabled ? '1' : '0';
6901         buffer[1] = '\n';
6902         buffer[2] = '\0';
6903
6904         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6905
6906         return 2;
6907 }
6908
6909 static ssize_t pqi_raid_level_show(struct device *dev,
6910         struct device_attribute *attr, char *buffer)
6911 {
6912         struct pqi_ctrl_info *ctrl_info;
6913         struct scsi_device *sdev;
6914         struct pqi_scsi_dev *device;
6915         unsigned long flags;
6916         char *raid_level;
6917
6918         sdev = to_scsi_device(dev);
6919         ctrl_info = shost_to_hba(sdev->host);
6920
6921         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6922
6923         device = sdev->hostdata;
6924         if (!device) {
6925                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6926                 return -ENODEV;
6927         }
6928
6929         if (pqi_is_logical_device(device))
6930                 raid_level = pqi_raid_level_to_string(device->raid_level);
6931         else
6932                 raid_level = "N/A";
6933
6934         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6935
6936         return snprintf(buffer, PAGE_SIZE, "%s\n", raid_level);
6937 }
6938
6939 static ssize_t pqi_raid_bypass_cnt_show(struct device *dev,
6940         struct device_attribute *attr, char *buffer)
6941 {
6942         struct pqi_ctrl_info *ctrl_info;
6943         struct scsi_device *sdev;
6944         struct pqi_scsi_dev *device;
6945         unsigned long flags;
6946         int raid_bypass_cnt;
6947
6948         sdev = to_scsi_device(dev);
6949         ctrl_info = shost_to_hba(sdev->host);
6950
6951         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6952
6953         device = sdev->hostdata;
6954         if (!device) {
6955                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6956                 return -ENODEV;
6957         }
6958
6959         raid_bypass_cnt = atomic_read(&device->raid_bypass_cnt);
6960
6961         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6962
6963         return snprintf(buffer, PAGE_SIZE, "0x%x\n", raid_bypass_cnt);
6964 }
6965
6966 static DEVICE_ATTR(lunid, 0444, pqi_lunid_show, NULL);
6967 static DEVICE_ATTR(unique_id, 0444, pqi_unique_id_show, NULL);
6968 static DEVICE_ATTR(path_info, 0444, pqi_path_info_show, NULL);
6969 static DEVICE_ATTR(sas_address, 0444, pqi_sas_address_show, NULL);
6970 static DEVICE_ATTR(ssd_smart_path_enabled, 0444, pqi_ssd_smart_path_enabled_show, NULL);
6971 static DEVICE_ATTR(raid_level, 0444, pqi_raid_level_show, NULL);
6972 static DEVICE_ATTR(raid_bypass_cnt, 0444, pqi_raid_bypass_cnt_show, NULL);
6973
6974 static struct device_attribute *pqi_sdev_attrs[] = {
6975         &dev_attr_lunid,
6976         &dev_attr_unique_id,
6977         &dev_attr_path_info,
6978         &dev_attr_sas_address,
6979         &dev_attr_ssd_smart_path_enabled,
6980         &dev_attr_raid_level,
6981         &dev_attr_raid_bypass_cnt,
6982         NULL
6983 };
6984
6985 static struct scsi_host_template pqi_driver_template = {
6986         .module = THIS_MODULE,
6987         .name = DRIVER_NAME_SHORT,
6988         .proc_name = DRIVER_NAME_SHORT,
6989         .queuecommand = pqi_scsi_queue_command,
6990         .scan_start = pqi_scan_start,
6991         .scan_finished = pqi_scan_finished,
6992         .this_id = -1,
6993         .eh_device_reset_handler = pqi_eh_device_reset_handler,
6994         .ioctl = pqi_ioctl,
6995         .slave_alloc = pqi_slave_alloc,
6996         .slave_configure = pqi_slave_configure,
6997         .slave_destroy = pqi_slave_destroy,
6998         .map_queues = pqi_map_queues,
6999         .sdev_attrs = pqi_sdev_attrs,
7000         .shost_attrs = pqi_shost_attrs,
7001 };
7002
7003 static int pqi_register_scsi(struct pqi_ctrl_info *ctrl_info)
7004 {
7005         int rc;
7006         struct Scsi_Host *shost;
7007
7008         shost = scsi_host_alloc(&pqi_driver_template, sizeof(ctrl_info));
7009         if (!shost) {
7010                 dev_err(&ctrl_info->pci_dev->dev, "scsi_host_alloc failed\n");
7011                 return -ENOMEM;
7012         }
7013
7014         shost->io_port = 0;
7015         shost->n_io_port = 0;
7016         shost->this_id = -1;
7017         shost->max_channel = PQI_MAX_BUS;
7018         shost->max_cmd_len = MAX_COMMAND_SIZE;
7019         shost->max_lun = ~0;
7020         shost->max_id = ~0;
7021         shost->max_sectors = ctrl_info->max_sectors;
7022         shost->can_queue = ctrl_info->scsi_ml_can_queue;
7023         shost->cmd_per_lun = shost->can_queue;
7024         shost->sg_tablesize = ctrl_info->sg_tablesize;
7025         shost->transportt = pqi_sas_transport_template;
7026         shost->irq = pci_irq_vector(ctrl_info->pci_dev, 0);
7027         shost->unique_id = shost->irq;
7028         shost->nr_hw_queues = ctrl_info->num_queue_groups;
7029         shost->host_tagset = 1;
7030         shost->hostdata[0] = (unsigned long)ctrl_info;
7031
7032         rc = scsi_add_host(shost, &ctrl_info->pci_dev->dev);
7033         if (rc) {
7034                 dev_err(&ctrl_info->pci_dev->dev, "scsi_add_host failed\n");
7035                 goto free_host;
7036         }
7037
7038         rc = pqi_add_sas_host(shost, ctrl_info);
7039         if (rc) {
7040                 dev_err(&ctrl_info->pci_dev->dev, "add SAS host failed\n");
7041                 goto remove_host;
7042         }
7043
7044         ctrl_info->scsi_host = shost;
7045
7046         return 0;
7047
7048 remove_host:
7049         scsi_remove_host(shost);
7050 free_host:
7051         scsi_host_put(shost);
7052
7053         return rc;
7054 }
7055
7056 static void pqi_unregister_scsi(struct pqi_ctrl_info *ctrl_info)
7057 {
7058         struct Scsi_Host *shost;
7059
7060         pqi_delete_sas_host(ctrl_info);
7061
7062         shost = ctrl_info->scsi_host;
7063         if (!shost)
7064                 return;
7065
7066         scsi_remove_host(shost);
7067         scsi_host_put(shost);
7068 }
7069
7070 static int pqi_wait_for_pqi_reset_completion(struct pqi_ctrl_info *ctrl_info)
7071 {
7072         int rc = 0;
7073         struct pqi_device_registers __iomem *pqi_registers;
7074         unsigned long timeout;
7075         unsigned int timeout_msecs;
7076         union pqi_reset_register reset_reg;
7077
7078         pqi_registers = ctrl_info->pqi_registers;
7079         timeout_msecs = readw(&pqi_registers->max_reset_timeout) * 100;
7080         timeout = msecs_to_jiffies(timeout_msecs) + jiffies;
7081
7082         while (1) {
7083                 msleep(PQI_RESET_POLL_INTERVAL_MSECS);
7084                 reset_reg.all_bits = readl(&pqi_registers->device_reset);
7085                 if (reset_reg.bits.reset_action == PQI_RESET_ACTION_COMPLETED)
7086                         break;
7087                 pqi_check_ctrl_health(ctrl_info);
7088                 if (pqi_ctrl_offline(ctrl_info)) {
7089                         rc = -ENXIO;
7090                         break;
7091                 }
7092                 if (time_after(jiffies, timeout)) {
7093                         rc = -ETIMEDOUT;
7094                         break;
7095                 }
7096         }
7097
7098         return rc;
7099 }
7100
7101 static int pqi_reset(struct pqi_ctrl_info *ctrl_info)
7102 {
7103         int rc;
7104         union pqi_reset_register reset_reg;
7105
7106         if (ctrl_info->pqi_reset_quiesce_supported) {
7107                 rc = sis_pqi_reset_quiesce(ctrl_info);
7108                 if (rc) {
7109                         dev_err(&ctrl_info->pci_dev->dev,
7110                                 "PQI reset failed during quiesce with error %d\n", rc);
7111                         return rc;
7112                 }
7113         }
7114
7115         reset_reg.all_bits = 0;
7116         reset_reg.bits.reset_type = PQI_RESET_TYPE_HARD_RESET;
7117         reset_reg.bits.reset_action = PQI_RESET_ACTION_RESET;
7118
7119         writel(reset_reg.all_bits, &ctrl_info->pqi_registers->device_reset);
7120
7121         rc = pqi_wait_for_pqi_reset_completion(ctrl_info);
7122         if (rc)
7123                 dev_err(&ctrl_info->pci_dev->dev,
7124                         "PQI reset failed with error %d\n", rc);
7125
7126         return rc;
7127 }
7128
7129 static int pqi_get_ctrl_serial_number(struct pqi_ctrl_info *ctrl_info)
7130 {
7131         int rc;
7132         struct bmic_sense_subsystem_info *sense_info;
7133
7134         sense_info = kzalloc(sizeof(*sense_info), GFP_KERNEL);
7135         if (!sense_info)
7136                 return -ENOMEM;
7137
7138         rc = pqi_sense_subsystem_info(ctrl_info, sense_info);
7139         if (rc)
7140                 goto out;
7141
7142         memcpy(ctrl_info->serial_number, sense_info->ctrl_serial_number,
7143                 sizeof(sense_info->ctrl_serial_number));
7144         ctrl_info->serial_number[sizeof(sense_info->ctrl_serial_number)] = '\0';
7145
7146 out:
7147         kfree(sense_info);
7148
7149         return rc;
7150 }
7151
7152 static int pqi_get_ctrl_product_details(struct pqi_ctrl_info *ctrl_info)
7153 {
7154         int rc;
7155         struct bmic_identify_controller *identify;
7156
7157         identify = kmalloc(sizeof(*identify), GFP_KERNEL);
7158         if (!identify)
7159                 return -ENOMEM;
7160
7161         rc = pqi_identify_controller(ctrl_info, identify);
7162         if (rc)
7163                 goto out;
7164
7165         if (get_unaligned_le32(&identify->extra_controller_flags) &
7166                 BMIC_IDENTIFY_EXTRA_FLAGS_LONG_FW_VERSION_SUPPORTED) {
7167                 memcpy(ctrl_info->firmware_version,
7168                         identify->firmware_version_long,
7169                         sizeof(identify->firmware_version_long));
7170         } else {
7171                 memcpy(ctrl_info->firmware_version,
7172                         identify->firmware_version_short,
7173                         sizeof(identify->firmware_version_short));
7174                 ctrl_info->firmware_version
7175                         [sizeof(identify->firmware_version_short)] = '\0';
7176                 snprintf(ctrl_info->firmware_version +
7177                         strlen(ctrl_info->firmware_version),
7178                         sizeof(ctrl_info->firmware_version) -
7179                         sizeof(identify->firmware_version_short),
7180                         "-%u",
7181                         get_unaligned_le16(&identify->firmware_build_number));
7182         }
7183
7184         memcpy(ctrl_info->model, identify->product_id,
7185                 sizeof(identify->product_id));
7186         ctrl_info->model[sizeof(identify->product_id)] = '\0';
7187
7188         memcpy(ctrl_info->vendor, identify->vendor_id,
7189                 sizeof(identify->vendor_id));
7190         ctrl_info->vendor[sizeof(identify->vendor_id)] = '\0';
7191
7192 out:
7193         kfree(identify);
7194
7195         return rc;
7196 }
7197
7198 struct pqi_config_table_section_info {
7199         struct pqi_ctrl_info *ctrl_info;
7200         void            *section;
7201         u32             section_offset;
7202         void __iomem    *section_iomem_addr;
7203 };
7204
7205 static inline bool pqi_is_firmware_feature_supported(
7206         struct pqi_config_table_firmware_features *firmware_features,
7207         unsigned int bit_position)
7208 {
7209         unsigned int byte_index;
7210
7211         byte_index = bit_position / BITS_PER_BYTE;
7212
7213         if (byte_index >= le16_to_cpu(firmware_features->num_elements))
7214                 return false;
7215
7216         return firmware_features->features_supported[byte_index] &
7217                 (1 << (bit_position % BITS_PER_BYTE)) ? true : false;
7218 }
7219
7220 static inline bool pqi_is_firmware_feature_enabled(
7221         struct pqi_config_table_firmware_features *firmware_features,
7222         void __iomem *firmware_features_iomem_addr,
7223         unsigned int bit_position)
7224 {
7225         unsigned int byte_index;
7226         u8 __iomem *features_enabled_iomem_addr;
7227
7228         byte_index = (bit_position / BITS_PER_BYTE) +
7229                 (le16_to_cpu(firmware_features->num_elements) * 2);
7230
7231         features_enabled_iomem_addr = firmware_features_iomem_addr +
7232                 offsetof(struct pqi_config_table_firmware_features,
7233                         features_supported) + byte_index;
7234
7235         return *((__force u8 *)features_enabled_iomem_addr) &
7236                 (1 << (bit_position % BITS_PER_BYTE)) ? true : false;
7237 }
7238
7239 static inline void pqi_request_firmware_feature(
7240         struct pqi_config_table_firmware_features *firmware_features,
7241         unsigned int bit_position)
7242 {
7243         unsigned int byte_index;
7244
7245         byte_index = (bit_position / BITS_PER_BYTE) +
7246                 le16_to_cpu(firmware_features->num_elements);
7247
7248         firmware_features->features_supported[byte_index] |=
7249                 (1 << (bit_position % BITS_PER_BYTE));
7250 }
7251
7252 static int pqi_config_table_update(struct pqi_ctrl_info *ctrl_info,
7253         u16 first_section, u16 last_section)
7254 {
7255         struct pqi_vendor_general_request request;
7256
7257         memset(&request, 0, sizeof(request));
7258
7259         request.header.iu_type = PQI_REQUEST_IU_VENDOR_GENERAL;
7260         put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
7261                 &request.header.iu_length);
7262         put_unaligned_le16(PQI_VENDOR_GENERAL_CONFIG_TABLE_UPDATE,
7263                 &request.function_code);
7264         put_unaligned_le16(first_section,
7265                 &request.data.config_table_update.first_section);
7266         put_unaligned_le16(last_section,
7267                 &request.data.config_table_update.last_section);
7268
7269         return pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
7270                 0, NULL, NO_TIMEOUT);
7271 }
7272
7273 static int pqi_enable_firmware_features(struct pqi_ctrl_info *ctrl_info,
7274         struct pqi_config_table_firmware_features *firmware_features,
7275         void __iomem *firmware_features_iomem_addr)
7276 {
7277         void *features_requested;
7278         void __iomem *features_requested_iomem_addr;
7279         void __iomem *host_max_known_feature_iomem_addr;
7280
7281         features_requested = firmware_features->features_supported +
7282                 le16_to_cpu(firmware_features->num_elements);
7283
7284         features_requested_iomem_addr = firmware_features_iomem_addr +
7285                 (features_requested - (void *)firmware_features);
7286
7287         memcpy_toio(features_requested_iomem_addr, features_requested,
7288                 le16_to_cpu(firmware_features->num_elements));
7289
7290         if (pqi_is_firmware_feature_supported(firmware_features,
7291                 PQI_FIRMWARE_FEATURE_MAX_KNOWN_FEATURE)) {
7292                 host_max_known_feature_iomem_addr =
7293                         features_requested_iomem_addr +
7294                         (le16_to_cpu(firmware_features->num_elements) * 2) +
7295                         sizeof(__le16);
7296                 writew(PQI_FIRMWARE_FEATURE_MAXIMUM,
7297                         host_max_known_feature_iomem_addr);
7298         }
7299
7300         return pqi_config_table_update(ctrl_info,
7301                 PQI_CONFIG_TABLE_SECTION_FIRMWARE_FEATURES,
7302                 PQI_CONFIG_TABLE_SECTION_FIRMWARE_FEATURES);
7303 }
7304
7305 struct pqi_firmware_feature {
7306         char            *feature_name;
7307         unsigned int    feature_bit;
7308         bool            supported;
7309         bool            enabled;
7310         void (*feature_status)(struct pqi_ctrl_info *ctrl_info,
7311                 struct pqi_firmware_feature *firmware_feature);
7312 };
7313
7314 static void pqi_firmware_feature_status(struct pqi_ctrl_info *ctrl_info,
7315         struct pqi_firmware_feature *firmware_feature)
7316 {
7317         if (!firmware_feature->supported) {
7318                 dev_info(&ctrl_info->pci_dev->dev, "%s not supported by controller\n",
7319                         firmware_feature->feature_name);
7320                 return;
7321         }
7322
7323         if (firmware_feature->enabled) {
7324                 dev_info(&ctrl_info->pci_dev->dev,
7325                         "%s enabled\n", firmware_feature->feature_name);
7326                 return;
7327         }
7328
7329         dev_err(&ctrl_info->pci_dev->dev, "failed to enable %s\n",
7330                 firmware_feature->feature_name);
7331 }
7332
7333 static void pqi_ctrl_update_feature_flags(struct pqi_ctrl_info *ctrl_info,
7334         struct pqi_firmware_feature *firmware_feature)
7335 {
7336         switch (firmware_feature->feature_bit) {
7337         case PQI_FIRMWARE_FEATURE_RAID_1_WRITE_BYPASS:
7338                 ctrl_info->enable_r1_writes = firmware_feature->enabled;
7339                 break;
7340         case PQI_FIRMWARE_FEATURE_RAID_5_WRITE_BYPASS:
7341                 ctrl_info->enable_r5_writes = firmware_feature->enabled;
7342                 break;
7343         case PQI_FIRMWARE_FEATURE_RAID_6_WRITE_BYPASS:
7344                 ctrl_info->enable_r6_writes = firmware_feature->enabled;
7345                 break;
7346         case PQI_FIRMWARE_FEATURE_SOFT_RESET_HANDSHAKE:
7347                 ctrl_info->soft_reset_handshake_supported =
7348                         firmware_feature->enabled;
7349                 break;
7350         case PQI_FIRMWARE_FEATURE_RAID_IU_TIMEOUT:
7351                 ctrl_info->raid_iu_timeout_supported = firmware_feature->enabled;
7352                 break;
7353         case PQI_FIRMWARE_FEATURE_TMF_IU_TIMEOUT:
7354                 ctrl_info->tmf_iu_timeout_supported = firmware_feature->enabled;
7355                 break;
7356         }
7357
7358         pqi_firmware_feature_status(ctrl_info, firmware_feature);
7359 }
7360
7361 static inline void pqi_firmware_feature_update(struct pqi_ctrl_info *ctrl_info,
7362         struct pqi_firmware_feature *firmware_feature)
7363 {
7364         if (firmware_feature->feature_status)
7365                 firmware_feature->feature_status(ctrl_info, firmware_feature);
7366 }
7367
7368 static DEFINE_MUTEX(pqi_firmware_features_mutex);
7369
7370 static struct pqi_firmware_feature pqi_firmware_features[] = {
7371         {
7372                 .feature_name = "Online Firmware Activation",
7373                 .feature_bit = PQI_FIRMWARE_FEATURE_OFA,
7374                 .feature_status = pqi_firmware_feature_status,
7375         },
7376         {
7377                 .feature_name = "Serial Management Protocol",
7378                 .feature_bit = PQI_FIRMWARE_FEATURE_SMP,
7379                 .feature_status = pqi_firmware_feature_status,
7380         },
7381         {
7382                 .feature_name = "Maximum Known Feature",
7383                 .feature_bit = PQI_FIRMWARE_FEATURE_MAX_KNOWN_FEATURE,
7384                 .feature_status = pqi_firmware_feature_status,
7385         },
7386         {
7387                 .feature_name = "RAID 0 Read Bypass",
7388                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_0_READ_BYPASS,
7389                 .feature_status = pqi_firmware_feature_status,
7390         },
7391         {
7392                 .feature_name = "RAID 1 Read Bypass",
7393                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_1_READ_BYPASS,
7394                 .feature_status = pqi_firmware_feature_status,
7395         },
7396         {
7397                 .feature_name = "RAID 5 Read Bypass",
7398                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_5_READ_BYPASS,
7399                 .feature_status = pqi_firmware_feature_status,
7400         },
7401         {
7402                 .feature_name = "RAID 6 Read Bypass",
7403                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_6_READ_BYPASS,
7404                 .feature_status = pqi_firmware_feature_status,
7405         },
7406         {
7407                 .feature_name = "RAID 0 Write Bypass",
7408                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_0_WRITE_BYPASS,
7409                 .feature_status = pqi_firmware_feature_status,
7410         },
7411         {
7412                 .feature_name = "RAID 1 Write Bypass",
7413                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_1_WRITE_BYPASS,
7414                 .feature_status = pqi_ctrl_update_feature_flags,
7415         },
7416         {
7417                 .feature_name = "RAID 5 Write Bypass",
7418                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_5_WRITE_BYPASS,
7419                 .feature_status = pqi_ctrl_update_feature_flags,
7420         },
7421         {
7422                 .feature_name = "RAID 6 Write Bypass",
7423                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_6_WRITE_BYPASS,
7424                 .feature_status = pqi_ctrl_update_feature_flags,
7425         },
7426         {
7427                 .feature_name = "New Soft Reset Handshake",
7428                 .feature_bit = PQI_FIRMWARE_FEATURE_SOFT_RESET_HANDSHAKE,
7429                 .feature_status = pqi_ctrl_update_feature_flags,
7430         },
7431         {
7432                 .feature_name = "RAID IU Timeout",
7433                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_IU_TIMEOUT,
7434                 .feature_status = pqi_ctrl_update_feature_flags,
7435         },
7436         {
7437                 .feature_name = "TMF IU Timeout",
7438                 .feature_bit = PQI_FIRMWARE_FEATURE_TMF_IU_TIMEOUT,
7439                 .feature_status = pqi_ctrl_update_feature_flags,
7440         },
7441         {
7442                 .feature_name = "RAID Bypass on encrypted logical volumes on NVMe",
7443                 .feature_bit = PQI_FIRMWARE_FEATURE_RAID_BYPASS_ON_ENCRYPTED_NVME,
7444                 .feature_status = pqi_firmware_feature_status,
7445         },
7446 };
7447
7448 static void pqi_process_firmware_features(
7449         struct pqi_config_table_section_info *section_info)
7450 {
7451         int rc;
7452         struct pqi_ctrl_info *ctrl_info;
7453         struct pqi_config_table_firmware_features *firmware_features;
7454         void __iomem *firmware_features_iomem_addr;
7455         unsigned int i;
7456         unsigned int num_features_supported;
7457
7458         ctrl_info = section_info->ctrl_info;
7459         firmware_features = section_info->section;
7460         firmware_features_iomem_addr = section_info->section_iomem_addr;
7461
7462         for (i = 0, num_features_supported = 0;
7463                 i < ARRAY_SIZE(pqi_firmware_features); i++) {
7464                 if (pqi_is_firmware_feature_supported(firmware_features,
7465                         pqi_firmware_features[i].feature_bit)) {
7466                         pqi_firmware_features[i].supported = true;
7467                         num_features_supported++;
7468                 } else {
7469                         pqi_firmware_feature_update(ctrl_info,
7470                                 &pqi_firmware_features[i]);
7471                 }
7472         }
7473
7474         if (num_features_supported == 0)
7475                 return;
7476
7477         for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7478                 if (!pqi_firmware_features[i].supported)
7479                         continue;
7480                 pqi_request_firmware_feature(firmware_features,
7481                         pqi_firmware_features[i].feature_bit);
7482         }
7483
7484         rc = pqi_enable_firmware_features(ctrl_info, firmware_features,
7485                 firmware_features_iomem_addr);
7486         if (rc) {
7487                 dev_err(&ctrl_info->pci_dev->dev,
7488                         "failed to enable firmware features in PQI configuration table\n");
7489                 for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7490                         if (!pqi_firmware_features[i].supported)
7491                                 continue;
7492                         pqi_firmware_feature_update(ctrl_info,
7493                                 &pqi_firmware_features[i]);
7494                 }
7495                 return;
7496         }
7497
7498         for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7499                 if (!pqi_firmware_features[i].supported)
7500                         continue;
7501                 if (pqi_is_firmware_feature_enabled(firmware_features,
7502                         firmware_features_iomem_addr,
7503                         pqi_firmware_features[i].feature_bit)) {
7504                                 pqi_firmware_features[i].enabled = true;
7505                 }
7506                 pqi_firmware_feature_update(ctrl_info,
7507                         &pqi_firmware_features[i]);
7508         }
7509 }
7510
7511 static void pqi_init_firmware_features(void)
7512 {
7513         unsigned int i;
7514
7515         for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7516                 pqi_firmware_features[i].supported = false;
7517                 pqi_firmware_features[i].enabled = false;
7518         }
7519 }
7520
7521 static void pqi_process_firmware_features_section(
7522         struct pqi_config_table_section_info *section_info)
7523 {
7524         mutex_lock(&pqi_firmware_features_mutex);
7525         pqi_init_firmware_features();
7526         pqi_process_firmware_features(section_info);
7527         mutex_unlock(&pqi_firmware_features_mutex);
7528 }
7529
7530 /*
7531  * Reset all controller settings that can be initialized during the processing
7532  * of the PQI Configuration Table.
7533  */
7534
7535 static int pqi_process_config_table(struct pqi_ctrl_info *ctrl_info)
7536 {
7537         u32 table_length;
7538         u32 section_offset;
7539         bool firmware_feature_section_present;
7540         void __iomem *table_iomem_addr;
7541         struct pqi_config_table *config_table;
7542         struct pqi_config_table_section_header *section;
7543         struct pqi_config_table_section_info section_info;
7544         struct pqi_config_table_section_info feature_section_info;
7545
7546         table_length = ctrl_info->config_table_length;
7547         if (table_length == 0)
7548                 return 0;
7549
7550         config_table = kmalloc(table_length, GFP_KERNEL);
7551         if (!config_table) {
7552                 dev_err(&ctrl_info->pci_dev->dev,
7553                         "failed to allocate memory for PQI configuration table\n");
7554                 return -ENOMEM;
7555         }
7556
7557         /*
7558          * Copy the config table contents from I/O memory space into the
7559          * temporary buffer.
7560          */
7561         table_iomem_addr = ctrl_info->iomem_base + ctrl_info->config_table_offset;
7562         memcpy_fromio(config_table, table_iomem_addr, table_length);
7563
7564         firmware_feature_section_present = false;
7565         section_info.ctrl_info = ctrl_info;
7566         section_offset = get_unaligned_le32(&config_table->first_section_offset);
7567
7568         while (section_offset) {
7569                 section = (void *)config_table + section_offset;
7570
7571                 section_info.section = section;
7572                 section_info.section_offset = section_offset;
7573                 section_info.section_iomem_addr = table_iomem_addr + section_offset;
7574
7575                 switch (get_unaligned_le16(&section->section_id)) {
7576                 case PQI_CONFIG_TABLE_SECTION_FIRMWARE_FEATURES:
7577                         firmware_feature_section_present = true;
7578                         feature_section_info = section_info;
7579                         break;
7580                 case PQI_CONFIG_TABLE_SECTION_HEARTBEAT:
7581                         if (pqi_disable_heartbeat)
7582                                 dev_warn(&ctrl_info->pci_dev->dev,
7583                                 "heartbeat disabled by module parameter\n");
7584                         else
7585                                 ctrl_info->heartbeat_counter =
7586                                         table_iomem_addr +
7587                                         section_offset +
7588                                         offsetof(struct pqi_config_table_heartbeat,
7589                                                 heartbeat_counter);
7590                         break;
7591                 case PQI_CONFIG_TABLE_SECTION_SOFT_RESET:
7592                         ctrl_info->soft_reset_status =
7593                                 table_iomem_addr +
7594                                 section_offset +
7595                                 offsetof(struct pqi_config_table_soft_reset,
7596                                         soft_reset_status);
7597                         break;
7598                 }
7599
7600                 section_offset = get_unaligned_le16(&section->next_section_offset);
7601         }
7602
7603         /*
7604          * We process the firmware feature section after all other sections
7605          * have been processed so that the feature bit callbacks can take
7606          * into account the settings configured by other sections.
7607          */
7608         if (firmware_feature_section_present)
7609                 pqi_process_firmware_features_section(&feature_section_info);
7610
7611         kfree(config_table);
7612
7613         return 0;
7614 }
7615
7616 /* Switches the controller from PQI mode back into SIS mode. */
7617
7618 static int pqi_revert_to_sis_mode(struct pqi_ctrl_info *ctrl_info)
7619 {
7620         int rc;
7621
7622         pqi_change_irq_mode(ctrl_info, IRQ_MODE_NONE);
7623         rc = pqi_reset(ctrl_info);
7624         if (rc)
7625                 return rc;
7626         rc = sis_reenable_sis_mode(ctrl_info);
7627         if (rc) {
7628                 dev_err(&ctrl_info->pci_dev->dev,
7629                         "re-enabling SIS mode failed with error %d\n", rc);
7630                 return rc;
7631         }
7632         pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
7633
7634         return 0;
7635 }
7636
7637 /*
7638  * If the controller isn't already in SIS mode, this function forces it into
7639  * SIS mode.
7640  */
7641
7642 static int pqi_force_sis_mode(struct pqi_ctrl_info *ctrl_info)
7643 {
7644         if (!sis_is_firmware_running(ctrl_info))
7645                 return -ENXIO;
7646
7647         if (pqi_get_ctrl_mode(ctrl_info) == SIS_MODE)
7648                 return 0;
7649
7650         if (sis_is_kernel_up(ctrl_info)) {
7651                 pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
7652                 return 0;
7653         }
7654
7655         return pqi_revert_to_sis_mode(ctrl_info);
7656 }
7657
7658 #define PQI_POST_RESET_DELAY_B4_MSGU_READY      5000
7659
7660 static int pqi_ctrl_init(struct pqi_ctrl_info *ctrl_info)
7661 {
7662         int rc;
7663         u32 product_id;
7664
7665         if (reset_devices) {
7666                 sis_soft_reset(ctrl_info);
7667                 msleep(PQI_POST_RESET_DELAY_B4_MSGU_READY);
7668         } else {
7669                 rc = pqi_force_sis_mode(ctrl_info);
7670                 if (rc)
7671                         return rc;
7672         }
7673
7674         /*
7675          * Wait until the controller is ready to start accepting SIS
7676          * commands.
7677          */
7678         rc = sis_wait_for_ctrl_ready(ctrl_info);
7679         if (rc)
7680                 return rc;
7681
7682         /*
7683          * Get the controller properties.  This allows us to determine
7684          * whether or not it supports PQI mode.
7685          */
7686         rc = sis_get_ctrl_properties(ctrl_info);
7687         if (rc) {
7688                 dev_err(&ctrl_info->pci_dev->dev,
7689                         "error obtaining controller properties\n");
7690                 return rc;
7691         }
7692
7693         rc = sis_get_pqi_capabilities(ctrl_info);
7694         if (rc) {
7695                 dev_err(&ctrl_info->pci_dev->dev,
7696                         "error obtaining controller capabilities\n");
7697                 return rc;
7698         }
7699
7700         product_id = sis_get_product_id(ctrl_info);
7701         ctrl_info->product_id = (u8)product_id;
7702         ctrl_info->product_revision = (u8)(product_id >> 8);
7703
7704         if (reset_devices) {
7705                 if (ctrl_info->max_outstanding_requests >
7706                         PQI_MAX_OUTSTANDING_REQUESTS_KDUMP)
7707                                 ctrl_info->max_outstanding_requests =
7708                                         PQI_MAX_OUTSTANDING_REQUESTS_KDUMP;
7709         } else {
7710                 if (ctrl_info->max_outstanding_requests >
7711                         PQI_MAX_OUTSTANDING_REQUESTS)
7712                                 ctrl_info->max_outstanding_requests =
7713                                         PQI_MAX_OUTSTANDING_REQUESTS;
7714         }
7715
7716         pqi_calculate_io_resources(ctrl_info);
7717
7718         rc = pqi_alloc_error_buffer(ctrl_info);
7719         if (rc) {
7720                 dev_err(&ctrl_info->pci_dev->dev,
7721                         "failed to allocate PQI error buffer\n");
7722                 return rc;
7723         }
7724
7725         /*
7726          * If the function we are about to call succeeds, the
7727          * controller will transition from legacy SIS mode
7728          * into PQI mode.
7729          */
7730         rc = sis_init_base_struct_addr(ctrl_info);
7731         if (rc) {
7732                 dev_err(&ctrl_info->pci_dev->dev,
7733                         "error initializing PQI mode\n");
7734                 return rc;
7735         }
7736
7737         /* Wait for the controller to complete the SIS -> PQI transition. */
7738         rc = pqi_wait_for_pqi_mode_ready(ctrl_info);
7739         if (rc) {
7740                 dev_err(&ctrl_info->pci_dev->dev,
7741                         "transition to PQI mode failed\n");
7742                 return rc;
7743         }
7744
7745         /* From here on, we are running in PQI mode. */
7746         ctrl_info->pqi_mode_enabled = true;
7747         pqi_save_ctrl_mode(ctrl_info, PQI_MODE);
7748
7749         rc = pqi_alloc_admin_queues(ctrl_info);
7750         if (rc) {
7751                 dev_err(&ctrl_info->pci_dev->dev,
7752                         "failed to allocate admin queues\n");
7753                 return rc;
7754         }
7755
7756         rc = pqi_create_admin_queues(ctrl_info);
7757         if (rc) {
7758                 dev_err(&ctrl_info->pci_dev->dev,
7759                         "error creating admin queues\n");
7760                 return rc;
7761         }
7762
7763         rc = pqi_report_device_capability(ctrl_info);
7764         if (rc) {
7765                 dev_err(&ctrl_info->pci_dev->dev,
7766                         "obtaining device capability failed\n");
7767                 return rc;
7768         }
7769
7770         rc = pqi_validate_device_capability(ctrl_info);
7771         if (rc)
7772                 return rc;
7773
7774         pqi_calculate_queue_resources(ctrl_info);
7775
7776         rc = pqi_enable_msix_interrupts(ctrl_info);
7777         if (rc)
7778                 return rc;
7779
7780         if (ctrl_info->num_msix_vectors_enabled < ctrl_info->num_queue_groups) {
7781                 ctrl_info->max_msix_vectors =
7782                         ctrl_info->num_msix_vectors_enabled;
7783                 pqi_calculate_queue_resources(ctrl_info);
7784         }
7785
7786         rc = pqi_alloc_io_resources(ctrl_info);
7787         if (rc)
7788                 return rc;
7789
7790         rc = pqi_alloc_operational_queues(ctrl_info);
7791         if (rc) {
7792                 dev_err(&ctrl_info->pci_dev->dev,
7793                         "failed to allocate operational queues\n");
7794                 return rc;
7795         }
7796
7797         pqi_init_operational_queues(ctrl_info);
7798
7799         rc = pqi_request_irqs(ctrl_info);
7800         if (rc)
7801                 return rc;
7802
7803         rc = pqi_create_queues(ctrl_info);
7804         if (rc)
7805                 return rc;
7806
7807         pqi_change_irq_mode(ctrl_info, IRQ_MODE_MSIX);
7808
7809         ctrl_info->controller_online = true;
7810
7811         rc = pqi_process_config_table(ctrl_info);
7812         if (rc)
7813                 return rc;
7814
7815         pqi_start_heartbeat_timer(ctrl_info);
7816
7817         if (ctrl_info->enable_r5_writes || ctrl_info->enable_r6_writes) {
7818                 rc = pqi_get_advanced_raid_bypass_config(ctrl_info);
7819                 if (rc) { /* Supported features not returned correctly. */
7820                         dev_err(&ctrl_info->pci_dev->dev,
7821                                 "error obtaining advanced RAID bypass configuration\n");
7822                         return rc;
7823                 }
7824                 ctrl_info->ciss_report_log_flags |=
7825                         CISS_REPORT_LOG_FLAG_DRIVE_TYPE_MIX;
7826         }
7827
7828         rc = pqi_enable_events(ctrl_info);
7829         if (rc) {
7830                 dev_err(&ctrl_info->pci_dev->dev,
7831                         "error enabling events\n");
7832                 return rc;
7833         }
7834
7835         /* Register with the SCSI subsystem. */
7836         rc = pqi_register_scsi(ctrl_info);
7837         if (rc)
7838                 return rc;
7839
7840         rc = pqi_get_ctrl_product_details(ctrl_info);
7841         if (rc) {
7842                 dev_err(&ctrl_info->pci_dev->dev,
7843                         "error obtaining product details\n");
7844                 return rc;
7845         }
7846
7847         rc = pqi_get_ctrl_serial_number(ctrl_info);
7848         if (rc) {
7849                 dev_err(&ctrl_info->pci_dev->dev,
7850                         "error obtaining ctrl serial number\n");
7851                 return rc;
7852         }
7853
7854         rc = pqi_set_diag_rescan(ctrl_info);
7855         if (rc) {
7856                 dev_err(&ctrl_info->pci_dev->dev,
7857                         "error enabling multi-lun rescan\n");
7858                 return rc;
7859         }
7860
7861         rc = pqi_write_driver_version_to_host_wellness(ctrl_info);
7862         if (rc) {
7863                 dev_err(&ctrl_info->pci_dev->dev,
7864                         "error updating host wellness\n");
7865                 return rc;
7866         }
7867
7868         pqi_schedule_update_time_worker(ctrl_info);
7869
7870         pqi_scan_scsi_devices(ctrl_info);
7871
7872         return 0;
7873 }
7874
7875 static void pqi_reinit_queues(struct pqi_ctrl_info *ctrl_info)
7876 {
7877         unsigned int i;
7878         struct pqi_admin_queues *admin_queues;
7879         struct pqi_event_queue *event_queue;
7880
7881         admin_queues = &ctrl_info->admin_queues;
7882         admin_queues->iq_pi_copy = 0;
7883         admin_queues->oq_ci_copy = 0;
7884         writel(0, admin_queues->oq_pi);
7885
7886         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
7887                 ctrl_info->queue_groups[i].iq_pi_copy[RAID_PATH] = 0;
7888                 ctrl_info->queue_groups[i].iq_pi_copy[AIO_PATH] = 0;
7889                 ctrl_info->queue_groups[i].oq_ci_copy = 0;
7890
7891                 writel(0, ctrl_info->queue_groups[i].iq_ci[RAID_PATH]);
7892                 writel(0, ctrl_info->queue_groups[i].iq_ci[AIO_PATH]);
7893                 writel(0, ctrl_info->queue_groups[i].oq_pi);
7894         }
7895
7896         event_queue = &ctrl_info->event_queue;
7897         writel(0, event_queue->oq_pi);
7898         event_queue->oq_ci_copy = 0;
7899 }
7900
7901 static int pqi_ctrl_init_resume(struct pqi_ctrl_info *ctrl_info)
7902 {
7903         int rc;
7904
7905         rc = pqi_force_sis_mode(ctrl_info);
7906         if (rc)
7907                 return rc;
7908
7909         /*
7910          * Wait until the controller is ready to start accepting SIS
7911          * commands.
7912          */
7913         rc = sis_wait_for_ctrl_ready_resume(ctrl_info);
7914         if (rc)
7915                 return rc;
7916
7917         /*
7918          * Get the controller properties.  This allows us to determine
7919          * whether or not it supports PQI mode.
7920          */
7921         rc = sis_get_ctrl_properties(ctrl_info);
7922         if (rc) {
7923                 dev_err(&ctrl_info->pci_dev->dev,
7924                         "error obtaining controller properties\n");
7925                 return rc;
7926         }
7927
7928         rc = sis_get_pqi_capabilities(ctrl_info);
7929         if (rc) {
7930                 dev_err(&ctrl_info->pci_dev->dev,
7931                         "error obtaining controller capabilities\n");
7932                 return rc;
7933         }
7934
7935         /*
7936          * If the function we are about to call succeeds, the
7937          * controller will transition from legacy SIS mode
7938          * into PQI mode.
7939          */
7940         rc = sis_init_base_struct_addr(ctrl_info);
7941         if (rc) {
7942                 dev_err(&ctrl_info->pci_dev->dev,
7943                         "error initializing PQI mode\n");
7944                 return rc;
7945         }
7946
7947         /* Wait for the controller to complete the SIS -> PQI transition. */
7948         rc = pqi_wait_for_pqi_mode_ready(ctrl_info);
7949         if (rc) {
7950                 dev_err(&ctrl_info->pci_dev->dev,
7951                         "transition to PQI mode failed\n");
7952                 return rc;
7953         }
7954
7955         /* From here on, we are running in PQI mode. */
7956         ctrl_info->pqi_mode_enabled = true;
7957         pqi_save_ctrl_mode(ctrl_info, PQI_MODE);
7958
7959         pqi_reinit_queues(ctrl_info);
7960
7961         rc = pqi_create_admin_queues(ctrl_info);
7962         if (rc) {
7963                 dev_err(&ctrl_info->pci_dev->dev,
7964                         "error creating admin queues\n");
7965                 return rc;
7966         }
7967
7968         rc = pqi_create_queues(ctrl_info);
7969         if (rc)
7970                 return rc;
7971
7972         pqi_change_irq_mode(ctrl_info, IRQ_MODE_MSIX);
7973
7974         ctrl_info->controller_online = true;
7975         pqi_ctrl_unblock_requests(ctrl_info);
7976
7977         rc = pqi_process_config_table(ctrl_info);
7978         if (rc)
7979                 return rc;
7980
7981         pqi_start_heartbeat_timer(ctrl_info);
7982
7983         if (ctrl_info->enable_r5_writes || ctrl_info->enable_r6_writes) {
7984                 rc = pqi_get_advanced_raid_bypass_config(ctrl_info);
7985                 if (rc) {
7986                         dev_err(&ctrl_info->pci_dev->dev,
7987                                 "error obtaining advanced RAID bypass configuration\n");
7988                         return rc;
7989                 }
7990                 ctrl_info->ciss_report_log_flags |=
7991                         CISS_REPORT_LOG_FLAG_DRIVE_TYPE_MIX;
7992         }
7993
7994         rc = pqi_enable_events(ctrl_info);
7995         if (rc) {
7996                 dev_err(&ctrl_info->pci_dev->dev,
7997                         "error enabling events\n");
7998                 return rc;
7999         }
8000
8001         rc = pqi_get_ctrl_product_details(ctrl_info);
8002         if (rc) {
8003                 dev_err(&ctrl_info->pci_dev->dev,
8004                         "error obtaining product details\n");
8005                 return rc;
8006         }
8007
8008         rc = pqi_set_diag_rescan(ctrl_info);
8009         if (rc) {
8010                 dev_err(&ctrl_info->pci_dev->dev,
8011                         "error enabling multi-lun rescan\n");
8012                 return rc;
8013         }
8014
8015         rc = pqi_write_driver_version_to_host_wellness(ctrl_info);
8016         if (rc) {
8017                 dev_err(&ctrl_info->pci_dev->dev,
8018                         "error updating host wellness\n");
8019                 return rc;
8020         }
8021
8022         pqi_schedule_update_time_worker(ctrl_info);
8023
8024         pqi_scan_scsi_devices(ctrl_info);
8025
8026         return 0;
8027 }
8028
8029 static inline int pqi_set_pcie_completion_timeout(struct pci_dev *pci_dev, u16 timeout)
8030 {
8031         int rc;
8032
8033         rc = pcie_capability_clear_and_set_word(pci_dev, PCI_EXP_DEVCTL2,
8034                 PCI_EXP_DEVCTL2_COMP_TIMEOUT, timeout);
8035
8036         return pcibios_err_to_errno(rc);
8037 }
8038
8039 static int pqi_pci_init(struct pqi_ctrl_info *ctrl_info)
8040 {
8041         int rc;
8042         u64 mask;
8043
8044         rc = pci_enable_device(ctrl_info->pci_dev);
8045         if (rc) {
8046                 dev_err(&ctrl_info->pci_dev->dev,
8047                         "failed to enable PCI device\n");
8048                 return rc;
8049         }
8050
8051         if (sizeof(dma_addr_t) > 4)
8052                 mask = DMA_BIT_MASK(64);
8053         else
8054                 mask = DMA_BIT_MASK(32);
8055
8056         rc = dma_set_mask_and_coherent(&ctrl_info->pci_dev->dev, mask);
8057         if (rc) {
8058                 dev_err(&ctrl_info->pci_dev->dev, "failed to set DMA mask\n");
8059                 goto disable_device;
8060         }
8061
8062         rc = pci_request_regions(ctrl_info->pci_dev, DRIVER_NAME_SHORT);
8063         if (rc) {
8064                 dev_err(&ctrl_info->pci_dev->dev,
8065                         "failed to obtain PCI resources\n");
8066                 goto disable_device;
8067         }
8068
8069         ctrl_info->iomem_base = ioremap(pci_resource_start(
8070                 ctrl_info->pci_dev, 0),
8071                 sizeof(struct pqi_ctrl_registers));
8072         if (!ctrl_info->iomem_base) {
8073                 dev_err(&ctrl_info->pci_dev->dev,
8074                         "failed to map memory for controller registers\n");
8075                 rc = -ENOMEM;
8076                 goto release_regions;
8077         }
8078
8079 #define PCI_EXP_COMP_TIMEOUT_65_TO_210_MS               0x6
8080
8081         /* Increase the PCIe completion timeout. */
8082         rc = pqi_set_pcie_completion_timeout(ctrl_info->pci_dev,
8083                 PCI_EXP_COMP_TIMEOUT_65_TO_210_MS);
8084         if (rc) {
8085                 dev_err(&ctrl_info->pci_dev->dev,
8086                         "failed to set PCIe completion timeout\n");
8087                 goto release_regions;
8088         }
8089
8090         /* Enable bus mastering. */
8091         pci_set_master(ctrl_info->pci_dev);
8092
8093         ctrl_info->registers = ctrl_info->iomem_base;
8094         ctrl_info->pqi_registers = &ctrl_info->registers->pqi_registers;
8095
8096         pci_set_drvdata(ctrl_info->pci_dev, ctrl_info);
8097
8098         return 0;
8099
8100 release_regions:
8101         pci_release_regions(ctrl_info->pci_dev);
8102 disable_device:
8103         pci_disable_device(ctrl_info->pci_dev);
8104
8105         return rc;
8106 }
8107
8108 static void pqi_cleanup_pci_init(struct pqi_ctrl_info *ctrl_info)
8109 {
8110         iounmap(ctrl_info->iomem_base);
8111         pci_release_regions(ctrl_info->pci_dev);
8112         if (pci_is_enabled(ctrl_info->pci_dev))
8113                 pci_disable_device(ctrl_info->pci_dev);
8114         pci_set_drvdata(ctrl_info->pci_dev, NULL);
8115 }
8116
8117 static struct pqi_ctrl_info *pqi_alloc_ctrl_info(int numa_node)
8118 {
8119         struct pqi_ctrl_info *ctrl_info;
8120
8121         ctrl_info = kzalloc_node(sizeof(struct pqi_ctrl_info),
8122                         GFP_KERNEL, numa_node);
8123         if (!ctrl_info)
8124                 return NULL;
8125
8126         mutex_init(&ctrl_info->scan_mutex);
8127         mutex_init(&ctrl_info->lun_reset_mutex);
8128         mutex_init(&ctrl_info->ofa_mutex);
8129
8130         INIT_LIST_HEAD(&ctrl_info->scsi_device_list);
8131         spin_lock_init(&ctrl_info->scsi_device_list_lock);
8132
8133         INIT_WORK(&ctrl_info->event_work, pqi_event_worker);
8134         atomic_set(&ctrl_info->num_interrupts, 0);
8135         atomic_set(&ctrl_info->sync_cmds_outstanding, 0);
8136
8137         INIT_DELAYED_WORK(&ctrl_info->rescan_work, pqi_rescan_worker);
8138         INIT_DELAYED_WORK(&ctrl_info->update_time_work, pqi_update_time_worker);
8139
8140         timer_setup(&ctrl_info->heartbeat_timer, pqi_heartbeat_timer_handler, 0);
8141         INIT_WORK(&ctrl_info->ctrl_offline_work, pqi_ctrl_offline_worker);
8142
8143         sema_init(&ctrl_info->sync_request_sem,
8144                 PQI_RESERVED_IO_SLOTS_SYNCHRONOUS_REQUESTS);
8145         init_waitqueue_head(&ctrl_info->block_requests_wait);
8146
8147         INIT_LIST_HEAD(&ctrl_info->raid_bypass_retry_list);
8148         spin_lock_init(&ctrl_info->raid_bypass_retry_list_lock);
8149         INIT_WORK(&ctrl_info->raid_bypass_retry_work,
8150                 pqi_raid_bypass_retry_worker);
8151
8152         ctrl_info->ctrl_id = atomic_inc_return(&pqi_controller_count) - 1;
8153         ctrl_info->irq_mode = IRQ_MODE_NONE;
8154         ctrl_info->max_msix_vectors = PQI_MAX_MSIX_VECTORS;
8155
8156         ctrl_info->ciss_report_log_flags = CISS_REPORT_LOG_FLAG_UNIQUE_LUN_ID;
8157         ctrl_info->max_transfer_encrypted_sas_sata =
8158                 PQI_DEFAULT_MAX_TRANSFER_ENCRYPTED_SAS_SATA;
8159         ctrl_info->max_transfer_encrypted_nvme =
8160                 PQI_DEFAULT_MAX_TRANSFER_ENCRYPTED_NVME;
8161         ctrl_info->max_write_raid_5_6 = PQI_DEFAULT_MAX_WRITE_RAID_5_6;
8162         ctrl_info->max_write_raid_1_10_2drive = ~0;
8163         ctrl_info->max_write_raid_1_10_3drive = ~0;
8164
8165         return ctrl_info;
8166 }
8167
8168 static inline void pqi_free_ctrl_info(struct pqi_ctrl_info *ctrl_info)
8169 {
8170         kfree(ctrl_info);
8171 }
8172
8173 static void pqi_free_interrupts(struct pqi_ctrl_info *ctrl_info)
8174 {
8175         pqi_free_irqs(ctrl_info);
8176         pqi_disable_msix_interrupts(ctrl_info);
8177 }
8178
8179 static void pqi_free_ctrl_resources(struct pqi_ctrl_info *ctrl_info)
8180 {
8181         pqi_stop_heartbeat_timer(ctrl_info);
8182         pqi_free_interrupts(ctrl_info);
8183         if (ctrl_info->queue_memory_base)
8184                 dma_free_coherent(&ctrl_info->pci_dev->dev,
8185                         ctrl_info->queue_memory_length,
8186                         ctrl_info->queue_memory_base,
8187                         ctrl_info->queue_memory_base_dma_handle);
8188         if (ctrl_info->admin_queue_memory_base)
8189                 dma_free_coherent(&ctrl_info->pci_dev->dev,
8190                         ctrl_info->admin_queue_memory_length,
8191                         ctrl_info->admin_queue_memory_base,
8192                         ctrl_info->admin_queue_memory_base_dma_handle);
8193         pqi_free_all_io_requests(ctrl_info);
8194         if (ctrl_info->error_buffer)
8195                 dma_free_coherent(&ctrl_info->pci_dev->dev,
8196                         ctrl_info->error_buffer_length,
8197                         ctrl_info->error_buffer,
8198                         ctrl_info->error_buffer_dma_handle);
8199         if (ctrl_info->iomem_base)
8200                 pqi_cleanup_pci_init(ctrl_info);
8201         pqi_free_ctrl_info(ctrl_info);
8202 }
8203
8204 static void pqi_remove_ctrl(struct pqi_ctrl_info *ctrl_info)
8205 {
8206         pqi_cancel_rescan_worker(ctrl_info);
8207         pqi_cancel_update_time_worker(ctrl_info);
8208         pqi_unregister_scsi(ctrl_info);
8209         if (ctrl_info->pqi_mode_enabled)
8210                 pqi_revert_to_sis_mode(ctrl_info);
8211         pqi_free_ctrl_resources(ctrl_info);
8212 }
8213
8214 static void pqi_ofa_ctrl_quiesce(struct pqi_ctrl_info *ctrl_info)
8215 {
8216         pqi_cancel_update_time_worker(ctrl_info);
8217         pqi_cancel_rescan_worker(ctrl_info);
8218         pqi_wait_until_lun_reset_finished(ctrl_info);
8219         pqi_wait_until_scan_finished(ctrl_info);
8220         pqi_ctrl_ofa_start(ctrl_info);
8221         pqi_ctrl_block_requests(ctrl_info);
8222         pqi_ctrl_wait_until_quiesced(ctrl_info);
8223         pqi_ctrl_wait_for_pending_io(ctrl_info, PQI_PENDING_IO_TIMEOUT_SECS);
8224         pqi_fail_io_queued_for_all_devices(ctrl_info);
8225         pqi_wait_until_inbound_queues_empty(ctrl_info);
8226         pqi_stop_heartbeat_timer(ctrl_info);
8227         ctrl_info->pqi_mode_enabled = false;
8228         pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
8229 }
8230
8231 static void pqi_ofa_ctrl_unquiesce(struct pqi_ctrl_info *ctrl_info)
8232 {
8233         pqi_ofa_free_host_buffer(ctrl_info);
8234         ctrl_info->pqi_mode_enabled = true;
8235         pqi_save_ctrl_mode(ctrl_info, PQI_MODE);
8236         ctrl_info->controller_online = true;
8237         pqi_ctrl_unblock_requests(ctrl_info);
8238         pqi_start_heartbeat_timer(ctrl_info);
8239         pqi_schedule_update_time_worker(ctrl_info);
8240         pqi_clear_soft_reset_status(ctrl_info,
8241                 PQI_SOFT_RESET_ABORT);
8242         pqi_scan_scsi_devices(ctrl_info);
8243 }
8244
8245 static int pqi_ofa_alloc_mem(struct pqi_ctrl_info *ctrl_info,
8246         u32 total_size, u32 chunk_size)
8247 {
8248         u32 sg_count;
8249         u32 size;
8250         int i;
8251         struct pqi_sg_descriptor *mem_descriptor = NULL;
8252         struct device *dev;
8253         struct pqi_ofa_memory *ofap;
8254
8255         dev = &ctrl_info->pci_dev->dev;
8256
8257         sg_count = (total_size + chunk_size - 1);
8258         sg_count /= chunk_size;
8259
8260         ofap = ctrl_info->pqi_ofa_mem_virt_addr;
8261
8262         if (sg_count*chunk_size < total_size)
8263                 goto out;
8264
8265         ctrl_info->pqi_ofa_chunk_virt_addr =
8266                                 kcalloc(sg_count, sizeof(void *), GFP_KERNEL);
8267         if (!ctrl_info->pqi_ofa_chunk_virt_addr)
8268                 goto out;
8269
8270         for (size = 0, i = 0; size < total_size; size += chunk_size, i++) {
8271                 dma_addr_t dma_handle;
8272
8273                 ctrl_info->pqi_ofa_chunk_virt_addr[i] =
8274                         dma_alloc_coherent(dev, chunk_size, &dma_handle,
8275                                            GFP_KERNEL);
8276
8277                 if (!ctrl_info->pqi_ofa_chunk_virt_addr[i])
8278                         break;
8279
8280                 mem_descriptor = &ofap->sg_descriptor[i];
8281                 put_unaligned_le64((u64)dma_handle, &mem_descriptor->address);
8282                 put_unaligned_le32(chunk_size, &mem_descriptor->length);
8283         }
8284
8285         if (!size || size < total_size)
8286                 goto out_free_chunks;
8287
8288         put_unaligned_le32(CISS_SG_LAST, &mem_descriptor->flags);
8289         put_unaligned_le16(sg_count, &ofap->num_memory_descriptors);
8290         put_unaligned_le32(size, &ofap->bytes_allocated);
8291
8292         return 0;
8293
8294 out_free_chunks:
8295         while (--i >= 0) {
8296                 mem_descriptor = &ofap->sg_descriptor[i];
8297                 dma_free_coherent(dev, chunk_size,
8298                                 ctrl_info->pqi_ofa_chunk_virt_addr[i],
8299                                 get_unaligned_le64(&mem_descriptor->address));
8300         }
8301         kfree(ctrl_info->pqi_ofa_chunk_virt_addr);
8302
8303 out:
8304         put_unaligned_le32 (0, &ofap->bytes_allocated);
8305         return -ENOMEM;
8306 }
8307
8308 static int pqi_ofa_alloc_host_buffer(struct pqi_ctrl_info *ctrl_info)
8309 {
8310         u32 total_size;
8311         u32 min_chunk_size;
8312         u32 chunk_sz;
8313
8314         total_size = le32_to_cpu(
8315                         ctrl_info->pqi_ofa_mem_virt_addr->bytes_allocated);
8316         min_chunk_size = total_size / PQI_OFA_MAX_SG_DESCRIPTORS;
8317
8318         for (chunk_sz = total_size; chunk_sz >= min_chunk_size; chunk_sz /= 2)
8319                 if (!pqi_ofa_alloc_mem(ctrl_info, total_size, chunk_sz))
8320                         return 0;
8321
8322         return -ENOMEM;
8323 }
8324
8325 static void pqi_ofa_setup_host_buffer(struct pqi_ctrl_info *ctrl_info,
8326         u32 bytes_requested)
8327 {
8328         struct pqi_ofa_memory *pqi_ofa_memory;
8329         struct device *dev;
8330
8331         dev = &ctrl_info->pci_dev->dev;
8332         pqi_ofa_memory = dma_alloc_coherent(dev,
8333                                             PQI_OFA_MEMORY_DESCRIPTOR_LENGTH,
8334                                             &ctrl_info->pqi_ofa_mem_dma_handle,
8335                                             GFP_KERNEL);
8336
8337         if (!pqi_ofa_memory)
8338                 return;
8339
8340         put_unaligned_le16(PQI_OFA_VERSION, &pqi_ofa_memory->version);
8341         memcpy(&pqi_ofa_memory->signature, PQI_OFA_SIGNATURE,
8342                                         sizeof(pqi_ofa_memory->signature));
8343         pqi_ofa_memory->bytes_allocated = cpu_to_le32(bytes_requested);
8344
8345         ctrl_info->pqi_ofa_mem_virt_addr = pqi_ofa_memory;
8346
8347         if (pqi_ofa_alloc_host_buffer(ctrl_info) < 0) {
8348                 dev_err(dev, "Failed to allocate host buffer of size = %u",
8349                         bytes_requested);
8350         }
8351
8352         return;
8353 }
8354
8355 static void pqi_ofa_free_host_buffer(struct pqi_ctrl_info *ctrl_info)
8356 {
8357         int i;
8358         struct pqi_sg_descriptor *mem_descriptor;
8359         struct pqi_ofa_memory *ofap;
8360
8361         ofap = ctrl_info->pqi_ofa_mem_virt_addr;
8362
8363         if (!ofap)
8364                 return;
8365
8366         if (!ofap->bytes_allocated)
8367                 goto out;
8368
8369         mem_descriptor = ofap->sg_descriptor;
8370
8371         for (i = 0; i < get_unaligned_le16(&ofap->num_memory_descriptors);
8372                 i++) {
8373                 dma_free_coherent(&ctrl_info->pci_dev->dev,
8374                         get_unaligned_le32(&mem_descriptor[i].length),
8375                         ctrl_info->pqi_ofa_chunk_virt_addr[i],
8376                         get_unaligned_le64(&mem_descriptor[i].address));
8377         }
8378         kfree(ctrl_info->pqi_ofa_chunk_virt_addr);
8379
8380 out:
8381         dma_free_coherent(&ctrl_info->pci_dev->dev,
8382                         PQI_OFA_MEMORY_DESCRIPTOR_LENGTH, ofap,
8383                         ctrl_info->pqi_ofa_mem_dma_handle);
8384         ctrl_info->pqi_ofa_mem_virt_addr = NULL;
8385 }
8386
8387 static int pqi_ofa_host_memory_update(struct pqi_ctrl_info *ctrl_info)
8388 {
8389         struct pqi_vendor_general_request request;
8390         size_t size;
8391         struct pqi_ofa_memory *ofap;
8392
8393         memset(&request, 0, sizeof(request));
8394
8395         ofap = ctrl_info->pqi_ofa_mem_virt_addr;
8396
8397         request.header.iu_type = PQI_REQUEST_IU_VENDOR_GENERAL;
8398         put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
8399                 &request.header.iu_length);
8400         put_unaligned_le16(PQI_VENDOR_GENERAL_HOST_MEMORY_UPDATE,
8401                 &request.function_code);
8402
8403         if (ofap) {
8404                 size = offsetof(struct pqi_ofa_memory, sg_descriptor) +
8405                         get_unaligned_le16(&ofap->num_memory_descriptors) *
8406                         sizeof(struct pqi_sg_descriptor);
8407
8408                 put_unaligned_le64((u64)ctrl_info->pqi_ofa_mem_dma_handle,
8409                         &request.data.ofa_memory_allocation.buffer_address);
8410                 put_unaligned_le32(size,
8411                         &request.data.ofa_memory_allocation.buffer_length);
8412
8413         }
8414
8415         return pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
8416                 0, NULL, NO_TIMEOUT);
8417 }
8418
8419 static int pqi_ofa_ctrl_restart(struct pqi_ctrl_info *ctrl_info)
8420 {
8421         msleep(PQI_POST_RESET_DELAY_B4_MSGU_READY);
8422         return pqi_ctrl_init_resume(ctrl_info);
8423 }
8424
8425 static void pqi_perform_lockup_action(void)
8426 {
8427         switch (pqi_lockup_action) {
8428         case PANIC:
8429                 panic("FATAL: Smart Family Controller lockup detected");
8430                 break;
8431         case REBOOT:
8432                 emergency_restart();
8433                 break;
8434         case NONE:
8435         default:
8436                 break;
8437         }
8438 }
8439
8440 static struct pqi_raid_error_info pqi_ctrl_offline_raid_error_info = {
8441         .data_out_result = PQI_DATA_IN_OUT_HARDWARE_ERROR,
8442         .status = SAM_STAT_CHECK_CONDITION,
8443 };
8444
8445 static void pqi_fail_all_outstanding_requests(struct pqi_ctrl_info *ctrl_info)
8446 {
8447         unsigned int i;
8448         struct pqi_io_request *io_request;
8449         struct scsi_cmnd *scmd;
8450
8451         for (i = 0; i < ctrl_info->max_io_slots; i++) {
8452                 io_request = &ctrl_info->io_request_pool[i];
8453                 if (atomic_read(&io_request->refcount) == 0)
8454                         continue;
8455
8456                 scmd = io_request->scmd;
8457                 if (scmd) {
8458                         set_host_byte(scmd, DID_NO_CONNECT);
8459                 } else {
8460                         io_request->status = -ENXIO;
8461                         io_request->error_info =
8462                                 &pqi_ctrl_offline_raid_error_info;
8463                 }
8464
8465                 io_request->io_complete_callback(io_request,
8466                         io_request->context);
8467         }
8468 }
8469
8470 static void pqi_take_ctrl_offline_deferred(struct pqi_ctrl_info *ctrl_info)
8471 {
8472         pqi_perform_lockup_action();
8473         pqi_stop_heartbeat_timer(ctrl_info);
8474         pqi_free_interrupts(ctrl_info);
8475         pqi_cancel_rescan_worker(ctrl_info);
8476         pqi_cancel_update_time_worker(ctrl_info);
8477         pqi_ctrl_wait_until_quiesced(ctrl_info);
8478         pqi_fail_all_outstanding_requests(ctrl_info);
8479         pqi_clear_all_queued_raid_bypass_retries(ctrl_info);
8480         pqi_ctrl_unblock_requests(ctrl_info);
8481 }
8482
8483 static void pqi_ctrl_offline_worker(struct work_struct *work)
8484 {
8485         struct pqi_ctrl_info *ctrl_info;
8486
8487         ctrl_info = container_of(work, struct pqi_ctrl_info, ctrl_offline_work);
8488         pqi_take_ctrl_offline_deferred(ctrl_info);
8489 }
8490
8491 static void pqi_take_ctrl_offline(struct pqi_ctrl_info *ctrl_info)
8492 {
8493         if (!ctrl_info->controller_online)
8494                 return;
8495
8496         ctrl_info->controller_online = false;
8497         ctrl_info->pqi_mode_enabled = false;
8498         pqi_ctrl_block_requests(ctrl_info);
8499         if (!pqi_disable_ctrl_shutdown)
8500                 sis_shutdown_ctrl(ctrl_info);
8501         pci_disable_device(ctrl_info->pci_dev);
8502         dev_err(&ctrl_info->pci_dev->dev, "controller offline\n");
8503         schedule_work(&ctrl_info->ctrl_offline_work);
8504 }
8505
8506 static void pqi_print_ctrl_info(struct pci_dev *pci_dev,
8507         const struct pci_device_id *id)
8508 {
8509         char *ctrl_description;
8510
8511         if (id->driver_data)
8512                 ctrl_description = (char *)id->driver_data;
8513         else
8514                 ctrl_description = "Microsemi Smart Family Controller";
8515
8516         dev_info(&pci_dev->dev, "%s found\n", ctrl_description);
8517 }
8518
8519 static int pqi_pci_probe(struct pci_dev *pci_dev,
8520         const struct pci_device_id *id)
8521 {
8522         int rc;
8523         int node, cp_node;
8524         struct pqi_ctrl_info *ctrl_info;
8525
8526         pqi_print_ctrl_info(pci_dev, id);
8527
8528         if (pqi_disable_device_id_wildcards &&
8529                 id->subvendor == PCI_ANY_ID &&
8530                 id->subdevice == PCI_ANY_ID) {
8531                 dev_warn(&pci_dev->dev,
8532                         "controller not probed because device ID wildcards are disabled\n");
8533                 return -ENODEV;
8534         }
8535
8536         if (id->subvendor == PCI_ANY_ID || id->subdevice == PCI_ANY_ID)
8537                 dev_warn(&pci_dev->dev,
8538                         "controller device ID matched using wildcards\n");
8539
8540         node = dev_to_node(&pci_dev->dev);
8541         if (node == NUMA_NO_NODE) {
8542                 cp_node = cpu_to_node(0);
8543                 if (cp_node == NUMA_NO_NODE)
8544                         cp_node = 0;
8545                 set_dev_node(&pci_dev->dev, cp_node);
8546         }
8547
8548         ctrl_info = pqi_alloc_ctrl_info(node);
8549         if (!ctrl_info) {
8550                 dev_err(&pci_dev->dev,
8551                         "failed to allocate controller info block\n");
8552                 return -ENOMEM;
8553         }
8554
8555         ctrl_info->pci_dev = pci_dev;
8556
8557         rc = pqi_pci_init(ctrl_info);
8558         if (rc)
8559                 goto error;
8560
8561         rc = pqi_ctrl_init(ctrl_info);
8562         if (rc)
8563                 goto error;
8564
8565         return 0;
8566
8567 error:
8568         pqi_remove_ctrl(ctrl_info);
8569
8570         return rc;
8571 }
8572
8573 static void pqi_pci_remove(struct pci_dev *pci_dev)
8574 {
8575         struct pqi_ctrl_info *ctrl_info;
8576
8577         ctrl_info = pci_get_drvdata(pci_dev);
8578         if (!ctrl_info)
8579                 return;
8580
8581         pqi_remove_ctrl(ctrl_info);
8582 }
8583
8584 static void pqi_crash_if_pending_command(struct pqi_ctrl_info *ctrl_info)
8585 {
8586         unsigned int i;
8587         struct pqi_io_request *io_request;
8588         struct scsi_cmnd *scmd;
8589
8590         for (i = 0; i < ctrl_info->max_io_slots; i++) {
8591                 io_request = &ctrl_info->io_request_pool[i];
8592                 if (atomic_read(&io_request->refcount) == 0)
8593                         continue;
8594                 scmd = io_request->scmd;
8595                 WARN_ON(scmd != NULL); /* IO command from SML */
8596                 WARN_ON(scmd == NULL); /* Non-IO cmd or driver initiated*/
8597         }
8598 }
8599
8600 static void pqi_shutdown(struct pci_dev *pci_dev)
8601 {
8602         int rc;
8603         struct pqi_ctrl_info *ctrl_info;
8604
8605         ctrl_info = pci_get_drvdata(pci_dev);
8606         if (!ctrl_info) {
8607                 dev_err(&pci_dev->dev,
8608                         "cache could not be flushed\n");
8609                 return;
8610         }
8611
8612         pqi_disable_events(ctrl_info);
8613         pqi_wait_until_ofa_finished(ctrl_info);
8614         pqi_cancel_update_time_worker(ctrl_info);
8615         pqi_cancel_rescan_worker(ctrl_info);
8616         pqi_cancel_event_worker(ctrl_info);
8617
8618         pqi_ctrl_shutdown_start(ctrl_info);
8619         pqi_ctrl_wait_until_quiesced(ctrl_info);
8620
8621         rc = pqi_ctrl_wait_for_pending_io(ctrl_info, NO_TIMEOUT);
8622         if (rc) {
8623                 dev_err(&pci_dev->dev,
8624                         "wait for pending I/O failed\n");
8625                 return;
8626         }
8627
8628         pqi_ctrl_block_device_reset(ctrl_info);
8629         pqi_wait_until_lun_reset_finished(ctrl_info);
8630
8631         /*
8632          * Write all data in the controller's battery-backed cache to
8633          * storage.
8634          */
8635         rc = pqi_flush_cache(ctrl_info, SHUTDOWN);
8636         if (rc)
8637                 dev_err(&pci_dev->dev,
8638                         "unable to flush controller cache\n");
8639
8640         pqi_ctrl_block_requests(ctrl_info);
8641
8642         rc = pqi_ctrl_wait_for_pending_sync_cmds(ctrl_info);
8643         if (rc) {
8644                 dev_err(&pci_dev->dev,
8645                         "wait for pending sync cmds failed\n");
8646                 return;
8647         }
8648
8649         pqi_crash_if_pending_command(ctrl_info);
8650         pqi_reset(ctrl_info);
8651 }
8652
8653 static void pqi_process_lockup_action_param(void)
8654 {
8655         unsigned int i;
8656
8657         if (!pqi_lockup_action_param)
8658                 return;
8659
8660         for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
8661                 if (strcmp(pqi_lockup_action_param,
8662                         pqi_lockup_actions[i].name) == 0) {
8663                         pqi_lockup_action = pqi_lockup_actions[i].action;
8664                         return;
8665                 }
8666         }
8667
8668         pr_warn("%s: invalid lockup action setting \"%s\" - supported settings: none, reboot, panic\n",
8669                 DRIVER_NAME_SHORT, pqi_lockup_action_param);
8670 }
8671
8672 static void pqi_process_module_params(void)
8673 {
8674         pqi_process_lockup_action_param();
8675 }
8676
8677 static __maybe_unused int pqi_suspend(struct pci_dev *pci_dev, pm_message_t state)
8678 {
8679         struct pqi_ctrl_info *ctrl_info;
8680
8681         ctrl_info = pci_get_drvdata(pci_dev);
8682
8683         pqi_disable_events(ctrl_info);
8684         pqi_cancel_update_time_worker(ctrl_info);
8685         pqi_cancel_rescan_worker(ctrl_info);
8686         pqi_wait_until_scan_finished(ctrl_info);
8687         pqi_wait_until_lun_reset_finished(ctrl_info);
8688         pqi_wait_until_ofa_finished(ctrl_info);
8689         pqi_flush_cache(ctrl_info, SUSPEND);
8690         pqi_ctrl_block_requests(ctrl_info);
8691         pqi_ctrl_wait_until_quiesced(ctrl_info);
8692         pqi_wait_until_inbound_queues_empty(ctrl_info);
8693         pqi_ctrl_wait_for_pending_io(ctrl_info, NO_TIMEOUT);
8694         pqi_stop_heartbeat_timer(ctrl_info);
8695
8696         if (state.event == PM_EVENT_FREEZE)
8697                 return 0;
8698
8699         pci_save_state(pci_dev);
8700         pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state));
8701
8702         ctrl_info->controller_online = false;
8703         ctrl_info->pqi_mode_enabled = false;
8704
8705         return 0;
8706 }
8707
8708 static __maybe_unused int pqi_resume(struct pci_dev *pci_dev)
8709 {
8710         int rc;
8711         struct pqi_ctrl_info *ctrl_info;
8712
8713         ctrl_info = pci_get_drvdata(pci_dev);
8714
8715         if (pci_dev->current_state != PCI_D0) {
8716                 ctrl_info->max_hw_queue_index = 0;
8717                 pqi_free_interrupts(ctrl_info);
8718                 pqi_change_irq_mode(ctrl_info, IRQ_MODE_INTX);
8719                 rc = request_irq(pci_irq_vector(pci_dev, 0), pqi_irq_handler,
8720                         IRQF_SHARED, DRIVER_NAME_SHORT,
8721                         &ctrl_info->queue_groups[0]);
8722                 if (rc) {
8723                         dev_err(&ctrl_info->pci_dev->dev,
8724                                 "irq %u init failed with error %d\n",
8725                                 pci_dev->irq, rc);
8726                         return rc;
8727                 }
8728                 pqi_start_heartbeat_timer(ctrl_info);
8729                 pqi_ctrl_unblock_requests(ctrl_info);
8730                 return 0;
8731         }
8732
8733         pci_set_power_state(pci_dev, PCI_D0);
8734         pci_restore_state(pci_dev);
8735
8736         return pqi_ctrl_init_resume(ctrl_info);
8737 }
8738
8739 /* Define the PCI IDs for the controllers that we support. */
8740 static const struct pci_device_id pqi_pci_id_table[] = {
8741         {
8742                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8743                                0x105b, 0x1211)
8744         },
8745         {
8746                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8747                                0x105b, 0x1321)
8748         },
8749         {
8750                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8751                                0x152d, 0x8a22)
8752         },
8753         {
8754                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8755                                0x152d, 0x8a23)
8756         },
8757         {
8758                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8759                                0x152d, 0x8a24)
8760         },
8761         {
8762                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8763                                0x152d, 0x8a36)
8764         },
8765         {
8766                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8767                                0x152d, 0x8a37)
8768         },
8769         {
8770                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8771                                0x193d, 0x1104)
8772         },
8773         {
8774                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8775                                0x193d, 0x1105)
8776         },
8777         {
8778                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8779                                0x193d, 0x1106)
8780         },
8781         {
8782                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8783                                0x193d, 0x1107)
8784         },
8785         {
8786                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8787                                0x193d, 0x8460)
8788         },
8789         {
8790                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8791                                0x193d, 0x8461)
8792         },
8793         {
8794                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8795                                0x193d, 0xc460)
8796         },
8797         {
8798                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8799                                0x193d, 0xc461)
8800         },
8801         {
8802                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8803                                0x193d, 0xf460)
8804         },
8805         {
8806                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8807                                0x193d, 0xf461)
8808         },
8809         {
8810                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8811                                0x1bd4, 0x0045)
8812         },
8813         {
8814                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8815                                0x1bd4, 0x0046)
8816         },
8817         {
8818                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8819                                0x1bd4, 0x0047)
8820         },
8821         {
8822                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8823                                0x1bd4, 0x0048)
8824         },
8825         {
8826                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8827                                0x1bd4, 0x004a)
8828         },
8829         {
8830                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8831                                0x1bd4, 0x004b)
8832         },
8833         {
8834                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8835                                0x1bd4, 0x004c)
8836         },
8837         {
8838                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8839                                0x1bd4, 0x004f)
8840         },
8841         {
8842                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8843                                0x19e5, 0xd227)
8844         },
8845         {
8846                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8847                                0x19e5, 0xd228)
8848         },
8849         {
8850                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8851                                0x19e5, 0xd229)
8852         },
8853         {
8854                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8855                                0x19e5, 0xd22a)
8856         },
8857         {
8858                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8859                                0x19e5, 0xd22b)
8860         },
8861         {
8862                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8863                                0x19e5, 0xd22c)
8864         },
8865         {
8866                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8867                                PCI_VENDOR_ID_ADAPTEC2, 0x0110)
8868         },
8869         {
8870                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8871                                PCI_VENDOR_ID_ADAPTEC2, 0x0608)
8872         },
8873         {
8874                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8875                                PCI_VENDOR_ID_ADAPTEC2, 0x0800)
8876         },
8877         {
8878                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8879                                PCI_VENDOR_ID_ADAPTEC2, 0x0801)
8880         },
8881         {
8882                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8883                                PCI_VENDOR_ID_ADAPTEC2, 0x0802)
8884         },
8885         {
8886                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8887                                PCI_VENDOR_ID_ADAPTEC2, 0x0803)
8888         },
8889         {
8890                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8891                                PCI_VENDOR_ID_ADAPTEC2, 0x0804)
8892         },
8893         {
8894                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8895                                PCI_VENDOR_ID_ADAPTEC2, 0x0805)
8896         },
8897         {
8898                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8899                                PCI_VENDOR_ID_ADAPTEC2, 0x0806)
8900         },
8901         {
8902                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8903                                PCI_VENDOR_ID_ADAPTEC2, 0x0807)
8904         },
8905         {
8906                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8907                                PCI_VENDOR_ID_ADAPTEC2, 0x0808)
8908         },
8909         {
8910                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8911                                PCI_VENDOR_ID_ADAPTEC2, 0x0809)
8912         },
8913         {
8914                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8915                                PCI_VENDOR_ID_ADAPTEC2, 0x080a)
8916         },
8917         {
8918                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8919                                PCI_VENDOR_ID_ADAPTEC2, 0x0900)
8920         },
8921         {
8922                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8923                                PCI_VENDOR_ID_ADAPTEC2, 0x0901)
8924         },
8925         {
8926                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8927                                PCI_VENDOR_ID_ADAPTEC2, 0x0902)
8928         },
8929         {
8930                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8931                                PCI_VENDOR_ID_ADAPTEC2, 0x0903)
8932         },
8933         {
8934                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8935                                PCI_VENDOR_ID_ADAPTEC2, 0x0904)
8936         },
8937         {
8938                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8939                                PCI_VENDOR_ID_ADAPTEC2, 0x0905)
8940         },
8941         {
8942                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8943                                PCI_VENDOR_ID_ADAPTEC2, 0x0906)
8944         },
8945         {
8946                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8947                                PCI_VENDOR_ID_ADAPTEC2, 0x0907)
8948         },
8949         {
8950                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8951                                PCI_VENDOR_ID_ADAPTEC2, 0x0908)
8952         },
8953         {
8954                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8955                                PCI_VENDOR_ID_ADAPTEC2, 0x090a)
8956         },
8957         {
8958                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8959                                PCI_VENDOR_ID_ADAPTEC2, 0x1200)
8960         },
8961         {
8962                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8963                                PCI_VENDOR_ID_ADAPTEC2, 0x1201)
8964         },
8965         {
8966                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8967                                PCI_VENDOR_ID_ADAPTEC2, 0x1202)
8968         },
8969         {
8970                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8971                                PCI_VENDOR_ID_ADAPTEC2, 0x1280)
8972         },
8973         {
8974                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8975                                PCI_VENDOR_ID_ADAPTEC2, 0x1281)
8976         },
8977         {
8978                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8979                                PCI_VENDOR_ID_ADAPTEC2, 0x1282)
8980         },
8981         {
8982                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8983                                PCI_VENDOR_ID_ADAPTEC2, 0x1300)
8984         },
8985         {
8986                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8987                                PCI_VENDOR_ID_ADAPTEC2, 0x1301)
8988         },
8989         {
8990                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8991                                PCI_VENDOR_ID_ADAPTEC2, 0x1302)
8992         },
8993         {
8994                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8995                                PCI_VENDOR_ID_ADAPTEC2, 0x1303)
8996         },
8997         {
8998                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8999                                PCI_VENDOR_ID_ADAPTEC2, 0x1380)
9000         },
9001         {
9002                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9003                                PCI_VENDOR_ID_ADVANTECH, 0x8312)
9004         },
9005         {
9006                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9007                                PCI_VENDOR_ID_DELL, 0x1fe0)
9008         },
9009         {
9010                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9011                                PCI_VENDOR_ID_HP, 0x0600)
9012         },
9013         {
9014                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9015                                PCI_VENDOR_ID_HP, 0x0601)
9016         },
9017         {
9018                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9019                                PCI_VENDOR_ID_HP, 0x0602)
9020         },
9021         {
9022                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9023                                PCI_VENDOR_ID_HP, 0x0603)
9024         },
9025         {
9026                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9027                                PCI_VENDOR_ID_HP, 0x0609)
9028         },
9029         {
9030                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9031                                PCI_VENDOR_ID_HP, 0x0650)
9032         },
9033         {
9034                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9035                                PCI_VENDOR_ID_HP, 0x0651)
9036         },
9037         {
9038                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9039                                PCI_VENDOR_ID_HP, 0x0652)
9040         },
9041         {
9042                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9043                                PCI_VENDOR_ID_HP, 0x0653)
9044         },
9045         {
9046                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9047                                PCI_VENDOR_ID_HP, 0x0654)
9048         },
9049         {
9050                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9051                                PCI_VENDOR_ID_HP, 0x0655)
9052         },
9053         {
9054                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9055                                PCI_VENDOR_ID_HP, 0x0700)
9056         },
9057         {
9058                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9059                                PCI_VENDOR_ID_HP, 0x0701)
9060         },
9061         {
9062                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9063                                PCI_VENDOR_ID_HP, 0x1001)
9064         },
9065         {
9066                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9067                                PCI_VENDOR_ID_HP, 0x1100)
9068         },
9069         {
9070                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9071                                PCI_VENDOR_ID_HP, 0x1101)
9072         },
9073         {
9074                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9075                                0x1d8d, 0x0800)
9076         },
9077         {
9078                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9079                                0x1d8d, 0x0908)
9080         },
9081         {
9082                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9083                                0x1d8d, 0x0806)
9084         },
9085         {
9086                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9087                                0x1d8d, 0x0916)
9088         },
9089         {
9090                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9091                                PCI_VENDOR_ID_GIGABYTE, 0x1000)
9092         },
9093         {
9094                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9095                                PCI_ANY_ID, PCI_ANY_ID)
9096         },
9097         { 0 }
9098 };
9099
9100 MODULE_DEVICE_TABLE(pci, pqi_pci_id_table);
9101
9102 static struct pci_driver pqi_pci_driver = {
9103         .name = DRIVER_NAME_SHORT,
9104         .id_table = pqi_pci_id_table,
9105         .probe = pqi_pci_probe,
9106         .remove = pqi_pci_remove,
9107         .shutdown = pqi_shutdown,
9108 #if defined(CONFIG_PM)
9109         .suspend = pqi_suspend,
9110         .resume = pqi_resume,
9111 #endif
9112 };
9113
9114 static int __init pqi_init(void)
9115 {
9116         int rc;
9117
9118         pr_info(DRIVER_NAME "\n");
9119
9120         pqi_sas_transport_template = sas_attach_transport(&pqi_sas_transport_functions);
9121         if (!pqi_sas_transport_template)
9122                 return -ENODEV;
9123
9124         pqi_process_module_params();
9125
9126         rc = pci_register_driver(&pqi_pci_driver);
9127         if (rc)
9128                 sas_release_transport(pqi_sas_transport_template);
9129
9130         return rc;
9131 }
9132
9133 static void __exit pqi_cleanup(void)
9134 {
9135         pci_unregister_driver(&pqi_pci_driver);
9136         sas_release_transport(pqi_sas_transport_template);
9137 }
9138
9139 module_init(pqi_init);
9140 module_exit(pqi_cleanup);
9141
9142 static void __attribute__((unused)) verify_structures(void)
9143 {
9144         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9145                 sis_host_to_ctrl_doorbell) != 0x20);
9146         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9147                 sis_interrupt_mask) != 0x34);
9148         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9149                 sis_ctrl_to_host_doorbell) != 0x9c);
9150         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9151                 sis_ctrl_to_host_doorbell_clear) != 0xa0);
9152         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9153                 sis_driver_scratch) != 0xb0);
9154         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9155                 sis_product_identifier) != 0xb4);
9156         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9157                 sis_firmware_status) != 0xbc);
9158         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9159                 sis_mailbox) != 0x1000);
9160         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9161                 pqi_registers) != 0x4000);
9162
9163         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9164                 iu_type) != 0x0);
9165         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9166                 iu_length) != 0x2);
9167         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9168                 response_queue_id) != 0x4);
9169         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9170                 work_area) != 0x6);
9171         BUILD_BUG_ON(sizeof(struct pqi_iu_header) != 0x8);
9172
9173         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9174                 status) != 0x0);
9175         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9176                 service_response) != 0x1);
9177         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9178                 data_present) != 0x2);
9179         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9180                 reserved) != 0x3);
9181         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9182                 residual_count) != 0x4);
9183         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9184                 data_length) != 0x8);
9185         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9186                 reserved1) != 0xa);
9187         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9188                 data) != 0xc);
9189         BUILD_BUG_ON(sizeof(struct pqi_aio_error_info) != 0x10c);
9190
9191         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9192                 data_in_result) != 0x0);
9193         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9194                 data_out_result) != 0x1);
9195         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9196                 reserved) != 0x2);
9197         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9198                 status) != 0x5);
9199         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9200                 status_qualifier) != 0x6);
9201         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9202                 sense_data_length) != 0x8);
9203         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9204                 response_data_length) != 0xa);
9205         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9206                 data_in_transferred) != 0xc);
9207         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9208                 data_out_transferred) != 0x10);
9209         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9210                 data) != 0x14);
9211         BUILD_BUG_ON(sizeof(struct pqi_raid_error_info) != 0x114);
9212
9213         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9214                 signature) != 0x0);
9215         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9216                 function_and_status_code) != 0x8);
9217         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9218                 max_admin_iq_elements) != 0x10);
9219         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9220                 max_admin_oq_elements) != 0x11);
9221         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9222                 admin_iq_element_length) != 0x12);
9223         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9224                 admin_oq_element_length) != 0x13);
9225         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9226                 max_reset_timeout) != 0x14);
9227         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9228                 legacy_intx_status) != 0x18);
9229         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9230                 legacy_intx_mask_set) != 0x1c);
9231         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9232                 legacy_intx_mask_clear) != 0x20);
9233         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9234                 device_status) != 0x40);
9235         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9236                 admin_iq_pi_offset) != 0x48);
9237         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9238                 admin_oq_ci_offset) != 0x50);
9239         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9240                 admin_iq_element_array_addr) != 0x58);
9241         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9242                 admin_oq_element_array_addr) != 0x60);
9243         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9244                 admin_iq_ci_addr) != 0x68);
9245         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9246                 admin_oq_pi_addr) != 0x70);
9247         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9248                 admin_iq_num_elements) != 0x78);
9249         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9250                 admin_oq_num_elements) != 0x79);
9251         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9252                 admin_queue_int_msg_num) != 0x7a);
9253         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9254                 device_error) != 0x80);
9255         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9256                 error_details) != 0x88);
9257         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9258                 device_reset) != 0x90);
9259         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9260                 power_action) != 0x94);
9261         BUILD_BUG_ON(sizeof(struct pqi_device_registers) != 0x100);
9262
9263         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9264                 header.iu_type) != 0);
9265         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9266                 header.iu_length) != 2);
9267         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9268                 header.work_area) != 6);
9269         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9270                 request_id) != 8);
9271         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9272                 function_code) != 10);
9273         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9274                 data.report_device_capability.buffer_length) != 44);
9275         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9276                 data.report_device_capability.sg_descriptor) != 48);
9277         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9278                 data.create_operational_iq.queue_id) != 12);
9279         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9280                 data.create_operational_iq.element_array_addr) != 16);
9281         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9282                 data.create_operational_iq.ci_addr) != 24);
9283         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9284                 data.create_operational_iq.num_elements) != 32);
9285         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9286                 data.create_operational_iq.element_length) != 34);
9287         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9288                 data.create_operational_iq.queue_protocol) != 36);
9289         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9290                 data.create_operational_oq.queue_id) != 12);
9291         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9292                 data.create_operational_oq.element_array_addr) != 16);
9293         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9294                 data.create_operational_oq.pi_addr) != 24);
9295         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9296                 data.create_operational_oq.num_elements) != 32);
9297         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9298                 data.create_operational_oq.element_length) != 34);
9299         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9300                 data.create_operational_oq.queue_protocol) != 36);
9301         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9302                 data.create_operational_oq.int_msg_num) != 40);
9303         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9304                 data.create_operational_oq.coalescing_count) != 42);
9305         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9306                 data.create_operational_oq.min_coalescing_time) != 44);
9307         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9308                 data.create_operational_oq.max_coalescing_time) != 48);
9309         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9310                 data.delete_operational_queue.queue_id) != 12);
9311         BUILD_BUG_ON(sizeof(struct pqi_general_admin_request) != 64);
9312         BUILD_BUG_ON(sizeof_field(struct pqi_general_admin_request,
9313                 data.create_operational_iq) != 64 - 11);
9314         BUILD_BUG_ON(sizeof_field(struct pqi_general_admin_request,
9315                 data.create_operational_oq) != 64 - 11);
9316         BUILD_BUG_ON(sizeof_field(struct pqi_general_admin_request,
9317                 data.delete_operational_queue) != 64 - 11);
9318
9319         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9320                 header.iu_type) != 0);
9321         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9322                 header.iu_length) != 2);
9323         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9324                 header.work_area) != 6);
9325         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9326                 request_id) != 8);
9327         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9328                 function_code) != 10);
9329         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9330                 status) != 11);
9331         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9332                 data.create_operational_iq.status_descriptor) != 12);
9333         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9334                 data.create_operational_iq.iq_pi_offset) != 16);
9335         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9336                 data.create_operational_oq.status_descriptor) != 12);
9337         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9338                 data.create_operational_oq.oq_ci_offset) != 16);
9339         BUILD_BUG_ON(sizeof(struct pqi_general_admin_response) != 64);
9340
9341         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9342                 header.iu_type) != 0);
9343         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9344                 header.iu_length) != 2);
9345         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9346                 header.response_queue_id) != 4);
9347         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9348                 header.work_area) != 6);
9349         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9350                 request_id) != 8);
9351         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9352                 nexus_id) != 10);
9353         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9354                 buffer_length) != 12);
9355         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9356                 lun_number) != 16);
9357         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9358                 protocol_specific) != 24);
9359         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9360                 error_index) != 27);
9361         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9362                 cdb) != 32);
9363         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9364                 timeout) != 60);
9365         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9366                 sg_descriptors) != 64);
9367         BUILD_BUG_ON(sizeof(struct pqi_raid_path_request) !=
9368                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
9369
9370         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9371                 header.iu_type) != 0);
9372         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9373                 header.iu_length) != 2);
9374         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9375                 header.response_queue_id) != 4);
9376         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9377                 header.work_area) != 6);
9378         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9379                 request_id) != 8);
9380         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9381                 nexus_id) != 12);
9382         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9383                 buffer_length) != 16);
9384         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9385                 data_encryption_key_index) != 22);
9386         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9387                 encrypt_tweak_lower) != 24);
9388         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9389                 encrypt_tweak_upper) != 28);
9390         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9391                 cdb) != 32);
9392         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9393                 error_index) != 48);
9394         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9395                 num_sg_descriptors) != 50);
9396         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9397                 cdb_length) != 51);
9398         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9399                 lun_number) != 52);
9400         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9401                 sg_descriptors) != 64);
9402         BUILD_BUG_ON(sizeof(struct pqi_aio_path_request) !=
9403                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
9404
9405         BUILD_BUG_ON(offsetof(struct pqi_io_response,
9406                 header.iu_type) != 0);
9407         BUILD_BUG_ON(offsetof(struct pqi_io_response,
9408                 header.iu_length) != 2);
9409         BUILD_BUG_ON(offsetof(struct pqi_io_response,
9410                 request_id) != 8);
9411         BUILD_BUG_ON(offsetof(struct pqi_io_response,
9412                 error_index) != 10);
9413
9414         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9415                 header.iu_type) != 0);
9416         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9417                 header.iu_length) != 2);
9418         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9419                 header.response_queue_id) != 4);
9420         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9421                 request_id) != 8);
9422         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9423                 data.report_event_configuration.buffer_length) != 12);
9424         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9425                 data.report_event_configuration.sg_descriptors) != 16);
9426         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9427                 data.set_event_configuration.global_event_oq_id) != 10);
9428         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9429                 data.set_event_configuration.buffer_length) != 12);
9430         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9431                 data.set_event_configuration.sg_descriptors) != 16);
9432
9433         BUILD_BUG_ON(offsetof(struct pqi_iu_layer_descriptor,
9434                 max_inbound_iu_length) != 6);
9435         BUILD_BUG_ON(offsetof(struct pqi_iu_layer_descriptor,
9436                 max_outbound_iu_length) != 14);
9437         BUILD_BUG_ON(sizeof(struct pqi_iu_layer_descriptor) != 16);
9438
9439         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9440                 data_length) != 0);
9441         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9442                 iq_arbitration_priority_support_bitmask) != 8);
9443         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9444                 maximum_aw_a) != 9);
9445         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9446                 maximum_aw_b) != 10);
9447         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9448                 maximum_aw_c) != 11);
9449         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9450                 max_inbound_queues) != 16);
9451         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9452                 max_elements_per_iq) != 18);
9453         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9454                 max_iq_element_length) != 24);
9455         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9456                 min_iq_element_length) != 26);
9457         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9458                 max_outbound_queues) != 30);
9459         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9460                 max_elements_per_oq) != 32);
9461         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9462                 intr_coalescing_time_granularity) != 34);
9463         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9464                 max_oq_element_length) != 36);
9465         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9466                 min_oq_element_length) != 38);
9467         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9468                 iu_layer_descriptors) != 64);
9469         BUILD_BUG_ON(sizeof(struct pqi_device_capability) != 576);
9470
9471         BUILD_BUG_ON(offsetof(struct pqi_event_descriptor,
9472                 event_type) != 0);
9473         BUILD_BUG_ON(offsetof(struct pqi_event_descriptor,
9474                 oq_id) != 2);
9475         BUILD_BUG_ON(sizeof(struct pqi_event_descriptor) != 4);
9476
9477         BUILD_BUG_ON(offsetof(struct pqi_event_config,
9478                 num_event_descriptors) != 2);
9479         BUILD_BUG_ON(offsetof(struct pqi_event_config,
9480                 descriptors) != 4);
9481
9482         BUILD_BUG_ON(PQI_NUM_SUPPORTED_EVENTS !=
9483                 ARRAY_SIZE(pqi_supported_event_types));
9484
9485         BUILD_BUG_ON(offsetof(struct pqi_event_response,
9486                 header.iu_type) != 0);
9487         BUILD_BUG_ON(offsetof(struct pqi_event_response,
9488                 header.iu_length) != 2);
9489         BUILD_BUG_ON(offsetof(struct pqi_event_response,
9490                 event_type) != 8);
9491         BUILD_BUG_ON(offsetof(struct pqi_event_response,
9492                 event_id) != 10);
9493         BUILD_BUG_ON(offsetof(struct pqi_event_response,
9494                 additional_event_id) != 12);
9495         BUILD_BUG_ON(offsetof(struct pqi_event_response,
9496                 data) != 16);
9497         BUILD_BUG_ON(sizeof(struct pqi_event_response) != 32);
9498
9499         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9500                 header.iu_type) != 0);
9501         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9502                 header.iu_length) != 2);
9503         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9504                 event_type) != 8);
9505         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9506                 event_id) != 10);
9507         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9508                 additional_event_id) != 12);
9509         BUILD_BUG_ON(sizeof(struct pqi_event_acknowledge_request) != 16);
9510
9511         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9512                 header.iu_type) != 0);
9513         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9514                 header.iu_length) != 2);
9515         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9516                 request_id) != 8);
9517         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9518                 nexus_id) != 10);
9519         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9520                 timeout) != 14);
9521         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9522                 lun_number) != 16);
9523         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9524                 protocol_specific) != 24);
9525         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9526                 outbound_queue_id_to_manage) != 26);
9527         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9528                 request_id_to_manage) != 28);
9529         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9530                 task_management_function) != 30);
9531         BUILD_BUG_ON(sizeof(struct pqi_task_management_request) != 32);
9532
9533         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9534                 header.iu_type) != 0);
9535         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9536                 header.iu_length) != 2);
9537         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9538                 request_id) != 8);
9539         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9540                 nexus_id) != 10);
9541         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9542                 additional_response_info) != 12);
9543         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9544                 response_code) != 15);
9545         BUILD_BUG_ON(sizeof(struct pqi_task_management_response) != 16);
9546
9547         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9548                 configured_logical_drive_count) != 0);
9549         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9550                 configuration_signature) != 1);
9551         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9552                 firmware_version_short) != 5);
9553         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9554                 extended_logical_unit_count) != 154);
9555         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9556                 firmware_build_number) != 190);
9557         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9558                 vendor_id) != 200);
9559         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9560                 product_id) != 208);
9561         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9562                 extra_controller_flags) != 286);
9563         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9564                 controller_mode) != 292);
9565         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9566                 spare_part_number) != 293);
9567         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9568                 firmware_version_long) != 325);
9569
9570         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9571                 phys_bay_in_box) != 115);
9572         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9573                 device_type) != 120);
9574         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9575                 redundant_path_present_map) != 1736);
9576         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9577                 active_path_number) != 1738);
9578         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9579                 alternate_paths_phys_connector) != 1739);
9580         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9581                 alternate_paths_phys_box_on_port) != 1755);
9582         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9583                 current_queue_depth_limit) != 1796);
9584         BUILD_BUG_ON(sizeof(struct bmic_identify_physical_device) != 2560);
9585
9586         BUILD_BUG_ON(sizeof(struct bmic_sense_feature_buffer_header) != 4);
9587         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_buffer_header,
9588                 page_code) != 0);
9589         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_buffer_header,
9590                 subpage_code) != 1);
9591         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_buffer_header,
9592                 buffer_length) != 2);
9593
9594         BUILD_BUG_ON(sizeof(struct bmic_sense_feature_page_header) != 4);
9595         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_page_header,
9596                 page_code) != 0);
9597         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_page_header,
9598                 subpage_code) != 1);
9599         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_page_header,
9600                 page_length) != 2);
9601
9602         BUILD_BUG_ON(sizeof(struct bmic_sense_feature_io_page_aio_subpage)
9603                 != 18);
9604         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9605                 header) != 0);
9606         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9607                 firmware_read_support) != 4);
9608         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9609                 driver_read_support) != 5);
9610         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9611                 firmware_write_support) != 6);
9612         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9613                 driver_write_support) != 7);
9614         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9615                 max_transfer_encrypted_sas_sata) != 8);
9616         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9617                 max_transfer_encrypted_nvme) != 10);
9618         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9619                 max_write_raid_5_6) != 12);
9620         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9621                 max_write_raid_1_10_2drive) != 14);
9622         BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9623                 max_write_raid_1_10_3drive) != 16);
9624
9625         BUILD_BUG_ON(PQI_ADMIN_IQ_NUM_ELEMENTS > 255);
9626         BUILD_BUG_ON(PQI_ADMIN_OQ_NUM_ELEMENTS > 255);
9627         BUILD_BUG_ON(PQI_ADMIN_IQ_ELEMENT_LENGTH %
9628                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9629         BUILD_BUG_ON(PQI_ADMIN_OQ_ELEMENT_LENGTH %
9630                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9631         BUILD_BUG_ON(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH > 1048560);
9632         BUILD_BUG_ON(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH %
9633                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9634         BUILD_BUG_ON(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH > 1048560);
9635         BUILD_BUG_ON(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH %
9636                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9637
9638         BUILD_BUG_ON(PQI_RESERVED_IO_SLOTS >= PQI_MAX_OUTSTANDING_REQUESTS);
9639         BUILD_BUG_ON(PQI_RESERVED_IO_SLOTS >=
9640                 PQI_MAX_OUTSTANDING_REQUESTS_KDUMP);
9641 }