Statistics
| Branch: | Revision:

root / hw / scsi-bus.c @ 5414dec6

History | View | Annotate | Download (45.9 kB)

1
#include "hw.h"
2
#include "qemu-error.h"
3
#include "scsi.h"
4
#include "scsi-defs.h"
5
#include "qdev.h"
6
#include "blockdev.h"
7
#include "trace.h"
8
#include "dma.h"
9

    
10
static char *scsibus_get_dev_path(DeviceState *dev);
11
static char *scsibus_get_fw_dev_path(DeviceState *dev);
12
static int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf);
13
static void scsi_req_dequeue(SCSIRequest *req);
14

    
15
static struct BusInfo scsi_bus_info = {
16
    .name  = "SCSI",
17
    .size  = sizeof(SCSIBus),
18
    .get_dev_path = scsibus_get_dev_path,
19
    .get_fw_dev_path = scsibus_get_fw_dev_path,
20
    .props = (Property[]) {
21
        DEFINE_PROP_UINT32("channel", SCSIDevice, channel, 0),
22
        DEFINE_PROP_UINT32("scsi-id", SCSIDevice, id, -1),
23
        DEFINE_PROP_UINT32("lun", SCSIDevice, lun, -1),
24
        DEFINE_PROP_END_OF_LIST(),
25
    },
26
};
27
static int next_scsi_bus;
28

    
29
static int scsi_device_init(SCSIDevice *s)
30
{
31
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
32
    if (sc->init) {
33
        return sc->init(s);
34
    }
35
    return 0;
36
}
37

    
38
static void scsi_device_destroy(SCSIDevice *s)
39
{
40
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
41
    if (sc->destroy) {
42
        sc->destroy(s);
43
    }
44
}
45

    
46
static SCSIRequest *scsi_device_alloc_req(SCSIDevice *s, uint32_t tag, uint32_t lun,
47
                                          uint8_t *buf, void *hba_private)
48
{
49
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
50
    if (sc->alloc_req) {
51
        return sc->alloc_req(s, tag, lun, buf, hba_private);
52
    }
53

    
54
    return NULL;
55
}
56

    
57
static void scsi_device_unit_attention_reported(SCSIDevice *s)
58
{
59
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
60
    if (sc->unit_attention_reported) {
61
        sc->unit_attention_reported(s);
62
    }
63
}
64

    
65
/* Create a scsi bus, and attach devices to it.  */
66
void scsi_bus_new(SCSIBus *bus, DeviceState *host, const SCSIBusInfo *info)
67
{
68
    qbus_create_inplace(&bus->qbus, &scsi_bus_info, host, NULL);
69
    bus->busnr = next_scsi_bus++;
70
    bus->info = info;
71
    bus->qbus.allow_hotplug = 1;
72
}
73

    
74
static void scsi_dma_restart_bh(void *opaque)
75
{
76
    SCSIDevice *s = opaque;
77
    SCSIRequest *req, *next;
78

    
79
    qemu_bh_delete(s->bh);
80
    s->bh = NULL;
81

    
82
    QTAILQ_FOREACH_SAFE(req, &s->requests, next, next) {
83
        scsi_req_ref(req);
84
        if (req->retry) {
85
            req->retry = false;
86
            switch (req->cmd.mode) {
87
            case SCSI_XFER_FROM_DEV:
88
            case SCSI_XFER_TO_DEV:
89
                scsi_req_continue(req);
90
                break;
91
            case SCSI_XFER_NONE:
92
                assert(!req->sg);
93
                scsi_req_dequeue(req);
94
                scsi_req_enqueue(req);
95
                break;
96
            }
97
        }
98
        scsi_req_unref(req);
99
    }
100
}
101

    
102
void scsi_req_retry(SCSIRequest *req)
103
{
104
    /* No need to save a reference, because scsi_dma_restart_bh just
105
     * looks at the request list.  */
106
    req->retry = true;
107
}
108

    
109
static void scsi_dma_restart_cb(void *opaque, int running, RunState state)
110
{
111
    SCSIDevice *s = opaque;
112

    
113
    if (!running) {
114
        return;
115
    }
116
    if (!s->bh) {
117
        s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
118
        qemu_bh_schedule(s->bh);
119
    }
120
}
121

    
122
static int scsi_qdev_init(DeviceState *qdev)
123
{
124
    SCSIDevice *dev = SCSI_DEVICE(qdev);
125
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
126
    SCSIDevice *d;
127
    int rc = -1;
128

    
129
    if (dev->channel > bus->info->max_channel) {
130
        error_report("bad scsi channel id: %d", dev->channel);
131
        goto err;
132
    }
133
    if (dev->id != -1 && dev->id > bus->info->max_target) {
134
        error_report("bad scsi device id: %d", dev->id);
135
        goto err;
136
    }
137
    if (dev->lun != -1 && dev->lun > bus->info->max_lun) {
138
        error_report("bad scsi device lun: %d", dev->lun);
139
        goto err;
140
    }
141

    
142
    if (dev->id == -1) {
143
        int id = -1;
144
        if (dev->lun == -1) {
145
            dev->lun = 0;
146
        }
147
        do {
148
            d = scsi_device_find(bus, dev->channel, ++id, dev->lun);
149
        } while (d && d->lun == dev->lun && id < bus->info->max_target);
150
        if (d && d->lun == dev->lun) {
151
            error_report("no free target");
152
            goto err;
153
        }
154
        dev->id = id;
155
    } else if (dev->lun == -1) {
156
        int lun = -1;
157
        do {
158
            d = scsi_device_find(bus, dev->channel, dev->id, ++lun);
159
        } while (d && d->lun == lun && lun < bus->info->max_lun);
160
        if (d && d->lun == lun) {
161
            error_report("no free lun");
162
            goto err;
163
        }
164
        dev->lun = lun;
165
    } else {
166
        d = scsi_device_find(bus, dev->channel, dev->id, dev->lun);
167
        assert(d);
168
        if (d->lun == dev->lun && dev != d) {
169
            qdev_free(&d->qdev);
170
        }
171
    }
172

    
173
    QTAILQ_INIT(&dev->requests);
174
    rc = scsi_device_init(dev);
175
    if (rc == 0) {
176
        dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb,
177
                                                         dev);
178
    }
179

    
180
err:
181
    return rc;
182
}
183

    
184
static int scsi_qdev_exit(DeviceState *qdev)
185
{
186
    SCSIDevice *dev = SCSI_DEVICE(qdev);
187

    
188
    if (dev->vmsentry) {
189
        qemu_del_vm_change_state_handler(dev->vmsentry);
190
    }
191
    scsi_device_destroy(dev);
192
    return 0;
193
}
194

    
195
/* handle legacy '-drive if=scsi,...' cmd line args */
196
SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockDriverState *bdrv,
197
                                      int unit, bool removable, int bootindex)
198
{
199
    const char *driver;
200
    DeviceState *dev;
201

    
202
    driver = bdrv_is_sg(bdrv) ? "scsi-generic" : "scsi-disk";
203
    dev = qdev_create(&bus->qbus, driver);
204
    qdev_prop_set_uint32(dev, "scsi-id", unit);
205
    if (bootindex >= 0) {
206
        qdev_prop_set_int32(dev, "bootindex", bootindex);
207
    }
208
    if (qdev_prop_exists(dev, "removable")) {
209
        qdev_prop_set_bit(dev, "removable", removable);
210
    }
211
    if (qdev_prop_set_drive(dev, "drive", bdrv) < 0) {
212
        qdev_free(dev);
213
        return NULL;
214
    }
215
    if (qdev_init(dev) < 0)
216
        return NULL;
217
    return SCSI_DEVICE(dev);
218
}
219

    
220
int scsi_bus_legacy_handle_cmdline(SCSIBus *bus)
221
{
222
    Location loc;
223
    DriveInfo *dinfo;
224
    int res = 0, unit;
225

    
226
    loc_push_none(&loc);
227
    for (unit = 0; unit <= bus->info->max_target; unit++) {
228
        dinfo = drive_get(IF_SCSI, bus->busnr, unit);
229
        if (dinfo == NULL) {
230
            continue;
231
        }
232
        qemu_opts_loc_restore(dinfo->opts);
233
        if (!scsi_bus_legacy_add_drive(bus, dinfo->bdrv, unit, false, -1)) {
234
            res = -1;
235
            break;
236
        }
237
    }
238
    loc_pop(&loc);
239
    return res;
240
}
241

    
242
static int32_t scsi_invalid_field(SCSIRequest *req, uint8_t *buf)
243
{
244
    scsi_req_build_sense(req, SENSE_CODE(INVALID_FIELD));
245
    scsi_req_complete(req, CHECK_CONDITION);
246
    return 0;
247
}
248

    
249
static const struct SCSIReqOps reqops_invalid_field = {
250
    .size         = sizeof(SCSIRequest),
251
    .send_command = scsi_invalid_field
252
};
253

    
254
/* SCSIReqOps implementation for invalid commands.  */
255

    
256
static int32_t scsi_invalid_command(SCSIRequest *req, uint8_t *buf)
257
{
258
    scsi_req_build_sense(req, SENSE_CODE(INVALID_OPCODE));
259
    scsi_req_complete(req, CHECK_CONDITION);
260
    return 0;
261
}
262

    
263
static const struct SCSIReqOps reqops_invalid_opcode = {
264
    .size         = sizeof(SCSIRequest),
265
    .send_command = scsi_invalid_command
266
};
267

    
268
/* SCSIReqOps implementation for unit attention conditions.  */
269

    
270
static int32_t scsi_unit_attention(SCSIRequest *req, uint8_t *buf)
271
{
272
    if (req->dev && req->dev->unit_attention.key == UNIT_ATTENTION) {
273
        scsi_req_build_sense(req, req->dev->unit_attention);
274
    } else if (req->bus->unit_attention.key == UNIT_ATTENTION) {
275
        scsi_req_build_sense(req, req->bus->unit_attention);
276
    }
277
    scsi_req_complete(req, CHECK_CONDITION);
278
    return 0;
279
}
280

    
281
static const struct SCSIReqOps reqops_unit_attention = {
282
    .size         = sizeof(SCSIRequest),
283
    .send_command = scsi_unit_attention
284
};
285

    
286
/* SCSIReqOps implementation for REPORT LUNS and for commands sent to
287
   an invalid LUN.  */
288

    
289
typedef struct SCSITargetReq SCSITargetReq;
290

    
291
struct SCSITargetReq {
292
    SCSIRequest req;
293
    int len;
294
    uint8_t buf[2056];
295
};
296

    
297
static void store_lun(uint8_t *outbuf, int lun)
298
{
299
    if (lun < 256) {
300
        outbuf[1] = lun;
301
        return;
302
    }
303
    outbuf[1] = (lun & 255);
304
    outbuf[0] = (lun >> 8) | 0x40;
305
}
306

    
307
static bool scsi_target_emulate_report_luns(SCSITargetReq *r)
308
{
309
    DeviceState *qdev;
310
    int i, len, n;
311
    int channel, id;
312
    bool found_lun0;
313

    
314
    if (r->req.cmd.xfer < 16) {
315
        return false;
316
    }
317
    if (r->req.cmd.buf[2] > 2) {
318
        return false;
319
    }
320
    channel = r->req.dev->channel;
321
    id = r->req.dev->id;
322
    found_lun0 = false;
323
    n = 0;
324
    QTAILQ_FOREACH(qdev, &r->req.bus->qbus.children, sibling) {
325
        SCSIDevice *dev = SCSI_DEVICE(qdev);
326

    
327
        if (dev->channel == channel && dev->id == id) {
328
            if (dev->lun == 0) {
329
                found_lun0 = true;
330
            }
331
            n += 8;
332
        }
333
    }
334
    if (!found_lun0) {
335
        n += 8;
336
    }
337
    len = MIN(n + 8, r->req.cmd.xfer & ~7);
338
    if (len > sizeof(r->buf)) {
339
        /* TODO: > 256 LUNs? */
340
        return false;
341
    }
342

    
343
    memset(r->buf, 0, len);
344
    stl_be_p(&r->buf, n);
345
    i = found_lun0 ? 8 : 16;
346
    QTAILQ_FOREACH(qdev, &r->req.bus->qbus.children, sibling) {
347
        SCSIDevice *dev = SCSI_DEVICE(qdev);
348

    
349
        if (dev->channel == channel && dev->id == id) {
350
            store_lun(&r->buf[i], dev->lun);
351
            i += 8;
352
        }
353
    }
354
    assert(i == n + 8);
355
    r->len = len;
356
    return true;
357
}
358

    
359
static bool scsi_target_emulate_inquiry(SCSITargetReq *r)
360
{
361
    assert(r->req.dev->lun != r->req.lun);
362
    if (r->req.cmd.buf[1] & 0x2) {
363
        /* Command support data - optional, not implemented */
364
        return false;
365
    }
366

    
367
    if (r->req.cmd.buf[1] & 0x1) {
368
        /* Vital product data */
369
        uint8_t page_code = r->req.cmd.buf[2];
370
        r->buf[r->len++] = page_code ; /* this page */
371
        r->buf[r->len++] = 0x00;
372

    
373
        switch (page_code) {
374
        case 0x00: /* Supported page codes, mandatory */
375
        {
376
            int pages;
377
            pages = r->len++;
378
            r->buf[r->len++] = 0x00; /* list of supported pages (this page) */
379
            r->buf[pages] = r->len - pages - 1; /* number of pages */
380
            break;
381
        }
382
        default:
383
            return false;
384
        }
385
        /* done with EVPD */
386
        assert(r->len < sizeof(r->buf));
387
        r->len = MIN(r->req.cmd.xfer, r->len);
388
        return true;
389
    }
390

    
391
    /* Standard INQUIRY data */
392
    if (r->req.cmd.buf[2] != 0) {
393
        return false;
394
    }
395

    
396
    /* PAGE CODE == 0 */
397
    r->len = MIN(r->req.cmd.xfer, 36);
398
    memset(r->buf, 0, r->len);
399
    if (r->req.lun != 0) {
400
        r->buf[0] = TYPE_NO_LUN;
401
    } else {
402
        r->buf[0] = TYPE_NOT_PRESENT | TYPE_INACTIVE;
403
        r->buf[2] = 5; /* Version */
404
        r->buf[3] = 2 | 0x10; /* HiSup, response data format */
405
        r->buf[4] = r->len - 5; /* Additional Length = (Len - 1) - 4 */
406
        r->buf[7] = 0x10 | (r->req.bus->info->tcq ? 0x02 : 0); /* Sync, TCQ.  */
407
        memcpy(&r->buf[8], "QEMU    ", 8);
408
        memcpy(&r->buf[16], "QEMU TARGET     ", 16);
409
        strncpy((char *) &r->buf[32], QEMU_VERSION, 4);
410
    }
411
    return true;
412
}
413

    
414
static int32_t scsi_target_send_command(SCSIRequest *req, uint8_t *buf)
415
{
416
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
417

    
418
    switch (buf[0]) {
419
    case REPORT_LUNS:
420
        if (!scsi_target_emulate_report_luns(r)) {
421
            goto illegal_request;
422
        }
423
        break;
424
    case INQUIRY:
425
        if (!scsi_target_emulate_inquiry(r)) {
426
            goto illegal_request;
427
        }
428
        break;
429
    case REQUEST_SENSE:
430
        r->len = scsi_device_get_sense(r->req.dev, r->buf,
431
                                       MIN(req->cmd.xfer, sizeof r->buf),
432
                                       (req->cmd.buf[1] & 1) == 0);
433
        if (r->req.dev->sense_is_ua) {
434
            scsi_device_unit_attention_reported(req->dev);
435
            r->req.dev->sense_len = 0;
436
            r->req.dev->sense_is_ua = false;
437
        }
438
        break;
439
    default:
440
        scsi_req_build_sense(req, SENSE_CODE(LUN_NOT_SUPPORTED));
441
        scsi_req_complete(req, CHECK_CONDITION);
442
        return 0;
443
    illegal_request:
444
        scsi_req_build_sense(req, SENSE_CODE(INVALID_FIELD));
445
        scsi_req_complete(req, CHECK_CONDITION);
446
        return 0;
447
    }
448

    
449
    if (!r->len) {
450
        scsi_req_complete(req, GOOD);
451
    }
452
    return r->len;
453
}
454

    
455
static void scsi_target_read_data(SCSIRequest *req)
456
{
457
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
458
    uint32_t n;
459

    
460
    n = r->len;
461
    if (n > 0) {
462
        r->len = 0;
463
        scsi_req_data(&r->req, n);
464
    } else {
465
        scsi_req_complete(&r->req, GOOD);
466
    }
467
}
468

    
469
static uint8_t *scsi_target_get_buf(SCSIRequest *req)
470
{
471
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
472

    
473
    return r->buf;
474
}
475

    
476
static const struct SCSIReqOps reqops_target_command = {
477
    .size         = sizeof(SCSITargetReq),
478
    .send_command = scsi_target_send_command,
479
    .read_data    = scsi_target_read_data,
480
    .get_buf      = scsi_target_get_buf,
481
};
482

    
483

    
484
SCSIRequest *scsi_req_alloc(const SCSIReqOps *reqops, SCSIDevice *d,
485
                            uint32_t tag, uint32_t lun, void *hba_private)
486
{
487
    SCSIRequest *req;
488

    
489
    req = g_malloc0(reqops->size);
490
    req->refcount = 1;
491
    req->bus = scsi_bus_from_device(d);
492
    req->dev = d;
493
    req->tag = tag;
494
    req->lun = lun;
495
    req->hba_private = hba_private;
496
    req->status = -1;
497
    req->sense_len = 0;
498
    req->ops = reqops;
499
    trace_scsi_req_alloc(req->dev->id, req->lun, req->tag);
500
    return req;
501
}
502

    
503
SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun,
504
                          uint8_t *buf, void *hba_private)
505
{
506
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, d->qdev.parent_bus);
507
    SCSIRequest *req;
508
    SCSICommand cmd;
509

    
510
    if (scsi_req_parse(&cmd, d, buf) != 0) {
511
        trace_scsi_req_parse_bad(d->id, lun, tag, buf[0]);
512
        req = scsi_req_alloc(&reqops_invalid_opcode, d, tag, lun, hba_private);
513
    } else {
514
        trace_scsi_req_parsed(d->id, lun, tag, buf[0],
515
                              cmd.mode, cmd.xfer);
516
        if (cmd.lba != -1) {
517
            trace_scsi_req_parsed_lba(d->id, lun, tag, buf[0],
518
                                      cmd.lba);
519
        }
520

    
521
        if (cmd.xfer > INT32_MAX) {
522
            req = scsi_req_alloc(&reqops_invalid_field, d, tag, lun, hba_private);
523
        } else if ((d->unit_attention.key == UNIT_ATTENTION ||
524
                   bus->unit_attention.key == UNIT_ATTENTION) &&
525
                  (buf[0] != INQUIRY &&
526
                   buf[0] != REPORT_LUNS &&
527
                   buf[0] != GET_CONFIGURATION &&
528
                   buf[0] != GET_EVENT_STATUS_NOTIFICATION &&
529

    
530
                   /*
531
                    * If we already have a pending unit attention condition,
532
                    * report this one before triggering another one.
533
                    */
534
                   !(buf[0] == REQUEST_SENSE && d->sense_is_ua))) {
535
            req = scsi_req_alloc(&reqops_unit_attention, d, tag, lun,
536
                                 hba_private);
537
        } else if (lun != d->lun ||
538
                   buf[0] == REPORT_LUNS ||
539
                   (buf[0] == REQUEST_SENSE && d->sense_len)) {
540
            req = scsi_req_alloc(&reqops_target_command, d, tag, lun,
541
                                 hba_private);
542
        } else {
543
            req = scsi_device_alloc_req(d, tag, lun, buf, hba_private);
544
        }
545
    }
546

    
547
    req->cmd = cmd;
548
    req->resid = req->cmd.xfer;
549

    
550
    switch (buf[0]) {
551
    case INQUIRY:
552
        trace_scsi_inquiry(d->id, lun, tag, cmd.buf[1], cmd.buf[2]);
553
        break;
554
    case TEST_UNIT_READY:
555
        trace_scsi_test_unit_ready(d->id, lun, tag);
556
        break;
557
    case REPORT_LUNS:
558
        trace_scsi_report_luns(d->id, lun, tag);
559
        break;
560
    case REQUEST_SENSE:
561
        trace_scsi_request_sense(d->id, lun, tag);
562
        break;
563
    default:
564
        break;
565
    }
566

    
567
    return req;
568
}
569

    
570
uint8_t *scsi_req_get_buf(SCSIRequest *req)
571
{
572
    return req->ops->get_buf(req);
573
}
574

    
575
static void scsi_clear_unit_attention(SCSIRequest *req)
576
{
577
    SCSISense *ua;
578
    if (req->dev->unit_attention.key != UNIT_ATTENTION &&
579
        req->bus->unit_attention.key != UNIT_ATTENTION) {
580
        return;
581
    }
582

    
583
    /*
584
     * If an INQUIRY command enters the enabled command state,
585
     * the device server shall [not] clear any unit attention condition;
586
     * See also MMC-6, paragraphs 6.5 and 6.6.2.
587
     */
588
    if (req->cmd.buf[0] == INQUIRY ||
589
        req->cmd.buf[0] == GET_CONFIGURATION ||
590
        req->cmd.buf[0] == GET_EVENT_STATUS_NOTIFICATION) {
591
        return;
592
    }
593

    
594
    if (req->dev->unit_attention.key == UNIT_ATTENTION) {
595
        ua = &req->dev->unit_attention;
596
    } else {
597
        ua = &req->bus->unit_attention;
598
    }
599

    
600
    /*
601
     * If a REPORT LUNS command enters the enabled command state, [...]
602
     * the device server shall clear any pending unit attention condition
603
     * with an additional sense code of REPORTED LUNS DATA HAS CHANGED.
604
     */
605
    if (req->cmd.buf[0] == REPORT_LUNS &&
606
        !(ua->asc == SENSE_CODE(REPORTED_LUNS_CHANGED).asc &&
607
          ua->ascq == SENSE_CODE(REPORTED_LUNS_CHANGED).ascq)) {
608
        return;
609
    }
610

    
611
    *ua = SENSE_CODE(NO_SENSE);
612
}
613

    
614
int scsi_req_get_sense(SCSIRequest *req, uint8_t *buf, int len)
615
{
616
    int ret;
617

    
618
    assert(len >= 14);
619
    if (!req->sense_len) {
620
        return 0;
621
    }
622

    
623
    ret = scsi_build_sense(req->sense, req->sense_len, buf, len, true);
624

    
625
    /*
626
     * FIXME: clearing unit attention conditions upon autosense should be done
627
     * only if the UA_INTLCK_CTRL field in the Control mode page is set to 00b
628
     * (SAM-5, 5.14).
629
     *
630
     * We assume UA_INTLCK_CTRL to be 00b for HBAs that support autosense, and
631
     * 10b for HBAs that do not support it (do not call scsi_req_get_sense).
632
     * Here we handle unit attention clearing for UA_INTLCK_CTRL == 00b.
633
     */
634
    if (req->dev->sense_is_ua) {
635
        scsi_device_unit_attention_reported(req->dev);
636
        req->dev->sense_len = 0;
637
        req->dev->sense_is_ua = false;
638
    }
639
    return ret;
640
}
641

    
642
int scsi_device_get_sense(SCSIDevice *dev, uint8_t *buf, int len, bool fixed)
643
{
644
    return scsi_build_sense(dev->sense, dev->sense_len, buf, len, fixed);
645
}
646

    
647
void scsi_req_build_sense(SCSIRequest *req, SCSISense sense)
648
{
649
    trace_scsi_req_build_sense(req->dev->id, req->lun, req->tag,
650
                               sense.key, sense.asc, sense.ascq);
651
    memset(req->sense, 0, 18);
652
    req->sense[0] = 0x70;
653
    req->sense[2] = sense.key;
654
    req->sense[7] = 10;
655
    req->sense[12] = sense.asc;
656
    req->sense[13] = sense.ascq;
657
    req->sense_len = 18;
658
}
659

    
660
static void scsi_req_enqueue_internal(SCSIRequest *req)
661
{
662
    assert(!req->enqueued);
663
    scsi_req_ref(req);
664
    if (req->bus->info->get_sg_list) {
665
        req->sg = req->bus->info->get_sg_list(req);
666
    } else {
667
        req->sg = NULL;
668
    }
669
    req->enqueued = true;
670
    QTAILQ_INSERT_TAIL(&req->dev->requests, req, next);
671
}
672

    
673
int32_t scsi_req_enqueue(SCSIRequest *req)
674
{
675
    int32_t rc;
676

    
677
    assert(!req->retry);
678
    scsi_req_enqueue_internal(req);
679
    scsi_req_ref(req);
680
    rc = req->ops->send_command(req, req->cmd.buf);
681
    scsi_req_unref(req);
682
    return rc;
683
}
684

    
685
static void scsi_req_dequeue(SCSIRequest *req)
686
{
687
    trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);
688
    req->retry = false;
689
    if (req->enqueued) {
690
        QTAILQ_REMOVE(&req->dev->requests, req, next);
691
        req->enqueued = false;
692
        scsi_req_unref(req);
693
    }
694
}
695

    
696
static int scsi_get_performance_length(int num_desc, int type, int data_type)
697
{
698
    /* MMC-6, paragraph 6.7.  */
699
    switch (type) {
700
    case 0:
701
        if ((data_type & 3) == 0) {
702
            /* Each descriptor is as in Table 295 - Nominal performance.  */
703
            return 16 * num_desc + 8;
704
        } else {
705
            /* Each descriptor is as in Table 296 - Exceptions.  */
706
            return 6 * num_desc + 8;
707
        }
708
    case 1:
709
    case 4:
710
    case 5:
711
        return 8 * num_desc + 8;
712
    case 2:
713
        return 2048 * num_desc + 8;
714
    case 3:
715
        return 16 * num_desc + 8;
716
    default:
717
        return 8;
718
    }
719
}
720

    
721
static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
722
{
723
    switch (buf[0] >> 5) {
724
    case 0:
725
        cmd->xfer = buf[4];
726
        cmd->len = 6;
727
        break;
728
    case 1:
729
    case 2:
730
        cmd->xfer = lduw_be_p(&buf[7]);
731
        cmd->len = 10;
732
        break;
733
    case 4:
734
        cmd->xfer = ldl_be_p(&buf[10]) & 0xffffffffULL;
735
        cmd->len = 16;
736
        break;
737
    case 5:
738
        cmd->xfer = ldl_be_p(&buf[6]) & 0xffffffffULL;
739
        cmd->len = 12;
740
        break;
741
    default:
742
        return -1;
743
    }
744

    
745
    switch (buf[0]) {
746
    case TEST_UNIT_READY:
747
    case REWIND:
748
    case START_STOP:
749
    case SET_CAPACITY:
750
    case WRITE_FILEMARKS:
751
    case WRITE_FILEMARKS_16:
752
    case SPACE:
753
    case RESERVE:
754
    case RELEASE:
755
    case ERASE:
756
    case ALLOW_MEDIUM_REMOVAL:
757
    case VERIFY_10:
758
    case SEEK_10:
759
    case SYNCHRONIZE_CACHE:
760
    case SYNCHRONIZE_CACHE_16:
761
    case LOCATE_16:
762
    case LOCK_UNLOCK_CACHE:
763
    case LOAD_UNLOAD:
764
    case SET_CD_SPEED:
765
    case SET_LIMITS:
766
    case WRITE_LONG_10:
767
    case MOVE_MEDIUM:
768
    case UPDATE_BLOCK:
769
    case RESERVE_TRACK:
770
    case SET_READ_AHEAD:
771
    case PRE_FETCH:
772
    case PRE_FETCH_16:
773
    case ALLOW_OVERWRITE:
774
        cmd->xfer = 0;
775
        break;
776
    case MODE_SENSE:
777
        break;
778
    case WRITE_SAME_10:
779
    case WRITE_SAME_16:
780
        cmd->xfer = dev->blocksize;
781
        break;
782
    case READ_CAPACITY_10:
783
        cmd->xfer = 8;
784
        break;
785
    case READ_BLOCK_LIMITS:
786
        cmd->xfer = 6;
787
        break;
788
    case SEND_VOLUME_TAG:
789
        /* GPCMD_SET_STREAMING from multimedia commands.  */
790
        if (dev->type == TYPE_ROM) {
791
            cmd->xfer = buf[10] | (buf[9] << 8);
792
        } else {
793
            cmd->xfer = buf[9] | (buf[8] << 8);
794
        }
795
        break;
796
    case WRITE_6:
797
        /* length 0 means 256 blocks */
798
        if (cmd->xfer == 0) {
799
            cmd->xfer = 256;
800
        }
801
    case WRITE_10:
802
    case WRITE_VERIFY_10:
803
    case WRITE_12:
804
    case WRITE_VERIFY_12:
805
    case WRITE_16:
806
    case WRITE_VERIFY_16:
807
        cmd->xfer *= dev->blocksize;
808
        break;
809
    case READ_6:
810
    case READ_REVERSE:
811
        /* length 0 means 256 blocks */
812
        if (cmd->xfer == 0) {
813
            cmd->xfer = 256;
814
        }
815
    case READ_10:
816
    case RECOVER_BUFFERED_DATA:
817
    case READ_12:
818
    case READ_16:
819
        cmd->xfer *= dev->blocksize;
820
        break;
821
    case FORMAT_UNIT:
822
        /* MMC mandates the parameter list to be 12-bytes long.  Parameters
823
         * for block devices are restricted to the header right now.  */
824
        if (dev->type == TYPE_ROM && (buf[1] & 16)) {
825
            cmd->xfer = 12;
826
        } else {
827
            cmd->xfer = (buf[1] & 16) == 0 ? 0 : (buf[1] & 32 ? 8 : 4);
828
        }
829
        break;
830
    case INQUIRY:
831
    case RECEIVE_DIAGNOSTIC:
832
    case SEND_DIAGNOSTIC:
833
        cmd->xfer = buf[4] | (buf[3] << 8);
834
        break;
835
    case READ_CD:
836
    case READ_BUFFER:
837
    case WRITE_BUFFER:
838
    case SEND_CUE_SHEET:
839
        cmd->xfer = buf[8] | (buf[7] << 8) | (buf[6] << 16);
840
        break;
841
    case PERSISTENT_RESERVE_OUT:
842
        cmd->xfer = ldl_be_p(&buf[5]) & 0xffffffffULL;
843
        break;
844
    case ERASE_12:
845
        if (dev->type == TYPE_ROM) {
846
            /* MMC command GET PERFORMANCE.  */
847
            cmd->xfer = scsi_get_performance_length(buf[9] | (buf[8] << 8),
848
                                                    buf[10], buf[1] & 0x1f);
849
        }
850
        break;
851
    case MECHANISM_STATUS:
852
    case READ_DVD_STRUCTURE:
853
    case SEND_DVD_STRUCTURE:
854
    case MAINTENANCE_OUT:
855
    case MAINTENANCE_IN:
856
        if (dev->type == TYPE_ROM) {
857
            /* GPCMD_REPORT_KEY and GPCMD_SEND_KEY from multi media commands */
858
            cmd->xfer = buf[9] | (buf[8] << 8);
859
        }
860
        break;
861
    }
862
    return 0;
863
}
864

    
865
static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
866
{
867
    switch (buf[0]) {
868
    /* stream commands */
869
    case ERASE_12:
870
    case ERASE_16:
871
        cmd->xfer = 0;
872
        break;
873
    case READ_6:
874
    case READ_REVERSE:
875
    case RECOVER_BUFFERED_DATA:
876
    case WRITE_6:
877
        cmd->len = 6;
878
        cmd->xfer = buf[4] | (buf[3] << 8) | (buf[2] << 16);
879
        if (buf[1] & 0x01) { /* fixed */
880
            cmd->xfer *= dev->blocksize;
881
        }
882
        break;
883
    case READ_16:
884
    case READ_REVERSE_16:
885
    case VERIFY_16:
886
    case WRITE_16:
887
        cmd->len = 16;
888
        cmd->xfer = buf[14] | (buf[13] << 8) | (buf[12] << 16);
889
        if (buf[1] & 0x01) { /* fixed */
890
            cmd->xfer *= dev->blocksize;
891
        }
892
        break;
893
    case REWIND:
894
    case START_STOP:
895
        cmd->len = 6;
896
        cmd->xfer = 0;
897
        break;
898
    case SPACE_16:
899
        cmd->xfer = buf[13] | (buf[12] << 8);
900
        break;
901
    case READ_POSITION:
902
        cmd->xfer = buf[8] | (buf[7] << 8);
903
        break;
904
    case FORMAT_UNIT:
905
        cmd->xfer = buf[4] | (buf[3] << 8);
906
        break;
907
    /* generic commands */
908
    default:
909
        return scsi_req_length(cmd, dev, buf);
910
    }
911
    return 0;
912
}
913

    
914
static void scsi_cmd_xfer_mode(SCSICommand *cmd)
915
{
916
    if (!cmd->xfer) {
917
        cmd->mode = SCSI_XFER_NONE;
918
        return;
919
    }
920
    switch (cmd->buf[0]) {
921
    case WRITE_6:
922
    case WRITE_10:
923
    case WRITE_VERIFY_10:
924
    case WRITE_12:
925
    case WRITE_VERIFY_12:
926
    case WRITE_16:
927
    case WRITE_VERIFY_16:
928
    case COPY:
929
    case COPY_VERIFY:
930
    case COMPARE:
931
    case CHANGE_DEFINITION:
932
    case LOG_SELECT:
933
    case MODE_SELECT:
934
    case MODE_SELECT_10:
935
    case SEND_DIAGNOSTIC:
936
    case WRITE_BUFFER:
937
    case FORMAT_UNIT:
938
    case REASSIGN_BLOCKS:
939
    case SEARCH_EQUAL:
940
    case SEARCH_HIGH:
941
    case SEARCH_LOW:
942
    case UPDATE_BLOCK:
943
    case WRITE_LONG_10:
944
    case WRITE_SAME_10:
945
    case WRITE_SAME_16:
946
    case UNMAP:
947
    case SEARCH_HIGH_12:
948
    case SEARCH_EQUAL_12:
949
    case SEARCH_LOW_12:
950
    case MEDIUM_SCAN:
951
    case SEND_VOLUME_TAG:
952
    case SEND_CUE_SHEET:
953
    case SEND_DVD_STRUCTURE:
954
    case PERSISTENT_RESERVE_OUT:
955
    case MAINTENANCE_OUT:
956
    case ATA_PASSTHROUGH:
957
        cmd->mode = SCSI_XFER_TO_DEV;
958
        break;
959
    default:
960
        cmd->mode = SCSI_XFER_FROM_DEV;
961
        break;
962
    }
963
}
964

    
965
static uint64_t scsi_cmd_lba(SCSICommand *cmd)
966
{
967
    uint8_t *buf = cmd->buf;
968
    uint64_t lba;
969

    
970
    switch (buf[0] >> 5) {
971
    case 0:
972
        lba = ldl_be_p(&buf[0]) & 0x1fffff;
973
        break;
974
    case 1:
975
    case 2:
976
    case 5:
977
        lba = ldl_be_p(&buf[2]) & 0xffffffffULL;
978
        break;
979
    case 4:
980
        lba = ldq_be_p(&buf[2]);
981
        break;
982
    default:
983
        lba = -1;
984

    
985
    }
986
    return lba;
987
}
988

    
989
int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
990
{
991
    int rc;
992

    
993
    if (dev->type == TYPE_TAPE) {
994
        rc = scsi_req_stream_length(cmd, dev, buf);
995
    } else {
996
        rc = scsi_req_length(cmd, dev, buf);
997
    }
998
    if (rc != 0)
999
        return rc;
1000

    
1001
    memcpy(cmd->buf, buf, cmd->len);
1002
    scsi_cmd_xfer_mode(cmd);
1003
    cmd->lba = scsi_cmd_lba(cmd);
1004
    return 0;
1005
}
1006

    
1007
/*
1008
 * Predefined sense codes
1009
 */
1010

    
1011
/* No sense data available */
1012
const struct SCSISense sense_code_NO_SENSE = {
1013
    .key = NO_SENSE , .asc = 0x00 , .ascq = 0x00
1014
};
1015

    
1016
/* LUN not ready, Manual intervention required */
1017
const struct SCSISense sense_code_LUN_NOT_READY = {
1018
    .key = NOT_READY, .asc = 0x04, .ascq = 0x03
1019
};
1020

    
1021
/* LUN not ready, Medium not present */
1022
const struct SCSISense sense_code_NO_MEDIUM = {
1023
    .key = NOT_READY, .asc = 0x3a, .ascq = 0x00
1024
};
1025

    
1026
/* LUN not ready, medium removal prevented */
1027
const struct SCSISense sense_code_NOT_READY_REMOVAL_PREVENTED = {
1028
    .key = NOT_READY, .asc = 0x53, .ascq = 0x00
1029
};
1030

    
1031
/* Hardware error, internal target failure */
1032
const struct SCSISense sense_code_TARGET_FAILURE = {
1033
    .key = HARDWARE_ERROR, .asc = 0x44, .ascq = 0x00
1034
};
1035

    
1036
/* Illegal request, invalid command operation code */
1037
const struct SCSISense sense_code_INVALID_OPCODE = {
1038
    .key = ILLEGAL_REQUEST, .asc = 0x20, .ascq = 0x00
1039
};
1040

    
1041
/* Illegal request, LBA out of range */
1042
const struct SCSISense sense_code_LBA_OUT_OF_RANGE = {
1043
    .key = ILLEGAL_REQUEST, .asc = 0x21, .ascq = 0x00
1044
};
1045

    
1046
/* Illegal request, Invalid field in CDB */
1047
const struct SCSISense sense_code_INVALID_FIELD = {
1048
    .key = ILLEGAL_REQUEST, .asc = 0x24, .ascq = 0x00
1049
};
1050

    
1051
/* Illegal request, LUN not supported */
1052
const struct SCSISense sense_code_LUN_NOT_SUPPORTED = {
1053
    .key = ILLEGAL_REQUEST, .asc = 0x25, .ascq = 0x00
1054
};
1055

    
1056
/* Illegal request, Saving parameters not supported */
1057
const struct SCSISense sense_code_SAVING_PARAMS_NOT_SUPPORTED = {
1058
    .key = ILLEGAL_REQUEST, .asc = 0x39, .ascq = 0x00
1059
};
1060

    
1061
/* Illegal request, Incompatible medium installed */
1062
const struct SCSISense sense_code_INCOMPATIBLE_FORMAT = {
1063
    .key = ILLEGAL_REQUEST, .asc = 0x30, .ascq = 0x00
1064
};
1065

    
1066
/* Illegal request, medium removal prevented */
1067
const struct SCSISense sense_code_ILLEGAL_REQ_REMOVAL_PREVENTED = {
1068
    .key = ILLEGAL_REQUEST, .asc = 0x53, .ascq = 0x00
1069
};
1070

    
1071
/* Command aborted, I/O process terminated */
1072
const struct SCSISense sense_code_IO_ERROR = {
1073
    .key = ABORTED_COMMAND, .asc = 0x00, .ascq = 0x06
1074
};
1075

    
1076
/* Command aborted, I_T Nexus loss occurred */
1077
const struct SCSISense sense_code_I_T_NEXUS_LOSS = {
1078
    .key = ABORTED_COMMAND, .asc = 0x29, .ascq = 0x07
1079
};
1080

    
1081
/* Command aborted, Logical Unit failure */
1082
const struct SCSISense sense_code_LUN_FAILURE = {
1083
    .key = ABORTED_COMMAND, .asc = 0x3e, .ascq = 0x01
1084
};
1085

    
1086
/* Unit attention, Power on, reset or bus device reset occurred */
1087
const struct SCSISense sense_code_RESET = {
1088
    .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x00
1089
};
1090

    
1091
/* Unit attention, No medium */
1092
const struct SCSISense sense_code_UNIT_ATTENTION_NO_MEDIUM = {
1093
    .key = UNIT_ATTENTION, .asc = 0x3a, .ascq = 0x00
1094
};
1095

    
1096
/* Unit attention, Medium may have changed */
1097
const struct SCSISense sense_code_MEDIUM_CHANGED = {
1098
    .key = UNIT_ATTENTION, .asc = 0x28, .ascq = 0x00
1099
};
1100

    
1101
/* Unit attention, Reported LUNs data has changed */
1102
const struct SCSISense sense_code_REPORTED_LUNS_CHANGED = {
1103
    .key = UNIT_ATTENTION, .asc = 0x3f, .ascq = 0x0e
1104
};
1105

    
1106
/* Unit attention, Device internal reset */
1107
const struct SCSISense sense_code_DEVICE_INTERNAL_RESET = {
1108
    .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x04
1109
};
1110

    
1111
/*
1112
 * scsi_build_sense
1113
 *
1114
 * Convert between fixed and descriptor sense buffers
1115
 */
1116
int scsi_build_sense(uint8_t *in_buf, int in_len,
1117
                     uint8_t *buf, int len, bool fixed)
1118
{
1119
    bool fixed_in;
1120
    SCSISense sense;
1121
    if (!fixed && len < 8) {
1122
        return 0;
1123
    }
1124

    
1125
    if (in_len == 0) {
1126
        sense.key = NO_SENSE;
1127
        sense.asc = 0;
1128
        sense.ascq = 0;
1129
    } else {
1130
        fixed_in = (in_buf[0] & 2) == 0;
1131

    
1132
        if (fixed == fixed_in) {
1133
            memcpy(buf, in_buf, MIN(len, in_len));
1134
            return MIN(len, in_len);
1135
        }
1136

    
1137
        if (fixed_in) {
1138
            sense.key = in_buf[2];
1139
            sense.asc = in_buf[12];
1140
            sense.ascq = in_buf[13];
1141
        } else {
1142
            sense.key = in_buf[1];
1143
            sense.asc = in_buf[2];
1144
            sense.ascq = in_buf[3];
1145
        }
1146
    }
1147

    
1148
    memset(buf, 0, len);
1149
    if (fixed) {
1150
        /* Return fixed format sense buffer */
1151
        buf[0] = 0x70;
1152
        buf[2] = sense.key;
1153
        buf[7] = 10;
1154
        buf[12] = sense.asc;
1155
        buf[13] = sense.ascq;
1156
        return MIN(len, 18);
1157
    } else {
1158
        /* Return descriptor format sense buffer */
1159
        buf[0] = 0x72;
1160
        buf[1] = sense.key;
1161
        buf[2] = sense.asc;
1162
        buf[3] = sense.ascq;
1163
        return 8;
1164
    }
1165
}
1166

    
1167
static const char *scsi_command_name(uint8_t cmd)
1168
{
1169
    static const char *names[] = {
1170
        [ TEST_UNIT_READY          ] = "TEST_UNIT_READY",
1171
        [ REWIND                   ] = "REWIND",
1172
        [ REQUEST_SENSE            ] = "REQUEST_SENSE",
1173
        [ FORMAT_UNIT              ] = "FORMAT_UNIT",
1174
        [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",
1175
        [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS",
1176
        [ READ_6                   ] = "READ_6",
1177
        [ WRITE_6                  ] = "WRITE_6",
1178
        [ SET_CAPACITY             ] = "SET_CAPACITY",
1179
        [ READ_REVERSE             ] = "READ_REVERSE",
1180
        [ WRITE_FILEMARKS          ] = "WRITE_FILEMARKS",
1181
        [ SPACE                    ] = "SPACE",
1182
        [ INQUIRY                  ] = "INQUIRY",
1183
        [ RECOVER_BUFFERED_DATA    ] = "RECOVER_BUFFERED_DATA",
1184
        [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",
1185
        [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",
1186
        [ MODE_SELECT              ] = "MODE_SELECT",
1187
        [ RESERVE                  ] = "RESERVE",
1188
        [ RELEASE                  ] = "RELEASE",
1189
        [ COPY                     ] = "COPY",
1190
        [ ERASE                    ] = "ERASE",
1191
        [ MODE_SENSE               ] = "MODE_SENSE",
1192
        [ START_STOP               ] = "START_STOP",
1193
        [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",
1194
        [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",
1195
        [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",
1196
        [ READ_CAPACITY_10         ] = "READ_CAPACITY_10",
1197
        [ READ_10                  ] = "READ_10",
1198
        [ WRITE_10                 ] = "WRITE_10",
1199
        [ SEEK_10                  ] = "SEEK_10",
1200
        [ WRITE_VERIFY_10          ] = "WRITE_VERIFY_10",
1201
        [ VERIFY_10                ] = "VERIFY_10",
1202
        [ SEARCH_HIGH              ] = "SEARCH_HIGH",
1203
        [ SEARCH_EQUAL             ] = "SEARCH_EQUAL",
1204
        [ SEARCH_LOW               ] = "SEARCH_LOW",
1205
        [ SET_LIMITS               ] = "SET_LIMITS",
1206
        [ PRE_FETCH                ] = "PRE_FETCH/READ_POSITION",
1207
        /* READ_POSITION and PRE_FETCH use the same operation code */
1208
        [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",
1209
        [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",
1210
        [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA",
1211
        [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",
1212
        [ COMPARE                  ] = "COMPARE",
1213
        [ COPY_VERIFY              ] = "COPY_VERIFY",
1214
        [ WRITE_BUFFER             ] = "WRITE_BUFFER",
1215
        [ READ_BUFFER              ] = "READ_BUFFER",
1216
        [ UPDATE_BLOCK             ] = "UPDATE_BLOCK",
1217
        [ READ_LONG_10             ] = "READ_LONG_10",
1218
        [ WRITE_LONG_10            ] = "WRITE_LONG_10",
1219
        [ CHANGE_DEFINITION        ] = "CHANGE_DEFINITION",
1220
        [ WRITE_SAME_10            ] = "WRITE_SAME_10",
1221
        [ UNMAP                    ] = "UNMAP",
1222
        [ READ_TOC                 ] = "READ_TOC",
1223
        [ REPORT_DENSITY_SUPPORT   ] = "REPORT_DENSITY_SUPPORT",
1224
        [ SANITIZE                 ] = "SANITIZE",
1225
        [ GET_CONFIGURATION        ] = "GET_CONFIGURATION",
1226
        [ LOG_SELECT               ] = "LOG_SELECT",
1227
        [ LOG_SENSE                ] = "LOG_SENSE",
1228
        [ MODE_SELECT_10           ] = "MODE_SELECT_10",
1229
        [ RESERVE_10               ] = "RESERVE_10",
1230
        [ RELEASE_10               ] = "RELEASE_10",
1231
        [ MODE_SENSE_10            ] = "MODE_SENSE_10",
1232
        [ PERSISTENT_RESERVE_IN    ] = "PERSISTENT_RESERVE_IN",
1233
        [ PERSISTENT_RESERVE_OUT   ] = "PERSISTENT_RESERVE_OUT",
1234
        [ WRITE_FILEMARKS_16       ] = "WRITE_FILEMARKS_16",
1235
        [ EXTENDED_COPY            ] = "EXTENDED_COPY",
1236
        [ ATA_PASSTHROUGH          ] = "ATA_PASSTHROUGH",
1237
        [ ACCESS_CONTROL_IN        ] = "ACCESS_CONTROL_IN",
1238
        [ ACCESS_CONTROL_OUT       ] = "ACCESS_CONTROL_OUT",
1239
        [ READ_16                  ] = "READ_16",
1240
        [ COMPARE_AND_WRITE        ] = "COMPARE_AND_WRITE",
1241
        [ WRITE_16                 ] = "WRITE_16",
1242
        [ WRITE_VERIFY_16          ] = "WRITE_VERIFY_16",
1243
        [ VERIFY_16                ] = "VERIFY_16",
1244
        [ PRE_FETCH_16             ] = "PRE_FETCH_16",
1245
        [ SYNCHRONIZE_CACHE_16     ] = "SPACE_16/SYNCHRONIZE_CACHE_16",
1246
        /* SPACE_16 and SYNCHRONIZE_CACHE_16 use the same operation code */
1247
        [ LOCATE_16                ] = "LOCATE_16",
1248
        [ WRITE_SAME_16            ] = "ERASE_16/WRITE_SAME_16",
1249
        /* ERASE_16 and WRITE_SAME_16 use the same operation code */
1250
        [ SERVICE_ACTION_IN_16     ] = "SERVICE_ACTION_IN_16",
1251
        [ WRITE_LONG_16            ] = "WRITE_LONG_16",
1252
        [ REPORT_LUNS              ] = "REPORT_LUNS",
1253
        [ BLANK                    ] = "BLANK",
1254
        [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
1255
        [ LOAD_UNLOAD              ] = "LOAD_UNLOAD",
1256
        [ READ_12                  ] = "READ_12",
1257
        [ WRITE_12                 ] = "WRITE_12",
1258
        [ ERASE_12                 ] = "ERASE_12/GET_PERFORMANCE",
1259
        /* ERASE_12 and GET_PERFORMANCE use the same operation code */
1260
        [ SERVICE_ACTION_IN_12     ] = "SERVICE_ACTION_IN_12",
1261
        [ WRITE_VERIFY_12          ] = "WRITE_VERIFY_12",
1262
        [ VERIFY_12                ] = "VERIFY_12",
1263
        [ SEARCH_HIGH_12           ] = "SEARCH_HIGH_12",
1264
        [ SEARCH_EQUAL_12          ] = "SEARCH_EQUAL_12",
1265
        [ SEARCH_LOW_12            ] = "SEARCH_LOW_12",
1266
        [ READ_ELEMENT_STATUS      ] = "READ_ELEMENT_STATUS",
1267
        [ SEND_VOLUME_TAG          ] = "SEND_VOLUME_TAG/SET_STREAMING",
1268
        /* SEND_VOLUME_TAG and SET_STREAMING use the same operation code */
1269
        [ READ_CD                  ] = "READ_CD",
1270
        [ READ_DEFECT_DATA_12      ] = "READ_DEFECT_DATA_12",
1271
        [ READ_DVD_STRUCTURE       ] = "READ_DVD_STRUCTURE",
1272
        [ RESERVE_TRACK            ] = "RESERVE_TRACK",
1273
        [ SEND_CUE_SHEET           ] = "SEND_CUE_SHEET",
1274
        [ SEND_DVD_STRUCTURE       ] = "SEND_DVD_STRUCTURE",
1275
        [ SET_CD_SPEED             ] = "SET_CD_SPEED",
1276
        [ SET_READ_AHEAD           ] = "SET_READ_AHEAD",
1277
        [ ALLOW_OVERWRITE          ] = "ALLOW_OVERWRITE",
1278
        [ MECHANISM_STATUS         ] = "MECHANISM_STATUS",
1279
    };
1280

    
1281
    if (cmd >= ARRAY_SIZE(names) || names[cmd] == NULL)
1282
        return "*UNKNOWN*";
1283
    return names[cmd];
1284
}
1285

    
1286
SCSIRequest *scsi_req_ref(SCSIRequest *req)
1287
{
1288
    req->refcount++;
1289
    return req;
1290
}
1291

    
1292
void scsi_req_unref(SCSIRequest *req)
1293
{
1294
    assert(req->refcount > 0);
1295
    if (--req->refcount == 0) {
1296
        if (req->ops->free_req) {
1297
            req->ops->free_req(req);
1298
        }
1299
        g_free(req);
1300
    }
1301
}
1302

    
1303
/* Tell the device that we finished processing this chunk of I/O.  It
1304
   will start the next chunk or complete the command.  */
1305
void scsi_req_continue(SCSIRequest *req)
1306
{
1307
    trace_scsi_req_continue(req->dev->id, req->lun, req->tag);
1308
    if (req->cmd.mode == SCSI_XFER_TO_DEV) {
1309
        req->ops->write_data(req);
1310
    } else {
1311
        req->ops->read_data(req);
1312
    }
1313
}
1314

    
1315
/* Called by the devices when data is ready for the HBA.  The HBA should
1316
   start a DMA operation to read or fill the device's data buffer.
1317
   Once it completes, calling scsi_req_continue will restart I/O.  */
1318
void scsi_req_data(SCSIRequest *req, int len)
1319
{
1320
    uint8_t *buf;
1321
    if (req->io_canceled) {
1322
        trace_scsi_req_data_canceled(req->dev->id, req->lun, req->tag, len);
1323
        return;
1324
    }
1325
    trace_scsi_req_data(req->dev->id, req->lun, req->tag, len);
1326
    assert(req->cmd.mode != SCSI_XFER_NONE);
1327
    if (!req->sg) {
1328
        req->resid -= len;
1329
        req->bus->info->transfer_data(req, len);
1330
        return;
1331
    }
1332

    
1333
    /* If the device calls scsi_req_data and the HBA specified a
1334
     * scatter/gather list, the transfer has to happen in a single
1335
     * step.  */
1336
    assert(!req->dma_started);
1337
    req->dma_started = true;
1338

    
1339
    buf = scsi_req_get_buf(req);
1340
    if (req->cmd.mode == SCSI_XFER_FROM_DEV) {
1341
        req->resid = dma_buf_read(buf, len, req->sg);
1342
    } else {
1343
        req->resid = dma_buf_write(buf, len, req->sg);
1344
    }
1345
    scsi_req_continue(req);
1346
}
1347

    
1348
void scsi_req_print(SCSIRequest *req)
1349
{
1350
    FILE *fp = stderr;
1351
    int i;
1352

    
1353
    fprintf(fp, "[%s id=%d] %s",
1354
            req->dev->qdev.parent_bus->name,
1355
            req->dev->id,
1356
            scsi_command_name(req->cmd.buf[0]));
1357
    for (i = 1; i < req->cmd.len; i++) {
1358
        fprintf(fp, " 0x%02x", req->cmd.buf[i]);
1359
    }
1360
    switch (req->cmd.mode) {
1361
    case SCSI_XFER_NONE:
1362
        fprintf(fp, " - none\n");
1363
        break;
1364
    case SCSI_XFER_FROM_DEV:
1365
        fprintf(fp, " - from-dev len=%zd\n", req->cmd.xfer);
1366
        break;
1367
    case SCSI_XFER_TO_DEV:
1368
        fprintf(fp, " - to-dev len=%zd\n", req->cmd.xfer);
1369
        break;
1370
    default:
1371
        fprintf(fp, " - Oops\n");
1372
        break;
1373
    }
1374
}
1375

    
1376
void scsi_req_complete(SCSIRequest *req, int status)
1377
{
1378
    assert(req->status == -1);
1379
    req->status = status;
1380

    
1381
    assert(req->sense_len < sizeof(req->sense));
1382
    if (status == GOOD) {
1383
        req->sense_len = 0;
1384
    }
1385

    
1386
    if (req->sense_len) {
1387
        memcpy(req->dev->sense, req->sense, req->sense_len);
1388
        req->dev->sense_len = req->sense_len;
1389
        req->dev->sense_is_ua = (req->ops == &reqops_unit_attention);
1390
    } else {
1391
        req->dev->sense_len = 0;
1392
        req->dev->sense_is_ua = false;
1393
    }
1394

    
1395
    /*
1396
     * Unit attention state is now stored in the device's sense buffer
1397
     * if the HBA didn't do autosense.  Clear the pending unit attention
1398
     * flags.
1399
     */
1400
    scsi_clear_unit_attention(req);
1401

    
1402
    scsi_req_ref(req);
1403
    scsi_req_dequeue(req);
1404
    req->bus->info->complete(req, req->status, req->resid);
1405
    scsi_req_unref(req);
1406
}
1407

    
1408
void scsi_req_cancel(SCSIRequest *req)
1409
{
1410
    if (!req->enqueued) {
1411
        return;
1412
    }
1413
    scsi_req_ref(req);
1414
    scsi_req_dequeue(req);
1415
    req->io_canceled = true;
1416
    if (req->ops->cancel_io) {
1417
        req->ops->cancel_io(req);
1418
    }
1419
    if (req->bus->info->cancel) {
1420
        req->bus->info->cancel(req);
1421
    }
1422
    scsi_req_unref(req);
1423
}
1424

    
1425
void scsi_req_abort(SCSIRequest *req, int status)
1426
{
1427
    if (!req->enqueued) {
1428
        return;
1429
    }
1430
    scsi_req_ref(req);
1431
    scsi_req_dequeue(req);
1432
    req->io_canceled = true;
1433
    if (req->ops->cancel_io) {
1434
        req->ops->cancel_io(req);
1435
    }
1436
    scsi_req_complete(req, status);
1437
    scsi_req_unref(req);
1438
}
1439

    
1440
void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense)
1441
{
1442
    SCSIRequest *req;
1443

    
1444
    while (!QTAILQ_EMPTY(&sdev->requests)) {
1445
        req = QTAILQ_FIRST(&sdev->requests);
1446
        scsi_req_cancel(req);
1447
    }
1448
    sdev->unit_attention = sense;
1449
}
1450

    
1451
static char *scsibus_get_dev_path(DeviceState *dev)
1452
{
1453
    SCSIDevice *d = DO_UPCAST(SCSIDevice, qdev, dev);
1454
    DeviceState *hba = dev->parent_bus->parent;
1455
    char *id = NULL;
1456
    char *path;
1457

    
1458
    if (hba && hba->parent_bus && hba->parent_bus->info->get_dev_path) {
1459
        id = hba->parent_bus->info->get_dev_path(hba);
1460
    }
1461
    if (id) {
1462
        path = g_strdup_printf("%s/%d:%d:%d", id, d->channel, d->id, d->lun);
1463
    } else {
1464
        path = g_strdup_printf("%d:%d:%d", d->channel, d->id, d->lun);
1465
    }
1466
    g_free(id);
1467
    return path;
1468
}
1469

    
1470
static char *scsibus_get_fw_dev_path(DeviceState *dev)
1471
{
1472
    SCSIDevice *d = SCSI_DEVICE(dev);
1473
    char path[100];
1474

    
1475
    snprintf(path, sizeof(path), "channel@%x/%s@%x,%x", d->channel,
1476
             qdev_fw_name(dev), d->id, d->lun);
1477

    
1478
    return strdup(path);
1479
}
1480

    
1481
SCSIDevice *scsi_device_find(SCSIBus *bus, int channel, int id, int lun)
1482
{
1483
    DeviceState *qdev;
1484
    SCSIDevice *target_dev = NULL;
1485

    
1486
    QTAILQ_FOREACH_REVERSE(qdev, &bus->qbus.children, ChildrenHead, sibling) {
1487
        SCSIDevice *dev = SCSI_DEVICE(qdev);
1488

    
1489
        if (dev->channel == channel && dev->id == id) {
1490
            if (dev->lun == lun) {
1491
                return dev;
1492
            }
1493
            target_dev = dev;
1494
        }
1495
    }
1496
    return target_dev;
1497
}
1498

    
1499
/* SCSI request list.  For simplicity, pv points to the whole device */
1500

    
1501
static void put_scsi_requests(QEMUFile *f, void *pv, size_t size)
1502
{
1503
    SCSIDevice *s = pv;
1504
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
1505
    SCSIRequest *req;
1506

    
1507
    QTAILQ_FOREACH(req, &s->requests, next) {
1508
        assert(!req->io_canceled);
1509
        assert(req->status == -1);
1510
        assert(req->retry);
1511
        assert(req->enqueued);
1512

    
1513
        qemu_put_sbyte(f, 1);
1514
        qemu_put_buffer(f, req->cmd.buf, sizeof(req->cmd.buf));
1515
        qemu_put_be32s(f, &req->tag);
1516
        qemu_put_be32s(f, &req->lun);
1517
        if (bus->info->save_request) {
1518
            bus->info->save_request(f, req);
1519
        }
1520
        if (req->ops->save_request) {
1521
            req->ops->save_request(f, req);
1522
        }
1523
    }
1524
    qemu_put_sbyte(f, 0);
1525
}
1526

    
1527
static int get_scsi_requests(QEMUFile *f, void *pv, size_t size)
1528
{
1529
    SCSIDevice *s = pv;
1530
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
1531

    
1532
    while (qemu_get_sbyte(f)) {
1533
        uint8_t buf[SCSI_CMD_BUF_SIZE];
1534
        uint32_t tag;
1535
        uint32_t lun;
1536
        SCSIRequest *req;
1537

    
1538
        qemu_get_buffer(f, buf, sizeof(buf));
1539
        qemu_get_be32s(f, &tag);
1540
        qemu_get_be32s(f, &lun);
1541
        req = scsi_req_new(s, tag, lun, buf, NULL);
1542
        if (bus->info->load_request) {
1543
            req->hba_private = bus->info->load_request(f, req);
1544
        }
1545
        if (req->ops->load_request) {
1546
            req->ops->load_request(f, req);
1547
        }
1548

    
1549
        /* Just restart it later.  */
1550
        req->retry = true;
1551
        scsi_req_enqueue_internal(req);
1552

    
1553
        /* At this point, the request will be kept alive by the reference
1554
         * added by scsi_req_enqueue_internal, so we can release our reference.
1555
         * The HBA of course will add its own reference in the load_request
1556
         * callback if it needs to hold on the SCSIRequest.
1557
         */
1558
        scsi_req_unref(req);
1559
    }
1560

    
1561
    return 0;
1562
}
1563

    
1564
static const VMStateInfo vmstate_info_scsi_requests = {
1565
    .name = "scsi-requests",
1566
    .get  = get_scsi_requests,
1567
    .put  = put_scsi_requests,
1568
};
1569

    
1570
const VMStateDescription vmstate_scsi_device = {
1571
    .name = "SCSIDevice",
1572
    .version_id = 1,
1573
    .minimum_version_id = 1,
1574
    .minimum_version_id_old = 1,
1575
    .fields = (VMStateField[]) {
1576
        VMSTATE_UINT8(unit_attention.key, SCSIDevice),
1577
        VMSTATE_UINT8(unit_attention.asc, SCSIDevice),
1578
        VMSTATE_UINT8(unit_attention.ascq, SCSIDevice),
1579
        VMSTATE_BOOL(sense_is_ua, SCSIDevice),
1580
        VMSTATE_UINT8_ARRAY(sense, SCSIDevice, SCSI_SENSE_BUF_SIZE),
1581
        VMSTATE_UINT32(sense_len, SCSIDevice),
1582
        {
1583
            .name         = "requests",
1584
            .version_id   = 0,
1585
            .field_exists = NULL,
1586
            .size         = 0,   /* ouch */
1587
            .info         = &vmstate_info_scsi_requests,
1588
            .flags        = VMS_SINGLE,
1589
            .offset       = 0,
1590
        },
1591
        VMSTATE_END_OF_LIST()
1592
    }
1593
};
1594

    
1595
static void scsi_device_class_init(ObjectClass *klass, void *data)
1596
{
1597
    DeviceClass *k = DEVICE_CLASS(klass);
1598
    k->bus_info = &scsi_bus_info;
1599
    k->init     = scsi_qdev_init;
1600
    k->unplug   = qdev_simple_unplug_cb;
1601
    k->exit     = scsi_qdev_exit;
1602
}
1603

    
1604
static TypeInfo scsi_device_type_info = {
1605
    .name = TYPE_SCSI_DEVICE,
1606
    .parent = TYPE_DEVICE,
1607
    .instance_size = sizeof(SCSIDevice),
1608
    .abstract = true,
1609
    .class_size = sizeof(SCSIDeviceClass),
1610
    .class_init = scsi_device_class_init,
1611
};
1612

    
1613
static void scsi_register_types(void)
1614
{
1615
    type_register_static(&scsi_device_type_info);
1616
}
1617

    
1618
type_init(scsi_register_types)