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