xref: /openbmc/qemu/hw/scsi/spapr_vscsi.c (revision 1d300b5f)
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", be64_to_cpu(srp->cmd.lun));
718         if (srp->cmd.cdb[0] == INQUIRY) {
719             vscsi_inquiry_no_target(s, req);
720         } else {
721             vscsi_makeup_sense(s, req, ILLEGAL_REQUEST, 0x24, 0x00);
722             vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);
723         } return 1;
724     }
725 
726     req->sreq = scsi_req_new(sdev, req->qtag, lun, srp->cmd.cdb, req);
727     n = scsi_req_enqueue(req->sreq);
728 
729     dprintf("VSCSI: Queued command tag 0x%x CMD 0x%x LUN %d ret: %d\n",
730             req->qtag, srp->cmd.cdb[0], lun, n);
731 
732     if (n) {
733         /* Transfer direction must be set before preprocessing the
734          * descriptors
735          */
736         req->writing = (n < 1);
737 
738         /* Preprocess RDMA descriptors */
739         vscsi_preprocess_desc(req);
740 
741         /* Get transfer direction and initiate transfer */
742         if (n > 0) {
743             req->data_len = n;
744         } else if (n < 0) {
745             req->data_len = -n;
746         }
747         scsi_req_continue(req->sreq);
748     }
749     /* Don't touch req here, it may have been recycled already */
750 
751     return 0;
752 }
753 
754 static int vscsi_process_tsk_mgmt(VSCSIState *s, vscsi_req *req)
755 {
756     union viosrp_iu *iu = &req->iu;
757     int fn;
758 
759     fprintf(stderr, "vscsi_process_tsk_mgmt %02x\n",
760             iu->srp.tsk_mgmt.tsk_mgmt_func);
761 
762     switch (iu->srp.tsk_mgmt.tsk_mgmt_func) {
763 #if 0 /* We really don't deal with these for now */
764     case SRP_TSK_ABORT_TASK:
765         fn = ABORT_TASK;
766         break;
767     case SRP_TSK_ABORT_TASK_SET:
768         fn = ABORT_TASK_SET;
769         break;
770     case SRP_TSK_CLEAR_TASK_SET:
771         fn = CLEAR_TASK_SET;
772         break;
773     case SRP_TSK_LUN_RESET:
774         fn = LOGICAL_UNIT_RESET;
775         break;
776     case SRP_TSK_CLEAR_ACA:
777         fn = CLEAR_ACA;
778         break;
779 #endif
780     default:
781         fn = 0;
782     }
783     if (fn) {
784         /* XXX Send/Handle target task management */
785         ;
786     } else {
787         vscsi_makeup_sense(s, req, ILLEGAL_REQUEST, 0x20, 0);
788         vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);
789     }
790     return !fn;
791 }
792 
793 static int vscsi_handle_srp_req(VSCSIState *s, vscsi_req *req)
794 {
795     union srp_iu *srp = &req->iu.srp;
796     int done = 1;
797     uint8_t opcode = srp->rsp.opcode;
798 
799     switch (opcode) {
800     case SRP_LOGIN_REQ:
801         vscsi_process_login(s, req);
802         break;
803     case SRP_TSK_MGMT:
804         done = vscsi_process_tsk_mgmt(s, req);
805         break;
806     case SRP_CMD:
807         done = vscsi_queue_cmd(s, req);
808         break;
809     case SRP_LOGIN_RSP:
810     case SRP_I_LOGOUT:
811     case SRP_T_LOGOUT:
812     case SRP_RSP:
813     case SRP_CRED_REQ:
814     case SRP_CRED_RSP:
815     case SRP_AER_REQ:
816     case SRP_AER_RSP:
817         fprintf(stderr, "VSCSI: Unsupported opcode %02x\n", opcode);
818         break;
819     default:
820         fprintf(stderr, "VSCSI: Unknown type %02x\n", opcode);
821     }
822 
823     return done;
824 }
825 
826 static int vscsi_send_adapter_info(VSCSIState *s, vscsi_req *req)
827 {
828     struct viosrp_adapter_info *sinfo;
829     struct mad_adapter_info_data info;
830     int rc;
831 
832     sinfo = &req->iu.mad.adapter_info;
833 
834 #if 0 /* What for ? */
835     rc = spapr_vio_dma_read(&s->vdev, be64_to_cpu(sinfo->buffer),
836                             &info, be16_to_cpu(sinfo->common.length));
837     if (rc) {
838         fprintf(stderr, "vscsi_send_adapter_info: DMA read failure !\n");
839     }
840 #endif
841     memset(&info, 0, sizeof(info));
842     strcpy(info.srp_version, SRP_VERSION);
843     memcpy(info.partition_name, "qemu", sizeof("qemu"));
844     info.partition_number = cpu_to_be32(0);
845     info.mad_version = cpu_to_be32(1);
846     info.os_type = cpu_to_be32(2);
847     info.port_max_txu[0] = cpu_to_be32(VSCSI_MAX_SECTORS << 9);
848 
849     rc = spapr_vio_dma_write(&s->vdev, be64_to_cpu(sinfo->buffer),
850                              &info, be16_to_cpu(sinfo->common.length));
851     if (rc)  {
852         fprintf(stderr, "vscsi_send_adapter_info: DMA write failure !\n");
853     }
854 
855     sinfo->common.status = rc ? cpu_to_be32(1) : 0;
856 
857     return vscsi_send_iu(s, req, sizeof(*sinfo), VIOSRP_MAD_FORMAT);
858 }
859 
860 static int vscsi_handle_mad_req(VSCSIState *s, vscsi_req *req)
861 {
862     union mad_iu *mad = &req->iu.mad;
863 
864     switch (be32_to_cpu(mad->empty_iu.common.type)) {
865     case VIOSRP_EMPTY_IU_TYPE:
866         fprintf(stderr, "Unsupported EMPTY MAD IU\n");
867         break;
868     case VIOSRP_ERROR_LOG_TYPE:
869         fprintf(stderr, "Unsupported ERROR LOG MAD IU\n");
870         mad->error_log.common.status = cpu_to_be16(1);
871         vscsi_send_iu(s, req, sizeof(mad->error_log), VIOSRP_MAD_FORMAT);
872         break;
873     case VIOSRP_ADAPTER_INFO_TYPE:
874         vscsi_send_adapter_info(s, req);
875         break;
876     case VIOSRP_HOST_CONFIG_TYPE:
877         mad->host_config.common.status = cpu_to_be16(1);
878         vscsi_send_iu(s, req, sizeof(mad->host_config), VIOSRP_MAD_FORMAT);
879         break;
880     default:
881         fprintf(stderr, "VSCSI: Unknown MAD type %02x\n",
882                 be32_to_cpu(mad->empty_iu.common.type));
883     }
884 
885     return 1;
886 }
887 
888 static void vscsi_got_payload(VSCSIState *s, vscsi_crq *crq)
889 {
890     vscsi_req *req;
891     int done;
892 
893     req = vscsi_get_req(s);
894     if (req == NULL) {
895         fprintf(stderr, "VSCSI: Failed to get a request !\n");
896         return;
897     }
898 
899     /* We only support a limited number of descriptors, we know
900      * the ibmvscsi driver uses up to 10 max, so it should fit
901      * in our 256 bytes IUs. If not we'll have to increase the size
902      * of the structure.
903      */
904     if (crq->s.IU_length > sizeof(union viosrp_iu)) {
905         fprintf(stderr, "VSCSI: SRP IU too long (%d bytes) !\n",
906                 crq->s.IU_length);
907         vscsi_put_req(req);
908         return;
909     }
910 
911     /* XXX Handle failure differently ? */
912     if (spapr_vio_dma_read(&s->vdev, crq->s.IU_data_ptr, &req->iu,
913                            crq->s.IU_length)) {
914         fprintf(stderr, "vscsi_got_payload: DMA read failure !\n");
915         vscsi_put_req(req);
916         return;
917     }
918     memcpy(&req->crq, crq, sizeof(vscsi_crq));
919 
920     if (crq->s.format == VIOSRP_MAD_FORMAT) {
921         done = vscsi_handle_mad_req(s, req);
922     } else {
923         done = vscsi_handle_srp_req(s, req);
924     }
925 
926     if (done) {
927         vscsi_put_req(req);
928     }
929 }
930 
931 
932 static int vscsi_do_crq(struct VIOsPAPRDevice *dev, uint8_t *crq_data)
933 {
934     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(dev);
935     vscsi_crq crq;
936 
937     memcpy(crq.raw, crq_data, 16);
938     crq.s.timeout = be16_to_cpu(crq.s.timeout);
939     crq.s.IU_length = be16_to_cpu(crq.s.IU_length);
940     crq.s.IU_data_ptr = be64_to_cpu(crq.s.IU_data_ptr);
941 
942     dprintf("VSCSI: do_crq %02x %02x ...\n", crq.raw[0], crq.raw[1]);
943 
944     switch (crq.s.valid) {
945     case 0xc0: /* Init command/response */
946 
947         /* Respond to initialization request */
948         if (crq.s.format == 0x01) {
949             memset(crq.raw, 0, 16);
950             crq.s.valid = 0xc0;
951             crq.s.format = 0x02;
952             spapr_vio_send_crq(dev, crq.raw);
953         }
954 
955         /* Note that in hotplug cases, we might get a 0x02
956          * as a result of us emitting the init request
957          */
958 
959         break;
960     case 0xff: /* Link event */
961 
962         /* Not handled for now */
963 
964         break;
965     case 0x80: /* Payloads */
966         switch (crq.s.format) {
967         case VIOSRP_SRP_FORMAT: /* AKA VSCSI request */
968         case VIOSRP_MAD_FORMAT: /* AKA VSCSI response */
969             vscsi_got_payload(s, &crq);
970             break;
971         case VIOSRP_OS400_FORMAT:
972         case VIOSRP_AIX_FORMAT:
973         case VIOSRP_LINUX_FORMAT:
974         case VIOSRP_INLINE_FORMAT:
975             fprintf(stderr, "vscsi_do_srq: Unsupported payload format %02x\n",
976                     crq.s.format);
977             break;
978         default:
979             fprintf(stderr, "vscsi_do_srq: Unknown payload format %02x\n",
980                     crq.s.format);
981         }
982         break;
983     default:
984         fprintf(stderr, "vscsi_do_crq: unknown CRQ %02x %02x ...\n",
985                 crq.raw[0], crq.raw[1]);
986     };
987 
988     return 0;
989 }
990 
991 static const struct SCSIBusInfo vscsi_scsi_info = {
992     .tcq = true,
993     .max_channel = 7, /* logical unit addressing format */
994     .max_target = 63,
995     .max_lun = 31,
996 
997     .transfer_data = vscsi_transfer_data,
998     .complete = vscsi_command_complete,
999     .cancel = vscsi_request_cancelled,
1000     .save_request = vscsi_save_request,
1001     .load_request = vscsi_load_request,
1002 };
1003 
1004 static void spapr_vscsi_reset(VIOsPAPRDevice *dev)
1005 {
1006     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(dev);
1007     int i;
1008 
1009     memset(s->reqs, 0, sizeof(s->reqs));
1010     for (i = 0; i < VSCSI_REQ_LIMIT; i++) {
1011         s->reqs[i].qtag = i;
1012     }
1013 }
1014 
1015 static int spapr_vscsi_init(VIOsPAPRDevice *dev)
1016 {
1017     VSCSIState *s = VIO_SPAPR_VSCSI_DEVICE(dev);
1018     Error *err = NULL;
1019 
1020     dev->crq.SendFunc = vscsi_do_crq;
1021 
1022     scsi_bus_new(&s->bus, &dev->qdev, &vscsi_scsi_info, NULL);
1023     if (!dev->qdev.hotplugged) {
1024         scsi_bus_legacy_handle_cmdline(&s->bus, &err);
1025         if (err != NULL) {
1026             error_free(err);
1027             return -1;
1028         }
1029     }
1030 
1031     return 0;
1032 }
1033 
1034 void spapr_vscsi_create(VIOsPAPRBus *bus)
1035 {
1036     DeviceState *dev;
1037 
1038     dev = qdev_create(&bus->bus, "spapr-vscsi");
1039 
1040     qdev_init_nofail(dev);
1041 }
1042 
1043 static int spapr_vscsi_devnode(VIOsPAPRDevice *dev, void *fdt, int node_off)
1044 {
1045     int ret;
1046 
1047     ret = fdt_setprop_cell(fdt, node_off, "#address-cells", 2);
1048     if (ret < 0) {
1049         return ret;
1050     }
1051 
1052     ret = fdt_setprop_cell(fdt, node_off, "#size-cells", 0);
1053     if (ret < 0) {
1054         return ret;
1055     }
1056 
1057     return 0;
1058 }
1059 
1060 static Property spapr_vscsi_properties[] = {
1061     DEFINE_SPAPR_PROPERTIES(VSCSIState, vdev),
1062     DEFINE_PROP_END_OF_LIST(),
1063 };
1064 
1065 static const VMStateDescription vmstate_spapr_vscsi = {
1066     .name = "spapr_vscsi",
1067     .version_id = 1,
1068     .minimum_version_id = 1,
1069     .minimum_version_id_old = 1,
1070     .fields      = (VMStateField []) {
1071         VMSTATE_SPAPR_VIO(vdev, VSCSIState),
1072         /* VSCSI state */
1073         /* ???? */
1074 
1075         VMSTATE_END_OF_LIST()
1076     },
1077 };
1078 
1079 static void spapr_vscsi_class_init(ObjectClass *klass, void *data)
1080 {
1081     DeviceClass *dc = DEVICE_CLASS(klass);
1082     VIOsPAPRDeviceClass *k = VIO_SPAPR_DEVICE_CLASS(klass);
1083 
1084     k->init = spapr_vscsi_init;
1085     k->reset = spapr_vscsi_reset;
1086     k->devnode = spapr_vscsi_devnode;
1087     k->dt_name = "v-scsi";
1088     k->dt_type = "vscsi";
1089     k->dt_compatible = "IBM,v-scsi";
1090     k->signal_mask = 0x00000001;
1091     dc->props = spapr_vscsi_properties;
1092     k->rtce_window_size = 0x10000000;
1093     dc->vmsd = &vmstate_spapr_vscsi;
1094 }
1095 
1096 static const TypeInfo spapr_vscsi_info = {
1097     .name          = TYPE_VIO_SPAPR_VSCSI_DEVICE,
1098     .parent        = TYPE_VIO_SPAPR_DEVICE,
1099     .instance_size = sizeof(VSCSIState),
1100     .class_init    = spapr_vscsi_class_init,
1101 };
1102 
1103 static void spapr_vscsi_register_types(void)
1104 {
1105     type_register_static(&spapr_vscsi_info);
1106 }
1107 
1108 type_init(spapr_vscsi_register_types)
1109