xref: /spdk/lib/vhost/vhost.c (revision b30d57cdad6d2bc75cc1e4e2ebbcebcb0d98dcfa)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 
36 #include "spdk/env.h"
37 #include "spdk/likely.h"
38 #include "spdk/string.h"
39 #include "spdk/util.h"
40 #include "spdk/memory.h"
41 #include "spdk/barrier.h"
42 #include "spdk/vhost.h"
43 #include "vhost_internal.h"
44 
45 bool g_packed_ring_recovery = false;
46 
47 static struct spdk_cpuset g_vhost_core_mask;
48 
49 /* Path to folder where character device will be created. Can be set by user. */
50 static char dev_dirname[PATH_MAX] = "";
51 
52 /* Thread performing all vhost management operations */
53 static struct spdk_thread *g_vhost_init_thread;
54 
55 static spdk_vhost_fini_cb g_fini_cpl_cb;
56 
57 /**
58  * DPDK calls our callbacks synchronously but the work those callbacks
59  * perform needs to be async. Luckily, all DPDK callbacks are called on
60  * a DPDK-internal pthread, so we'll just wait on a semaphore in there.
61  */
62 static sem_t g_dpdk_sem;
63 
64 /** Return code for the current DPDK callback */
65 static int g_dpdk_response;
66 
67 struct vhost_session_fn_ctx {
68 	/** Device pointer obtained before enqueuing the event */
69 	struct spdk_vhost_dev *vdev;
70 
71 	/** ID of the session to send event to. */
72 	uint32_t vsession_id;
73 
74 	/** User provided function to be executed on session's thread. */
75 	spdk_vhost_session_fn cb_fn;
76 
77 	/**
78 	 * User provided function to be called on the init thread
79 	 * after iterating through all sessions.
80 	 */
81 	spdk_vhost_dev_fn cpl_fn;
82 
83 	/** Custom user context */
84 	void *user_ctx;
85 };
86 
87 static TAILQ_HEAD(, spdk_vhost_dev) g_vhost_devices = TAILQ_HEAD_INITIALIZER(
88 			g_vhost_devices);
89 static pthread_mutex_t g_vhost_mutex = PTHREAD_MUTEX_INITIALIZER;
90 
91 void *vhost_gpa_to_vva(struct spdk_vhost_session *vsession, uint64_t addr, uint64_t len)
92 {
93 	void *vva;
94 	uint64_t newlen;
95 
96 	newlen = len;
97 	vva = (void *)rte_vhost_va_from_guest_pa(vsession->mem, addr, &newlen);
98 	if (newlen != len) {
99 		return NULL;
100 	}
101 
102 	return vva;
103 
104 }
105 
106 static void
107 vhost_log_req_desc(struct spdk_vhost_session *vsession, struct spdk_vhost_virtqueue *virtqueue,
108 		   uint16_t req_id)
109 {
110 	struct vring_desc *desc, *desc_table;
111 	uint32_t desc_table_size;
112 	int rc;
113 
114 	if (spdk_likely(!vhost_dev_has_feature(vsession, VHOST_F_LOG_ALL))) {
115 		return;
116 	}
117 
118 	rc = vhost_vq_get_desc(vsession, virtqueue, req_id, &desc, &desc_table, &desc_table_size);
119 	if (spdk_unlikely(rc != 0)) {
120 		SPDK_ERRLOG("Can't log used ring descriptors!\n");
121 		return;
122 	}
123 
124 	do {
125 		if (vhost_vring_desc_is_wr(desc)) {
126 			/* To be honest, only pages realy touched should be logged, but
127 			 * doing so would require tracking those changes in each backed.
128 			 * Also backend most likely will touch all/most of those pages so
129 			 * for lets assume we touched all pages passed to as writeable buffers. */
130 			rte_vhost_log_write(vsession->vid, desc->addr, desc->len);
131 		}
132 		vhost_vring_desc_get_next(&desc, desc_table, desc_table_size);
133 	} while (desc);
134 }
135 
136 static void
137 vhost_log_used_vring_elem(struct spdk_vhost_session *vsession,
138 			  struct spdk_vhost_virtqueue *virtqueue,
139 			  uint16_t idx)
140 {
141 	uint64_t offset, len;
142 
143 	if (spdk_likely(!vhost_dev_has_feature(vsession, VHOST_F_LOG_ALL))) {
144 		return;
145 	}
146 
147 	if (spdk_unlikely(virtqueue->packed.packed_ring)) {
148 		offset = idx * sizeof(struct vring_packed_desc);
149 		len = sizeof(struct vring_packed_desc);
150 	} else {
151 		offset = offsetof(struct vring_used, ring[idx]);
152 		len = sizeof(virtqueue->vring.used->ring[idx]);
153 	}
154 
155 	rte_vhost_log_used_vring(vsession->vid, virtqueue->vring_idx, offset, len);
156 }
157 
158 static void
159 vhost_log_used_vring_idx(struct spdk_vhost_session *vsession,
160 			 struct spdk_vhost_virtqueue *virtqueue)
161 {
162 	uint64_t offset, len;
163 	uint16_t vq_idx;
164 
165 	if (spdk_likely(!vhost_dev_has_feature(vsession, VHOST_F_LOG_ALL))) {
166 		return;
167 	}
168 
169 	offset = offsetof(struct vring_used, idx);
170 	len = sizeof(virtqueue->vring.used->idx);
171 	vq_idx = virtqueue - vsession->virtqueue;
172 
173 	rte_vhost_log_used_vring(vsession->vid, vq_idx, offset, len);
174 }
175 
176 /*
177  * Get available requests from avail ring.
178  */
179 uint16_t
180 vhost_vq_avail_ring_get(struct spdk_vhost_virtqueue *virtqueue, uint16_t *reqs,
181 			uint16_t reqs_len)
182 {
183 	struct rte_vhost_vring *vring = &virtqueue->vring;
184 	struct vring_avail *avail = vring->avail;
185 	uint16_t size_mask = vring->size - 1;
186 	uint16_t last_idx = virtqueue->last_avail_idx, avail_idx = avail->idx;
187 	uint16_t count, i;
188 	int rc;
189 	uint64_t u64_value;
190 
191 	spdk_smp_rmb();
192 
193 	if (virtqueue->vsession && spdk_unlikely(virtqueue->vsession->interrupt_mode)) {
194 		/* Read to clear vring's kickfd */
195 		rc = read(vring->kickfd, &u64_value, sizeof(u64_value));
196 		if (rc < 0) {
197 			SPDK_ERRLOG("failed to acknowledge kickfd: %s.\n", spdk_strerror(errno));
198 			return -errno;
199 		}
200 	}
201 
202 	count = avail_idx - last_idx;
203 	if (spdk_likely(count == 0)) {
204 		return 0;
205 	}
206 
207 	if (spdk_unlikely(count > vring->size)) {
208 		/* TODO: the queue is unrecoverably broken and should be marked so.
209 		 * For now we will fail silently and report there are no new avail entries.
210 		 */
211 		return 0;
212 	}
213 
214 	count = spdk_min(count, reqs_len);
215 
216 	virtqueue->last_avail_idx += count;
217 	/* Check whether there are unprocessed reqs in vq, then kick vq manually */
218 	if (virtqueue->vsession && spdk_unlikely(virtqueue->vsession->interrupt_mode)) {
219 		/* If avail_idx is larger than virtqueue's last_avail_idx, then there is unprocessed reqs.
220 		 * avail_idx should get updated here from memory, in case of race condition with guest.
221 		 */
222 		avail_idx = * (volatile uint16_t *) &avail->idx;
223 		if (avail_idx > virtqueue->last_avail_idx) {
224 			/* Write to notify vring's kickfd */
225 			rc = write(vring->kickfd, &u64_value, sizeof(u64_value));
226 			if (rc < 0) {
227 				SPDK_ERRLOG("failed to kick vring: %s.\n", spdk_strerror(errno));
228 				return -errno;
229 			}
230 		}
231 	}
232 
233 	for (i = 0; i < count; i++) {
234 		reqs[i] = vring->avail->ring[(last_idx + i) & size_mask];
235 	}
236 
237 	SPDK_DEBUGLOG(vhost_ring,
238 		      "AVAIL: last_idx=%"PRIu16" avail_idx=%"PRIu16" count=%"PRIu16"\n",
239 		      last_idx, avail_idx, count);
240 
241 	return count;
242 }
243 
244 static bool
245 vhost_vring_desc_is_indirect(struct vring_desc *cur_desc)
246 {
247 	return !!(cur_desc->flags & VRING_DESC_F_INDIRECT);
248 }
249 
250 static bool
251 vhost_vring_packed_desc_is_indirect(struct vring_packed_desc *cur_desc)
252 {
253 	return (cur_desc->flags & VRING_DESC_F_INDIRECT) != 0;
254 }
255 
256 static bool
257 vhost_inflight_packed_desc_is_indirect(spdk_vhost_inflight_desc *cur_desc)
258 {
259 	return (cur_desc->flags & VRING_DESC_F_INDIRECT) != 0;
260 }
261 
262 int
263 vhost_vq_get_desc(struct spdk_vhost_session *vsession, struct spdk_vhost_virtqueue *virtqueue,
264 		  uint16_t req_idx, struct vring_desc **desc, struct vring_desc **desc_table,
265 		  uint32_t *desc_table_size)
266 {
267 	if (spdk_unlikely(req_idx >= virtqueue->vring.size)) {
268 		return -1;
269 	}
270 
271 	*desc = &virtqueue->vring.desc[req_idx];
272 
273 	if (vhost_vring_desc_is_indirect(*desc)) {
274 		*desc_table_size = (*desc)->len / sizeof(**desc);
275 		*desc_table = vhost_gpa_to_vva(vsession, (*desc)->addr,
276 					       sizeof(**desc) * *desc_table_size);
277 		*desc = *desc_table;
278 		if (*desc == NULL) {
279 			return -1;
280 		}
281 
282 		return 0;
283 	}
284 
285 	*desc_table = virtqueue->vring.desc;
286 	*desc_table_size = virtqueue->vring.size;
287 
288 	return 0;
289 }
290 
291 static bool
292 vhost_packed_desc_indirect_to_desc_table(struct spdk_vhost_session *vsession,
293 		uint64_t addr, uint32_t len,
294 		struct vring_packed_desc **desc_table,
295 		uint32_t *desc_table_size)
296 {
297 	*desc_table_size = len / sizeof(struct vring_packed_desc);
298 
299 	*desc_table = vhost_gpa_to_vva(vsession, addr, len);
300 	if (spdk_unlikely(*desc_table == NULL)) {
301 		return false;
302 	}
303 
304 	return true;
305 }
306 
307 int
308 vhost_vq_get_desc_packed(struct spdk_vhost_session *vsession,
309 			 struct spdk_vhost_virtqueue *virtqueue,
310 			 uint16_t req_idx, struct vring_packed_desc **desc,
311 			 struct vring_packed_desc **desc_table, uint32_t *desc_table_size)
312 {
313 	*desc =  &virtqueue->vring.desc_packed[req_idx];
314 
315 	/* In packed ring when the desc is non-indirect we get next desc
316 	 * by judging (desc->flag & VRING_DESC_F_NEXT) != 0. When the desc
317 	 * is indirect we get next desc by idx and desc_table_size. It's
318 	 * different from split ring.
319 	 */
320 	if (vhost_vring_packed_desc_is_indirect(*desc)) {
321 		if (!vhost_packed_desc_indirect_to_desc_table(vsession, (*desc)->addr, (*desc)->len,
322 				desc_table, desc_table_size)) {
323 			return -1;
324 		}
325 
326 		*desc = *desc_table;
327 	} else {
328 		*desc_table = NULL;
329 		*desc_table_size  = 0;
330 	}
331 
332 	return 0;
333 }
334 
335 int
336 vhost_inflight_queue_get_desc(struct spdk_vhost_session *vsession,
337 			      spdk_vhost_inflight_desc *desc_array,
338 			      uint16_t req_idx, spdk_vhost_inflight_desc **desc,
339 			      struct vring_packed_desc  **desc_table, uint32_t *desc_table_size)
340 {
341 	*desc = &desc_array[req_idx];
342 
343 	if (vhost_inflight_packed_desc_is_indirect(*desc)) {
344 		if (!vhost_packed_desc_indirect_to_desc_table(vsession, (*desc)->addr, (*desc)->len,
345 				desc_table, desc_table_size)) {
346 			return -1;
347 		}
348 
349 		/* This desc is the inflight desc not the packed desc.
350 		 * When set the F_INDIRECT the table entry should be the packed desc
351 		 * so set the inflight desc NULL.
352 		 */
353 		*desc = NULL;
354 	} else {
355 		/* When not set the F_INDIRECT means there is no packed desc table */
356 		*desc_table = NULL;
357 		*desc_table_size = 0;
358 	}
359 
360 	return 0;
361 }
362 
363 int
364 vhost_vq_used_signal(struct spdk_vhost_session *vsession,
365 		     struct spdk_vhost_virtqueue *virtqueue)
366 {
367 	if (virtqueue->used_req_cnt == 0) {
368 		return 0;
369 	}
370 
371 	virtqueue->req_cnt += virtqueue->used_req_cnt;
372 	virtqueue->used_req_cnt = 0;
373 
374 	SPDK_DEBUGLOG(vhost_ring,
375 		      "Queue %td - USED RING: sending IRQ: last used %"PRIu16"\n",
376 		      virtqueue - vsession->virtqueue, virtqueue->last_used_idx);
377 
378 	if (rte_vhost_vring_call(vsession->vid, virtqueue->vring_idx) == 0) {
379 		/* interrupt signalled */
380 		return 1;
381 	} else {
382 		/* interrupt not signalled */
383 		return 0;
384 	}
385 }
386 
387 static void
388 session_vq_io_stats_update(struct spdk_vhost_session *vsession,
389 			   struct spdk_vhost_virtqueue *virtqueue, uint64_t now)
390 {
391 	uint32_t irq_delay_base = vsession->coalescing_delay_time_base;
392 	uint32_t io_threshold = vsession->coalescing_io_rate_threshold;
393 	int32_t irq_delay;
394 	uint32_t req_cnt;
395 
396 	req_cnt = virtqueue->req_cnt + virtqueue->used_req_cnt;
397 	if (req_cnt <= io_threshold) {
398 		return;
399 	}
400 
401 	irq_delay = (irq_delay_base * (req_cnt - io_threshold)) / io_threshold;
402 	virtqueue->irq_delay_time = (uint32_t) spdk_max(0, irq_delay);
403 
404 	virtqueue->req_cnt = 0;
405 	virtqueue->next_event_time = now;
406 }
407 
408 static void
409 check_session_vq_io_stats(struct spdk_vhost_session *vsession,
410 			  struct spdk_vhost_virtqueue *virtqueue, uint64_t now)
411 {
412 	if (now < vsession->next_stats_check_time) {
413 		return;
414 	}
415 
416 	vsession->next_stats_check_time = now + vsession->stats_check_interval;
417 	session_vq_io_stats_update(vsession, virtqueue, now);
418 }
419 
420 static inline bool
421 vhost_vq_event_is_suppressed(struct spdk_vhost_virtqueue *vq)
422 {
423 	if (spdk_unlikely(vq->packed.packed_ring)) {
424 		if (vq->vring.driver_event->flags & VRING_PACKED_EVENT_FLAG_DISABLE) {
425 			return true;
426 		}
427 	} else {
428 		if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
429 			return true;
430 		}
431 	}
432 
433 	return false;
434 }
435 
436 void
437 vhost_session_vq_used_signal(struct spdk_vhost_virtqueue *virtqueue)
438 {
439 	struct spdk_vhost_session *vsession = virtqueue->vsession;
440 	uint64_t now;
441 
442 	if (vsession->coalescing_delay_time_base == 0) {
443 		if (virtqueue->vring.desc == NULL) {
444 			return;
445 		}
446 
447 		if (vhost_vq_event_is_suppressed(virtqueue)) {
448 			return;
449 		}
450 
451 		vhost_vq_used_signal(vsession, virtqueue);
452 	} else {
453 		now = spdk_get_ticks();
454 		check_session_vq_io_stats(vsession, virtqueue, now);
455 
456 		/* No need for event right now */
457 		if (now < virtqueue->next_event_time) {
458 			return;
459 		}
460 
461 		if (vhost_vq_event_is_suppressed(virtqueue)) {
462 			return;
463 		}
464 
465 		if (!vhost_vq_used_signal(vsession, virtqueue)) {
466 			return;
467 		}
468 
469 		/* Syscall is quite long so update time */
470 		now = spdk_get_ticks();
471 		virtqueue->next_event_time = now + virtqueue->irq_delay_time;
472 	}
473 }
474 
475 void
476 vhost_session_used_signal(struct spdk_vhost_session *vsession)
477 {
478 	struct spdk_vhost_virtqueue *virtqueue;
479 	uint16_t q_idx;
480 
481 	for (q_idx = 0; q_idx < vsession->max_queues; q_idx++) {
482 		virtqueue = &vsession->virtqueue[q_idx];
483 		vhost_session_vq_used_signal(virtqueue);
484 	}
485 }
486 
487 static int
488 vhost_session_set_coalescing(struct spdk_vhost_dev *vdev,
489 			     struct spdk_vhost_session *vsession, void *ctx)
490 {
491 	vsession->coalescing_delay_time_base =
492 		vdev->coalescing_delay_us * spdk_get_ticks_hz() / 1000000ULL;
493 	vsession->coalescing_io_rate_threshold =
494 		vdev->coalescing_iops_threshold * SPDK_VHOST_STATS_CHECK_INTERVAL_MS / 1000U;
495 	return 0;
496 }
497 
498 static int
499 vhost_dev_set_coalescing(struct spdk_vhost_dev *vdev, uint32_t delay_base_us,
500 			 uint32_t iops_threshold)
501 {
502 	uint64_t delay_time_base = delay_base_us * spdk_get_ticks_hz() / 1000000ULL;
503 	uint32_t io_rate = iops_threshold * SPDK_VHOST_STATS_CHECK_INTERVAL_MS / 1000U;
504 
505 	if (delay_time_base >= UINT32_MAX) {
506 		SPDK_ERRLOG("Delay time of %"PRIu32" is to big\n", delay_base_us);
507 		return -EINVAL;
508 	} else if (io_rate == 0) {
509 		SPDK_ERRLOG("IOPS rate of %"PRIu32" is too low. Min is %u\n", io_rate,
510 			    1000U / SPDK_VHOST_STATS_CHECK_INTERVAL_MS);
511 		return -EINVAL;
512 	}
513 
514 	vdev->coalescing_delay_us = delay_base_us;
515 	vdev->coalescing_iops_threshold = iops_threshold;
516 	return 0;
517 }
518 
519 int
520 spdk_vhost_set_coalescing(struct spdk_vhost_dev *vdev, uint32_t delay_base_us,
521 			  uint32_t iops_threshold)
522 {
523 	int rc;
524 
525 	rc = vhost_dev_set_coalescing(vdev, delay_base_us, iops_threshold);
526 	if (rc != 0) {
527 		return rc;
528 	}
529 
530 	vhost_dev_foreach_session(vdev, vhost_session_set_coalescing, NULL, NULL);
531 	return 0;
532 }
533 
534 void
535 spdk_vhost_get_coalescing(struct spdk_vhost_dev *vdev, uint32_t *delay_base_us,
536 			  uint32_t *iops_threshold)
537 {
538 	if (delay_base_us) {
539 		*delay_base_us = vdev->coalescing_delay_us;
540 	}
541 
542 	if (iops_threshold) {
543 		*iops_threshold = vdev->coalescing_iops_threshold;
544 	}
545 }
546 
547 /*
548  * Enqueue id and len to used ring.
549  */
550 void
551 vhost_vq_used_ring_enqueue(struct spdk_vhost_session *vsession,
552 			   struct spdk_vhost_virtqueue *virtqueue,
553 			   uint16_t id, uint32_t len)
554 {
555 	struct rte_vhost_vring *vring = &virtqueue->vring;
556 	struct vring_used *used = vring->used;
557 	uint16_t last_idx = virtqueue->last_used_idx & (vring->size - 1);
558 	uint16_t vq_idx = virtqueue->vring_idx;
559 
560 	SPDK_DEBUGLOG(vhost_ring,
561 		      "Queue %td - USED RING: last_idx=%"PRIu16" req id=%"PRIu16" len=%"PRIu32"\n",
562 		      virtqueue - vsession->virtqueue, virtqueue->last_used_idx, id, len);
563 
564 	vhost_log_req_desc(vsession, virtqueue, id);
565 
566 	virtqueue->last_used_idx++;
567 	used->ring[last_idx].id = id;
568 	used->ring[last_idx].len = len;
569 
570 	/* Ensure the used ring is updated before we log it or increment used->idx. */
571 	spdk_smp_wmb();
572 
573 	rte_vhost_set_last_inflight_io_split(vsession->vid, vq_idx, id);
574 
575 	vhost_log_used_vring_elem(vsession, virtqueue, last_idx);
576 	* (volatile uint16_t *) &used->idx = virtqueue->last_used_idx;
577 	vhost_log_used_vring_idx(vsession, virtqueue);
578 
579 	rte_vhost_clr_inflight_desc_split(vsession->vid, vq_idx, virtqueue->last_used_idx, id);
580 
581 	virtqueue->used_req_cnt++;
582 
583 	if (vsession->interrupt_mode) {
584 		if (virtqueue->vring.desc == NULL || vhost_vq_event_is_suppressed(virtqueue)) {
585 			return;
586 		}
587 
588 		vhost_vq_used_signal(vsession, virtqueue);
589 	}
590 }
591 
592 void
593 vhost_vq_packed_ring_enqueue(struct spdk_vhost_session *vsession,
594 			     struct spdk_vhost_virtqueue *virtqueue,
595 			     uint16_t num_descs, uint16_t buffer_id,
596 			     uint32_t length, uint16_t inflight_head)
597 {
598 	struct vring_packed_desc *desc = &virtqueue->vring.desc_packed[virtqueue->last_used_idx];
599 	bool used, avail;
600 
601 	SPDK_DEBUGLOG(vhost_ring,
602 		      "Queue %td - RING: buffer_id=%"PRIu16"\n",
603 		      virtqueue - vsession->virtqueue, buffer_id);
604 
605 	/* When the descriptor is used, two flags in descriptor
606 	 * avail flag and used flag are set to equal
607 	 * and used flag value == used_wrap_counter.
608 	 */
609 	used = !!(desc->flags & VRING_DESC_F_USED);
610 	avail = !!(desc->flags & VRING_DESC_F_AVAIL);
611 	if (spdk_unlikely(used == virtqueue->packed.used_phase && used == avail)) {
612 		SPDK_ERRLOG("descriptor has been used before\n");
613 		return;
614 	}
615 
616 	/* In used desc addr is unused and len specifies the buffer length
617 	 * that has been written to by the device.
618 	 */
619 	desc->addr = 0;
620 	desc->len = length;
621 
622 	/* This bit specifies whether any data has been written by the device */
623 	if (length != 0) {
624 		desc->flags |= VRING_DESC_F_WRITE;
625 	}
626 
627 	/* Buffer ID is included in the last descriptor in the list.
628 	 * The driver needs to keep track of the size of the list corresponding
629 	 * to each buffer ID.
630 	 */
631 	desc->id = buffer_id;
632 
633 	/* A device MUST NOT make the descriptor used before buffer_id is
634 	 * written to the descriptor.
635 	 */
636 	spdk_smp_wmb();
637 
638 	rte_vhost_set_last_inflight_io_packed(vsession->vid, virtqueue->vring_idx, inflight_head);
639 	/* To mark a desc as used, the device sets the F_USED bit in flags to match
640 	 * the internal Device ring wrap counter. It also sets the F_AVAIL bit to
641 	 * match the same value.
642 	 */
643 	if (virtqueue->packed.used_phase) {
644 		desc->flags |= VRING_DESC_F_AVAIL_USED;
645 	} else {
646 		desc->flags &= ~VRING_DESC_F_AVAIL_USED;
647 	}
648 	rte_vhost_clr_inflight_desc_packed(vsession->vid, virtqueue->vring_idx, inflight_head);
649 
650 	vhost_log_used_vring_elem(vsession, virtqueue, virtqueue->last_used_idx);
651 	virtqueue->last_used_idx += num_descs;
652 	if (virtqueue->last_used_idx >= virtqueue->vring.size) {
653 		virtqueue->last_used_idx -= virtqueue->vring.size;
654 		virtqueue->packed.used_phase = !virtqueue->packed.used_phase;
655 	}
656 
657 	virtqueue->used_req_cnt++;
658 }
659 
660 bool
661 vhost_vq_packed_ring_is_avail(struct spdk_vhost_virtqueue *virtqueue)
662 {
663 	uint16_t flags = virtqueue->vring.desc_packed[virtqueue->last_avail_idx].flags;
664 
665 	/* To mark a desc as available, the driver sets the F_AVAIL bit in flags
666 	 * to match the internal avail wrap counter. It also sets the F_USED bit to
667 	 * match the inverse value but it's not mandatory.
668 	 */
669 	return (!!(flags & VRING_DESC_F_AVAIL) == virtqueue->packed.avail_phase);
670 }
671 
672 bool
673 vhost_vring_packed_desc_is_wr(struct vring_packed_desc *cur_desc)
674 {
675 	return (cur_desc->flags & VRING_DESC_F_WRITE) != 0;
676 }
677 
678 bool
679 vhost_vring_inflight_desc_is_wr(spdk_vhost_inflight_desc *cur_desc)
680 {
681 	return (cur_desc->flags & VRING_DESC_F_WRITE) != 0;
682 }
683 
684 int
685 vhost_vring_packed_desc_get_next(struct vring_packed_desc **desc, uint16_t *req_idx,
686 				 struct spdk_vhost_virtqueue *vq,
687 				 struct vring_packed_desc *desc_table,
688 				 uint32_t desc_table_size)
689 {
690 	if (desc_table != NULL) {
691 		/* When the desc_table isn't NULL means it's indirect and we get the next
692 		 * desc by req_idx and desc_table_size. The return value is NULL means
693 		 * we reach the last desc of this request.
694 		 */
695 		(*req_idx)++;
696 		if (*req_idx < desc_table_size) {
697 			*desc = &desc_table[*req_idx];
698 		} else {
699 			*desc = NULL;
700 		}
701 	} else {
702 		/* When the desc_table is NULL means it's non-indirect and we get the next
703 		 * desc by req_idx and F_NEXT in flags. The return value is NULL means
704 		 * we reach the last desc of this request. When return new desc
705 		 * we update the req_idx too.
706 		 */
707 		if (((*desc)->flags & VRING_DESC_F_NEXT) == 0) {
708 			*desc = NULL;
709 			return 0;
710 		}
711 
712 		*req_idx = (*req_idx + 1) % vq->vring.size;
713 		*desc = &vq->vring.desc_packed[*req_idx];
714 	}
715 
716 	return 0;
717 }
718 
719 static int
720 vhost_vring_desc_payload_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
721 				uint16_t *iov_index, uintptr_t payload, uint64_t remaining)
722 {
723 	uintptr_t vva;
724 	uint64_t len;
725 
726 	do {
727 		if (*iov_index >= SPDK_VHOST_IOVS_MAX) {
728 			SPDK_ERRLOG("SPDK_VHOST_IOVS_MAX(%d) reached\n", SPDK_VHOST_IOVS_MAX);
729 			return -1;
730 		}
731 		len = remaining;
732 		vva = (uintptr_t)rte_vhost_va_from_guest_pa(vsession->mem, payload, &len);
733 		if (vva == 0 || len == 0) {
734 			SPDK_ERRLOG("gpa_to_vva(%p) == NULL\n", (void *)payload);
735 			return -1;
736 		}
737 		iov[*iov_index].iov_base = (void *)vva;
738 		iov[*iov_index].iov_len = len;
739 		remaining -= len;
740 		payload += len;
741 		(*iov_index)++;
742 	} while (remaining);
743 
744 	return 0;
745 }
746 
747 int
748 vhost_vring_packed_desc_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
749 			       uint16_t *iov_index, const struct vring_packed_desc *desc)
750 {
751 	return vhost_vring_desc_payload_to_iov(vsession, iov, iov_index,
752 					       desc->addr, desc->len);
753 }
754 
755 int
756 vhost_vring_inflight_desc_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
757 				 uint16_t *iov_index, const spdk_vhost_inflight_desc *desc)
758 {
759 	return vhost_vring_desc_payload_to_iov(vsession, iov, iov_index,
760 					       desc->addr, desc->len);
761 }
762 
763 /* 1, Traverse the desc chain to get the buffer_id and return buffer_id as task_idx.
764  * 2, Update the vq->last_avail_idx to point next available desc chain.
765  * 3, Update the avail_wrap_counter if last_avail_idx overturn.
766  */
767 uint16_t
768 vhost_vring_packed_desc_get_buffer_id(struct spdk_vhost_virtqueue *vq, uint16_t req_idx,
769 				      uint16_t *num_descs)
770 {
771 	struct vring_packed_desc *desc;
772 	uint16_t desc_head = req_idx;
773 
774 	*num_descs = 1;
775 
776 	desc =  &vq->vring.desc_packed[req_idx];
777 	if (!vhost_vring_packed_desc_is_indirect(desc)) {
778 		while ((desc->flags & VRING_DESC_F_NEXT) != 0) {
779 			req_idx = (req_idx + 1) % vq->vring.size;
780 			desc = &vq->vring.desc_packed[req_idx];
781 			(*num_descs)++;
782 		}
783 	}
784 
785 	/* Queue Size doesn't have to be a power of 2
786 	 * Device maintains last_avail_idx so we can make sure
787 	 * the value is valid(0 ~ vring.size - 1)
788 	 */
789 	vq->last_avail_idx = (req_idx + 1) % vq->vring.size;
790 	if (vq->last_avail_idx < desc_head) {
791 		vq->packed.avail_phase = !vq->packed.avail_phase;
792 	}
793 
794 	return desc->id;
795 }
796 
797 int
798 vhost_vring_desc_get_next(struct vring_desc **desc,
799 			  struct vring_desc *desc_table, uint32_t desc_table_size)
800 {
801 	struct vring_desc *old_desc = *desc;
802 	uint16_t next_idx;
803 
804 	if ((old_desc->flags & VRING_DESC_F_NEXT) == 0) {
805 		*desc = NULL;
806 		return 0;
807 	}
808 
809 	next_idx = old_desc->next;
810 	if (spdk_unlikely(next_idx >= desc_table_size)) {
811 		*desc = NULL;
812 		return -1;
813 	}
814 
815 	*desc = &desc_table[next_idx];
816 	return 0;
817 }
818 
819 int
820 vhost_vring_desc_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
821 			uint16_t *iov_index, const struct vring_desc *desc)
822 {
823 	return vhost_vring_desc_payload_to_iov(vsession, iov, iov_index,
824 					       desc->addr, desc->len);
825 }
826 
827 static struct spdk_vhost_session *
828 vhost_session_find_by_id(struct spdk_vhost_dev *vdev, unsigned id)
829 {
830 	struct spdk_vhost_session *vsession;
831 
832 	TAILQ_FOREACH(vsession, &vdev->vsessions, tailq) {
833 		if (vsession->id == id) {
834 			return vsession;
835 		}
836 	}
837 
838 	return NULL;
839 }
840 
841 struct spdk_vhost_session *
842 vhost_session_find_by_vid(int vid)
843 {
844 	struct spdk_vhost_dev *vdev;
845 	struct spdk_vhost_session *vsession;
846 
847 	TAILQ_FOREACH(vdev, &g_vhost_devices, tailq) {
848 		TAILQ_FOREACH(vsession, &vdev->vsessions, tailq) {
849 			if (vsession->vid == vid) {
850 				return vsession;
851 			}
852 		}
853 	}
854 
855 	return NULL;
856 }
857 
858 struct spdk_vhost_dev *
859 spdk_vhost_dev_next(struct spdk_vhost_dev *vdev)
860 {
861 	if (vdev == NULL) {
862 		return TAILQ_FIRST(&g_vhost_devices);
863 	}
864 
865 	return TAILQ_NEXT(vdev, tailq);
866 }
867 
868 struct spdk_vhost_dev *
869 spdk_vhost_dev_find(const char *ctrlr_name)
870 {
871 	struct spdk_vhost_dev *vdev;
872 	size_t dev_dirname_len = strlen(dev_dirname);
873 
874 	if (strncmp(ctrlr_name, dev_dirname, dev_dirname_len) == 0) {
875 		ctrlr_name += dev_dirname_len;
876 	}
877 
878 	TAILQ_FOREACH(vdev, &g_vhost_devices, tailq) {
879 		if (strcmp(vdev->name, ctrlr_name) == 0) {
880 			return vdev;
881 		}
882 	}
883 
884 	return NULL;
885 }
886 
887 static int
888 vhost_parse_core_mask(const char *mask, struct spdk_cpuset *cpumask)
889 {
890 	int rc;
891 
892 	if (cpumask == NULL) {
893 		return -1;
894 	}
895 
896 	if (mask == NULL) {
897 		spdk_cpuset_copy(cpumask, &g_vhost_core_mask);
898 		return 0;
899 	}
900 
901 	rc = spdk_cpuset_parse(cpumask, mask);
902 	if (rc < 0) {
903 		SPDK_ERRLOG("invalid cpumask %s\n", mask);
904 		return -1;
905 	}
906 
907 	spdk_cpuset_and(cpumask, &g_vhost_core_mask);
908 
909 	if (spdk_cpuset_count(cpumask) == 0) {
910 		SPDK_ERRLOG("no cpu is selected among core mask(=%s)\n",
911 			    spdk_cpuset_fmt(&g_vhost_core_mask));
912 		return -1;
913 	}
914 
915 	return 0;
916 }
917 
918 static void
919 vhost_setup_core_mask(void *ctx)
920 {
921 	struct spdk_thread *thread = spdk_get_thread();
922 	spdk_cpuset_or(&g_vhost_core_mask, spdk_thread_get_cpumask(thread));
923 }
924 
925 static void
926 vhost_setup_core_mask_done(void *ctx)
927 {
928 	spdk_vhost_init_cb init_cb = ctx;
929 
930 	if (spdk_cpuset_count(&g_vhost_core_mask) == 0) {
931 		init_cb(-ECHILD);
932 		return;
933 	}
934 
935 	init_cb(0);
936 }
937 
938 static void
939 vhost_dev_thread_exit(void *arg1)
940 {
941 	spdk_thread_exit(spdk_get_thread());
942 }
943 
944 int
945 vhost_dev_register(struct spdk_vhost_dev *vdev, const char *name, const char *mask_str,
946 		   const struct spdk_vhost_dev_backend *backend)
947 {
948 	char path[PATH_MAX];
949 	struct spdk_cpuset cpumask = {};
950 	int rc;
951 
952 	assert(vdev);
953 	if (name == NULL) {
954 		SPDK_ERRLOG("Can't register controller with no name\n");
955 		return -EINVAL;
956 	}
957 
958 	if (vhost_parse_core_mask(mask_str, &cpumask) != 0) {
959 		SPDK_ERRLOG("cpumask %s is invalid (core mask is 0x%s)\n",
960 			    mask_str, spdk_cpuset_fmt(&g_vhost_core_mask));
961 		return -EINVAL;
962 	}
963 
964 	if (spdk_vhost_dev_find(name)) {
965 		SPDK_ERRLOG("vhost controller %s already exists.\n", name);
966 		return -EEXIST;
967 	}
968 
969 	if (snprintf(path, sizeof(path), "%s%s", dev_dirname, name) >= (int)sizeof(path)) {
970 		SPDK_ERRLOG("Resulting socket path for controller %s is too long: %s%s\n", name, dev_dirname,
971 			    name);
972 		return -EINVAL;
973 	}
974 
975 	vdev->name = strdup(name);
976 	vdev->path = strdup(path);
977 	if (vdev->name == NULL || vdev->path == NULL) {
978 		rc = -EIO;
979 		goto out;
980 	}
981 
982 	vdev->thread = spdk_thread_create(vdev->name, &cpumask);
983 	if (vdev->thread == NULL) {
984 		SPDK_ERRLOG("Failed to create thread for vhost controller %s.\n", name);
985 		rc = -EIO;
986 		goto out;
987 	}
988 
989 	vdev->registered = true;
990 	vdev->backend = backend;
991 	TAILQ_INIT(&vdev->vsessions);
992 
993 	vhost_dev_set_coalescing(vdev, SPDK_VHOST_COALESCING_DELAY_BASE_US,
994 				 SPDK_VHOST_VQ_IOPS_COALESCING_THRESHOLD);
995 
996 	if (vhost_register_unix_socket(path, name, vdev->virtio_features, vdev->disabled_features,
997 				       vdev->protocol_features)) {
998 		spdk_thread_send_msg(vdev->thread, vhost_dev_thread_exit, NULL);
999 		rc = -EIO;
1000 		goto out;
1001 	}
1002 
1003 	TAILQ_INSERT_TAIL(&g_vhost_devices, vdev, tailq);
1004 
1005 	SPDK_INFOLOG(vhost, "Controller %s: new controller added\n", vdev->name);
1006 	return 0;
1007 
1008 out:
1009 	free(vdev->name);
1010 	free(vdev->path);
1011 	return rc;
1012 }
1013 
1014 int
1015 vhost_dev_unregister(struct spdk_vhost_dev *vdev)
1016 {
1017 	if (!TAILQ_EMPTY(&vdev->vsessions)) {
1018 		SPDK_ERRLOG("Controller %s has still valid connection.\n", vdev->name);
1019 		return -EBUSY;
1020 	}
1021 
1022 	if (vdev->registered && vhost_driver_unregister(vdev->path) != 0) {
1023 		SPDK_ERRLOG("Could not unregister controller %s with vhost library\n"
1024 			    "Check if domain socket %s still exists\n",
1025 			    vdev->name, vdev->path);
1026 		return -EIO;
1027 	}
1028 
1029 	SPDK_INFOLOG(vhost, "Controller %s: removed\n", vdev->name);
1030 
1031 	spdk_thread_send_msg(vdev->thread, vhost_dev_thread_exit, NULL);
1032 
1033 	free(vdev->name);
1034 	free(vdev->path);
1035 	TAILQ_REMOVE(&g_vhost_devices, vdev, tailq);
1036 	return 0;
1037 }
1038 
1039 const char *
1040 spdk_vhost_dev_get_name(struct spdk_vhost_dev *vdev)
1041 {
1042 	assert(vdev != NULL);
1043 	return vdev->name;
1044 }
1045 
1046 const struct spdk_cpuset *
1047 spdk_vhost_dev_get_cpumask(struct spdk_vhost_dev *vdev)
1048 {
1049 	assert(vdev != NULL);
1050 	return spdk_thread_get_cpumask(vdev->thread);
1051 }
1052 
1053 static void
1054 wait_for_semaphore(int timeout_sec, const char *errmsg)
1055 {
1056 	struct timespec timeout;
1057 	int rc;
1058 
1059 	clock_gettime(CLOCK_REALTIME, &timeout);
1060 	timeout.tv_sec += timeout_sec;
1061 	rc = sem_timedwait(&g_dpdk_sem, &timeout);
1062 	if (rc != 0) {
1063 		SPDK_ERRLOG("Timeout waiting for event: %s.\n", errmsg);
1064 		sem_wait(&g_dpdk_sem);
1065 	}
1066 }
1067 
1068 static void
1069 vhost_session_cb_done(int rc)
1070 {
1071 	g_dpdk_response = rc;
1072 	sem_post(&g_dpdk_sem);
1073 }
1074 
1075 void
1076 vhost_session_start_done(struct spdk_vhost_session *vsession, int response)
1077 {
1078 	if (response == 0) {
1079 		vsession->started = true;
1080 
1081 		assert(vsession->vdev->active_session_num < UINT32_MAX);
1082 		vsession->vdev->active_session_num++;
1083 	}
1084 
1085 	vhost_session_cb_done(response);
1086 }
1087 
1088 void
1089 vhost_session_stop_done(struct spdk_vhost_session *vsession, int response)
1090 {
1091 	if (response == 0) {
1092 		vsession->started = false;
1093 
1094 		assert(vsession->vdev->active_session_num > 0);
1095 		vsession->vdev->active_session_num--;
1096 	}
1097 
1098 	vhost_session_cb_done(response);
1099 }
1100 
1101 static void
1102 vhost_event_cb(void *arg1)
1103 {
1104 	struct vhost_session_fn_ctx *ctx = arg1;
1105 	struct spdk_vhost_session *vsession;
1106 
1107 	if (pthread_mutex_trylock(&g_vhost_mutex) != 0) {
1108 		spdk_thread_send_msg(spdk_get_thread(), vhost_event_cb, arg1);
1109 		return;
1110 	}
1111 
1112 	vsession = vhost_session_find_by_id(ctx->vdev, ctx->vsession_id);
1113 	ctx->cb_fn(ctx->vdev, vsession, NULL);
1114 	pthread_mutex_unlock(&g_vhost_mutex);
1115 }
1116 
1117 int
1118 vhost_session_send_event(struct spdk_vhost_session *vsession,
1119 			 spdk_vhost_session_fn cb_fn, unsigned timeout_sec,
1120 			 const char *errmsg)
1121 {
1122 	struct vhost_session_fn_ctx ev_ctx = {0};
1123 	struct spdk_vhost_dev *vdev = vsession->vdev;
1124 
1125 	ev_ctx.vdev = vdev;
1126 	ev_ctx.vsession_id = vsession->id;
1127 	ev_ctx.cb_fn = cb_fn;
1128 
1129 	spdk_thread_send_msg(vdev->thread, vhost_event_cb, &ev_ctx);
1130 
1131 	pthread_mutex_unlock(&g_vhost_mutex);
1132 	wait_for_semaphore(timeout_sec, errmsg);
1133 	pthread_mutex_lock(&g_vhost_mutex);
1134 
1135 	return g_dpdk_response;
1136 }
1137 
1138 static void
1139 foreach_session_finish_cb(void *arg1)
1140 {
1141 	struct vhost_session_fn_ctx *ev_ctx = arg1;
1142 	struct spdk_vhost_dev *vdev = ev_ctx->vdev;
1143 
1144 	if (pthread_mutex_trylock(&g_vhost_mutex) != 0) {
1145 		spdk_thread_send_msg(spdk_get_thread(),
1146 				     foreach_session_finish_cb, arg1);
1147 		return;
1148 	}
1149 
1150 	assert(vdev->pending_async_op_num > 0);
1151 	vdev->pending_async_op_num--;
1152 	if (ev_ctx->cpl_fn != NULL) {
1153 		ev_ctx->cpl_fn(vdev, ev_ctx->user_ctx);
1154 	}
1155 
1156 	pthread_mutex_unlock(&g_vhost_mutex);
1157 	free(ev_ctx);
1158 }
1159 
1160 static void
1161 foreach_session(void *arg1)
1162 {
1163 	struct vhost_session_fn_ctx *ev_ctx = arg1;
1164 	struct spdk_vhost_session *vsession;
1165 	struct spdk_vhost_dev *vdev = ev_ctx->vdev;
1166 	int rc;
1167 
1168 	if (pthread_mutex_trylock(&g_vhost_mutex) != 0) {
1169 		spdk_thread_send_msg(spdk_get_thread(), foreach_session, arg1);
1170 		return;
1171 	}
1172 
1173 	TAILQ_FOREACH(vsession, &vdev->vsessions, tailq) {
1174 		if (vsession->initialized) {
1175 			rc = ev_ctx->cb_fn(vdev, vsession, ev_ctx->user_ctx);
1176 			if (rc < 0) {
1177 				goto out;
1178 			}
1179 		}
1180 	}
1181 
1182 out:
1183 	pthread_mutex_unlock(&g_vhost_mutex);
1184 
1185 	spdk_thread_send_msg(g_vhost_init_thread, foreach_session_finish_cb, arg1);
1186 }
1187 
1188 void
1189 vhost_dev_foreach_session(struct spdk_vhost_dev *vdev,
1190 			  spdk_vhost_session_fn fn,
1191 			  spdk_vhost_dev_fn cpl_fn,
1192 			  void *arg)
1193 {
1194 	struct vhost_session_fn_ctx *ev_ctx;
1195 
1196 	ev_ctx = calloc(1, sizeof(*ev_ctx));
1197 	if (ev_ctx == NULL) {
1198 		SPDK_ERRLOG("Failed to alloc vhost event.\n");
1199 		assert(false);
1200 		return;
1201 	}
1202 
1203 	ev_ctx->vdev = vdev;
1204 	ev_ctx->cb_fn = fn;
1205 	ev_ctx->cpl_fn = cpl_fn;
1206 	ev_ctx->user_ctx = arg;
1207 
1208 	assert(vdev->pending_async_op_num < UINT32_MAX);
1209 	vdev->pending_async_op_num++;
1210 
1211 	spdk_thread_send_msg(vdev->thread, foreach_session, ev_ctx);
1212 }
1213 
1214 static int
1215 _stop_session(struct spdk_vhost_session *vsession)
1216 {
1217 	struct spdk_vhost_dev *vdev = vsession->vdev;
1218 	struct spdk_vhost_virtqueue *q;
1219 	int rc;
1220 	uint16_t i;
1221 
1222 	rc = vdev->backend->stop_session(vsession);
1223 	if (rc != 0) {
1224 		SPDK_ERRLOG("Couldn't stop device with vid %d.\n", vsession->vid);
1225 		pthread_mutex_unlock(&g_vhost_mutex);
1226 		return rc;
1227 	}
1228 
1229 	for (i = 0; i < vsession->max_queues; i++) {
1230 		q = &vsession->virtqueue[i];
1231 
1232 		/* vring.desc and vring.desc_packed are in a union struct
1233 		 * so q->vring.desc can replace q->vring.desc_packed.
1234 		 */
1235 		if (q->vring.desc == NULL) {
1236 			continue;
1237 		}
1238 
1239 		/* Packed virtqueues support up to 2^15 entries each
1240 		 * so left one bit can be used as wrap counter.
1241 		 */
1242 		if (q->packed.packed_ring) {
1243 			q->last_avail_idx = q->last_avail_idx |
1244 					    ((uint16_t)q->packed.avail_phase << 15);
1245 			q->last_used_idx = q->last_used_idx |
1246 					   ((uint16_t)q->packed.used_phase << 15);
1247 		}
1248 
1249 		rte_vhost_set_vring_base(vsession->vid, i, q->last_avail_idx, q->last_used_idx);
1250 	}
1251 
1252 	vhost_session_mem_unregister(vsession->mem);
1253 	free(vsession->mem);
1254 
1255 	return 0;
1256 }
1257 
1258 int
1259 vhost_stop_device_cb(int vid)
1260 {
1261 	struct spdk_vhost_session *vsession;
1262 	int rc;
1263 
1264 	pthread_mutex_lock(&g_vhost_mutex);
1265 	vsession = vhost_session_find_by_vid(vid);
1266 	if (vsession == NULL) {
1267 		SPDK_ERRLOG("Couldn't find session with vid %d.\n", vid);
1268 		pthread_mutex_unlock(&g_vhost_mutex);
1269 		return -EINVAL;
1270 	}
1271 
1272 	if (!vsession->started) {
1273 		/* already stopped, nothing to do */
1274 		pthread_mutex_unlock(&g_vhost_mutex);
1275 		return -EALREADY;
1276 	}
1277 
1278 	rc = _stop_session(vsession);
1279 	pthread_mutex_unlock(&g_vhost_mutex);
1280 
1281 	return rc;
1282 }
1283 
1284 int
1285 vhost_start_device_cb(int vid)
1286 {
1287 	struct spdk_vhost_dev *vdev;
1288 	struct spdk_vhost_session *vsession;
1289 	int rc = -1;
1290 	uint16_t i;
1291 	bool packed_ring;
1292 
1293 	pthread_mutex_lock(&g_vhost_mutex);
1294 
1295 	vsession = vhost_session_find_by_vid(vid);
1296 	if (vsession == NULL) {
1297 		SPDK_ERRLOG("Couldn't find session with vid %d.\n", vid);
1298 		goto out;
1299 	}
1300 
1301 	if (spdk_interrupt_mode_is_enabled()) {
1302 		vsession->interrupt_mode = true;
1303 	}
1304 
1305 	vdev = vsession->vdev;
1306 	if (vsession->started) {
1307 		/* already started, nothing to do */
1308 		rc = 0;
1309 		goto out;
1310 	}
1311 
1312 	if (vhost_get_negotiated_features(vid, &vsession->negotiated_features) != 0) {
1313 		SPDK_ERRLOG("vhost device %d: Failed to get negotiated driver features\n", vid);
1314 		goto out;
1315 	}
1316 
1317 	packed_ring = ((vsession->negotiated_features & (1ULL << VIRTIO_F_RING_PACKED)) != 0);
1318 
1319 	vsession->max_queues = 0;
1320 	memset(vsession->virtqueue, 0, sizeof(vsession->virtqueue));
1321 	for (i = 0; i < SPDK_VHOST_MAX_VQUEUES; i++) {
1322 		struct spdk_vhost_virtqueue *q = &vsession->virtqueue[i];
1323 
1324 		q->vsession = vsession;
1325 		q->vring_idx = -1;
1326 		if (rte_vhost_get_vhost_vring(vid, i, &q->vring)) {
1327 			continue;
1328 		}
1329 		q->vring_idx = i;
1330 		rte_vhost_get_vhost_ring_inflight(vid, i, &q->vring_inflight);
1331 
1332 		/* vring.desc and vring.desc_packed are in a union struct
1333 		 * so q->vring.desc can replace q->vring.desc_packed.
1334 		 */
1335 		if (q->vring.desc == NULL || q->vring.size == 0) {
1336 			continue;
1337 		}
1338 
1339 		if (rte_vhost_get_vring_base(vsession->vid, i, &q->last_avail_idx, &q->last_used_idx)) {
1340 			q->vring.desc = NULL;
1341 			continue;
1342 		}
1343 
1344 		if (packed_ring) {
1345 			/* Use the inflight mem to restore the last_avail_idx and last_used_idx.
1346 			 * When the vring format is packed, there is no used_idx in the
1347 			 * used ring, so VM can't resend the used_idx to VHOST when reconnect.
1348 			 * QEMU version 5.2.0 supports the packed inflight before that it only
1349 			 * supports split ring inflight because it doesn't send negotiated features
1350 			 * before get inflight fd. Users can use RPC to enable this function.
1351 			 */
1352 			if (spdk_unlikely(g_packed_ring_recovery)) {
1353 				rte_vhost_get_vring_base_from_inflight(vsession->vid, i,
1354 								       &q->last_avail_idx,
1355 								       &q->last_used_idx);
1356 			}
1357 
1358 			/* Packed virtqueues support up to 2^15 entries each
1359 			 * so left one bit can be used as wrap counter.
1360 			 */
1361 			q->packed.avail_phase = q->last_avail_idx >> 15;
1362 			q->last_avail_idx = q->last_avail_idx & 0x7FFF;
1363 			q->packed.used_phase = q->last_used_idx >> 15;
1364 			q->last_used_idx = q->last_used_idx & 0x7FFF;
1365 
1366 			if (!vsession->interrupt_mode) {
1367 				/* Disable I/O submission notifications, we'll be polling. */
1368 				q->vring.device_event->flags = VRING_PACKED_EVENT_FLAG_DISABLE;
1369 			}
1370 		} else {
1371 			if (!vsession->interrupt_mode) {
1372 				/* Disable I/O submission notifications, we'll be polling. */
1373 				q->vring.used->flags = VRING_USED_F_NO_NOTIFY;
1374 			}
1375 		}
1376 
1377 		q->packed.packed_ring = packed_ring;
1378 		vsession->max_queues = i + 1;
1379 	}
1380 
1381 	if (vhost_get_mem_table(vid, &vsession->mem) != 0) {
1382 		SPDK_ERRLOG("vhost device %d: Failed to get guest memory table\n", vid);
1383 		goto out;
1384 	}
1385 
1386 	/*
1387 	 * Not sure right now but this look like some kind of QEMU bug and guest IO
1388 	 * might be frozed without kicking all queues after live-migration. This look like
1389 	 * the previous vhost instance failed to effectively deliver all interrupts before
1390 	 * the GET_VRING_BASE message. This shouldn't harm guest since spurious interrupts
1391 	 * should be ignored by guest virtio driver.
1392 	 *
1393 	 * Tested on QEMU 2.10.91 and 2.11.50.
1394 	 */
1395 	for (i = 0; i < vsession->max_queues; i++) {
1396 		struct spdk_vhost_virtqueue *q = &vsession->virtqueue[i];
1397 
1398 		/* vring.desc and vring.desc_packed are in a union struct
1399 		 * so q->vring.desc can replace q->vring.desc_packed.
1400 		 */
1401 		if (q->vring.desc != NULL && q->vring.size > 0) {
1402 			rte_vhost_vring_call(vsession->vid, q->vring_idx);
1403 		}
1404 	}
1405 
1406 	vhost_session_set_coalescing(vdev, vsession, NULL);
1407 	vhost_session_mem_register(vsession->mem);
1408 	vsession->initialized = true;
1409 	rc = vdev->backend->start_session(vsession);
1410 	if (rc != 0) {
1411 		vhost_session_mem_unregister(vsession->mem);
1412 		free(vsession->mem);
1413 		goto out;
1414 	}
1415 
1416 out:
1417 	pthread_mutex_unlock(&g_vhost_mutex);
1418 	return rc;
1419 }
1420 
1421 int
1422 spdk_vhost_set_socket_path(const char *basename)
1423 {
1424 	int ret;
1425 
1426 	if (basename && strlen(basename) > 0) {
1427 		ret = snprintf(dev_dirname, sizeof(dev_dirname) - 2, "%s", basename);
1428 		if (ret <= 0) {
1429 			return -EINVAL;
1430 		}
1431 		if ((size_t)ret >= sizeof(dev_dirname) - 2) {
1432 			SPDK_ERRLOG("Char dev dir path length %d is too long\n", ret);
1433 			return -EINVAL;
1434 		}
1435 
1436 		if (dev_dirname[ret - 1] != '/') {
1437 			dev_dirname[ret] = '/';
1438 			dev_dirname[ret + 1]  = '\0';
1439 		}
1440 	}
1441 
1442 	return 0;
1443 }
1444 
1445 void
1446 vhost_dump_info_json(struct spdk_vhost_dev *vdev, struct spdk_json_write_ctx *w)
1447 {
1448 	assert(vdev->backend->dump_info_json != NULL);
1449 	vdev->backend->dump_info_json(vdev, w);
1450 }
1451 
1452 int
1453 spdk_vhost_dev_remove(struct spdk_vhost_dev *vdev)
1454 {
1455 	if (vdev->pending_async_op_num) {
1456 		return -EBUSY;
1457 	}
1458 
1459 	return vdev->backend->remove_device(vdev);
1460 }
1461 
1462 int
1463 vhost_new_connection_cb(int vid, const char *ifname)
1464 {
1465 	struct spdk_vhost_dev *vdev;
1466 	struct spdk_vhost_session *vsession;
1467 
1468 	pthread_mutex_lock(&g_vhost_mutex);
1469 
1470 	vdev = spdk_vhost_dev_find(ifname);
1471 	if (vdev == NULL) {
1472 		SPDK_ERRLOG("Couldn't find device with vid %d to create connection for.\n", vid);
1473 		pthread_mutex_unlock(&g_vhost_mutex);
1474 		return -1;
1475 	}
1476 
1477 	/* We expect sessions inside vdev->vsessions to be sorted in ascending
1478 	 * order in regard of vsession->id. For now we always set id = vsessions_cnt++
1479 	 * and append each session to the very end of the vsessions list.
1480 	 * This is required for spdk_vhost_dev_foreach_session() to work.
1481 	 */
1482 	if (vdev->vsessions_num == UINT_MAX) {
1483 		assert(false);
1484 		return -EINVAL;
1485 	}
1486 
1487 	if (posix_memalign((void **)&vsession, SPDK_CACHE_LINE_SIZE, sizeof(*vsession) +
1488 			   vdev->backend->session_ctx_size)) {
1489 		SPDK_ERRLOG("vsession alloc failed\n");
1490 		pthread_mutex_unlock(&g_vhost_mutex);
1491 		return -1;
1492 	}
1493 	memset(vsession, 0, sizeof(*vsession) + vdev->backend->session_ctx_size);
1494 
1495 	vsession->vdev = vdev;
1496 	vsession->vid = vid;
1497 	vsession->id = vdev->vsessions_num++;
1498 	vsession->name = spdk_sprintf_alloc("%ss%u", vdev->name, vsession->vid);
1499 	if (vsession->name == NULL) {
1500 		SPDK_ERRLOG("vsession alloc failed\n");
1501 		pthread_mutex_unlock(&g_vhost_mutex);
1502 		free(vsession);
1503 		return -1;
1504 	}
1505 	vsession->started = false;
1506 	vsession->initialized = false;
1507 	vsession->next_stats_check_time = 0;
1508 	vsession->stats_check_interval = SPDK_VHOST_STATS_CHECK_INTERVAL_MS *
1509 					 spdk_get_ticks_hz() / 1000UL;
1510 	TAILQ_INSERT_TAIL(&vdev->vsessions, vsession, tailq);
1511 
1512 	vhost_session_install_rte_compat_hooks(vsession);
1513 	pthread_mutex_unlock(&g_vhost_mutex);
1514 	return 0;
1515 }
1516 
1517 int
1518 vhost_destroy_connection_cb(int vid)
1519 {
1520 	struct spdk_vhost_session *vsession;
1521 	int rc = 0;
1522 
1523 	pthread_mutex_lock(&g_vhost_mutex);
1524 	vsession = vhost_session_find_by_vid(vid);
1525 	if (vsession == NULL) {
1526 		SPDK_ERRLOG("Couldn't find session with vid %d.\n", vid);
1527 		pthread_mutex_unlock(&g_vhost_mutex);
1528 		return -EINVAL;
1529 	}
1530 
1531 	if (vsession->started) {
1532 		rc = _stop_session(vsession);
1533 	}
1534 
1535 	TAILQ_REMOVE(&vsession->vdev->vsessions, vsession, tailq);
1536 	free(vsession->name);
1537 	free(vsession);
1538 	pthread_mutex_unlock(&g_vhost_mutex);
1539 
1540 	return rc;
1541 }
1542 
1543 void
1544 spdk_vhost_lock(void)
1545 {
1546 	pthread_mutex_lock(&g_vhost_mutex);
1547 }
1548 
1549 int
1550 spdk_vhost_trylock(void)
1551 {
1552 	return -pthread_mutex_trylock(&g_vhost_mutex);
1553 }
1554 
1555 void
1556 spdk_vhost_unlock(void)
1557 {
1558 	pthread_mutex_unlock(&g_vhost_mutex);
1559 }
1560 
1561 void
1562 spdk_vhost_init(spdk_vhost_init_cb init_cb)
1563 {
1564 	size_t len;
1565 	int ret;
1566 
1567 	g_vhost_init_thread = spdk_get_thread();
1568 	assert(g_vhost_init_thread != NULL);
1569 
1570 	if (dev_dirname[0] == '\0') {
1571 		if (getcwd(dev_dirname, sizeof(dev_dirname) - 1) == NULL) {
1572 			SPDK_ERRLOG("getcwd failed (%d): %s\n", errno, spdk_strerror(errno));
1573 			ret = -1;
1574 			goto out;
1575 		}
1576 
1577 		len = strlen(dev_dirname);
1578 		if (dev_dirname[len - 1] != '/') {
1579 			dev_dirname[len] = '/';
1580 			dev_dirname[len + 1] = '\0';
1581 		}
1582 	}
1583 
1584 	ret = sem_init(&g_dpdk_sem, 0, 0);
1585 	if (ret != 0) {
1586 		SPDK_ERRLOG("Failed to initialize semaphore for rte_vhost pthread.\n");
1587 		ret = -1;
1588 		goto out;
1589 	}
1590 
1591 	spdk_cpuset_zero(&g_vhost_core_mask);
1592 
1593 	/* iterate threads instead of using SPDK_ENV_FOREACH_CORE to ensure that threads are really
1594 	 * created.
1595 	 */
1596 	spdk_for_each_thread(vhost_setup_core_mask, init_cb, vhost_setup_core_mask_done);
1597 	return;
1598 out:
1599 	init_cb(ret);
1600 }
1601 
1602 static void
1603 vhost_fini(void *arg1)
1604 {
1605 	struct spdk_vhost_dev *vdev, *tmp;
1606 
1607 	spdk_vhost_lock();
1608 	vdev = spdk_vhost_dev_next(NULL);
1609 	while (vdev != NULL) {
1610 		tmp = spdk_vhost_dev_next(vdev);
1611 		spdk_vhost_dev_remove(vdev);
1612 		/* don't care if it fails, there's nothing we can do for now */
1613 		vdev = tmp;
1614 	}
1615 	spdk_vhost_unlock();
1616 
1617 	spdk_cpuset_zero(&g_vhost_core_mask);
1618 
1619 	/* All devices are removed now. */
1620 	sem_destroy(&g_dpdk_sem);
1621 
1622 	g_fini_cpl_cb();
1623 }
1624 
1625 static void *
1626 session_shutdown(void *arg)
1627 {
1628 	struct spdk_vhost_dev *vdev = NULL;
1629 
1630 	TAILQ_FOREACH(vdev, &g_vhost_devices, tailq) {
1631 		vhost_driver_unregister(vdev->path);
1632 		vdev->registered = false;
1633 	}
1634 
1635 	SPDK_INFOLOG(vhost, "Exiting\n");
1636 	spdk_thread_send_msg(g_vhost_init_thread, vhost_fini, NULL);
1637 	return NULL;
1638 }
1639 
1640 void
1641 spdk_vhost_fini(spdk_vhost_fini_cb fini_cb)
1642 {
1643 	pthread_t tid;
1644 	int rc;
1645 
1646 	assert(spdk_get_thread() == g_vhost_init_thread);
1647 	g_fini_cpl_cb = fini_cb;
1648 
1649 	/* rte_vhost API for removing sockets is not asynchronous. Since it may call SPDK
1650 	 * ops for stopping a device or removing a connection, we need to call it from
1651 	 * a separate thread to avoid deadlock.
1652 	 */
1653 	rc = pthread_create(&tid, NULL, &session_shutdown, NULL);
1654 	if (rc < 0) {
1655 		SPDK_ERRLOG("Failed to start session shutdown thread (%d): %s\n", rc, spdk_strerror(rc));
1656 		abort();
1657 	}
1658 	pthread_detach(tid);
1659 }
1660 
1661 void
1662 spdk_vhost_config_json(struct spdk_json_write_ctx *w)
1663 {
1664 	struct spdk_vhost_dev *vdev;
1665 	uint32_t delay_base_us;
1666 	uint32_t iops_threshold;
1667 
1668 	spdk_json_write_array_begin(w);
1669 
1670 	spdk_vhost_lock();
1671 	vdev = spdk_vhost_dev_next(NULL);
1672 	while (vdev != NULL) {
1673 		vdev->backend->write_config_json(vdev, w);
1674 
1675 		spdk_vhost_get_coalescing(vdev, &delay_base_us, &iops_threshold);
1676 		if (delay_base_us) {
1677 			spdk_json_write_object_begin(w);
1678 			spdk_json_write_named_string(w, "method", "vhost_controller_set_coalescing");
1679 
1680 			spdk_json_write_named_object_begin(w, "params");
1681 			spdk_json_write_named_string(w, "ctrlr", vdev->name);
1682 			spdk_json_write_named_uint32(w, "delay_base_us", delay_base_us);
1683 			spdk_json_write_named_uint32(w, "iops_threshold", iops_threshold);
1684 			spdk_json_write_object_end(w);
1685 
1686 			spdk_json_write_object_end(w);
1687 		}
1688 		vdev = spdk_vhost_dev_next(vdev);
1689 	}
1690 	spdk_vhost_unlock();
1691 
1692 	spdk_json_write_array_end(w);
1693 }
1694 
1695 SPDK_LOG_REGISTER_COMPONENT(vhost)
1696 SPDK_LOG_REGISTER_COMPONENT(vhost_ring)
1697