xref: /freebsd/usr.sbin/bhyve/pci_virtio_scsi.c (revision ab40f58ccfe6c07ebefddc72f4661a52fe746353)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2016 Jakub Klama <jceel@FreeBSD.org>.
5  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer
13  *    in this position and unchanged.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #include <sys/linker_set.h>
36 #include <sys/types.h>
37 #include <sys/uio.h>
38 #include <sys/time.h>
39 #include <sys/queue.h>
40 #include <sys/sbuf.h>
41 
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdbool.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <assert.h>
50 #include <pthread.h>
51 #include <pthread_np.h>
52 
53 #include <cam/scsi/scsi_all.h>
54 #include <cam/scsi/scsi_message.h>
55 #include <cam/ctl/ctl.h>
56 #include <cam/ctl/ctl_io.h>
57 #include <cam/ctl/ctl_backend.h>
58 #include <cam/ctl/ctl_ioctl.h>
59 #include <cam/ctl/ctl_util.h>
60 #include <cam/ctl/ctl_scsi_all.h>
61 #include <camlib.h>
62 
63 #include "bhyverun.h"
64 #include "pci_emul.h"
65 #include "virtio.h"
66 #include "iov.h"
67 
68 #define VTSCSI_RINGSZ		64
69 #define	VTSCSI_REQUESTQ		1
70 #define	VTSCSI_THR_PER_Q	16
71 #define	VTSCSI_MAXQ		(VTSCSI_REQUESTQ + 2)
72 #define	VTSCSI_MAXSEG		64
73 
74 #define	VTSCSI_IN_HEADER_LEN(_sc)	\
75 	(sizeof(struct pci_vtscsi_req_cmd_rd) + _sc->vss_config.cdb_size)
76 
77 #define	VTSCSI_OUT_HEADER_LEN(_sc) 	\
78 	(sizeof(struct pci_vtscsi_req_cmd_wr) + _sc->vss_config.sense_size)
79 
80 #define	VIRTIO_SCSI_MAX_CHANNEL	0
81 #define	VIRTIO_SCSI_MAX_TARGET	0
82 #define	VIRTIO_SCSI_MAX_LUN	16383
83 
84 #define	VIRTIO_SCSI_F_INOUT	(1 << 0)
85 #define	VIRTIO_SCSI_F_HOTPLUG	(1 << 1)
86 #define	VIRTIO_SCSI_F_CHANGE	(1 << 2)
87 
88 static int pci_vtscsi_debug = 0;
89 #define	DPRINTF(params) if (pci_vtscsi_debug) printf params
90 #define	WPRINTF(params) printf params
91 
92 struct pci_vtscsi_config {
93 	uint32_t num_queues;
94 	uint32_t seg_max;
95 	uint32_t max_sectors;
96 	uint32_t cmd_per_lun;
97 	uint32_t event_info_size;
98 	uint32_t sense_size;
99 	uint32_t cdb_size;
100 	uint16_t max_channel;
101 	uint16_t max_target;
102 	uint32_t max_lun;
103 } __attribute__((packed));
104 
105 struct pci_vtscsi_queue {
106 	struct pci_vtscsi_softc *         vsq_sc;
107 	struct vqueue_info *              vsq_vq;
108 	int                               vsq_ctl_fd;
109 	pthread_mutex_t                   vsq_mtx;
110 	pthread_mutex_t                   vsq_qmtx;
111 	pthread_cond_t                    vsq_cv;
112 	STAILQ_HEAD(, pci_vtscsi_request) vsq_requests;
113 	LIST_HEAD(, pci_vtscsi_worker)    vsq_workers;
114 };
115 
116 struct pci_vtscsi_worker {
117 	struct pci_vtscsi_queue *     vsw_queue;
118 	pthread_t                     vsw_thread;
119 	bool                          vsw_exiting;
120 	LIST_ENTRY(pci_vtscsi_worker) vsw_link;
121 };
122 
123 struct pci_vtscsi_request {
124 	struct pci_vtscsi_queue * vsr_queue;
125 	struct iovec              vsr_iov_in[VTSCSI_MAXSEG];
126 	int                       vsr_niov_in;
127 	struct iovec              vsr_iov_out[VTSCSI_MAXSEG];
128 	int                       vsr_niov_out;
129 	uint32_t                  vsr_idx;
130 	STAILQ_ENTRY(pci_vtscsi_request) vsr_link;
131 };
132 
133 /*
134  * Per-device softc
135  */
136 struct pci_vtscsi_softc {
137 	struct virtio_softc      vss_vs;
138 	struct vqueue_info       vss_vq[VTSCSI_MAXQ];
139 	struct pci_vtscsi_queue  vss_queues[VTSCSI_REQUESTQ];
140 	pthread_mutex_t          vss_mtx;
141 	int                      vss_iid;
142 	int                      vss_ctl_fd;
143 	uint32_t                 vss_features;
144 	struct pci_vtscsi_config vss_config;
145 };
146 
147 #define	VIRTIO_SCSI_T_TMF			0
148 #define	VIRTIO_SCSI_T_TMF_ABORT_TASK		0
149 #define	VIRTIO_SCSI_T_TMF_ABORT_TASK_SET	1
150 #define	VIRTIO_SCSI_T_TMF_CLEAR_ACA		2
151 #define	VIRTIO_SCSI_T_TMF_CLEAR_TASK_SET	3
152 #define	VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET	4
153 #define	VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET	5
154 #define	VIRTIO_SCSI_T_TMF_QUERY_TASK		6
155 #define	VIRTIO_SCSI_T_TMF_QUERY_TASK_SET 	7
156 
157 /* command-specific response values */
158 #define	VIRTIO_SCSI_S_FUNCTION_COMPLETE		0
159 #define	VIRTIO_SCSI_S_FUNCTION_SUCCEEDED	10
160 #define	VIRTIO_SCSI_S_FUNCTION_REJECTED		11
161 
162 struct pci_vtscsi_ctrl_tmf {
163 	uint32_t type;
164 	uint32_t subtype;
165 	uint8_t lun[8];
166 	uint64_t id;
167 	uint8_t response;
168 } __attribute__((packed));
169 
170 #define	VIRTIO_SCSI_T_AN_QUERY			1
171 #define	VIRTIO_SCSI_EVT_ASYNC_OPERATIONAL_CHANGE 2
172 #define	VIRTIO_SCSI_EVT_ASYNC_POWER_MGMT	4
173 #define	VIRTIO_SCSI_EVT_ASYNC_EXTERNAL_REQUEST	8
174 #define	VIRTIO_SCSI_EVT_ASYNC_MEDIA_CHANGE	16
175 #define	VIRTIO_SCSI_EVT_ASYNC_MULTI_HOST	32
176 #define	VIRTIO_SCSI_EVT_ASYNC_DEVICE_BUSY	64
177 
178 struct pci_vtscsi_ctrl_an {
179 	uint32_t type;
180 	uint8_t lun[8];
181 	uint32_t event_requested;
182 	uint32_t event_actual;
183 	uint8_t response;
184 } __attribute__((packed));
185 
186 /* command-specific response values */
187 #define	VIRTIO_SCSI_S_OK 			0
188 #define	VIRTIO_SCSI_S_OVERRUN			1
189 #define	VIRTIO_SCSI_S_ABORTED			2
190 #define	VIRTIO_SCSI_S_BAD_TARGET		3
191 #define	VIRTIO_SCSI_S_RESET			4
192 #define	VIRTIO_SCSI_S_BUSY			5
193 #define	VIRTIO_SCSI_S_TRANSPORT_FAILURE		6
194 #define	VIRTIO_SCSI_S_TARGET_FAILURE		7
195 #define	VIRTIO_SCSI_S_NEXUS_FAILURE		8
196 #define	VIRTIO_SCSI_S_FAILURE			9
197 #define	VIRTIO_SCSI_S_INCORRECT_LUN		12
198 
199 /* task_attr */
200 #define	VIRTIO_SCSI_S_SIMPLE			0
201 #define	VIRTIO_SCSI_S_ORDERED			1
202 #define	VIRTIO_SCSI_S_HEAD			2
203 #define	VIRTIO_SCSI_S_ACA			3
204 
205 struct pci_vtscsi_event {
206 	uint32_t event;
207 	uint8_t lun[8];
208 	uint32_t reason;
209 } __attribute__((packed));
210 
211 struct pci_vtscsi_req_cmd_rd {
212 	uint8_t lun[8];
213 	uint64_t id;
214 	uint8_t task_attr;
215 	uint8_t prio;
216 	uint8_t crn;
217 	uint8_t cdb[];
218 } __attribute__((packed));
219 
220 struct pci_vtscsi_req_cmd_wr {
221 	uint32_t sense_len;
222 	uint32_t residual;
223 	uint16_t status_qualifier;
224 	uint8_t status;
225 	uint8_t response;
226 	uint8_t sense[];
227 } __attribute__((packed));
228 
229 static void *pci_vtscsi_proc(void *);
230 static void pci_vtscsi_reset(void *);
231 static void pci_vtscsi_neg_features(void *, uint64_t);
232 static int pci_vtscsi_cfgread(void *, int, int, uint32_t *);
233 static int pci_vtscsi_cfgwrite(void *, int, int, uint32_t);
234 static inline int pci_vtscsi_get_lun(uint8_t *);
235 static int pci_vtscsi_control_handle(struct pci_vtscsi_softc *, void *, size_t);
236 static int pci_vtscsi_tmf_handle(struct pci_vtscsi_softc *,
237     struct pci_vtscsi_ctrl_tmf *);
238 static int pci_vtscsi_an_handle(struct pci_vtscsi_softc *,
239     struct pci_vtscsi_ctrl_an *);
240 static int pci_vtscsi_request_handle(struct pci_vtscsi_queue *, struct iovec *,
241     int, struct iovec *, int);
242 static void pci_vtscsi_controlq_notify(void *, struct vqueue_info *);
243 static void pci_vtscsi_eventq_notify(void *, struct vqueue_info *);
244 static void pci_vtscsi_requestq_notify(void *, struct vqueue_info *);
245 static int  pci_vtscsi_init_queue(struct pci_vtscsi_softc *,
246     struct pci_vtscsi_queue *, int);
247 static int pci_vtscsi_init(struct vmctx *, struct pci_devinst *, char *);
248 
249 static struct virtio_consts vtscsi_vi_consts = {
250 	"vtscsi",				/* our name */
251 	VTSCSI_MAXQ,				/* we support 2+n virtqueues */
252 	sizeof(struct pci_vtscsi_config),	/* config reg size */
253 	pci_vtscsi_reset,			/* reset */
254 	NULL,					/* device-wide qnotify */
255 	pci_vtscsi_cfgread,			/* read virtio config */
256 	pci_vtscsi_cfgwrite,			/* write virtio config */
257 	pci_vtscsi_neg_features,		/* apply negotiated features */
258 	0,					/* our capabilities */
259 };
260 
261 static void *
262 pci_vtscsi_proc(void *arg)
263 {
264 	struct pci_vtscsi_worker *worker = (struct pci_vtscsi_worker *)arg;
265 	struct pci_vtscsi_queue *q = worker->vsw_queue;
266 	struct pci_vtscsi_request *req;
267 	int iolen;
268 
269 	for (;;) {
270 		pthread_mutex_lock(&q->vsq_mtx);
271 
272 		while (STAILQ_EMPTY(&q->vsq_requests)
273 		    && !worker->vsw_exiting)
274 			pthread_cond_wait(&q->vsq_cv, &q->vsq_mtx);
275 
276 		if (worker->vsw_exiting)
277 			break;
278 
279 		req = STAILQ_FIRST(&q->vsq_requests);
280 		STAILQ_REMOVE_HEAD(&q->vsq_requests, vsr_link);
281 
282 		pthread_mutex_unlock(&q->vsq_mtx);
283 		iolen = pci_vtscsi_request_handle(q, req->vsr_iov_in,
284 		    req->vsr_niov_in, req->vsr_iov_out, req->vsr_niov_out);
285 
286 		pthread_mutex_lock(&q->vsq_qmtx);
287 		vq_relchain(q->vsq_vq, req->vsr_idx, iolen);
288 		vq_endchains(q->vsq_vq, 0);
289 		pthread_mutex_unlock(&q->vsq_qmtx);
290 
291 		DPRINTF(("virtio-scsi: request <idx=%d> completed\n",
292 		    req->vsr_idx));
293 		free(req);
294 	}
295 
296 	pthread_mutex_unlock(&q->vsq_mtx);
297 	return (NULL);
298 }
299 
300 static void
301 pci_vtscsi_reset(void *vsc)
302 {
303 	struct pci_vtscsi_softc *sc;
304 
305 	sc = vsc;
306 
307 	DPRINTF(("vtscsi: device reset requested\n"));
308 	vi_reset_dev(&sc->vss_vs);
309 
310 	/* initialize config structure */
311 	sc->vss_config = (struct pci_vtscsi_config){
312 		.num_queues = VTSCSI_REQUESTQ,
313 		.seg_max = VTSCSI_MAXSEG,
314 		.max_sectors = 2,
315 		.cmd_per_lun = 1,
316 		.event_info_size = sizeof(struct pci_vtscsi_event),
317 		.sense_size = 96,
318 		.cdb_size = 32,
319 		.max_channel = VIRTIO_SCSI_MAX_CHANNEL,
320 		.max_target = VIRTIO_SCSI_MAX_TARGET,
321 		.max_lun = VIRTIO_SCSI_MAX_LUN
322 	};
323 }
324 
325 static void
326 pci_vtscsi_neg_features(void *vsc, uint64_t negotiated_features)
327 {
328 	struct pci_vtscsi_softc *sc = vsc;
329 
330 	sc->vss_features = negotiated_features;
331 }
332 
333 static int
334 pci_vtscsi_cfgread(void *vsc, int offset, int size, uint32_t *retval)
335 {
336 	struct pci_vtscsi_softc *sc = vsc;
337 	void *ptr;
338 
339 	ptr = (uint8_t *)&sc->vss_config + offset;
340 	memcpy(retval, ptr, size);
341 	return (0);
342 }
343 
344 static int
345 pci_vtscsi_cfgwrite(void *vsc, int offset, int size, uint32_t val)
346 {
347 
348 	return (0);
349 }
350 
351 static inline int
352 pci_vtscsi_get_lun(uint8_t *lun)
353 {
354 
355 	return (((lun[2] << 8) | lun[3]) & 0x3fff);
356 }
357 
358 static int
359 pci_vtscsi_control_handle(struct pci_vtscsi_softc *sc, void *buf,
360     size_t bufsize)
361 {
362 	struct pci_vtscsi_ctrl_tmf *tmf;
363 	struct pci_vtscsi_ctrl_an *an;
364 	uint32_t type;
365 
366 	type = *(uint32_t *)buf;
367 
368 	if (type == VIRTIO_SCSI_T_TMF) {
369 		tmf = (struct pci_vtscsi_ctrl_tmf *)buf;
370 		return (pci_vtscsi_tmf_handle(sc, tmf));
371 	}
372 
373 	if (type == VIRTIO_SCSI_T_AN_QUERY) {
374 		an = (struct pci_vtscsi_ctrl_an *)buf;
375 		return (pci_vtscsi_an_handle(sc, an));
376 	}
377 
378 	return (0);
379 }
380 
381 static int
382 pci_vtscsi_tmf_handle(struct pci_vtscsi_softc *sc,
383     struct pci_vtscsi_ctrl_tmf *tmf)
384 {
385 	union ctl_io *io;
386 	int err;
387 
388 	io = ctl_scsi_alloc_io(sc->vss_iid);
389 	ctl_scsi_zero_io(io);
390 
391 	io->io_hdr.io_type = CTL_IO_TASK;
392 	io->io_hdr.nexus.targ_port = tmf->lun[1];
393 	io->io_hdr.nexus.targ_lun = pci_vtscsi_get_lun(tmf->lun);
394 	io->taskio.tag_type = CTL_TAG_SIMPLE;
395 	io->taskio.tag_num = (uint32_t)tmf->id;
396 
397 	switch (tmf->subtype) {
398 	case VIRTIO_SCSI_T_TMF_ABORT_TASK:
399 		io->taskio.task_action = CTL_TASK_ABORT_TASK;
400 		break;
401 
402 	case VIRTIO_SCSI_T_TMF_ABORT_TASK_SET:
403 		io->taskio.task_action = CTL_TASK_ABORT_TASK_SET;
404 		break;
405 
406 	case VIRTIO_SCSI_T_TMF_CLEAR_ACA:
407 		io->taskio.task_action = CTL_TASK_CLEAR_ACA;
408 		break;
409 
410 	case VIRTIO_SCSI_T_TMF_CLEAR_TASK_SET:
411 		io->taskio.task_action = CTL_TASK_CLEAR_TASK_SET;
412 		break;
413 
414 	case VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET:
415 		io->taskio.task_action = CTL_TASK_I_T_NEXUS_RESET;
416 		break;
417 
418 	case VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET:
419 		io->taskio.task_action = CTL_TASK_LUN_RESET;
420 		break;
421 
422 	case VIRTIO_SCSI_T_TMF_QUERY_TASK:
423 		io->taskio.task_action = CTL_TASK_QUERY_TASK;
424 		break;
425 
426 	case VIRTIO_SCSI_T_TMF_QUERY_TASK_SET:
427 		io->taskio.task_action = CTL_TASK_QUERY_TASK_SET;
428 		break;
429 	}
430 
431 	if (pci_vtscsi_debug) {
432 		struct sbuf *sb = sbuf_new_auto();
433 		ctl_io_sbuf(io, sb);
434 		sbuf_finish(sb);
435 		DPRINTF(("pci_virtio_scsi: %s", sbuf_data(sb)));
436 		sbuf_delete(sb);
437 	}
438 
439 	err = ioctl(sc->vss_ctl_fd, CTL_IO, io);
440 	if (err != 0)
441 		WPRINTF(("CTL_IO: err=%d (%s)\n", errno, strerror(errno)));
442 
443 	tmf->response = io->taskio.task_status;
444 	ctl_scsi_free_io(io);
445 	return (1);
446 }
447 
448 static int
449 pci_vtscsi_an_handle(struct pci_vtscsi_softc *sc,
450     struct pci_vtscsi_ctrl_an *an)
451 {
452 
453 	return (0);
454 }
455 
456 static int
457 pci_vtscsi_request_handle(struct pci_vtscsi_queue *q, struct iovec *iov_in,
458     int niov_in, struct iovec *iov_out, int niov_out)
459 {
460 	struct pci_vtscsi_softc *sc = q->vsq_sc;
461 	struct pci_vtscsi_req_cmd_rd *cmd_rd = NULL;
462 	struct pci_vtscsi_req_cmd_wr *cmd_wr;
463 	struct iovec data_iov_in[VTSCSI_MAXSEG], data_iov_out[VTSCSI_MAXSEG];
464 	union ctl_io *io;
465 	size_t data_niov_in, data_niov_out;
466 	void *ext_data_ptr = NULL;
467 	uint32_t ext_data_len = 0, ext_sg_entries = 0;
468 	int err;
469 
470 	seek_iov(iov_in, niov_in, data_iov_in, &data_niov_in,
471 	    VTSCSI_IN_HEADER_LEN(sc));
472 	seek_iov(iov_out, niov_out, data_iov_out, &data_niov_out,
473 	    VTSCSI_OUT_HEADER_LEN(sc));
474 
475 	truncate_iov(iov_in, niov_in, VTSCSI_IN_HEADER_LEN(sc));
476 	truncate_iov(iov_out, niov_out, VTSCSI_OUT_HEADER_LEN(sc));
477 	iov_to_buf(iov_in, niov_in, (void **)&cmd_rd);
478 
479 	cmd_wr = malloc(VTSCSI_OUT_HEADER_LEN(sc));
480 	io = ctl_scsi_alloc_io(sc->vss_iid);
481 	ctl_scsi_zero_io(io);
482 
483 	io->io_hdr.nexus.targ_port = cmd_rd->lun[1];
484 	io->io_hdr.nexus.targ_lun = pci_vtscsi_get_lun(cmd_rd->lun);
485 
486 	io->io_hdr.io_type = CTL_IO_SCSI;
487 
488 	if (data_niov_in > 0) {
489 		ext_data_ptr = (void *)data_iov_in;
490 		ext_sg_entries = data_niov_in;
491 		ext_data_len = count_iov(data_iov_in, data_niov_in);
492 		io->io_hdr.flags |= CTL_FLAG_DATA_OUT;
493 	} else if (data_niov_out > 0) {
494 		ext_data_ptr = (void *)data_iov_out;
495 		ext_sg_entries = data_niov_out;
496 		ext_data_len = count_iov(data_iov_out, data_niov_out);
497 		io->io_hdr.flags |= CTL_FLAG_DATA_IN;
498 	}
499 
500 	io->scsiio.sense_len = sc->vss_config.sense_size;
501 	io->scsiio.tag_num = (uint32_t)cmd_rd->id;
502 	io->scsiio.tag_type = CTL_TAG_SIMPLE;
503 	io->scsiio.ext_sg_entries = ext_sg_entries;
504 	io->scsiio.ext_data_ptr = ext_data_ptr;
505 	io->scsiio.ext_data_len = ext_data_len;
506 	io->scsiio.ext_data_filled = 0;
507 	io->scsiio.cdb_len = sc->vss_config.cdb_size;
508 	memcpy(io->scsiio.cdb, cmd_rd->cdb, sc->vss_config.cdb_size);
509 
510 	if (pci_vtscsi_debug) {
511 		struct sbuf *sb = sbuf_new_auto();
512 		ctl_io_sbuf(io, sb);
513 		sbuf_finish(sb);
514 		DPRINTF(("pci_virtio_scsi: %s", sbuf_data(sb)));
515 		sbuf_delete(sb);
516 	}
517 
518 	err = ioctl(q->vsq_ctl_fd, CTL_IO, io);
519 	if (err != 0) {
520 		WPRINTF(("CTL_IO: err=%d (%s)\n", errno, strerror(errno)));
521 		cmd_wr->response = VIRTIO_SCSI_S_FAILURE;
522 	} else {
523 		cmd_wr->sense_len = MIN(io->scsiio.sense_len,
524 		    sc->vss_config.sense_size);
525 		cmd_wr->residual = io->scsiio.residual;
526 		cmd_wr->status = io->scsiio.scsi_status;
527 		cmd_wr->response = VIRTIO_SCSI_S_OK;
528 		memcpy(&cmd_wr->sense, &io->scsiio.sense_data,
529 		    cmd_wr->sense_len);
530 	}
531 
532 	buf_to_iov(cmd_wr, VTSCSI_OUT_HEADER_LEN(sc), iov_out, niov_out, 0);
533 	free(cmd_rd);
534 	free(cmd_wr);
535 	ctl_scsi_free_io(io);
536 	return (VTSCSI_OUT_HEADER_LEN(sc) + io->scsiio.ext_data_filled);
537 }
538 
539 static void
540 pci_vtscsi_controlq_notify(void *vsc, struct vqueue_info *vq)
541 {
542 	struct pci_vtscsi_softc *sc;
543 	struct iovec iov[VTSCSI_MAXSEG];
544 	uint16_t idx, n;
545 	void *buf = NULL;
546 	size_t bufsize;
547 	int iolen;
548 
549 	sc = vsc;
550 
551 	while (vq_has_descs(vq)) {
552 		n = vq_getchain(vq, &idx, iov, VTSCSI_MAXSEG, NULL);
553 		bufsize = iov_to_buf(iov, n, &buf);
554 		iolen = pci_vtscsi_control_handle(sc, buf, bufsize);
555 		buf_to_iov(buf + bufsize - iolen, iolen, iov, n, iolen);
556 
557 		/*
558 		 * Release this chain and handle more
559 		 */
560 		vq_relchain(vq, idx, iolen);
561 	}
562 	vq_endchains(vq, 1);	/* Generate interrupt if appropriate. */
563 }
564 
565 static void
566 pci_vtscsi_eventq_notify(void *vsc, struct vqueue_info *vq)
567 {
568 
569 	vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
570 }
571 
572 static void
573 pci_vtscsi_requestq_notify(void *vsc, struct vqueue_info *vq)
574 {
575 	struct pci_vtscsi_softc *sc;
576 	struct pci_vtscsi_queue *q;
577 	struct pci_vtscsi_request *req;
578 	struct iovec iov[VTSCSI_MAXSEG];
579 	uint16_t flags[VTSCSI_MAXSEG];
580 	uint16_t idx, n, i;
581 	int readable;
582 
583 	sc = vsc;
584 	q = &sc->vss_queues[vq->vq_num - 2];
585 
586 	while (vq_has_descs(vq)) {
587 		readable = 0;
588 		n = vq_getchain(vq, &idx, iov, VTSCSI_MAXSEG, flags);
589 
590 		/* Count readable descriptors */
591 		for (i = 0; i < n; i++) {
592 			if (flags[i] & VRING_DESC_F_WRITE)
593 				break;
594 
595 			readable++;
596 		}
597 
598 		req = calloc(1, sizeof(struct pci_vtscsi_request));
599 		req->vsr_idx = idx;
600 		req->vsr_queue = q;
601 		req->vsr_niov_in = readable;
602 		req->vsr_niov_out = n - readable;
603 		memcpy(req->vsr_iov_in, iov,
604 		    req->vsr_niov_in * sizeof(struct iovec));
605 		memcpy(req->vsr_iov_out, iov + readable,
606 		    req->vsr_niov_out * sizeof(struct iovec));
607 
608 		pthread_mutex_lock(&q->vsq_mtx);
609 		STAILQ_INSERT_TAIL(&q->vsq_requests, req, vsr_link);
610 		pthread_cond_signal(&q->vsq_cv);
611 		pthread_mutex_unlock(&q->vsq_mtx);
612 
613 		DPRINTF(("virtio-scsi: request <idx=%d> enqueued\n", idx));
614 	}
615 }
616 
617 static int
618 pci_vtscsi_init_queue(struct pci_vtscsi_softc *sc,
619     struct pci_vtscsi_queue *queue, int num)
620 {
621 	struct pci_vtscsi_worker *worker;
622 	char threadname[16];
623 	int i;
624 
625 	queue->vsq_sc = sc;
626 	queue->vsq_ctl_fd = open("/dev/cam/ctl", O_RDWR);
627 	queue->vsq_vq = &sc->vss_vq[num + 2];
628 
629 	if (queue->vsq_ctl_fd < 0) {
630 		WPRINTF(("cannot open /dev/cam/ctl: %s\n", strerror(errno)));
631 		return (-1);
632 	}
633 
634 	pthread_mutex_init(&queue->vsq_mtx, NULL);
635 	pthread_mutex_init(&queue->vsq_qmtx, NULL);
636 	pthread_cond_init(&queue->vsq_cv, NULL);
637 	STAILQ_INIT(&queue->vsq_requests);
638 	LIST_INIT(&queue->vsq_workers);
639 
640 	for (i = 0; i < VTSCSI_THR_PER_Q; i++) {
641 		worker = calloc(1, sizeof(struct pci_vtscsi_worker));
642 		worker->vsw_queue = queue;
643 
644 		pthread_create(&worker->vsw_thread, NULL, &pci_vtscsi_proc,
645 		    (void *)worker);
646 
647 		sprintf(threadname, "virtio-scsi:%d-%d", num, i);
648 		pthread_set_name_np(worker->vsw_thread, threadname);
649 		LIST_INSERT_HEAD(&queue->vsq_workers, worker, vsw_link);
650 	}
651 
652 	return (0);
653 }
654 
655 static int
656 pci_vtscsi_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts)
657 {
658 	struct pci_vtscsi_softc *sc;
659 	char *optname = NULL;
660 	char *opt;
661 	int i;
662 
663 	sc = calloc(1, sizeof(struct pci_vtscsi_softc));
664 	sc->vss_ctl_fd = open("/dev/cam/ctl", O_RDWR);
665 
666 	if (sc->vss_ctl_fd < 0) {
667 		WPRINTF(("cannot open /dev/cam/ctl: %s\n", strerror(errno)));
668 		return (1);
669 	}
670 
671 	while ((opt = strsep(&opts, ",")) != NULL) {
672 		if ((optname = strsep(&opt, "=")) != NULL) {
673 			if (strcmp(optname, "iid") == 0) {
674 				sc->vss_iid = strtoul(opt, NULL, 10);
675 			}
676 		}
677 	}
678 
679 	vi_softc_linkup(&sc->vss_vs, &vtscsi_vi_consts, sc, pi, sc->vss_vq);
680 	sc->vss_vs.vs_mtx = &sc->vss_mtx;
681 
682 	/* controlq */
683 	sc->vss_vq[0].vq_qsize = VTSCSI_RINGSZ;
684 	sc->vss_vq[0].vq_notify = pci_vtscsi_controlq_notify;
685 
686 	/* eventq */
687 	sc->vss_vq[1].vq_qsize = VTSCSI_RINGSZ;
688 	sc->vss_vq[1].vq_notify = pci_vtscsi_eventq_notify;
689 
690 	/* request queues */
691 	for (i = 2; i < VTSCSI_MAXQ; i++) {
692 		sc->vss_vq[i].vq_qsize = VTSCSI_RINGSZ;
693 		sc->vss_vq[i].vq_notify = pci_vtscsi_requestq_notify;
694 		pci_vtscsi_init_queue(sc, &sc->vss_queues[i - 2], i - 2);
695 	}
696 
697 	/* initialize config space */
698 	pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_SCSI);
699 	pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
700 	pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_STORAGE);
701 	pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_SCSI);
702 	pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
703 
704 	if (vi_intr_init(&sc->vss_vs, 1, fbsdrun_virtio_msix()))
705 		return (1);
706 	vi_set_io_bar(&sc->vss_vs, 0);
707 
708 	return (0);
709 }
710 
711 
712 struct pci_devemu pci_de_vscsi = {
713 	.pe_emu =	"virtio-scsi",
714 	.pe_init =	pci_vtscsi_init,
715 	.pe_barwrite =	vi_pci_write,
716 	.pe_barread =	vi_pci_read
717 };
718 PCI_EMUL_SET(pci_de_vscsi);
719