xref: /openbmc/qemu/hw/scsi/spapr_vscsi.c (revision 5accc840)
1 /*
2  * QEMU PowerPC pSeries Logical Partition (aka sPAPR) hardware System Emulator
3  *
4  * PAPR Virtual SCSI, aka ibmvscsi
5  *
6  * Copyright (c) 2010,2011 Benjamin Herrenschmidt, IBM Corporation.
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a copy
9  * of this software and associated documentation files (the "Software"), to deal
10  * in the Software without restriction, including without limitation the rights
11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12  * copies of the Software, and to permit persons to whom the Software is
13  * furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24  * THE SOFTWARE.
25  *
26  * TODO:
27  *
28  *  - Cleanups :-)
29  *  - Sort out better how to assign devices to VSCSI instances
30  *  - Fix residual counts
31  *  - Add indirect descriptors support
32  *  - Maybe do autosense (PAPR seems to mandate it, linux doesn't care)
33  */
34 #include "hw/hw.h"
35 #include "hw/scsi/scsi.h"
36 #include "block/scsi.h"
37 #include "srp.h"
38 #include "hw/qdev.h"
39 #include "hw/ppc/spapr.h"
40 #include "hw/ppc/spapr_vio.h"
41 #include "viosrp.h"
42 
43 #include <libfdt.h>
44 
45 /*#define DEBUG_VSCSI*/
46 
47 #ifdef DEBUG_VSCSI
48 #define DPRINTF(fmt, ...) \
49     do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
50 #else
51 #define DPRINTF(fmt, ...) \
52     do { } while (0)
53 #endif
54 
55 /*
56  * Virtual SCSI device
57  */
58 
59 /* Random numbers */
60 #define VSCSI_MAX_SECTORS       4096
61 #define VSCSI_REQ_LIMIT         24
62 
63 #define SCSI_SENSE_BUF_SIZE     96
64 #define SRP_RSP_SENSE_DATA_LEN  18
65 
66 typedef union vscsi_crq {
67     struct viosrp_crq s;
68     uint8_t raw[16];
69 } vscsi_crq;
70 
71 typedef struct vscsi_req {
72     vscsi_crq               crq;
73     union viosrp_iu         iu;
74 
75     /* SCSI request tracking */
76     SCSIRequest             *sreq;
77     uint32_t                qtag; /* qemu tag != srp tag */
78     bool                    active;
79     uint32_t                data_len;
80     bool                    writing;
81     uint32_t                senselen;
82     uint8_t                 sense[SCSI_SENSE_BUF_SIZE];
83 
84     /* RDMA related bits */
85     uint8_t                 dma_fmt;
86     uint16_t                local_desc;
87     uint16_t                total_desc;
88     uint16_t                cdb_offset;
89     uint16_t                cur_desc_num;
90     uint16_t                cur_desc_offset;
91 } vscsi_req;
92 
93 #define TYPE_VIO_SPAPR_VSCSI_DEVICE "spapr-vscsi"
94 #define VIO_SPAPR_VSCSI_DEVICE(obj) \
95      OBJECT_CHECK(VSCSIState, (obj), TYPE_VIO_SPAPR_VSCSI_DEVICE)
96 
97 typedef struct {
98     VIOsPAPRDevice vdev;
99     SCSIBus bus;
100     vscsi_req reqs[VSCSI_REQ_LIMIT];
101 } VSCSIState;
102 
103 static struct vscsi_req *vscsi_get_req(VSCSIState *s)
104 {
105     vscsi_req *req;
106     int i;
107 
108     for (i = 0; i < VSCSI_REQ_LIMIT; i++) {
109         req = &s->reqs[i];
110         if (!req->active) {
111             memset(req, 0, sizeof(*req));
112             req->qtag = i;
113             req->active = 1;
114             return req;
115         }
116     }
117     return NULL;
118 }
119 
120 static void vscsi_put_req(vscsi_req *req)
121 {
122     if (req->sreq != NULL) {
123         scsi_req_unref(req->sreq);
124     }
125     req->sreq = NULL;
126     req->active = 0;
127 }
128 
129 static SCSIDevice *vscsi_device_find(SCSIBus *bus, uint64_t srp_lun, int *lun)
130 {
131     int channel = 0, id = 0;
132 
133 retry:
134     switch (srp_lun >> 62) {
135     case 0:
136         if ((srp_lun >> 56) != 0) {
137             channel = (srp_lun >> 56) & 0x3f;
138             id = (srp_lun >> 48) & 0xff;
139             srp_lun <<= 16;
140             goto retry;
141         }
142         *lun = (srp_lun >> 48) & 0xff;
143         break;
144 
145     case 1:
146         *lun = (srp_lun >> 48) & 0x3fff;
147         break;
148     case 2:
149         channel = (srp_lun >> 53) & 0x7;
150         id = (srp_lun >> 56) & 0x3f;
151         *lun = (srp_lun >> 48) & 0x1f;
152         break;
153     case 3:
154         *lun = -1;
155         return NULL;
156     default:
157         abort();
158     }
159 
160     return scsi_device_find(bus, channel, id, *lun);
161 }
162 
163 static int vscsi_send_iu(VSCSIState *s, vscsi_req *req,
164                          uint64_t length, uint8_t format)
165 {
166     long rc, rc1;
167 
168     /* First copy the SRP */
169     rc = spapr_vio_dma_write(&s->vdev, req->crq.s.IU_data_ptr,
170                              &req->iu, length);
171     if (rc) {
172         fprintf(stderr, "vscsi_send_iu: DMA write failure !\n");
173     }
174 
175     req->crq.s.valid = 0x80;
176     req->crq.s.format = format;
177     req->crq.s.reserved = 0x00;
178     req->crq.s.timeout = cpu_to_be16(0x0000);
179     req->crq.s.IU_length = cpu_to_be16(length);
180     req->crq.s.IU_data_ptr = req->iu.srp.rsp.tag; /* right byte order */
181 
182     if (rc == 0) {
183         req->crq.s.status = 0x99; /* Just needs to be non-zero */
184     } else {
185         req->crq.s.status = 0x00;
186     }
187 
188     rc1 = spapr_vio_send_crq(&s->vdev, req->crq.raw);
189     if (rc1) {
190         fprintf(stderr, "vscsi_send_iu: Error sending response\n");
191         return rc1;
192     }
193 
194     return rc;
195 }
196 
197 static void vscsi_makeup_sense(VSCSIState *s, vscsi_req *req,
198                                uint8_t key, uint8_t asc, uint8_t ascq)
199 {
200     req->senselen = SRP_RSP_SENSE_DATA_LEN;
201 
202     /* Valid bit and 'current errors' */
203     req->sense[0] = (0x1 << 7 | 0x70);
204     /* Sense key */
205     req->sense[2] = key;
206     /* Additional sense length */
207     req->sense[7] = 0xa; /* 10 bytes */
208     /* Additional sense code */
209     req->sense[12] = asc;
210     req->sense[13] = ascq;
211 }
212 
213 static int vscsi_send_rsp(VSCSIState *s, vscsi_req *req,
214                           uint8_t status, int32_t res_in, int32_t res_out)
215 {
216     union viosrp_iu *iu = &req->iu;
217     uint64_t tag = iu->srp.rsp.tag;
218     int total_len = sizeof(iu->srp.rsp);
219     uint8_t sol_not = iu->srp.cmd.sol_not;
220 
221     DPRINTF("VSCSI: Sending resp status: 0x%x, "
222             "res_in: %d, res_out: %d\n", status, res_in, res_out);
223 
224     memset(iu, 0, sizeof(struct srp_rsp));
225     iu->srp.rsp.opcode = SRP_RSP;
226     iu->srp.rsp.req_lim_delta = cpu_to_be32(1);
227     iu->srp.rsp.tag = tag;
228 
229     /* Handle residuals */
230     if (res_in < 0) {
231         iu->srp.rsp.flags |= SRP_RSP_FLAG_DIUNDER;
232         res_in = -res_in;
233     } else if (res_in) {
234         iu->srp.rsp.flags |= SRP_RSP_FLAG_DIOVER;
235     }
236     if (res_out < 0) {
237         iu->srp.rsp.flags |= SRP_RSP_FLAG_DOUNDER;
238         res_out = -res_out;
239     } else if (res_out) {
240         iu->srp.rsp.flags |= SRP_RSP_FLAG_DOOVER;
241     }
242     iu->srp.rsp.data_in_res_cnt = cpu_to_be32(res_in);
243     iu->srp.rsp.data_out_res_cnt = cpu_to_be32(res_out);
244 
245     /* We don't do response data */
246     /* iu->srp.rsp.flags &= ~SRP_RSP_FLAG_RSPVALID; */
247     iu->srp.rsp.resp_data_len = cpu_to_be32(0);
248 
249     /* Handle success vs. failure */
250     iu->srp.rsp.status = status;
251     if (status) {
252         iu->srp.rsp.sol_not = (sol_not & 0x04) >> 2;
253         if (req->senselen) {
254             req->iu.srp.rsp.flags |= SRP_RSP_FLAG_SNSVALID;
255             req->iu.srp.rsp.sense_data_len = cpu_to_be32(req->senselen);
256             memcpy(req->iu.srp.rsp.data, req->sense, req->senselen);
257             total_len += req->senselen;
258         }
259     } else {
260         iu->srp.rsp.sol_not = (sol_not & 0x02) >> 1;
261     }
262 
263     vscsi_send_iu(s, req, total_len, VIOSRP_SRP_FORMAT);
264     return 0;
265 }
266 
267 static inline struct srp_direct_buf vscsi_swap_desc(struct srp_direct_buf desc)
268 {
269     desc.va = be64_to_cpu(desc.va);
270     desc.len = be32_to_cpu(desc.len);
271     return desc;
272 }
273 
274 static int vscsi_fetch_desc(VSCSIState *s, struct vscsi_req *req,
275                             unsigned n, unsigned buf_offset,
276                             struct srp_direct_buf *ret)
277 {
278     struct srp_cmd *cmd = &req->iu.srp.cmd;
279 
280     switch (req->dma_fmt) {
281     case SRP_NO_DATA_DESC: {
282         DPRINTF("VSCSI: no data descriptor\n");
283         return 0;
284     }
285     case SRP_DATA_DESC_DIRECT: {
286         memcpy(ret, cmd->add_data + req->cdb_offset, sizeof(*ret));
287         assert(req->cur_desc_num == 0);
288         DPRINTF("VSCSI: direct segment\n");
289         break;
290     }
291     case SRP_DATA_DESC_INDIRECT: {
292         struct srp_indirect_buf *tmp = (struct srp_indirect_buf *)
293                                        (cmd->add_data + req->cdb_offset);
294         if (n < req->local_desc) {
295             *ret = tmp->desc_list[n];
296             DPRINTF("VSCSI: indirect segment local tag=0x%x desc#%d/%d\n",
297                     req->qtag, n, req->local_desc);
298 
299         } else if (n < req->total_desc) {
300             int rc;
301             struct srp_direct_buf tbl_desc = vscsi_swap_desc(tmp->table_desc);
302             unsigned desc_offset = n * sizeof(struct srp_direct_buf);
303 
304             if (desc_offset >= tbl_desc.len) {
305                 DPRINTF("VSCSI:   #%d is ouf of range (%d bytes)\n",
306                         n, desc_offset);
307                 return -1;
308             }
309             rc = spapr_vio_dma_read(&s->vdev, tbl_desc.va + desc_offset,
310                                     ret, sizeof(struct srp_direct_buf));
311             if (rc) {
312                 DPRINTF("VSCSI: spapr_vio_dma_read -> %d reading ext_desc\n",
313                         rc);
314                 return -1;
315             }
316             DPRINTF("VSCSI: indirect segment ext. tag=0x%x desc#%d/%d { va=%"PRIx64" len=%x }\n",
317                     req->qtag, n, req->total_desc, tbl_desc.va, tbl_desc.len);
318         } else {
319             DPRINTF("VSCSI:   Out of descriptors !\n");
320             return 0;
321         }
322         break;
323     }
324     default:
325         fprintf(stderr, "VSCSI:   Unknown format %x\n", req->dma_fmt);
326         return -1;
327     }
328 
329     *ret = vscsi_swap_desc(*ret);
330     if (buf_offset > ret->len) {
331         DPRINTF("   offset=%x is out of a descriptor #%d boundary=%x\n",
332                 buf_offset, req->cur_desc_num, ret->len);
333         return -1;
334     }
335     ret->va += buf_offset;
336     ret->len -= buf_offset;
337 
338     DPRINTF("   cur=%d offs=%x ret { va=%"PRIx64" len=%x }\n",
339             req->cur_desc_num, req->cur_desc_offset, ret->va, ret->len);
340 
341     return ret->len ? 1 : 0;
342 }
343 
344 static int vscsi_srp_direct_data(VSCSIState *s, vscsi_req *req,
345                                  uint8_t *buf, uint32_t len)
346 {
347     struct srp_direct_buf md;
348     uint32_t llen;
349     int rc = 0;
350 
351     rc = vscsi_fetch_desc(s, req, req->cur_desc_num, req->cur_desc_offset, &md);
352     if (rc < 0) {
353         return -1;
354     } else if (rc == 0) {
355         return 0;
356     }
357 
358     llen = MIN(len, md.len);
359     if (llen) {
360         if (req->writing) { /* writing = to device = reading from memory */
361             rc = spapr_vio_dma_read(&s->vdev, md.va, buf, llen);
362         } else {
363             rc = spapr_vio_dma_write(&s->vdev, md.va, buf, llen);
364         }
365     }
366 
367     if (rc) {
368         return -1;
369     }
370     req->cur_desc_offset += llen;
371 
372     return llen;
373 }
374 
375 static int vscsi_srp_indirect_data(VSCSIState *s, vscsi_req *req,
376                                    uint8_t *buf, uint32_t len)
377 {
378     struct srp_direct_buf md;
379     int rc = 0;
380     uint32_t llen, total = 0;
381 
382     DPRINTF("VSCSI: indirect segment 0x%x bytes\n", len);
383 
384     /* While we have data ... */
385     while (len) {
386         rc = vscsi_fetch_desc(s, req, req->cur_desc_num, req->cur_desc_offset, &md);
387         if (rc < 0) {
388             return -1;
389         } else if (rc == 0) {
390             break;
391         }
392 
393         /* Perform transfer */
394         llen = MIN(len, md.len);
395         if (req->writing) { /* writing = to device = reading from memory */
396             rc = spapr_vio_dma_read(&s->vdev, md.va, buf, llen);
397         } else {
398             rc = spapr_vio_dma_write(&s->vdev, md.va, buf, llen);
399         }
400         if (rc) {
401             DPRINTF("VSCSI: spapr_vio_dma_r/w(%d) -> %d\n", req->writing, rc);
402             break;
403         }
404         DPRINTF("VSCSI:     data: %02x %02x %02x %02x...\n",
405                 buf[0], buf[1], buf[2], buf[3]);
406 
407         len -= llen;
408         buf += llen;
409 
410         total += llen;
411 
412         /* Update current position in the current descriptor */
413         req->cur_desc_offset += llen;
414         if (md.len == llen) {
415             /* Go to the next descriptor if the current one finished */
416             ++req->cur_desc_num;
417             req->cur_desc_offset = 0;
418         }
419     }
420 
421     return rc ? -1 : total;
422 }
423 
424 static int vscsi_srp_transfer_data(VSCSIState *s, vscsi_req *req,
425                                    int writing, uint8_t *buf, uint32_t len)
426 {
427     int err = 0;
428 
429     switch (req->dma_fmt) {
430     case SRP_NO_DATA_DESC:
431         DPRINTF("VSCSI: no data desc transfer, skipping 0x%x bytes\n", len);
432         break;
433     case SRP_DATA_DESC_DIRECT:
434         err = vscsi_srp_direct_data(s, req, buf, len);
435         break;
436     case SRP_DATA_DESC_INDIRECT:
437         err = vscsi_srp_indirect_data(s, req, buf, len);
438         break;
439     }
440     return err;
441 }
442 
443 /* Bits from linux srp */
444 static int data_out_desc_size(struct srp_cmd *cmd)
445 {
446     int size = 0;
447     uint8_t fmt = cmd->buf_fmt >> 4;
448 
449     switch (fmt) {
450     case SRP_NO_DATA_DESC:
451         break;
452     case SRP_DATA_DESC_DIRECT:
453         size = sizeof(struct srp_direct_buf);
454         break;
455     case SRP_DATA_DESC_INDIRECT:
456         size = sizeof(struct srp_indirect_buf) +
457             sizeof(struct srp_direct_buf)*cmd->data_out_desc_cnt;
458         break;
459     default:
460         break;
461     }
462     return size;
463 }
464 
465 static int vscsi_preprocess_desc(vscsi_req *req)
466 {
467     struct srp_cmd *cmd = &req->iu.srp.cmd;
468 
469     req->cdb_offset = cmd->add_cdb_len & ~3;
470 
471     if (req->writing) {
472         req->dma_fmt = cmd->buf_fmt >> 4;
473     } else {
474         req->cdb_offset += data_out_desc_size(cmd);
475         req->dma_fmt = cmd->buf_fmt & ((1U << 4) - 1);
476     }
477 
478     switch (req->dma_fmt) {
479     case SRP_NO_DATA_DESC:
480         break;
481     case SRP_DATA_DESC_DIRECT:
482         req->total_desc = req->local_desc = 1;
483         break;
484     case SRP_DATA_DESC_INDIRECT: {
485         struct srp_indirect_buf *ind_tmp = (struct srp_indirect_buf *)
486                 (cmd->add_data + req->cdb_offset);
487 
488         req->total_desc = be32_to_cpu(ind_tmp->table_desc.len) /
489                           sizeof(struct srp_direct_buf);
490         req->local_desc = req->writing ? cmd->data_out_desc_cnt :
491                           cmd->data_in_desc_cnt;
492         break;
493     }
494     default:
495         fprintf(stderr,
496                 "vscsi_preprocess_desc: Unknown format %x\n", req->dma_fmt);
497         return -1;
498     }
499 
500     return 0;
501 }
502 
503 /* Callback to indicate that the SCSI layer has completed a transfer.  */
504 static void vscsi_transfer_data(SCSIRequest *sreq, uint32_t len)
505 {
506     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(sreq->bus->qbus.parent);
507     vscsi_req *req = sreq->hba_private;
508     uint8_t *buf;
509     int rc = 0;
510 
511     DPRINTF("VSCSI: SCSI xfer complete tag=0x%x len=0x%x, req=%p\n",
512             sreq->tag, len, req);
513     if (req == NULL) {
514         fprintf(stderr, "VSCSI: Can't find request for tag 0x%x\n", sreq->tag);
515         return;
516     }
517 
518     if (len) {
519         buf = scsi_req_get_buf(sreq);
520         rc = vscsi_srp_transfer_data(s, req, req->writing, buf, len);
521     }
522     if (rc < 0) {
523         fprintf(stderr, "VSCSI: RDMA error rc=%d!\n", rc);
524         vscsi_makeup_sense(s, req, HARDWARE_ERROR, 0, 0);
525         scsi_req_abort(req->sreq, CHECK_CONDITION);
526         return;
527     }
528 
529     /* Start next chunk */
530     req->data_len -= rc;
531     scsi_req_continue(sreq);
532 }
533 
534 /* Callback to indicate that the SCSI layer has completed a transfer.  */
535 static void vscsi_command_complete(SCSIRequest *sreq, uint32_t status, size_t resid)
536 {
537     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(sreq->bus->qbus.parent);
538     vscsi_req *req = sreq->hba_private;
539     int32_t res_in = 0, res_out = 0;
540 
541     DPRINTF("VSCSI: SCSI cmd complete, tag=0x%x status=0x%x, req=%p\n",
542             sreq->tag, status, req);
543     if (req == NULL) {
544         fprintf(stderr, "VSCSI: Can't find request for tag 0x%x\n", sreq->tag);
545         return;
546     }
547 
548     if (status == CHECK_CONDITION) {
549         req->senselen = scsi_req_get_sense(req->sreq, req->sense,
550                                            sizeof(req->sense));
551         DPRINTF("VSCSI: Sense data, %d bytes:\n", req->senselen);
552         DPRINTF("       %02x  %02x  %02x  %02x  %02x  %02x  %02x  %02x\n",
553                 req->sense[0], req->sense[1], req->sense[2], req->sense[3],
554                 req->sense[4], req->sense[5], req->sense[6], req->sense[7]);
555         DPRINTF("       %02x  %02x  %02x  %02x  %02x  %02x  %02x  %02x\n",
556                 req->sense[8], req->sense[9], req->sense[10], req->sense[11],
557                 req->sense[12], req->sense[13], req->sense[14], req->sense[15]);
558     }
559 
560     DPRINTF("VSCSI: Command complete err=%d\n", status);
561     if (status == 0) {
562         /* We handle overflows, not underflows for normal commands,
563          * but hopefully nobody cares
564          */
565         if (req->writing) {
566             res_out = req->data_len;
567         } else {
568             res_in = req->data_len;
569         }
570     }
571     vscsi_send_rsp(s, req, status, res_in, res_out);
572     vscsi_put_req(req);
573 }
574 
575 static void vscsi_request_cancelled(SCSIRequest *sreq)
576 {
577     vscsi_req *req = sreq->hba_private;
578 
579     vscsi_put_req(req);
580 }
581 
582 static const VMStateDescription vmstate_spapr_vscsi_req = {
583     .name = "spapr_vscsi_req",
584     .version_id = 1,
585     .minimum_version_id = 1,
586     .minimum_version_id_old = 1,
587     .fields      = (VMStateField []) {
588         VMSTATE_BUFFER(crq.raw, vscsi_req),
589         VMSTATE_BUFFER(iu.srp.reserved, vscsi_req),
590         VMSTATE_UINT32(qtag, vscsi_req),
591         VMSTATE_BOOL(active, vscsi_req),
592         VMSTATE_UINT32(data_len, vscsi_req),
593         VMSTATE_BOOL(writing, vscsi_req),
594         VMSTATE_UINT32(senselen, vscsi_req),
595         VMSTATE_BUFFER(sense, vscsi_req),
596         VMSTATE_UINT8(dma_fmt, vscsi_req),
597         VMSTATE_UINT16(local_desc, vscsi_req),
598         VMSTATE_UINT16(total_desc, vscsi_req),
599         VMSTATE_UINT16(cdb_offset, vscsi_req),
600       /*Restart SCSI request from the beginning for now */
601       /*VMSTATE_UINT16(cur_desc_num, vscsi_req),
602         VMSTATE_UINT16(cur_desc_offset, vscsi_req),*/
603         VMSTATE_END_OF_LIST()
604     },
605 };
606 
607 static void vscsi_save_request(QEMUFile *f, SCSIRequest *sreq)
608 {
609     vscsi_req *req = sreq->hba_private;
610     assert(req->active);
611 
612     vmstate_save_state(f, &vmstate_spapr_vscsi_req, req);
613 
614     DPRINTF("VSCSI: saving tag=%u, current desc#%d, offset=%x\n",
615             req->qtag, req->cur_desc_num, req->cur_desc_offset);
616 }
617 
618 static void *vscsi_load_request(QEMUFile *f, SCSIRequest *sreq)
619 {
620     SCSIBus *bus = sreq->bus;
621     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(bus->qbus.parent);
622     vscsi_req *req;
623     int rc;
624 
625     assert(sreq->tag < VSCSI_REQ_LIMIT);
626     req = &s->reqs[sreq->tag];
627     assert(!req->active);
628 
629     memset(req, 0, sizeof(*req));
630     rc = vmstate_load_state(f, &vmstate_spapr_vscsi_req, req, 1);
631     if (rc) {
632         fprintf(stderr, "VSCSI: failed loading request tag#%u\n", sreq->tag);
633         return NULL;
634     }
635     assert(req->active);
636 
637     req->sreq = scsi_req_ref(sreq);
638 
639     DPRINTF("VSCSI: restoring tag=%u, current desc#%d, offset=%x\n",
640             req->qtag, req->cur_desc_num, req->cur_desc_offset);
641 
642     return req;
643 }
644 
645 static void vscsi_process_login(VSCSIState *s, vscsi_req *req)
646 {
647     union viosrp_iu *iu = &req->iu;
648     struct srp_login_rsp *rsp = &iu->srp.login_rsp;
649     uint64_t tag = iu->srp.rsp.tag;
650 
651     DPRINTF("VSCSI: Got login, sendin response !\n");
652 
653     /* TODO handle case that requested size is wrong and
654      * buffer format is wrong
655      */
656     memset(iu, 0, sizeof(struct srp_login_rsp));
657     rsp->opcode = SRP_LOGIN_RSP;
658     /* Don't advertise quite as many request as we support to
659      * keep room for management stuff etc...
660      */
661     rsp->req_lim_delta = cpu_to_be32(VSCSI_REQ_LIMIT-2);
662     rsp->tag = tag;
663     rsp->max_it_iu_len = cpu_to_be32(sizeof(union srp_iu));
664     rsp->max_ti_iu_len = cpu_to_be32(sizeof(union srp_iu));
665     /* direct and indirect */
666     rsp->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT | SRP_BUF_FORMAT_INDIRECT);
667 
668     vscsi_send_iu(s, req, sizeof(*rsp), VIOSRP_SRP_FORMAT);
669 }
670 
671 static void vscsi_inquiry_no_target(VSCSIState *s, vscsi_req *req)
672 {
673     uint8_t *cdb = req->iu.srp.cmd.cdb;
674     uint8_t resp_data[36];
675     int rc, len, alen;
676 
677     /* We dont do EVPD. Also check that page_code is 0 */
678     if ((cdb[1] & 0x01) || (cdb[1] & 0x01) || cdb[2] != 0) {
679         /* Send INVALID FIELD IN CDB */
680         vscsi_makeup_sense(s, req, ILLEGAL_REQUEST, 0x24, 0);
681         vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);
682         return;
683     }
684     alen = cdb[3];
685     alen = (alen << 8) | cdb[4];
686     len = MIN(alen, 36);
687 
688     /* Fake up inquiry using PQ=3 */
689     memset(resp_data, 0, 36);
690     resp_data[0] = 0x7f;   /* Not capable of supporting a device here */
691     resp_data[2] = 0x06;   /* SPS-4 */
692     resp_data[3] = 0x02;   /* Resp data format */
693     resp_data[4] = 36 - 5; /* Additional length */
694     resp_data[7] = 0x10;   /* Sync transfers */
695     memcpy(&resp_data[16], "QEMU EMPTY      ", 16);
696     memcpy(&resp_data[8], "QEMU    ", 8);
697 
698     req->writing = 0;
699     vscsi_preprocess_desc(req);
700     rc = vscsi_srp_transfer_data(s, req, 0, resp_data, len);
701     if (rc < 0) {
702         vscsi_makeup_sense(s, req, HARDWARE_ERROR, 0, 0);
703         vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);
704     } else {
705         vscsi_send_rsp(s, req, 0, 36 - rc, 0);
706     }
707 }
708 
709 static int vscsi_queue_cmd(VSCSIState *s, vscsi_req *req)
710 {
711     union srp_iu *srp = &req->iu.srp;
712     SCSIDevice *sdev;
713     int n, lun;
714 
715     sdev = vscsi_device_find(&s->bus, be64_to_cpu(srp->cmd.lun), &lun);
716     if (!sdev) {
717         DPRINTF("VSCSI: Command for lun %08" PRIx64 " with no drive\n",
718                 be64_to_cpu(srp->cmd.lun));
719         if (srp->cmd.cdb[0] == INQUIRY) {
720             vscsi_inquiry_no_target(s, req);
721         } else {
722             vscsi_makeup_sense(s, req, ILLEGAL_REQUEST, 0x24, 0x00);
723             vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);
724         } return 1;
725     }
726 
727     req->sreq = scsi_req_new(sdev, req->qtag, lun, srp->cmd.cdb, req);
728     n = scsi_req_enqueue(req->sreq);
729 
730     DPRINTF("VSCSI: Queued command tag 0x%x CMD 0x%x LUN %d ret: %d\n",
731             req->qtag, srp->cmd.cdb[0], lun, n);
732 
733     if (n) {
734         /* Transfer direction must be set before preprocessing the
735          * descriptors
736          */
737         req->writing = (n < 1);
738 
739         /* Preprocess RDMA descriptors */
740         vscsi_preprocess_desc(req);
741 
742         /* Get transfer direction and initiate transfer */
743         if (n > 0) {
744             req->data_len = n;
745         } else if (n < 0) {
746             req->data_len = -n;
747         }
748         scsi_req_continue(req->sreq);
749     }
750     /* Don't touch req here, it may have been recycled already */
751 
752     return 0;
753 }
754 
755 static int vscsi_process_tsk_mgmt(VSCSIState *s, vscsi_req *req)
756 {
757     union viosrp_iu *iu = &req->iu;
758     int fn;
759 
760     fprintf(stderr, "vscsi_process_tsk_mgmt %02x\n",
761             iu->srp.tsk_mgmt.tsk_mgmt_func);
762 
763     switch (iu->srp.tsk_mgmt.tsk_mgmt_func) {
764 #if 0 /* We really don't deal with these for now */
765     case SRP_TSK_ABORT_TASK:
766         fn = ABORT_TASK;
767         break;
768     case SRP_TSK_ABORT_TASK_SET:
769         fn = ABORT_TASK_SET;
770         break;
771     case SRP_TSK_CLEAR_TASK_SET:
772         fn = CLEAR_TASK_SET;
773         break;
774     case SRP_TSK_LUN_RESET:
775         fn = LOGICAL_UNIT_RESET;
776         break;
777     case SRP_TSK_CLEAR_ACA:
778         fn = CLEAR_ACA;
779         break;
780 #endif
781     default:
782         fn = 0;
783     }
784     if (fn) {
785         /* XXX Send/Handle target task management */
786         ;
787     } else {
788         vscsi_makeup_sense(s, req, ILLEGAL_REQUEST, 0x20, 0);
789         vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);
790     }
791     return !fn;
792 }
793 
794 static int vscsi_handle_srp_req(VSCSIState *s, vscsi_req *req)
795 {
796     union srp_iu *srp = &req->iu.srp;
797     int done = 1;
798     uint8_t opcode = srp->rsp.opcode;
799 
800     switch (opcode) {
801     case SRP_LOGIN_REQ:
802         vscsi_process_login(s, req);
803         break;
804     case SRP_TSK_MGMT:
805         done = vscsi_process_tsk_mgmt(s, req);
806         break;
807     case SRP_CMD:
808         done = vscsi_queue_cmd(s, req);
809         break;
810     case SRP_LOGIN_RSP:
811     case SRP_I_LOGOUT:
812     case SRP_T_LOGOUT:
813     case SRP_RSP:
814     case SRP_CRED_REQ:
815     case SRP_CRED_RSP:
816     case SRP_AER_REQ:
817     case SRP_AER_RSP:
818         fprintf(stderr, "VSCSI: Unsupported opcode %02x\n", opcode);
819         break;
820     default:
821         fprintf(stderr, "VSCSI: Unknown type %02x\n", opcode);
822     }
823 
824     return done;
825 }
826 
827 static int vscsi_send_adapter_info(VSCSIState *s, vscsi_req *req)
828 {
829     struct viosrp_adapter_info *sinfo;
830     struct mad_adapter_info_data info;
831     int rc;
832 
833     sinfo = &req->iu.mad.adapter_info;
834 
835 #if 0 /* What for ? */
836     rc = spapr_vio_dma_read(&s->vdev, be64_to_cpu(sinfo->buffer),
837                             &info, be16_to_cpu(sinfo->common.length));
838     if (rc) {
839         fprintf(stderr, "vscsi_send_adapter_info: DMA read failure !\n");
840     }
841 #endif
842     memset(&info, 0, sizeof(info));
843     strcpy(info.srp_version, SRP_VERSION);
844     memcpy(info.partition_name, "qemu", sizeof("qemu"));
845     info.partition_number = cpu_to_be32(0);
846     info.mad_version = cpu_to_be32(1);
847     info.os_type = cpu_to_be32(2);
848     info.port_max_txu[0] = cpu_to_be32(VSCSI_MAX_SECTORS << 9);
849 
850     rc = spapr_vio_dma_write(&s->vdev, be64_to_cpu(sinfo->buffer),
851                              &info, be16_to_cpu(sinfo->common.length));
852     if (rc)  {
853         fprintf(stderr, "vscsi_send_adapter_info: DMA write failure !\n");
854     }
855 
856     sinfo->common.status = rc ? cpu_to_be32(1) : 0;
857 
858     return vscsi_send_iu(s, req, sizeof(*sinfo), VIOSRP_MAD_FORMAT);
859 }
860 
861 static int vscsi_handle_mad_req(VSCSIState *s, vscsi_req *req)
862 {
863     union mad_iu *mad = &req->iu.mad;
864 
865     switch (be32_to_cpu(mad->empty_iu.common.type)) {
866     case VIOSRP_EMPTY_IU_TYPE:
867         fprintf(stderr, "Unsupported EMPTY MAD IU\n");
868         break;
869     case VIOSRP_ERROR_LOG_TYPE:
870         fprintf(stderr, "Unsupported ERROR LOG MAD IU\n");
871         mad->error_log.common.status = cpu_to_be16(1);
872         vscsi_send_iu(s, req, sizeof(mad->error_log), VIOSRP_MAD_FORMAT);
873         break;
874     case VIOSRP_ADAPTER_INFO_TYPE:
875         vscsi_send_adapter_info(s, req);
876         break;
877     case VIOSRP_HOST_CONFIG_TYPE:
878         mad->host_config.common.status = cpu_to_be16(1);
879         vscsi_send_iu(s, req, sizeof(mad->host_config), VIOSRP_MAD_FORMAT);
880         break;
881     default:
882         fprintf(stderr, "VSCSI: Unknown MAD type %02x\n",
883                 be32_to_cpu(mad->empty_iu.common.type));
884     }
885 
886     return 1;
887 }
888 
889 static void vscsi_got_payload(VSCSIState *s, vscsi_crq *crq)
890 {
891     vscsi_req *req;
892     int done;
893 
894     req = vscsi_get_req(s);
895     if (req == NULL) {
896         fprintf(stderr, "VSCSI: Failed to get a request !\n");
897         return;
898     }
899 
900     /* We only support a limited number of descriptors, we know
901      * the ibmvscsi driver uses up to 10 max, so it should fit
902      * in our 256 bytes IUs. If not we'll have to increase the size
903      * of the structure.
904      */
905     if (crq->s.IU_length > sizeof(union viosrp_iu)) {
906         fprintf(stderr, "VSCSI: SRP IU too long (%d bytes) !\n",
907                 crq->s.IU_length);
908         vscsi_put_req(req);
909         return;
910     }
911 
912     /* XXX Handle failure differently ? */
913     if (spapr_vio_dma_read(&s->vdev, crq->s.IU_data_ptr, &req->iu,
914                            crq->s.IU_length)) {
915         fprintf(stderr, "vscsi_got_payload: DMA read failure !\n");
916         vscsi_put_req(req);
917         return;
918     }
919     memcpy(&req->crq, crq, sizeof(vscsi_crq));
920 
921     if (crq->s.format == VIOSRP_MAD_FORMAT) {
922         done = vscsi_handle_mad_req(s, req);
923     } else {
924         done = vscsi_handle_srp_req(s, req);
925     }
926 
927     if (done) {
928         vscsi_put_req(req);
929     }
930 }
931 
932 
933 static int vscsi_do_crq(struct VIOsPAPRDevice *dev, uint8_t *crq_data)
934 {
935     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(dev);
936     vscsi_crq crq;
937 
938     memcpy(crq.raw, crq_data, 16);
939     crq.s.timeout = be16_to_cpu(crq.s.timeout);
940     crq.s.IU_length = be16_to_cpu(crq.s.IU_length);
941     crq.s.IU_data_ptr = be64_to_cpu(crq.s.IU_data_ptr);
942 
943     DPRINTF("VSCSI: do_crq %02x %02x ...\n", crq.raw[0], crq.raw[1]);
944 
945     switch (crq.s.valid) {
946     case 0xc0: /* Init command/response */
947 
948         /* Respond to initialization request */
949         if (crq.s.format == 0x01) {
950             memset(crq.raw, 0, 16);
951             crq.s.valid = 0xc0;
952             crq.s.format = 0x02;
953             spapr_vio_send_crq(dev, crq.raw);
954         }
955 
956         /* Note that in hotplug cases, we might get a 0x02
957          * as a result of us emitting the init request
958          */
959 
960         break;
961     case 0xff: /* Link event */
962 
963         /* Not handled for now */
964 
965         break;
966     case 0x80: /* Payloads */
967         switch (crq.s.format) {
968         case VIOSRP_SRP_FORMAT: /* AKA VSCSI request */
969         case VIOSRP_MAD_FORMAT: /* AKA VSCSI response */
970             vscsi_got_payload(s, &crq);
971             break;
972         case VIOSRP_OS400_FORMAT:
973         case VIOSRP_AIX_FORMAT:
974         case VIOSRP_LINUX_FORMAT:
975         case VIOSRP_INLINE_FORMAT:
976             fprintf(stderr, "vscsi_do_srq: Unsupported payload format %02x\n",
977                     crq.s.format);
978             break;
979         default:
980             fprintf(stderr, "vscsi_do_srq: Unknown payload format %02x\n",
981                     crq.s.format);
982         }
983         break;
984     default:
985         fprintf(stderr, "vscsi_do_crq: unknown CRQ %02x %02x ...\n",
986                 crq.raw[0], crq.raw[1]);
987     };
988 
989     return 0;
990 }
991 
992 static const struct SCSIBusInfo vscsi_scsi_info = {
993     .tcq = true,
994     .max_channel = 7, /* logical unit addressing format */
995     .max_target = 63,
996     .max_lun = 31,
997 
998     .transfer_data = vscsi_transfer_data,
999     .complete = vscsi_command_complete,
1000     .cancel = vscsi_request_cancelled,
1001     .save_request = vscsi_save_request,
1002     .load_request = vscsi_load_request,
1003 };
1004 
1005 static void spapr_vscsi_reset(VIOsPAPRDevice *dev)
1006 {
1007     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(dev);
1008     int i;
1009 
1010     memset(s->reqs, 0, sizeof(s->reqs));
1011     for (i = 0; i < VSCSI_REQ_LIMIT; i++) {
1012         s->reqs[i].qtag = i;
1013     }
1014 }
1015 
1016 static int spapr_vscsi_init(VIOsPAPRDevice *dev)
1017 {
1018     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(dev);
1019     Error *err = NULL;
1020 
1021     dev->crq.SendFunc = vscsi_do_crq;
1022 
1023     scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev),
1024                  &vscsi_scsi_info, NULL);
1025     if (!dev->qdev.hotplugged) {
1026         scsi_bus_legacy_handle_cmdline(&s->bus, &err);
1027         if (err != NULL) {
1028             error_free(err);
1029             return -1;
1030         }
1031     }
1032 
1033     return 0;
1034 }
1035 
1036 void spapr_vscsi_create(VIOsPAPRBus *bus)
1037 {
1038     DeviceState *dev;
1039 
1040     dev = qdev_create(&bus->bus, "spapr-vscsi");
1041 
1042     qdev_init_nofail(dev);
1043 }
1044 
1045 static int spapr_vscsi_devnode(VIOsPAPRDevice *dev, void *fdt, int node_off)
1046 {
1047     int ret;
1048 
1049     ret = fdt_setprop_cell(fdt, node_off, "#address-cells", 2);
1050     if (ret < 0) {
1051         return ret;
1052     }
1053 
1054     ret = fdt_setprop_cell(fdt, node_off, "#size-cells", 0);
1055     if (ret < 0) {
1056         return ret;
1057     }
1058 
1059     return 0;
1060 }
1061 
1062 static Property spapr_vscsi_properties[] = {
1063     DEFINE_SPAPR_PROPERTIES(VSCSIState, vdev),
1064     DEFINE_PROP_END_OF_LIST(),
1065 };
1066 
1067 static const VMStateDescription vmstate_spapr_vscsi = {
1068     .name = "spapr_vscsi",
1069     .version_id = 1,
1070     .minimum_version_id = 1,
1071     .minimum_version_id_old = 1,
1072     .fields      = (VMStateField []) {
1073         VMSTATE_SPAPR_VIO(vdev, VSCSIState),
1074         /* VSCSI state */
1075         /* ???? */
1076 
1077         VMSTATE_END_OF_LIST()
1078     },
1079 };
1080 
1081 static void spapr_vscsi_class_init(ObjectClass *klass, void *data)
1082 {
1083     DeviceClass *dc = DEVICE_CLASS(klass);
1084     VIOsPAPRDeviceClass *k = VIO_SPAPR_DEVICE_CLASS(klass);
1085 
1086     k->init = spapr_vscsi_init;
1087     k->reset = spapr_vscsi_reset;
1088     k->devnode = spapr_vscsi_devnode;
1089     k->dt_name = "v-scsi";
1090     k->dt_type = "vscsi";
1091     k->dt_compatible = "IBM,v-scsi";
1092     k->signal_mask = 0x00000001;
1093     dc->props = spapr_vscsi_properties;
1094     k->rtce_window_size = 0x10000000;
1095     dc->vmsd = &vmstate_spapr_vscsi;
1096 }
1097 
1098 static const TypeInfo spapr_vscsi_info = {
1099     .name          = TYPE_VIO_SPAPR_VSCSI_DEVICE,
1100     .parent        = TYPE_VIO_SPAPR_DEVICE,
1101     .instance_size = sizeof(VSCSIState),
1102     .class_init    = spapr_vscsi_class_init,
1103 };
1104 
1105 static void spapr_vscsi_register_types(void)
1106 {
1107     type_register_static(&spapr_vscsi_info);
1108 }
1109 
1110 type_init(spapr_vscsi_register_types)
1111