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