GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / scsi / smartpqi / smartpqi_init.c
1 /*
2  *    driver for Microsemi PQI-based storage controllers
3  *    Copyright (c) 2016-2017 Microsemi Corporation
4  *    Copyright (c) 2016 PMC-Sierra, Inc.
5  *
6  *    This program is free software; you can redistribute it and/or modify
7  *    it under the terms of the GNU General Public License as published by
8  *    the Free Software Foundation; version 2 of the License.
9  *
10  *    This program is distributed in the hope that it will be useful,
11  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *    MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
13  *    NON INFRINGEMENT.  See the GNU General Public License for more details.
14  *
15  *    Questions/Comments/Bugfixes to esc.storagedev@microsemi.com
16  *
17  */
18
19 #include <linux/module.h>
20 #include <linux/kernel.h>
21 #include <linux/pci.h>
22 #include <linux/delay.h>
23 #include <linux/interrupt.h>
24 #include <linux/sched.h>
25 #include <linux/rtc.h>
26 #include <linux/bcd.h>
27 #include <linux/reboot.h>
28 #include <linux/cciss_ioctl.h>
29 #include <linux/blk-mq-pci.h>
30 #include <scsi/scsi_host.h>
31 #include <scsi/scsi_cmnd.h>
32 #include <scsi/scsi_device.h>
33 #include <scsi/scsi_eh.h>
34 #include <scsi/scsi_transport_sas.h>
35 #include <asm/unaligned.h>
36 #include "smartpqi.h"
37 #include "smartpqi_sis.h"
38
39 #if !defined(BUILD_TIMESTAMP)
40 #define BUILD_TIMESTAMP
41 #endif
42
43 #define DRIVER_VERSION          "1.1.4-130"
44 #define DRIVER_MAJOR            1
45 #define DRIVER_MINOR            1
46 #define DRIVER_RELEASE          4
47 #define DRIVER_REVISION         130
48
49 #define DRIVER_NAME             "Microsemi PQI Driver (v" \
50                                 DRIVER_VERSION BUILD_TIMESTAMP ")"
51 #define DRIVER_NAME_SHORT       "smartpqi"
52
53 #define PQI_EXTRA_SGL_MEMORY    (12 * sizeof(struct pqi_sg_descriptor))
54
55 MODULE_AUTHOR("Microsemi");
56 MODULE_DESCRIPTION("Driver for Microsemi Smart Family Controller version "
57         DRIVER_VERSION);
58 MODULE_SUPPORTED_DEVICE("Microsemi Smart Family Controllers");
59 MODULE_VERSION(DRIVER_VERSION);
60 MODULE_LICENSE("GPL");
61
62 static void pqi_take_ctrl_offline(struct pqi_ctrl_info *ctrl_info);
63 static void pqi_ctrl_offline_worker(struct work_struct *work);
64 static void pqi_retry_raid_bypass_requests(struct pqi_ctrl_info *ctrl_info);
65 static int pqi_scan_scsi_devices(struct pqi_ctrl_info *ctrl_info);
66 static void pqi_scan_start(struct Scsi_Host *shost);
67 static void pqi_start_io(struct pqi_ctrl_info *ctrl_info,
68         struct pqi_queue_group *queue_group, enum pqi_io_path path,
69         struct pqi_io_request *io_request);
70 static int pqi_submit_raid_request_synchronous(struct pqi_ctrl_info *ctrl_info,
71         struct pqi_iu_header *request, unsigned int flags,
72         struct pqi_raid_error_info *error_info, unsigned long timeout_msecs);
73 static int pqi_aio_submit_io(struct pqi_ctrl_info *ctrl_info,
74         struct scsi_cmnd *scmd, u32 aio_handle, u8 *cdb,
75         unsigned int cdb_length, struct pqi_queue_group *queue_group,
76         struct pqi_encryption_info *encryption_info, bool raid_bypass);
77
78 /* for flags argument to pqi_submit_raid_request_synchronous() */
79 #define PQI_SYNC_FLAGS_INTERRUPTABLE    0x1
80
81 static struct scsi_transport_template *pqi_sas_transport_template;
82
83 static atomic_t pqi_controller_count = ATOMIC_INIT(0);
84
85 enum pqi_lockup_action {
86         NONE,
87         REBOOT,
88         PANIC
89 };
90
91 static enum pqi_lockup_action pqi_lockup_action = NONE;
92
93 static struct {
94         enum pqi_lockup_action  action;
95         char                    *name;
96 } pqi_lockup_actions[] = {
97         {
98                 .action = NONE,
99                 .name = "none",
100         },
101         {
102                 .action = REBOOT,
103                 .name = "reboot",
104         },
105         {
106                 .action = PANIC,
107                 .name = "panic",
108         },
109 };
110
111 static unsigned int pqi_supported_event_types[] = {
112         PQI_EVENT_TYPE_HOTPLUG,
113         PQI_EVENT_TYPE_HARDWARE,
114         PQI_EVENT_TYPE_PHYSICAL_DEVICE,
115         PQI_EVENT_TYPE_LOGICAL_DEVICE,
116         PQI_EVENT_TYPE_AIO_STATE_CHANGE,
117         PQI_EVENT_TYPE_AIO_CONFIG_CHANGE,
118 };
119
120 static int pqi_disable_device_id_wildcards;
121 module_param_named(disable_device_id_wildcards,
122         pqi_disable_device_id_wildcards, int, 0644);
123 MODULE_PARM_DESC(disable_device_id_wildcards,
124         "Disable device ID wildcards.");
125
126 static int pqi_disable_heartbeat;
127 module_param_named(disable_heartbeat,
128         pqi_disable_heartbeat, int, 0644);
129 MODULE_PARM_DESC(disable_heartbeat,
130         "Disable heartbeat.");
131
132 static int pqi_disable_ctrl_shutdown;
133 module_param_named(disable_ctrl_shutdown,
134         pqi_disable_ctrl_shutdown, int, 0644);
135 MODULE_PARM_DESC(disable_ctrl_shutdown,
136         "Disable controller shutdown when controller locked up.");
137
138 static char *pqi_lockup_action_param;
139 module_param_named(lockup_action,
140         pqi_lockup_action_param, charp, 0644);
141 MODULE_PARM_DESC(lockup_action, "Action to take when controller locked up.\n"
142         "\t\tSupported: none, reboot, panic\n"
143         "\t\tDefault: none");
144
145 static char *raid_levels[] = {
146         "RAID-0",
147         "RAID-4",
148         "RAID-1(1+0)",
149         "RAID-5",
150         "RAID-5+1",
151         "RAID-ADG",
152         "RAID-1(ADM)",
153 };
154
155 static char *pqi_raid_level_to_string(u8 raid_level)
156 {
157         if (raid_level < ARRAY_SIZE(raid_levels))
158                 return raid_levels[raid_level];
159
160         return "RAID UNKNOWN";
161 }
162
163 #define SA_RAID_0               0
164 #define SA_RAID_4               1
165 #define SA_RAID_1               2       /* also used for RAID 10 */
166 #define SA_RAID_5               3       /* also used for RAID 50 */
167 #define SA_RAID_51              4
168 #define SA_RAID_6               5       /* also used for RAID 60 */
169 #define SA_RAID_ADM             6       /* also used for RAID 1+0 ADM */
170 #define SA_RAID_MAX             SA_RAID_ADM
171 #define SA_RAID_UNKNOWN         0xff
172
173 static inline void pqi_scsi_done(struct scsi_cmnd *scmd)
174 {
175         pqi_prep_for_scsi_done(scmd);
176         scmd->scsi_done(scmd);
177 }
178
179 static inline bool pqi_scsi3addr_equal(u8 *scsi3addr1, u8 *scsi3addr2)
180 {
181         return memcmp(scsi3addr1, scsi3addr2, 8) == 0;
182 }
183
184 static inline struct pqi_ctrl_info *shost_to_hba(struct Scsi_Host *shost)
185 {
186         void *hostdata = shost_priv(shost);
187
188         return *((struct pqi_ctrl_info **)hostdata);
189 }
190
191 static inline bool pqi_is_logical_device(struct pqi_scsi_dev *device)
192 {
193         return !device->is_physical_device;
194 }
195
196 static inline bool pqi_is_external_raid_addr(u8 *scsi3addr)
197 {
198         return scsi3addr[2] != 0;
199 }
200
201 static inline bool pqi_ctrl_offline(struct pqi_ctrl_info *ctrl_info)
202 {
203         return !ctrl_info->controller_online;
204 }
205
206 static inline void pqi_check_ctrl_health(struct pqi_ctrl_info *ctrl_info)
207 {
208         if (ctrl_info->controller_online)
209                 if (!sis_is_firmware_running(ctrl_info))
210                         pqi_take_ctrl_offline(ctrl_info);
211 }
212
213 static inline bool pqi_is_hba_lunid(u8 *scsi3addr)
214 {
215         return pqi_scsi3addr_equal(scsi3addr, RAID_CTLR_LUNID);
216 }
217
218 static inline enum pqi_ctrl_mode pqi_get_ctrl_mode(
219         struct pqi_ctrl_info *ctrl_info)
220 {
221         return sis_read_driver_scratch(ctrl_info);
222 }
223
224 static inline void pqi_save_ctrl_mode(struct pqi_ctrl_info *ctrl_info,
225         enum pqi_ctrl_mode mode)
226 {
227         sis_write_driver_scratch(ctrl_info, mode);
228 }
229
230 static inline void pqi_ctrl_block_requests(struct pqi_ctrl_info *ctrl_info)
231 {
232         ctrl_info->block_requests = true;
233         scsi_block_requests(ctrl_info->scsi_host);
234 }
235
236 static inline void pqi_ctrl_unblock_requests(struct pqi_ctrl_info *ctrl_info)
237 {
238         ctrl_info->block_requests = false;
239         wake_up_all(&ctrl_info->block_requests_wait);
240         pqi_retry_raid_bypass_requests(ctrl_info);
241         scsi_unblock_requests(ctrl_info->scsi_host);
242 }
243
244 static inline bool pqi_ctrl_blocked(struct pqi_ctrl_info *ctrl_info)
245 {
246         return ctrl_info->block_requests;
247 }
248
249 static unsigned long pqi_wait_if_ctrl_blocked(struct pqi_ctrl_info *ctrl_info,
250         unsigned long timeout_msecs)
251 {
252         unsigned long remaining_msecs;
253
254         if (!pqi_ctrl_blocked(ctrl_info))
255                 return timeout_msecs;
256
257         atomic_inc(&ctrl_info->num_blocked_threads);
258
259         if (timeout_msecs == NO_TIMEOUT) {
260                 wait_event(ctrl_info->block_requests_wait,
261                         !pqi_ctrl_blocked(ctrl_info));
262                 remaining_msecs = timeout_msecs;
263         } else {
264                 unsigned long remaining_jiffies;
265
266                 remaining_jiffies =
267                         wait_event_timeout(ctrl_info->block_requests_wait,
268                                 !pqi_ctrl_blocked(ctrl_info),
269                                 msecs_to_jiffies(timeout_msecs));
270                 remaining_msecs = jiffies_to_msecs(remaining_jiffies);
271         }
272
273         atomic_dec(&ctrl_info->num_blocked_threads);
274
275         return remaining_msecs;
276 }
277
278 static inline void pqi_ctrl_busy(struct pqi_ctrl_info *ctrl_info)
279 {
280         atomic_inc(&ctrl_info->num_busy_threads);
281 }
282
283 static inline void pqi_ctrl_unbusy(struct pqi_ctrl_info *ctrl_info)
284 {
285         atomic_dec(&ctrl_info->num_busy_threads);
286 }
287
288 static inline void pqi_ctrl_wait_until_quiesced(struct pqi_ctrl_info *ctrl_info)
289 {
290         while (atomic_read(&ctrl_info->num_busy_threads) >
291                 atomic_read(&ctrl_info->num_blocked_threads))
292                 usleep_range(1000, 2000);
293 }
294
295 static inline bool pqi_device_offline(struct pqi_scsi_dev *device)
296 {
297         return device->device_offline;
298 }
299
300 static inline void pqi_device_reset_start(struct pqi_scsi_dev *device)
301 {
302         device->in_reset = true;
303 }
304
305 static inline void pqi_device_reset_done(struct pqi_scsi_dev *device)
306 {
307         device->in_reset = false;
308 }
309
310 static inline bool pqi_device_in_reset(struct pqi_scsi_dev *device)
311 {
312         return device->in_reset;
313 }
314
315 static inline void pqi_schedule_rescan_worker_with_delay(
316         struct pqi_ctrl_info *ctrl_info, unsigned long delay)
317 {
318         if (pqi_ctrl_offline(ctrl_info))
319                 return;
320
321         schedule_delayed_work(&ctrl_info->rescan_work, delay);
322 }
323
324 static inline void pqi_schedule_rescan_worker(struct pqi_ctrl_info *ctrl_info)
325 {
326         pqi_schedule_rescan_worker_with_delay(ctrl_info, 0);
327 }
328
329 #define PQI_RESCAN_WORK_DELAY  (10 * HZ)
330
331 static inline void pqi_schedule_rescan_worker_delayed(
332         struct pqi_ctrl_info *ctrl_info)
333 {
334         pqi_schedule_rescan_worker_with_delay(ctrl_info, PQI_RESCAN_WORK_DELAY);
335 }
336
337 static inline void pqi_cancel_rescan_worker(struct pqi_ctrl_info *ctrl_info)
338 {
339         cancel_delayed_work_sync(&ctrl_info->rescan_work);
340 }
341
342 static inline u32 pqi_read_heartbeat_counter(struct pqi_ctrl_info *ctrl_info)
343 {
344         if (!ctrl_info->heartbeat_counter)
345                 return 0;
346
347         return readl(ctrl_info->heartbeat_counter);
348 }
349
350 static int pqi_map_single(struct pci_dev *pci_dev,
351         struct pqi_sg_descriptor *sg_descriptor, void *buffer,
352         size_t buffer_length, int data_direction)
353 {
354         dma_addr_t bus_address;
355
356         if (!buffer || buffer_length == 0 || data_direction == PCI_DMA_NONE)
357                 return 0;
358
359         bus_address = pci_map_single(pci_dev, buffer, buffer_length,
360                 data_direction);
361         if (pci_dma_mapping_error(pci_dev, bus_address))
362                 return -ENOMEM;
363
364         put_unaligned_le64((u64)bus_address, &sg_descriptor->address);
365         put_unaligned_le32(buffer_length, &sg_descriptor->length);
366         put_unaligned_le32(CISS_SG_LAST, &sg_descriptor->flags);
367
368         return 0;
369 }
370
371 static void pqi_pci_unmap(struct pci_dev *pci_dev,
372         struct pqi_sg_descriptor *descriptors, int num_descriptors,
373         int data_direction)
374 {
375         int i;
376
377         if (data_direction == PCI_DMA_NONE)
378                 return;
379
380         for (i = 0; i < num_descriptors; i++)
381                 pci_unmap_single(pci_dev,
382                         (dma_addr_t)get_unaligned_le64(&descriptors[i].address),
383                         get_unaligned_le32(&descriptors[i].length),
384                         data_direction);
385 }
386
387 static int pqi_build_raid_path_request(struct pqi_ctrl_info *ctrl_info,
388         struct pqi_raid_path_request *request, u8 cmd,
389         u8 *scsi3addr, void *buffer, size_t buffer_length,
390         u16 vpd_page, int *pci_direction)
391 {
392         u8 *cdb;
393         int pci_dir;
394
395         memset(request, 0, sizeof(*request));
396
397         request->header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
398         put_unaligned_le16(offsetof(struct pqi_raid_path_request,
399                 sg_descriptors[1]) - PQI_REQUEST_HEADER_LENGTH,
400                 &request->header.iu_length);
401         put_unaligned_le32(buffer_length, &request->buffer_length);
402         memcpy(request->lun_number, scsi3addr, sizeof(request->lun_number));
403         request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
404         request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
405
406         cdb = request->cdb;
407
408         switch (cmd) {
409         case INQUIRY:
410                 request->data_direction = SOP_READ_FLAG;
411                 cdb[0] = INQUIRY;
412                 if (vpd_page & VPD_PAGE) {
413                         cdb[1] = 0x1;
414                         cdb[2] = (u8)vpd_page;
415                 }
416                 cdb[4] = (u8)buffer_length;
417                 break;
418         case CISS_REPORT_LOG:
419         case CISS_REPORT_PHYS:
420                 request->data_direction = SOP_READ_FLAG;
421                 cdb[0] = cmd;
422                 if (cmd == CISS_REPORT_PHYS)
423                         cdb[1] = CISS_REPORT_PHYS_EXTENDED;
424                 else
425                         cdb[1] = CISS_REPORT_LOG_EXTENDED;
426                 put_unaligned_be32(buffer_length, &cdb[6]);
427                 break;
428         case CISS_GET_RAID_MAP:
429                 request->data_direction = SOP_READ_FLAG;
430                 cdb[0] = CISS_READ;
431                 cdb[1] = CISS_GET_RAID_MAP;
432                 put_unaligned_be32(buffer_length, &cdb[6]);
433                 break;
434         case SA_FLUSH_CACHE:
435                 request->data_direction = SOP_WRITE_FLAG;
436                 cdb[0] = BMIC_WRITE;
437                 cdb[6] = BMIC_FLUSH_CACHE;
438                 put_unaligned_be16(buffer_length, &cdb[7]);
439                 break;
440         case BMIC_IDENTIFY_CONTROLLER:
441         case BMIC_IDENTIFY_PHYSICAL_DEVICE:
442                 request->data_direction = SOP_READ_FLAG;
443                 cdb[0] = BMIC_READ;
444                 cdb[6] = cmd;
445                 put_unaligned_be16(buffer_length, &cdb[7]);
446                 break;
447         case BMIC_WRITE_HOST_WELLNESS:
448                 request->data_direction = SOP_WRITE_FLAG;
449                 cdb[0] = BMIC_WRITE;
450                 cdb[6] = cmd;
451                 put_unaligned_be16(buffer_length, &cdb[7]);
452                 break;
453         default:
454                 dev_err(&ctrl_info->pci_dev->dev, "unknown command 0x%c\n",
455                         cmd);
456                 break;
457         }
458
459         switch (request->data_direction) {
460         case SOP_READ_FLAG:
461                 pci_dir = PCI_DMA_FROMDEVICE;
462                 break;
463         case SOP_WRITE_FLAG:
464                 pci_dir = PCI_DMA_TODEVICE;
465                 break;
466         case SOP_NO_DIRECTION_FLAG:
467                 pci_dir = PCI_DMA_NONE;
468                 break;
469         default:
470                 pci_dir = PCI_DMA_BIDIRECTIONAL;
471                 break;
472         }
473
474         *pci_direction = pci_dir;
475
476         return pqi_map_single(ctrl_info->pci_dev, &request->sg_descriptors[0],
477                 buffer, buffer_length, pci_dir);
478 }
479
480 static inline void pqi_reinit_io_request(struct pqi_io_request *io_request)
481 {
482         io_request->scmd = NULL;
483         io_request->status = 0;
484         io_request->error_info = NULL;
485         io_request->raid_bypass = false;
486 }
487
488 static struct pqi_io_request *pqi_alloc_io_request(
489         struct pqi_ctrl_info *ctrl_info)
490 {
491         struct pqi_io_request *io_request;
492         u16 i = ctrl_info->next_io_request_slot;        /* benignly racy */
493
494         while (1) {
495                 io_request = &ctrl_info->io_request_pool[i];
496                 if (atomic_inc_return(&io_request->refcount) == 1)
497                         break;
498                 atomic_dec(&io_request->refcount);
499                 i = (i + 1) % ctrl_info->max_io_slots;
500         }
501
502         /* benignly racy */
503         ctrl_info->next_io_request_slot = (i + 1) % ctrl_info->max_io_slots;
504
505         pqi_reinit_io_request(io_request);
506
507         return io_request;
508 }
509
510 static void pqi_free_io_request(struct pqi_io_request *io_request)
511 {
512         atomic_dec(&io_request->refcount);
513 }
514
515 static int pqi_identify_controller(struct pqi_ctrl_info *ctrl_info,
516         struct bmic_identify_controller *buffer)
517 {
518         int rc;
519         int pci_direction;
520         struct pqi_raid_path_request request;
521
522         rc = pqi_build_raid_path_request(ctrl_info, &request,
523                 BMIC_IDENTIFY_CONTROLLER, RAID_CTLR_LUNID, buffer,
524                 sizeof(*buffer), 0, &pci_direction);
525         if (rc)
526                 return rc;
527
528         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0,
529                 NULL, NO_TIMEOUT);
530
531         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
532                 pci_direction);
533
534         return rc;
535 }
536
537 static int pqi_scsi_inquiry(struct pqi_ctrl_info *ctrl_info,
538         u8 *scsi3addr, u16 vpd_page, void *buffer, size_t buffer_length)
539 {
540         int rc;
541         int pci_direction;
542         struct pqi_raid_path_request request;
543
544         rc = pqi_build_raid_path_request(ctrl_info, &request,
545                 INQUIRY, scsi3addr, buffer, buffer_length, vpd_page,
546                 &pci_direction);
547         if (rc)
548                 return rc;
549
550         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0,
551                 NULL, NO_TIMEOUT);
552
553         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
554                 pci_direction);
555
556         return rc;
557 }
558
559 static int pqi_identify_physical_device(struct pqi_ctrl_info *ctrl_info,
560         struct pqi_scsi_dev *device,
561         struct bmic_identify_physical_device *buffer,
562         size_t buffer_length)
563 {
564         int rc;
565         int pci_direction;
566         u16 bmic_device_index;
567         struct pqi_raid_path_request request;
568
569         rc = pqi_build_raid_path_request(ctrl_info, &request,
570                 BMIC_IDENTIFY_PHYSICAL_DEVICE, RAID_CTLR_LUNID, buffer,
571                 buffer_length, 0, &pci_direction);
572         if (rc)
573                 return rc;
574
575         bmic_device_index = CISS_GET_DRIVE_NUMBER(device->scsi3addr);
576         request.cdb[2] = (u8)bmic_device_index;
577         request.cdb[9] = (u8)(bmic_device_index >> 8);
578
579         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
580                 0, NULL, NO_TIMEOUT);
581
582         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
583                 pci_direction);
584
585         return rc;
586 }
587
588 static int pqi_flush_cache(struct pqi_ctrl_info *ctrl_info,
589         enum bmic_flush_cache_shutdown_event shutdown_event)
590 {
591         int rc;
592         struct pqi_raid_path_request request;
593         int pci_direction;
594         struct bmic_flush_cache *flush_cache;
595
596         /*
597          * Don't bother trying to flush the cache if the controller is
598          * locked up.
599          */
600         if (pqi_ctrl_offline(ctrl_info))
601                 return -ENXIO;
602
603         flush_cache = kzalloc(sizeof(*flush_cache), GFP_KERNEL);
604         if (!flush_cache)
605                 return -ENOMEM;
606
607         flush_cache->shutdown_event = shutdown_event;
608
609         rc = pqi_build_raid_path_request(ctrl_info, &request,
610                 SA_FLUSH_CACHE, RAID_CTLR_LUNID, flush_cache,
611                 sizeof(*flush_cache), 0, &pci_direction);
612         if (rc)
613                 goto out;
614
615         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
616                 0, NULL, NO_TIMEOUT);
617
618         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
619                 pci_direction);
620
621 out:
622         kfree(flush_cache);
623
624         return rc;
625 }
626
627 static int pqi_write_host_wellness(struct pqi_ctrl_info *ctrl_info,
628         void *buffer, size_t buffer_length)
629 {
630         int rc;
631         struct pqi_raid_path_request request;
632         int pci_direction;
633
634         rc = pqi_build_raid_path_request(ctrl_info, &request,
635                 BMIC_WRITE_HOST_WELLNESS, RAID_CTLR_LUNID, buffer,
636                 buffer_length, 0, &pci_direction);
637         if (rc)
638                 return rc;
639
640         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
641                 0, NULL, NO_TIMEOUT);
642
643         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
644                 pci_direction);
645
646         return rc;
647 }
648
649 #pragma pack(1)
650
651 struct bmic_host_wellness_driver_version {
652         u8      start_tag[4];
653         u8      driver_version_tag[2];
654         __le16  driver_version_length;
655         char    driver_version[32];
656         u8      dont_write_tag[2];
657         u8      end_tag[2];
658 };
659
660 #pragma pack()
661
662 static int pqi_write_driver_version_to_host_wellness(
663         struct pqi_ctrl_info *ctrl_info)
664 {
665         int rc;
666         struct bmic_host_wellness_driver_version *buffer;
667         size_t buffer_length;
668
669         buffer_length = sizeof(*buffer);
670
671         buffer = kmalloc(buffer_length, GFP_KERNEL);
672         if (!buffer)
673                 return -ENOMEM;
674
675         buffer->start_tag[0] = '<';
676         buffer->start_tag[1] = 'H';
677         buffer->start_tag[2] = 'W';
678         buffer->start_tag[3] = '>';
679         buffer->driver_version_tag[0] = 'D';
680         buffer->driver_version_tag[1] = 'V';
681         put_unaligned_le16(sizeof(buffer->driver_version),
682                 &buffer->driver_version_length);
683         strncpy(buffer->driver_version, "Linux " DRIVER_VERSION,
684                 sizeof(buffer->driver_version) - 1);
685         buffer->driver_version[sizeof(buffer->driver_version) - 1] = '\0';
686         buffer->dont_write_tag[0] = 'D';
687         buffer->dont_write_tag[1] = 'W';
688         buffer->end_tag[0] = 'Z';
689         buffer->end_tag[1] = 'Z';
690
691         rc = pqi_write_host_wellness(ctrl_info, buffer, buffer_length);
692
693         kfree(buffer);
694
695         return rc;
696 }
697
698 #pragma pack(1)
699
700 struct bmic_host_wellness_time {
701         u8      start_tag[4];
702         u8      time_tag[2];
703         __le16  time_length;
704         u8      time[8];
705         u8      dont_write_tag[2];
706         u8      end_tag[2];
707 };
708
709 #pragma pack()
710
711 static int pqi_write_current_time_to_host_wellness(
712         struct pqi_ctrl_info *ctrl_info)
713 {
714         int rc;
715         struct bmic_host_wellness_time *buffer;
716         size_t buffer_length;
717         time64_t local_time;
718         unsigned int year;
719         struct tm tm;
720
721         buffer_length = sizeof(*buffer);
722
723         buffer = kmalloc(buffer_length, GFP_KERNEL);
724         if (!buffer)
725                 return -ENOMEM;
726
727         buffer->start_tag[0] = '<';
728         buffer->start_tag[1] = 'H';
729         buffer->start_tag[2] = 'W';
730         buffer->start_tag[3] = '>';
731         buffer->time_tag[0] = 'T';
732         buffer->time_tag[1] = 'D';
733         put_unaligned_le16(sizeof(buffer->time),
734                 &buffer->time_length);
735
736         local_time = ktime_get_real_seconds();
737         time64_to_tm(local_time, -sys_tz.tz_minuteswest * 60, &tm);
738         year = tm.tm_year + 1900;
739
740         buffer->time[0] = bin2bcd(tm.tm_hour);
741         buffer->time[1] = bin2bcd(tm.tm_min);
742         buffer->time[2] = bin2bcd(tm.tm_sec);
743         buffer->time[3] = 0;
744         buffer->time[4] = bin2bcd(tm.tm_mon + 1);
745         buffer->time[5] = bin2bcd(tm.tm_mday);
746         buffer->time[6] = bin2bcd(year / 100);
747         buffer->time[7] = bin2bcd(year % 100);
748
749         buffer->dont_write_tag[0] = 'D';
750         buffer->dont_write_tag[1] = 'W';
751         buffer->end_tag[0] = 'Z';
752         buffer->end_tag[1] = 'Z';
753
754         rc = pqi_write_host_wellness(ctrl_info, buffer, buffer_length);
755
756         kfree(buffer);
757
758         return rc;
759 }
760
761 #define PQI_UPDATE_TIME_WORK_INTERVAL   (24UL * 60 * 60 * HZ)
762
763 static void pqi_update_time_worker(struct work_struct *work)
764 {
765         int rc;
766         struct pqi_ctrl_info *ctrl_info;
767
768         ctrl_info = container_of(to_delayed_work(work), struct pqi_ctrl_info,
769                 update_time_work);
770
771         if (pqi_ctrl_offline(ctrl_info))
772                 return;
773
774         rc = pqi_write_current_time_to_host_wellness(ctrl_info);
775         if (rc)
776                 dev_warn(&ctrl_info->pci_dev->dev,
777                         "error updating time on controller\n");
778
779         schedule_delayed_work(&ctrl_info->update_time_work,
780                 PQI_UPDATE_TIME_WORK_INTERVAL);
781 }
782
783 static inline void pqi_schedule_update_time_worker(
784         struct pqi_ctrl_info *ctrl_info)
785 {
786         schedule_delayed_work(&ctrl_info->update_time_work, 0);
787 }
788
789 static inline void pqi_cancel_update_time_worker(
790         struct pqi_ctrl_info *ctrl_info)
791 {
792         cancel_delayed_work_sync(&ctrl_info->update_time_work);
793 }
794
795 static int pqi_report_luns(struct pqi_ctrl_info *ctrl_info, u8 cmd,
796         void *buffer, size_t buffer_length)
797 {
798         int rc;
799         int pci_direction;
800         struct pqi_raid_path_request request;
801
802         rc = pqi_build_raid_path_request(ctrl_info, &request,
803                 cmd, RAID_CTLR_LUNID, buffer, buffer_length, 0, &pci_direction);
804         if (rc)
805                 return rc;
806
807         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0,
808                 NULL, NO_TIMEOUT);
809
810         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
811                 pci_direction);
812
813         return rc;
814 }
815
816 static int pqi_report_phys_logical_luns(struct pqi_ctrl_info *ctrl_info, u8 cmd,
817         void **buffer)
818 {
819         int rc;
820         size_t lun_list_length;
821         size_t lun_data_length;
822         size_t new_lun_list_length;
823         void *lun_data = NULL;
824         struct report_lun_header *report_lun_header;
825
826         report_lun_header = kmalloc(sizeof(*report_lun_header), GFP_KERNEL);
827         if (!report_lun_header) {
828                 rc = -ENOMEM;
829                 goto out;
830         }
831
832         rc = pqi_report_luns(ctrl_info, cmd, report_lun_header,
833                 sizeof(*report_lun_header));
834         if (rc)
835                 goto out;
836
837         lun_list_length = get_unaligned_be32(&report_lun_header->list_length);
838
839 again:
840         lun_data_length = sizeof(struct report_lun_header) + lun_list_length;
841
842         lun_data = kmalloc(lun_data_length, GFP_KERNEL);
843         if (!lun_data) {
844                 rc = -ENOMEM;
845                 goto out;
846         }
847
848         if (lun_list_length == 0) {
849                 memcpy(lun_data, report_lun_header, sizeof(*report_lun_header));
850                 goto out;
851         }
852
853         rc = pqi_report_luns(ctrl_info, cmd, lun_data, lun_data_length);
854         if (rc)
855                 goto out;
856
857         new_lun_list_length = get_unaligned_be32(
858                 &((struct report_lun_header *)lun_data)->list_length);
859
860         if (new_lun_list_length > lun_list_length) {
861                 lun_list_length = new_lun_list_length;
862                 kfree(lun_data);
863                 goto again;
864         }
865
866 out:
867         kfree(report_lun_header);
868
869         if (rc) {
870                 kfree(lun_data);
871                 lun_data = NULL;
872         }
873
874         *buffer = lun_data;
875
876         return rc;
877 }
878
879 static inline int pqi_report_phys_luns(struct pqi_ctrl_info *ctrl_info,
880         void **buffer)
881 {
882         return pqi_report_phys_logical_luns(ctrl_info, CISS_REPORT_PHYS,
883                 buffer);
884 }
885
886 static inline int pqi_report_logical_luns(struct pqi_ctrl_info *ctrl_info,
887         void **buffer)
888 {
889         return pqi_report_phys_logical_luns(ctrl_info, CISS_REPORT_LOG, buffer);
890 }
891
892 static int pqi_get_device_lists(struct pqi_ctrl_info *ctrl_info,
893         struct report_phys_lun_extended **physdev_list,
894         struct report_log_lun_extended **logdev_list)
895 {
896         int rc;
897         size_t logdev_list_length;
898         size_t logdev_data_length;
899         struct report_log_lun_extended *internal_logdev_list;
900         struct report_log_lun_extended *logdev_data;
901         struct report_lun_header report_lun_header;
902
903         rc = pqi_report_phys_luns(ctrl_info, (void **)physdev_list);
904         if (rc)
905                 dev_err(&ctrl_info->pci_dev->dev,
906                         "report physical LUNs failed\n");
907
908         rc = pqi_report_logical_luns(ctrl_info, (void **)logdev_list);
909         if (rc)
910                 dev_err(&ctrl_info->pci_dev->dev,
911                         "report logical LUNs failed\n");
912
913         /*
914          * Tack the controller itself onto the end of the logical device list.
915          */
916
917         logdev_data = *logdev_list;
918
919         if (logdev_data) {
920                 logdev_list_length =
921                         get_unaligned_be32(&logdev_data->header.list_length);
922         } else {
923                 memset(&report_lun_header, 0, sizeof(report_lun_header));
924                 logdev_data =
925                         (struct report_log_lun_extended *)&report_lun_header;
926                 logdev_list_length = 0;
927         }
928
929         logdev_data_length = sizeof(struct report_lun_header) +
930                 logdev_list_length;
931
932         internal_logdev_list = kmalloc(logdev_data_length +
933                 sizeof(struct report_log_lun_extended), GFP_KERNEL);
934         if (!internal_logdev_list) {
935                 kfree(*logdev_list);
936                 *logdev_list = NULL;
937                 return -ENOMEM;
938         }
939
940         memcpy(internal_logdev_list, logdev_data, logdev_data_length);
941         memset((u8 *)internal_logdev_list + logdev_data_length, 0,
942                 sizeof(struct report_log_lun_extended_entry));
943         put_unaligned_be32(logdev_list_length +
944                 sizeof(struct report_log_lun_extended_entry),
945                 &internal_logdev_list->header.list_length);
946
947         kfree(*logdev_list);
948         *logdev_list = internal_logdev_list;
949
950         return 0;
951 }
952
953 static inline void pqi_set_bus_target_lun(struct pqi_scsi_dev *device,
954         int bus, int target, int lun)
955 {
956         device->bus = bus;
957         device->target = target;
958         device->lun = lun;
959 }
960
961 static void pqi_assign_bus_target_lun(struct pqi_scsi_dev *device)
962 {
963         u8 *scsi3addr;
964         u32 lunid;
965         int bus;
966         int target;
967         int lun;
968
969         scsi3addr = device->scsi3addr;
970         lunid = get_unaligned_le32(scsi3addr);
971
972         if (pqi_is_hba_lunid(scsi3addr)) {
973                 /* The specified device is the controller. */
974                 pqi_set_bus_target_lun(device, PQI_HBA_BUS, 0, lunid & 0x3fff);
975                 device->target_lun_valid = true;
976                 return;
977         }
978
979         if (pqi_is_logical_device(device)) {
980                 if (device->is_external_raid_device) {
981                         bus = PQI_EXTERNAL_RAID_VOLUME_BUS;
982                         target = (lunid >> 16) & 0x3fff;
983                         lun = lunid & 0xff;
984                 } else {
985                         bus = PQI_RAID_VOLUME_BUS;
986                         target = 0;
987                         lun = lunid & 0x3fff;
988                 }
989                 pqi_set_bus_target_lun(device, bus, target, lun);
990                 device->target_lun_valid = true;
991                 return;
992         }
993
994         /*
995          * Defer target and LUN assignment for non-controller physical devices
996          * because the SAS transport layer will make these assignments later.
997          */
998         pqi_set_bus_target_lun(device, PQI_PHYSICAL_DEVICE_BUS, 0, 0);
999 }
1000
1001 static void pqi_get_raid_level(struct pqi_ctrl_info *ctrl_info,
1002         struct pqi_scsi_dev *device)
1003 {
1004         int rc;
1005         u8 raid_level;
1006         u8 *buffer;
1007
1008         raid_level = SA_RAID_UNKNOWN;
1009
1010         buffer = kmalloc(64, GFP_KERNEL);
1011         if (buffer) {
1012                 rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1013                         VPD_PAGE | CISS_VPD_LV_DEVICE_GEOMETRY, buffer, 64);
1014                 if (rc == 0) {
1015                         raid_level = buffer[8];
1016                         if (raid_level > SA_RAID_MAX)
1017                                 raid_level = SA_RAID_UNKNOWN;
1018                 }
1019                 kfree(buffer);
1020         }
1021
1022         device->raid_level = raid_level;
1023 }
1024
1025 static int pqi_validate_raid_map(struct pqi_ctrl_info *ctrl_info,
1026         struct pqi_scsi_dev *device, struct raid_map *raid_map)
1027 {
1028         char *err_msg;
1029         u32 raid_map_size;
1030         u32 r5or6_blocks_per_row;
1031         unsigned int num_phys_disks;
1032         unsigned int num_raid_map_entries;
1033
1034         raid_map_size = get_unaligned_le32(&raid_map->structure_size);
1035
1036         if (raid_map_size < offsetof(struct raid_map, disk_data)) {
1037                 err_msg = "RAID map too small";
1038                 goto bad_raid_map;
1039         }
1040
1041         if (raid_map_size > sizeof(*raid_map)) {
1042                 err_msg = "RAID map too large";
1043                 goto bad_raid_map;
1044         }
1045
1046         num_phys_disks = get_unaligned_le16(&raid_map->layout_map_count) *
1047                 (get_unaligned_le16(&raid_map->data_disks_per_row) +
1048                 get_unaligned_le16(&raid_map->metadata_disks_per_row));
1049         num_raid_map_entries = num_phys_disks *
1050                 get_unaligned_le16(&raid_map->row_cnt);
1051
1052         if (num_raid_map_entries > RAID_MAP_MAX_ENTRIES) {
1053                 err_msg = "invalid number of map entries in RAID map";
1054                 goto bad_raid_map;
1055         }
1056
1057         if (device->raid_level == SA_RAID_1) {
1058                 if (get_unaligned_le16(&raid_map->layout_map_count) != 2) {
1059                         err_msg = "invalid RAID-1 map";
1060                         goto bad_raid_map;
1061                 }
1062         } else if (device->raid_level == SA_RAID_ADM) {
1063                 if (get_unaligned_le16(&raid_map->layout_map_count) != 3) {
1064                         err_msg = "invalid RAID-1(ADM) map";
1065                         goto bad_raid_map;
1066                 }
1067         } else if ((device->raid_level == SA_RAID_5 ||
1068                 device->raid_level == SA_RAID_6) &&
1069                 get_unaligned_le16(&raid_map->layout_map_count) > 1) {
1070                 /* RAID 50/60 */
1071                 r5or6_blocks_per_row =
1072                         get_unaligned_le16(&raid_map->strip_size) *
1073                         get_unaligned_le16(&raid_map->data_disks_per_row);
1074                 if (r5or6_blocks_per_row == 0) {
1075                         err_msg = "invalid RAID-5 or RAID-6 map";
1076                         goto bad_raid_map;
1077                 }
1078         }
1079
1080         return 0;
1081
1082 bad_raid_map:
1083         dev_warn(&ctrl_info->pci_dev->dev,
1084                 "logical device %08x%08x %s\n",
1085                 *((u32 *)&device->scsi3addr),
1086                 *((u32 *)&device->scsi3addr[4]), err_msg);
1087
1088         return -EINVAL;
1089 }
1090
1091 static int pqi_get_raid_map(struct pqi_ctrl_info *ctrl_info,
1092         struct pqi_scsi_dev *device)
1093 {
1094         int rc;
1095         int pci_direction;
1096         struct pqi_raid_path_request request;
1097         struct raid_map *raid_map;
1098
1099         raid_map = kmalloc(sizeof(*raid_map), GFP_KERNEL);
1100         if (!raid_map)
1101                 return -ENOMEM;
1102
1103         rc = pqi_build_raid_path_request(ctrl_info, &request,
1104                 CISS_GET_RAID_MAP, device->scsi3addr, raid_map,
1105                 sizeof(*raid_map), 0, &pci_direction);
1106         if (rc)
1107                 goto error;
1108
1109         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0,
1110                 NULL, NO_TIMEOUT);
1111
1112         pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
1113                 pci_direction);
1114
1115         if (rc)
1116                 goto error;
1117
1118         rc = pqi_validate_raid_map(ctrl_info, device, raid_map);
1119         if (rc)
1120                 goto error;
1121
1122         device->raid_map = raid_map;
1123
1124         return 0;
1125
1126 error:
1127         kfree(raid_map);
1128
1129         return rc;
1130 }
1131
1132 static void pqi_get_raid_bypass_status(struct pqi_ctrl_info *ctrl_info,
1133         struct pqi_scsi_dev *device)
1134 {
1135         int rc;
1136         u8 *buffer;
1137         u8 bypass_status;
1138
1139         buffer = kmalloc(64, GFP_KERNEL);
1140         if (!buffer)
1141                 return;
1142
1143         rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1144                 VPD_PAGE | CISS_VPD_LV_BYPASS_STATUS, buffer, 64);
1145         if (rc)
1146                 goto out;
1147
1148 #define RAID_BYPASS_STATUS      4
1149 #define RAID_BYPASS_CONFIGURED  0x1
1150 #define RAID_BYPASS_ENABLED     0x2
1151
1152         bypass_status = buffer[RAID_BYPASS_STATUS];
1153         device->raid_bypass_configured =
1154                 (bypass_status & RAID_BYPASS_CONFIGURED) != 0;
1155         if (device->raid_bypass_configured &&
1156                 (bypass_status & RAID_BYPASS_ENABLED) &&
1157                 pqi_get_raid_map(ctrl_info, device) == 0)
1158                 device->raid_bypass_enabled = true;
1159
1160 out:
1161         kfree(buffer);
1162 }
1163
1164 /*
1165  * Use vendor-specific VPD to determine online/offline status of a volume.
1166  */
1167
1168 static void pqi_get_volume_status(struct pqi_ctrl_info *ctrl_info,
1169         struct pqi_scsi_dev *device)
1170 {
1171         int rc;
1172         size_t page_length;
1173         u8 volume_status = CISS_LV_STATUS_UNAVAILABLE;
1174         bool volume_offline = true;
1175         u32 volume_flags;
1176         struct ciss_vpd_logical_volume_status *vpd;
1177
1178         vpd = kmalloc(sizeof(*vpd), GFP_KERNEL);
1179         if (!vpd)
1180                 goto no_buffer;
1181
1182         rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1183                 VPD_PAGE | CISS_VPD_LV_STATUS, vpd, sizeof(*vpd));
1184         if (rc)
1185                 goto out;
1186
1187         if (vpd->page_code != CISS_VPD_LV_STATUS)
1188                 goto out;
1189
1190         page_length = offsetof(struct ciss_vpd_logical_volume_status,
1191                 volume_status) + vpd->page_length;
1192         if (page_length < sizeof(*vpd))
1193                 goto out;
1194
1195         volume_status = vpd->volume_status;
1196         volume_flags = get_unaligned_be32(&vpd->flags);
1197         volume_offline = (volume_flags & CISS_LV_FLAGS_NO_HOST_IO) != 0;
1198
1199 out:
1200         kfree(vpd);
1201 no_buffer:
1202         device->volume_status = volume_status;
1203         device->volume_offline = volume_offline;
1204 }
1205
1206 #define PQI_INQUIRY_PAGE0_RETRIES       3
1207
1208 static int pqi_get_device_info(struct pqi_ctrl_info *ctrl_info,
1209         struct pqi_scsi_dev *device)
1210 {
1211         int rc;
1212         u8 *buffer;
1213         unsigned int retries;
1214
1215         buffer = kmalloc(64, GFP_KERNEL);
1216         if (!buffer)
1217                 return -ENOMEM;
1218
1219         /* Send an inquiry to the device to see what it is. */
1220         for (retries = 0;;) {
1221                 rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr, 0,
1222                         buffer, 64);
1223                 if (rc == 0)
1224                         break;
1225                 if (pqi_is_logical_device(device) ||
1226                         rc != PQI_CMD_STATUS_ABORTED ||
1227                         ++retries > PQI_INQUIRY_PAGE0_RETRIES)
1228                         goto out;
1229         }
1230
1231         scsi_sanitize_inquiry_string(&buffer[8], 8);
1232         scsi_sanitize_inquiry_string(&buffer[16], 16);
1233
1234         device->devtype = buffer[0] & 0x1f;
1235         memcpy(device->vendor, &buffer[8], sizeof(device->vendor));
1236         memcpy(device->model, &buffer[16], sizeof(device->model));
1237
1238         if (pqi_is_logical_device(device) && device->devtype == TYPE_DISK) {
1239                 if (device->is_external_raid_device) {
1240                         device->raid_level = SA_RAID_UNKNOWN;
1241                         device->volume_status = CISS_LV_OK;
1242                         device->volume_offline = false;
1243                 } else {
1244                         pqi_get_raid_level(ctrl_info, device);
1245                         pqi_get_raid_bypass_status(ctrl_info, device);
1246                         pqi_get_volume_status(ctrl_info, device);
1247                 }
1248         }
1249
1250 out:
1251         kfree(buffer);
1252
1253         return rc;
1254 }
1255
1256 static void pqi_get_physical_disk_info(struct pqi_ctrl_info *ctrl_info,
1257         struct pqi_scsi_dev *device,
1258         struct bmic_identify_physical_device *id_phys)
1259 {
1260         int rc;
1261
1262         memset(id_phys, 0, sizeof(*id_phys));
1263
1264         rc = pqi_identify_physical_device(ctrl_info, device,
1265                 id_phys, sizeof(*id_phys));
1266         if (rc) {
1267                 device->queue_depth = PQI_PHYSICAL_DISK_DEFAULT_MAX_QUEUE_DEPTH;
1268                 return;
1269         }
1270
1271         device->queue_depth =
1272                 get_unaligned_le16(&id_phys->current_queue_depth_limit);
1273         device->device_type = id_phys->device_type;
1274         device->active_path_index = id_phys->active_path_number;
1275         device->path_map = id_phys->redundant_path_present_map;
1276         memcpy(&device->box,
1277                 &id_phys->alternate_paths_phys_box_on_port,
1278                 sizeof(device->box));
1279         memcpy(&device->phys_connector,
1280                 &id_phys->alternate_paths_phys_connector,
1281                 sizeof(device->phys_connector));
1282         device->bay = id_phys->phys_bay_in_box;
1283 }
1284
1285 static void pqi_show_volume_status(struct pqi_ctrl_info *ctrl_info,
1286         struct pqi_scsi_dev *device)
1287 {
1288         char *status;
1289         static const char unknown_state_str[] =
1290                 "Volume is in an unknown state (%u)";
1291         char unknown_state_buffer[sizeof(unknown_state_str) + 10];
1292
1293         switch (device->volume_status) {
1294         case CISS_LV_OK:
1295                 status = "Volume online";
1296                 break;
1297         case CISS_LV_FAILED:
1298                 status = "Volume failed";
1299                 break;
1300         case CISS_LV_NOT_CONFIGURED:
1301                 status = "Volume not configured";
1302                 break;
1303         case CISS_LV_DEGRADED:
1304                 status = "Volume degraded";
1305                 break;
1306         case CISS_LV_READY_FOR_RECOVERY:
1307                 status = "Volume ready for recovery operation";
1308                 break;
1309         case CISS_LV_UNDERGOING_RECOVERY:
1310                 status = "Volume undergoing recovery";
1311                 break;
1312         case CISS_LV_WRONG_PHYSICAL_DRIVE_REPLACED:
1313                 status = "Wrong physical drive was replaced";
1314                 break;
1315         case CISS_LV_PHYSICAL_DRIVE_CONNECTION_PROBLEM:
1316                 status = "A physical drive not properly connected";
1317                 break;
1318         case CISS_LV_HARDWARE_OVERHEATING:
1319                 status = "Hardware is overheating";
1320                 break;
1321         case CISS_LV_HARDWARE_HAS_OVERHEATED:
1322                 status = "Hardware has overheated";
1323                 break;
1324         case CISS_LV_UNDERGOING_EXPANSION:
1325                 status = "Volume undergoing expansion";
1326                 break;
1327         case CISS_LV_NOT_AVAILABLE:
1328                 status = "Volume waiting for transforming volume";
1329                 break;
1330         case CISS_LV_QUEUED_FOR_EXPANSION:
1331                 status = "Volume queued for expansion";
1332                 break;
1333         case CISS_LV_DISABLED_SCSI_ID_CONFLICT:
1334                 status = "Volume disabled due to SCSI ID conflict";
1335                 break;
1336         case CISS_LV_EJECTED:
1337                 status = "Volume has been ejected";
1338                 break;
1339         case CISS_LV_UNDERGOING_ERASE:
1340                 status = "Volume undergoing background erase";
1341                 break;
1342         case CISS_LV_READY_FOR_PREDICTIVE_SPARE_REBUILD:
1343                 status = "Volume ready for predictive spare rebuild";
1344                 break;
1345         case CISS_LV_UNDERGOING_RPI:
1346                 status = "Volume undergoing rapid parity initialization";
1347                 break;
1348         case CISS_LV_PENDING_RPI:
1349                 status = "Volume queued for rapid parity initialization";
1350                 break;
1351         case CISS_LV_ENCRYPTED_NO_KEY:
1352                 status = "Encrypted volume inaccessible - key not present";
1353                 break;
1354         case CISS_LV_UNDERGOING_ENCRYPTION:
1355                 status = "Volume undergoing encryption process";
1356                 break;
1357         case CISS_LV_UNDERGOING_ENCRYPTION_REKEYING:
1358                 status = "Volume undergoing encryption re-keying process";
1359                 break;
1360         case CISS_LV_ENCRYPTED_IN_NON_ENCRYPTED_CONTROLLER:
1361                 status = "Volume encrypted but encryption is disabled";
1362                 break;
1363         case CISS_LV_PENDING_ENCRYPTION:
1364                 status = "Volume pending migration to encrypted state";
1365                 break;
1366         case CISS_LV_PENDING_ENCRYPTION_REKEYING:
1367                 status = "Volume pending encryption rekeying";
1368                 break;
1369         case CISS_LV_NOT_SUPPORTED:
1370                 status = "Volume not supported on this controller";
1371                 break;
1372         case CISS_LV_STATUS_UNAVAILABLE:
1373                 status = "Volume status not available";
1374                 break;
1375         default:
1376                 snprintf(unknown_state_buffer, sizeof(unknown_state_buffer),
1377                         unknown_state_str, device->volume_status);
1378                 status = unknown_state_buffer;
1379                 break;
1380         }
1381
1382         dev_info(&ctrl_info->pci_dev->dev,
1383                 "scsi %d:%d:%d:%d %s\n",
1384                 ctrl_info->scsi_host->host_no,
1385                 device->bus, device->target, device->lun, status);
1386 }
1387
1388 static void pqi_rescan_worker(struct work_struct *work)
1389 {
1390         struct pqi_ctrl_info *ctrl_info;
1391
1392         ctrl_info = container_of(to_delayed_work(work), struct pqi_ctrl_info,
1393                 rescan_work);
1394
1395         pqi_scan_scsi_devices(ctrl_info);
1396 }
1397
1398 static int pqi_add_device(struct pqi_ctrl_info *ctrl_info,
1399         struct pqi_scsi_dev *device)
1400 {
1401         int rc;
1402
1403         if (pqi_is_logical_device(device))
1404                 rc = scsi_add_device(ctrl_info->scsi_host, device->bus,
1405                         device->target, device->lun);
1406         else
1407                 rc = pqi_add_sas_device(ctrl_info->sas_host, device);
1408
1409         return rc;
1410 }
1411
1412 static inline void pqi_remove_device(struct pqi_ctrl_info *ctrl_info,
1413         struct pqi_scsi_dev *device)
1414 {
1415         if (pqi_is_logical_device(device))
1416                 scsi_remove_device(device->sdev);
1417         else
1418                 pqi_remove_sas_device(device);
1419 }
1420
1421 /* Assumes the SCSI device list lock is held. */
1422
1423 static struct pqi_scsi_dev *pqi_find_scsi_dev(struct pqi_ctrl_info *ctrl_info,
1424         int bus, int target, int lun)
1425 {
1426         struct pqi_scsi_dev *device;
1427
1428         list_for_each_entry(device, &ctrl_info->scsi_device_list,
1429                 scsi_device_list_entry)
1430                 if (device->bus == bus && device->target == target &&
1431                         device->lun == lun)
1432                         return device;
1433
1434         return NULL;
1435 }
1436
1437 static inline bool pqi_device_equal(struct pqi_scsi_dev *dev1,
1438         struct pqi_scsi_dev *dev2)
1439 {
1440         if (dev1->is_physical_device != dev2->is_physical_device)
1441                 return false;
1442
1443         if (dev1->is_physical_device)
1444                 return dev1->wwid == dev2->wwid;
1445
1446         return memcmp(dev1->volume_id, dev2->volume_id,
1447                 sizeof(dev1->volume_id)) == 0;
1448 }
1449
1450 enum pqi_find_result {
1451         DEVICE_NOT_FOUND,
1452         DEVICE_CHANGED,
1453         DEVICE_SAME,
1454 };
1455
1456 static enum pqi_find_result pqi_scsi_find_entry(struct pqi_ctrl_info *ctrl_info,
1457         struct pqi_scsi_dev *device_to_find,
1458         struct pqi_scsi_dev **matching_device)
1459 {
1460         struct pqi_scsi_dev *device;
1461
1462         list_for_each_entry(device, &ctrl_info->scsi_device_list,
1463                 scsi_device_list_entry) {
1464                 if (pqi_scsi3addr_equal(device_to_find->scsi3addr,
1465                         device->scsi3addr)) {
1466                         *matching_device = device;
1467                         if (pqi_device_equal(device_to_find, device)) {
1468                                 if (device_to_find->volume_offline)
1469                                         return DEVICE_CHANGED;
1470                                 return DEVICE_SAME;
1471                         }
1472                         return DEVICE_CHANGED;
1473                 }
1474         }
1475
1476         return DEVICE_NOT_FOUND;
1477 }
1478
1479 #define PQI_DEV_INFO_BUFFER_LENGTH      128
1480
1481 static void pqi_dev_info(struct pqi_ctrl_info *ctrl_info,
1482         char *action, struct pqi_scsi_dev *device)
1483 {
1484         ssize_t count;
1485         char buffer[PQI_DEV_INFO_BUFFER_LENGTH];
1486
1487         count = snprintf(buffer, PQI_DEV_INFO_BUFFER_LENGTH,
1488                 "%d:%d:", ctrl_info->scsi_host->host_no, device->bus);
1489
1490         if (device->target_lun_valid)
1491                 count += snprintf(buffer + count,
1492                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1493                         "%d:%d",
1494                         device->target,
1495                         device->lun);
1496         else
1497                 count += snprintf(buffer + count,
1498                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1499                         "-:-");
1500
1501         if (pqi_is_logical_device(device))
1502                 count += snprintf(buffer + count,
1503                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1504                         " %08x%08x",
1505                         *((u32 *)&device->scsi3addr),
1506                         *((u32 *)&device->scsi3addr[4]));
1507         else
1508                 count += snprintf(buffer + count,
1509                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1510                         " %016llx", device->sas_address);
1511
1512         count += snprintf(buffer + count, PQI_DEV_INFO_BUFFER_LENGTH - count,
1513                 " %s %.8s %.16s ",
1514                 scsi_device_type(device->devtype),
1515                 device->vendor,
1516                 device->model);
1517
1518         if (pqi_is_logical_device(device)) {
1519                 if (device->devtype == TYPE_DISK)
1520                         count += snprintf(buffer + count,
1521                                 PQI_DEV_INFO_BUFFER_LENGTH - count,
1522                                 "SSDSmartPathCap%c En%c %-12s",
1523                                 device->raid_bypass_configured ? '+' : '-',
1524                                 device->raid_bypass_enabled ? '+' : '-',
1525                                 pqi_raid_level_to_string(device->raid_level));
1526         } else {
1527                 count += snprintf(buffer + count,
1528                         PQI_DEV_INFO_BUFFER_LENGTH - count,
1529                         "AIO%c", device->aio_enabled ? '+' : '-');
1530                 if (device->devtype == TYPE_DISK ||
1531                         device->devtype == TYPE_ZBC)
1532                         count += snprintf(buffer + count,
1533                                 PQI_DEV_INFO_BUFFER_LENGTH - count,
1534                                 " qd=%-6d", device->queue_depth);
1535         }
1536
1537         dev_info(&ctrl_info->pci_dev->dev, "%s %s\n", action, buffer);
1538 }
1539
1540 /* Assumes the SCSI device list lock is held. */
1541
1542 static void pqi_scsi_update_device(struct pqi_scsi_dev *existing_device,
1543         struct pqi_scsi_dev *new_device)
1544 {
1545         existing_device->devtype = new_device->devtype;
1546         existing_device->device_type = new_device->device_type;
1547         existing_device->bus = new_device->bus;
1548         if (new_device->target_lun_valid) {
1549                 existing_device->target = new_device->target;
1550                 existing_device->lun = new_device->lun;
1551                 existing_device->target_lun_valid = true;
1552         }
1553
1554         /* By definition, the scsi3addr and wwid fields are already the same. */
1555
1556         existing_device->is_physical_device = new_device->is_physical_device;
1557         existing_device->is_external_raid_device =
1558                 new_device->is_external_raid_device;
1559         existing_device->aio_enabled = new_device->aio_enabled;
1560         memcpy(existing_device->vendor, new_device->vendor,
1561                 sizeof(existing_device->vendor));
1562         memcpy(existing_device->model, new_device->model,
1563                 sizeof(existing_device->model));
1564         existing_device->sas_address = new_device->sas_address;
1565         existing_device->raid_level = new_device->raid_level;
1566         existing_device->queue_depth = new_device->queue_depth;
1567         existing_device->aio_handle = new_device->aio_handle;
1568         existing_device->volume_status = new_device->volume_status;
1569         existing_device->active_path_index = new_device->active_path_index;
1570         existing_device->path_map = new_device->path_map;
1571         existing_device->bay = new_device->bay;
1572         memcpy(existing_device->box, new_device->box,
1573                 sizeof(existing_device->box));
1574         memcpy(existing_device->phys_connector, new_device->phys_connector,
1575                 sizeof(existing_device->phys_connector));
1576         existing_device->offload_to_mirror = 0;
1577         kfree(existing_device->raid_map);
1578         existing_device->raid_map = new_device->raid_map;
1579         existing_device->raid_bypass_configured =
1580                 new_device->raid_bypass_configured;
1581         existing_device->raid_bypass_enabled =
1582                 new_device->raid_bypass_enabled;
1583
1584         /* To prevent this from being freed later. */
1585         new_device->raid_map = NULL;
1586 }
1587
1588 static inline void pqi_free_device(struct pqi_scsi_dev *device)
1589 {
1590         if (device) {
1591                 kfree(device->raid_map);
1592                 kfree(device);
1593         }
1594 }
1595
1596 /*
1597  * Called when exposing a new device to the OS fails in order to re-adjust
1598  * our internal SCSI device list to match the SCSI ML's view.
1599  */
1600
1601 static inline void pqi_fixup_botched_add(struct pqi_ctrl_info *ctrl_info,
1602         struct pqi_scsi_dev *device)
1603 {
1604         unsigned long flags;
1605
1606         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1607         list_del(&device->scsi_device_list_entry);
1608         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
1609
1610         /* Allow the device structure to be freed later. */
1611         device->keep_device = false;
1612 }
1613
1614 static void pqi_update_device_list(struct pqi_ctrl_info *ctrl_info,
1615         struct pqi_scsi_dev *new_device_list[], unsigned int num_new_devices)
1616 {
1617         int rc;
1618         unsigned int i;
1619         unsigned long flags;
1620         enum pqi_find_result find_result;
1621         struct pqi_scsi_dev *device;
1622         struct pqi_scsi_dev *next;
1623         struct pqi_scsi_dev *matching_device;
1624         LIST_HEAD(add_list);
1625         LIST_HEAD(delete_list);
1626
1627         /*
1628          * The idea here is to do as little work as possible while holding the
1629          * spinlock.  That's why we go to great pains to defer anything other
1630          * than updating the internal device list until after we release the
1631          * spinlock.
1632          */
1633
1634         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1635
1636         /* Assume that all devices in the existing list have gone away. */
1637         list_for_each_entry(device, &ctrl_info->scsi_device_list,
1638                 scsi_device_list_entry)
1639                 device->device_gone = true;
1640
1641         for (i = 0; i < num_new_devices; i++) {
1642                 device = new_device_list[i];
1643
1644                 find_result = pqi_scsi_find_entry(ctrl_info, device,
1645                                                 &matching_device);
1646
1647                 switch (find_result) {
1648                 case DEVICE_SAME:
1649                         /*
1650                          * The newly found device is already in the existing
1651                          * device list.
1652                          */
1653                         device->new_device = false;
1654                         matching_device->device_gone = false;
1655                         pqi_scsi_update_device(matching_device, device);
1656                         break;
1657                 case DEVICE_NOT_FOUND:
1658                         /*
1659                          * The newly found device is NOT in the existing device
1660                          * list.
1661                          */
1662                         device->new_device = true;
1663                         break;
1664                 case DEVICE_CHANGED:
1665                         /*
1666                          * The original device has gone away and we need to add
1667                          * the new device.
1668                          */
1669                         device->new_device = true;
1670                         break;
1671                 }
1672         }
1673
1674         /* Process all devices that have gone away. */
1675         list_for_each_entry_safe(device, next, &ctrl_info->scsi_device_list,
1676                 scsi_device_list_entry) {
1677                 if (device->device_gone) {
1678                         list_del(&device->scsi_device_list_entry);
1679                         list_add_tail(&device->delete_list_entry, &delete_list);
1680                 }
1681         }
1682
1683         /* Process all new devices. */
1684         for (i = 0; i < num_new_devices; i++) {
1685                 device = new_device_list[i];
1686                 if (!device->new_device)
1687                         continue;
1688                 if (device->volume_offline)
1689                         continue;
1690                 list_add_tail(&device->scsi_device_list_entry,
1691                         &ctrl_info->scsi_device_list);
1692                 list_add_tail(&device->add_list_entry, &add_list);
1693                 /* To prevent this device structure from being freed later. */
1694                 device->keep_device = true;
1695         }
1696
1697         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
1698
1699         /* Remove all devices that have gone away. */
1700         list_for_each_entry_safe(device, next, &delete_list,
1701                 delete_list_entry) {
1702                 if (device->volume_offline) {
1703                         pqi_dev_info(ctrl_info, "offline", device);
1704                         pqi_show_volume_status(ctrl_info, device);
1705                 } else {
1706                         pqi_dev_info(ctrl_info, "removed", device);
1707                 }
1708                 if (device->sdev)
1709                         pqi_remove_device(ctrl_info, device);
1710                 list_del(&device->delete_list_entry);
1711                 pqi_free_device(device);
1712         }
1713
1714         /*
1715          * Notify the SCSI ML if the queue depth of any existing device has
1716          * changed.
1717          */
1718         list_for_each_entry(device, &ctrl_info->scsi_device_list,
1719                 scsi_device_list_entry) {
1720                 if (device->sdev && device->queue_depth !=
1721                         device->advertised_queue_depth) {
1722                         device->advertised_queue_depth = device->queue_depth;
1723                         scsi_change_queue_depth(device->sdev,
1724                                 device->advertised_queue_depth);
1725                 }
1726         }
1727
1728         /* Expose any new devices. */
1729         list_for_each_entry_safe(device, next, &add_list, add_list_entry) {
1730                 if (!device->sdev) {
1731                         pqi_dev_info(ctrl_info, "added", device);
1732                         rc = pqi_add_device(ctrl_info, device);
1733                         if (rc) {
1734                                 dev_warn(&ctrl_info->pci_dev->dev,
1735                                         "scsi %d:%d:%d:%d addition failed, device not added\n",
1736                                         ctrl_info->scsi_host->host_no,
1737                                         device->bus, device->target,
1738                                         device->lun);
1739                                 pqi_fixup_botched_add(ctrl_info, device);
1740                         }
1741                 }
1742         }
1743 }
1744
1745 static bool pqi_is_supported_device(struct pqi_scsi_dev *device)
1746 {
1747         bool is_supported = false;
1748
1749         switch (device->devtype) {
1750         case TYPE_DISK:
1751         case TYPE_ZBC:
1752         case TYPE_TAPE:
1753         case TYPE_MEDIUM_CHANGER:
1754         case TYPE_ENCLOSURE:
1755                 is_supported = true;
1756                 break;
1757         case TYPE_RAID:
1758                 /*
1759                  * Only support the HBA controller itself as a RAID
1760                  * controller.  If it's a RAID controller other than
1761                  * the HBA itself (an external RAID controller, for
1762                  * example), we don't support it.
1763                  */
1764                 if (pqi_is_hba_lunid(device->scsi3addr))
1765                         is_supported = true;
1766                 break;
1767         }
1768
1769         return is_supported;
1770 }
1771
1772 static inline bool pqi_skip_device(u8 *scsi3addr)
1773 {
1774         /* Ignore all masked devices. */
1775         if (MASKED_DEVICE(scsi3addr))
1776                 return true;
1777
1778         return false;
1779 }
1780
1781 static int pqi_update_scsi_devices(struct pqi_ctrl_info *ctrl_info)
1782 {
1783         int i;
1784         int rc;
1785         LIST_HEAD(new_device_list_head);
1786         struct report_phys_lun_extended *physdev_list = NULL;
1787         struct report_log_lun_extended *logdev_list = NULL;
1788         struct report_phys_lun_extended_entry *phys_lun_ext_entry;
1789         struct report_log_lun_extended_entry *log_lun_ext_entry;
1790         struct bmic_identify_physical_device *id_phys = NULL;
1791         u32 num_physicals;
1792         u32 num_logicals;
1793         struct pqi_scsi_dev **new_device_list = NULL;
1794         struct pqi_scsi_dev *device;
1795         struct pqi_scsi_dev *next;
1796         unsigned int num_new_devices;
1797         unsigned int num_valid_devices;
1798         bool is_physical_device;
1799         u8 *scsi3addr;
1800         static char *out_of_memory_msg =
1801                 "failed to allocate memory, device discovery stopped";
1802
1803         rc = pqi_get_device_lists(ctrl_info, &physdev_list, &logdev_list);
1804         if (rc)
1805                 goto out;
1806
1807         if (physdev_list)
1808                 num_physicals =
1809                         get_unaligned_be32(&physdev_list->header.list_length)
1810                                 / sizeof(physdev_list->lun_entries[0]);
1811         else
1812                 num_physicals = 0;
1813
1814         if (logdev_list)
1815                 num_logicals =
1816                         get_unaligned_be32(&logdev_list->header.list_length)
1817                                 / sizeof(logdev_list->lun_entries[0]);
1818         else
1819                 num_logicals = 0;
1820
1821         if (num_physicals) {
1822                 /*
1823                  * We need this buffer for calls to pqi_get_physical_disk_info()
1824                  * below.  We allocate it here instead of inside
1825                  * pqi_get_physical_disk_info() because it's a fairly large
1826                  * buffer.
1827                  */
1828                 id_phys = kmalloc(sizeof(*id_phys), GFP_KERNEL);
1829                 if (!id_phys) {
1830                         dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
1831                                 out_of_memory_msg);
1832                         rc = -ENOMEM;
1833                         goto out;
1834                 }
1835         }
1836
1837         num_new_devices = num_physicals + num_logicals;
1838
1839         new_device_list = kmalloc_array(num_new_devices,
1840                                         sizeof(*new_device_list),
1841                                         GFP_KERNEL);
1842         if (!new_device_list) {
1843                 dev_warn(&ctrl_info->pci_dev->dev, "%s\n", out_of_memory_msg);
1844                 rc = -ENOMEM;
1845                 goto out;
1846         }
1847
1848         for (i = 0; i < num_new_devices; i++) {
1849                 device = kzalloc(sizeof(*device), GFP_KERNEL);
1850                 if (!device) {
1851                         dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
1852                                 out_of_memory_msg);
1853                         rc = -ENOMEM;
1854                         goto out;
1855                 }
1856                 list_add_tail(&device->new_device_list_entry,
1857                         &new_device_list_head);
1858         }
1859
1860         device = NULL;
1861         num_valid_devices = 0;
1862
1863         for (i = 0; i < num_new_devices; i++) {
1864
1865                 if (i < num_physicals) {
1866                         is_physical_device = true;
1867                         phys_lun_ext_entry = &physdev_list->lun_entries[i];
1868                         log_lun_ext_entry = NULL;
1869                         scsi3addr = phys_lun_ext_entry->lunid;
1870                 } else {
1871                         is_physical_device = false;
1872                         phys_lun_ext_entry = NULL;
1873                         log_lun_ext_entry =
1874                                 &logdev_list->lun_entries[i - num_physicals];
1875                         scsi3addr = log_lun_ext_entry->lunid;
1876                 }
1877
1878                 if (is_physical_device && pqi_skip_device(scsi3addr))
1879                         continue;
1880
1881                 if (device)
1882                         device = list_next_entry(device, new_device_list_entry);
1883                 else
1884                         device = list_first_entry(&new_device_list_head,
1885                                 struct pqi_scsi_dev, new_device_list_entry);
1886
1887                 memcpy(device->scsi3addr, scsi3addr, sizeof(device->scsi3addr));
1888                 device->is_physical_device = is_physical_device;
1889                 if (!is_physical_device)
1890                         device->is_external_raid_device =
1891                                 pqi_is_external_raid_addr(scsi3addr);
1892
1893                 /* Gather information about the device. */
1894                 rc = pqi_get_device_info(ctrl_info, device);
1895                 if (rc == -ENOMEM) {
1896                         dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
1897                                 out_of_memory_msg);
1898                         goto out;
1899                 }
1900                 if (rc) {
1901                         if (device->is_physical_device)
1902                                 dev_warn(&ctrl_info->pci_dev->dev,
1903                                         "obtaining device info failed, skipping physical device %016llx\n",
1904                                         get_unaligned_be64(
1905                                                 &phys_lun_ext_entry->wwid));
1906                         else
1907                                 dev_warn(&ctrl_info->pci_dev->dev,
1908                                         "obtaining device info failed, skipping logical device %08x%08x\n",
1909                                         *((u32 *)&device->scsi3addr),
1910                                         *((u32 *)&device->scsi3addr[4]));
1911                         rc = 0;
1912                         continue;
1913                 }
1914
1915                 if (!pqi_is_supported_device(device))
1916                         continue;
1917
1918                 pqi_assign_bus_target_lun(device);
1919
1920                 if (device->is_physical_device) {
1921                         device->wwid = phys_lun_ext_entry->wwid;
1922                         if ((phys_lun_ext_entry->device_flags &
1923                                 REPORT_PHYS_LUN_DEV_FLAG_AIO_ENABLED) &&
1924                                 phys_lun_ext_entry->aio_handle)
1925                                 device->aio_enabled = true;
1926                 } else {
1927                         memcpy(device->volume_id, log_lun_ext_entry->volume_id,
1928                                 sizeof(device->volume_id));
1929                 }
1930
1931                 switch (device->devtype) {
1932                 case TYPE_DISK:
1933                 case TYPE_ZBC:
1934                 case TYPE_ENCLOSURE:
1935                         if (device->is_physical_device) {
1936                                 device->sas_address =
1937                                         get_unaligned_be64(&device->wwid);
1938                                 if (device->devtype == TYPE_DISK ||
1939                                         device->devtype == TYPE_ZBC) {
1940                                         device->aio_handle =
1941                                                 phys_lun_ext_entry->aio_handle;
1942                                         pqi_get_physical_disk_info(ctrl_info,
1943                                                 device, id_phys);
1944                                 }
1945                         }
1946                         break;
1947                 }
1948
1949                 new_device_list[num_valid_devices++] = device;
1950         }
1951
1952         pqi_update_device_list(ctrl_info, new_device_list, num_valid_devices);
1953
1954 out:
1955         list_for_each_entry_safe(device, next, &new_device_list_head,
1956                 new_device_list_entry) {
1957                 if (device->keep_device)
1958                         continue;
1959                 list_del(&device->new_device_list_entry);
1960                 pqi_free_device(device);
1961         }
1962
1963         kfree(new_device_list);
1964         kfree(physdev_list);
1965         kfree(logdev_list);
1966         kfree(id_phys);
1967
1968         return rc;
1969 }
1970
1971 static void pqi_remove_all_scsi_devices(struct pqi_ctrl_info *ctrl_info)
1972 {
1973         unsigned long flags;
1974         struct pqi_scsi_dev *device;
1975
1976         while (1) {
1977                 spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1978
1979                 device = list_first_entry_or_null(&ctrl_info->scsi_device_list,
1980                         struct pqi_scsi_dev, scsi_device_list_entry);
1981                 if (device)
1982                         list_del(&device->scsi_device_list_entry);
1983
1984                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock,
1985                         flags);
1986
1987                 if (!device)
1988                         break;
1989
1990                 if (device->sdev)
1991                         pqi_remove_device(ctrl_info, device);
1992                 pqi_free_device(device);
1993         }
1994 }
1995
1996 static int pqi_scan_scsi_devices(struct pqi_ctrl_info *ctrl_info)
1997 {
1998         int rc;
1999
2000         if (pqi_ctrl_offline(ctrl_info))
2001                 return -ENXIO;
2002
2003         mutex_lock(&ctrl_info->scan_mutex);
2004
2005         rc = pqi_update_scsi_devices(ctrl_info);
2006         if (rc)
2007                 pqi_schedule_rescan_worker_delayed(ctrl_info);
2008
2009         mutex_unlock(&ctrl_info->scan_mutex);
2010
2011         return rc;
2012 }
2013
2014 static void pqi_scan_start(struct Scsi_Host *shost)
2015 {
2016         pqi_scan_scsi_devices(shost_to_hba(shost));
2017 }
2018
2019 /* Returns TRUE if scan is finished. */
2020
2021 static int pqi_scan_finished(struct Scsi_Host *shost,
2022         unsigned long elapsed_time)
2023 {
2024         struct pqi_ctrl_info *ctrl_info;
2025
2026         ctrl_info = shost_priv(shost);
2027
2028         return !mutex_is_locked(&ctrl_info->scan_mutex);
2029 }
2030
2031 static void pqi_wait_until_scan_finished(struct pqi_ctrl_info *ctrl_info)
2032 {
2033         mutex_lock(&ctrl_info->scan_mutex);
2034         mutex_unlock(&ctrl_info->scan_mutex);
2035 }
2036
2037 static void pqi_wait_until_lun_reset_finished(struct pqi_ctrl_info *ctrl_info)
2038 {
2039         mutex_lock(&ctrl_info->lun_reset_mutex);
2040         mutex_unlock(&ctrl_info->lun_reset_mutex);
2041 }
2042
2043 static inline void pqi_set_encryption_info(
2044         struct pqi_encryption_info *encryption_info, struct raid_map *raid_map,
2045         u64 first_block)
2046 {
2047         u32 volume_blk_size;
2048
2049         /*
2050          * Set the encryption tweak values based on logical block address.
2051          * If the block size is 512, the tweak value is equal to the LBA.
2052          * For other block sizes, tweak value is (LBA * block size) / 512.
2053          */
2054         volume_blk_size = get_unaligned_le32(&raid_map->volume_blk_size);
2055         if (volume_blk_size != 512)
2056                 first_block = (first_block * volume_blk_size) / 512;
2057
2058         encryption_info->data_encryption_key_index =
2059                 get_unaligned_le16(&raid_map->data_encryption_key_index);
2060         encryption_info->encrypt_tweak_lower = lower_32_bits(first_block);
2061         encryption_info->encrypt_tweak_upper = upper_32_bits(first_block);
2062 }
2063
2064 /*
2065  * Attempt to perform RAID bypass mapping for a logical volume I/O.
2066  */
2067
2068 #define PQI_RAID_BYPASS_INELIGIBLE      1
2069
2070 static int pqi_raid_bypass_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
2071         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
2072         struct pqi_queue_group *queue_group)
2073 {
2074         struct raid_map *raid_map;
2075         bool is_write = false;
2076         u32 map_index;
2077         u64 first_block;
2078         u64 last_block;
2079         u32 block_cnt;
2080         u32 blocks_per_row;
2081         u64 first_row;
2082         u64 last_row;
2083         u32 first_row_offset;
2084         u32 last_row_offset;
2085         u32 first_column;
2086         u32 last_column;
2087         u64 r0_first_row;
2088         u64 r0_last_row;
2089         u32 r5or6_blocks_per_row;
2090         u64 r5or6_first_row;
2091         u64 r5or6_last_row;
2092         u32 r5or6_first_row_offset;
2093         u32 r5or6_last_row_offset;
2094         u32 r5or6_first_column;
2095         u32 r5or6_last_column;
2096         u16 data_disks_per_row;
2097         u32 total_disks_per_row;
2098         u16 layout_map_count;
2099         u32 stripesize;
2100         u16 strip_size;
2101         u32 first_group;
2102         u32 last_group;
2103         u32 current_group;
2104         u32 map_row;
2105         u32 aio_handle;
2106         u64 disk_block;
2107         u32 disk_block_cnt;
2108         u8 cdb[16];
2109         u8 cdb_length;
2110         int offload_to_mirror;
2111         struct pqi_encryption_info *encryption_info_ptr;
2112         struct pqi_encryption_info encryption_info;
2113 #if BITS_PER_LONG == 32
2114         u64 tmpdiv;
2115 #endif
2116
2117         /* Check for valid opcode, get LBA and block count. */
2118         switch (scmd->cmnd[0]) {
2119         case WRITE_6:
2120                 is_write = true;
2121                 /* fall through */
2122         case READ_6:
2123                 first_block = (u64)(((scmd->cmnd[1] & 0x1f) << 16) |
2124                         (scmd->cmnd[2] << 8) | scmd->cmnd[3]);
2125                 block_cnt = (u32)scmd->cmnd[4];
2126                 if (block_cnt == 0)
2127                         block_cnt = 256;
2128                 break;
2129         case WRITE_10:
2130                 is_write = true;
2131                 /* fall through */
2132         case READ_10:
2133                 first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2134                 block_cnt = (u32)get_unaligned_be16(&scmd->cmnd[7]);
2135                 break;
2136         case WRITE_12:
2137                 is_write = true;
2138                 /* fall through */
2139         case READ_12:
2140                 first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2141                 block_cnt = get_unaligned_be32(&scmd->cmnd[6]);
2142                 break;
2143         case WRITE_16:
2144                 is_write = true;
2145                 /* fall through */
2146         case READ_16:
2147                 first_block = get_unaligned_be64(&scmd->cmnd[2]);
2148                 block_cnt = get_unaligned_be32(&scmd->cmnd[10]);
2149                 break;
2150         default:
2151                 /* Process via normal I/O path. */
2152                 return PQI_RAID_BYPASS_INELIGIBLE;
2153         }
2154
2155         /* Check for write to non-RAID-0. */
2156         if (is_write && device->raid_level != SA_RAID_0)
2157                 return PQI_RAID_BYPASS_INELIGIBLE;
2158
2159         if (unlikely(block_cnt == 0))
2160                 return PQI_RAID_BYPASS_INELIGIBLE;
2161
2162         last_block = first_block + block_cnt - 1;
2163         raid_map = device->raid_map;
2164
2165         /* Check for invalid block or wraparound. */
2166         if (last_block >= get_unaligned_le64(&raid_map->volume_blk_cnt) ||
2167                 last_block < first_block)
2168                 return PQI_RAID_BYPASS_INELIGIBLE;
2169
2170         data_disks_per_row = get_unaligned_le16(&raid_map->data_disks_per_row);
2171         strip_size = get_unaligned_le16(&raid_map->strip_size);
2172         layout_map_count = get_unaligned_le16(&raid_map->layout_map_count);
2173
2174         /* Calculate stripe information for the request. */
2175         blocks_per_row = data_disks_per_row * strip_size;
2176 #if BITS_PER_LONG == 32
2177         tmpdiv = first_block;
2178         do_div(tmpdiv, blocks_per_row);
2179         first_row = tmpdiv;
2180         tmpdiv = last_block;
2181         do_div(tmpdiv, blocks_per_row);
2182         last_row = tmpdiv;
2183         first_row_offset = (u32)(first_block - (first_row * blocks_per_row));
2184         last_row_offset = (u32)(last_block - (last_row * blocks_per_row));
2185         tmpdiv = first_row_offset;
2186         do_div(tmpdiv, strip_size);
2187         first_column = tmpdiv;
2188         tmpdiv = last_row_offset;
2189         do_div(tmpdiv, strip_size);
2190         last_column = tmpdiv;
2191 #else
2192         first_row = first_block / blocks_per_row;
2193         last_row = last_block / blocks_per_row;
2194         first_row_offset = (u32)(first_block - (first_row * blocks_per_row));
2195         last_row_offset = (u32)(last_block - (last_row * blocks_per_row));
2196         first_column = first_row_offset / strip_size;
2197         last_column = last_row_offset / strip_size;
2198 #endif
2199
2200         /* If this isn't a single row/column then give to the controller. */
2201         if (first_row != last_row || first_column != last_column)
2202                 return PQI_RAID_BYPASS_INELIGIBLE;
2203
2204         /* Proceeding with driver mapping. */
2205         total_disks_per_row = data_disks_per_row +
2206                 get_unaligned_le16(&raid_map->metadata_disks_per_row);
2207         map_row = ((u32)(first_row >> raid_map->parity_rotation_shift)) %
2208                 get_unaligned_le16(&raid_map->row_cnt);
2209         map_index = (map_row * total_disks_per_row) + first_column;
2210
2211         /* RAID 1 */
2212         if (device->raid_level == SA_RAID_1) {
2213                 if (device->offload_to_mirror)
2214                         map_index += data_disks_per_row;
2215                 device->offload_to_mirror = !device->offload_to_mirror;
2216         } else if (device->raid_level == SA_RAID_ADM) {
2217                 /* RAID ADM */
2218                 /*
2219                  * Handles N-way mirrors  (R1-ADM) and R10 with # of drives
2220                  * divisible by 3.
2221                  */
2222                 offload_to_mirror = device->offload_to_mirror;
2223                 if (offload_to_mirror == 0)  {
2224                         /* use physical disk in the first mirrored group. */
2225                         map_index %= data_disks_per_row;
2226                 } else {
2227                         do {
2228                                 /*
2229                                  * Determine mirror group that map_index
2230                                  * indicates.
2231                                  */
2232                                 current_group = map_index / data_disks_per_row;
2233
2234                                 if (offload_to_mirror != current_group) {
2235                                         if (current_group <
2236                                                 layout_map_count - 1) {
2237                                                 /*
2238                                                  * Select raid index from
2239                                                  * next group.
2240                                                  */
2241                                                 map_index += data_disks_per_row;
2242                                                 current_group++;
2243                                         } else {
2244                                                 /*
2245                                                  * Select raid index from first
2246                                                  * group.
2247                                                  */
2248                                                 map_index %= data_disks_per_row;
2249                                                 current_group = 0;
2250                                         }
2251                                 }
2252                         } while (offload_to_mirror != current_group);
2253                 }
2254
2255                 /* Set mirror group to use next time. */
2256                 offload_to_mirror =
2257                         (offload_to_mirror >= layout_map_count - 1) ?
2258                                 0 : offload_to_mirror + 1;
2259                 WARN_ON(offload_to_mirror >= layout_map_count);
2260                 device->offload_to_mirror = offload_to_mirror;
2261                 /*
2262                  * Avoid direct use of device->offload_to_mirror within this
2263                  * function since multiple threads might simultaneously
2264                  * increment it beyond the range of device->layout_map_count -1.
2265                  */
2266         } else if ((device->raid_level == SA_RAID_5 ||
2267                 device->raid_level == SA_RAID_6) && layout_map_count > 1) {
2268                 /* RAID 50/60 */
2269                 /* Verify first and last block are in same RAID group */
2270                 r5or6_blocks_per_row = strip_size * data_disks_per_row;
2271                 stripesize = r5or6_blocks_per_row * layout_map_count;
2272 #if BITS_PER_LONG == 32
2273                 tmpdiv = first_block;
2274                 first_group = do_div(tmpdiv, stripesize);
2275                 tmpdiv = first_group;
2276                 do_div(tmpdiv, r5or6_blocks_per_row);
2277                 first_group = tmpdiv;
2278                 tmpdiv = last_block;
2279                 last_group = do_div(tmpdiv, stripesize);
2280                 tmpdiv = last_group;
2281                 do_div(tmpdiv, r5or6_blocks_per_row);
2282                 last_group = tmpdiv;
2283 #else
2284                 first_group = (first_block % stripesize) / r5or6_blocks_per_row;
2285                 last_group = (last_block % stripesize) / r5or6_blocks_per_row;
2286 #endif
2287                 if (first_group != last_group)
2288                         return PQI_RAID_BYPASS_INELIGIBLE;
2289
2290                 /* Verify request is in a single row of RAID 5/6 */
2291 #if BITS_PER_LONG == 32
2292                 tmpdiv = first_block;
2293                 do_div(tmpdiv, stripesize);
2294                 first_row = r5or6_first_row = r0_first_row = tmpdiv;
2295                 tmpdiv = last_block;
2296                 do_div(tmpdiv, stripesize);
2297                 r5or6_last_row = r0_last_row = tmpdiv;
2298 #else
2299                 first_row = r5or6_first_row = r0_first_row =
2300                         first_block / stripesize;
2301                 r5or6_last_row = r0_last_row = last_block / stripesize;
2302 #endif
2303                 if (r5or6_first_row != r5or6_last_row)
2304                         return PQI_RAID_BYPASS_INELIGIBLE;
2305
2306                 /* Verify request is in a single column */
2307 #if BITS_PER_LONG == 32
2308                 tmpdiv = first_block;
2309                 first_row_offset = do_div(tmpdiv, stripesize);
2310                 tmpdiv = first_row_offset;
2311                 first_row_offset = (u32)do_div(tmpdiv, r5or6_blocks_per_row);
2312                 r5or6_first_row_offset = first_row_offset;
2313                 tmpdiv = last_block;
2314                 r5or6_last_row_offset = do_div(tmpdiv, stripesize);
2315                 tmpdiv = r5or6_last_row_offset;
2316                 r5or6_last_row_offset = do_div(tmpdiv, r5or6_blocks_per_row);
2317                 tmpdiv = r5or6_first_row_offset;
2318                 do_div(tmpdiv, strip_size);
2319                 first_column = r5or6_first_column = tmpdiv;
2320                 tmpdiv = r5or6_last_row_offset;
2321                 do_div(tmpdiv, strip_size);
2322                 r5or6_last_column = tmpdiv;
2323 #else
2324                 first_row_offset = r5or6_first_row_offset =
2325                         (u32)((first_block % stripesize) %
2326                         r5or6_blocks_per_row);
2327
2328                 r5or6_last_row_offset =
2329                         (u32)((last_block % stripesize) %
2330                         r5or6_blocks_per_row);
2331
2332                 first_column = r5or6_first_row_offset / strip_size;
2333                 r5or6_first_column = first_column;
2334                 r5or6_last_column = r5or6_last_row_offset / strip_size;
2335 #endif
2336                 if (r5or6_first_column != r5or6_last_column)
2337                         return PQI_RAID_BYPASS_INELIGIBLE;
2338
2339                 /* Request is eligible */
2340                 map_row =
2341                         ((u32)(first_row >> raid_map->parity_rotation_shift)) %
2342                         get_unaligned_le16(&raid_map->row_cnt);
2343
2344                 map_index = (first_group *
2345                         (get_unaligned_le16(&raid_map->row_cnt) *
2346                         total_disks_per_row)) +
2347                         (map_row * total_disks_per_row) + first_column;
2348         }
2349
2350         if (unlikely(map_index >= RAID_MAP_MAX_ENTRIES))
2351                 return PQI_RAID_BYPASS_INELIGIBLE;
2352
2353         aio_handle = raid_map->disk_data[map_index].aio_handle;
2354         disk_block = get_unaligned_le64(&raid_map->disk_starting_blk) +
2355                 first_row * strip_size +
2356                 (first_row_offset - first_column * strip_size);
2357         disk_block_cnt = block_cnt;
2358
2359         /* Handle differing logical/physical block sizes. */
2360         if (raid_map->phys_blk_shift) {
2361                 disk_block <<= raid_map->phys_blk_shift;
2362                 disk_block_cnt <<= raid_map->phys_blk_shift;
2363         }
2364
2365         if (unlikely(disk_block_cnt > 0xffff))
2366                 return PQI_RAID_BYPASS_INELIGIBLE;
2367
2368         /* Build the new CDB for the physical disk I/O. */
2369         if (disk_block > 0xffffffff) {
2370                 cdb[0] = is_write ? WRITE_16 : READ_16;
2371                 cdb[1] = 0;
2372                 put_unaligned_be64(disk_block, &cdb[2]);
2373                 put_unaligned_be32(disk_block_cnt, &cdb[10]);
2374                 cdb[14] = 0;
2375                 cdb[15] = 0;
2376                 cdb_length = 16;
2377         } else {
2378                 cdb[0] = is_write ? WRITE_10 : READ_10;
2379                 cdb[1] = 0;
2380                 put_unaligned_be32((u32)disk_block, &cdb[2]);
2381                 cdb[6] = 0;
2382                 put_unaligned_be16((u16)disk_block_cnt, &cdb[7]);
2383                 cdb[9] = 0;
2384                 cdb_length = 10;
2385         }
2386
2387         if (get_unaligned_le16(&raid_map->flags) &
2388                 RAID_MAP_ENCRYPTION_ENABLED) {
2389                 pqi_set_encryption_info(&encryption_info, raid_map,
2390                         first_block);
2391                 encryption_info_ptr = &encryption_info;
2392         } else {
2393                 encryption_info_ptr = NULL;
2394         }
2395
2396         return pqi_aio_submit_io(ctrl_info, scmd, aio_handle,
2397                 cdb, cdb_length, queue_group, encryption_info_ptr, true);
2398 }
2399
2400 #define PQI_STATUS_IDLE         0x0
2401
2402 #define PQI_CREATE_ADMIN_QUEUE_PAIR     1
2403 #define PQI_DELETE_ADMIN_QUEUE_PAIR     2
2404
2405 #define PQI_DEVICE_STATE_POWER_ON_AND_RESET             0x0
2406 #define PQI_DEVICE_STATE_STATUS_AVAILABLE               0x1
2407 #define PQI_DEVICE_STATE_ALL_REGISTERS_READY            0x2
2408 #define PQI_DEVICE_STATE_ADMIN_QUEUE_PAIR_READY         0x3
2409 #define PQI_DEVICE_STATE_ERROR                          0x4
2410
2411 #define PQI_MODE_READY_TIMEOUT_SECS             30
2412 #define PQI_MODE_READY_POLL_INTERVAL_MSECS      1
2413
2414 static int pqi_wait_for_pqi_mode_ready(struct pqi_ctrl_info *ctrl_info)
2415 {
2416         struct pqi_device_registers __iomem *pqi_registers;
2417         unsigned long timeout;
2418         u64 signature;
2419         u8 status;
2420
2421         pqi_registers = ctrl_info->pqi_registers;
2422         timeout = (PQI_MODE_READY_TIMEOUT_SECS * HZ) + jiffies;
2423
2424         while (1) {
2425                 signature = readq(&pqi_registers->signature);
2426                 if (memcmp(&signature, PQI_DEVICE_SIGNATURE,
2427                         sizeof(signature)) == 0)
2428                         break;
2429                 if (time_after(jiffies, timeout)) {
2430                         dev_err(&ctrl_info->pci_dev->dev,
2431                                 "timed out waiting for PQI signature\n");
2432                         return -ETIMEDOUT;
2433                 }
2434                 msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2435         }
2436
2437         while (1) {
2438                 status = readb(&pqi_registers->function_and_status_code);
2439                 if (status == PQI_STATUS_IDLE)
2440                         break;
2441                 if (time_after(jiffies, timeout)) {
2442                         dev_err(&ctrl_info->pci_dev->dev,
2443                                 "timed out waiting for PQI IDLE\n");
2444                         return -ETIMEDOUT;
2445                 }
2446                 msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2447         }
2448
2449         while (1) {
2450                 if (readl(&pqi_registers->device_status) ==
2451                         PQI_DEVICE_STATE_ALL_REGISTERS_READY)
2452                         break;
2453                 if (time_after(jiffies, timeout)) {
2454                         dev_err(&ctrl_info->pci_dev->dev,
2455                                 "timed out waiting for PQI all registers ready\n");
2456                         return -ETIMEDOUT;
2457                 }
2458                 msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2459         }
2460
2461         return 0;
2462 }
2463
2464 static inline void pqi_aio_path_disabled(struct pqi_io_request *io_request)
2465 {
2466         struct pqi_scsi_dev *device;
2467
2468         device = io_request->scmd->device->hostdata;
2469         device->raid_bypass_enabled = false;
2470         device->aio_enabled = false;
2471 }
2472
2473 static inline void pqi_take_device_offline(struct scsi_device *sdev, char *path)
2474 {
2475         struct pqi_ctrl_info *ctrl_info;
2476         struct pqi_scsi_dev *device;
2477
2478         device = sdev->hostdata;
2479         if (device->device_offline)
2480                 return;
2481
2482         device->device_offline = true;
2483         scsi_device_set_state(sdev, SDEV_OFFLINE);
2484         ctrl_info = shost_to_hba(sdev->host);
2485         pqi_schedule_rescan_worker(ctrl_info);
2486         dev_err(&ctrl_info->pci_dev->dev, "offlined %s scsi %d:%d:%d:%d\n",
2487                 path, ctrl_info->scsi_host->host_no, device->bus,
2488                 device->target, device->lun);
2489 }
2490
2491 static void pqi_process_raid_io_error(struct pqi_io_request *io_request)
2492 {
2493         u8 scsi_status;
2494         u8 host_byte;
2495         struct scsi_cmnd *scmd;
2496         struct pqi_raid_error_info *error_info;
2497         size_t sense_data_length;
2498         int residual_count;
2499         int xfer_count;
2500         struct scsi_sense_hdr sshdr;
2501
2502         scmd = io_request->scmd;
2503         if (!scmd)
2504                 return;
2505
2506         error_info = io_request->error_info;
2507         scsi_status = error_info->status;
2508         host_byte = DID_OK;
2509
2510         switch (error_info->data_out_result) {
2511         case PQI_DATA_IN_OUT_GOOD:
2512                 break;
2513         case PQI_DATA_IN_OUT_UNDERFLOW:
2514                 xfer_count =
2515                         get_unaligned_le32(&error_info->data_out_transferred);
2516                 residual_count = scsi_bufflen(scmd) - xfer_count;
2517                 scsi_set_resid(scmd, residual_count);
2518                 if (xfer_count < scmd->underflow)
2519                         host_byte = DID_SOFT_ERROR;
2520                 break;
2521         case PQI_DATA_IN_OUT_UNSOLICITED_ABORT:
2522         case PQI_DATA_IN_OUT_ABORTED:
2523                 host_byte = DID_ABORT;
2524                 break;
2525         case PQI_DATA_IN_OUT_TIMEOUT:
2526                 host_byte = DID_TIME_OUT;
2527                 break;
2528         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW:
2529         case PQI_DATA_IN_OUT_PROTOCOL_ERROR:
2530         case PQI_DATA_IN_OUT_BUFFER_ERROR:
2531         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_DESCRIPTOR_AREA:
2532         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_BRIDGE:
2533         case PQI_DATA_IN_OUT_ERROR:
2534         case PQI_DATA_IN_OUT_HARDWARE_ERROR:
2535         case PQI_DATA_IN_OUT_PCIE_FABRIC_ERROR:
2536         case PQI_DATA_IN_OUT_PCIE_COMPLETION_TIMEOUT:
2537         case PQI_DATA_IN_OUT_PCIE_COMPLETER_ABORT_RECEIVED:
2538         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST_RECEIVED:
2539         case PQI_DATA_IN_OUT_PCIE_ECRC_CHECK_FAILED:
2540         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST:
2541         case PQI_DATA_IN_OUT_PCIE_ACS_VIOLATION:
2542         case PQI_DATA_IN_OUT_PCIE_TLP_PREFIX_BLOCKED:
2543         case PQI_DATA_IN_OUT_PCIE_POISONED_MEMORY_READ:
2544         default:
2545                 host_byte = DID_ERROR;
2546                 break;
2547         }
2548
2549         sense_data_length = get_unaligned_le16(&error_info->sense_data_length);
2550         if (sense_data_length == 0)
2551                 sense_data_length =
2552                         get_unaligned_le16(&error_info->response_data_length);
2553         if (sense_data_length) {
2554                 if (sense_data_length > sizeof(error_info->data))
2555                         sense_data_length = sizeof(error_info->data);
2556
2557                 if (scsi_status == SAM_STAT_CHECK_CONDITION &&
2558                         scsi_normalize_sense(error_info->data,
2559                                 sense_data_length, &sshdr) &&
2560                                 sshdr.sense_key == HARDWARE_ERROR &&
2561                                 sshdr.asc == 0x3e &&
2562                                 sshdr.ascq == 0x1) {
2563                         pqi_take_device_offline(scmd->device, "RAID");
2564                         host_byte = DID_NO_CONNECT;
2565                 }
2566
2567                 if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
2568                         sense_data_length = SCSI_SENSE_BUFFERSIZE;
2569                 memcpy(scmd->sense_buffer, error_info->data,
2570                         sense_data_length);
2571         }
2572
2573         scmd->result = scsi_status;
2574         set_host_byte(scmd, host_byte);
2575 }
2576
2577 static void pqi_process_aio_io_error(struct pqi_io_request *io_request)
2578 {
2579         u8 scsi_status;
2580         u8 host_byte;
2581         struct scsi_cmnd *scmd;
2582         struct pqi_aio_error_info *error_info;
2583         size_t sense_data_length;
2584         int residual_count;
2585         int xfer_count;
2586         bool device_offline;
2587
2588         scmd = io_request->scmd;
2589         error_info = io_request->error_info;
2590         host_byte = DID_OK;
2591         sense_data_length = 0;
2592         device_offline = false;
2593
2594         switch (error_info->service_response) {
2595         case PQI_AIO_SERV_RESPONSE_COMPLETE:
2596                 scsi_status = error_info->status;
2597                 break;
2598         case PQI_AIO_SERV_RESPONSE_FAILURE:
2599                 switch (error_info->status) {
2600                 case PQI_AIO_STATUS_IO_ABORTED:
2601                         scsi_status = SAM_STAT_TASK_ABORTED;
2602                         break;
2603                 case PQI_AIO_STATUS_UNDERRUN:
2604                         scsi_status = SAM_STAT_GOOD;
2605                         residual_count = get_unaligned_le32(
2606                                                 &error_info->residual_count);
2607                         scsi_set_resid(scmd, residual_count);
2608                         xfer_count = scsi_bufflen(scmd) - residual_count;
2609                         if (xfer_count < scmd->underflow)
2610                                 host_byte = DID_SOFT_ERROR;
2611                         break;
2612                 case PQI_AIO_STATUS_OVERRUN:
2613                         scsi_status = SAM_STAT_GOOD;
2614                         break;
2615                 case PQI_AIO_STATUS_AIO_PATH_DISABLED:
2616                         pqi_aio_path_disabled(io_request);
2617                         scsi_status = SAM_STAT_GOOD;
2618                         io_request->status = -EAGAIN;
2619                         break;
2620                 case PQI_AIO_STATUS_NO_PATH_TO_DEVICE:
2621                 case PQI_AIO_STATUS_INVALID_DEVICE:
2622                         if (!io_request->raid_bypass) {
2623                                 device_offline = true;
2624                                 pqi_take_device_offline(scmd->device, "AIO");
2625                                 host_byte = DID_NO_CONNECT;
2626                         }
2627                         scsi_status = SAM_STAT_CHECK_CONDITION;
2628                         break;
2629                 case PQI_AIO_STATUS_IO_ERROR:
2630                 default:
2631                         scsi_status = SAM_STAT_CHECK_CONDITION;
2632                         break;
2633                 }
2634                 break;
2635         case PQI_AIO_SERV_RESPONSE_TMF_COMPLETE:
2636         case PQI_AIO_SERV_RESPONSE_TMF_SUCCEEDED:
2637                 scsi_status = SAM_STAT_GOOD;
2638                 break;
2639         case PQI_AIO_SERV_RESPONSE_TMF_REJECTED:
2640         case PQI_AIO_SERV_RESPONSE_TMF_INCORRECT_LUN:
2641         default:
2642                 scsi_status = SAM_STAT_CHECK_CONDITION;
2643                 break;
2644         }
2645
2646         if (error_info->data_present) {
2647                 sense_data_length =
2648                         get_unaligned_le16(&error_info->data_length);
2649                 if (sense_data_length) {
2650                         if (sense_data_length > sizeof(error_info->data))
2651                                 sense_data_length = sizeof(error_info->data);
2652                         if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
2653                                 sense_data_length = SCSI_SENSE_BUFFERSIZE;
2654                         memcpy(scmd->sense_buffer, error_info->data,
2655                                 sense_data_length);
2656                 }
2657         }
2658
2659         if (device_offline && sense_data_length == 0)
2660                 scsi_build_sense_buffer(0, scmd->sense_buffer, HARDWARE_ERROR,
2661                         0x3e, 0x1);
2662
2663         scmd->result = scsi_status;
2664         set_host_byte(scmd, host_byte);
2665 }
2666
2667 static void pqi_process_io_error(unsigned int iu_type,
2668         struct pqi_io_request *io_request)
2669 {
2670         switch (iu_type) {
2671         case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
2672                 pqi_process_raid_io_error(io_request);
2673                 break;
2674         case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
2675                 pqi_process_aio_io_error(io_request);
2676                 break;
2677         }
2678 }
2679
2680 static int pqi_interpret_task_management_response(
2681         struct pqi_task_management_response *response)
2682 {
2683         int rc;
2684
2685         switch (response->response_code) {
2686         case SOP_TMF_COMPLETE:
2687         case SOP_TMF_FUNCTION_SUCCEEDED:
2688                 rc = 0;
2689                 break;
2690         default:
2691                 rc = -EIO;
2692                 break;
2693         }
2694
2695         return rc;
2696 }
2697
2698 static unsigned int pqi_process_io_intr(struct pqi_ctrl_info *ctrl_info,
2699         struct pqi_queue_group *queue_group)
2700 {
2701         unsigned int num_responses;
2702         pqi_index_t oq_pi;
2703         pqi_index_t oq_ci;
2704         struct pqi_io_request *io_request;
2705         struct pqi_io_response *response;
2706         u16 request_id;
2707
2708         num_responses = 0;
2709         oq_ci = queue_group->oq_ci_copy;
2710
2711         while (1) {
2712                 oq_pi = readl(queue_group->oq_pi);
2713                 if (oq_pi == oq_ci)
2714                         break;
2715
2716                 num_responses++;
2717                 response = queue_group->oq_element_array +
2718                         (oq_ci * PQI_OPERATIONAL_OQ_ELEMENT_LENGTH);
2719
2720                 request_id = get_unaligned_le16(&response->request_id);
2721                 WARN_ON(request_id >= ctrl_info->max_io_slots);
2722
2723                 io_request = &ctrl_info->io_request_pool[request_id];
2724                 WARN_ON(atomic_read(&io_request->refcount) == 0);
2725
2726                 switch (response->header.iu_type) {
2727                 case PQI_RESPONSE_IU_RAID_PATH_IO_SUCCESS:
2728                 case PQI_RESPONSE_IU_AIO_PATH_IO_SUCCESS:
2729                         if (io_request->scmd)
2730                                 io_request->scmd->result = 0;
2731                         /* fall through */
2732                 case PQI_RESPONSE_IU_GENERAL_MANAGEMENT:
2733                         break;
2734                 case PQI_RESPONSE_IU_TASK_MANAGEMENT:
2735                         io_request->status =
2736                                 pqi_interpret_task_management_response(
2737                                         (void *)response);
2738                         break;
2739                 case PQI_RESPONSE_IU_AIO_PATH_DISABLED:
2740                         pqi_aio_path_disabled(io_request);
2741                         io_request->status = -EAGAIN;
2742                         break;
2743                 case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
2744                 case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
2745                         io_request->error_info = ctrl_info->error_buffer +
2746                                 (get_unaligned_le16(&response->error_index) *
2747                                 PQI_ERROR_BUFFER_ELEMENT_LENGTH);
2748                         pqi_process_io_error(response->header.iu_type,
2749                                 io_request);
2750                         break;
2751                 default:
2752                         dev_err(&ctrl_info->pci_dev->dev,
2753                                 "unexpected IU type: 0x%x\n",
2754                                 response->header.iu_type);
2755                         break;
2756                 }
2757
2758                 io_request->io_complete_callback(io_request,
2759                         io_request->context);
2760
2761                 /*
2762                  * Note that the I/O request structure CANNOT BE TOUCHED after
2763                  * returning from the I/O completion callback!
2764                  */
2765
2766                 oq_ci = (oq_ci + 1) % ctrl_info->num_elements_per_oq;
2767         }
2768
2769         if (num_responses) {
2770                 queue_group->oq_ci_copy = oq_ci;
2771                 writel(oq_ci, queue_group->oq_ci);
2772         }
2773
2774         return num_responses;
2775 }
2776
2777 static inline unsigned int pqi_num_elements_free(unsigned int pi,
2778         unsigned int ci, unsigned int elements_in_queue)
2779 {
2780         unsigned int num_elements_used;
2781
2782         if (pi >= ci)
2783                 num_elements_used = pi - ci;
2784         else
2785                 num_elements_used = elements_in_queue - ci + pi;
2786
2787         return elements_in_queue - num_elements_used - 1;
2788 }
2789
2790 static void pqi_send_event_ack(struct pqi_ctrl_info *ctrl_info,
2791         struct pqi_event_acknowledge_request *iu, size_t iu_length)
2792 {
2793         pqi_index_t iq_pi;
2794         pqi_index_t iq_ci;
2795         unsigned long flags;
2796         void *next_element;
2797         struct pqi_queue_group *queue_group;
2798
2799         queue_group = &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP];
2800         put_unaligned_le16(queue_group->oq_id, &iu->header.response_queue_id);
2801
2802         while (1) {
2803                 spin_lock_irqsave(&queue_group->submit_lock[RAID_PATH], flags);
2804
2805                 iq_pi = queue_group->iq_pi_copy[RAID_PATH];
2806                 iq_ci = readl(queue_group->iq_ci[RAID_PATH]);
2807
2808                 if (pqi_num_elements_free(iq_pi, iq_ci,
2809                         ctrl_info->num_elements_per_iq))
2810                         break;
2811
2812                 spin_unlock_irqrestore(
2813                         &queue_group->submit_lock[RAID_PATH], flags);
2814
2815                 if (pqi_ctrl_offline(ctrl_info))
2816                         return;
2817         }
2818
2819         next_element = queue_group->iq_element_array[RAID_PATH] +
2820                 (iq_pi * PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
2821
2822         memcpy(next_element, iu, iu_length);
2823
2824         iq_pi = (iq_pi + 1) % ctrl_info->num_elements_per_iq;
2825         queue_group->iq_pi_copy[RAID_PATH] = iq_pi;
2826
2827         /*
2828          * This write notifies the controller that an IU is available to be
2829          * processed.
2830          */
2831         writel(iq_pi, queue_group->iq_pi[RAID_PATH]);
2832
2833         spin_unlock_irqrestore(&queue_group->submit_lock[RAID_PATH], flags);
2834 }
2835
2836 static void pqi_acknowledge_event(struct pqi_ctrl_info *ctrl_info,
2837         struct pqi_event *event)
2838 {
2839         struct pqi_event_acknowledge_request request;
2840
2841         memset(&request, 0, sizeof(request));
2842
2843         request.header.iu_type = PQI_REQUEST_IU_ACKNOWLEDGE_VENDOR_EVENT;
2844         put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
2845                 &request.header.iu_length);
2846         request.event_type = event->event_type;
2847         request.event_id = event->event_id;
2848         request.additional_event_id = event->additional_event_id;
2849
2850         pqi_send_event_ack(ctrl_info, &request, sizeof(request));
2851 }
2852
2853 static void pqi_event_worker(struct work_struct *work)
2854 {
2855         unsigned int i;
2856         struct pqi_ctrl_info *ctrl_info;
2857         struct pqi_event *event;
2858
2859         ctrl_info = container_of(work, struct pqi_ctrl_info, event_work);
2860
2861         pqi_ctrl_busy(ctrl_info);
2862         pqi_wait_if_ctrl_blocked(ctrl_info, NO_TIMEOUT);
2863         if (pqi_ctrl_offline(ctrl_info))
2864                 goto out;
2865
2866         pqi_schedule_rescan_worker_delayed(ctrl_info);
2867
2868         event = ctrl_info->events;
2869         for (i = 0; i < PQI_NUM_SUPPORTED_EVENTS; i++) {
2870                 if (event->pending) {
2871                         event->pending = false;
2872                         pqi_acknowledge_event(ctrl_info, event);
2873                 }
2874                 event++;
2875         }
2876
2877 out:
2878         pqi_ctrl_unbusy(ctrl_info);
2879 }
2880
2881 #define PQI_HEARTBEAT_TIMER_INTERVAL    (10 * HZ)
2882
2883 static void pqi_heartbeat_timer_handler(struct timer_list *t)
2884 {
2885         int num_interrupts;
2886         u32 heartbeat_count;
2887         struct pqi_ctrl_info *ctrl_info = from_timer(ctrl_info, t,
2888                                                      heartbeat_timer);
2889
2890         pqi_check_ctrl_health(ctrl_info);
2891         if (pqi_ctrl_offline(ctrl_info))
2892                 return;
2893
2894         num_interrupts = atomic_read(&ctrl_info->num_interrupts);
2895         heartbeat_count = pqi_read_heartbeat_counter(ctrl_info);
2896
2897         if (num_interrupts == ctrl_info->previous_num_interrupts) {
2898                 if (heartbeat_count == ctrl_info->previous_heartbeat_count) {
2899                         dev_err(&ctrl_info->pci_dev->dev,
2900                                 "no heartbeat detected - last heartbeat count: %u\n",
2901                                 heartbeat_count);
2902                         pqi_take_ctrl_offline(ctrl_info);
2903                         return;
2904                 }
2905         } else {
2906                 ctrl_info->previous_num_interrupts = num_interrupts;
2907         }
2908
2909         ctrl_info->previous_heartbeat_count = heartbeat_count;
2910         mod_timer(&ctrl_info->heartbeat_timer,
2911                 jiffies + PQI_HEARTBEAT_TIMER_INTERVAL);
2912 }
2913
2914 static void pqi_start_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
2915 {
2916         if (!ctrl_info->heartbeat_counter)
2917                 return;
2918
2919         ctrl_info->previous_num_interrupts =
2920                 atomic_read(&ctrl_info->num_interrupts);
2921         ctrl_info->previous_heartbeat_count =
2922                 pqi_read_heartbeat_counter(ctrl_info);
2923
2924         ctrl_info->heartbeat_timer.expires =
2925                 jiffies + PQI_HEARTBEAT_TIMER_INTERVAL;
2926         add_timer(&ctrl_info->heartbeat_timer);
2927 }
2928
2929 static inline void pqi_stop_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
2930 {
2931         del_timer_sync(&ctrl_info->heartbeat_timer);
2932 }
2933
2934 static inline int pqi_event_type_to_event_index(unsigned int event_type)
2935 {
2936         int index;
2937
2938         for (index = 0; index < ARRAY_SIZE(pqi_supported_event_types); index++)
2939                 if (event_type == pqi_supported_event_types[index])
2940                         return index;
2941
2942         return -1;
2943 }
2944
2945 static inline bool pqi_is_supported_event(unsigned int event_type)
2946 {
2947         return pqi_event_type_to_event_index(event_type) != -1;
2948 }
2949
2950 static unsigned int pqi_process_event_intr(struct pqi_ctrl_info *ctrl_info)
2951 {
2952         unsigned int num_events;
2953         pqi_index_t oq_pi;
2954         pqi_index_t oq_ci;
2955         struct pqi_event_queue *event_queue;
2956         struct pqi_event_response *response;
2957         struct pqi_event *event;
2958         int event_index;
2959
2960         event_queue = &ctrl_info->event_queue;
2961         num_events = 0;
2962         oq_ci = event_queue->oq_ci_copy;
2963
2964         while (1) {
2965                 oq_pi = readl(event_queue->oq_pi);
2966                 if (oq_pi == oq_ci)
2967                         break;
2968
2969                 num_events++;
2970                 response = event_queue->oq_element_array +
2971                         (oq_ci * PQI_EVENT_OQ_ELEMENT_LENGTH);
2972
2973                 event_index =
2974                         pqi_event_type_to_event_index(response->event_type);
2975
2976                 if (event_index >= 0) {
2977                         if (response->request_acknowlege) {
2978                                 event = &ctrl_info->events[event_index];
2979                                 event->pending = true;
2980                                 event->event_type = response->event_type;
2981                                 event->event_id = response->event_id;
2982                                 event->additional_event_id =
2983                                         response->additional_event_id;
2984                         }
2985                 }
2986
2987                 oq_ci = (oq_ci + 1) % PQI_NUM_EVENT_QUEUE_ELEMENTS;
2988         }
2989
2990         if (num_events) {
2991                 event_queue->oq_ci_copy = oq_ci;
2992                 writel(oq_ci, event_queue->oq_ci);
2993                 schedule_work(&ctrl_info->event_work);
2994         }
2995
2996         return num_events;
2997 }
2998
2999 #define PQI_LEGACY_INTX_MASK    0x1
3000
3001 static inline void pqi_configure_legacy_intx(struct pqi_ctrl_info *ctrl_info,
3002                                                 bool enable_intx)
3003 {
3004         u32 intx_mask;
3005         struct pqi_device_registers __iomem *pqi_registers;
3006         volatile void __iomem *register_addr;
3007
3008         pqi_registers = ctrl_info->pqi_registers;
3009
3010         if (enable_intx)
3011                 register_addr = &pqi_registers->legacy_intx_mask_clear;
3012         else
3013                 register_addr = &pqi_registers->legacy_intx_mask_set;
3014
3015         intx_mask = readl(register_addr);
3016         intx_mask |= PQI_LEGACY_INTX_MASK;
3017         writel(intx_mask, register_addr);
3018 }
3019
3020 static void pqi_change_irq_mode(struct pqi_ctrl_info *ctrl_info,
3021         enum pqi_irq_mode new_mode)
3022 {
3023         switch (ctrl_info->irq_mode) {
3024         case IRQ_MODE_MSIX:
3025                 switch (new_mode) {
3026                 case IRQ_MODE_MSIX:
3027                         break;
3028                 case IRQ_MODE_INTX:
3029                         pqi_configure_legacy_intx(ctrl_info, true);
3030                         sis_enable_intx(ctrl_info);
3031                         break;
3032                 case IRQ_MODE_NONE:
3033                         break;
3034                 }
3035                 break;
3036         case IRQ_MODE_INTX:
3037                 switch (new_mode) {
3038                 case IRQ_MODE_MSIX:
3039                         pqi_configure_legacy_intx(ctrl_info, false);
3040                         sis_enable_msix(ctrl_info);
3041                         break;
3042                 case IRQ_MODE_INTX:
3043                         break;
3044                 case IRQ_MODE_NONE:
3045                         pqi_configure_legacy_intx(ctrl_info, false);
3046                         break;
3047                 }
3048                 break;
3049         case IRQ_MODE_NONE:
3050                 switch (new_mode) {
3051                 case IRQ_MODE_MSIX:
3052                         sis_enable_msix(ctrl_info);
3053                         break;
3054                 case IRQ_MODE_INTX:
3055                         pqi_configure_legacy_intx(ctrl_info, true);
3056                         sis_enable_intx(ctrl_info);
3057                         break;
3058                 case IRQ_MODE_NONE:
3059                         break;
3060                 }
3061                 break;
3062         }
3063
3064         ctrl_info->irq_mode = new_mode;
3065 }
3066
3067 #define PQI_LEGACY_INTX_PENDING         0x1
3068
3069 static inline bool pqi_is_valid_irq(struct pqi_ctrl_info *ctrl_info)
3070 {
3071         bool valid_irq;
3072         u32 intx_status;
3073
3074         switch (ctrl_info->irq_mode) {
3075         case IRQ_MODE_MSIX:
3076                 valid_irq = true;
3077                 break;
3078         case IRQ_MODE_INTX:
3079                 intx_status =
3080                         readl(&ctrl_info->pqi_registers->legacy_intx_status);
3081                 if (intx_status & PQI_LEGACY_INTX_PENDING)
3082                         valid_irq = true;
3083                 else
3084                         valid_irq = false;
3085                 break;
3086         case IRQ_MODE_NONE:
3087         default:
3088                 valid_irq = false;
3089                 break;
3090         }
3091
3092         return valid_irq;
3093 }
3094
3095 static irqreturn_t pqi_irq_handler(int irq, void *data)
3096 {
3097         struct pqi_ctrl_info *ctrl_info;
3098         struct pqi_queue_group *queue_group;
3099         unsigned int num_responses_handled;
3100
3101         queue_group = data;
3102         ctrl_info = queue_group->ctrl_info;
3103
3104         if (!pqi_is_valid_irq(ctrl_info))
3105                 return IRQ_NONE;
3106
3107         num_responses_handled = pqi_process_io_intr(ctrl_info, queue_group);
3108
3109         if (irq == ctrl_info->event_irq)
3110                 num_responses_handled += pqi_process_event_intr(ctrl_info);
3111
3112         if (num_responses_handled)
3113                 atomic_inc(&ctrl_info->num_interrupts);
3114
3115         pqi_start_io(ctrl_info, queue_group, RAID_PATH, NULL);
3116         pqi_start_io(ctrl_info, queue_group, AIO_PATH, NULL);
3117
3118         return IRQ_HANDLED;
3119 }
3120
3121 static int pqi_request_irqs(struct pqi_ctrl_info *ctrl_info)
3122 {
3123         struct pci_dev *pci_dev = ctrl_info->pci_dev;
3124         int i;
3125         int rc;
3126
3127         ctrl_info->event_irq = pci_irq_vector(pci_dev, 0);
3128
3129         for (i = 0; i < ctrl_info->num_msix_vectors_enabled; i++) {
3130                 rc = request_irq(pci_irq_vector(pci_dev, i), pqi_irq_handler, 0,
3131                         DRIVER_NAME_SHORT, &ctrl_info->queue_groups[i]);
3132                 if (rc) {
3133                         dev_err(&pci_dev->dev,
3134                                 "irq %u init failed with error %d\n",
3135                                 pci_irq_vector(pci_dev, i), rc);
3136                         return rc;
3137                 }
3138                 ctrl_info->num_msix_vectors_initialized++;
3139         }
3140
3141         return 0;
3142 }
3143
3144 static void pqi_free_irqs(struct pqi_ctrl_info *ctrl_info)
3145 {
3146         int i;
3147
3148         for (i = 0; i < ctrl_info->num_msix_vectors_initialized; i++)
3149                 free_irq(pci_irq_vector(ctrl_info->pci_dev, i),
3150                         &ctrl_info->queue_groups[i]);
3151
3152         ctrl_info->num_msix_vectors_initialized = 0;
3153 }
3154
3155 static int pqi_enable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3156 {
3157         int num_vectors_enabled;
3158
3159         num_vectors_enabled = pci_alloc_irq_vectors(ctrl_info->pci_dev,
3160                         PQI_MIN_MSIX_VECTORS, ctrl_info->num_queue_groups,
3161                         PCI_IRQ_MSIX | PCI_IRQ_AFFINITY);
3162         if (num_vectors_enabled < 0) {
3163                 dev_err(&ctrl_info->pci_dev->dev,
3164                         "MSI-X init failed with error %d\n",
3165                         num_vectors_enabled);
3166                 return num_vectors_enabled;
3167         }
3168
3169         ctrl_info->num_msix_vectors_enabled = num_vectors_enabled;
3170         ctrl_info->irq_mode = IRQ_MODE_MSIX;
3171         return 0;
3172 }
3173
3174 static void pqi_disable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3175 {
3176         if (ctrl_info->num_msix_vectors_enabled) {
3177                 pci_free_irq_vectors(ctrl_info->pci_dev);
3178                 ctrl_info->num_msix_vectors_enabled = 0;
3179         }
3180 }
3181
3182 static int pqi_alloc_operational_queues(struct pqi_ctrl_info *ctrl_info)
3183 {
3184         unsigned int i;
3185         size_t alloc_length;
3186         size_t element_array_length_per_iq;
3187         size_t element_array_length_per_oq;
3188         void *element_array;
3189         void __iomem *next_queue_index;
3190         void *aligned_pointer;
3191         unsigned int num_inbound_queues;
3192         unsigned int num_outbound_queues;
3193         unsigned int num_queue_indexes;
3194         struct pqi_queue_group *queue_group;
3195
3196         element_array_length_per_iq =
3197                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH *
3198                 ctrl_info->num_elements_per_iq;
3199         element_array_length_per_oq =
3200                 PQI_OPERATIONAL_OQ_ELEMENT_LENGTH *
3201                 ctrl_info->num_elements_per_oq;
3202         num_inbound_queues = ctrl_info->num_queue_groups * 2;
3203         num_outbound_queues = ctrl_info->num_queue_groups;
3204         num_queue_indexes = (ctrl_info->num_queue_groups * 3) + 1;
3205
3206         aligned_pointer = NULL;
3207
3208         for (i = 0; i < num_inbound_queues; i++) {
3209                 aligned_pointer = PTR_ALIGN(aligned_pointer,
3210                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3211                 aligned_pointer += element_array_length_per_iq;
3212         }
3213
3214         for (i = 0; i < num_outbound_queues; i++) {
3215                 aligned_pointer = PTR_ALIGN(aligned_pointer,
3216                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3217                 aligned_pointer += element_array_length_per_oq;
3218         }
3219
3220         aligned_pointer = PTR_ALIGN(aligned_pointer,
3221                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3222         aligned_pointer += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3223                 PQI_EVENT_OQ_ELEMENT_LENGTH;
3224
3225         for (i = 0; i < num_queue_indexes; i++) {
3226                 aligned_pointer = PTR_ALIGN(aligned_pointer,
3227                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3228                 aligned_pointer += sizeof(pqi_index_t);
3229         }
3230
3231         alloc_length = (size_t)aligned_pointer +
3232                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
3233
3234         alloc_length += PQI_EXTRA_SGL_MEMORY;
3235
3236         ctrl_info->queue_memory_base =
3237                 dma_zalloc_coherent(&ctrl_info->pci_dev->dev,
3238                         alloc_length,
3239                         &ctrl_info->queue_memory_base_dma_handle, GFP_KERNEL);
3240
3241         if (!ctrl_info->queue_memory_base)
3242                 return -ENOMEM;
3243
3244         ctrl_info->queue_memory_length = alloc_length;
3245
3246         element_array = PTR_ALIGN(ctrl_info->queue_memory_base,
3247                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3248
3249         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3250                 queue_group = &ctrl_info->queue_groups[i];
3251                 queue_group->iq_element_array[RAID_PATH] = element_array;
3252                 queue_group->iq_element_array_bus_addr[RAID_PATH] =
3253                         ctrl_info->queue_memory_base_dma_handle +
3254                                 (element_array - ctrl_info->queue_memory_base);
3255                 element_array += element_array_length_per_iq;
3256                 element_array = PTR_ALIGN(element_array,
3257                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3258                 queue_group->iq_element_array[AIO_PATH] = element_array;
3259                 queue_group->iq_element_array_bus_addr[AIO_PATH] =
3260                         ctrl_info->queue_memory_base_dma_handle +
3261                         (element_array - ctrl_info->queue_memory_base);
3262                 element_array += element_array_length_per_iq;
3263                 element_array = PTR_ALIGN(element_array,
3264                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3265         }
3266
3267         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3268                 queue_group = &ctrl_info->queue_groups[i];
3269                 queue_group->oq_element_array = element_array;
3270                 queue_group->oq_element_array_bus_addr =
3271                         ctrl_info->queue_memory_base_dma_handle +
3272                         (element_array - ctrl_info->queue_memory_base);
3273                 element_array += element_array_length_per_oq;
3274                 element_array = PTR_ALIGN(element_array,
3275                         PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3276         }
3277
3278         ctrl_info->event_queue.oq_element_array = element_array;
3279         ctrl_info->event_queue.oq_element_array_bus_addr =
3280                 ctrl_info->queue_memory_base_dma_handle +
3281                 (element_array - ctrl_info->queue_memory_base);
3282         element_array += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3283                 PQI_EVENT_OQ_ELEMENT_LENGTH;
3284
3285         next_queue_index = (void __iomem *)PTR_ALIGN(element_array,
3286                 PQI_OPERATIONAL_INDEX_ALIGNMENT);
3287
3288         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3289                 queue_group = &ctrl_info->queue_groups[i];
3290                 queue_group->iq_ci[RAID_PATH] = next_queue_index;
3291                 queue_group->iq_ci_bus_addr[RAID_PATH] =
3292                         ctrl_info->queue_memory_base_dma_handle +
3293                         (next_queue_index -
3294                         (void __iomem *)ctrl_info->queue_memory_base);
3295                 next_queue_index += sizeof(pqi_index_t);
3296                 next_queue_index = PTR_ALIGN(next_queue_index,
3297                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3298                 queue_group->iq_ci[AIO_PATH] = next_queue_index;
3299                 queue_group->iq_ci_bus_addr[AIO_PATH] =
3300                         ctrl_info->queue_memory_base_dma_handle +
3301                         (next_queue_index -
3302                         (void __iomem *)ctrl_info->queue_memory_base);
3303                 next_queue_index += sizeof(pqi_index_t);
3304                 next_queue_index = PTR_ALIGN(next_queue_index,
3305                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3306                 queue_group->oq_pi = next_queue_index;
3307                 queue_group->oq_pi_bus_addr =
3308                         ctrl_info->queue_memory_base_dma_handle +
3309                         (next_queue_index -
3310                         (void __iomem *)ctrl_info->queue_memory_base);
3311                 next_queue_index += sizeof(pqi_index_t);
3312                 next_queue_index = PTR_ALIGN(next_queue_index,
3313                         PQI_OPERATIONAL_INDEX_ALIGNMENT);
3314         }
3315
3316         ctrl_info->event_queue.oq_pi = next_queue_index;
3317         ctrl_info->event_queue.oq_pi_bus_addr =
3318                 ctrl_info->queue_memory_base_dma_handle +
3319                 (next_queue_index -
3320                 (void __iomem *)ctrl_info->queue_memory_base);
3321
3322         return 0;
3323 }
3324
3325 static void pqi_init_operational_queues(struct pqi_ctrl_info *ctrl_info)
3326 {
3327         unsigned int i;
3328         u16 next_iq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3329         u16 next_oq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3330
3331         /*
3332          * Initialize the backpointers to the controller structure in
3333          * each operational queue group structure.
3334          */
3335         for (i = 0; i < ctrl_info->num_queue_groups; i++)
3336                 ctrl_info->queue_groups[i].ctrl_info = ctrl_info;
3337
3338         /*
3339          * Assign IDs to all operational queues.  Note that the IDs
3340          * assigned to operational IQs are independent of the IDs
3341          * assigned to operational OQs.
3342          */
3343         ctrl_info->event_queue.oq_id = next_oq_id++;
3344         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3345                 ctrl_info->queue_groups[i].iq_id[RAID_PATH] = next_iq_id++;
3346                 ctrl_info->queue_groups[i].iq_id[AIO_PATH] = next_iq_id++;
3347                 ctrl_info->queue_groups[i].oq_id = next_oq_id++;
3348         }
3349
3350         /*
3351          * Assign MSI-X table entry indexes to all queues.  Note that the
3352          * interrupt for the event queue is shared with the first queue group.
3353          */
3354         ctrl_info->event_queue.int_msg_num = 0;
3355         for (i = 0; i < ctrl_info->num_queue_groups; i++)
3356                 ctrl_info->queue_groups[i].int_msg_num = i;
3357
3358         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3359                 spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[0]);
3360                 spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[1]);
3361                 INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[0]);
3362                 INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[1]);
3363         }
3364 }
3365
3366 static int pqi_alloc_admin_queues(struct pqi_ctrl_info *ctrl_info)
3367 {
3368         size_t alloc_length;
3369         struct pqi_admin_queues_aligned *admin_queues_aligned;
3370         struct pqi_admin_queues *admin_queues;
3371
3372         alloc_length = sizeof(struct pqi_admin_queues_aligned) +
3373                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
3374
3375         ctrl_info->admin_queue_memory_base =
3376                 dma_zalloc_coherent(&ctrl_info->pci_dev->dev,
3377                         alloc_length,
3378                         &ctrl_info->admin_queue_memory_base_dma_handle,
3379                         GFP_KERNEL);
3380
3381         if (!ctrl_info->admin_queue_memory_base)
3382                 return -ENOMEM;
3383
3384         ctrl_info->admin_queue_memory_length = alloc_length;
3385
3386         admin_queues = &ctrl_info->admin_queues;
3387         admin_queues_aligned = PTR_ALIGN(ctrl_info->admin_queue_memory_base,
3388                 PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3389         admin_queues->iq_element_array =
3390                 &admin_queues_aligned->iq_element_array;
3391         admin_queues->oq_element_array =
3392                 &admin_queues_aligned->oq_element_array;
3393         admin_queues->iq_ci = &admin_queues_aligned->iq_ci;
3394         admin_queues->oq_pi =
3395                 (pqi_index_t __iomem *)&admin_queues_aligned->oq_pi;
3396
3397         admin_queues->iq_element_array_bus_addr =
3398                 ctrl_info->admin_queue_memory_base_dma_handle +
3399                 (admin_queues->iq_element_array -
3400                 ctrl_info->admin_queue_memory_base);
3401         admin_queues->oq_element_array_bus_addr =
3402                 ctrl_info->admin_queue_memory_base_dma_handle +
3403                 (admin_queues->oq_element_array -
3404                 ctrl_info->admin_queue_memory_base);
3405         admin_queues->iq_ci_bus_addr =
3406                 ctrl_info->admin_queue_memory_base_dma_handle +
3407                 ((void *)admin_queues->iq_ci -
3408                 ctrl_info->admin_queue_memory_base);
3409         admin_queues->oq_pi_bus_addr =
3410                 ctrl_info->admin_queue_memory_base_dma_handle +
3411                 ((void __iomem *)admin_queues->oq_pi -
3412                 (void __iomem *)ctrl_info->admin_queue_memory_base);
3413
3414         return 0;
3415 }
3416
3417 #define PQI_ADMIN_QUEUE_CREATE_TIMEOUT_JIFFIES          HZ
3418 #define PQI_ADMIN_QUEUE_CREATE_POLL_INTERVAL_MSECS      1
3419
3420 static int pqi_create_admin_queues(struct pqi_ctrl_info *ctrl_info)
3421 {
3422         struct pqi_device_registers __iomem *pqi_registers;
3423         struct pqi_admin_queues *admin_queues;
3424         unsigned long timeout;
3425         u8 status;
3426         u32 reg;
3427
3428         pqi_registers = ctrl_info->pqi_registers;
3429         admin_queues = &ctrl_info->admin_queues;
3430
3431         writeq((u64)admin_queues->iq_element_array_bus_addr,
3432                 &pqi_registers->admin_iq_element_array_addr);
3433         writeq((u64)admin_queues->oq_element_array_bus_addr,
3434                 &pqi_registers->admin_oq_element_array_addr);
3435         writeq((u64)admin_queues->iq_ci_bus_addr,
3436                 &pqi_registers->admin_iq_ci_addr);
3437         writeq((u64)admin_queues->oq_pi_bus_addr,
3438                 &pqi_registers->admin_oq_pi_addr);
3439
3440         reg = PQI_ADMIN_IQ_NUM_ELEMENTS |
3441                 (PQI_ADMIN_OQ_NUM_ELEMENTS) << 8 |
3442                 (admin_queues->int_msg_num << 16);
3443         writel(reg, &pqi_registers->admin_iq_num_elements);
3444         writel(PQI_CREATE_ADMIN_QUEUE_PAIR,
3445                 &pqi_registers->function_and_status_code);
3446
3447         timeout = PQI_ADMIN_QUEUE_CREATE_TIMEOUT_JIFFIES + jiffies;
3448         while (1) {
3449                 status = readb(&pqi_registers->function_and_status_code);
3450                 if (status == PQI_STATUS_IDLE)
3451                         break;
3452                 if (time_after(jiffies, timeout))
3453                         return -ETIMEDOUT;
3454                 msleep(PQI_ADMIN_QUEUE_CREATE_POLL_INTERVAL_MSECS);
3455         }
3456
3457         /*
3458          * The offset registers are not initialized to the correct
3459          * offsets until *after* the create admin queue pair command
3460          * completes successfully.
3461          */
3462         admin_queues->iq_pi = ctrl_info->iomem_base +
3463                 PQI_DEVICE_REGISTERS_OFFSET +
3464                 readq(&pqi_registers->admin_iq_pi_offset);
3465         admin_queues->oq_ci = ctrl_info->iomem_base +
3466                 PQI_DEVICE_REGISTERS_OFFSET +
3467                 readq(&pqi_registers->admin_oq_ci_offset);
3468
3469         return 0;
3470 }
3471
3472 static void pqi_submit_admin_request(struct pqi_ctrl_info *ctrl_info,
3473         struct pqi_general_admin_request *request)
3474 {
3475         struct pqi_admin_queues *admin_queues;
3476         void *next_element;
3477         pqi_index_t iq_pi;
3478
3479         admin_queues = &ctrl_info->admin_queues;
3480         iq_pi = admin_queues->iq_pi_copy;
3481
3482         next_element = admin_queues->iq_element_array +
3483                 (iq_pi * PQI_ADMIN_IQ_ELEMENT_LENGTH);
3484
3485         memcpy(next_element, request, sizeof(*request));
3486
3487         iq_pi = (iq_pi + 1) % PQI_ADMIN_IQ_NUM_ELEMENTS;
3488         admin_queues->iq_pi_copy = iq_pi;
3489
3490         /*
3491          * This write notifies the controller that an IU is available to be
3492          * processed.
3493          */
3494         writel(iq_pi, admin_queues->iq_pi);
3495 }
3496
3497 #define PQI_ADMIN_REQUEST_TIMEOUT_SECS  60
3498
3499 static int pqi_poll_for_admin_response(struct pqi_ctrl_info *ctrl_info,
3500         struct pqi_general_admin_response *response)
3501 {
3502         struct pqi_admin_queues *admin_queues;
3503         pqi_index_t oq_pi;
3504         pqi_index_t oq_ci;
3505         unsigned long timeout;
3506
3507         admin_queues = &ctrl_info->admin_queues;
3508         oq_ci = admin_queues->oq_ci_copy;
3509
3510         timeout = (PQI_ADMIN_REQUEST_TIMEOUT_SECS * HZ) + jiffies;
3511
3512         while (1) {
3513                 oq_pi = readl(admin_queues->oq_pi);
3514                 if (oq_pi != oq_ci)
3515                         break;
3516                 if (time_after(jiffies, timeout)) {
3517                         dev_err(&ctrl_info->pci_dev->dev,
3518                                 "timed out waiting for admin response\n");
3519                         return -ETIMEDOUT;
3520                 }
3521                 if (!sis_is_firmware_running(ctrl_info))
3522                         return -ENXIO;
3523                 usleep_range(1000, 2000);
3524         }
3525
3526         memcpy(response, admin_queues->oq_element_array +
3527                 (oq_ci * PQI_ADMIN_OQ_ELEMENT_LENGTH), sizeof(*response));
3528
3529         oq_ci = (oq_ci + 1) % PQI_ADMIN_OQ_NUM_ELEMENTS;
3530         admin_queues->oq_ci_copy = oq_ci;
3531         writel(oq_ci, admin_queues->oq_ci);
3532
3533         return 0;
3534 }
3535
3536 static void pqi_start_io(struct pqi_ctrl_info *ctrl_info,
3537         struct pqi_queue_group *queue_group, enum pqi_io_path path,
3538         struct pqi_io_request *io_request)
3539 {
3540         struct pqi_io_request *next;
3541         void *next_element;
3542         pqi_index_t iq_pi;
3543         pqi_index_t iq_ci;
3544         size_t iu_length;
3545         unsigned long flags;
3546         unsigned int num_elements_needed;
3547         unsigned int num_elements_to_end_of_queue;
3548         size_t copy_count;
3549         struct pqi_iu_header *request;
3550
3551         spin_lock_irqsave(&queue_group->submit_lock[path], flags);
3552
3553         if (io_request) {
3554                 io_request->queue_group = queue_group;
3555                 list_add_tail(&io_request->request_list_entry,
3556                         &queue_group->request_list[path]);
3557         }
3558
3559         iq_pi = queue_group->iq_pi_copy[path];
3560
3561         list_for_each_entry_safe(io_request, next,
3562                 &queue_group->request_list[path], request_list_entry) {
3563
3564                 request = io_request->iu;
3565
3566                 iu_length = get_unaligned_le16(&request->iu_length) +
3567                         PQI_REQUEST_HEADER_LENGTH;
3568                 num_elements_needed =
3569                         DIV_ROUND_UP(iu_length,
3570                                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
3571
3572                 iq_ci = readl(queue_group->iq_ci[path]);
3573
3574                 if (num_elements_needed > pqi_num_elements_free(iq_pi, iq_ci,
3575                         ctrl_info->num_elements_per_iq))
3576                         break;
3577
3578                 put_unaligned_le16(queue_group->oq_id,
3579                         &request->response_queue_id);
3580
3581                 next_element = queue_group->iq_element_array[path] +
3582                         (iq_pi * PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
3583
3584                 num_elements_to_end_of_queue =
3585                         ctrl_info->num_elements_per_iq - iq_pi;
3586
3587                 if (num_elements_needed <= num_elements_to_end_of_queue) {
3588                         memcpy(next_element, request, iu_length);
3589                 } else {
3590                         copy_count = num_elements_to_end_of_queue *
3591                                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH;
3592                         memcpy(next_element, request, copy_count);
3593                         memcpy(queue_group->iq_element_array[path],
3594                                 (u8 *)request + copy_count,
3595                                 iu_length - copy_count);
3596                 }
3597
3598                 iq_pi = (iq_pi + num_elements_needed) %
3599                         ctrl_info->num_elements_per_iq;
3600
3601                 list_del(&io_request->request_list_entry);
3602         }
3603
3604         if (iq_pi != queue_group->iq_pi_copy[path]) {
3605                 queue_group->iq_pi_copy[path] = iq_pi;
3606                 /*
3607                  * This write notifies the controller that one or more IUs are
3608                  * available to be processed.
3609                  */
3610                 writel(iq_pi, queue_group->iq_pi[path]);
3611         }
3612
3613         spin_unlock_irqrestore(&queue_group->submit_lock[path], flags);
3614 }
3615
3616 #define PQI_WAIT_FOR_COMPLETION_IO_TIMEOUT_SECS         10
3617
3618 static int pqi_wait_for_completion_io(struct pqi_ctrl_info *ctrl_info,
3619         struct completion *wait)
3620 {
3621         int rc;
3622
3623         while (1) {
3624                 if (wait_for_completion_io_timeout(wait,
3625                         PQI_WAIT_FOR_COMPLETION_IO_TIMEOUT_SECS * HZ)) {
3626                         rc = 0;
3627                         break;
3628                 }
3629
3630                 pqi_check_ctrl_health(ctrl_info);
3631                 if (pqi_ctrl_offline(ctrl_info)) {
3632                         rc = -ENXIO;
3633                         break;
3634                 }
3635         }
3636
3637         return rc;
3638 }
3639
3640 static void pqi_raid_synchronous_complete(struct pqi_io_request *io_request,
3641         void *context)
3642 {
3643         struct completion *waiting = context;
3644
3645         complete(waiting);
3646 }
3647
3648 static int pqi_process_raid_io_error_synchronous(struct pqi_raid_error_info
3649                                                 *error_info)
3650 {
3651         int rc = -EIO;
3652
3653         switch (error_info->data_out_result) {
3654         case PQI_DATA_IN_OUT_GOOD:
3655                 if (error_info->status == SAM_STAT_GOOD)
3656                         rc = 0;
3657                 break;
3658         case PQI_DATA_IN_OUT_UNDERFLOW:
3659                 if (error_info->status == SAM_STAT_GOOD ||
3660                         error_info->status == SAM_STAT_CHECK_CONDITION)
3661                         rc = 0;
3662                 break;
3663         case PQI_DATA_IN_OUT_ABORTED:
3664                 rc = PQI_CMD_STATUS_ABORTED;
3665                 break;
3666         }
3667
3668         return rc;
3669 }
3670
3671 static int pqi_submit_raid_request_synchronous(struct pqi_ctrl_info *ctrl_info,
3672         struct pqi_iu_header *request, unsigned int flags,
3673         struct pqi_raid_error_info *error_info, unsigned long timeout_msecs)
3674 {
3675         int rc = 0;
3676         struct pqi_io_request *io_request;
3677         unsigned long start_jiffies;
3678         unsigned long msecs_blocked;
3679         size_t iu_length;
3680         DECLARE_COMPLETION_ONSTACK(wait);
3681
3682         /*
3683          * Note that specifying PQI_SYNC_FLAGS_INTERRUPTABLE and a timeout value
3684          * are mutually exclusive.
3685          */
3686
3687         if (flags & PQI_SYNC_FLAGS_INTERRUPTABLE) {
3688                 if (down_interruptible(&ctrl_info->sync_request_sem))
3689                         return -ERESTARTSYS;
3690         } else {
3691                 if (timeout_msecs == NO_TIMEOUT) {
3692                         down(&ctrl_info->sync_request_sem);
3693                 } else {
3694                         start_jiffies = jiffies;
3695                         if (down_timeout(&ctrl_info->sync_request_sem,
3696                                 msecs_to_jiffies(timeout_msecs)))
3697                                 return -ETIMEDOUT;
3698                         msecs_blocked =
3699                                 jiffies_to_msecs(jiffies - start_jiffies);
3700                         if (msecs_blocked >= timeout_msecs) {
3701                                 rc = -ETIMEDOUT;
3702                                 goto out;
3703                         }
3704                         timeout_msecs -= msecs_blocked;
3705                 }
3706         }
3707
3708         pqi_ctrl_busy(ctrl_info);
3709         timeout_msecs = pqi_wait_if_ctrl_blocked(ctrl_info, timeout_msecs);
3710         if (timeout_msecs == 0) {
3711                 pqi_ctrl_unbusy(ctrl_info);
3712                 rc = -ETIMEDOUT;
3713                 goto out;
3714         }
3715
3716         if (pqi_ctrl_offline(ctrl_info)) {
3717                 pqi_ctrl_unbusy(ctrl_info);
3718                 rc = -ENXIO;
3719                 goto out;
3720         }
3721
3722         io_request = pqi_alloc_io_request(ctrl_info);
3723
3724         put_unaligned_le16(io_request->index,
3725                 &(((struct pqi_raid_path_request *)request)->request_id));
3726
3727         if (request->iu_type == PQI_REQUEST_IU_RAID_PATH_IO)
3728                 ((struct pqi_raid_path_request *)request)->error_index =
3729                         ((struct pqi_raid_path_request *)request)->request_id;
3730
3731         iu_length = get_unaligned_le16(&request->iu_length) +
3732                 PQI_REQUEST_HEADER_LENGTH;
3733         memcpy(io_request->iu, request, iu_length);
3734
3735         io_request->io_complete_callback = pqi_raid_synchronous_complete;
3736         io_request->context = &wait;
3737
3738         pqi_start_io(ctrl_info,
3739                 &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP], RAID_PATH,
3740                 io_request);
3741
3742         pqi_ctrl_unbusy(ctrl_info);
3743
3744         if (timeout_msecs == NO_TIMEOUT) {
3745                 pqi_wait_for_completion_io(ctrl_info, &wait);
3746         } else {
3747                 if (!wait_for_completion_io_timeout(&wait,
3748                         msecs_to_jiffies(timeout_msecs))) {
3749                         dev_warn(&ctrl_info->pci_dev->dev,
3750                                 "command timed out\n");
3751                         rc = -ETIMEDOUT;
3752                 }
3753         }
3754
3755         if (error_info) {
3756                 if (io_request->error_info)
3757                         memcpy(error_info, io_request->error_info,
3758                                 sizeof(*error_info));
3759                 else
3760                         memset(error_info, 0, sizeof(*error_info));
3761         } else if (rc == 0 && io_request->error_info) {
3762                 rc = pqi_process_raid_io_error_synchronous(
3763                         io_request->error_info);
3764         }
3765
3766         pqi_free_io_request(io_request);
3767
3768 out:
3769         up(&ctrl_info->sync_request_sem);
3770
3771         return rc;
3772 }
3773
3774 static int pqi_validate_admin_response(
3775         struct pqi_general_admin_response *response, u8 expected_function_code)
3776 {
3777         if (response->header.iu_type != PQI_RESPONSE_IU_GENERAL_ADMIN)
3778                 return -EINVAL;
3779
3780         if (get_unaligned_le16(&response->header.iu_length) !=
3781                 PQI_GENERAL_ADMIN_IU_LENGTH)
3782                 return -EINVAL;
3783
3784         if (response->function_code != expected_function_code)
3785                 return -EINVAL;
3786
3787         if (response->status != PQI_GENERAL_ADMIN_STATUS_SUCCESS)
3788                 return -EINVAL;
3789
3790         return 0;
3791 }
3792
3793 static int pqi_submit_admin_request_synchronous(
3794         struct pqi_ctrl_info *ctrl_info,
3795         struct pqi_general_admin_request *request,
3796         struct pqi_general_admin_response *response)
3797 {
3798         int rc;
3799
3800         pqi_submit_admin_request(ctrl_info, request);
3801
3802         rc = pqi_poll_for_admin_response(ctrl_info, response);
3803
3804         if (rc == 0)
3805                 rc = pqi_validate_admin_response(response,
3806                         request->function_code);
3807
3808         return rc;
3809 }
3810
3811 static int pqi_report_device_capability(struct pqi_ctrl_info *ctrl_info)
3812 {
3813         int rc;
3814         struct pqi_general_admin_request request;
3815         struct pqi_general_admin_response response;
3816         struct pqi_device_capability *capability;
3817         struct pqi_iu_layer_descriptor *sop_iu_layer_descriptor;
3818
3819         capability = kmalloc(sizeof(*capability), GFP_KERNEL);
3820         if (!capability)
3821                 return -ENOMEM;
3822
3823         memset(&request, 0, sizeof(request));
3824
3825         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
3826         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
3827                 &request.header.iu_length);
3828         request.function_code =
3829                 PQI_GENERAL_ADMIN_FUNCTION_REPORT_DEVICE_CAPABILITY;
3830         put_unaligned_le32(sizeof(*capability),
3831                 &request.data.report_device_capability.buffer_length);
3832
3833         rc = pqi_map_single(ctrl_info->pci_dev,
3834                 &request.data.report_device_capability.sg_descriptor,
3835                 capability, sizeof(*capability),
3836                 PCI_DMA_FROMDEVICE);
3837         if (rc)
3838                 goto out;
3839
3840         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
3841                 &response);
3842
3843         pqi_pci_unmap(ctrl_info->pci_dev,
3844                 &request.data.report_device_capability.sg_descriptor, 1,
3845                 PCI_DMA_FROMDEVICE);
3846
3847         if (rc)
3848                 goto out;
3849
3850         if (response.status != PQI_GENERAL_ADMIN_STATUS_SUCCESS) {
3851                 rc = -EIO;
3852                 goto out;
3853         }
3854
3855         ctrl_info->max_inbound_queues =
3856                 get_unaligned_le16(&capability->max_inbound_queues);
3857         ctrl_info->max_elements_per_iq =
3858                 get_unaligned_le16(&capability->max_elements_per_iq);
3859         ctrl_info->max_iq_element_length =
3860                 get_unaligned_le16(&capability->max_iq_element_length)
3861                 * 16;
3862         ctrl_info->max_outbound_queues =
3863                 get_unaligned_le16(&capability->max_outbound_queues);
3864         ctrl_info->max_elements_per_oq =
3865                 get_unaligned_le16(&capability->max_elements_per_oq);
3866         ctrl_info->max_oq_element_length =
3867                 get_unaligned_le16(&capability->max_oq_element_length)
3868                 * 16;
3869
3870         sop_iu_layer_descriptor =
3871                 &capability->iu_layer_descriptors[PQI_PROTOCOL_SOP];
3872
3873         ctrl_info->max_inbound_iu_length_per_firmware =
3874                 get_unaligned_le16(
3875                         &sop_iu_layer_descriptor->max_inbound_iu_length);
3876         ctrl_info->inbound_spanning_supported =
3877                 sop_iu_layer_descriptor->inbound_spanning_supported;
3878         ctrl_info->outbound_spanning_supported =
3879                 sop_iu_layer_descriptor->outbound_spanning_supported;
3880
3881 out:
3882         kfree(capability);
3883
3884         return rc;
3885 }
3886
3887 static int pqi_validate_device_capability(struct pqi_ctrl_info *ctrl_info)
3888 {
3889         if (ctrl_info->max_iq_element_length <
3890                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) {
3891                 dev_err(&ctrl_info->pci_dev->dev,
3892                         "max. inbound queue element length of %d is less than the required length of %d\n",
3893                         ctrl_info->max_iq_element_length,
3894                         PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
3895                 return -EINVAL;
3896         }
3897
3898         if (ctrl_info->max_oq_element_length <
3899                 PQI_OPERATIONAL_OQ_ELEMENT_LENGTH) {
3900                 dev_err(&ctrl_info->pci_dev->dev,
3901                         "max. outbound queue element length of %d is less than the required length of %d\n",
3902                         ctrl_info->max_oq_element_length,
3903                         PQI_OPERATIONAL_OQ_ELEMENT_LENGTH);
3904                 return -EINVAL;
3905         }
3906
3907         if (ctrl_info->max_inbound_iu_length_per_firmware <
3908                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) {
3909                 dev_err(&ctrl_info->pci_dev->dev,
3910                         "max. inbound IU length of %u is less than the min. required length of %d\n",
3911                         ctrl_info->max_inbound_iu_length_per_firmware,
3912                         PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
3913                 return -EINVAL;
3914         }
3915
3916         if (!ctrl_info->inbound_spanning_supported) {
3917                 dev_err(&ctrl_info->pci_dev->dev,
3918                         "the controller does not support inbound spanning\n");
3919                 return -EINVAL;
3920         }
3921
3922         if (ctrl_info->outbound_spanning_supported) {
3923                 dev_err(&ctrl_info->pci_dev->dev,
3924                         "the controller supports outbound spanning but this driver does not\n");
3925                 return -EINVAL;
3926         }
3927
3928         return 0;
3929 }
3930
3931 static int pqi_create_event_queue(struct pqi_ctrl_info *ctrl_info)
3932 {
3933         int rc;
3934         struct pqi_event_queue *event_queue;
3935         struct pqi_general_admin_request request;
3936         struct pqi_general_admin_response response;
3937
3938         event_queue = &ctrl_info->event_queue;
3939
3940         /*
3941          * Create OQ (Outbound Queue - device to host queue) to dedicate
3942          * to events.
3943          */
3944         memset(&request, 0, sizeof(request));
3945         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
3946         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
3947                 &request.header.iu_length);
3948         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_OQ;
3949         put_unaligned_le16(event_queue->oq_id,
3950                 &request.data.create_operational_oq.queue_id);
3951         put_unaligned_le64((u64)event_queue->oq_element_array_bus_addr,
3952                 &request.data.create_operational_oq.element_array_addr);
3953         put_unaligned_le64((u64)event_queue->oq_pi_bus_addr,
3954                 &request.data.create_operational_oq.pi_addr);
3955         put_unaligned_le16(PQI_NUM_EVENT_QUEUE_ELEMENTS,
3956                 &request.data.create_operational_oq.num_elements);
3957         put_unaligned_le16(PQI_EVENT_OQ_ELEMENT_LENGTH / 16,
3958                 &request.data.create_operational_oq.element_length);
3959         request.data.create_operational_oq.queue_protocol = PQI_PROTOCOL_SOP;
3960         put_unaligned_le16(event_queue->int_msg_num,
3961                 &request.data.create_operational_oq.int_msg_num);
3962
3963         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
3964                 &response);
3965         if (rc)
3966                 return rc;
3967
3968         event_queue->oq_ci = ctrl_info->iomem_base +
3969                 PQI_DEVICE_REGISTERS_OFFSET +
3970                 get_unaligned_le64(
3971                         &response.data.create_operational_oq.oq_ci_offset);
3972
3973         return 0;
3974 }
3975
3976 static int pqi_create_queue_group(struct pqi_ctrl_info *ctrl_info,
3977         unsigned int group_number)
3978 {
3979         int rc;
3980         struct pqi_queue_group *queue_group;
3981         struct pqi_general_admin_request request;
3982         struct pqi_general_admin_response response;
3983
3984         queue_group = &ctrl_info->queue_groups[group_number];
3985
3986         /*
3987          * Create IQ (Inbound Queue - host to device queue) for
3988          * RAID path.
3989          */
3990         memset(&request, 0, sizeof(request));
3991         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
3992         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
3993                 &request.header.iu_length);
3994         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_IQ;
3995         put_unaligned_le16(queue_group->iq_id[RAID_PATH],
3996                 &request.data.create_operational_iq.queue_id);
3997         put_unaligned_le64(
3998                 (u64)queue_group->iq_element_array_bus_addr[RAID_PATH],
3999                 &request.data.create_operational_iq.element_array_addr);
4000         put_unaligned_le64((u64)queue_group->iq_ci_bus_addr[RAID_PATH],
4001                 &request.data.create_operational_iq.ci_addr);
4002         put_unaligned_le16(ctrl_info->num_elements_per_iq,
4003                 &request.data.create_operational_iq.num_elements);
4004         put_unaligned_le16(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH / 16,
4005                 &request.data.create_operational_iq.element_length);
4006         request.data.create_operational_iq.queue_protocol = PQI_PROTOCOL_SOP;
4007
4008         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4009                 &response);
4010         if (rc) {
4011                 dev_err(&ctrl_info->pci_dev->dev,
4012                         "error creating inbound RAID queue\n");
4013                 return rc;
4014         }
4015
4016         queue_group->iq_pi[RAID_PATH] = ctrl_info->iomem_base +
4017                 PQI_DEVICE_REGISTERS_OFFSET +
4018                 get_unaligned_le64(
4019                         &response.data.create_operational_iq.iq_pi_offset);
4020
4021         /*
4022          * Create IQ (Inbound Queue - host to device queue) for
4023          * Advanced I/O (AIO) path.
4024          */
4025         memset(&request, 0, sizeof(request));
4026         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4027         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4028                 &request.header.iu_length);
4029         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_IQ;
4030         put_unaligned_le16(queue_group->iq_id[AIO_PATH],
4031                 &request.data.create_operational_iq.queue_id);
4032         put_unaligned_le64((u64)queue_group->
4033                 iq_element_array_bus_addr[AIO_PATH],
4034                 &request.data.create_operational_iq.element_array_addr);
4035         put_unaligned_le64((u64)queue_group->iq_ci_bus_addr[AIO_PATH],
4036                 &request.data.create_operational_iq.ci_addr);
4037         put_unaligned_le16(ctrl_info->num_elements_per_iq,
4038                 &request.data.create_operational_iq.num_elements);
4039         put_unaligned_le16(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH / 16,
4040                 &request.data.create_operational_iq.element_length);
4041         request.data.create_operational_iq.queue_protocol = PQI_PROTOCOL_SOP;
4042
4043         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4044                 &response);
4045         if (rc) {
4046                 dev_err(&ctrl_info->pci_dev->dev,
4047                         "error creating inbound AIO queue\n");
4048                 return rc;
4049         }
4050
4051         queue_group->iq_pi[AIO_PATH] = ctrl_info->iomem_base +
4052                 PQI_DEVICE_REGISTERS_OFFSET +
4053                 get_unaligned_le64(
4054                         &response.data.create_operational_iq.iq_pi_offset);
4055
4056         /*
4057          * Designate the 2nd IQ as the AIO path.  By default, all IQs are
4058          * assumed to be for RAID path I/O unless we change the queue's
4059          * property.
4060          */
4061         memset(&request, 0, sizeof(request));
4062         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4063         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4064                 &request.header.iu_length);
4065         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CHANGE_IQ_PROPERTY;
4066         put_unaligned_le16(queue_group->iq_id[AIO_PATH],
4067                 &request.data.change_operational_iq_properties.queue_id);
4068         put_unaligned_le32(PQI_IQ_PROPERTY_IS_AIO_QUEUE,
4069                 &request.data.change_operational_iq_properties.vendor_specific);
4070
4071         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4072                 &response);
4073         if (rc) {
4074                 dev_err(&ctrl_info->pci_dev->dev,
4075                         "error changing queue property\n");
4076                 return rc;
4077         }
4078
4079         /*
4080          * Create OQ (Outbound Queue - device to host queue).
4081          */
4082         memset(&request, 0, sizeof(request));
4083         request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4084         put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4085                 &request.header.iu_length);
4086         request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_OQ;
4087         put_unaligned_le16(queue_group->oq_id,
4088                 &request.data.create_operational_oq.queue_id);
4089         put_unaligned_le64((u64)queue_group->oq_element_array_bus_addr,
4090                 &request.data.create_operational_oq.element_array_addr);
4091         put_unaligned_le64((u64)queue_group->oq_pi_bus_addr,
4092                 &request.data.create_operational_oq.pi_addr);
4093         put_unaligned_le16(ctrl_info->num_elements_per_oq,
4094                 &request.data.create_operational_oq.num_elements);
4095         put_unaligned_le16(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH / 16,
4096                 &request.data.create_operational_oq.element_length);
4097         request.data.create_operational_oq.queue_protocol = PQI_PROTOCOL_SOP;
4098         put_unaligned_le16(queue_group->int_msg_num,
4099                 &request.data.create_operational_oq.int_msg_num);
4100
4101         rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4102                 &response);
4103         if (rc) {
4104                 dev_err(&ctrl_info->pci_dev->dev,
4105                         "error creating outbound queue\n");
4106                 return rc;
4107         }
4108
4109         queue_group->oq_ci = ctrl_info->iomem_base +
4110                 PQI_DEVICE_REGISTERS_OFFSET +
4111                 get_unaligned_le64(
4112                         &response.data.create_operational_oq.oq_ci_offset);
4113
4114         return 0;
4115 }
4116
4117 static int pqi_create_queues(struct pqi_ctrl_info *ctrl_info)
4118 {
4119         int rc;
4120         unsigned int i;
4121
4122         rc = pqi_create_event_queue(ctrl_info);
4123         if (rc) {
4124                 dev_err(&ctrl_info->pci_dev->dev,
4125                         "error creating event queue\n");
4126                 return rc;
4127         }
4128
4129         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
4130                 rc = pqi_create_queue_group(ctrl_info, i);
4131                 if (rc) {
4132                         dev_err(&ctrl_info->pci_dev->dev,
4133                                 "error creating queue group number %u/%u\n",
4134                                 i, ctrl_info->num_queue_groups);
4135                         return rc;
4136                 }
4137         }
4138
4139         return 0;
4140 }
4141
4142 #define PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH   \
4143         (offsetof(struct pqi_event_config, descriptors) + \
4144         (PQI_MAX_EVENT_DESCRIPTORS * sizeof(struct pqi_event_descriptor)))
4145
4146 static int pqi_configure_events(struct pqi_ctrl_info *ctrl_info,
4147         bool enable_events)
4148 {
4149         int rc;
4150         unsigned int i;
4151         struct pqi_event_config *event_config;
4152         struct pqi_event_descriptor *event_descriptor;
4153         struct pqi_general_management_request request;
4154
4155         event_config = kmalloc(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4156                 GFP_KERNEL);
4157         if (!event_config)
4158                 return -ENOMEM;
4159
4160         memset(&request, 0, sizeof(request));
4161
4162         request.header.iu_type = PQI_REQUEST_IU_REPORT_VENDOR_EVENT_CONFIG;
4163         put_unaligned_le16(offsetof(struct pqi_general_management_request,
4164                 data.report_event_configuration.sg_descriptors[1]) -
4165                 PQI_REQUEST_HEADER_LENGTH, &request.header.iu_length);
4166         put_unaligned_le32(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4167                 &request.data.report_event_configuration.buffer_length);
4168
4169         rc = pqi_map_single(ctrl_info->pci_dev,
4170                 request.data.report_event_configuration.sg_descriptors,
4171                 event_config, PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4172                 PCI_DMA_FROMDEVICE);
4173         if (rc)
4174                 goto out;
4175
4176         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
4177                 0, NULL, NO_TIMEOUT);
4178
4179         pqi_pci_unmap(ctrl_info->pci_dev,
4180                 request.data.report_event_configuration.sg_descriptors, 1,
4181                 PCI_DMA_FROMDEVICE);
4182
4183         if (rc)
4184                 goto out;
4185
4186         for (i = 0; i < event_config->num_event_descriptors; i++) {
4187                 event_descriptor = &event_config->descriptors[i];
4188                 if (enable_events &&
4189                         pqi_is_supported_event(event_descriptor->event_type))
4190                         put_unaligned_le16(ctrl_info->event_queue.oq_id,
4191                                         &event_descriptor->oq_id);
4192                 else
4193                         put_unaligned_le16(0, &event_descriptor->oq_id);
4194         }
4195
4196         memset(&request, 0, sizeof(request));
4197
4198         request.header.iu_type = PQI_REQUEST_IU_SET_VENDOR_EVENT_CONFIG;
4199         put_unaligned_le16(offsetof(struct pqi_general_management_request,
4200                 data.report_event_configuration.sg_descriptors[1]) -
4201                 PQI_REQUEST_HEADER_LENGTH, &request.header.iu_length);
4202         put_unaligned_le32(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4203                 &request.data.report_event_configuration.buffer_length);
4204
4205         rc = pqi_map_single(ctrl_info->pci_dev,
4206                 request.data.report_event_configuration.sg_descriptors,
4207                 event_config, PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4208                 PCI_DMA_TODEVICE);
4209         if (rc)
4210                 goto out;
4211
4212         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0,
4213                 NULL, NO_TIMEOUT);
4214
4215         pqi_pci_unmap(ctrl_info->pci_dev,
4216                 request.data.report_event_configuration.sg_descriptors, 1,
4217                 PCI_DMA_TODEVICE);
4218
4219 out:
4220         kfree(event_config);
4221
4222         return rc;
4223 }
4224
4225 static inline int pqi_enable_events(struct pqi_ctrl_info *ctrl_info)
4226 {
4227         return pqi_configure_events(ctrl_info, true);
4228 }
4229
4230 static inline int pqi_disable_events(struct pqi_ctrl_info *ctrl_info)
4231 {
4232         return pqi_configure_events(ctrl_info, false);
4233 }
4234
4235 static void pqi_free_all_io_requests(struct pqi_ctrl_info *ctrl_info)
4236 {
4237         unsigned int i;
4238         struct device *dev;
4239         size_t sg_chain_buffer_length;
4240         struct pqi_io_request *io_request;
4241
4242         if (!ctrl_info->io_request_pool)
4243                 return;
4244
4245         dev = &ctrl_info->pci_dev->dev;
4246         sg_chain_buffer_length = ctrl_info->sg_chain_buffer_length;
4247         io_request = ctrl_info->io_request_pool;
4248
4249         for (i = 0; i < ctrl_info->max_io_slots; i++) {
4250                 kfree(io_request->iu);
4251                 if (!io_request->sg_chain_buffer)
4252                         break;
4253                 dma_free_coherent(dev, sg_chain_buffer_length,
4254                         io_request->sg_chain_buffer,
4255                         io_request->sg_chain_buffer_dma_handle);
4256                 io_request++;
4257         }
4258
4259         kfree(ctrl_info->io_request_pool);
4260         ctrl_info->io_request_pool = NULL;
4261 }
4262
4263 static inline int pqi_alloc_error_buffer(struct pqi_ctrl_info *ctrl_info)
4264 {
4265         ctrl_info->error_buffer = dma_zalloc_coherent(&ctrl_info->pci_dev->dev,
4266                 ctrl_info->error_buffer_length,
4267                 &ctrl_info->error_buffer_dma_handle, GFP_KERNEL);
4268
4269         if (!ctrl_info->error_buffer)
4270                 return -ENOMEM;
4271
4272         return 0;
4273 }
4274
4275 static int pqi_alloc_io_resources(struct pqi_ctrl_info *ctrl_info)
4276 {
4277         unsigned int i;
4278         void *sg_chain_buffer;
4279         size_t sg_chain_buffer_length;
4280         dma_addr_t sg_chain_buffer_dma_handle;
4281         struct device *dev;
4282         struct pqi_io_request *io_request;
4283
4284         ctrl_info->io_request_pool =
4285                 kcalloc(ctrl_info->max_io_slots,
4286                         sizeof(ctrl_info->io_request_pool[0]), GFP_KERNEL);
4287
4288         if (!ctrl_info->io_request_pool) {
4289                 dev_err(&ctrl_info->pci_dev->dev,
4290                         "failed to allocate I/O request pool\n");
4291                 goto error;
4292         }
4293
4294         dev = &ctrl_info->pci_dev->dev;
4295         sg_chain_buffer_length = ctrl_info->sg_chain_buffer_length;
4296         io_request = ctrl_info->io_request_pool;
4297
4298         for (i = 0; i < ctrl_info->max_io_slots; i++) {
4299                 io_request->iu =
4300                         kmalloc(ctrl_info->max_inbound_iu_length, GFP_KERNEL);
4301
4302                 if (!io_request->iu) {
4303                         dev_err(&ctrl_info->pci_dev->dev,
4304                                 "failed to allocate IU buffers\n");
4305                         goto error;
4306                 }
4307
4308                 sg_chain_buffer = dma_alloc_coherent(dev,
4309                         sg_chain_buffer_length, &sg_chain_buffer_dma_handle,
4310                         GFP_KERNEL);
4311
4312                 if (!sg_chain_buffer) {
4313                         dev_err(&ctrl_info->pci_dev->dev,
4314                                 "failed to allocate PQI scatter-gather chain buffers\n");
4315                         goto error;
4316                 }
4317
4318                 io_request->index = i;
4319                 io_request->sg_chain_buffer = sg_chain_buffer;
4320                 io_request->sg_chain_buffer_dma_handle =
4321                         sg_chain_buffer_dma_handle;
4322                 io_request++;
4323         }
4324
4325         return 0;
4326
4327 error:
4328         pqi_free_all_io_requests(ctrl_info);
4329
4330         return -ENOMEM;
4331 }
4332
4333 /*
4334  * Calculate required resources that are sized based on max. outstanding
4335  * requests and max. transfer size.
4336  */
4337
4338 static void pqi_calculate_io_resources(struct pqi_ctrl_info *ctrl_info)
4339 {
4340         u32 max_transfer_size;
4341         u32 max_sg_entries;
4342
4343         ctrl_info->scsi_ml_can_queue =
4344                 ctrl_info->max_outstanding_requests - PQI_RESERVED_IO_SLOTS;
4345         ctrl_info->max_io_slots = ctrl_info->max_outstanding_requests;
4346
4347         ctrl_info->error_buffer_length =
4348                 ctrl_info->max_io_slots * PQI_ERROR_BUFFER_ELEMENT_LENGTH;
4349
4350         if (reset_devices)
4351                 max_transfer_size = min(ctrl_info->max_transfer_size,
4352                         PQI_MAX_TRANSFER_SIZE_KDUMP);
4353         else
4354                 max_transfer_size = min(ctrl_info->max_transfer_size,
4355                         PQI_MAX_TRANSFER_SIZE);
4356
4357         max_sg_entries = max_transfer_size / PAGE_SIZE;
4358
4359         /* +1 to cover when the buffer is not page-aligned. */
4360         max_sg_entries++;
4361
4362         max_sg_entries = min(ctrl_info->max_sg_entries, max_sg_entries);
4363
4364         max_transfer_size = (max_sg_entries - 1) * PAGE_SIZE;
4365
4366         ctrl_info->sg_chain_buffer_length =
4367                 (max_sg_entries * sizeof(struct pqi_sg_descriptor)) +
4368                 PQI_EXTRA_SGL_MEMORY;
4369         ctrl_info->sg_tablesize = max_sg_entries;
4370         ctrl_info->max_sectors = max_transfer_size / 512;
4371 }
4372
4373 static void pqi_calculate_queue_resources(struct pqi_ctrl_info *ctrl_info)
4374 {
4375         int num_queue_groups;
4376         u16 num_elements_per_iq;
4377         u16 num_elements_per_oq;
4378
4379         if (reset_devices) {
4380                 num_queue_groups = 1;
4381         } else {
4382                 int num_cpus;
4383                 int max_queue_groups;
4384
4385                 max_queue_groups = min(ctrl_info->max_inbound_queues / 2,
4386                         ctrl_info->max_outbound_queues - 1);
4387                 max_queue_groups = min(max_queue_groups, PQI_MAX_QUEUE_GROUPS);
4388
4389                 num_cpus = num_online_cpus();
4390                 num_queue_groups = min(num_cpus, ctrl_info->max_msix_vectors);
4391                 num_queue_groups = min(num_queue_groups, max_queue_groups);
4392         }
4393
4394         ctrl_info->num_queue_groups = num_queue_groups;
4395         ctrl_info->max_hw_queue_index = num_queue_groups - 1;
4396
4397         /*
4398          * Make sure that the max. inbound IU length is an even multiple
4399          * of our inbound element length.
4400          */
4401         ctrl_info->max_inbound_iu_length =
4402                 (ctrl_info->max_inbound_iu_length_per_firmware /
4403                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) *
4404                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH;
4405
4406         num_elements_per_iq =
4407                 (ctrl_info->max_inbound_iu_length /
4408                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4409
4410         /* Add one because one element in each queue is unusable. */
4411         num_elements_per_iq++;
4412
4413         num_elements_per_iq = min(num_elements_per_iq,
4414                 ctrl_info->max_elements_per_iq);
4415
4416         num_elements_per_oq = ((num_elements_per_iq - 1) * 2) + 1;
4417         num_elements_per_oq = min(num_elements_per_oq,
4418                 ctrl_info->max_elements_per_oq);
4419
4420         ctrl_info->num_elements_per_iq = num_elements_per_iq;
4421         ctrl_info->num_elements_per_oq = num_elements_per_oq;
4422
4423         ctrl_info->max_sg_per_iu =
4424                 ((ctrl_info->max_inbound_iu_length -
4425                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) /
4426                 sizeof(struct pqi_sg_descriptor)) +
4427                 PQI_MAX_EMBEDDED_SG_DESCRIPTORS;
4428 }
4429
4430 static inline void pqi_set_sg_descriptor(
4431         struct pqi_sg_descriptor *sg_descriptor, struct scatterlist *sg)
4432 {
4433         u64 address = (u64)sg_dma_address(sg);
4434         unsigned int length = sg_dma_len(sg);
4435
4436         put_unaligned_le64(address, &sg_descriptor->address);
4437         put_unaligned_le32(length, &sg_descriptor->length);
4438         put_unaligned_le32(0, &sg_descriptor->flags);
4439 }
4440
4441 static int pqi_build_raid_sg_list(struct pqi_ctrl_info *ctrl_info,
4442         struct pqi_raid_path_request *request, struct scsi_cmnd *scmd,
4443         struct pqi_io_request *io_request)
4444 {
4445         int i;
4446         u16 iu_length;
4447         int sg_count;
4448         bool chained;
4449         unsigned int num_sg_in_iu;
4450         unsigned int max_sg_per_iu;
4451         struct scatterlist *sg;
4452         struct pqi_sg_descriptor *sg_descriptor;
4453
4454         sg_count = scsi_dma_map(scmd);
4455         if (sg_count < 0)
4456                 return sg_count;
4457
4458         iu_length = offsetof(struct pqi_raid_path_request, sg_descriptors) -
4459                 PQI_REQUEST_HEADER_LENGTH;
4460
4461         if (sg_count == 0)
4462                 goto out;
4463
4464         sg = scsi_sglist(scmd);
4465         sg_descriptor = request->sg_descriptors;
4466         max_sg_per_iu = ctrl_info->max_sg_per_iu - 1;
4467         chained = false;
4468         num_sg_in_iu = 0;
4469         i = 0;
4470
4471         while (1) {
4472                 pqi_set_sg_descriptor(sg_descriptor, sg);
4473                 if (!chained)
4474                         num_sg_in_iu++;
4475                 i++;
4476                 if (i == sg_count)
4477                         break;
4478                 sg_descriptor++;
4479                 if (i == max_sg_per_iu) {
4480                         put_unaligned_le64(
4481                                 (u64)io_request->sg_chain_buffer_dma_handle,
4482                                 &sg_descriptor->address);
4483                         put_unaligned_le32((sg_count - num_sg_in_iu)
4484                                 * sizeof(*sg_descriptor),
4485                                 &sg_descriptor->length);
4486                         put_unaligned_le32(CISS_SG_CHAIN,
4487                                 &sg_descriptor->flags);
4488                         chained = true;
4489                         num_sg_in_iu++;
4490                         sg_descriptor = io_request->sg_chain_buffer;
4491                 }
4492                 sg = sg_next(sg);
4493         }
4494
4495         put_unaligned_le32(CISS_SG_LAST, &sg_descriptor->flags);
4496         request->partial = chained;
4497         iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
4498
4499 out:
4500         put_unaligned_le16(iu_length, &request->header.iu_length);
4501
4502         return 0;
4503 }
4504
4505 static int pqi_build_aio_sg_list(struct pqi_ctrl_info *ctrl_info,
4506         struct pqi_aio_path_request *request, struct scsi_cmnd *scmd,
4507         struct pqi_io_request *io_request)
4508 {
4509         int i;
4510         u16 iu_length;
4511         int sg_count;
4512         bool chained;
4513         unsigned int num_sg_in_iu;
4514         unsigned int max_sg_per_iu;
4515         struct scatterlist *sg;
4516         struct pqi_sg_descriptor *sg_descriptor;
4517
4518         sg_count = scsi_dma_map(scmd);
4519         if (sg_count < 0)
4520                 return sg_count;
4521
4522         iu_length = offsetof(struct pqi_aio_path_request, sg_descriptors) -
4523                 PQI_REQUEST_HEADER_LENGTH;
4524         num_sg_in_iu = 0;
4525
4526         if (sg_count == 0)
4527                 goto out;
4528
4529         sg = scsi_sglist(scmd);
4530         sg_descriptor = request->sg_descriptors;
4531         max_sg_per_iu = ctrl_info->max_sg_per_iu - 1;
4532         chained = false;
4533         i = 0;
4534
4535         while (1) {
4536                 pqi_set_sg_descriptor(sg_descriptor, sg);
4537                 if (!chained)
4538                         num_sg_in_iu++;
4539                 i++;
4540                 if (i == sg_count)
4541                         break;
4542                 sg_descriptor++;
4543                 if (i == max_sg_per_iu) {
4544                         put_unaligned_le64(
4545                                 (u64)io_request->sg_chain_buffer_dma_handle,
4546                                 &sg_descriptor->address);
4547                         put_unaligned_le32((sg_count - num_sg_in_iu)
4548                                 * sizeof(*sg_descriptor),
4549                                 &sg_descriptor->length);
4550                         put_unaligned_le32(CISS_SG_CHAIN,
4551                                 &sg_descriptor->flags);
4552                         chained = true;
4553                         num_sg_in_iu++;
4554                         sg_descriptor = io_request->sg_chain_buffer;
4555                 }
4556                 sg = sg_next(sg);
4557         }
4558
4559         put_unaligned_le32(CISS_SG_LAST, &sg_descriptor->flags);
4560         request->partial = chained;
4561         iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
4562
4563 out:
4564         put_unaligned_le16(iu_length, &request->header.iu_length);
4565         request->num_sg_descriptors = num_sg_in_iu;
4566
4567         return 0;
4568 }
4569
4570 static void pqi_raid_io_complete(struct pqi_io_request *io_request,
4571         void *context)
4572 {
4573         struct scsi_cmnd *scmd;
4574
4575         scmd = io_request->scmd;
4576         pqi_free_io_request(io_request);
4577         scsi_dma_unmap(scmd);
4578         pqi_scsi_done(scmd);
4579 }
4580
4581 static int pqi_raid_submit_scsi_cmd_with_io_request(
4582         struct pqi_ctrl_info *ctrl_info, struct pqi_io_request *io_request,
4583         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
4584         struct pqi_queue_group *queue_group)
4585 {
4586         int rc;
4587         size_t cdb_length;
4588         struct pqi_raid_path_request *request;
4589
4590         io_request->io_complete_callback = pqi_raid_io_complete;
4591         io_request->scmd = scmd;
4592
4593         request = io_request->iu;
4594         memset(request, 0,
4595                 offsetof(struct pqi_raid_path_request, sg_descriptors));
4596
4597         request->header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
4598         put_unaligned_le32(scsi_bufflen(scmd), &request->buffer_length);
4599         request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
4600         put_unaligned_le16(io_request->index, &request->request_id);
4601         request->error_index = request->request_id;
4602         memcpy(request->lun_number, device->scsi3addr,
4603                 sizeof(request->lun_number));
4604
4605         cdb_length = min_t(size_t, scmd->cmd_len, sizeof(request->cdb));
4606         memcpy(request->cdb, scmd->cmnd, cdb_length);
4607
4608         switch (cdb_length) {
4609         case 6:
4610         case 10:
4611         case 12:
4612         case 16:
4613                 /* No bytes in the Additional CDB bytes field */
4614                 request->additional_cdb_bytes_usage =
4615                         SOP_ADDITIONAL_CDB_BYTES_0;
4616                 break;
4617         case 20:
4618                 /* 4 bytes in the Additional cdb field */
4619                 request->additional_cdb_bytes_usage =
4620                         SOP_ADDITIONAL_CDB_BYTES_4;
4621                 break;
4622         case 24:
4623                 /* 8 bytes in the Additional cdb field */
4624                 request->additional_cdb_bytes_usage =
4625                         SOP_ADDITIONAL_CDB_BYTES_8;
4626                 break;
4627         case 28:
4628                 /* 12 bytes in the Additional cdb field */
4629                 request->additional_cdb_bytes_usage =
4630                         SOP_ADDITIONAL_CDB_BYTES_12;
4631                 break;
4632         case 32:
4633         default:
4634                 /* 16 bytes in the Additional cdb field */
4635                 request->additional_cdb_bytes_usage =
4636                         SOP_ADDITIONAL_CDB_BYTES_16;
4637                 break;
4638         }
4639
4640         switch (scmd->sc_data_direction) {
4641         case DMA_FROM_DEVICE:
4642                 request->data_direction = SOP_READ_FLAG;
4643                 break;
4644         case DMA_TO_DEVICE:
4645                 request->data_direction = SOP_WRITE_FLAG;
4646                 break;
4647         case DMA_NONE:
4648                 request->data_direction = SOP_NO_DIRECTION_FLAG;
4649                 break;
4650         case DMA_BIDIRECTIONAL:
4651                 request->data_direction = SOP_BIDIRECTIONAL;
4652                 break;
4653         default:
4654                 dev_err(&ctrl_info->pci_dev->dev,
4655                         "unknown data direction: %d\n",
4656                         scmd->sc_data_direction);
4657                 break;
4658         }
4659
4660         rc = pqi_build_raid_sg_list(ctrl_info, request, scmd, io_request);
4661         if (rc) {
4662                 pqi_free_io_request(io_request);
4663                 return SCSI_MLQUEUE_HOST_BUSY;
4664         }
4665
4666         pqi_start_io(ctrl_info, queue_group, RAID_PATH, io_request);
4667
4668         return 0;
4669 }
4670
4671 static inline int pqi_raid_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
4672         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
4673         struct pqi_queue_group *queue_group)
4674 {
4675         struct pqi_io_request *io_request;
4676
4677         io_request = pqi_alloc_io_request(ctrl_info);
4678
4679         return pqi_raid_submit_scsi_cmd_with_io_request(ctrl_info, io_request,
4680                 device, scmd, queue_group);
4681 }
4682
4683 static inline void pqi_schedule_bypass_retry(struct pqi_ctrl_info *ctrl_info)
4684 {
4685         if (!pqi_ctrl_blocked(ctrl_info))
4686                 schedule_work(&ctrl_info->raid_bypass_retry_work);
4687 }
4688
4689 static bool pqi_raid_bypass_retry_needed(struct pqi_io_request *io_request)
4690 {
4691         struct scsi_cmnd *scmd;
4692         struct pqi_scsi_dev *device;
4693         struct pqi_ctrl_info *ctrl_info;
4694
4695         if (!io_request->raid_bypass)
4696                 return false;
4697
4698         scmd = io_request->scmd;
4699         if ((scmd->result & 0xff) == SAM_STAT_GOOD)
4700                 return false;
4701         if (host_byte(scmd->result) == DID_NO_CONNECT)
4702                 return false;
4703
4704         device = scmd->device->hostdata;
4705         if (pqi_device_offline(device))
4706                 return false;
4707
4708         ctrl_info = shost_to_hba(scmd->device->host);
4709         if (pqi_ctrl_offline(ctrl_info))
4710                 return false;
4711
4712         return true;
4713 }
4714
4715 static inline void pqi_add_to_raid_bypass_retry_list(
4716         struct pqi_ctrl_info *ctrl_info,
4717         struct pqi_io_request *io_request, bool at_head)
4718 {
4719         unsigned long flags;
4720
4721         spin_lock_irqsave(&ctrl_info->raid_bypass_retry_list_lock, flags);
4722         if (at_head)
4723                 list_add(&io_request->request_list_entry,
4724                         &ctrl_info->raid_bypass_retry_list);
4725         else
4726                 list_add_tail(&io_request->request_list_entry,
4727                         &ctrl_info->raid_bypass_retry_list);
4728         spin_unlock_irqrestore(&ctrl_info->raid_bypass_retry_list_lock, flags);
4729 }
4730
4731 static void pqi_queued_raid_bypass_complete(struct pqi_io_request *io_request,
4732         void *context)
4733 {
4734         struct scsi_cmnd *scmd;
4735
4736         scmd = io_request->scmd;
4737         pqi_free_io_request(io_request);
4738         pqi_scsi_done(scmd);
4739 }
4740
4741 static void pqi_queue_raid_bypass_retry(struct pqi_io_request *io_request)
4742 {
4743         struct scsi_cmnd *scmd;
4744         struct pqi_ctrl_info *ctrl_info;
4745
4746         io_request->io_complete_callback = pqi_queued_raid_bypass_complete;
4747         scmd = io_request->scmd;
4748         scmd->result = 0;
4749         ctrl_info = shost_to_hba(scmd->device->host);
4750
4751         pqi_add_to_raid_bypass_retry_list(ctrl_info, io_request, false);
4752         pqi_schedule_bypass_retry(ctrl_info);
4753 }
4754
4755 static int pqi_retry_raid_bypass(struct pqi_io_request *io_request)
4756 {
4757         struct scsi_cmnd *scmd;
4758         struct pqi_scsi_dev *device;
4759         struct pqi_ctrl_info *ctrl_info;
4760         struct pqi_queue_group *queue_group;
4761
4762         scmd = io_request->scmd;
4763         device = scmd->device->hostdata;
4764         if (pqi_device_in_reset(device)) {
4765                 pqi_free_io_request(io_request);
4766                 set_host_byte(scmd, DID_RESET);
4767                 pqi_scsi_done(scmd);
4768                 return 0;
4769         }
4770
4771         ctrl_info = shost_to_hba(scmd->device->host);
4772         queue_group = io_request->queue_group;
4773
4774         pqi_reinit_io_request(io_request);
4775
4776         return pqi_raid_submit_scsi_cmd_with_io_request(ctrl_info, io_request,
4777                 device, scmd, queue_group);
4778 }
4779
4780 static inline struct pqi_io_request *pqi_next_queued_raid_bypass_request(
4781         struct pqi_ctrl_info *ctrl_info)
4782 {
4783         unsigned long flags;
4784         struct pqi_io_request *io_request;
4785
4786         spin_lock_irqsave(&ctrl_info->raid_bypass_retry_list_lock, flags);
4787         io_request = list_first_entry_or_null(
4788                 &ctrl_info->raid_bypass_retry_list,
4789                 struct pqi_io_request, request_list_entry);
4790         if (io_request)
4791                 list_del(&io_request->request_list_entry);
4792         spin_unlock_irqrestore(&ctrl_info->raid_bypass_retry_list_lock, flags);
4793
4794         return io_request;
4795 }
4796
4797 static void pqi_retry_raid_bypass_requests(struct pqi_ctrl_info *ctrl_info)
4798 {
4799         int rc;
4800         struct pqi_io_request *io_request;
4801
4802         pqi_ctrl_busy(ctrl_info);
4803
4804         while (1) {
4805                 if (pqi_ctrl_blocked(ctrl_info))
4806                         break;
4807                 io_request = pqi_next_queued_raid_bypass_request(ctrl_info);
4808                 if (!io_request)
4809                         break;
4810                 rc = pqi_retry_raid_bypass(io_request);
4811                 if (rc) {
4812                         pqi_add_to_raid_bypass_retry_list(ctrl_info, io_request,
4813                                 true);
4814                         pqi_schedule_bypass_retry(ctrl_info);
4815                         break;
4816                 }
4817         }
4818
4819         pqi_ctrl_unbusy(ctrl_info);
4820 }
4821
4822 static void pqi_raid_bypass_retry_worker(struct work_struct *work)
4823 {
4824         struct pqi_ctrl_info *ctrl_info;
4825
4826         ctrl_info = container_of(work, struct pqi_ctrl_info,
4827                 raid_bypass_retry_work);
4828         pqi_retry_raid_bypass_requests(ctrl_info);
4829 }
4830
4831 static void pqi_clear_all_queued_raid_bypass_retries(
4832         struct pqi_ctrl_info *ctrl_info)
4833 {
4834         unsigned long flags;
4835
4836         spin_lock_irqsave(&ctrl_info->raid_bypass_retry_list_lock, flags);
4837         INIT_LIST_HEAD(&ctrl_info->raid_bypass_retry_list);
4838         spin_unlock_irqrestore(&ctrl_info->raid_bypass_retry_list_lock, flags);
4839 }
4840
4841 static void pqi_aio_io_complete(struct pqi_io_request *io_request,
4842         void *context)
4843 {
4844         struct scsi_cmnd *scmd;
4845
4846         scmd = io_request->scmd;
4847         scsi_dma_unmap(scmd);
4848         if (io_request->status == -EAGAIN)
4849                 set_host_byte(scmd, DID_IMM_RETRY);
4850         else if (pqi_raid_bypass_retry_needed(io_request)) {
4851                 pqi_queue_raid_bypass_retry(io_request);
4852                 return;
4853         }
4854         pqi_free_io_request(io_request);
4855         pqi_scsi_done(scmd);
4856 }
4857
4858 static inline int pqi_aio_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
4859         struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
4860         struct pqi_queue_group *queue_group)
4861 {
4862         return pqi_aio_submit_io(ctrl_info, scmd, device->aio_handle,
4863                 scmd->cmnd, scmd->cmd_len, queue_group, NULL, false);
4864 }
4865
4866 static int pqi_aio_submit_io(struct pqi_ctrl_info *ctrl_info,
4867         struct scsi_cmnd *scmd, u32 aio_handle, u8 *cdb,
4868         unsigned int cdb_length, struct pqi_queue_group *queue_group,
4869         struct pqi_encryption_info *encryption_info, bool raid_bypass)
4870 {
4871         int rc;
4872         struct pqi_io_request *io_request;
4873         struct pqi_aio_path_request *request;
4874
4875         io_request = pqi_alloc_io_request(ctrl_info);
4876         io_request->io_complete_callback = pqi_aio_io_complete;
4877         io_request->scmd = scmd;
4878         io_request->raid_bypass = raid_bypass;
4879
4880         request = io_request->iu;
4881         memset(request, 0,
4882                 offsetof(struct pqi_raid_path_request, sg_descriptors));
4883
4884         request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_IO;
4885         put_unaligned_le32(aio_handle, &request->nexus_id);
4886         put_unaligned_le32(scsi_bufflen(scmd), &request->buffer_length);
4887         request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
4888         put_unaligned_le16(io_request->index, &request->request_id);
4889         request->error_index = request->request_id;
4890         if (cdb_length > sizeof(request->cdb))
4891                 cdb_length = sizeof(request->cdb);
4892         request->cdb_length = cdb_length;
4893         memcpy(request->cdb, cdb, cdb_length);
4894
4895         switch (scmd->sc_data_direction) {
4896         case DMA_TO_DEVICE:
4897                 request->data_direction = SOP_READ_FLAG;
4898                 break;
4899         case DMA_FROM_DEVICE:
4900                 request->data_direction = SOP_WRITE_FLAG;
4901                 break;
4902         case DMA_NONE:
4903                 request->data_direction = SOP_NO_DIRECTION_FLAG;
4904                 break;
4905         case DMA_BIDIRECTIONAL:
4906                 request->data_direction = SOP_BIDIRECTIONAL;
4907                 break;
4908         default:
4909                 dev_err(&ctrl_info->pci_dev->dev,
4910                         "unknown data direction: %d\n",
4911                         scmd->sc_data_direction);
4912                 break;
4913         }
4914
4915         if (encryption_info) {
4916                 request->encryption_enable = true;
4917                 put_unaligned_le16(encryption_info->data_encryption_key_index,
4918                         &request->data_encryption_key_index);
4919                 put_unaligned_le32(encryption_info->encrypt_tweak_lower,
4920                         &request->encrypt_tweak_lower);
4921                 put_unaligned_le32(encryption_info->encrypt_tweak_upper,
4922                         &request->encrypt_tweak_upper);
4923         }
4924
4925         rc = pqi_build_aio_sg_list(ctrl_info, request, scmd, io_request);
4926         if (rc) {
4927                 pqi_free_io_request(io_request);
4928                 return SCSI_MLQUEUE_HOST_BUSY;
4929         }
4930
4931         pqi_start_io(ctrl_info, queue_group, AIO_PATH, io_request);
4932
4933         return 0;
4934 }
4935
4936 static inline u16 pqi_get_hw_queue(struct pqi_ctrl_info *ctrl_info,
4937         struct scsi_cmnd *scmd)
4938 {
4939         u16 hw_queue;
4940
4941         hw_queue = blk_mq_unique_tag_to_hwq(blk_mq_unique_tag(scmd->request));
4942         if (hw_queue > ctrl_info->max_hw_queue_index)
4943                 hw_queue = 0;
4944
4945         return hw_queue;
4946 }
4947
4948 /*
4949  * This function gets called just before we hand the completed SCSI request
4950  * back to the SML.
4951  */
4952
4953 void pqi_prep_for_scsi_done(struct scsi_cmnd *scmd)
4954 {
4955         struct pqi_scsi_dev *device;
4956
4957         device = scmd->device->hostdata;
4958         atomic_dec(&device->scsi_cmds_outstanding);
4959 }
4960
4961 static int pqi_scsi_queue_command(struct Scsi_Host *shost,
4962         struct scsi_cmnd *scmd)
4963 {
4964         int rc;
4965         struct pqi_ctrl_info *ctrl_info;
4966         struct pqi_scsi_dev *device;
4967         u16 hw_queue;
4968         struct pqi_queue_group *queue_group;
4969         bool raid_bypassed;
4970
4971         device = scmd->device->hostdata;
4972         ctrl_info = shost_to_hba(shost);
4973
4974         atomic_inc(&device->scsi_cmds_outstanding);
4975
4976         if (pqi_ctrl_offline(ctrl_info)) {
4977                 set_host_byte(scmd, DID_NO_CONNECT);
4978                 pqi_scsi_done(scmd);
4979                 return 0;
4980         }
4981
4982         pqi_ctrl_busy(ctrl_info);
4983         if (pqi_ctrl_blocked(ctrl_info) || pqi_device_in_reset(device)) {
4984                 rc = SCSI_MLQUEUE_HOST_BUSY;
4985                 goto out;
4986         }
4987
4988         /*
4989          * This is necessary because the SML doesn't zero out this field during
4990          * error recovery.
4991          */
4992         scmd->result = 0;
4993
4994         hw_queue = pqi_get_hw_queue(ctrl_info, scmd);
4995         queue_group = &ctrl_info->queue_groups[hw_queue];
4996
4997         if (pqi_is_logical_device(device)) {
4998                 raid_bypassed = false;
4999                 if (device->raid_bypass_enabled &&
5000                                 !blk_rq_is_passthrough(scmd->request)) {
5001                         rc = pqi_raid_bypass_submit_scsi_cmd(ctrl_info, device,
5002                                 scmd, queue_group);
5003                         if (rc == 0 || rc == SCSI_MLQUEUE_HOST_BUSY)
5004                                 raid_bypassed = true;
5005                 }
5006                 if (!raid_bypassed)
5007                         rc = pqi_raid_submit_scsi_cmd(ctrl_info, device, scmd,
5008                                 queue_group);
5009         } else {
5010                 if (device->aio_enabled)
5011                         rc = pqi_aio_submit_scsi_cmd(ctrl_info, device, scmd,
5012                                 queue_group);
5013                 else
5014                         rc = pqi_raid_submit_scsi_cmd(ctrl_info, device, scmd,
5015                                 queue_group);
5016         }
5017
5018 out:
5019         pqi_ctrl_unbusy(ctrl_info);
5020         if (rc)
5021                 atomic_dec(&device->scsi_cmds_outstanding);
5022
5023         return rc;
5024 }
5025
5026 static int pqi_wait_until_queued_io_drained(struct pqi_ctrl_info *ctrl_info,
5027         struct pqi_queue_group *queue_group)
5028 {
5029         unsigned int path;
5030         unsigned long flags;
5031         bool list_is_empty;
5032
5033         for (path = 0; path < 2; path++) {
5034                 while (1) {
5035                         spin_lock_irqsave(
5036                                 &queue_group->submit_lock[path], flags);
5037                         list_is_empty =
5038                                 list_empty(&queue_group->request_list[path]);
5039                         spin_unlock_irqrestore(
5040                                 &queue_group->submit_lock[path], flags);
5041                         if (list_is_empty)
5042                                 break;
5043                         pqi_check_ctrl_health(ctrl_info);
5044                         if (pqi_ctrl_offline(ctrl_info))
5045                                 return -ENXIO;
5046                         usleep_range(1000, 2000);
5047                 }
5048         }
5049
5050         return 0;
5051 }
5052
5053 static int pqi_wait_until_inbound_queues_empty(struct pqi_ctrl_info *ctrl_info)
5054 {
5055         int rc;
5056         unsigned int i;
5057         unsigned int path;
5058         struct pqi_queue_group *queue_group;
5059         pqi_index_t iq_pi;
5060         pqi_index_t iq_ci;
5061
5062         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
5063                 queue_group = &ctrl_info->queue_groups[i];
5064
5065                 rc = pqi_wait_until_queued_io_drained(ctrl_info, queue_group);
5066                 if (rc)
5067                         return rc;
5068
5069                 for (path = 0; path < 2; path++) {
5070                         iq_pi = queue_group->iq_pi_copy[path];
5071
5072                         while (1) {
5073                                 iq_ci = readl(queue_group->iq_ci[path]);
5074                                 if (iq_ci == iq_pi)
5075                                         break;
5076                                 pqi_check_ctrl_health(ctrl_info);
5077                                 if (pqi_ctrl_offline(ctrl_info))
5078                                         return -ENXIO;
5079                                 usleep_range(1000, 2000);
5080                         }
5081                 }
5082         }
5083
5084         return 0;
5085 }
5086
5087 static void pqi_fail_io_queued_for_device(struct pqi_ctrl_info *ctrl_info,
5088         struct pqi_scsi_dev *device)
5089 {
5090         unsigned int i;
5091         unsigned int path;
5092         struct pqi_queue_group *queue_group;
5093         unsigned long flags;
5094         struct pqi_io_request *io_request;
5095         struct pqi_io_request *next;
5096         struct scsi_cmnd *scmd;
5097         struct pqi_scsi_dev *scsi_device;
5098
5099         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
5100                 queue_group = &ctrl_info->queue_groups[i];
5101
5102                 for (path = 0; path < 2; path++) {
5103                         spin_lock_irqsave(
5104                                 &queue_group->submit_lock[path], flags);
5105
5106                         list_for_each_entry_safe(io_request, next,
5107                                 &queue_group->request_list[path],
5108                                 request_list_entry) {
5109                                 scmd = io_request->scmd;
5110                                 if (!scmd)
5111                                         continue;
5112
5113                                 scsi_device = scmd->device->hostdata;
5114                                 if (scsi_device != device)
5115                                         continue;
5116
5117                                 list_del(&io_request->request_list_entry);
5118                                 set_host_byte(scmd, DID_RESET);
5119                                 pqi_scsi_done(scmd);
5120                         }
5121
5122                         spin_unlock_irqrestore(
5123                                 &queue_group->submit_lock[path], flags);
5124                 }
5125         }
5126 }
5127
5128 static int pqi_device_wait_for_pending_io(struct pqi_ctrl_info *ctrl_info,
5129         struct pqi_scsi_dev *device)
5130 {
5131         while (atomic_read(&device->scsi_cmds_outstanding)) {
5132                 pqi_check_ctrl_health(ctrl_info);
5133                 if (pqi_ctrl_offline(ctrl_info))
5134                         return -ENXIO;
5135                 usleep_range(1000, 2000);
5136         }
5137
5138         return 0;
5139 }
5140
5141 static int pqi_ctrl_wait_for_pending_io(struct pqi_ctrl_info *ctrl_info)
5142 {
5143         bool io_pending;
5144         unsigned long flags;
5145         struct pqi_scsi_dev *device;
5146
5147         while (1) {
5148                 io_pending = false;
5149
5150                 spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
5151                 list_for_each_entry(device, &ctrl_info->scsi_device_list,
5152                         scsi_device_list_entry) {
5153                         if (atomic_read(&device->scsi_cmds_outstanding)) {
5154                                 io_pending = true;
5155                                 break;
5156                         }
5157                 }
5158                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock,
5159                                         flags);
5160
5161                 if (!io_pending)
5162                         break;
5163
5164                 pqi_check_ctrl_health(ctrl_info);
5165                 if (pqi_ctrl_offline(ctrl_info))
5166                         return -ENXIO;
5167
5168                 usleep_range(1000, 2000);
5169         }
5170
5171         return 0;
5172 }
5173
5174 static void pqi_lun_reset_complete(struct pqi_io_request *io_request,
5175         void *context)
5176 {
5177         struct completion *waiting = context;
5178
5179         complete(waiting);
5180 }
5181
5182 #define PQI_LUN_RESET_TIMEOUT_SECS      10
5183
5184 static int pqi_wait_for_lun_reset_completion(struct pqi_ctrl_info *ctrl_info,
5185         struct pqi_scsi_dev *device, struct completion *wait)
5186 {
5187         int rc;
5188
5189         while (1) {
5190                 if (wait_for_completion_io_timeout(wait,
5191                         PQI_LUN_RESET_TIMEOUT_SECS * HZ)) {
5192                         rc = 0;
5193                         break;
5194                 }
5195
5196                 pqi_check_ctrl_health(ctrl_info);
5197                 if (pqi_ctrl_offline(ctrl_info)) {
5198                         rc = -ENXIO;
5199                         break;
5200                 }
5201         }
5202
5203         return rc;
5204 }
5205
5206 static int pqi_lun_reset(struct pqi_ctrl_info *ctrl_info,
5207         struct pqi_scsi_dev *device)
5208 {
5209         int rc;
5210         struct pqi_io_request *io_request;
5211         DECLARE_COMPLETION_ONSTACK(wait);
5212         struct pqi_task_management_request *request;
5213
5214         io_request = pqi_alloc_io_request(ctrl_info);
5215         io_request->io_complete_callback = pqi_lun_reset_complete;
5216         io_request->context = &wait;
5217
5218         request = io_request->iu;
5219         memset(request, 0, sizeof(*request));
5220
5221         request->header.iu_type = PQI_REQUEST_IU_TASK_MANAGEMENT;
5222         put_unaligned_le16(sizeof(*request) - PQI_REQUEST_HEADER_LENGTH,
5223                 &request->header.iu_length);
5224         put_unaligned_le16(io_request->index, &request->request_id);
5225         memcpy(request->lun_number, device->scsi3addr,
5226                 sizeof(request->lun_number));
5227         request->task_management_function = SOP_TASK_MANAGEMENT_LUN_RESET;
5228
5229         pqi_start_io(ctrl_info,
5230                 &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP], RAID_PATH,
5231                 io_request);
5232
5233         rc = pqi_wait_for_lun_reset_completion(ctrl_info, device, &wait);
5234         if (rc == 0)
5235                 rc = io_request->status;
5236
5237         pqi_free_io_request(io_request);
5238
5239         return rc;
5240 }
5241
5242 /* Performs a reset at the LUN level. */
5243
5244 static int pqi_device_reset(struct pqi_ctrl_info *ctrl_info,
5245         struct pqi_scsi_dev *device)
5246 {
5247         int rc;
5248
5249         rc = pqi_lun_reset(ctrl_info, device);
5250         if (rc == 0)
5251                 rc = pqi_device_wait_for_pending_io(ctrl_info, device);
5252
5253         return rc == 0 ? SUCCESS : FAILED;
5254 }
5255
5256 static int pqi_eh_device_reset_handler(struct scsi_cmnd *scmd)
5257 {
5258         int rc;
5259         struct Scsi_Host *shost;
5260         struct pqi_ctrl_info *ctrl_info;
5261         struct pqi_scsi_dev *device;
5262
5263         shost = scmd->device->host;
5264         ctrl_info = shost_to_hba(shost);
5265         device = scmd->device->hostdata;
5266
5267         dev_err(&ctrl_info->pci_dev->dev,
5268                 "resetting scsi %d:%d:%d:%d\n",
5269                 shost->host_no, device->bus, device->target, device->lun);
5270
5271         pqi_check_ctrl_health(ctrl_info);
5272         if (pqi_ctrl_offline(ctrl_info)) {
5273                 rc = FAILED;
5274                 goto out;
5275         }
5276
5277         mutex_lock(&ctrl_info->lun_reset_mutex);
5278
5279         pqi_ctrl_block_requests(ctrl_info);
5280         pqi_ctrl_wait_until_quiesced(ctrl_info);
5281         pqi_fail_io_queued_for_device(ctrl_info, device);
5282         rc = pqi_wait_until_inbound_queues_empty(ctrl_info);
5283         pqi_device_reset_start(device);
5284         pqi_ctrl_unblock_requests(ctrl_info);
5285
5286         if (rc)
5287                 rc = FAILED;
5288         else
5289                 rc = pqi_device_reset(ctrl_info, device);
5290
5291         pqi_device_reset_done(device);
5292
5293         mutex_unlock(&ctrl_info->lun_reset_mutex);
5294
5295 out:
5296         dev_err(&ctrl_info->pci_dev->dev,
5297                 "reset of scsi %d:%d:%d:%d: %s\n",
5298                 shost->host_no, device->bus, device->target, device->lun,
5299                 rc == SUCCESS ? "SUCCESS" : "FAILED");
5300
5301         return rc;
5302 }
5303
5304 static int pqi_slave_alloc(struct scsi_device *sdev)
5305 {
5306         struct pqi_scsi_dev *device;
5307         unsigned long flags;
5308         struct pqi_ctrl_info *ctrl_info;
5309         struct scsi_target *starget;
5310         struct sas_rphy *rphy;
5311
5312         ctrl_info = shost_to_hba(sdev->host);
5313
5314         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
5315
5316         if (sdev_channel(sdev) == PQI_PHYSICAL_DEVICE_BUS) {
5317                 starget = scsi_target(sdev);
5318                 rphy = target_to_rphy(starget);
5319                 device = pqi_find_device_by_sas_rphy(ctrl_info, rphy);
5320                 if (device) {
5321                         device->target = sdev_id(sdev);
5322                         device->lun = sdev->lun;
5323                         device->target_lun_valid = true;
5324                 }
5325         } else {
5326                 device = pqi_find_scsi_dev(ctrl_info, sdev_channel(sdev),
5327                         sdev_id(sdev), sdev->lun);
5328         }
5329
5330         if (device) {
5331                 sdev->hostdata = device;
5332                 device->sdev = sdev;
5333                 if (device->queue_depth) {
5334                         device->advertised_queue_depth = device->queue_depth;
5335                         scsi_change_queue_depth(sdev,
5336                                 device->advertised_queue_depth);
5337                 }
5338         }
5339
5340         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
5341
5342         return 0;
5343 }
5344
5345 static int pqi_map_queues(struct Scsi_Host *shost)
5346 {
5347         struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
5348
5349         return blk_mq_pci_map_queues(&shost->tag_set, ctrl_info->pci_dev, 0);
5350 }
5351
5352 static int pqi_getpciinfo_ioctl(struct pqi_ctrl_info *ctrl_info,
5353         void __user *arg)
5354 {
5355         struct pci_dev *pci_dev;
5356         u32 subsystem_vendor;
5357         u32 subsystem_device;
5358         cciss_pci_info_struct pciinfo;
5359
5360         if (!arg)
5361                 return -EINVAL;
5362
5363         pci_dev = ctrl_info->pci_dev;
5364
5365         pciinfo.domain = pci_domain_nr(pci_dev->bus);
5366         pciinfo.bus = pci_dev->bus->number;
5367         pciinfo.dev_fn = pci_dev->devfn;
5368         subsystem_vendor = pci_dev->subsystem_vendor;
5369         subsystem_device = pci_dev->subsystem_device;
5370         pciinfo.board_id = ((subsystem_device << 16) & 0xffff0000) |
5371                 subsystem_vendor;
5372
5373         if (copy_to_user(arg, &pciinfo, sizeof(pciinfo)))
5374                 return -EFAULT;
5375
5376         return 0;
5377 }
5378
5379 static int pqi_getdrivver_ioctl(void __user *arg)
5380 {
5381         u32 version;
5382
5383         if (!arg)
5384                 return -EINVAL;
5385
5386         version = (DRIVER_MAJOR << 28) | (DRIVER_MINOR << 24) |
5387                 (DRIVER_RELEASE << 16) | DRIVER_REVISION;
5388
5389         if (copy_to_user(arg, &version, sizeof(version)))
5390                 return -EFAULT;
5391
5392         return 0;
5393 }
5394
5395 struct ciss_error_info {
5396         u8      scsi_status;
5397         int     command_status;
5398         size_t  sense_data_length;
5399 };
5400
5401 static void pqi_error_info_to_ciss(struct pqi_raid_error_info *pqi_error_info,
5402         struct ciss_error_info *ciss_error_info)
5403 {
5404         int ciss_cmd_status;
5405         size_t sense_data_length;
5406
5407         switch (pqi_error_info->data_out_result) {
5408         case PQI_DATA_IN_OUT_GOOD:
5409                 ciss_cmd_status = CISS_CMD_STATUS_SUCCESS;
5410                 break;
5411         case PQI_DATA_IN_OUT_UNDERFLOW:
5412                 ciss_cmd_status = CISS_CMD_STATUS_DATA_UNDERRUN;
5413                 break;
5414         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW:
5415                 ciss_cmd_status = CISS_CMD_STATUS_DATA_OVERRUN;
5416                 break;
5417         case PQI_DATA_IN_OUT_PROTOCOL_ERROR:
5418         case PQI_DATA_IN_OUT_BUFFER_ERROR:
5419         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_DESCRIPTOR_AREA:
5420         case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_BRIDGE:
5421         case PQI_DATA_IN_OUT_ERROR:
5422                 ciss_cmd_status = CISS_CMD_STATUS_PROTOCOL_ERROR;
5423                 break;
5424         case PQI_DATA_IN_OUT_HARDWARE_ERROR:
5425         case PQI_DATA_IN_OUT_PCIE_FABRIC_ERROR:
5426         case PQI_DATA_IN_OUT_PCIE_COMPLETION_TIMEOUT:
5427         case PQI_DATA_IN_OUT_PCIE_COMPLETER_ABORT_RECEIVED:
5428         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST_RECEIVED:
5429         case PQI_DATA_IN_OUT_PCIE_ECRC_CHECK_FAILED:
5430         case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST:
5431         case PQI_DATA_IN_OUT_PCIE_ACS_VIOLATION:
5432         case PQI_DATA_IN_OUT_PCIE_TLP_PREFIX_BLOCKED:
5433         case PQI_DATA_IN_OUT_PCIE_POISONED_MEMORY_READ:
5434                 ciss_cmd_status = CISS_CMD_STATUS_HARDWARE_ERROR;
5435                 break;
5436         case PQI_DATA_IN_OUT_UNSOLICITED_ABORT:
5437                 ciss_cmd_status = CISS_CMD_STATUS_UNSOLICITED_ABORT;
5438                 break;
5439         case PQI_DATA_IN_OUT_ABORTED:
5440                 ciss_cmd_status = CISS_CMD_STATUS_ABORTED;
5441                 break;
5442         case PQI_DATA_IN_OUT_TIMEOUT:
5443                 ciss_cmd_status = CISS_CMD_STATUS_TIMEOUT;
5444                 break;
5445         default:
5446                 ciss_cmd_status = CISS_CMD_STATUS_TARGET_STATUS;
5447                 break;
5448         }
5449
5450         sense_data_length =
5451                 get_unaligned_le16(&pqi_error_info->sense_data_length);
5452         if (sense_data_length == 0)
5453                 sense_data_length =
5454                 get_unaligned_le16(&pqi_error_info->response_data_length);
5455         if (sense_data_length)
5456                 if (sense_data_length > sizeof(pqi_error_info->data))
5457                         sense_data_length = sizeof(pqi_error_info->data);
5458
5459         ciss_error_info->scsi_status = pqi_error_info->status;
5460         ciss_error_info->command_status = ciss_cmd_status;
5461         ciss_error_info->sense_data_length = sense_data_length;
5462 }
5463
5464 static int pqi_passthru_ioctl(struct pqi_ctrl_info *ctrl_info, void __user *arg)
5465 {
5466         int rc;
5467         char *kernel_buffer = NULL;
5468         u16 iu_length;
5469         size_t sense_data_length;
5470         IOCTL_Command_struct iocommand;
5471         struct pqi_raid_path_request request;
5472         struct pqi_raid_error_info pqi_error_info;
5473         struct ciss_error_info ciss_error_info;
5474
5475         if (pqi_ctrl_offline(ctrl_info))
5476                 return -ENXIO;
5477         if (!arg)
5478                 return -EINVAL;
5479         if (!capable(CAP_SYS_RAWIO))
5480                 return -EPERM;
5481         if (copy_from_user(&iocommand, arg, sizeof(iocommand)))
5482                 return -EFAULT;
5483         if (iocommand.buf_size < 1 &&
5484                 iocommand.Request.Type.Direction != XFER_NONE)
5485                 return -EINVAL;
5486         if (iocommand.Request.CDBLen > sizeof(request.cdb))
5487                 return -EINVAL;
5488         if (iocommand.Request.Type.Type != TYPE_CMD)
5489                 return -EINVAL;
5490
5491         switch (iocommand.Request.Type.Direction) {
5492         case XFER_NONE:
5493         case XFER_WRITE:
5494         case XFER_READ:
5495         case XFER_READ | XFER_WRITE:
5496                 break;
5497         default:
5498                 return -EINVAL;
5499         }
5500
5501         if (iocommand.buf_size > 0) {
5502                 kernel_buffer = kmalloc(iocommand.buf_size, GFP_KERNEL);
5503                 if (!kernel_buffer)
5504                         return -ENOMEM;
5505                 if (iocommand.Request.Type.Direction & XFER_WRITE) {
5506                         if (copy_from_user(kernel_buffer, iocommand.buf,
5507                                 iocommand.buf_size)) {
5508                                 rc = -EFAULT;
5509                                 goto out;
5510                         }
5511                 } else {
5512                         memset(kernel_buffer, 0, iocommand.buf_size);
5513                 }
5514         }
5515
5516         memset(&request, 0, sizeof(request));
5517
5518         request.header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
5519         iu_length = offsetof(struct pqi_raid_path_request, sg_descriptors) -
5520                 PQI_REQUEST_HEADER_LENGTH;
5521         memcpy(request.lun_number, iocommand.LUN_info.LunAddrBytes,
5522                 sizeof(request.lun_number));
5523         memcpy(request.cdb, iocommand.Request.CDB, iocommand.Request.CDBLen);
5524         request.additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
5525
5526         switch (iocommand.Request.Type.Direction) {
5527         case XFER_NONE:
5528                 request.data_direction = SOP_NO_DIRECTION_FLAG;
5529                 break;
5530         case XFER_WRITE:
5531                 request.data_direction = SOP_WRITE_FLAG;
5532                 break;
5533         case XFER_READ:
5534                 request.data_direction = SOP_READ_FLAG;
5535                 break;
5536         case XFER_READ | XFER_WRITE:
5537                 request.data_direction = SOP_BIDIRECTIONAL;
5538                 break;
5539         }
5540
5541         request.task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5542
5543         if (iocommand.buf_size > 0) {
5544                 put_unaligned_le32(iocommand.buf_size, &request.buffer_length);
5545
5546                 rc = pqi_map_single(ctrl_info->pci_dev,
5547                         &request.sg_descriptors[0], kernel_buffer,
5548                         iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
5549                 if (rc)
5550                         goto out;
5551
5552                 iu_length += sizeof(request.sg_descriptors[0]);
5553         }
5554
5555         put_unaligned_le16(iu_length, &request.header.iu_length);
5556
5557         rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
5558                 PQI_SYNC_FLAGS_INTERRUPTABLE, &pqi_error_info, NO_TIMEOUT);
5559
5560         if (iocommand.buf_size > 0)
5561                 pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
5562                         PCI_DMA_BIDIRECTIONAL);
5563
5564         memset(&iocommand.error_info, 0, sizeof(iocommand.error_info));
5565
5566         if (rc == 0) {
5567                 pqi_error_info_to_ciss(&pqi_error_info, &ciss_error_info);
5568                 iocommand.error_info.ScsiStatus = ciss_error_info.scsi_status;
5569                 iocommand.error_info.CommandStatus =
5570                         ciss_error_info.command_status;
5571                 sense_data_length = ciss_error_info.sense_data_length;
5572                 if (sense_data_length) {
5573                         if (sense_data_length >
5574                                 sizeof(iocommand.error_info.SenseInfo))
5575                                 sense_data_length =
5576                                         sizeof(iocommand.error_info.SenseInfo);
5577                         memcpy(iocommand.error_info.SenseInfo,
5578                                 pqi_error_info.data, sense_data_length);
5579                         iocommand.error_info.SenseLen = sense_data_length;
5580                 }
5581         }
5582
5583         if (copy_to_user(arg, &iocommand, sizeof(iocommand))) {
5584                 rc = -EFAULT;
5585                 goto out;
5586         }
5587
5588         if (rc == 0 && iocommand.buf_size > 0 &&
5589                 (iocommand.Request.Type.Direction & XFER_READ)) {
5590                 if (copy_to_user(iocommand.buf, kernel_buffer,
5591                         iocommand.buf_size)) {
5592                         rc = -EFAULT;
5593                 }
5594         }
5595
5596 out:
5597         kfree(kernel_buffer);
5598
5599         return rc;
5600 }
5601
5602 static int pqi_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
5603 {
5604         int rc;
5605         struct pqi_ctrl_info *ctrl_info;
5606
5607         ctrl_info = shost_to_hba(sdev->host);
5608
5609         switch (cmd) {
5610         case CCISS_DEREGDISK:
5611         case CCISS_REGNEWDISK:
5612         case CCISS_REGNEWD:
5613                 rc = pqi_scan_scsi_devices(ctrl_info);
5614                 break;
5615         case CCISS_GETPCIINFO:
5616                 rc = pqi_getpciinfo_ioctl(ctrl_info, arg);
5617                 break;
5618         case CCISS_GETDRIVVER:
5619                 rc = pqi_getdrivver_ioctl(arg);
5620                 break;
5621         case CCISS_PASSTHRU:
5622                 rc = pqi_passthru_ioctl(ctrl_info, arg);
5623                 break;
5624         default:
5625                 rc = -EINVAL;
5626                 break;
5627         }
5628
5629         return rc;
5630 }
5631
5632 static ssize_t pqi_version_show(struct device *dev,
5633         struct device_attribute *attr, char *buffer)
5634 {
5635         ssize_t count = 0;
5636         struct Scsi_Host *shost;
5637         struct pqi_ctrl_info *ctrl_info;
5638
5639         shost = class_to_shost(dev);
5640         ctrl_info = shost_to_hba(shost);
5641
5642         count += snprintf(buffer + count, PAGE_SIZE - count,
5643                 "  driver: %s\n", DRIVER_VERSION BUILD_TIMESTAMP);
5644
5645         count += snprintf(buffer + count, PAGE_SIZE - count,
5646                 "firmware: %s\n", ctrl_info->firmware_version);
5647
5648         return count;
5649 }
5650
5651 static ssize_t pqi_host_rescan_store(struct device *dev,
5652         struct device_attribute *attr, const char *buffer, size_t count)
5653 {
5654         struct Scsi_Host *shost = class_to_shost(dev);
5655
5656         pqi_scan_start(shost);
5657
5658         return count;
5659 }
5660
5661 static ssize_t pqi_lockup_action_show(struct device *dev,
5662         struct device_attribute *attr, char *buffer)
5663 {
5664         int count = 0;
5665         unsigned int i;
5666
5667         for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
5668                 if (pqi_lockup_actions[i].action == pqi_lockup_action)
5669                         count += snprintf(buffer + count, PAGE_SIZE - count,
5670                                 "[%s] ", pqi_lockup_actions[i].name);
5671                 else
5672                         count += snprintf(buffer + count, PAGE_SIZE - count,
5673                                 "%s ", pqi_lockup_actions[i].name);
5674         }
5675
5676         count += snprintf(buffer + count, PAGE_SIZE - count, "\n");
5677
5678         return count;
5679 }
5680
5681 static ssize_t pqi_lockup_action_store(struct device *dev,
5682         struct device_attribute *attr, const char *buffer, size_t count)
5683 {
5684         unsigned int i;
5685         char *action_name;
5686         char action_name_buffer[32];
5687
5688         strlcpy(action_name_buffer, buffer, sizeof(action_name_buffer));
5689         action_name = strstrip(action_name_buffer);
5690
5691         for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
5692                 if (strcmp(action_name, pqi_lockup_actions[i].name) == 0) {
5693                         pqi_lockup_action = pqi_lockup_actions[i].action;
5694                         return count;
5695                 }
5696         }
5697
5698         return -EINVAL;
5699 }
5700
5701 static DEVICE_ATTR(version, 0444, pqi_version_show, NULL);
5702 static DEVICE_ATTR(rescan, 0200, NULL, pqi_host_rescan_store);
5703 static DEVICE_ATTR(lockup_action, 0644,
5704         pqi_lockup_action_show, pqi_lockup_action_store);
5705
5706 static struct device_attribute *pqi_shost_attrs[] = {
5707         &dev_attr_version,
5708         &dev_attr_rescan,
5709         &dev_attr_lockup_action,
5710         NULL
5711 };
5712
5713 static ssize_t pqi_sas_address_show(struct device *dev,
5714         struct device_attribute *attr, char *buffer)
5715 {
5716         struct pqi_ctrl_info *ctrl_info;
5717         struct scsi_device *sdev;
5718         struct pqi_scsi_dev *device;
5719         unsigned long flags;
5720         u64 sas_address;
5721
5722         sdev = to_scsi_device(dev);
5723         ctrl_info = shost_to_hba(sdev->host);
5724
5725         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
5726
5727         device = sdev->hostdata;
5728         if (pqi_is_logical_device(device)) {
5729                 spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock,
5730                         flags);
5731                 return -ENODEV;
5732         }
5733         sas_address = device->sas_address;
5734
5735         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
5736
5737         return snprintf(buffer, PAGE_SIZE, "0x%016llx\n", sas_address);
5738 }
5739
5740 static ssize_t pqi_ssd_smart_path_enabled_show(struct device *dev,
5741         struct device_attribute *attr, char *buffer)
5742 {
5743         struct pqi_ctrl_info *ctrl_info;
5744         struct scsi_device *sdev;
5745         struct pqi_scsi_dev *device;
5746         unsigned long flags;
5747
5748         sdev = to_scsi_device(dev);
5749         ctrl_info = shost_to_hba(sdev->host);
5750
5751         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
5752
5753         device = sdev->hostdata;
5754         buffer[0] = device->raid_bypass_enabled ? '1' : '0';
5755         buffer[1] = '\n';
5756         buffer[2] = '\0';
5757
5758         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
5759
5760         return 2;
5761 }
5762
5763 static ssize_t pqi_raid_level_show(struct device *dev,
5764         struct device_attribute *attr, char *buffer)
5765 {
5766         struct pqi_ctrl_info *ctrl_info;
5767         struct scsi_device *sdev;
5768         struct pqi_scsi_dev *device;
5769         unsigned long flags;
5770         char *raid_level;
5771
5772         sdev = to_scsi_device(dev);
5773         ctrl_info = shost_to_hba(sdev->host);
5774
5775         spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
5776
5777         device = sdev->hostdata;
5778
5779         if (pqi_is_logical_device(device))
5780                 raid_level = pqi_raid_level_to_string(device->raid_level);
5781         else
5782                 raid_level = "N/A";
5783
5784         spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
5785
5786         return snprintf(buffer, PAGE_SIZE, "%s\n", raid_level);
5787 }
5788
5789 static DEVICE_ATTR(sas_address, 0444, pqi_sas_address_show, NULL);
5790 static DEVICE_ATTR(ssd_smart_path_enabled, 0444,
5791         pqi_ssd_smart_path_enabled_show, NULL);
5792 static DEVICE_ATTR(raid_level, 0444, pqi_raid_level_show, NULL);
5793
5794 static struct device_attribute *pqi_sdev_attrs[] = {
5795         &dev_attr_sas_address,
5796         &dev_attr_ssd_smart_path_enabled,
5797         &dev_attr_raid_level,
5798         NULL
5799 };
5800
5801 static struct scsi_host_template pqi_driver_template = {
5802         .module = THIS_MODULE,
5803         .name = DRIVER_NAME_SHORT,
5804         .proc_name = DRIVER_NAME_SHORT,
5805         .queuecommand = pqi_scsi_queue_command,
5806         .scan_start = pqi_scan_start,
5807         .scan_finished = pqi_scan_finished,
5808         .this_id = -1,
5809         .use_clustering = ENABLE_CLUSTERING,
5810         .eh_device_reset_handler = pqi_eh_device_reset_handler,
5811         .ioctl = pqi_ioctl,
5812         .slave_alloc = pqi_slave_alloc,
5813         .map_queues = pqi_map_queues,
5814         .sdev_attrs = pqi_sdev_attrs,
5815         .shost_attrs = pqi_shost_attrs,
5816 };
5817
5818 static int pqi_register_scsi(struct pqi_ctrl_info *ctrl_info)
5819 {
5820         int rc;
5821         struct Scsi_Host *shost;
5822
5823         shost = scsi_host_alloc(&pqi_driver_template, sizeof(ctrl_info));
5824         if (!shost) {
5825                 dev_err(&ctrl_info->pci_dev->dev,
5826                         "scsi_host_alloc failed for controller %u\n",
5827                         ctrl_info->ctrl_id);
5828                 return -ENOMEM;
5829         }
5830
5831         shost->io_port = 0;
5832         shost->n_io_port = 0;
5833         shost->this_id = -1;
5834         shost->max_channel = PQI_MAX_BUS;
5835         shost->max_cmd_len = MAX_COMMAND_SIZE;
5836         shost->max_lun = ~0;
5837         shost->max_id = ~0;
5838         shost->max_sectors = ctrl_info->max_sectors;
5839         shost->can_queue = ctrl_info->scsi_ml_can_queue;
5840         shost->cmd_per_lun = shost->can_queue;
5841         shost->sg_tablesize = ctrl_info->sg_tablesize;
5842         shost->transportt = pqi_sas_transport_template;
5843         shost->irq = pci_irq_vector(ctrl_info->pci_dev, 0);
5844         shost->unique_id = shost->irq;
5845         shost->nr_hw_queues = ctrl_info->num_queue_groups;
5846         shost->hostdata[0] = (unsigned long)ctrl_info;
5847
5848         rc = scsi_add_host(shost, &ctrl_info->pci_dev->dev);
5849         if (rc) {
5850                 dev_err(&ctrl_info->pci_dev->dev,
5851                         "scsi_add_host failed for controller %u\n",
5852                         ctrl_info->ctrl_id);
5853                 goto free_host;
5854         }
5855
5856         rc = pqi_add_sas_host(shost, ctrl_info);
5857         if (rc) {
5858                 dev_err(&ctrl_info->pci_dev->dev,
5859                         "add SAS host failed for controller %u\n",
5860                         ctrl_info->ctrl_id);
5861                 goto remove_host;
5862         }
5863
5864         ctrl_info->scsi_host = shost;
5865
5866         return 0;
5867
5868 remove_host:
5869         scsi_remove_host(shost);
5870 free_host:
5871         scsi_host_put(shost);
5872
5873         return rc;
5874 }
5875
5876 static void pqi_unregister_scsi(struct pqi_ctrl_info *ctrl_info)
5877 {
5878         struct Scsi_Host *shost;
5879
5880         pqi_delete_sas_host(ctrl_info);
5881
5882         shost = ctrl_info->scsi_host;
5883         if (!shost)
5884                 return;
5885
5886         scsi_remove_host(shost);
5887         scsi_host_put(shost);
5888 }
5889
5890 static int pqi_wait_for_pqi_reset_completion(struct pqi_ctrl_info *ctrl_info)
5891 {
5892         int rc = 0;
5893         struct pqi_device_registers __iomem *pqi_registers;
5894         unsigned long timeout;
5895         unsigned int timeout_msecs;
5896         union pqi_reset_register reset_reg;
5897
5898         pqi_registers = ctrl_info->pqi_registers;
5899         timeout_msecs = readw(&pqi_registers->max_reset_timeout) * 100;
5900         timeout = msecs_to_jiffies(timeout_msecs) + jiffies;
5901
5902         while (1) {
5903                 msleep(PQI_RESET_POLL_INTERVAL_MSECS);
5904                 reset_reg.all_bits = readl(&pqi_registers->device_reset);
5905                 if (reset_reg.bits.reset_action == PQI_RESET_ACTION_COMPLETED)
5906                         break;
5907                 pqi_check_ctrl_health(ctrl_info);
5908                 if (pqi_ctrl_offline(ctrl_info)) {
5909                         rc = -ENXIO;
5910                         break;
5911                 }
5912                 if (time_after(jiffies, timeout)) {
5913                         rc = -ETIMEDOUT;
5914                         break;
5915                 }
5916         }
5917
5918         return rc;
5919 }
5920
5921 static int pqi_reset(struct pqi_ctrl_info *ctrl_info)
5922 {
5923         int rc;
5924         union pqi_reset_register reset_reg;
5925
5926         if (ctrl_info->pqi_reset_quiesce_supported) {
5927                 rc = sis_pqi_reset_quiesce(ctrl_info);
5928                 if (rc) {
5929                         dev_err(&ctrl_info->pci_dev->dev,
5930                                 "PQI reset failed during quiesce with error %d\n",
5931                                 rc);
5932                         return rc;
5933                 }
5934         }
5935
5936         reset_reg.all_bits = 0;
5937         reset_reg.bits.reset_type = PQI_RESET_TYPE_HARD_RESET;
5938         reset_reg.bits.reset_action = PQI_RESET_ACTION_RESET;
5939
5940         writel(reset_reg.all_bits, &ctrl_info->pqi_registers->device_reset);
5941
5942         rc = pqi_wait_for_pqi_reset_completion(ctrl_info);
5943         if (rc)
5944                 dev_err(&ctrl_info->pci_dev->dev,
5945                         "PQI reset failed with error %d\n", rc);
5946
5947         return rc;
5948 }
5949
5950 static int pqi_get_ctrl_firmware_version(struct pqi_ctrl_info *ctrl_info)
5951 {
5952         int rc;
5953         struct bmic_identify_controller *identify;
5954
5955         identify = kmalloc(sizeof(*identify), GFP_KERNEL);
5956         if (!identify)
5957                 return -ENOMEM;
5958
5959         rc = pqi_identify_controller(ctrl_info, identify);
5960         if (rc)
5961                 goto out;
5962
5963         memcpy(ctrl_info->firmware_version, identify->firmware_version,
5964                 sizeof(identify->firmware_version));
5965         ctrl_info->firmware_version[sizeof(identify->firmware_version)] = '\0';
5966         snprintf(ctrl_info->firmware_version +
5967                 strlen(ctrl_info->firmware_version),
5968                 sizeof(ctrl_info->firmware_version),
5969                 "-%u", get_unaligned_le16(&identify->firmware_build_number));
5970
5971 out:
5972         kfree(identify);
5973
5974         return rc;
5975 }
5976
5977 static int pqi_process_config_table(struct pqi_ctrl_info *ctrl_info)
5978 {
5979         u32 table_length;
5980         u32 section_offset;
5981         void __iomem *table_iomem_addr;
5982         struct pqi_config_table *config_table;
5983         struct pqi_config_table_section_header *section;
5984
5985         table_length = ctrl_info->config_table_length;
5986
5987         config_table = kmalloc(table_length, GFP_KERNEL);
5988         if (!config_table) {
5989                 dev_err(&ctrl_info->pci_dev->dev,
5990                         "failed to allocate memory for PQI configuration table\n");
5991                 return -ENOMEM;
5992         }
5993
5994         /*
5995          * Copy the config table contents from I/O memory space into the
5996          * temporary buffer.
5997          */
5998         table_iomem_addr = ctrl_info->iomem_base +
5999                 ctrl_info->config_table_offset;
6000         memcpy_fromio(config_table, table_iomem_addr, table_length);
6001
6002         section_offset =
6003                 get_unaligned_le32(&config_table->first_section_offset);
6004
6005         while (section_offset) {
6006                 section = (void *)config_table + section_offset;
6007
6008                 switch (get_unaligned_le16(&section->section_id)) {
6009                 case PQI_CONFIG_TABLE_SECTION_HEARTBEAT:
6010                         if (pqi_disable_heartbeat)
6011                                 dev_warn(&ctrl_info->pci_dev->dev,
6012                                 "heartbeat disabled by module parameter\n");
6013                         else
6014                                 ctrl_info->heartbeat_counter =
6015                                         table_iomem_addr +
6016                                         section_offset +
6017                                         offsetof(
6018                                         struct pqi_config_table_heartbeat,
6019                                                 heartbeat_counter);
6020                         break;
6021                 }
6022
6023                 section_offset =
6024                         get_unaligned_le16(&section->next_section_offset);
6025         }
6026
6027         kfree(config_table);
6028
6029         return 0;
6030 }
6031
6032 /* Switches the controller from PQI mode back into SIS mode. */
6033
6034 static int pqi_revert_to_sis_mode(struct pqi_ctrl_info *ctrl_info)
6035 {
6036         int rc;
6037
6038         pqi_change_irq_mode(ctrl_info, IRQ_MODE_NONE);
6039         rc = pqi_reset(ctrl_info);
6040         if (rc)
6041                 return rc;
6042         rc = sis_reenable_sis_mode(ctrl_info);
6043         if (rc) {
6044                 dev_err(&ctrl_info->pci_dev->dev,
6045                         "re-enabling SIS mode failed with error %d\n", rc);
6046                 return rc;
6047         }
6048         pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
6049
6050         return 0;
6051 }
6052
6053 /*
6054  * If the controller isn't already in SIS mode, this function forces it into
6055  * SIS mode.
6056  */
6057
6058 static int pqi_force_sis_mode(struct pqi_ctrl_info *ctrl_info)
6059 {
6060         if (!sis_is_firmware_running(ctrl_info))
6061                 return -ENXIO;
6062
6063         if (pqi_get_ctrl_mode(ctrl_info) == SIS_MODE)
6064                 return 0;
6065
6066         if (sis_is_kernel_up(ctrl_info)) {
6067                 pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
6068                 return 0;
6069         }
6070
6071         return pqi_revert_to_sis_mode(ctrl_info);
6072 }
6073
6074 static int pqi_ctrl_init(struct pqi_ctrl_info *ctrl_info)
6075 {
6076         int rc;
6077
6078         rc = pqi_force_sis_mode(ctrl_info);
6079         if (rc)
6080                 return rc;
6081
6082         /*
6083          * Wait until the controller is ready to start accepting SIS
6084          * commands.
6085          */
6086         rc = sis_wait_for_ctrl_ready(ctrl_info);
6087         if (rc)
6088                 return rc;
6089
6090         /*
6091          * Get the controller properties.  This allows us to determine
6092          * whether or not it supports PQI mode.
6093          */
6094         rc = sis_get_ctrl_properties(ctrl_info);
6095         if (rc) {
6096                 dev_err(&ctrl_info->pci_dev->dev,
6097                         "error obtaining controller properties\n");
6098                 return rc;
6099         }
6100
6101         rc = sis_get_pqi_capabilities(ctrl_info);
6102         if (rc) {
6103                 dev_err(&ctrl_info->pci_dev->dev,
6104                         "error obtaining controller capabilities\n");
6105                 return rc;
6106         }
6107
6108         if (reset_devices) {
6109                 if (ctrl_info->max_outstanding_requests >
6110                         PQI_MAX_OUTSTANDING_REQUESTS_KDUMP)
6111                         ctrl_info->max_outstanding_requests =
6112                                         PQI_MAX_OUTSTANDING_REQUESTS_KDUMP;
6113         } else {
6114                 if (ctrl_info->max_outstanding_requests >
6115                         PQI_MAX_OUTSTANDING_REQUESTS)
6116                         ctrl_info->max_outstanding_requests =
6117                                         PQI_MAX_OUTSTANDING_REQUESTS;
6118         }
6119
6120         pqi_calculate_io_resources(ctrl_info);
6121
6122         rc = pqi_alloc_error_buffer(ctrl_info);
6123         if (rc) {
6124                 dev_err(&ctrl_info->pci_dev->dev,
6125                         "failed to allocate PQI error buffer\n");
6126                 return rc;
6127         }
6128
6129         /*
6130          * If the function we are about to call succeeds, the
6131          * controller will transition from legacy SIS mode
6132          * into PQI mode.
6133          */
6134         rc = sis_init_base_struct_addr(ctrl_info);
6135         if (rc) {
6136                 dev_err(&ctrl_info->pci_dev->dev,
6137                         "error initializing PQI mode\n");
6138                 return rc;
6139         }
6140
6141         /* Wait for the controller to complete the SIS -> PQI transition. */
6142         rc = pqi_wait_for_pqi_mode_ready(ctrl_info);
6143         if (rc) {
6144                 dev_err(&ctrl_info->pci_dev->dev,
6145                         "transition to PQI mode failed\n");
6146                 return rc;
6147         }
6148
6149         /* From here on, we are running in PQI mode. */
6150         ctrl_info->pqi_mode_enabled = true;
6151         pqi_save_ctrl_mode(ctrl_info, PQI_MODE);
6152
6153         rc = pqi_process_config_table(ctrl_info);
6154         if (rc)
6155                 return rc;
6156
6157         rc = pqi_alloc_admin_queues(ctrl_info);
6158         if (rc) {
6159                 dev_err(&ctrl_info->pci_dev->dev,
6160                         "failed to allocate admin queues\n");
6161                 return rc;
6162         }
6163
6164         rc = pqi_create_admin_queues(ctrl_info);
6165         if (rc) {
6166                 dev_err(&ctrl_info->pci_dev->dev,
6167                         "error creating admin queues\n");
6168                 return rc;
6169         }
6170
6171         rc = pqi_report_device_capability(ctrl_info);
6172         if (rc) {
6173                 dev_err(&ctrl_info->pci_dev->dev,
6174                         "obtaining device capability failed\n");
6175                 return rc;
6176         }
6177
6178         rc = pqi_validate_device_capability(ctrl_info);
6179         if (rc)
6180                 return rc;
6181
6182         pqi_calculate_queue_resources(ctrl_info);
6183
6184         rc = pqi_enable_msix_interrupts(ctrl_info);
6185         if (rc)
6186                 return rc;
6187
6188         if (ctrl_info->num_msix_vectors_enabled < ctrl_info->num_queue_groups) {
6189                 ctrl_info->max_msix_vectors =
6190                         ctrl_info->num_msix_vectors_enabled;
6191                 pqi_calculate_queue_resources(ctrl_info);
6192         }
6193
6194         rc = pqi_alloc_io_resources(ctrl_info);
6195         if (rc)
6196                 return rc;
6197
6198         rc = pqi_alloc_operational_queues(ctrl_info);
6199         if (rc) {
6200                 dev_err(&ctrl_info->pci_dev->dev,
6201                         "failed to allocate operational queues\n");
6202                 return rc;
6203         }
6204
6205         pqi_init_operational_queues(ctrl_info);
6206
6207         rc = pqi_request_irqs(ctrl_info);
6208         if (rc)
6209                 return rc;
6210
6211         rc = pqi_create_queues(ctrl_info);
6212         if (rc)
6213                 return rc;
6214
6215         pqi_change_irq_mode(ctrl_info, IRQ_MODE_MSIX);
6216
6217         ctrl_info->controller_online = true;
6218         pqi_start_heartbeat_timer(ctrl_info);
6219
6220         rc = pqi_enable_events(ctrl_info);
6221         if (rc) {
6222                 dev_err(&ctrl_info->pci_dev->dev,
6223                         "error enabling events\n");
6224                 return rc;
6225         }
6226
6227         /* Register with the SCSI subsystem. */
6228         rc = pqi_register_scsi(ctrl_info);
6229         if (rc)
6230                 return rc;
6231
6232         rc = pqi_get_ctrl_firmware_version(ctrl_info);
6233         if (rc) {
6234                 dev_err(&ctrl_info->pci_dev->dev,
6235                         "error obtaining firmware version\n");
6236                 return rc;
6237         }
6238
6239         rc = pqi_write_driver_version_to_host_wellness(ctrl_info);
6240         if (rc) {
6241                 dev_err(&ctrl_info->pci_dev->dev,
6242                         "error updating host wellness\n");
6243                 return rc;
6244         }
6245
6246         pqi_schedule_update_time_worker(ctrl_info);
6247
6248         pqi_scan_scsi_devices(ctrl_info);
6249
6250         return 0;
6251 }
6252
6253 static void pqi_reinit_queues(struct pqi_ctrl_info *ctrl_info)
6254 {
6255         unsigned int i;
6256         struct pqi_admin_queues *admin_queues;
6257         struct pqi_event_queue *event_queue;
6258
6259         admin_queues = &ctrl_info->admin_queues;
6260         admin_queues->iq_pi_copy = 0;
6261         admin_queues->oq_ci_copy = 0;
6262         writel(0, admin_queues->oq_pi);
6263
6264         for (i = 0; i < ctrl_info->num_queue_groups; i++) {
6265                 ctrl_info->queue_groups[i].iq_pi_copy[RAID_PATH] = 0;
6266                 ctrl_info->queue_groups[i].iq_pi_copy[AIO_PATH] = 0;
6267                 ctrl_info->queue_groups[i].oq_ci_copy = 0;
6268
6269                 writel(0, ctrl_info->queue_groups[i].iq_ci[RAID_PATH]);
6270                 writel(0, ctrl_info->queue_groups[i].iq_ci[AIO_PATH]);
6271                 writel(0, ctrl_info->queue_groups[i].oq_pi);
6272         }
6273
6274         event_queue = &ctrl_info->event_queue;
6275         writel(0, event_queue->oq_pi);
6276         event_queue->oq_ci_copy = 0;
6277 }
6278
6279 static int pqi_ctrl_init_resume(struct pqi_ctrl_info *ctrl_info)
6280 {
6281         int rc;
6282
6283         rc = pqi_force_sis_mode(ctrl_info);
6284         if (rc)
6285                 return rc;
6286
6287         /*
6288          * Wait until the controller is ready to start accepting SIS
6289          * commands.
6290          */
6291         rc = sis_wait_for_ctrl_ready_resume(ctrl_info);
6292         if (rc)
6293                 return rc;
6294
6295         /*
6296          * If the function we are about to call succeeds, the
6297          * controller will transition from legacy SIS mode
6298          * into PQI mode.
6299          */
6300         rc = sis_init_base_struct_addr(ctrl_info);
6301         if (rc) {
6302                 dev_err(&ctrl_info->pci_dev->dev,
6303                         "error initializing PQI mode\n");
6304                 return rc;
6305         }
6306
6307         /* Wait for the controller to complete the SIS -> PQI transition. */
6308         rc = pqi_wait_for_pqi_mode_ready(ctrl_info);
6309         if (rc) {
6310                 dev_err(&ctrl_info->pci_dev->dev,
6311                         "transition to PQI mode failed\n");
6312                 return rc;
6313         }
6314
6315         /* From here on, we are running in PQI mode. */
6316         ctrl_info->pqi_mode_enabled = true;
6317         pqi_save_ctrl_mode(ctrl_info, PQI_MODE);
6318
6319         pqi_reinit_queues(ctrl_info);
6320
6321         rc = pqi_create_admin_queues(ctrl_info);
6322         if (rc) {
6323                 dev_err(&ctrl_info->pci_dev->dev,
6324                         "error creating admin queues\n");
6325                 return rc;
6326         }
6327
6328         rc = pqi_create_queues(ctrl_info);
6329         if (rc)
6330                 return rc;
6331
6332         pqi_change_irq_mode(ctrl_info, IRQ_MODE_MSIX);
6333
6334         ctrl_info->controller_online = true;
6335         pqi_start_heartbeat_timer(ctrl_info);
6336         pqi_ctrl_unblock_requests(ctrl_info);
6337
6338         rc = pqi_enable_events(ctrl_info);
6339         if (rc) {
6340                 dev_err(&ctrl_info->pci_dev->dev,
6341                         "error enabling events\n");
6342                 return rc;
6343         }
6344
6345         rc = pqi_write_driver_version_to_host_wellness(ctrl_info);
6346         if (rc) {
6347                 dev_err(&ctrl_info->pci_dev->dev,
6348                         "error updating host wellness\n");
6349                 return rc;
6350         }
6351
6352         pqi_schedule_update_time_worker(ctrl_info);
6353
6354         pqi_scan_scsi_devices(ctrl_info);
6355
6356         return 0;
6357 }
6358
6359 static inline int pqi_set_pcie_completion_timeout(struct pci_dev *pci_dev,
6360         u16 timeout)
6361 {
6362         return pcie_capability_clear_and_set_word(pci_dev, PCI_EXP_DEVCTL2,
6363                 PCI_EXP_DEVCTL2_COMP_TIMEOUT, timeout);
6364 }
6365
6366 static int pqi_pci_init(struct pqi_ctrl_info *ctrl_info)
6367 {
6368         int rc;
6369         u64 mask;
6370
6371         rc = pci_enable_device(ctrl_info->pci_dev);
6372         if (rc) {
6373                 dev_err(&ctrl_info->pci_dev->dev,
6374                         "failed to enable PCI device\n");
6375                 return rc;
6376         }
6377
6378         if (sizeof(dma_addr_t) > 4)
6379                 mask = DMA_BIT_MASK(64);
6380         else
6381                 mask = DMA_BIT_MASK(32);
6382
6383         rc = dma_set_mask_and_coherent(&ctrl_info->pci_dev->dev, mask);
6384         if (rc) {
6385                 dev_err(&ctrl_info->pci_dev->dev, "failed to set DMA mask\n");
6386                 goto disable_device;
6387         }
6388
6389         rc = pci_request_regions(ctrl_info->pci_dev, DRIVER_NAME_SHORT);
6390         if (rc) {
6391                 dev_err(&ctrl_info->pci_dev->dev,
6392                         "failed to obtain PCI resources\n");
6393                 goto disable_device;
6394         }
6395
6396         ctrl_info->iomem_base = ioremap_nocache(pci_resource_start(
6397                 ctrl_info->pci_dev, 0),
6398                 sizeof(struct pqi_ctrl_registers));
6399         if (!ctrl_info->iomem_base) {
6400                 dev_err(&ctrl_info->pci_dev->dev,
6401                         "failed to map memory for controller registers\n");
6402                 rc = -ENOMEM;
6403                 goto release_regions;
6404         }
6405
6406 #define PCI_EXP_COMP_TIMEOUT_65_TO_210_MS               0x6
6407
6408         /* Increase the PCIe completion timeout. */
6409         rc = pqi_set_pcie_completion_timeout(ctrl_info->pci_dev,
6410                 PCI_EXP_COMP_TIMEOUT_65_TO_210_MS);
6411         if (rc) {
6412                 dev_err(&ctrl_info->pci_dev->dev,
6413                         "failed to set PCIe completion timeout\n");
6414                 goto release_regions;
6415         }
6416
6417         /* Enable bus mastering. */
6418         pci_set_master(ctrl_info->pci_dev);
6419
6420         ctrl_info->registers = ctrl_info->iomem_base;
6421         ctrl_info->pqi_registers = &ctrl_info->registers->pqi_registers;
6422
6423         pci_set_drvdata(ctrl_info->pci_dev, ctrl_info);
6424
6425         return 0;
6426
6427 release_regions:
6428         pci_release_regions(ctrl_info->pci_dev);
6429 disable_device:
6430         pci_disable_device(ctrl_info->pci_dev);
6431
6432         return rc;
6433 }
6434
6435 static void pqi_cleanup_pci_init(struct pqi_ctrl_info *ctrl_info)
6436 {
6437         iounmap(ctrl_info->iomem_base);
6438         pci_release_regions(ctrl_info->pci_dev);
6439         if (pci_is_enabled(ctrl_info->pci_dev))
6440                 pci_disable_device(ctrl_info->pci_dev);
6441         pci_set_drvdata(ctrl_info->pci_dev, NULL);
6442 }
6443
6444 static struct pqi_ctrl_info *pqi_alloc_ctrl_info(int numa_node)
6445 {
6446         struct pqi_ctrl_info *ctrl_info;
6447
6448         ctrl_info = kzalloc_node(sizeof(struct pqi_ctrl_info),
6449                         GFP_KERNEL, numa_node);
6450         if (!ctrl_info)
6451                 return NULL;
6452
6453         mutex_init(&ctrl_info->scan_mutex);
6454         mutex_init(&ctrl_info->lun_reset_mutex);
6455
6456         INIT_LIST_HEAD(&ctrl_info->scsi_device_list);
6457         spin_lock_init(&ctrl_info->scsi_device_list_lock);
6458
6459         INIT_WORK(&ctrl_info->event_work, pqi_event_worker);
6460         atomic_set(&ctrl_info->num_interrupts, 0);
6461
6462         INIT_DELAYED_WORK(&ctrl_info->rescan_work, pqi_rescan_worker);
6463         INIT_DELAYED_WORK(&ctrl_info->update_time_work, pqi_update_time_worker);
6464
6465         timer_setup(&ctrl_info->heartbeat_timer, pqi_heartbeat_timer_handler, 0);
6466         INIT_WORK(&ctrl_info->ctrl_offline_work, pqi_ctrl_offline_worker);
6467
6468         sema_init(&ctrl_info->sync_request_sem,
6469                 PQI_RESERVED_IO_SLOTS_SYNCHRONOUS_REQUESTS);
6470         init_waitqueue_head(&ctrl_info->block_requests_wait);
6471
6472         INIT_LIST_HEAD(&ctrl_info->raid_bypass_retry_list);
6473         spin_lock_init(&ctrl_info->raid_bypass_retry_list_lock);
6474         INIT_WORK(&ctrl_info->raid_bypass_retry_work,
6475                 pqi_raid_bypass_retry_worker);
6476
6477         ctrl_info->ctrl_id = atomic_inc_return(&pqi_controller_count) - 1;
6478         ctrl_info->irq_mode = IRQ_MODE_NONE;
6479         ctrl_info->max_msix_vectors = PQI_MAX_MSIX_VECTORS;
6480
6481         return ctrl_info;
6482 }
6483
6484 static inline void pqi_free_ctrl_info(struct pqi_ctrl_info *ctrl_info)
6485 {
6486         kfree(ctrl_info);
6487 }
6488
6489 static void pqi_free_interrupts(struct pqi_ctrl_info *ctrl_info)
6490 {
6491         pqi_free_irqs(ctrl_info);
6492         pqi_disable_msix_interrupts(ctrl_info);
6493 }
6494
6495 static void pqi_free_ctrl_resources(struct pqi_ctrl_info *ctrl_info)
6496 {
6497         pqi_stop_heartbeat_timer(ctrl_info);
6498         pqi_free_interrupts(ctrl_info);
6499         if (ctrl_info->queue_memory_base)
6500                 dma_free_coherent(&ctrl_info->pci_dev->dev,
6501                         ctrl_info->queue_memory_length,
6502                         ctrl_info->queue_memory_base,
6503                         ctrl_info->queue_memory_base_dma_handle);
6504         if (ctrl_info->admin_queue_memory_base)
6505                 dma_free_coherent(&ctrl_info->pci_dev->dev,
6506                         ctrl_info->admin_queue_memory_length,
6507                         ctrl_info->admin_queue_memory_base,
6508                         ctrl_info->admin_queue_memory_base_dma_handle);
6509         pqi_free_all_io_requests(ctrl_info);
6510         if (ctrl_info->error_buffer)
6511                 dma_free_coherent(&ctrl_info->pci_dev->dev,
6512                         ctrl_info->error_buffer_length,
6513                         ctrl_info->error_buffer,
6514                         ctrl_info->error_buffer_dma_handle);
6515         if (ctrl_info->iomem_base)
6516                 pqi_cleanup_pci_init(ctrl_info);
6517         pqi_free_ctrl_info(ctrl_info);
6518 }
6519
6520 static void pqi_remove_ctrl(struct pqi_ctrl_info *ctrl_info)
6521 {
6522         pqi_cancel_rescan_worker(ctrl_info);
6523         pqi_cancel_update_time_worker(ctrl_info);
6524         pqi_remove_all_scsi_devices(ctrl_info);
6525         pqi_unregister_scsi(ctrl_info);
6526         if (ctrl_info->pqi_mode_enabled)
6527                 pqi_revert_to_sis_mode(ctrl_info);
6528         pqi_free_ctrl_resources(ctrl_info);
6529 }
6530
6531 static void pqi_perform_lockup_action(void)
6532 {
6533         switch (pqi_lockup_action) {
6534         case PANIC:
6535                 panic("FATAL: Smart Family Controller lockup detected");
6536                 break;
6537         case REBOOT:
6538                 emergency_restart();
6539                 break;
6540         case NONE:
6541         default:
6542                 break;
6543         }
6544 }
6545
6546 static struct pqi_raid_error_info pqi_ctrl_offline_raid_error_info = {
6547         .data_out_result = PQI_DATA_IN_OUT_HARDWARE_ERROR,
6548         .status = SAM_STAT_CHECK_CONDITION,
6549 };
6550
6551 static void pqi_fail_all_outstanding_requests(struct pqi_ctrl_info *ctrl_info)
6552 {
6553         unsigned int i;
6554         struct pqi_io_request *io_request;
6555         struct scsi_cmnd *scmd;
6556
6557         for (i = 0; i < ctrl_info->max_io_slots; i++) {
6558                 io_request = &ctrl_info->io_request_pool[i];
6559                 if (atomic_read(&io_request->refcount) == 0)
6560                         continue;
6561
6562                 scmd = io_request->scmd;
6563                 if (scmd) {
6564                         set_host_byte(scmd, DID_NO_CONNECT);
6565                 } else {
6566                         io_request->status = -ENXIO;
6567                         io_request->error_info =
6568                                 &pqi_ctrl_offline_raid_error_info;
6569                 }
6570
6571                 io_request->io_complete_callback(io_request,
6572                         io_request->context);
6573         }
6574 }
6575
6576 static void pqi_take_ctrl_offline_deferred(struct pqi_ctrl_info *ctrl_info)
6577 {
6578         pqi_perform_lockup_action();
6579         pqi_stop_heartbeat_timer(ctrl_info);
6580         pqi_free_interrupts(ctrl_info);
6581         pqi_cancel_rescan_worker(ctrl_info);
6582         pqi_cancel_update_time_worker(ctrl_info);
6583         pqi_ctrl_wait_until_quiesced(ctrl_info);
6584         pqi_fail_all_outstanding_requests(ctrl_info);
6585         pqi_clear_all_queued_raid_bypass_retries(ctrl_info);
6586         pqi_ctrl_unblock_requests(ctrl_info);
6587 }
6588
6589 static void pqi_ctrl_offline_worker(struct work_struct *work)
6590 {
6591         struct pqi_ctrl_info *ctrl_info;
6592
6593         ctrl_info = container_of(work, struct pqi_ctrl_info, ctrl_offline_work);
6594         pqi_take_ctrl_offline_deferred(ctrl_info);
6595 }
6596
6597 static void pqi_take_ctrl_offline(struct pqi_ctrl_info *ctrl_info)
6598 {
6599         if (!ctrl_info->controller_online)
6600                 return;
6601
6602         ctrl_info->controller_online = false;
6603         ctrl_info->pqi_mode_enabled = false;
6604         pqi_ctrl_block_requests(ctrl_info);
6605         if (!pqi_disable_ctrl_shutdown)
6606                 sis_shutdown_ctrl(ctrl_info);
6607         pci_disable_device(ctrl_info->pci_dev);
6608         dev_err(&ctrl_info->pci_dev->dev, "controller offline\n");
6609         schedule_work(&ctrl_info->ctrl_offline_work);
6610 }
6611
6612 static void pqi_print_ctrl_info(struct pci_dev *pci_dev,
6613         const struct pci_device_id *id)
6614 {
6615         char *ctrl_description;
6616
6617         if (id->driver_data)
6618                 ctrl_description = (char *)id->driver_data;
6619         else
6620                 ctrl_description = "Microsemi Smart Family Controller";
6621
6622         dev_info(&pci_dev->dev, "%s found\n", ctrl_description);
6623 }
6624
6625 static int pqi_pci_probe(struct pci_dev *pci_dev,
6626         const struct pci_device_id *id)
6627 {
6628         int rc;
6629         int node;
6630         struct pqi_ctrl_info *ctrl_info;
6631
6632         pqi_print_ctrl_info(pci_dev, id);
6633
6634         if (pqi_disable_device_id_wildcards &&
6635                 id->subvendor == PCI_ANY_ID &&
6636                 id->subdevice == PCI_ANY_ID) {
6637                 dev_warn(&pci_dev->dev,
6638                         "controller not probed because device ID wildcards are disabled\n");
6639                 return -ENODEV;
6640         }
6641
6642         if (id->subvendor == PCI_ANY_ID || id->subdevice == PCI_ANY_ID)
6643                 dev_warn(&pci_dev->dev,
6644                         "controller device ID matched using wildcards\n");
6645
6646         node = dev_to_node(&pci_dev->dev);
6647         if (node == NUMA_NO_NODE)
6648                 set_dev_node(&pci_dev->dev, 0);
6649
6650         ctrl_info = pqi_alloc_ctrl_info(node);
6651         if (!ctrl_info) {
6652                 dev_err(&pci_dev->dev,
6653                         "failed to allocate controller info block\n");
6654                 return -ENOMEM;
6655         }
6656
6657         ctrl_info->pci_dev = pci_dev;
6658
6659         rc = pqi_pci_init(ctrl_info);
6660         if (rc)
6661                 goto error;
6662
6663         rc = pqi_ctrl_init(ctrl_info);
6664         if (rc)
6665                 goto error;
6666
6667         return 0;
6668
6669 error:
6670         pqi_remove_ctrl(ctrl_info);
6671
6672         return rc;
6673 }
6674
6675 static void pqi_pci_remove(struct pci_dev *pci_dev)
6676 {
6677         struct pqi_ctrl_info *ctrl_info;
6678
6679         ctrl_info = pci_get_drvdata(pci_dev);
6680         if (!ctrl_info)
6681                 return;
6682
6683         pqi_remove_ctrl(ctrl_info);
6684 }
6685
6686 static void pqi_shutdown(struct pci_dev *pci_dev)
6687 {
6688         int rc;
6689         struct pqi_ctrl_info *ctrl_info;
6690
6691         ctrl_info = pci_get_drvdata(pci_dev);
6692         if (!ctrl_info)
6693                 goto error;
6694
6695         /*
6696          * Write all data in the controller's battery-backed cache to
6697          * storage.
6698          */
6699         rc = pqi_flush_cache(ctrl_info, SHUTDOWN);
6700         pqi_free_interrupts(ctrl_info);
6701         pqi_reset(ctrl_info);
6702         if (rc == 0)
6703                 return;
6704
6705 error:
6706         dev_warn(&pci_dev->dev,
6707                 "unable to flush controller cache\n");
6708 }
6709
6710 static void pqi_process_lockup_action_param(void)
6711 {
6712         unsigned int i;
6713
6714         if (!pqi_lockup_action_param)
6715                 return;
6716
6717         for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
6718                 if (strcmp(pqi_lockup_action_param,
6719                         pqi_lockup_actions[i].name) == 0) {
6720                         pqi_lockup_action = pqi_lockup_actions[i].action;
6721                         return;
6722                 }
6723         }
6724
6725         pr_warn("%s: invalid lockup action setting \"%s\" - supported settings: none, reboot, panic\n",
6726                 DRIVER_NAME_SHORT, pqi_lockup_action_param);
6727 }
6728
6729 static void pqi_process_module_params(void)
6730 {
6731         pqi_process_lockup_action_param();
6732 }
6733
6734 static __maybe_unused int pqi_suspend(struct pci_dev *pci_dev, pm_message_t state)
6735 {
6736         struct pqi_ctrl_info *ctrl_info;
6737
6738         ctrl_info = pci_get_drvdata(pci_dev);
6739
6740         pqi_disable_events(ctrl_info);
6741         pqi_cancel_update_time_worker(ctrl_info);
6742         pqi_cancel_rescan_worker(ctrl_info);
6743         pqi_wait_until_scan_finished(ctrl_info);
6744         pqi_wait_until_lun_reset_finished(ctrl_info);
6745         pqi_flush_cache(ctrl_info, SUSPEND);
6746         pqi_ctrl_block_requests(ctrl_info);
6747         pqi_ctrl_wait_until_quiesced(ctrl_info);
6748         pqi_wait_until_inbound_queues_empty(ctrl_info);
6749         pqi_ctrl_wait_for_pending_io(ctrl_info);
6750         pqi_stop_heartbeat_timer(ctrl_info);
6751
6752         if (state.event == PM_EVENT_FREEZE)
6753                 return 0;
6754
6755         pci_save_state(pci_dev);
6756         pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state));
6757
6758         ctrl_info->controller_online = false;
6759         ctrl_info->pqi_mode_enabled = false;
6760
6761         return 0;
6762 }
6763
6764 static __maybe_unused int pqi_resume(struct pci_dev *pci_dev)
6765 {
6766         int rc;
6767         struct pqi_ctrl_info *ctrl_info;
6768
6769         ctrl_info = pci_get_drvdata(pci_dev);
6770
6771         if (pci_dev->current_state != PCI_D0) {
6772                 ctrl_info->max_hw_queue_index = 0;
6773                 pqi_free_interrupts(ctrl_info);
6774                 pqi_change_irq_mode(ctrl_info, IRQ_MODE_INTX);
6775                 rc = request_irq(pci_irq_vector(pci_dev, 0), pqi_irq_handler,
6776                         IRQF_SHARED, DRIVER_NAME_SHORT,
6777                         &ctrl_info->queue_groups[0]);
6778                 if (rc) {
6779                         dev_err(&ctrl_info->pci_dev->dev,
6780                                 "irq %u init failed with error %d\n",
6781                                 pci_dev->irq, rc);
6782                         return rc;
6783                 }
6784                 pqi_start_heartbeat_timer(ctrl_info);
6785                 pqi_ctrl_unblock_requests(ctrl_info);
6786                 return 0;
6787         }
6788
6789         pci_set_power_state(pci_dev, PCI_D0);
6790         pci_restore_state(pci_dev);
6791
6792         return pqi_ctrl_init_resume(ctrl_info);
6793 }
6794
6795 /* Define the PCI IDs for the controllers that we support. */
6796 static const struct pci_device_id pqi_pci_id_table[] = {
6797         {
6798                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6799                                0x105b, 0x1211)
6800         },
6801         {
6802                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6803                                0x105b, 0x1321)
6804         },
6805         {
6806                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6807                                0x152d, 0x8a22)
6808         },
6809         {
6810                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6811                                0x152d, 0x8a23)
6812         },
6813         {
6814                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6815                                0x152d, 0x8a24)
6816         },
6817         {
6818                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6819                                0x152d, 0x8a36)
6820         },
6821         {
6822                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6823                                0x152d, 0x8a37)
6824         },
6825         {
6826                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6827                                0x193d, 0x8460)
6828         },
6829         {
6830                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6831                                0x193d, 0x8461)
6832         },
6833         {
6834                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6835                                0x193d, 0xf460)
6836         },
6837         {
6838                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6839                                0x193d, 0xf461)
6840         },
6841         {
6842                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6843                                0x1bd4, 0x0045)
6844         },
6845         {
6846                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6847                                0x1bd4, 0x0046)
6848         },
6849         {
6850                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6851                                0x1bd4, 0x0047)
6852         },
6853         {
6854                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6855                                0x1bd4, 0x0048)
6856         },
6857         {
6858                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6859                                0x1bd4, 0x004a)
6860         },
6861         {
6862                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6863                                0x1bd4, 0x004b)
6864         },
6865         {
6866                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6867                                0x1bd4, 0x004c)
6868         },
6869         {
6870                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6871                                PCI_VENDOR_ID_ADAPTEC2, 0x0110)
6872         },
6873         {
6874                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6875                                PCI_VENDOR_ID_ADAPTEC2, 0x0608)
6876         },
6877         {
6878                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6879                                PCI_VENDOR_ID_ADAPTEC2, 0x0800)
6880         },
6881         {
6882                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6883                                PCI_VENDOR_ID_ADAPTEC2, 0x0801)
6884         },
6885         {
6886                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6887                                PCI_VENDOR_ID_ADAPTEC2, 0x0802)
6888         },
6889         {
6890                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6891                                PCI_VENDOR_ID_ADAPTEC2, 0x0803)
6892         },
6893         {
6894                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6895                                PCI_VENDOR_ID_ADAPTEC2, 0x0804)
6896         },
6897         {
6898                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6899                                PCI_VENDOR_ID_ADAPTEC2, 0x0805)
6900         },
6901         {
6902                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6903                                PCI_VENDOR_ID_ADAPTEC2, 0x0806)
6904         },
6905         {
6906                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6907                                PCI_VENDOR_ID_ADAPTEC2, 0x0807)
6908         },
6909         {
6910                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6911                                PCI_VENDOR_ID_ADAPTEC2, 0x0900)
6912         },
6913         {
6914                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6915                                PCI_VENDOR_ID_ADAPTEC2, 0x0901)
6916         },
6917         {
6918                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6919                                PCI_VENDOR_ID_ADAPTEC2, 0x0902)
6920         },
6921         {
6922                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6923                                PCI_VENDOR_ID_ADAPTEC2, 0x0903)
6924         },
6925         {
6926                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6927                                PCI_VENDOR_ID_ADAPTEC2, 0x0904)
6928         },
6929         {
6930                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6931                                PCI_VENDOR_ID_ADAPTEC2, 0x0905)
6932         },
6933         {
6934                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6935                                PCI_VENDOR_ID_ADAPTEC2, 0x0906)
6936         },
6937         {
6938                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6939                                PCI_VENDOR_ID_ADAPTEC2, 0x0907)
6940         },
6941         {
6942                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6943                                PCI_VENDOR_ID_ADAPTEC2, 0x0908)
6944         },
6945         {
6946                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6947                                PCI_VENDOR_ID_ADAPTEC2, 0x090a)
6948         },
6949         {
6950                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6951                                PCI_VENDOR_ID_ADAPTEC2, 0x1200)
6952         },
6953         {
6954                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6955                                PCI_VENDOR_ID_ADAPTEC2, 0x1201)
6956         },
6957         {
6958                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6959                                PCI_VENDOR_ID_ADAPTEC2, 0x1202)
6960         },
6961         {
6962                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6963                                PCI_VENDOR_ID_ADAPTEC2, 0x1280)
6964         },
6965         {
6966                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6967                                PCI_VENDOR_ID_ADAPTEC2, 0x1281)
6968         },
6969         {
6970                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6971                                PCI_VENDOR_ID_ADAPTEC2, 0x1282)
6972         },
6973         {
6974                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6975                                PCI_VENDOR_ID_ADAPTEC2, 0x1300)
6976         },
6977         {
6978                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6979                                PCI_VENDOR_ID_ADAPTEC2, 0x1301)
6980         },
6981         {
6982                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6983                                PCI_VENDOR_ID_ADAPTEC2, 0x1302)
6984         },
6985         {
6986                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6987                                PCI_VENDOR_ID_ADAPTEC2, 0x1303)
6988         },
6989         {
6990                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6991                                PCI_VENDOR_ID_ADAPTEC2, 0x1380)
6992         },
6993         {
6994                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6995                                PCI_VENDOR_ID_ADVANTECH, 0x8312)
6996         },
6997         {
6998                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
6999                                PCI_VENDOR_ID_DELL, 0x1fe0)
7000         },
7001         {
7002                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7003                                PCI_VENDOR_ID_HP, 0x0600)
7004         },
7005         {
7006                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7007                                PCI_VENDOR_ID_HP, 0x0601)
7008         },
7009         {
7010                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7011                                PCI_VENDOR_ID_HP, 0x0602)
7012         },
7013         {
7014                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7015                                PCI_VENDOR_ID_HP, 0x0603)
7016         },
7017         {
7018                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7019                                PCI_VENDOR_ID_HP, 0x0609)
7020         },
7021         {
7022                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7023                                PCI_VENDOR_ID_HP, 0x0650)
7024         },
7025         {
7026                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7027                                PCI_VENDOR_ID_HP, 0x0651)
7028         },
7029         {
7030                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7031                                PCI_VENDOR_ID_HP, 0x0652)
7032         },
7033         {
7034                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7035                                PCI_VENDOR_ID_HP, 0x0653)
7036         },
7037         {
7038                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7039                                PCI_VENDOR_ID_HP, 0x0654)
7040         },
7041         {
7042                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7043                                PCI_VENDOR_ID_HP, 0x0655)
7044         },
7045         {
7046                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7047                                PCI_VENDOR_ID_HP, 0x0700)
7048         },
7049         {
7050                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7051                                PCI_VENDOR_ID_HP, 0x0701)
7052         },
7053         {
7054                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7055                                PCI_VENDOR_ID_HP, 0x1001)
7056         },
7057         {
7058                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7059                                PCI_VENDOR_ID_HP, 0x1100)
7060         },
7061         {
7062                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7063                                PCI_VENDOR_ID_HP, 0x1101)
7064         },
7065         {
7066                 PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
7067                                PCI_ANY_ID, PCI_ANY_ID)
7068         },
7069         { 0 }
7070 };
7071
7072 MODULE_DEVICE_TABLE(pci, pqi_pci_id_table);
7073
7074 static struct pci_driver pqi_pci_driver = {
7075         .name = DRIVER_NAME_SHORT,
7076         .id_table = pqi_pci_id_table,
7077         .probe = pqi_pci_probe,
7078         .remove = pqi_pci_remove,
7079         .shutdown = pqi_shutdown,
7080 #if defined(CONFIG_PM)
7081         .suspend = pqi_suspend,
7082         .resume = pqi_resume,
7083 #endif
7084 };
7085
7086 static int __init pqi_init(void)
7087 {
7088         int rc;
7089
7090         pr_info(DRIVER_NAME "\n");
7091
7092         pqi_sas_transport_template =
7093                 sas_attach_transport(&pqi_sas_transport_functions);
7094         if (!pqi_sas_transport_template)
7095                 return -ENODEV;
7096
7097         pqi_process_module_params();
7098
7099         rc = pci_register_driver(&pqi_pci_driver);
7100         if (rc)
7101                 sas_release_transport(pqi_sas_transport_template);
7102
7103         return rc;
7104 }
7105
7106 static void __exit pqi_cleanup(void)
7107 {
7108         pci_unregister_driver(&pqi_pci_driver);
7109         sas_release_transport(pqi_sas_transport_template);
7110 }
7111
7112 module_init(pqi_init);
7113 module_exit(pqi_cleanup);
7114
7115 static void __attribute__((unused)) verify_structures(void)
7116 {
7117         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7118                 sis_host_to_ctrl_doorbell) != 0x20);
7119         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7120                 sis_interrupt_mask) != 0x34);
7121         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7122                 sis_ctrl_to_host_doorbell) != 0x9c);
7123         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7124                 sis_ctrl_to_host_doorbell_clear) != 0xa0);
7125         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7126                 sis_driver_scratch) != 0xb0);
7127         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7128                 sis_firmware_status) != 0xbc);
7129         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7130                 sis_mailbox) != 0x1000);
7131         BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
7132                 pqi_registers) != 0x4000);
7133
7134         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
7135                 iu_type) != 0x0);
7136         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
7137                 iu_length) != 0x2);
7138         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
7139                 response_queue_id) != 0x4);
7140         BUILD_BUG_ON(offsetof(struct pqi_iu_header,
7141                 work_area) != 0x6);
7142         BUILD_BUG_ON(sizeof(struct pqi_iu_header) != 0x8);
7143
7144         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7145                 status) != 0x0);
7146         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7147                 service_response) != 0x1);
7148         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7149                 data_present) != 0x2);
7150         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7151                 reserved) != 0x3);
7152         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7153                 residual_count) != 0x4);
7154         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7155                 data_length) != 0x8);
7156         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7157                 reserved1) != 0xa);
7158         BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
7159                 data) != 0xc);
7160         BUILD_BUG_ON(sizeof(struct pqi_aio_error_info) != 0x10c);
7161
7162         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7163                 data_in_result) != 0x0);
7164         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7165                 data_out_result) != 0x1);
7166         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7167                 reserved) != 0x2);
7168         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7169                 status) != 0x5);
7170         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7171                 status_qualifier) != 0x6);
7172         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7173                 sense_data_length) != 0x8);
7174         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7175                 response_data_length) != 0xa);
7176         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7177                 data_in_transferred) != 0xc);
7178         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7179                 data_out_transferred) != 0x10);
7180         BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
7181                 data) != 0x14);
7182         BUILD_BUG_ON(sizeof(struct pqi_raid_error_info) != 0x114);
7183
7184         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7185                 signature) != 0x0);
7186         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7187                 function_and_status_code) != 0x8);
7188         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7189                 max_admin_iq_elements) != 0x10);
7190         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7191                 max_admin_oq_elements) != 0x11);
7192         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7193                 admin_iq_element_length) != 0x12);
7194         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7195                 admin_oq_element_length) != 0x13);
7196         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7197                 max_reset_timeout) != 0x14);
7198         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7199                 legacy_intx_status) != 0x18);
7200         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7201                 legacy_intx_mask_set) != 0x1c);
7202         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7203                 legacy_intx_mask_clear) != 0x20);
7204         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7205                 device_status) != 0x40);
7206         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7207                 admin_iq_pi_offset) != 0x48);
7208         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7209                 admin_oq_ci_offset) != 0x50);
7210         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7211                 admin_iq_element_array_addr) != 0x58);
7212         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7213                 admin_oq_element_array_addr) != 0x60);
7214         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7215                 admin_iq_ci_addr) != 0x68);
7216         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7217                 admin_oq_pi_addr) != 0x70);
7218         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7219                 admin_iq_num_elements) != 0x78);
7220         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7221                 admin_oq_num_elements) != 0x79);
7222         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7223                 admin_queue_int_msg_num) != 0x7a);
7224         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7225                 device_error) != 0x80);
7226         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7227                 error_details) != 0x88);
7228         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7229                 device_reset) != 0x90);
7230         BUILD_BUG_ON(offsetof(struct pqi_device_registers,
7231                 power_action) != 0x94);
7232         BUILD_BUG_ON(sizeof(struct pqi_device_registers) != 0x100);
7233
7234         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7235                 header.iu_type) != 0);
7236         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7237                 header.iu_length) != 2);
7238         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7239                 header.work_area) != 6);
7240         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7241                 request_id) != 8);
7242         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7243                 function_code) != 10);
7244         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7245                 data.report_device_capability.buffer_length) != 44);
7246         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7247                 data.report_device_capability.sg_descriptor) != 48);
7248         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7249                 data.create_operational_iq.queue_id) != 12);
7250         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7251                 data.create_operational_iq.element_array_addr) != 16);
7252         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7253                 data.create_operational_iq.ci_addr) != 24);
7254         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7255                 data.create_operational_iq.num_elements) != 32);
7256         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7257                 data.create_operational_iq.element_length) != 34);
7258         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7259                 data.create_operational_iq.queue_protocol) != 36);
7260         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7261                 data.create_operational_oq.queue_id) != 12);
7262         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7263                 data.create_operational_oq.element_array_addr) != 16);
7264         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7265                 data.create_operational_oq.pi_addr) != 24);
7266         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7267                 data.create_operational_oq.num_elements) != 32);
7268         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7269                 data.create_operational_oq.element_length) != 34);
7270         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7271                 data.create_operational_oq.queue_protocol) != 36);
7272         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7273                 data.create_operational_oq.int_msg_num) != 40);
7274         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7275                 data.create_operational_oq.coalescing_count) != 42);
7276         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7277                 data.create_operational_oq.min_coalescing_time) != 44);
7278         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7279                 data.create_operational_oq.max_coalescing_time) != 48);
7280         BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
7281                 data.delete_operational_queue.queue_id) != 12);
7282         BUILD_BUG_ON(sizeof(struct pqi_general_admin_request) != 64);
7283         BUILD_BUG_ON(FIELD_SIZEOF(struct pqi_general_admin_request,
7284                 data.create_operational_iq) != 64 - 11);
7285         BUILD_BUG_ON(FIELD_SIZEOF(struct pqi_general_admin_request,
7286                 data.create_operational_oq) != 64 - 11);
7287         BUILD_BUG_ON(FIELD_SIZEOF(struct pqi_general_admin_request,
7288                 data.delete_operational_queue) != 64 - 11);
7289
7290         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7291                 header.iu_type) != 0);
7292         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7293                 header.iu_length) != 2);
7294         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7295                 header.work_area) != 6);
7296         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7297                 request_id) != 8);
7298         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7299                 function_code) != 10);
7300         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7301                 status) != 11);
7302         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7303                 data.create_operational_iq.status_descriptor) != 12);
7304         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7305                 data.create_operational_iq.iq_pi_offset) != 16);
7306         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7307                 data.create_operational_oq.status_descriptor) != 12);
7308         BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
7309                 data.create_operational_oq.oq_ci_offset) != 16);
7310         BUILD_BUG_ON(sizeof(struct pqi_general_admin_response) != 64);
7311
7312         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7313                 header.iu_type) != 0);
7314         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7315                 header.iu_length) != 2);
7316         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7317                 header.response_queue_id) != 4);
7318         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7319                 header.work_area) != 6);
7320         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7321                 request_id) != 8);
7322         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7323                 nexus_id) != 10);
7324         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7325                 buffer_length) != 12);
7326         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7327                 lun_number) != 16);
7328         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7329                 protocol_specific) != 24);
7330         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7331                 error_index) != 27);
7332         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7333                 cdb) != 32);
7334         BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
7335                 sg_descriptors) != 64);
7336         BUILD_BUG_ON(sizeof(struct pqi_raid_path_request) !=
7337                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
7338
7339         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7340                 header.iu_type) != 0);
7341         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7342                 header.iu_length) != 2);
7343         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7344                 header.response_queue_id) != 4);
7345         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7346                 header.work_area) != 6);
7347         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7348                 request_id) != 8);
7349         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7350                 nexus_id) != 12);
7351         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7352                 buffer_length) != 16);
7353         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7354                 data_encryption_key_index) != 22);
7355         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7356                 encrypt_tweak_lower) != 24);
7357         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7358                 encrypt_tweak_upper) != 28);
7359         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7360                 cdb) != 32);
7361         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7362                 error_index) != 48);
7363         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7364                 num_sg_descriptors) != 50);
7365         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7366                 cdb_length) != 51);
7367         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7368                 lun_number) != 52);
7369         BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
7370                 sg_descriptors) != 64);
7371         BUILD_BUG_ON(sizeof(struct pqi_aio_path_request) !=
7372                 PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
7373
7374         BUILD_BUG_ON(offsetof(struct pqi_io_response,
7375                 header.iu_type) != 0);
7376         BUILD_BUG_ON(offsetof(struct pqi_io_response,
7377                 header.iu_length) != 2);
7378         BUILD_BUG_ON(offsetof(struct pqi_io_response,
7379                 request_id) != 8);
7380         BUILD_BUG_ON(offsetof(struct pqi_io_response,
7381                 error_index) != 10);
7382
7383         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7384                 header.iu_type) != 0);
7385         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7386                 header.iu_length) != 2);
7387         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7388                 header.response_queue_id) != 4);
7389         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7390                 request_id) != 8);
7391         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7392                 data.report_event_configuration.buffer_length) != 12);
7393         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7394                 data.report_event_configuration.sg_descriptors) != 16);
7395         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7396                 data.set_event_configuration.global_event_oq_id) != 10);
7397         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7398                 data.set_event_configuration.buffer_length) != 12);
7399         BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
7400                 data.set_event_configuration.sg_descriptors) != 16);
7401
7402         BUILD_BUG_ON(offsetof(struct pqi_iu_layer_descriptor,
7403                 max_inbound_iu_length) != 6);
7404         BUILD_BUG_ON(offsetof(struct pqi_iu_layer_descriptor,
7405                 max_outbound_iu_length) != 14);
7406         BUILD_BUG_ON(sizeof(struct pqi_iu_layer_descriptor) != 16);
7407
7408         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7409                 data_length) != 0);
7410         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7411                 iq_arbitration_priority_support_bitmask) != 8);
7412         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7413                 maximum_aw_a) != 9);
7414         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7415                 maximum_aw_b) != 10);
7416         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7417                 maximum_aw_c) != 11);
7418         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7419                 max_inbound_queues) != 16);
7420         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7421                 max_elements_per_iq) != 18);
7422         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7423                 max_iq_element_length) != 24);
7424         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7425                 min_iq_element_length) != 26);
7426         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7427                 max_outbound_queues) != 30);
7428         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7429                 max_elements_per_oq) != 32);
7430         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7431                 intr_coalescing_time_granularity) != 34);
7432         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7433                 max_oq_element_length) != 36);
7434         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7435                 min_oq_element_length) != 38);
7436         BUILD_BUG_ON(offsetof(struct pqi_device_capability,
7437                 iu_layer_descriptors) != 64);
7438         BUILD_BUG_ON(sizeof(struct pqi_device_capability) != 576);
7439
7440         BUILD_BUG_ON(offsetof(struct pqi_event_descriptor,
7441                 event_type) != 0);
7442         BUILD_BUG_ON(offsetof(struct pqi_event_descriptor,
7443                 oq_id) != 2);
7444         BUILD_BUG_ON(sizeof(struct pqi_event_descriptor) != 4);
7445
7446         BUILD_BUG_ON(offsetof(struct pqi_event_config,
7447                 num_event_descriptors) != 2);
7448         BUILD_BUG_ON(offsetof(struct pqi_event_config,
7449                 descriptors) != 4);
7450
7451         BUILD_BUG_ON(PQI_NUM_SUPPORTED_EVENTS !=
7452                 ARRAY_SIZE(pqi_supported_event_types));
7453
7454         BUILD_BUG_ON(offsetof(struct pqi_event_response,
7455                 header.iu_type) != 0);
7456         BUILD_BUG_ON(offsetof(struct pqi_event_response,
7457                 header.iu_length) != 2);
7458         BUILD_BUG_ON(offsetof(struct pqi_event_response,
7459                 event_type) != 8);
7460         BUILD_BUG_ON(offsetof(struct pqi_event_response,
7461                 event_id) != 10);
7462         BUILD_BUG_ON(offsetof(struct pqi_event_response,
7463                 additional_event_id) != 12);
7464         BUILD_BUG_ON(offsetof(struct pqi_event_response,
7465                 data) != 16);
7466         BUILD_BUG_ON(sizeof(struct pqi_event_response) != 32);
7467
7468         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
7469                 header.iu_type) != 0);
7470         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
7471                 header.iu_length) != 2);
7472         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
7473                 event_type) != 8);
7474         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
7475                 event_id) != 10);
7476         BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
7477                 additional_event_id) != 12);
7478         BUILD_BUG_ON(sizeof(struct pqi_event_acknowledge_request) != 16);
7479
7480         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7481                 header.iu_type) != 0);
7482         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7483                 header.iu_length) != 2);
7484         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7485                 request_id) != 8);
7486         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7487                 nexus_id) != 10);
7488         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7489                 lun_number) != 16);
7490         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7491                 protocol_specific) != 24);
7492         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7493                 outbound_queue_id_to_manage) != 26);
7494         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7495                 request_id_to_manage) != 28);
7496         BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
7497                 task_management_function) != 30);
7498         BUILD_BUG_ON(sizeof(struct pqi_task_management_request) != 32);
7499
7500         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
7501                 header.iu_type) != 0);
7502         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
7503                 header.iu_length) != 2);
7504         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
7505                 request_id) != 8);
7506         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
7507                 nexus_id) != 10);
7508         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
7509                 additional_response_info) != 12);
7510         BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
7511                 response_code) != 15);
7512         BUILD_BUG_ON(sizeof(struct pqi_task_management_response) != 16);
7513
7514         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
7515                 configured_logical_drive_count) != 0);
7516         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
7517                 configuration_signature) != 1);
7518         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
7519                 firmware_version) != 5);
7520         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
7521                 extended_logical_unit_count) != 154);
7522         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
7523                 firmware_build_number) != 190);
7524         BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
7525                 controller_mode) != 292);
7526
7527         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
7528                 phys_bay_in_box) != 115);
7529         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
7530                 device_type) != 120);
7531         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
7532                 redundant_path_present_map) != 1736);
7533         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
7534                 active_path_number) != 1738);
7535         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
7536                 alternate_paths_phys_connector) != 1739);
7537         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
7538                 alternate_paths_phys_box_on_port) != 1755);
7539         BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
7540                 current_queue_depth_limit) != 1796);
7541         BUILD_BUG_ON(sizeof(struct bmic_identify_physical_device) != 2560);
7542
7543         BUILD_BUG_ON(PQI_ADMIN_IQ_NUM_ELEMENTS > 255);
7544         BUILD_BUG_ON(PQI_ADMIN_OQ_NUM_ELEMENTS > 255);
7545         BUILD_BUG_ON(PQI_ADMIN_IQ_ELEMENT_LENGTH %
7546                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
7547         BUILD_BUG_ON(PQI_ADMIN_OQ_ELEMENT_LENGTH %
7548                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
7549         BUILD_BUG_ON(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH > 1048560);
7550         BUILD_BUG_ON(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH %
7551                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
7552         BUILD_BUG_ON(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH > 1048560);
7553         BUILD_BUG_ON(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH %
7554                 PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
7555
7556         BUILD_BUG_ON(PQI_RESERVED_IO_SLOTS >= PQI_MAX_OUTSTANDING_REQUESTS);
7557         BUILD_BUG_ON(PQI_RESERVED_IO_SLOTS >=
7558                 PQI_MAX_OUTSTANDING_REQUESTS_KDUMP);
7559 }