xref: /openbmc/qemu/hw/scsi/megasas.c (revision e3ae2bbf)
1 /*
2  * QEMU MegaRAID SAS 8708EM2 Host Bus Adapter emulation
3  * Based on the linux driver code at drivers/scsi/megaraid
4  *
5  * Copyright (c) 2009-2012 Hannes Reinecke, SUSE Labs
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #include "qemu/osdep.h"
22 #include "qemu-common.h"
23 #include "hw/pci/pci.h"
24 #include "hw/qdev-properties.h"
25 #include "sysemu/dma.h"
26 #include "sysemu/block-backend.h"
27 #include "hw/pci/msi.h"
28 #include "hw/pci/msix.h"
29 #include "qemu/iov.h"
30 #include "qemu/module.h"
31 #include "hw/scsi/scsi.h"
32 #include "scsi/constants.h"
33 #include "trace.h"
34 #include "qapi/error.h"
35 #include "mfi.h"
36 #include "migration/vmstate.h"
37 #include "qom/object.h"
38 
39 #define MEGASAS_VERSION_GEN1 "1.70"
40 #define MEGASAS_VERSION_GEN2 "1.80"
41 #define MEGASAS_MAX_FRAMES 2048         /* Firmware limit at 65535 */
42 #define MEGASAS_DEFAULT_FRAMES 1000     /* Windows requires this */
43 #define MEGASAS_GEN2_DEFAULT_FRAMES 1008     /* Windows requires this */
44 #define MEGASAS_MAX_SGE 128             /* Firmware limit */
45 #define MEGASAS_DEFAULT_SGE 80
46 #define MEGASAS_MAX_SECTORS 0xFFFF      /* No real limit */
47 #define MEGASAS_MAX_ARRAYS 128
48 
49 #define MEGASAS_HBA_SERIAL "QEMU123456"
50 #define NAA_LOCALLY_ASSIGNED_ID 0x3ULL
51 #define IEEE_COMPANY_LOCALLY_ASSIGNED 0x525400
52 
53 #define MEGASAS_FLAG_USE_JBOD      0
54 #define MEGASAS_MASK_USE_JBOD      (1 << MEGASAS_FLAG_USE_JBOD)
55 #define MEGASAS_FLAG_USE_QUEUE64   1
56 #define MEGASAS_MASK_USE_QUEUE64   (1 << MEGASAS_FLAG_USE_QUEUE64)
57 
58 typedef struct MegasasCmd {
59     uint32_t index;
60     uint16_t flags;
61     uint16_t count;
62     uint64_t context;
63 
64     hwaddr pa;
65     hwaddr pa_size;
66     uint32_t dcmd_opcode;
67     union mfi_frame *frame;
68     SCSIRequest *req;
69     QEMUSGList qsg;
70     void *iov_buf;
71     size_t iov_size;
72     size_t iov_offset;
73     struct MegasasState *state;
74 } MegasasCmd;
75 
76 struct MegasasState {
77     /*< private >*/
78     PCIDevice parent_obj;
79     /*< public >*/
80 
81     MemoryRegion mmio_io;
82     MemoryRegion port_io;
83     MemoryRegion queue_io;
84     uint32_t frame_hi;
85 
86     uint32_t fw_state;
87     uint32_t fw_sge;
88     uint32_t fw_cmds;
89     uint32_t flags;
90     uint32_t fw_luns;
91     uint32_t intr_mask;
92     uint32_t doorbell;
93     uint32_t busy;
94     uint32_t diag;
95     uint32_t adp_reset;
96     OnOffAuto msi;
97     OnOffAuto msix;
98 
99     MegasasCmd *event_cmd;
100     uint16_t event_locale;
101     int event_class;
102     uint32_t event_count;
103     uint32_t shutdown_event;
104     uint32_t boot_event;
105 
106     uint64_t sas_addr;
107     char *hba_serial;
108 
109     uint64_t reply_queue_pa;
110     void *reply_queue;
111     uint16_t reply_queue_len;
112     uint32_t reply_queue_head;
113     uint32_t reply_queue_tail;
114     uint64_t consumer_pa;
115     uint64_t producer_pa;
116 
117     MegasasCmd frames[MEGASAS_MAX_FRAMES];
118     DECLARE_BITMAP(frame_map, MEGASAS_MAX_FRAMES);
119     SCSIBus bus;
120 };
121 typedef struct MegasasState MegasasState;
122 
123 struct MegasasBaseClass {
124     PCIDeviceClass parent_class;
125     const char *product_name;
126     const char *product_version;
127     int mmio_bar;
128     int ioport_bar;
129     int osts;
130 };
131 typedef struct MegasasBaseClass MegasasBaseClass;
132 
133 #define TYPE_MEGASAS_BASE "megasas-base"
134 #define TYPE_MEGASAS_GEN1 "megasas"
135 #define TYPE_MEGASAS_GEN2 "megasas-gen2"
136 
137 DECLARE_OBJ_CHECKERS(MegasasState, MegasasBaseClass,
138                      MEGASAS, TYPE_MEGASAS_BASE)
139 
140 
141 #define MEGASAS_INTR_DISABLED_MASK 0xFFFFFFFF
142 
143 static bool megasas_intr_enabled(MegasasState *s)
144 {
145     if ((s->intr_mask & MEGASAS_INTR_DISABLED_MASK) !=
146         MEGASAS_INTR_DISABLED_MASK) {
147         return true;
148     }
149     return false;
150 }
151 
152 static bool megasas_use_queue64(MegasasState *s)
153 {
154     return s->flags & MEGASAS_MASK_USE_QUEUE64;
155 }
156 
157 static bool megasas_use_msix(MegasasState *s)
158 {
159     return s->msix != ON_OFF_AUTO_OFF;
160 }
161 
162 static bool megasas_is_jbod(MegasasState *s)
163 {
164     return s->flags & MEGASAS_MASK_USE_JBOD;
165 }
166 
167 static void megasas_frame_set_cmd_status(MegasasState *s,
168                                          unsigned long frame, uint8_t v)
169 {
170     PCIDevice *pci = &s->parent_obj;
171     stb_pci_dma(pci, frame + offsetof(struct mfi_frame_header, cmd_status),
172                 v, MEMTXATTRS_UNSPECIFIED);
173 }
174 
175 static void megasas_frame_set_scsi_status(MegasasState *s,
176                                           unsigned long frame, uint8_t v)
177 {
178     PCIDevice *pci = &s->parent_obj;
179     stb_pci_dma(pci, frame + offsetof(struct mfi_frame_header, scsi_status),
180                 v, MEMTXATTRS_UNSPECIFIED);
181 }
182 
183 static inline const char *mfi_frame_desc(unsigned int cmd)
184 {
185     static const char *mfi_frame_descs[] = {
186         "MFI init", "LD Read", "LD Write", "LD SCSI", "PD SCSI",
187         "MFI Doorbell", "MFI Abort", "MFI SMP", "MFI Stop"
188     };
189 
190     if (cmd < ARRAY_SIZE(mfi_frame_descs)) {
191         return mfi_frame_descs[cmd];
192     }
193 
194     return "Unknown";
195 }
196 
197 /*
198  * Context is considered opaque, but the HBA firmware is running
199  * in little endian mode. So convert it to little endian, too.
200  */
201 static uint64_t megasas_frame_get_context(MegasasState *s,
202                                           unsigned long frame)
203 {
204     PCIDevice *pci = &s->parent_obj;
205     uint64_t val;
206 
207     ldq_le_pci_dma(pci, frame + offsetof(struct mfi_frame_header, context),
208                    &val, MEMTXATTRS_UNSPECIFIED);
209 
210     return val;
211 }
212 
213 static bool megasas_frame_is_ieee_sgl(MegasasCmd *cmd)
214 {
215     return cmd->flags & MFI_FRAME_IEEE_SGL;
216 }
217 
218 static bool megasas_frame_is_sgl64(MegasasCmd *cmd)
219 {
220     return cmd->flags & MFI_FRAME_SGL64;
221 }
222 
223 static bool megasas_frame_is_sense64(MegasasCmd *cmd)
224 {
225     return cmd->flags & MFI_FRAME_SENSE64;
226 }
227 
228 static uint64_t megasas_sgl_get_addr(MegasasCmd *cmd,
229                                      union mfi_sgl *sgl)
230 {
231     uint64_t addr;
232 
233     if (megasas_frame_is_ieee_sgl(cmd)) {
234         addr = le64_to_cpu(sgl->sg_skinny->addr);
235     } else if (megasas_frame_is_sgl64(cmd)) {
236         addr = le64_to_cpu(sgl->sg64->addr);
237     } else {
238         addr = le32_to_cpu(sgl->sg32->addr);
239     }
240     return addr;
241 }
242 
243 static uint32_t megasas_sgl_get_len(MegasasCmd *cmd,
244                                     union mfi_sgl *sgl)
245 {
246     uint32_t len;
247 
248     if (megasas_frame_is_ieee_sgl(cmd)) {
249         len = le32_to_cpu(sgl->sg_skinny->len);
250     } else if (megasas_frame_is_sgl64(cmd)) {
251         len = le32_to_cpu(sgl->sg64->len);
252     } else {
253         len = le32_to_cpu(sgl->sg32->len);
254     }
255     return len;
256 }
257 
258 static union mfi_sgl *megasas_sgl_next(MegasasCmd *cmd,
259                                        union mfi_sgl *sgl)
260 {
261     uint8_t *next = (uint8_t *)sgl;
262 
263     if (megasas_frame_is_ieee_sgl(cmd)) {
264         next += sizeof(struct mfi_sg_skinny);
265     } else if (megasas_frame_is_sgl64(cmd)) {
266         next += sizeof(struct mfi_sg64);
267     } else {
268         next += sizeof(struct mfi_sg32);
269     }
270 
271     if (next >= (uint8_t *)cmd->frame + cmd->pa_size) {
272         return NULL;
273     }
274     return (union mfi_sgl *)next;
275 }
276 
277 static void megasas_soft_reset(MegasasState *s);
278 
279 static int megasas_map_sgl(MegasasState *s, MegasasCmd *cmd, union mfi_sgl *sgl)
280 {
281     int i;
282     int iov_count = 0;
283     size_t iov_size = 0;
284 
285     cmd->flags = le16_to_cpu(cmd->frame->header.flags);
286     iov_count = cmd->frame->header.sge_count;
287     if (!iov_count || iov_count > MEGASAS_MAX_SGE) {
288         trace_megasas_iovec_sgl_overflow(cmd->index, iov_count,
289                                          MEGASAS_MAX_SGE);
290         return -1;
291     }
292     pci_dma_sglist_init(&cmd->qsg, PCI_DEVICE(s), iov_count);
293     for (i = 0; i < iov_count; i++) {
294         dma_addr_t iov_pa, iov_size_p;
295 
296         if (!sgl) {
297             trace_megasas_iovec_sgl_underflow(cmd->index, i);
298             goto unmap;
299         }
300         iov_pa = megasas_sgl_get_addr(cmd, sgl);
301         iov_size_p = megasas_sgl_get_len(cmd, sgl);
302         if (!iov_pa || !iov_size_p) {
303             trace_megasas_iovec_sgl_invalid(cmd->index, i,
304                                             iov_pa, iov_size_p);
305             goto unmap;
306         }
307         qemu_sglist_add(&cmd->qsg, iov_pa, iov_size_p);
308         sgl = megasas_sgl_next(cmd, sgl);
309         iov_size += (size_t)iov_size_p;
310     }
311     if (cmd->iov_size > iov_size) {
312         trace_megasas_iovec_overflow(cmd->index, iov_size, cmd->iov_size);
313         goto unmap;
314     } else if (cmd->iov_size < iov_size) {
315         trace_megasas_iovec_underflow(cmd->index, iov_size, cmd->iov_size);
316     }
317     cmd->iov_offset = 0;
318     return 0;
319 unmap:
320     qemu_sglist_destroy(&cmd->qsg);
321     return -1;
322 }
323 
324 /*
325  * passthrough sense and io sense are at the same offset
326  */
327 static int megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr,
328     uint8_t sense_len)
329 {
330     PCIDevice *pcid = PCI_DEVICE(cmd->state);
331     uint32_t pa_hi = 0, pa_lo;
332     hwaddr pa;
333     int frame_sense_len;
334 
335     frame_sense_len = cmd->frame->header.sense_len;
336     if (sense_len > frame_sense_len) {
337         sense_len = frame_sense_len;
338     }
339     if (sense_len) {
340         pa_lo = le32_to_cpu(cmd->frame->pass.sense_addr_lo);
341         if (megasas_frame_is_sense64(cmd)) {
342             pa_hi = le32_to_cpu(cmd->frame->pass.sense_addr_hi);
343         }
344         pa = ((uint64_t) pa_hi << 32) | pa_lo;
345         pci_dma_write(pcid, pa, sense_ptr, sense_len);
346         cmd->frame->header.sense_len = sense_len;
347     }
348     return sense_len;
349 }
350 
351 static void megasas_write_sense(MegasasCmd *cmd, SCSISense sense)
352 {
353     uint8_t sense_buf[SCSI_SENSE_BUF_SIZE];
354     uint8_t sense_len = 18;
355 
356     memset(sense_buf, 0, sense_len);
357     sense_buf[0] = 0xf0;
358     sense_buf[2] = sense.key;
359     sense_buf[7] = 10;
360     sense_buf[12] = sense.asc;
361     sense_buf[13] = sense.ascq;
362     megasas_build_sense(cmd, sense_buf, sense_len);
363 }
364 
365 static void megasas_copy_sense(MegasasCmd *cmd)
366 {
367     uint8_t sense_buf[SCSI_SENSE_BUF_SIZE];
368     uint8_t sense_len;
369 
370     sense_len = scsi_req_get_sense(cmd->req, sense_buf,
371                                    SCSI_SENSE_BUF_SIZE);
372     megasas_build_sense(cmd, sense_buf, sense_len);
373 }
374 
375 /*
376  * Format an INQUIRY CDB
377  */
378 static int megasas_setup_inquiry(uint8_t *cdb, int pg, int len)
379 {
380     memset(cdb, 0, 6);
381     cdb[0] = INQUIRY;
382     if (pg > 0) {
383         cdb[1] = 0x1;
384         cdb[2] = pg;
385     }
386     cdb[3] = (len >> 8) & 0xff;
387     cdb[4] = (len & 0xff);
388     return len;
389 }
390 
391 /*
392  * Encode lba and len into a READ_16/WRITE_16 CDB
393  */
394 static void megasas_encode_lba(uint8_t *cdb, uint64_t lba,
395                                uint32_t len, bool is_write)
396 {
397     memset(cdb, 0x0, 16);
398     if (is_write) {
399         cdb[0] = WRITE_16;
400     } else {
401         cdb[0] = READ_16;
402     }
403     cdb[2] = (lba >> 56) & 0xff;
404     cdb[3] = (lba >> 48) & 0xff;
405     cdb[4] = (lba >> 40) & 0xff;
406     cdb[5] = (lba >> 32) & 0xff;
407     cdb[6] = (lba >> 24) & 0xff;
408     cdb[7] = (lba >> 16) & 0xff;
409     cdb[8] = (lba >> 8) & 0xff;
410     cdb[9] = (lba) & 0xff;
411     cdb[10] = (len >> 24) & 0xff;
412     cdb[11] = (len >> 16) & 0xff;
413     cdb[12] = (len >> 8) & 0xff;
414     cdb[13] = (len) & 0xff;
415 }
416 
417 /*
418  * Utility functions
419  */
420 static uint64_t megasas_fw_time(void)
421 {
422     struct tm curtime;
423 
424     qemu_get_timedate(&curtime, 0);
425     return ((uint64_t)curtime.tm_sec & 0xff) << 48 |
426         ((uint64_t)curtime.tm_min & 0xff)  << 40 |
427         ((uint64_t)curtime.tm_hour & 0xff) << 32 |
428         ((uint64_t)curtime.tm_mday & 0xff) << 24 |
429         ((uint64_t)curtime.tm_mon & 0xff)  << 16 |
430         ((uint64_t)(curtime.tm_year + 1900) & 0xffff);
431 }
432 
433 /*
434  * Default disk sata address
435  * 0x1221 is the magic number as
436  * present in real hardware,
437  * so use it here, too.
438  */
439 static uint64_t megasas_get_sata_addr(uint16_t id)
440 {
441     uint64_t addr = (0x1221ULL << 48);
442     return addr | ((uint64_t)id << 24);
443 }
444 
445 /*
446  * Frame handling
447  */
448 static int megasas_next_index(MegasasState *s, int index, int limit)
449 {
450     index++;
451     if (index == limit) {
452         index = 0;
453     }
454     return index;
455 }
456 
457 static MegasasCmd *megasas_lookup_frame(MegasasState *s,
458     hwaddr frame)
459 {
460     MegasasCmd *cmd = NULL;
461     int num = 0, index;
462 
463     index = s->reply_queue_head;
464 
465     while (num < s->fw_cmds && index < MEGASAS_MAX_FRAMES) {
466         if (s->frames[index].pa && s->frames[index].pa == frame) {
467             cmd = &s->frames[index];
468             break;
469         }
470         index = megasas_next_index(s, index, s->fw_cmds);
471         num++;
472     }
473 
474     return cmd;
475 }
476 
477 static void megasas_unmap_frame(MegasasState *s, MegasasCmd *cmd)
478 {
479     PCIDevice *p = PCI_DEVICE(s);
480 
481     if (cmd->pa_size) {
482         pci_dma_unmap(p, cmd->frame, cmd->pa_size, 0, 0);
483     }
484     cmd->frame = NULL;
485     cmd->pa = 0;
486     cmd->pa_size = 0;
487     qemu_sglist_destroy(&cmd->qsg);
488     clear_bit(cmd->index, s->frame_map);
489 }
490 
491 /*
492  * This absolutely needs to be locked if
493  * qemu ever goes multithreaded.
494  */
495 static MegasasCmd *megasas_enqueue_frame(MegasasState *s,
496     hwaddr frame, uint64_t context, int count)
497 {
498     PCIDevice *pcid = PCI_DEVICE(s);
499     MegasasCmd *cmd = NULL;
500     int frame_size = MEGASAS_MAX_SGE * sizeof(union mfi_sgl);
501     hwaddr frame_size_p = frame_size;
502     unsigned long index;
503 
504     index = 0;
505     while (index < s->fw_cmds) {
506         index = find_next_zero_bit(s->frame_map, s->fw_cmds, index);
507         if (!s->frames[index].pa)
508             break;
509         /* Busy frame found */
510         trace_megasas_qf_mapped(index);
511     }
512     if (index >= s->fw_cmds) {
513         /* All frames busy */
514         trace_megasas_qf_busy(frame);
515         return NULL;
516     }
517     cmd = &s->frames[index];
518     set_bit(index, s->frame_map);
519     trace_megasas_qf_new(index, frame);
520 
521     cmd->pa = frame;
522     /* Map all possible frames */
523     cmd->frame = pci_dma_map(pcid, frame, &frame_size_p, 0);
524     if (!cmd->frame || frame_size_p != frame_size) {
525         trace_megasas_qf_map_failed(cmd->index, (unsigned long)frame);
526         if (cmd->frame) {
527             megasas_unmap_frame(s, cmd);
528         }
529         s->event_count++;
530         return NULL;
531     }
532     cmd->pa_size = frame_size_p;
533     cmd->context = context;
534     if (!megasas_use_queue64(s)) {
535         cmd->context &= (uint64_t)0xFFFFFFFF;
536     }
537     cmd->count = count;
538     cmd->dcmd_opcode = -1;
539     s->busy++;
540 
541     if (s->consumer_pa) {
542         ldl_le_pci_dma(pcid, s->consumer_pa, &s->reply_queue_tail,
543                        MEMTXATTRS_UNSPECIFIED);
544     }
545     trace_megasas_qf_enqueue(cmd->index, cmd->count, cmd->context,
546                              s->reply_queue_head, s->reply_queue_tail, s->busy);
547 
548     return cmd;
549 }
550 
551 static void megasas_complete_frame(MegasasState *s, uint64_t context)
552 {
553     const MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
554     PCIDevice *pci_dev = PCI_DEVICE(s);
555     int tail, queue_offset;
556 
557     /* Decrement busy count */
558     s->busy--;
559     if (s->reply_queue_pa) {
560         /*
561          * Put command on the reply queue.
562          * Context is opaque, but emulation is running in
563          * little endian. So convert it.
564          */
565         if (megasas_use_queue64(s)) {
566             queue_offset = s->reply_queue_head * sizeof(uint64_t);
567             stq_le_pci_dma(pci_dev, s->reply_queue_pa + queue_offset,
568                            context, attrs);
569         } else {
570             queue_offset = s->reply_queue_head * sizeof(uint32_t);
571             stl_le_pci_dma(pci_dev, s->reply_queue_pa + queue_offset,
572                            context, attrs);
573         }
574         ldl_le_pci_dma(pci_dev, s->consumer_pa, &s->reply_queue_tail, attrs);
575         trace_megasas_qf_complete(context, s->reply_queue_head,
576                                   s->reply_queue_tail, s->busy);
577     }
578 
579     if (megasas_intr_enabled(s)) {
580         /* Update reply queue pointer */
581         ldl_le_pci_dma(pci_dev, s->consumer_pa, &s->reply_queue_tail, attrs);
582         tail = s->reply_queue_head;
583         s->reply_queue_head = megasas_next_index(s, tail, s->fw_cmds);
584         trace_megasas_qf_update(s->reply_queue_head, s->reply_queue_tail,
585                                 s->busy);
586         stl_le_pci_dma(pci_dev, s->producer_pa, s->reply_queue_head, attrs);
587         /* Notify HBA */
588         if (msix_enabled(pci_dev)) {
589             trace_megasas_msix_raise(0);
590             msix_notify(pci_dev, 0);
591         } else if (msi_enabled(pci_dev)) {
592             trace_megasas_msi_raise(0);
593             msi_notify(pci_dev, 0);
594         } else {
595             s->doorbell++;
596             if (s->doorbell == 1) {
597                 trace_megasas_irq_raise();
598                 pci_irq_assert(pci_dev);
599             }
600         }
601     } else {
602         trace_megasas_qf_complete_noirq(context);
603     }
604 }
605 
606 static void megasas_complete_command(MegasasCmd *cmd)
607 {
608     cmd->iov_size = 0;
609     cmd->iov_offset = 0;
610 
611     cmd->req->hba_private = NULL;
612     scsi_req_unref(cmd->req);
613     cmd->req = NULL;
614 
615     megasas_unmap_frame(cmd->state, cmd);
616     megasas_complete_frame(cmd->state, cmd->context);
617 }
618 
619 static void megasas_reset_frames(MegasasState *s)
620 {
621     int i;
622     MegasasCmd *cmd;
623 
624     for (i = 0; i < s->fw_cmds; i++) {
625         cmd = &s->frames[i];
626         if (cmd->pa) {
627             megasas_unmap_frame(s, cmd);
628         }
629     }
630     bitmap_zero(s->frame_map, MEGASAS_MAX_FRAMES);
631 }
632 
633 static void megasas_abort_command(MegasasCmd *cmd)
634 {
635     /* Never abort internal commands.  */
636     if (cmd->dcmd_opcode != -1) {
637         return;
638     }
639     if (cmd->req != NULL) {
640         scsi_req_cancel(cmd->req);
641     }
642 }
643 
644 static int megasas_init_firmware(MegasasState *s, MegasasCmd *cmd)
645 {
646     const MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
647     PCIDevice *pcid = PCI_DEVICE(s);
648     uint32_t pa_hi, pa_lo;
649     hwaddr iq_pa, initq_size = sizeof(struct mfi_init_qinfo);
650     struct mfi_init_qinfo *initq = NULL;
651     uint32_t flags;
652     int ret = MFI_STAT_OK;
653 
654     if (s->reply_queue_pa) {
655         trace_megasas_initq_mapped(s->reply_queue_pa);
656         goto out;
657     }
658     pa_lo = le32_to_cpu(cmd->frame->init.qinfo_new_addr_lo);
659     pa_hi = le32_to_cpu(cmd->frame->init.qinfo_new_addr_hi);
660     iq_pa = (((uint64_t) pa_hi << 32) | pa_lo);
661     trace_megasas_init_firmware((uint64_t)iq_pa);
662     initq = pci_dma_map(pcid, iq_pa, &initq_size, 0);
663     if (!initq || initq_size != sizeof(*initq)) {
664         trace_megasas_initq_map_failed(cmd->index);
665         s->event_count++;
666         ret = MFI_STAT_MEMORY_NOT_AVAILABLE;
667         goto out;
668     }
669     s->reply_queue_len = le32_to_cpu(initq->rq_entries) & 0xFFFF;
670     if (s->reply_queue_len > s->fw_cmds) {
671         trace_megasas_initq_mismatch(s->reply_queue_len, s->fw_cmds);
672         s->event_count++;
673         ret = MFI_STAT_INVALID_PARAMETER;
674         goto out;
675     }
676     pa_lo = le32_to_cpu(initq->rq_addr_lo);
677     pa_hi = le32_to_cpu(initq->rq_addr_hi);
678     s->reply_queue_pa = ((uint64_t) pa_hi << 32) | pa_lo;
679     pa_lo = le32_to_cpu(initq->ci_addr_lo);
680     pa_hi = le32_to_cpu(initq->ci_addr_hi);
681     s->consumer_pa = ((uint64_t) pa_hi << 32) | pa_lo;
682     pa_lo = le32_to_cpu(initq->pi_addr_lo);
683     pa_hi = le32_to_cpu(initq->pi_addr_hi);
684     s->producer_pa = ((uint64_t) pa_hi << 32) | pa_lo;
685     ldl_le_pci_dma(pcid, s->producer_pa, &s->reply_queue_head, attrs);
686     s->reply_queue_head %= MEGASAS_MAX_FRAMES;
687     ldl_le_pci_dma(pcid, s->consumer_pa, &s->reply_queue_tail, attrs);
688     s->reply_queue_tail %= MEGASAS_MAX_FRAMES;
689     flags = le32_to_cpu(initq->flags);
690     if (flags & MFI_QUEUE_FLAG_CONTEXT64) {
691         s->flags |= MEGASAS_MASK_USE_QUEUE64;
692     }
693     trace_megasas_init_queue((unsigned long)s->reply_queue_pa,
694                              s->reply_queue_len, s->reply_queue_head,
695                              s->reply_queue_tail, flags);
696     megasas_reset_frames(s);
697     s->fw_state = MFI_FWSTATE_OPERATIONAL;
698 out:
699     if (initq) {
700         pci_dma_unmap(pcid, initq, initq_size, 0, 0);
701     }
702     return ret;
703 }
704 
705 static int megasas_map_dcmd(MegasasState *s, MegasasCmd *cmd)
706 {
707     dma_addr_t iov_pa, iov_size;
708     int iov_count;
709 
710     cmd->flags = le16_to_cpu(cmd->frame->header.flags);
711     iov_count = cmd->frame->header.sge_count;
712     if (!iov_count) {
713         trace_megasas_dcmd_zero_sge(cmd->index);
714         cmd->iov_size = 0;
715         return 0;
716     } else if (iov_count > 1) {
717         trace_megasas_dcmd_invalid_sge(cmd->index, iov_count);
718         cmd->iov_size = 0;
719         return -EINVAL;
720     }
721     iov_pa = megasas_sgl_get_addr(cmd, &cmd->frame->dcmd.sgl);
722     iov_size = megasas_sgl_get_len(cmd, &cmd->frame->dcmd.sgl);
723     pci_dma_sglist_init(&cmd->qsg, PCI_DEVICE(s), 1);
724     qemu_sglist_add(&cmd->qsg, iov_pa, iov_size);
725     cmd->iov_size = iov_size;
726     return 0;
727 }
728 
729 static void megasas_finish_dcmd(MegasasCmd *cmd, uint32_t iov_size)
730 {
731     trace_megasas_finish_dcmd(cmd->index, iov_size);
732 
733     if (iov_size > cmd->iov_size) {
734         if (megasas_frame_is_ieee_sgl(cmd)) {
735             cmd->frame->dcmd.sgl.sg_skinny->len = cpu_to_le32(iov_size);
736         } else if (megasas_frame_is_sgl64(cmd)) {
737             cmd->frame->dcmd.sgl.sg64->len = cpu_to_le32(iov_size);
738         } else {
739             cmd->frame->dcmd.sgl.sg32->len = cpu_to_le32(iov_size);
740         }
741     }
742 }
743 
744 static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd)
745 {
746     PCIDevice *pci_dev = PCI_DEVICE(s);
747     PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev);
748     MegasasBaseClass *base_class = MEGASAS_GET_CLASS(s);
749     struct mfi_ctrl_info info;
750     size_t dcmd_size = sizeof(info);
751     BusChild *kid;
752     int num_pd_disks = 0;
753 
754     memset(&info, 0x0, dcmd_size);
755     if (cmd->iov_size < dcmd_size) {
756         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
757                                             dcmd_size);
758         return MFI_STAT_INVALID_PARAMETER;
759     }
760 
761     info.pci.vendor = cpu_to_le16(pci_class->vendor_id);
762     info.pci.device = cpu_to_le16(pci_class->device_id);
763     info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id);
764     info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id);
765 
766     /*
767      * For some reason the firmware supports
768      * only up to 8 device ports.
769      * Despite supporting a far larger number
770      * of devices for the physical devices.
771      * So just display the first 8 devices
772      * in the device port list, independent
773      * of how many logical devices are actually
774      * present.
775      */
776     info.host.type = MFI_INFO_HOST_PCIE;
777     info.device.type = MFI_INFO_DEV_SAS3G;
778     info.device.port_count = 8;
779     QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
780         SCSIDevice *sdev = SCSI_DEVICE(kid->child);
781         uint16_t pd_id;
782 
783         if (num_pd_disks < 8) {
784             pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF);
785             info.device.port_addr[num_pd_disks] =
786                 cpu_to_le64(megasas_get_sata_addr(pd_id));
787         }
788         num_pd_disks++;
789     }
790 
791     memcpy(info.product_name, base_class->product_name, 24);
792     snprintf(info.serial_number, 32, "%s", s->hba_serial);
793     snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version());
794     memcpy(info.image_component[0].name, "APP", 3);
795     snprintf(info.image_component[0].version, 10, "%s-QEMU",
796              base_class->product_version);
797     memcpy(info.image_component[0].build_date, "Apr  1 2014", 11);
798     memcpy(info.image_component[0].build_time, "12:34:56", 8);
799     info.image_component_count = 1;
800     if (pci_dev->has_rom) {
801         uint8_t biosver[32];
802         uint8_t *ptr;
803 
804         ptr = memory_region_get_ram_ptr(&pci_dev->rom);
805         memcpy(biosver, ptr + 0x41, 31);
806         biosver[31] = 0;
807         memcpy(info.image_component[1].name, "BIOS", 4);
808         memcpy(info.image_component[1].version, biosver,
809                strlen((const char *)biosver));
810         info.image_component_count++;
811     }
812     info.current_fw_time = cpu_to_le32(megasas_fw_time());
813     info.max_arms = 32;
814     info.max_spans = 8;
815     info.max_arrays = MEGASAS_MAX_ARRAYS;
816     info.max_lds = MFI_MAX_LD;
817     info.max_cmds = cpu_to_le16(s->fw_cmds);
818     info.max_sg_elements = cpu_to_le16(s->fw_sge);
819     info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS);
820     if (!megasas_is_jbod(s))
821         info.lds_present = cpu_to_le16(num_pd_disks);
822     info.pd_present = cpu_to_le16(num_pd_disks);
823     info.pd_disks_present = cpu_to_le16(num_pd_disks);
824     info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM |
825                                    MFI_INFO_HW_MEM |
826                                    MFI_INFO_HW_FLASH);
827     info.memory_size = cpu_to_le16(512);
828     info.nvram_size = cpu_to_le16(32);
829     info.flash_size = cpu_to_le16(16);
830     info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0);
831     info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE |
832                                     MFI_INFO_AOPS_SELF_DIAGNOSTIC |
833                                     MFI_INFO_AOPS_MIXED_ARRAY);
834     info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY |
835                                MFI_INFO_LDOPS_ACCESS_POLICY |
836                                MFI_INFO_LDOPS_IO_POLICY |
837                                MFI_INFO_LDOPS_WRITE_POLICY |
838                                MFI_INFO_LDOPS_READ_POLICY);
839     info.max_strips_per_io = cpu_to_le16(s->fw_sge);
840     info.stripe_sz_ops.min = 3;
841     info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1);
842     info.properties.pred_fail_poll_interval = cpu_to_le16(300);
843     info.properties.intr_throttle_cnt = cpu_to_le16(16);
844     info.properties.intr_throttle_timeout = cpu_to_le16(50);
845     info.properties.rebuild_rate = 30;
846     info.properties.patrol_read_rate = 30;
847     info.properties.bgi_rate = 30;
848     info.properties.cc_rate = 30;
849     info.properties.recon_rate = 30;
850     info.properties.cache_flush_interval = 4;
851     info.properties.spinup_drv_cnt = 2;
852     info.properties.spinup_delay = 6;
853     info.properties.ecc_bucket_size = 15;
854     info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440);
855     info.properties.expose_encl_devices = 1;
856     info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD);
857     info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE |
858                                MFI_INFO_PDOPS_FORCE_OFFLINE);
859     info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS |
860                                        MFI_INFO_PDMIX_SATA |
861                                        MFI_INFO_PDMIX_LD);
862 
863     cmd->iov_size -= dma_buf_read(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
864     return MFI_STAT_OK;
865 }
866 
867 static int megasas_mfc_get_defaults(MegasasState *s, MegasasCmd *cmd)
868 {
869     struct mfi_defaults info;
870     size_t dcmd_size = sizeof(struct mfi_defaults);
871 
872     memset(&info, 0x0, dcmd_size);
873     if (cmd->iov_size < dcmd_size) {
874         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
875                                             dcmd_size);
876         return MFI_STAT_INVALID_PARAMETER;
877     }
878 
879     info.sas_addr = cpu_to_le64(s->sas_addr);
880     info.stripe_size = 3;
881     info.flush_time = 4;
882     info.background_rate = 30;
883     info.allow_mix_in_enclosure = 1;
884     info.allow_mix_in_ld = 1;
885     info.direct_pd_mapping = 1;
886     /* Enable for BIOS support */
887     info.bios_enumerate_lds = 1;
888     info.disable_ctrl_r = 1;
889     info.expose_enclosure_devices = 1;
890     info.disable_preboot_cli = 1;
891     info.cluster_disable = 1;
892 
893     cmd->iov_size -= dma_buf_read(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
894     return MFI_STAT_OK;
895 }
896 
897 static int megasas_dcmd_get_bios_info(MegasasState *s, MegasasCmd *cmd)
898 {
899     struct mfi_bios_data info;
900     size_t dcmd_size = sizeof(info);
901 
902     memset(&info, 0x0, dcmd_size);
903     if (cmd->iov_size < dcmd_size) {
904         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
905                                             dcmd_size);
906         return MFI_STAT_INVALID_PARAMETER;
907     }
908     info.continue_on_error = 1;
909     info.verbose = 1;
910     if (megasas_is_jbod(s)) {
911         info.expose_all_drives = 1;
912     }
913 
914     cmd->iov_size -= dma_buf_read(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
915     return MFI_STAT_OK;
916 }
917 
918 static int megasas_dcmd_get_fw_time(MegasasState *s, MegasasCmd *cmd)
919 {
920     uint64_t fw_time;
921     size_t dcmd_size = sizeof(fw_time);
922 
923     fw_time = cpu_to_le64(megasas_fw_time());
924 
925     cmd->iov_size -= dma_buf_read(&fw_time, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
926     return MFI_STAT_OK;
927 }
928 
929 static int megasas_dcmd_set_fw_time(MegasasState *s, MegasasCmd *cmd)
930 {
931     uint64_t fw_time;
932 
933     /* This is a dummy; setting of firmware time is not allowed */
934     memcpy(&fw_time, cmd->frame->dcmd.mbox, sizeof(fw_time));
935 
936     trace_megasas_dcmd_set_fw_time(cmd->index, fw_time);
937     fw_time = cpu_to_le64(megasas_fw_time());
938     return MFI_STAT_OK;
939 }
940 
941 static int megasas_event_info(MegasasState *s, MegasasCmd *cmd)
942 {
943     struct mfi_evt_log_state info;
944     size_t dcmd_size = sizeof(info);
945 
946     memset(&info, 0, dcmd_size);
947 
948     info.newest_seq_num = cpu_to_le32(s->event_count);
949     info.shutdown_seq_num = cpu_to_le32(s->shutdown_event);
950     info.boot_seq_num = cpu_to_le32(s->boot_event);
951 
952     cmd->iov_size -= dma_buf_read(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
953     return MFI_STAT_OK;
954 }
955 
956 static int megasas_event_wait(MegasasState *s, MegasasCmd *cmd)
957 {
958     union mfi_evt event;
959 
960     if (cmd->iov_size < sizeof(struct mfi_evt_detail)) {
961         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
962                                             sizeof(struct mfi_evt_detail));
963         return MFI_STAT_INVALID_PARAMETER;
964     }
965     s->event_count = cpu_to_le32(cmd->frame->dcmd.mbox[0]);
966     event.word = cpu_to_le32(cmd->frame->dcmd.mbox[4]);
967     s->event_locale = event.members.locale;
968     s->event_class = event.members.class;
969     s->event_cmd = cmd;
970     /* Decrease busy count; event frame doesn't count here */
971     s->busy--;
972     cmd->iov_size = sizeof(struct mfi_evt_detail);
973     return MFI_STAT_INVALID_STATUS;
974 }
975 
976 static int megasas_dcmd_pd_get_list(MegasasState *s, MegasasCmd *cmd)
977 {
978     struct mfi_pd_list info;
979     size_t dcmd_size = sizeof(info);
980     BusChild *kid;
981     uint32_t offset, dcmd_limit, num_pd_disks = 0, max_pd_disks;
982 
983     memset(&info, 0, dcmd_size);
984     offset = 8;
985     dcmd_limit = offset + sizeof(struct mfi_pd_address);
986     if (cmd->iov_size < dcmd_limit) {
987         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
988                                             dcmd_limit);
989         return MFI_STAT_INVALID_PARAMETER;
990     }
991 
992     max_pd_disks = (cmd->iov_size - offset) / sizeof(struct mfi_pd_address);
993     if (max_pd_disks > MFI_MAX_SYS_PDS) {
994         max_pd_disks = MFI_MAX_SYS_PDS;
995     }
996     QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
997         SCSIDevice *sdev = SCSI_DEVICE(kid->child);
998         uint16_t pd_id;
999 
1000         if (num_pd_disks >= max_pd_disks)
1001             break;
1002 
1003         pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF);
1004         info.addr[num_pd_disks].device_id = cpu_to_le16(pd_id);
1005         info.addr[num_pd_disks].encl_device_id = 0xFFFF;
1006         info.addr[num_pd_disks].encl_index = 0;
1007         info.addr[num_pd_disks].slot_number = sdev->id & 0xFF;
1008         info.addr[num_pd_disks].scsi_dev_type = sdev->type;
1009         info.addr[num_pd_disks].connect_port_bitmap = 0x1;
1010         info.addr[num_pd_disks].sas_addr[0] =
1011             cpu_to_le64(megasas_get_sata_addr(pd_id));
1012         num_pd_disks++;
1013         offset += sizeof(struct mfi_pd_address);
1014     }
1015     trace_megasas_dcmd_pd_get_list(cmd->index, num_pd_disks,
1016                                    max_pd_disks, offset);
1017 
1018     info.size = cpu_to_le32(offset);
1019     info.count = cpu_to_le32(num_pd_disks);
1020 
1021     cmd->iov_size -= dma_buf_read(&info, offset, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1022     return MFI_STAT_OK;
1023 }
1024 
1025 static int megasas_dcmd_pd_list_query(MegasasState *s, MegasasCmd *cmd)
1026 {
1027     uint16_t flags;
1028 
1029     /* mbox0 contains flags */
1030     flags = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
1031     trace_megasas_dcmd_pd_list_query(cmd->index, flags);
1032     if (flags == MR_PD_QUERY_TYPE_ALL ||
1033         megasas_is_jbod(s)) {
1034         return megasas_dcmd_pd_get_list(s, cmd);
1035     }
1036 
1037     return MFI_STAT_OK;
1038 }
1039 
1040 static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun,
1041                                       MegasasCmd *cmd)
1042 {
1043     struct mfi_pd_info *info = cmd->iov_buf;
1044     size_t dcmd_size = sizeof(struct mfi_pd_info);
1045     uint64_t pd_size;
1046     uint16_t pd_id = ((sdev->id & 0xFF) << 8) | (lun & 0xFF);
1047     uint8_t cmdbuf[6];
1048     size_t len, resid;
1049 
1050     if (!cmd->iov_buf) {
1051         cmd->iov_buf = g_malloc0(dcmd_size);
1052         info = cmd->iov_buf;
1053         info->inquiry_data[0] = 0x7f; /* Force PQual 0x3, PType 0x1f */
1054         info->vpd_page83[0] = 0x7f;
1055         megasas_setup_inquiry(cmdbuf, 0, sizeof(info->inquiry_data));
1056         cmd->req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);
1057         if (!cmd->req) {
1058             trace_megasas_dcmd_req_alloc_failed(cmd->index,
1059                                                 "PD get info std inquiry");
1060             g_free(cmd->iov_buf);
1061             cmd->iov_buf = NULL;
1062             return MFI_STAT_FLASH_ALLOC_FAIL;
1063         }
1064         trace_megasas_dcmd_internal_submit(cmd->index,
1065                                            "PD get info std inquiry", lun);
1066         len = scsi_req_enqueue(cmd->req);
1067         if (len > 0) {
1068             cmd->iov_size = len;
1069             scsi_req_continue(cmd->req);
1070         }
1071         return MFI_STAT_INVALID_STATUS;
1072     } else if (info->inquiry_data[0] != 0x7f && info->vpd_page83[0] == 0x7f) {
1073         megasas_setup_inquiry(cmdbuf, 0x83, sizeof(info->vpd_page83));
1074         cmd->req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);
1075         if (!cmd->req) {
1076             trace_megasas_dcmd_req_alloc_failed(cmd->index,
1077                                                 "PD get info vpd inquiry");
1078             return MFI_STAT_FLASH_ALLOC_FAIL;
1079         }
1080         trace_megasas_dcmd_internal_submit(cmd->index,
1081                                            "PD get info vpd inquiry", lun);
1082         len = scsi_req_enqueue(cmd->req);
1083         if (len > 0) {
1084             cmd->iov_size = len;
1085             scsi_req_continue(cmd->req);
1086         }
1087         return MFI_STAT_INVALID_STATUS;
1088     }
1089     /* Finished, set FW state */
1090     if ((info->inquiry_data[0] >> 5) == 0) {
1091         if (megasas_is_jbod(cmd->state)) {
1092             info->fw_state = cpu_to_le16(MFI_PD_STATE_SYSTEM);
1093         } else {
1094             info->fw_state = cpu_to_le16(MFI_PD_STATE_ONLINE);
1095         }
1096     } else {
1097         info->fw_state = cpu_to_le16(MFI_PD_STATE_OFFLINE);
1098     }
1099 
1100     info->ref.v.device_id = cpu_to_le16(pd_id);
1101     info->state.ddf.pd_type = cpu_to_le16(MFI_PD_DDF_TYPE_IN_VD|
1102                                           MFI_PD_DDF_TYPE_INTF_SAS);
1103     blk_get_geometry(sdev->conf.blk, &pd_size);
1104     info->raw_size = cpu_to_le64(pd_size);
1105     info->non_coerced_size = cpu_to_le64(pd_size);
1106     info->coerced_size = cpu_to_le64(pd_size);
1107     info->encl_device_id = 0xFFFF;
1108     info->slot_number = (sdev->id & 0xFF);
1109     info->path_info.count = 1;
1110     info->path_info.sas_addr[0] =
1111         cpu_to_le64(megasas_get_sata_addr(pd_id));
1112     info->connected_port_bitmap = 0x1;
1113     info->device_speed = 1;
1114     info->link_speed = 1;
1115     resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1116     g_free(cmd->iov_buf);
1117     cmd->iov_size = dcmd_size - resid;
1118     cmd->iov_buf = NULL;
1119     return MFI_STAT_OK;
1120 }
1121 
1122 static int megasas_dcmd_pd_get_info(MegasasState *s, MegasasCmd *cmd)
1123 {
1124     size_t dcmd_size = sizeof(struct mfi_pd_info);
1125     uint16_t pd_id;
1126     uint8_t target_id, lun_id;
1127     SCSIDevice *sdev = NULL;
1128     int retval = MFI_STAT_DEVICE_NOT_FOUND;
1129 
1130     if (cmd->iov_size < dcmd_size) {
1131         return MFI_STAT_INVALID_PARAMETER;
1132     }
1133 
1134     /* mbox0 has the ID */
1135     pd_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
1136     target_id = (pd_id >> 8) & 0xFF;
1137     lun_id = pd_id & 0xFF;
1138     sdev = scsi_device_find(&s->bus, 0, target_id, lun_id);
1139     trace_megasas_dcmd_pd_get_info(cmd->index, pd_id);
1140 
1141     if (sdev) {
1142         /* Submit inquiry */
1143         retval = megasas_pd_get_info_submit(sdev, pd_id, cmd);
1144     }
1145 
1146     return retval;
1147 }
1148 
1149 static int megasas_dcmd_ld_get_list(MegasasState *s, MegasasCmd *cmd)
1150 {
1151     struct mfi_ld_list info;
1152     size_t dcmd_size = sizeof(info), resid;
1153     uint32_t num_ld_disks = 0, max_ld_disks;
1154     uint64_t ld_size;
1155     BusChild *kid;
1156 
1157     memset(&info, 0, dcmd_size);
1158     if (cmd->iov_size > dcmd_size) {
1159         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
1160                                             dcmd_size);
1161         return MFI_STAT_INVALID_PARAMETER;
1162     }
1163 
1164     max_ld_disks = (cmd->iov_size - 8) / 16;
1165     if (megasas_is_jbod(s)) {
1166         max_ld_disks = 0;
1167     }
1168     if (max_ld_disks > MFI_MAX_LD) {
1169         max_ld_disks = MFI_MAX_LD;
1170     }
1171     QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
1172         SCSIDevice *sdev = SCSI_DEVICE(kid->child);
1173 
1174         if (num_ld_disks >= max_ld_disks) {
1175             break;
1176         }
1177         /* Logical device size is in blocks */
1178         blk_get_geometry(sdev->conf.blk, &ld_size);
1179         info.ld_list[num_ld_disks].ld.v.target_id = sdev->id;
1180         info.ld_list[num_ld_disks].state = MFI_LD_STATE_OPTIMAL;
1181         info.ld_list[num_ld_disks].size = cpu_to_le64(ld_size);
1182         num_ld_disks++;
1183     }
1184     info.ld_count = cpu_to_le32(num_ld_disks);
1185     trace_megasas_dcmd_ld_get_list(cmd->index, num_ld_disks, max_ld_disks);
1186 
1187     resid = dma_buf_read(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1188     cmd->iov_size = dcmd_size - resid;
1189     return MFI_STAT_OK;
1190 }
1191 
1192 static int megasas_dcmd_ld_list_query(MegasasState *s, MegasasCmd *cmd)
1193 {
1194     uint16_t flags;
1195     struct mfi_ld_targetid_list info;
1196     size_t dcmd_size = sizeof(info), resid;
1197     uint32_t num_ld_disks = 0, max_ld_disks = s->fw_luns;
1198     BusChild *kid;
1199 
1200     /* mbox0 contains flags */
1201     flags = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
1202     trace_megasas_dcmd_ld_list_query(cmd->index, flags);
1203     if (flags != MR_LD_QUERY_TYPE_ALL &&
1204         flags != MR_LD_QUERY_TYPE_EXPOSED_TO_HOST) {
1205         max_ld_disks = 0;
1206     }
1207 
1208     memset(&info, 0, dcmd_size);
1209     if (cmd->iov_size < 12) {
1210         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
1211                                             dcmd_size);
1212         return MFI_STAT_INVALID_PARAMETER;
1213     }
1214     dcmd_size = sizeof(uint32_t) * 2 + 3;
1215     max_ld_disks = cmd->iov_size - dcmd_size;
1216     if (megasas_is_jbod(s)) {
1217         max_ld_disks = 0;
1218     }
1219     if (max_ld_disks > MFI_MAX_LD) {
1220         max_ld_disks = MFI_MAX_LD;
1221     }
1222     QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
1223         SCSIDevice *sdev = SCSI_DEVICE(kid->child);
1224 
1225         if (num_ld_disks >= max_ld_disks) {
1226             break;
1227         }
1228         info.targetid[num_ld_disks] = sdev->lun;
1229         num_ld_disks++;
1230         dcmd_size++;
1231     }
1232     info.ld_count = cpu_to_le32(num_ld_disks);
1233     info.size = dcmd_size;
1234     trace_megasas_dcmd_ld_get_list(cmd->index, num_ld_disks, max_ld_disks);
1235 
1236     resid = dma_buf_read(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1237     cmd->iov_size = dcmd_size - resid;
1238     return MFI_STAT_OK;
1239 }
1240 
1241 static int megasas_ld_get_info_submit(SCSIDevice *sdev, int lun,
1242                                       MegasasCmd *cmd)
1243 {
1244     struct mfi_ld_info *info = cmd->iov_buf;
1245     size_t dcmd_size = sizeof(struct mfi_ld_info);
1246     uint8_t cdb[6];
1247     ssize_t len, resid;
1248     uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (lun & 0xFF);
1249     uint64_t ld_size;
1250 
1251     if (!cmd->iov_buf) {
1252         cmd->iov_buf = g_malloc0(dcmd_size);
1253         info = cmd->iov_buf;
1254         megasas_setup_inquiry(cdb, 0x83, sizeof(info->vpd_page83));
1255         cmd->req = scsi_req_new(sdev, cmd->index, lun, cdb, cmd);
1256         if (!cmd->req) {
1257             trace_megasas_dcmd_req_alloc_failed(cmd->index,
1258                                                 "LD get info vpd inquiry");
1259             g_free(cmd->iov_buf);
1260             cmd->iov_buf = NULL;
1261             return MFI_STAT_FLASH_ALLOC_FAIL;
1262         }
1263         trace_megasas_dcmd_internal_submit(cmd->index,
1264                                            "LD get info vpd inquiry", lun);
1265         len = scsi_req_enqueue(cmd->req);
1266         if (len > 0) {
1267             cmd->iov_size = len;
1268             scsi_req_continue(cmd->req);
1269         }
1270         return MFI_STAT_INVALID_STATUS;
1271     }
1272 
1273     info->ld_config.params.state = MFI_LD_STATE_OPTIMAL;
1274     info->ld_config.properties.ld.v.target_id = lun;
1275     info->ld_config.params.stripe_size = 3;
1276     info->ld_config.params.num_drives = 1;
1277     info->ld_config.params.is_consistent = 1;
1278     /* Logical device size is in blocks */
1279     blk_get_geometry(sdev->conf.blk, &ld_size);
1280     info->size = cpu_to_le64(ld_size);
1281     memset(info->ld_config.span, 0, sizeof(info->ld_config.span));
1282     info->ld_config.span[0].start_block = 0;
1283     info->ld_config.span[0].num_blocks = info->size;
1284     info->ld_config.span[0].array_ref = cpu_to_le16(sdev_id);
1285 
1286     resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1287     g_free(cmd->iov_buf);
1288     cmd->iov_size = dcmd_size - resid;
1289     cmd->iov_buf = NULL;
1290     return MFI_STAT_OK;
1291 }
1292 
1293 static int megasas_dcmd_ld_get_info(MegasasState *s, MegasasCmd *cmd)
1294 {
1295     struct mfi_ld_info info;
1296     size_t dcmd_size = sizeof(info);
1297     uint16_t ld_id;
1298     uint32_t max_ld_disks = s->fw_luns;
1299     SCSIDevice *sdev = NULL;
1300     int retval = MFI_STAT_DEVICE_NOT_FOUND;
1301 
1302     if (cmd->iov_size < dcmd_size) {
1303         return MFI_STAT_INVALID_PARAMETER;
1304     }
1305 
1306     /* mbox0 has the ID */
1307     ld_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
1308     trace_megasas_dcmd_ld_get_info(cmd->index, ld_id);
1309 
1310     if (megasas_is_jbod(s)) {
1311         return MFI_STAT_DEVICE_NOT_FOUND;
1312     }
1313 
1314     if (ld_id < max_ld_disks) {
1315         sdev = scsi_device_find(&s->bus, 0, ld_id, 0);
1316     }
1317 
1318     if (sdev) {
1319         retval = megasas_ld_get_info_submit(sdev, ld_id, cmd);
1320     }
1321 
1322     return retval;
1323 }
1324 
1325 static int megasas_dcmd_cfg_read(MegasasState *s, MegasasCmd *cmd)
1326 {
1327     uint8_t data[4096] = { 0 };
1328     struct mfi_config_data *info;
1329     int num_pd_disks = 0, array_offset, ld_offset;
1330     BusChild *kid;
1331 
1332     if (cmd->iov_size > 4096) {
1333         return MFI_STAT_INVALID_PARAMETER;
1334     }
1335 
1336     QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
1337         num_pd_disks++;
1338     }
1339     info = (struct mfi_config_data *)&data;
1340     /*
1341      * Array mapping:
1342      * - One array per SCSI device
1343      * - One logical drive per SCSI device
1344      *   spanning the entire device
1345      */
1346     info->array_count = num_pd_disks;
1347     info->array_size = sizeof(struct mfi_array) * num_pd_disks;
1348     info->log_drv_count = num_pd_disks;
1349     info->log_drv_size = sizeof(struct mfi_ld_config) * num_pd_disks;
1350     info->spares_count = 0;
1351     info->spares_size = sizeof(struct mfi_spare);
1352     info->size = sizeof(struct mfi_config_data) + info->array_size +
1353         info->log_drv_size;
1354     if (info->size > 4096) {
1355         return MFI_STAT_INVALID_PARAMETER;
1356     }
1357 
1358     array_offset = sizeof(struct mfi_config_data);
1359     ld_offset = array_offset + sizeof(struct mfi_array) * num_pd_disks;
1360 
1361     QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
1362         SCSIDevice *sdev = SCSI_DEVICE(kid->child);
1363         uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF);
1364         struct mfi_array *array;
1365         struct mfi_ld_config *ld;
1366         uint64_t pd_size;
1367         int i;
1368 
1369         array = (struct mfi_array *)(data + array_offset);
1370         blk_get_geometry(sdev->conf.blk, &pd_size);
1371         array->size = cpu_to_le64(pd_size);
1372         array->num_drives = 1;
1373         array->array_ref = cpu_to_le16(sdev_id);
1374         array->pd[0].ref.v.device_id = cpu_to_le16(sdev_id);
1375         array->pd[0].ref.v.seq_num = 0;
1376         array->pd[0].fw_state = MFI_PD_STATE_ONLINE;
1377         array->pd[0].encl.pd = 0xFF;
1378         array->pd[0].encl.slot = (sdev->id & 0xFF);
1379         for (i = 1; i < MFI_MAX_ROW_SIZE; i++) {
1380             array->pd[i].ref.v.device_id = 0xFFFF;
1381             array->pd[i].ref.v.seq_num = 0;
1382             array->pd[i].fw_state = MFI_PD_STATE_UNCONFIGURED_GOOD;
1383             array->pd[i].encl.pd = 0xFF;
1384             array->pd[i].encl.slot = 0xFF;
1385         }
1386         array_offset += sizeof(struct mfi_array);
1387         ld = (struct mfi_ld_config *)(data + ld_offset);
1388         memset(ld, 0, sizeof(struct mfi_ld_config));
1389         ld->properties.ld.v.target_id = sdev->id;
1390         ld->properties.default_cache_policy = MR_LD_CACHE_READ_AHEAD |
1391             MR_LD_CACHE_READ_ADAPTIVE;
1392         ld->properties.current_cache_policy = MR_LD_CACHE_READ_AHEAD |
1393             MR_LD_CACHE_READ_ADAPTIVE;
1394         ld->params.state = MFI_LD_STATE_OPTIMAL;
1395         ld->params.stripe_size = 3;
1396         ld->params.num_drives = 1;
1397         ld->params.span_depth = 1;
1398         ld->params.is_consistent = 1;
1399         ld->span[0].start_block = 0;
1400         ld->span[0].num_blocks = cpu_to_le64(pd_size);
1401         ld->span[0].array_ref = cpu_to_le16(sdev_id);
1402         ld_offset += sizeof(struct mfi_ld_config);
1403     }
1404 
1405     cmd->iov_size -= dma_buf_read(data, info->size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1406     return MFI_STAT_OK;
1407 }
1408 
1409 static int megasas_dcmd_get_properties(MegasasState *s, MegasasCmd *cmd)
1410 {
1411     struct mfi_ctrl_props info;
1412     size_t dcmd_size = sizeof(info);
1413 
1414     memset(&info, 0x0, dcmd_size);
1415     if (cmd->iov_size < dcmd_size) {
1416         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
1417                                             dcmd_size);
1418         return MFI_STAT_INVALID_PARAMETER;
1419     }
1420     info.pred_fail_poll_interval = cpu_to_le16(300);
1421     info.intr_throttle_cnt = cpu_to_le16(16);
1422     info.intr_throttle_timeout = cpu_to_le16(50);
1423     info.rebuild_rate = 30;
1424     info.patrol_read_rate = 30;
1425     info.bgi_rate = 30;
1426     info.cc_rate = 30;
1427     info.recon_rate = 30;
1428     info.cache_flush_interval = 4;
1429     info.spinup_drv_cnt = 2;
1430     info.spinup_delay = 6;
1431     info.ecc_bucket_size = 15;
1432     info.ecc_bucket_leak_rate = cpu_to_le16(1440);
1433     info.expose_encl_devices = 1;
1434 
1435     cmd->iov_size -= dma_buf_read(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1436     return MFI_STAT_OK;
1437 }
1438 
1439 static int megasas_cache_flush(MegasasState *s, MegasasCmd *cmd)
1440 {
1441     blk_drain_all();
1442     return MFI_STAT_OK;
1443 }
1444 
1445 static int megasas_ctrl_shutdown(MegasasState *s, MegasasCmd *cmd)
1446 {
1447     s->fw_state = MFI_FWSTATE_READY;
1448     return MFI_STAT_OK;
1449 }
1450 
1451 /* Some implementations use CLUSTER RESET LD to simulate a device reset */
1452 static int megasas_cluster_reset_ld(MegasasState *s, MegasasCmd *cmd)
1453 {
1454     uint16_t target_id;
1455     int i;
1456 
1457     /* mbox0 contains the device index */
1458     target_id = le16_to_cpu(cmd->frame->dcmd.mbox[0]);
1459     trace_megasas_dcmd_reset_ld(cmd->index, target_id);
1460     for (i = 0; i < s->fw_cmds; i++) {
1461         MegasasCmd *tmp_cmd = &s->frames[i];
1462         if (tmp_cmd->req && tmp_cmd->req->dev->id == target_id) {
1463             SCSIDevice *d = tmp_cmd->req->dev;
1464             qdev_reset_all(&d->qdev);
1465         }
1466     }
1467     return MFI_STAT_OK;
1468 }
1469 
1470 static int megasas_dcmd_set_properties(MegasasState *s, MegasasCmd *cmd)
1471 {
1472     struct mfi_ctrl_props info;
1473     size_t dcmd_size = sizeof(info);
1474 
1475     if (cmd->iov_size < dcmd_size) {
1476         trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
1477                                             dcmd_size);
1478         return MFI_STAT_INVALID_PARAMETER;
1479     }
1480     dma_buf_write(&info, dcmd_size, &cmd->qsg, MEMTXATTRS_UNSPECIFIED);
1481     trace_megasas_dcmd_unsupported(cmd->index, cmd->iov_size);
1482     return MFI_STAT_OK;
1483 }
1484 
1485 static int megasas_dcmd_dummy(MegasasState *s, MegasasCmd *cmd)
1486 {
1487     trace_megasas_dcmd_dummy(cmd->index, cmd->iov_size);
1488     return MFI_STAT_OK;
1489 }
1490 
1491 static const struct dcmd_cmd_tbl_t {
1492     int opcode;
1493     const char *desc;
1494     int (*func)(MegasasState *s, MegasasCmd *cmd);
1495 } dcmd_cmd_tbl[] = {
1496     { MFI_DCMD_CTRL_MFI_HOST_MEM_ALLOC, "CTRL_HOST_MEM_ALLOC",
1497       megasas_dcmd_dummy },
1498     { MFI_DCMD_CTRL_GET_INFO, "CTRL_GET_INFO",
1499       megasas_ctrl_get_info },
1500     { MFI_DCMD_CTRL_GET_PROPERTIES, "CTRL_GET_PROPERTIES",
1501       megasas_dcmd_get_properties },
1502     { MFI_DCMD_CTRL_SET_PROPERTIES, "CTRL_SET_PROPERTIES",
1503       megasas_dcmd_set_properties },
1504     { MFI_DCMD_CTRL_ALARM_GET, "CTRL_ALARM_GET",
1505       megasas_dcmd_dummy },
1506     { MFI_DCMD_CTRL_ALARM_ENABLE, "CTRL_ALARM_ENABLE",
1507       megasas_dcmd_dummy },
1508     { MFI_DCMD_CTRL_ALARM_DISABLE, "CTRL_ALARM_DISABLE",
1509       megasas_dcmd_dummy },
1510     { MFI_DCMD_CTRL_ALARM_SILENCE, "CTRL_ALARM_SILENCE",
1511       megasas_dcmd_dummy },
1512     { MFI_DCMD_CTRL_ALARM_TEST, "CTRL_ALARM_TEST",
1513       megasas_dcmd_dummy },
1514     { MFI_DCMD_CTRL_EVENT_GETINFO, "CTRL_EVENT_GETINFO",
1515       megasas_event_info },
1516     { MFI_DCMD_CTRL_EVENT_GET, "CTRL_EVENT_GET",
1517       megasas_dcmd_dummy },
1518     { MFI_DCMD_CTRL_EVENT_WAIT, "CTRL_EVENT_WAIT",
1519       megasas_event_wait },
1520     { MFI_DCMD_CTRL_SHUTDOWN, "CTRL_SHUTDOWN",
1521       megasas_ctrl_shutdown },
1522     { MFI_DCMD_HIBERNATE_STANDBY, "CTRL_STANDBY",
1523       megasas_dcmd_dummy },
1524     { MFI_DCMD_CTRL_GET_TIME, "CTRL_GET_TIME",
1525       megasas_dcmd_get_fw_time },
1526     { MFI_DCMD_CTRL_SET_TIME, "CTRL_SET_TIME",
1527       megasas_dcmd_set_fw_time },
1528     { MFI_DCMD_CTRL_BIOS_DATA_GET, "CTRL_BIOS_DATA_GET",
1529       megasas_dcmd_get_bios_info },
1530     { MFI_DCMD_CTRL_FACTORY_DEFAULTS, "CTRL_FACTORY_DEFAULTS",
1531       megasas_dcmd_dummy },
1532     { MFI_DCMD_CTRL_MFC_DEFAULTS_GET, "CTRL_MFC_DEFAULTS_GET",
1533       megasas_mfc_get_defaults },
1534     { MFI_DCMD_CTRL_MFC_DEFAULTS_SET, "CTRL_MFC_DEFAULTS_SET",
1535       megasas_dcmd_dummy },
1536     { MFI_DCMD_CTRL_CACHE_FLUSH, "CTRL_CACHE_FLUSH",
1537       megasas_cache_flush },
1538     { MFI_DCMD_PD_GET_LIST, "PD_GET_LIST",
1539       megasas_dcmd_pd_get_list },
1540     { MFI_DCMD_PD_LIST_QUERY, "PD_LIST_QUERY",
1541       megasas_dcmd_pd_list_query },
1542     { MFI_DCMD_PD_GET_INFO, "PD_GET_INFO",
1543       megasas_dcmd_pd_get_info },
1544     { MFI_DCMD_PD_STATE_SET, "PD_STATE_SET",
1545       megasas_dcmd_dummy },
1546     { MFI_DCMD_PD_REBUILD, "PD_REBUILD",
1547       megasas_dcmd_dummy },
1548     { MFI_DCMD_PD_BLINK, "PD_BLINK",
1549       megasas_dcmd_dummy },
1550     { MFI_DCMD_PD_UNBLINK, "PD_UNBLINK",
1551       megasas_dcmd_dummy },
1552     { MFI_DCMD_LD_GET_LIST, "LD_GET_LIST",
1553       megasas_dcmd_ld_get_list},
1554     { MFI_DCMD_LD_LIST_QUERY, "LD_LIST_QUERY",
1555       megasas_dcmd_ld_list_query },
1556     { MFI_DCMD_LD_GET_INFO, "LD_GET_INFO",
1557       megasas_dcmd_ld_get_info },
1558     { MFI_DCMD_LD_GET_PROP, "LD_GET_PROP",
1559       megasas_dcmd_dummy },
1560     { MFI_DCMD_LD_SET_PROP, "LD_SET_PROP",
1561       megasas_dcmd_dummy },
1562     { MFI_DCMD_LD_DELETE, "LD_DELETE",
1563       megasas_dcmd_dummy },
1564     { MFI_DCMD_CFG_READ, "CFG_READ",
1565       megasas_dcmd_cfg_read },
1566     { MFI_DCMD_CFG_ADD, "CFG_ADD",
1567       megasas_dcmd_dummy },
1568     { MFI_DCMD_CFG_CLEAR, "CFG_CLEAR",
1569       megasas_dcmd_dummy },
1570     { MFI_DCMD_CFG_FOREIGN_READ, "CFG_FOREIGN_READ",
1571       megasas_dcmd_dummy },
1572     { MFI_DCMD_CFG_FOREIGN_IMPORT, "CFG_FOREIGN_IMPORT",
1573       megasas_dcmd_dummy },
1574     { MFI_DCMD_BBU_STATUS, "BBU_STATUS",
1575       megasas_dcmd_dummy },
1576     { MFI_DCMD_BBU_CAPACITY_INFO, "BBU_CAPACITY_INFO",
1577       megasas_dcmd_dummy },
1578     { MFI_DCMD_BBU_DESIGN_INFO, "BBU_DESIGN_INFO",
1579       megasas_dcmd_dummy },
1580     { MFI_DCMD_BBU_PROP_GET, "BBU_PROP_GET",
1581       megasas_dcmd_dummy },
1582     { MFI_DCMD_CLUSTER, "CLUSTER",
1583       megasas_dcmd_dummy },
1584     { MFI_DCMD_CLUSTER_RESET_ALL, "CLUSTER_RESET_ALL",
1585       megasas_dcmd_dummy },
1586     { MFI_DCMD_CLUSTER_RESET_LD, "CLUSTER_RESET_LD",
1587       megasas_cluster_reset_ld },
1588     { -1, NULL, NULL }
1589 };
1590 
1591 static int megasas_handle_dcmd(MegasasState *s, MegasasCmd *cmd)
1592 {
1593     int retval = 0;
1594     size_t len;
1595     const struct dcmd_cmd_tbl_t *cmdptr = dcmd_cmd_tbl;
1596 
1597     cmd->dcmd_opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
1598     trace_megasas_handle_dcmd(cmd->index, cmd->dcmd_opcode);
1599     if (megasas_map_dcmd(s, cmd) < 0) {
1600         return MFI_STAT_MEMORY_NOT_AVAILABLE;
1601     }
1602     while (cmdptr->opcode != -1 && cmdptr->opcode != cmd->dcmd_opcode) {
1603         cmdptr++;
1604     }
1605     len = cmd->iov_size;
1606     if (cmdptr->opcode == -1) {
1607         trace_megasas_dcmd_unhandled(cmd->index, cmd->dcmd_opcode, len);
1608         retval = megasas_dcmd_dummy(s, cmd);
1609     } else {
1610         trace_megasas_dcmd_enter(cmd->index, cmdptr->desc, len);
1611         retval = cmdptr->func(s, cmd);
1612     }
1613     if (retval != MFI_STAT_INVALID_STATUS) {
1614         megasas_finish_dcmd(cmd, len);
1615     }
1616     return retval;
1617 }
1618 
1619 static int megasas_finish_internal_dcmd(MegasasCmd *cmd,
1620                                         SCSIRequest *req, size_t resid)
1621 {
1622     int retval = MFI_STAT_OK;
1623     int lun = req->lun;
1624 
1625     trace_megasas_dcmd_internal_finish(cmd->index, cmd->dcmd_opcode, lun);
1626     cmd->iov_size -= resid;
1627     switch (cmd->dcmd_opcode) {
1628     case MFI_DCMD_PD_GET_INFO:
1629         retval = megasas_pd_get_info_submit(req->dev, lun, cmd);
1630         break;
1631     case MFI_DCMD_LD_GET_INFO:
1632         retval = megasas_ld_get_info_submit(req->dev, lun, cmd);
1633         break;
1634     default:
1635         trace_megasas_dcmd_internal_invalid(cmd->index, cmd->dcmd_opcode);
1636         retval = MFI_STAT_INVALID_DCMD;
1637         break;
1638     }
1639     if (retval != MFI_STAT_INVALID_STATUS) {
1640         megasas_finish_dcmd(cmd, cmd->iov_size);
1641     }
1642     return retval;
1643 }
1644 
1645 static int megasas_enqueue_req(MegasasCmd *cmd, bool is_write)
1646 {
1647     int len;
1648 
1649     len = scsi_req_enqueue(cmd->req);
1650     if (len < 0) {
1651         len = -len;
1652     }
1653     if (len > 0) {
1654         if (len > cmd->iov_size) {
1655             if (is_write) {
1656                 trace_megasas_iov_write_overflow(cmd->index, len,
1657                                                  cmd->iov_size);
1658             } else {
1659                 trace_megasas_iov_read_overflow(cmd->index, len,
1660                                                 cmd->iov_size);
1661             }
1662         }
1663         if (len < cmd->iov_size) {
1664             if (is_write) {
1665                 trace_megasas_iov_write_underflow(cmd->index, len,
1666                                                   cmd->iov_size);
1667             } else {
1668                 trace_megasas_iov_read_underflow(cmd->index, len,
1669                                                  cmd->iov_size);
1670             }
1671             cmd->iov_size = len;
1672         }
1673         scsi_req_continue(cmd->req);
1674     }
1675     return len;
1676 }
1677 
1678 static int megasas_handle_scsi(MegasasState *s, MegasasCmd *cmd,
1679                                int frame_cmd)
1680 {
1681     uint8_t *cdb;
1682     int target_id, lun_id, cdb_len;
1683     bool is_write;
1684     struct SCSIDevice *sdev = NULL;
1685     bool is_logical = (frame_cmd == MFI_CMD_LD_SCSI_IO);
1686 
1687     cdb = cmd->frame->pass.cdb;
1688     target_id = cmd->frame->header.target_id;
1689     lun_id = cmd->frame->header.lun_id;
1690     cdb_len = cmd->frame->header.cdb_len;
1691 
1692     if (is_logical) {
1693         if (target_id >= MFI_MAX_LD || lun_id != 0) {
1694             trace_megasas_scsi_target_not_present(
1695                 mfi_frame_desc(frame_cmd), is_logical, target_id, lun_id);
1696             return MFI_STAT_DEVICE_NOT_FOUND;
1697         }
1698     }
1699     sdev = scsi_device_find(&s->bus, 0, target_id, lun_id);
1700 
1701     cmd->iov_size = le32_to_cpu(cmd->frame->header.data_len);
1702     trace_megasas_handle_scsi(mfi_frame_desc(frame_cmd), is_logical,
1703                               target_id, lun_id, sdev, cmd->iov_size);
1704 
1705     if (!sdev || (megasas_is_jbod(s) && is_logical)) {
1706         trace_megasas_scsi_target_not_present(
1707             mfi_frame_desc(frame_cmd), is_logical, target_id, lun_id);
1708         return MFI_STAT_DEVICE_NOT_FOUND;
1709     }
1710 
1711     if (cdb_len > 16) {
1712         trace_megasas_scsi_invalid_cdb_len(
1713                 mfi_frame_desc(frame_cmd), is_logical,
1714                 target_id, lun_id, cdb_len);
1715         megasas_write_sense(cmd, SENSE_CODE(INVALID_OPCODE));
1716         cmd->frame->header.scsi_status = CHECK_CONDITION;
1717         s->event_count++;
1718         return MFI_STAT_SCSI_DONE_WITH_ERROR;
1719     }
1720 
1721     if (megasas_map_sgl(s, cmd, &cmd->frame->pass.sgl)) {
1722         megasas_write_sense(cmd, SENSE_CODE(TARGET_FAILURE));
1723         cmd->frame->header.scsi_status = CHECK_CONDITION;
1724         s->event_count++;
1725         return MFI_STAT_SCSI_DONE_WITH_ERROR;
1726     }
1727 
1728     cmd->req = scsi_req_new(sdev, cmd->index, lun_id, cdb, cmd);
1729     if (!cmd->req) {
1730         trace_megasas_scsi_req_alloc_failed(
1731                 mfi_frame_desc(frame_cmd), target_id, lun_id);
1732         megasas_write_sense(cmd, SENSE_CODE(NO_SENSE));
1733         cmd->frame->header.scsi_status = BUSY;
1734         s->event_count++;
1735         return MFI_STAT_SCSI_DONE_WITH_ERROR;
1736     }
1737 
1738     is_write = (cmd->req->cmd.mode == SCSI_XFER_TO_DEV);
1739     if (cmd->iov_size) {
1740         if (is_write) {
1741             trace_megasas_scsi_write_start(cmd->index, cmd->iov_size);
1742         } else {
1743             trace_megasas_scsi_read_start(cmd->index, cmd->iov_size);
1744         }
1745     } else {
1746         trace_megasas_scsi_nodata(cmd->index);
1747     }
1748     megasas_enqueue_req(cmd, is_write);
1749     return MFI_STAT_INVALID_STATUS;
1750 }
1751 
1752 static int megasas_handle_io(MegasasState *s, MegasasCmd *cmd, int frame_cmd)
1753 {
1754     uint32_t lba_count, lba_start_hi, lba_start_lo;
1755     uint64_t lba_start;
1756     bool is_write = (frame_cmd == MFI_CMD_LD_WRITE);
1757     uint8_t cdb[16];
1758     int len;
1759     struct SCSIDevice *sdev = NULL;
1760     int target_id, lun_id, cdb_len;
1761 
1762     lba_count = le32_to_cpu(cmd->frame->io.header.data_len);
1763     lba_start_lo = le32_to_cpu(cmd->frame->io.lba_lo);
1764     lba_start_hi = le32_to_cpu(cmd->frame->io.lba_hi);
1765     lba_start = ((uint64_t)lba_start_hi << 32) | lba_start_lo;
1766 
1767     target_id = cmd->frame->header.target_id;
1768     lun_id = cmd->frame->header.lun_id;
1769     cdb_len = cmd->frame->header.cdb_len;
1770 
1771     if (target_id < MFI_MAX_LD && lun_id == 0) {
1772         sdev = scsi_device_find(&s->bus, 0, target_id, lun_id);
1773     }
1774 
1775     trace_megasas_handle_io(cmd->index,
1776                             mfi_frame_desc(frame_cmd), target_id, lun_id,
1777                             (unsigned long)lba_start, (unsigned long)lba_count);
1778     if (!sdev) {
1779         trace_megasas_io_target_not_present(cmd->index,
1780             mfi_frame_desc(frame_cmd), target_id, lun_id);
1781         return MFI_STAT_DEVICE_NOT_FOUND;
1782     }
1783 
1784     if (cdb_len > 16) {
1785         trace_megasas_scsi_invalid_cdb_len(
1786             mfi_frame_desc(frame_cmd), 1, target_id, lun_id, cdb_len);
1787         megasas_write_sense(cmd, SENSE_CODE(INVALID_OPCODE));
1788         cmd->frame->header.scsi_status = CHECK_CONDITION;
1789         s->event_count++;
1790         return MFI_STAT_SCSI_DONE_WITH_ERROR;
1791     }
1792 
1793     cmd->iov_size = lba_count * sdev->blocksize;
1794     if (megasas_map_sgl(s, cmd, &cmd->frame->io.sgl)) {
1795         megasas_write_sense(cmd, SENSE_CODE(TARGET_FAILURE));
1796         cmd->frame->header.scsi_status = CHECK_CONDITION;
1797         s->event_count++;
1798         return MFI_STAT_SCSI_DONE_WITH_ERROR;
1799     }
1800 
1801     megasas_encode_lba(cdb, lba_start, lba_count, is_write);
1802     cmd->req = scsi_req_new(sdev, cmd->index,
1803                             lun_id, cdb, cmd);
1804     if (!cmd->req) {
1805         trace_megasas_scsi_req_alloc_failed(
1806             mfi_frame_desc(frame_cmd), target_id, lun_id);
1807         megasas_write_sense(cmd, SENSE_CODE(NO_SENSE));
1808         cmd->frame->header.scsi_status = BUSY;
1809         s->event_count++;
1810         return MFI_STAT_SCSI_DONE_WITH_ERROR;
1811     }
1812     len = megasas_enqueue_req(cmd, is_write);
1813     if (len > 0) {
1814         if (is_write) {
1815             trace_megasas_io_write_start(cmd->index, lba_start, lba_count, len);
1816         } else {
1817             trace_megasas_io_read_start(cmd->index, lba_start, lba_count, len);
1818         }
1819     }
1820     return MFI_STAT_INVALID_STATUS;
1821 }
1822 
1823 static QEMUSGList *megasas_get_sg_list(SCSIRequest *req)
1824 {
1825     MegasasCmd *cmd = req->hba_private;
1826 
1827     if (cmd->dcmd_opcode != -1) {
1828         return NULL;
1829     } else {
1830         return &cmd->qsg;
1831     }
1832 }
1833 
1834 static void megasas_xfer_complete(SCSIRequest *req, uint32_t len)
1835 {
1836     MegasasCmd *cmd = req->hba_private;
1837     uint8_t *buf;
1838 
1839     trace_megasas_io_complete(cmd->index, len);
1840 
1841     if (cmd->dcmd_opcode != -1) {
1842         scsi_req_continue(req);
1843         return;
1844     }
1845 
1846     buf = scsi_req_get_buf(req);
1847     if (cmd->dcmd_opcode == MFI_DCMD_PD_GET_INFO && cmd->iov_buf) {
1848         struct mfi_pd_info *info = cmd->iov_buf;
1849 
1850         if (info->inquiry_data[0] == 0x7f) {
1851             memset(info->inquiry_data, 0, sizeof(info->inquiry_data));
1852             memcpy(info->inquiry_data, buf, len);
1853         } else if (info->vpd_page83[0] == 0x7f) {
1854             memset(info->vpd_page83, 0, sizeof(info->vpd_page83));
1855             memcpy(info->vpd_page83, buf, len);
1856         }
1857         scsi_req_continue(req);
1858     } else if (cmd->dcmd_opcode == MFI_DCMD_LD_GET_INFO) {
1859         struct mfi_ld_info *info = cmd->iov_buf;
1860 
1861         if (cmd->iov_buf) {
1862             memcpy(info->vpd_page83, buf, sizeof(info->vpd_page83));
1863             scsi_req_continue(req);
1864         }
1865     }
1866 }
1867 
1868 static void megasas_command_complete(SCSIRequest *req, size_t resid)
1869 {
1870     MegasasCmd *cmd = req->hba_private;
1871     uint8_t cmd_status = MFI_STAT_OK;
1872 
1873     trace_megasas_command_complete(cmd->index, req->status, resid);
1874 
1875     if (req->io_canceled) {
1876         return;
1877     }
1878 
1879     if (cmd->dcmd_opcode != -1) {
1880         /*
1881          * Internal command complete
1882          */
1883         cmd_status = megasas_finish_internal_dcmd(cmd, req, resid);
1884         if (cmd_status == MFI_STAT_INVALID_STATUS) {
1885             return;
1886         }
1887     } else {
1888         trace_megasas_scsi_complete(cmd->index, req->status,
1889                                     cmd->iov_size, req->cmd.xfer);
1890         if (req->status != GOOD) {
1891             cmd_status = MFI_STAT_SCSI_DONE_WITH_ERROR;
1892         }
1893         if (req->status == CHECK_CONDITION) {
1894             megasas_copy_sense(cmd);
1895         }
1896 
1897         cmd->frame->header.scsi_status = req->status;
1898     }
1899     cmd->frame->header.cmd_status = cmd_status;
1900     megasas_complete_command(cmd);
1901 }
1902 
1903 static void megasas_command_cancelled(SCSIRequest *req)
1904 {
1905     MegasasCmd *cmd = req->hba_private;
1906 
1907     if (!cmd) {
1908         return;
1909     }
1910     cmd->frame->header.cmd_status = MFI_STAT_SCSI_IO_FAILED;
1911     megasas_complete_command(cmd);
1912 }
1913 
1914 static int megasas_handle_abort(MegasasState *s, MegasasCmd *cmd)
1915 {
1916     uint64_t abort_ctx = le64_to_cpu(cmd->frame->abort.abort_context);
1917     hwaddr abort_addr, addr_hi, addr_lo;
1918     MegasasCmd *abort_cmd;
1919 
1920     addr_hi = le32_to_cpu(cmd->frame->abort.abort_mfi_addr_hi);
1921     addr_lo = le32_to_cpu(cmd->frame->abort.abort_mfi_addr_lo);
1922     abort_addr = ((uint64_t)addr_hi << 32) | addr_lo;
1923 
1924     abort_cmd = megasas_lookup_frame(s, abort_addr);
1925     if (!abort_cmd) {
1926         trace_megasas_abort_no_cmd(cmd->index, abort_ctx);
1927         s->event_count++;
1928         return MFI_STAT_OK;
1929     }
1930     if (!megasas_use_queue64(s)) {
1931         abort_ctx &= (uint64_t)0xFFFFFFFF;
1932     }
1933     if (abort_cmd->context != abort_ctx) {
1934         trace_megasas_abort_invalid_context(cmd->index, abort_cmd->context,
1935                                             abort_cmd->index);
1936         s->event_count++;
1937         return MFI_STAT_ABORT_NOT_POSSIBLE;
1938     }
1939     trace_megasas_abort_frame(cmd->index, abort_cmd->index);
1940     megasas_abort_command(abort_cmd);
1941     if (!s->event_cmd || abort_cmd != s->event_cmd) {
1942         s->event_cmd = NULL;
1943     }
1944     s->event_count++;
1945     return MFI_STAT_OK;
1946 }
1947 
1948 static void megasas_handle_frame(MegasasState *s, uint64_t frame_addr,
1949                                  uint32_t frame_count)
1950 {
1951     uint8_t frame_status = MFI_STAT_INVALID_CMD;
1952     uint64_t frame_context;
1953     int frame_cmd;
1954     MegasasCmd *cmd;
1955 
1956     /*
1957      * Always read 64bit context, top bits will be
1958      * masked out if required in megasas_enqueue_frame()
1959      */
1960     frame_context = megasas_frame_get_context(s, frame_addr);
1961 
1962     cmd = megasas_enqueue_frame(s, frame_addr, frame_context, frame_count);
1963     if (!cmd) {
1964         /* reply queue full */
1965         trace_megasas_frame_busy(frame_addr);
1966         megasas_frame_set_scsi_status(s, frame_addr, BUSY);
1967         megasas_frame_set_cmd_status(s, frame_addr, MFI_STAT_SCSI_DONE_WITH_ERROR);
1968         megasas_complete_frame(s, frame_context);
1969         s->event_count++;
1970         return;
1971     }
1972     frame_cmd = cmd->frame->header.frame_cmd;
1973     switch (frame_cmd) {
1974     case MFI_CMD_INIT:
1975         frame_status = megasas_init_firmware(s, cmd);
1976         break;
1977     case MFI_CMD_DCMD:
1978         frame_status = megasas_handle_dcmd(s, cmd);
1979         break;
1980     case MFI_CMD_ABORT:
1981         frame_status = megasas_handle_abort(s, cmd);
1982         break;
1983     case MFI_CMD_PD_SCSI_IO:
1984     case MFI_CMD_LD_SCSI_IO:
1985         frame_status = megasas_handle_scsi(s, cmd, frame_cmd);
1986         break;
1987     case MFI_CMD_LD_READ:
1988     case MFI_CMD_LD_WRITE:
1989         frame_status = megasas_handle_io(s, cmd, frame_cmd);
1990         break;
1991     default:
1992         trace_megasas_unhandled_frame_cmd(cmd->index, frame_cmd);
1993         s->event_count++;
1994         break;
1995     }
1996     if (frame_status != MFI_STAT_INVALID_STATUS) {
1997         if (cmd->frame) {
1998             cmd->frame->header.cmd_status = frame_status;
1999         } else {
2000             megasas_frame_set_cmd_status(s, frame_addr, frame_status);
2001         }
2002         megasas_unmap_frame(s, cmd);
2003         megasas_complete_frame(s, cmd->context);
2004     }
2005 }
2006 
2007 static uint64_t megasas_mmio_read(void *opaque, hwaddr addr,
2008                                   unsigned size)
2009 {
2010     MegasasState *s = opaque;
2011     PCIDevice *pci_dev = PCI_DEVICE(s);
2012     MegasasBaseClass *base_class = MEGASAS_GET_CLASS(s);
2013     uint32_t retval = 0;
2014 
2015     switch (addr) {
2016     case MFI_IDB:
2017         retval = 0;
2018         trace_megasas_mmio_readl("MFI_IDB", retval);
2019         break;
2020     case MFI_OMSG0:
2021     case MFI_OSP0:
2022         retval = (msix_present(pci_dev) ? MFI_FWSTATE_MSIX_SUPPORTED : 0) |
2023             (s->fw_state & MFI_FWSTATE_MASK) |
2024             ((s->fw_sge & 0xff) << 16) |
2025             (s->fw_cmds & 0xFFFF);
2026         trace_megasas_mmio_readl(addr == MFI_OMSG0 ? "MFI_OMSG0" : "MFI_OSP0",
2027                                  retval);
2028         break;
2029     case MFI_OSTS:
2030         if (megasas_intr_enabled(s) && s->doorbell) {
2031             retval = base_class->osts;
2032         }
2033         trace_megasas_mmio_readl("MFI_OSTS", retval);
2034         break;
2035     case MFI_OMSK:
2036         retval = s->intr_mask;
2037         trace_megasas_mmio_readl("MFI_OMSK", retval);
2038         break;
2039     case MFI_ODCR0:
2040         retval = s->doorbell ? 1 : 0;
2041         trace_megasas_mmio_readl("MFI_ODCR0", retval);
2042         break;
2043     case MFI_DIAG:
2044         retval = s->diag;
2045         trace_megasas_mmio_readl("MFI_DIAG", retval);
2046         break;
2047     case MFI_OSP1:
2048         retval = 15;
2049         trace_megasas_mmio_readl("MFI_OSP1", retval);
2050         break;
2051     default:
2052         trace_megasas_mmio_invalid_readl(addr);
2053         break;
2054     }
2055     return retval;
2056 }
2057 
2058 static int adp_reset_seq[] = {0x00, 0x04, 0x0b, 0x02, 0x07, 0x0d};
2059 
2060 static void megasas_mmio_write(void *opaque, hwaddr addr,
2061                                uint64_t val, unsigned size)
2062 {
2063     MegasasState *s = opaque;
2064     PCIDevice *pci_dev = PCI_DEVICE(s);
2065     uint64_t frame_addr;
2066     uint32_t frame_count;
2067     int i;
2068 
2069     switch (addr) {
2070     case MFI_IDB:
2071         trace_megasas_mmio_writel("MFI_IDB", val);
2072         if (val & MFI_FWINIT_ABORT) {
2073             /* Abort all pending cmds */
2074             for (i = 0; i < s->fw_cmds; i++) {
2075                 megasas_abort_command(&s->frames[i]);
2076             }
2077         }
2078         if (val & MFI_FWINIT_READY) {
2079             /* move to FW READY */
2080             megasas_soft_reset(s);
2081         }
2082         if (val & MFI_FWINIT_MFIMODE) {
2083             /* discard MFIs */
2084         }
2085         if (val & MFI_FWINIT_STOP_ADP) {
2086             /* Terminal error, stop processing */
2087             s->fw_state = MFI_FWSTATE_FAULT;
2088         }
2089         break;
2090     case MFI_OMSK:
2091         trace_megasas_mmio_writel("MFI_OMSK", val);
2092         s->intr_mask = val;
2093         if (!megasas_intr_enabled(s) &&
2094             !msi_enabled(pci_dev) &&
2095             !msix_enabled(pci_dev)) {
2096             trace_megasas_irq_lower();
2097             pci_irq_deassert(pci_dev);
2098         }
2099         if (megasas_intr_enabled(s)) {
2100             if (msix_enabled(pci_dev)) {
2101                 trace_megasas_msix_enabled(0);
2102             } else if (msi_enabled(pci_dev)) {
2103                 trace_megasas_msi_enabled(0);
2104             } else {
2105                 trace_megasas_intr_enabled();
2106             }
2107         } else {
2108             trace_megasas_intr_disabled();
2109             megasas_soft_reset(s);
2110         }
2111         break;
2112     case MFI_ODCR0:
2113         trace_megasas_mmio_writel("MFI_ODCR0", val);
2114         s->doorbell = 0;
2115         if (megasas_intr_enabled(s)) {
2116             if (!msix_enabled(pci_dev) && !msi_enabled(pci_dev)) {
2117                 trace_megasas_irq_lower();
2118                 pci_irq_deassert(pci_dev);
2119             }
2120         }
2121         break;
2122     case MFI_IQPH:
2123         trace_megasas_mmio_writel("MFI_IQPH", val);
2124         /* Received high 32 bits of a 64 bit MFI frame address */
2125         s->frame_hi = val;
2126         break;
2127     case MFI_IQPL:
2128         trace_megasas_mmio_writel("MFI_IQPL", val);
2129         /* Received low 32 bits of a 64 bit MFI frame address */
2130         /* Fallthrough */
2131     case MFI_IQP:
2132         if (addr == MFI_IQP) {
2133             trace_megasas_mmio_writel("MFI_IQP", val);
2134             /* Received 64 bit MFI frame address */
2135             s->frame_hi = 0;
2136         }
2137         frame_addr = (val & ~0x1F);
2138         /* Add possible 64 bit offset */
2139         frame_addr |= ((uint64_t)s->frame_hi << 32);
2140         s->frame_hi = 0;
2141         frame_count = (val >> 1) & 0xF;
2142         megasas_handle_frame(s, frame_addr, frame_count);
2143         break;
2144     case MFI_SEQ:
2145         trace_megasas_mmio_writel("MFI_SEQ", val);
2146         /* Magic sequence to start ADP reset */
2147         if (adp_reset_seq[s->adp_reset++] == val) {
2148             if (s->adp_reset == 6) {
2149                 s->adp_reset = 0;
2150                 s->diag = MFI_DIAG_WRITE_ENABLE;
2151             }
2152         } else {
2153             s->adp_reset = 0;
2154             s->diag = 0;
2155         }
2156         break;
2157     case MFI_DIAG:
2158         trace_megasas_mmio_writel("MFI_DIAG", val);
2159         /* ADP reset */
2160         if ((s->diag & MFI_DIAG_WRITE_ENABLE) &&
2161             (val & MFI_DIAG_RESET_ADP)) {
2162             s->diag |= MFI_DIAG_RESET_ADP;
2163             megasas_soft_reset(s);
2164             s->adp_reset = 0;
2165             s->diag = 0;
2166         }
2167         break;
2168     default:
2169         trace_megasas_mmio_invalid_writel(addr, val);
2170         break;
2171     }
2172 }
2173 
2174 static const MemoryRegionOps megasas_mmio_ops = {
2175     .read = megasas_mmio_read,
2176     .write = megasas_mmio_write,
2177     .endianness = DEVICE_LITTLE_ENDIAN,
2178     .impl = {
2179         .min_access_size = 8,
2180         .max_access_size = 8,
2181     }
2182 };
2183 
2184 static uint64_t megasas_port_read(void *opaque, hwaddr addr,
2185                                   unsigned size)
2186 {
2187     return megasas_mmio_read(opaque, addr & 0xff, size);
2188 }
2189 
2190 static void megasas_port_write(void *opaque, hwaddr addr,
2191                                uint64_t val, unsigned size)
2192 {
2193     megasas_mmio_write(opaque, addr & 0xff, val, size);
2194 }
2195 
2196 static const MemoryRegionOps megasas_port_ops = {
2197     .read = megasas_port_read,
2198     .write = megasas_port_write,
2199     .endianness = DEVICE_LITTLE_ENDIAN,
2200     .impl = {
2201         .min_access_size = 4,
2202         .max_access_size = 4,
2203     }
2204 };
2205 
2206 static uint64_t megasas_queue_read(void *opaque, hwaddr addr,
2207                                    unsigned size)
2208 {
2209     return 0;
2210 }
2211 
2212 static void megasas_queue_write(void *opaque, hwaddr addr,
2213                                uint64_t val, unsigned size)
2214 {
2215     return;
2216 }
2217 
2218 static const MemoryRegionOps megasas_queue_ops = {
2219     .read = megasas_queue_read,
2220     .write = megasas_queue_write,
2221     .endianness = DEVICE_LITTLE_ENDIAN,
2222     .impl = {
2223         .min_access_size = 8,
2224         .max_access_size = 8,
2225     }
2226 };
2227 
2228 static void megasas_soft_reset(MegasasState *s)
2229 {
2230     int i;
2231     MegasasCmd *cmd;
2232 
2233     trace_megasas_reset(s->fw_state);
2234     for (i = 0; i < s->fw_cmds; i++) {
2235         cmd = &s->frames[i];
2236         megasas_abort_command(cmd);
2237     }
2238     if (s->fw_state == MFI_FWSTATE_READY) {
2239         BusChild *kid;
2240 
2241         /*
2242          * The EFI firmware doesn't handle UA,
2243          * so we need to clear the Power On/Reset UA
2244          * after the initial reset.
2245          */
2246         QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
2247             SCSIDevice *sdev = SCSI_DEVICE(kid->child);
2248 
2249             sdev->unit_attention = SENSE_CODE(NO_SENSE);
2250             scsi_device_unit_attention_reported(sdev);
2251         }
2252     }
2253     megasas_reset_frames(s);
2254     s->reply_queue_len = s->fw_cmds;
2255     s->reply_queue_pa = 0;
2256     s->consumer_pa = 0;
2257     s->producer_pa = 0;
2258     s->fw_state = MFI_FWSTATE_READY;
2259     s->doorbell = 0;
2260     s->intr_mask = MEGASAS_INTR_DISABLED_MASK;
2261     s->frame_hi = 0;
2262     s->flags &= ~MEGASAS_MASK_USE_QUEUE64;
2263     s->event_count++;
2264     s->boot_event = s->event_count;
2265 }
2266 
2267 static void megasas_scsi_reset(DeviceState *dev)
2268 {
2269     MegasasState *s = MEGASAS(dev);
2270 
2271     megasas_soft_reset(s);
2272 }
2273 
2274 static const VMStateDescription vmstate_megasas_gen1 = {
2275     .name = "megasas",
2276     .version_id = 0,
2277     .minimum_version_id = 0,
2278     .fields = (VMStateField[]) {
2279         VMSTATE_PCI_DEVICE(parent_obj, MegasasState),
2280         VMSTATE_MSIX(parent_obj, MegasasState),
2281 
2282         VMSTATE_UINT32(fw_state, MegasasState),
2283         VMSTATE_UINT32(intr_mask, MegasasState),
2284         VMSTATE_UINT32(doorbell, MegasasState),
2285         VMSTATE_UINT64(reply_queue_pa, MegasasState),
2286         VMSTATE_UINT64(consumer_pa, MegasasState),
2287         VMSTATE_UINT64(producer_pa, MegasasState),
2288         VMSTATE_END_OF_LIST()
2289     }
2290 };
2291 
2292 static const VMStateDescription vmstate_megasas_gen2 = {
2293     .name = "megasas-gen2",
2294     .version_id = 0,
2295     .minimum_version_id = 0,
2296     .minimum_version_id_old = 0,
2297     .fields      = (VMStateField[]) {
2298         VMSTATE_PCI_DEVICE(parent_obj, MegasasState),
2299         VMSTATE_MSIX(parent_obj, MegasasState),
2300 
2301         VMSTATE_UINT32(fw_state, MegasasState),
2302         VMSTATE_UINT32(intr_mask, MegasasState),
2303         VMSTATE_UINT32(doorbell, MegasasState),
2304         VMSTATE_UINT64(reply_queue_pa, MegasasState),
2305         VMSTATE_UINT64(consumer_pa, MegasasState),
2306         VMSTATE_UINT64(producer_pa, MegasasState),
2307         VMSTATE_END_OF_LIST()
2308     }
2309 };
2310 
2311 static void megasas_scsi_uninit(PCIDevice *d)
2312 {
2313     MegasasState *s = MEGASAS(d);
2314 
2315     if (megasas_use_msix(s)) {
2316         msix_uninit(d, &s->mmio_io, &s->mmio_io);
2317     }
2318     msi_uninit(d);
2319 }
2320 
2321 static const struct SCSIBusInfo megasas_scsi_info = {
2322     .tcq = true,
2323     .max_target = MFI_MAX_LD,
2324     .max_lun = 255,
2325 
2326     .transfer_data = megasas_xfer_complete,
2327     .get_sg_list = megasas_get_sg_list,
2328     .complete = megasas_command_complete,
2329     .cancel = megasas_command_cancelled,
2330 };
2331 
2332 static void megasas_scsi_realize(PCIDevice *dev, Error **errp)
2333 {
2334     MegasasState *s = MEGASAS(dev);
2335     MegasasBaseClass *b = MEGASAS_GET_CLASS(s);
2336     uint8_t *pci_conf;
2337     int i, bar_type;
2338     Error *err = NULL;
2339     int ret;
2340 
2341     pci_conf = dev->config;
2342 
2343     /* PCI latency timer = 0 */
2344     pci_conf[PCI_LATENCY_TIMER] = 0;
2345     /* Interrupt pin 1 */
2346     pci_conf[PCI_INTERRUPT_PIN] = 0x01;
2347 
2348     if (s->msi != ON_OFF_AUTO_OFF) {
2349         ret = msi_init(dev, 0x50, 1, true, false, &err);
2350         /* Any error other than -ENOTSUP(board's MSI support is broken)
2351          * is a programming error */
2352         assert(!ret || ret == -ENOTSUP);
2353         if (ret && s->msi == ON_OFF_AUTO_ON) {
2354             /* Can't satisfy user's explicit msi=on request, fail */
2355             error_append_hint(&err, "You have to use msi=auto (default) or "
2356                     "msi=off with this machine type.\n");
2357             error_propagate(errp, err);
2358             return;
2359         } else if (ret) {
2360             /* With msi=auto, we fall back to MSI off silently */
2361             s->msi = ON_OFF_AUTO_OFF;
2362             error_free(err);
2363         }
2364     }
2365 
2366     memory_region_init_io(&s->mmio_io, OBJECT(s), &megasas_mmio_ops, s,
2367                           "megasas-mmio", 0x4000);
2368     memory_region_init_io(&s->port_io, OBJECT(s), &megasas_port_ops, s,
2369                           "megasas-io", 256);
2370     memory_region_init_io(&s->queue_io, OBJECT(s), &megasas_queue_ops, s,
2371                           "megasas-queue", 0x40000);
2372 
2373     if (megasas_use_msix(s) &&
2374         msix_init(dev, 15, &s->mmio_io, b->mmio_bar, 0x2000,
2375                   &s->mmio_io, b->mmio_bar, 0x3800, 0x68, NULL)) {
2376         /* TODO: check msix_init's error, and should fail on msix=on */
2377         s->msix = ON_OFF_AUTO_OFF;
2378     }
2379 
2380     if (pci_is_express(dev)) {
2381         pcie_endpoint_cap_init(dev, 0xa0);
2382     }
2383 
2384     bar_type = PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64;
2385     pci_register_bar(dev, b->ioport_bar,
2386                      PCI_BASE_ADDRESS_SPACE_IO, &s->port_io);
2387     pci_register_bar(dev, b->mmio_bar, bar_type, &s->mmio_io);
2388     pci_register_bar(dev, 3, bar_type, &s->queue_io);
2389 
2390     if (megasas_use_msix(s)) {
2391         msix_vector_use(dev, 0);
2392     }
2393 
2394     s->fw_state = MFI_FWSTATE_READY;
2395     if (!s->sas_addr) {
2396         s->sas_addr = ((NAA_LOCALLY_ASSIGNED_ID << 24) |
2397                        IEEE_COMPANY_LOCALLY_ASSIGNED) << 36;
2398         s->sas_addr |= pci_dev_bus_num(dev) << 16;
2399         s->sas_addr |= PCI_SLOT(dev->devfn) << 8;
2400         s->sas_addr |= PCI_FUNC(dev->devfn);
2401     }
2402     if (!s->hba_serial) {
2403         s->hba_serial = g_strdup(MEGASAS_HBA_SERIAL);
2404     }
2405     if (s->fw_sge >= MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE) {
2406         s->fw_sge = MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE;
2407     } else if (s->fw_sge >= 128 - MFI_PASS_FRAME_SIZE) {
2408         s->fw_sge = 128 - MFI_PASS_FRAME_SIZE;
2409     } else {
2410         s->fw_sge = 64 - MFI_PASS_FRAME_SIZE;
2411     }
2412     if (s->fw_cmds > MEGASAS_MAX_FRAMES) {
2413         s->fw_cmds = MEGASAS_MAX_FRAMES;
2414     }
2415     trace_megasas_init(s->fw_sge, s->fw_cmds,
2416                        megasas_is_jbod(s) ? "jbod" : "raid");
2417 
2418     if (megasas_is_jbod(s)) {
2419         s->fw_luns = MFI_MAX_SYS_PDS;
2420     } else {
2421         s->fw_luns = MFI_MAX_LD;
2422     }
2423     s->producer_pa = 0;
2424     s->consumer_pa = 0;
2425     for (i = 0; i < s->fw_cmds; i++) {
2426         s->frames[i].index = i;
2427         s->frames[i].context = -1;
2428         s->frames[i].pa = 0;
2429         s->frames[i].state = s;
2430     }
2431 
2432     scsi_bus_init(&s->bus, sizeof(s->bus), DEVICE(dev), &megasas_scsi_info);
2433 }
2434 
2435 static Property megasas_properties_gen1[] = {
2436     DEFINE_PROP_UINT32("max_sge", MegasasState, fw_sge,
2437                        MEGASAS_DEFAULT_SGE),
2438     DEFINE_PROP_UINT32("max_cmds", MegasasState, fw_cmds,
2439                        MEGASAS_DEFAULT_FRAMES),
2440     DEFINE_PROP_STRING("hba_serial", MegasasState, hba_serial),
2441     DEFINE_PROP_UINT64("sas_address", MegasasState, sas_addr, 0),
2442     DEFINE_PROP_ON_OFF_AUTO("msi", MegasasState, msi, ON_OFF_AUTO_AUTO),
2443     DEFINE_PROP_ON_OFF_AUTO("msix", MegasasState, msix, ON_OFF_AUTO_AUTO),
2444     DEFINE_PROP_BIT("use_jbod", MegasasState, flags,
2445                     MEGASAS_FLAG_USE_JBOD, false),
2446     DEFINE_PROP_END_OF_LIST(),
2447 };
2448 
2449 static Property megasas_properties_gen2[] = {
2450     DEFINE_PROP_UINT32("max_sge", MegasasState, fw_sge,
2451                        MEGASAS_DEFAULT_SGE),
2452     DEFINE_PROP_UINT32("max_cmds", MegasasState, fw_cmds,
2453                        MEGASAS_GEN2_DEFAULT_FRAMES),
2454     DEFINE_PROP_STRING("hba_serial", MegasasState, hba_serial),
2455     DEFINE_PROP_UINT64("sas_address", MegasasState, sas_addr, 0),
2456     DEFINE_PROP_ON_OFF_AUTO("msi", MegasasState, msi, ON_OFF_AUTO_AUTO),
2457     DEFINE_PROP_ON_OFF_AUTO("msix", MegasasState, msix, ON_OFF_AUTO_AUTO),
2458     DEFINE_PROP_BIT("use_jbod", MegasasState, flags,
2459                     MEGASAS_FLAG_USE_JBOD, false),
2460     DEFINE_PROP_END_OF_LIST(),
2461 };
2462 
2463 typedef struct MegasasInfo {
2464     const char *name;
2465     const char *desc;
2466     const char *product_name;
2467     const char *product_version;
2468     uint16_t device_id;
2469     uint16_t subsystem_id;
2470     int ioport_bar;
2471     int mmio_bar;
2472     int osts;
2473     const VMStateDescription *vmsd;
2474     Property *props;
2475     InterfaceInfo *interfaces;
2476 } MegasasInfo;
2477 
2478 static struct MegasasInfo megasas_devices[] = {
2479     {
2480         .name = TYPE_MEGASAS_GEN1,
2481         .desc = "LSI MegaRAID SAS 1078",
2482         .product_name = "LSI MegaRAID SAS 8708EM2",
2483         .product_version = MEGASAS_VERSION_GEN1,
2484         .device_id = PCI_DEVICE_ID_LSI_SAS1078,
2485         .subsystem_id = 0x1013,
2486         .ioport_bar = 2,
2487         .mmio_bar = 0,
2488         .osts = MFI_1078_RM | 1,
2489         .vmsd = &vmstate_megasas_gen1,
2490         .props = megasas_properties_gen1,
2491         .interfaces = (InterfaceInfo[]) {
2492             { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2493             { },
2494         },
2495     },{
2496         .name = TYPE_MEGASAS_GEN2,
2497         .desc = "LSI MegaRAID SAS 2108",
2498         .product_name = "LSI MegaRAID SAS 9260-8i",
2499         .product_version = MEGASAS_VERSION_GEN2,
2500         .device_id = PCI_DEVICE_ID_LSI_SAS0079,
2501         .subsystem_id = 0x9261,
2502         .ioport_bar = 0,
2503         .mmio_bar = 1,
2504         .osts = MFI_GEN2_RM,
2505         .vmsd = &vmstate_megasas_gen2,
2506         .props = megasas_properties_gen2,
2507         .interfaces = (InterfaceInfo[]) {
2508             { INTERFACE_PCIE_DEVICE },
2509             { }
2510         },
2511     }
2512 };
2513 
2514 static void megasas_class_init(ObjectClass *oc, void *data)
2515 {
2516     DeviceClass *dc = DEVICE_CLASS(oc);
2517     PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc);
2518     MegasasBaseClass *e = MEGASAS_CLASS(oc);
2519     const MegasasInfo *info = data;
2520 
2521     pc->realize = megasas_scsi_realize;
2522     pc->exit = megasas_scsi_uninit;
2523     pc->vendor_id = PCI_VENDOR_ID_LSI_LOGIC;
2524     pc->device_id = info->device_id;
2525     pc->subsystem_vendor_id = PCI_VENDOR_ID_LSI_LOGIC;
2526     pc->subsystem_id = info->subsystem_id;
2527     pc->class_id = PCI_CLASS_STORAGE_RAID;
2528     e->mmio_bar = info->mmio_bar;
2529     e->ioport_bar = info->ioport_bar;
2530     e->osts = info->osts;
2531     e->product_name = info->product_name;
2532     e->product_version = info->product_version;
2533     device_class_set_props(dc, info->props);
2534     dc->reset = megasas_scsi_reset;
2535     dc->vmsd = info->vmsd;
2536     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2537     dc->desc = info->desc;
2538 }
2539 
2540 static const TypeInfo megasas_info = {
2541     .name  = TYPE_MEGASAS_BASE,
2542     .parent = TYPE_PCI_DEVICE,
2543     .instance_size = sizeof(MegasasState),
2544     .class_size = sizeof(MegasasBaseClass),
2545     .abstract = true,
2546 };
2547 
2548 static void megasas_register_types(void)
2549 {
2550     int i;
2551 
2552     type_register_static(&megasas_info);
2553     for (i = 0; i < ARRAY_SIZE(megasas_devices); i++) {
2554         const MegasasInfo *info = &megasas_devices[i];
2555         TypeInfo type_info = {};
2556 
2557         type_info.name = info->name;
2558         type_info.parent = TYPE_MEGASAS_BASE;
2559         type_info.class_data = (void *)info;
2560         type_info.class_init = megasas_class_init;
2561         type_info.interfaces = info->interfaces;
2562 
2563         type_register(&type_info);
2564     }
2565 }
2566 
2567 type_init(megasas_register_types)
2568