xref: /spdk/lib/vhost/rte_vhost_user.c (revision 6f338d4bf3a8a91b7abe377a605a321ea2b05bf7)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (c) Intel Corporation.
3  *   All rights reserved.
4  *   Copyright (c) 2021 Mellanox Technologies LTD. All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "spdk/env.h"
10 #include "spdk/likely.h"
11 #include "spdk/string.h"
12 #include "spdk/util.h"
13 #include "spdk/memory.h"
14 #include "spdk/barrier.h"
15 #include "spdk/vhost.h"
16 #include "vhost_internal.h"
17 #include <rte_version.h>
18 
19 #include "spdk_internal/vhost_user.h"
20 
21 /* Path to folder where character device will be created. Can be set by user. */
22 static char g_vhost_user_dev_dirname[PATH_MAX] = "";
23 
24 static struct spdk_thread *g_vhost_user_init_thread;
25 
26 /**
27  * DPDK calls our callbacks synchronously but the work those callbacks
28  * perform needs to be async. Luckily, all DPDK callbacks are called on
29  * a DPDK-internal pthread, so we'll just wait on a semaphore in there.
30  */
31 static sem_t g_dpdk_sem;
32 
33 /** Return code for the current DPDK callback */
34 static int g_dpdk_response;
35 
36 struct vhost_session_fn_ctx {
37 	/** Device pointer obtained before enqueueing the event */
38 	struct spdk_vhost_dev *vdev;
39 
40 	/** ID of the session to send event to. */
41 	uint32_t vsession_id;
42 
43 	/** User provided function to be executed on session's thread. */
44 	spdk_vhost_session_fn cb_fn;
45 
46 	/**
47 	 * User provided function to be called on the init thread
48 	 * after iterating through all sessions.
49 	 */
50 	spdk_vhost_dev_fn cpl_fn;
51 
52 	/** Custom user context */
53 	void *user_ctx;
54 };
55 
56 static struct spdk_vhost_user_dev *
57 to_user_dev(struct spdk_vhost_dev *vdev)
58 {
59 	assert(vdev != NULL);
60 	return vdev->ctxt;
61 }
62 
63 static void __attribute__((constructor))
64 _vhost_user_sem_init(void)
65 {
66 	if (sem_init(&g_dpdk_sem, 0, 0) != 0) {
67 		SPDK_ERRLOG("Failed to initialize semaphore for rte_vhost pthread.\n");
68 		abort();
69 	}
70 }
71 
72 static void __attribute__((destructor))
73 _vhost_user_sem_destroy(void)
74 {
75 	sem_destroy(&g_dpdk_sem);
76 }
77 
78 void *vhost_gpa_to_vva(struct spdk_vhost_session *vsession, uint64_t addr, uint64_t len)
79 {
80 	void *vva;
81 	uint64_t newlen;
82 
83 	newlen = len;
84 	vva = (void *)rte_vhost_va_from_guest_pa(vsession->mem, addr, &newlen);
85 	if (newlen != len) {
86 		return NULL;
87 	}
88 
89 	return vva;
90 
91 }
92 
93 static void
94 vhost_log_req_desc(struct spdk_vhost_session *vsession, struct spdk_vhost_virtqueue *virtqueue,
95 		   uint16_t req_id)
96 {
97 	struct vring_desc *desc, *desc_table;
98 	uint32_t desc_table_size;
99 	int rc;
100 
101 	if (spdk_likely(!vhost_dev_has_feature(vsession, VHOST_F_LOG_ALL))) {
102 		return;
103 	}
104 
105 	rc = vhost_vq_get_desc(vsession, virtqueue, req_id, &desc, &desc_table, &desc_table_size);
106 	if (spdk_unlikely(rc != 0)) {
107 		SPDK_ERRLOG("Can't log used ring descriptors!\n");
108 		return;
109 	}
110 
111 	do {
112 		if (vhost_vring_desc_is_wr(desc)) {
113 			/* To be honest, only pages realy touched should be logged, but
114 			 * doing so would require tracking those changes in each backed.
115 			 * Also backend most likely will touch all/most of those pages so
116 			 * for lets assume we touched all pages passed to as writeable buffers. */
117 			rte_vhost_log_write(vsession->vid, desc->addr, desc->len);
118 		}
119 		vhost_vring_desc_get_next(&desc, desc_table, desc_table_size);
120 	} while (desc);
121 }
122 
123 static void
124 vhost_log_used_vring_elem(struct spdk_vhost_session *vsession,
125 			  struct spdk_vhost_virtqueue *virtqueue,
126 			  uint16_t idx)
127 {
128 	uint64_t offset, len;
129 
130 	if (spdk_likely(!vhost_dev_has_feature(vsession, VHOST_F_LOG_ALL))) {
131 		return;
132 	}
133 
134 	if (spdk_unlikely(virtqueue->packed.packed_ring)) {
135 		offset = idx * sizeof(struct vring_packed_desc);
136 		len = sizeof(struct vring_packed_desc);
137 	} else {
138 		offset = offsetof(struct vring_used, ring[idx]);
139 		len = sizeof(virtqueue->vring.used->ring[idx]);
140 	}
141 
142 	rte_vhost_log_used_vring(vsession->vid, virtqueue->vring_idx, offset, len);
143 }
144 
145 static void
146 vhost_log_used_vring_idx(struct spdk_vhost_session *vsession,
147 			 struct spdk_vhost_virtqueue *virtqueue)
148 {
149 	uint64_t offset, len;
150 	uint16_t vq_idx;
151 
152 	if (spdk_likely(!vhost_dev_has_feature(vsession, VHOST_F_LOG_ALL))) {
153 		return;
154 	}
155 
156 	offset = offsetof(struct vring_used, idx);
157 	len = sizeof(virtqueue->vring.used->idx);
158 	vq_idx = virtqueue - vsession->virtqueue;
159 
160 	rte_vhost_log_used_vring(vsession->vid, vq_idx, offset, len);
161 }
162 
163 /*
164  * Get available requests from avail ring.
165  */
166 uint16_t
167 vhost_vq_avail_ring_get(struct spdk_vhost_virtqueue *virtqueue, uint16_t *reqs,
168 			uint16_t reqs_len)
169 {
170 	struct rte_vhost_vring *vring = &virtqueue->vring;
171 	struct vring_avail *avail = vring->avail;
172 	uint16_t size_mask = vring->size - 1;
173 	uint16_t last_idx = virtqueue->last_avail_idx, avail_idx = avail->idx;
174 	uint16_t count, i;
175 	int rc;
176 	uint64_t u64_value;
177 
178 	spdk_smp_rmb();
179 
180 	if (virtqueue->vsession && spdk_unlikely(virtqueue->vsession->interrupt_mode)) {
181 		/* Read to clear vring's kickfd */
182 		rc = read(vring->kickfd, &u64_value, sizeof(u64_value));
183 		if (rc < 0) {
184 			SPDK_ERRLOG("failed to acknowledge kickfd: %s.\n", spdk_strerror(errno));
185 			return -errno;
186 		}
187 	}
188 
189 	count = avail_idx - last_idx;
190 	if (spdk_likely(count == 0)) {
191 		return 0;
192 	}
193 
194 	if (spdk_unlikely(count > vring->size)) {
195 		/* TODO: the queue is unrecoverably broken and should be marked so.
196 		 * For now we will fail silently and report there are no new avail entries.
197 		 */
198 		return 0;
199 	}
200 
201 	count = spdk_min(count, reqs_len);
202 
203 	virtqueue->last_avail_idx += count;
204 	/* Check whether there are unprocessed reqs in vq, then kick vq manually */
205 	if (virtqueue->vsession && spdk_unlikely(virtqueue->vsession->interrupt_mode)) {
206 		/* If avail_idx is larger than virtqueue's last_avail_idx, then there is unprocessed reqs.
207 		 * avail_idx should get updated here from memory, in case of race condition with guest.
208 		 */
209 		avail_idx = * (volatile uint16_t *) &avail->idx;
210 		if (avail_idx > virtqueue->last_avail_idx) {
211 			/* Write to notify vring's kickfd */
212 			rc = write(vring->kickfd, &u64_value, sizeof(u64_value));
213 			if (rc < 0) {
214 				SPDK_ERRLOG("failed to kick vring: %s.\n", spdk_strerror(errno));
215 				return -errno;
216 			}
217 		}
218 	}
219 
220 	for (i = 0; i < count; i++) {
221 		reqs[i] = vring->avail->ring[(last_idx + i) & size_mask];
222 	}
223 
224 	SPDK_DEBUGLOG(vhost_ring,
225 		      "AVAIL: last_idx=%"PRIu16" avail_idx=%"PRIu16" count=%"PRIu16"\n",
226 		      last_idx, avail_idx, count);
227 
228 	return count;
229 }
230 
231 static bool
232 vhost_vring_desc_is_indirect(struct vring_desc *cur_desc)
233 {
234 	return !!(cur_desc->flags & VRING_DESC_F_INDIRECT);
235 }
236 
237 static bool
238 vhost_vring_packed_desc_is_indirect(struct vring_packed_desc *cur_desc)
239 {
240 	return (cur_desc->flags & VRING_DESC_F_INDIRECT) != 0;
241 }
242 
243 static bool
244 vhost_inflight_packed_desc_is_indirect(spdk_vhost_inflight_desc *cur_desc)
245 {
246 	return (cur_desc->flags & VRING_DESC_F_INDIRECT) != 0;
247 }
248 
249 int
250 vhost_vq_get_desc(struct spdk_vhost_session *vsession, struct spdk_vhost_virtqueue *virtqueue,
251 		  uint16_t req_idx, struct vring_desc **desc, struct vring_desc **desc_table,
252 		  uint32_t *desc_table_size)
253 {
254 	if (spdk_unlikely(req_idx >= virtqueue->vring.size)) {
255 		return -1;
256 	}
257 
258 	*desc = &virtqueue->vring.desc[req_idx];
259 
260 	if (vhost_vring_desc_is_indirect(*desc)) {
261 		*desc_table_size = (*desc)->len / sizeof(**desc);
262 		*desc_table = vhost_gpa_to_vva(vsession, (*desc)->addr,
263 					       sizeof(**desc) * *desc_table_size);
264 		*desc = *desc_table;
265 		if (*desc == NULL) {
266 			return -1;
267 		}
268 
269 		return 0;
270 	}
271 
272 	*desc_table = virtqueue->vring.desc;
273 	*desc_table_size = virtqueue->vring.size;
274 
275 	return 0;
276 }
277 
278 static bool
279 vhost_packed_desc_indirect_to_desc_table(struct spdk_vhost_session *vsession,
280 		uint64_t addr, uint32_t len,
281 		struct vring_packed_desc **desc_table,
282 		uint32_t *desc_table_size)
283 {
284 	*desc_table_size = len / sizeof(struct vring_packed_desc);
285 
286 	*desc_table = vhost_gpa_to_vva(vsession, addr, len);
287 	if (spdk_unlikely(*desc_table == NULL)) {
288 		return false;
289 	}
290 
291 	return true;
292 }
293 
294 int
295 vhost_vq_get_desc_packed(struct spdk_vhost_session *vsession,
296 			 struct spdk_vhost_virtqueue *virtqueue,
297 			 uint16_t req_idx, struct vring_packed_desc **desc,
298 			 struct vring_packed_desc **desc_table, uint32_t *desc_table_size)
299 {
300 	*desc =  &virtqueue->vring.desc_packed[req_idx];
301 
302 	/* In packed ring when the desc is non-indirect we get next desc
303 	 * by judging (desc->flag & VRING_DESC_F_NEXT) != 0. When the desc
304 	 * is indirect we get next desc by idx and desc_table_size. It's
305 	 * different from split ring.
306 	 */
307 	if (vhost_vring_packed_desc_is_indirect(*desc)) {
308 		if (!vhost_packed_desc_indirect_to_desc_table(vsession, (*desc)->addr, (*desc)->len,
309 				desc_table, desc_table_size)) {
310 			return -1;
311 		}
312 
313 		*desc = *desc_table;
314 	} else {
315 		*desc_table = NULL;
316 		*desc_table_size  = 0;
317 	}
318 
319 	return 0;
320 }
321 
322 int
323 vhost_inflight_queue_get_desc(struct spdk_vhost_session *vsession,
324 			      spdk_vhost_inflight_desc *desc_array,
325 			      uint16_t req_idx, spdk_vhost_inflight_desc **desc,
326 			      struct vring_packed_desc  **desc_table, uint32_t *desc_table_size)
327 {
328 	*desc = &desc_array[req_idx];
329 
330 	if (vhost_inflight_packed_desc_is_indirect(*desc)) {
331 		if (!vhost_packed_desc_indirect_to_desc_table(vsession, (*desc)->addr, (*desc)->len,
332 				desc_table, desc_table_size)) {
333 			return -1;
334 		}
335 
336 		/* This desc is the inflight desc not the packed desc.
337 		 * When set the F_INDIRECT the table entry should be the packed desc
338 		 * so set the inflight desc NULL.
339 		 */
340 		*desc = NULL;
341 	} else {
342 		/* When not set the F_INDIRECT means there is no packed desc table */
343 		*desc_table = NULL;
344 		*desc_table_size = 0;
345 	}
346 
347 	return 0;
348 }
349 
350 int
351 vhost_vq_used_signal(struct spdk_vhost_session *vsession,
352 		     struct spdk_vhost_virtqueue *virtqueue)
353 {
354 	if (virtqueue->used_req_cnt == 0) {
355 		return 0;
356 	}
357 
358 	virtqueue->req_cnt += virtqueue->used_req_cnt;
359 	virtqueue->used_req_cnt = 0;
360 
361 	SPDK_DEBUGLOG(vhost_ring,
362 		      "Queue %td - USED RING: sending IRQ: last used %"PRIu16"\n",
363 		      virtqueue - vsession->virtqueue, virtqueue->last_used_idx);
364 
365 	if (rte_vhost_vring_call(vsession->vid, virtqueue->vring_idx) == 0) {
366 		/* interrupt signalled */
367 		return 1;
368 	} else {
369 		/* interrupt not signalled */
370 		return 0;
371 	}
372 }
373 
374 static void
375 session_vq_io_stats_update(struct spdk_vhost_session *vsession,
376 			   struct spdk_vhost_virtqueue *virtqueue, uint64_t now)
377 {
378 	uint32_t irq_delay_base = vsession->coalescing_delay_time_base;
379 	uint32_t io_threshold = vsession->coalescing_io_rate_threshold;
380 	int32_t irq_delay;
381 	uint32_t req_cnt;
382 
383 	req_cnt = virtqueue->req_cnt + virtqueue->used_req_cnt;
384 	if (req_cnt <= io_threshold) {
385 		return;
386 	}
387 
388 	irq_delay = (irq_delay_base * (req_cnt - io_threshold)) / io_threshold;
389 	virtqueue->irq_delay_time = (uint32_t) spdk_max(0, irq_delay);
390 
391 	virtqueue->req_cnt = 0;
392 	virtqueue->next_event_time = now;
393 }
394 
395 static void
396 check_session_vq_io_stats(struct spdk_vhost_session *vsession,
397 			  struct spdk_vhost_virtqueue *virtqueue, uint64_t now)
398 {
399 	if (now < vsession->next_stats_check_time) {
400 		return;
401 	}
402 
403 	vsession->next_stats_check_time = now + vsession->stats_check_interval;
404 	session_vq_io_stats_update(vsession, virtqueue, now);
405 }
406 
407 static inline bool
408 vhost_vq_event_is_suppressed(struct spdk_vhost_virtqueue *vq)
409 {
410 	if (spdk_unlikely(vq->packed.packed_ring)) {
411 		if (vq->vring.driver_event->flags & VRING_PACKED_EVENT_FLAG_DISABLE) {
412 			return true;
413 		}
414 	} else {
415 		if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
416 			return true;
417 		}
418 	}
419 
420 	return false;
421 }
422 
423 void
424 vhost_session_vq_used_signal(struct spdk_vhost_virtqueue *virtqueue)
425 {
426 	struct spdk_vhost_session *vsession = virtqueue->vsession;
427 	uint64_t now;
428 
429 	if (vsession->coalescing_delay_time_base == 0) {
430 		if (virtqueue->vring.desc == NULL) {
431 			return;
432 		}
433 
434 		if (vhost_vq_event_is_suppressed(virtqueue)) {
435 			return;
436 		}
437 
438 		vhost_vq_used_signal(vsession, virtqueue);
439 	} else {
440 		now = spdk_get_ticks();
441 		check_session_vq_io_stats(vsession, virtqueue, now);
442 
443 		/* No need for event right now */
444 		if (now < virtqueue->next_event_time) {
445 			return;
446 		}
447 
448 		if (vhost_vq_event_is_suppressed(virtqueue)) {
449 			return;
450 		}
451 
452 		if (!vhost_vq_used_signal(vsession, virtqueue)) {
453 			return;
454 		}
455 
456 		/* Syscall is quite long so update time */
457 		now = spdk_get_ticks();
458 		virtqueue->next_event_time = now + virtqueue->irq_delay_time;
459 	}
460 }
461 
462 void
463 vhost_session_used_signal(struct spdk_vhost_session *vsession)
464 {
465 	struct spdk_vhost_virtqueue *virtqueue;
466 	uint16_t q_idx;
467 
468 	for (q_idx = 0; q_idx < vsession->max_queues; q_idx++) {
469 		virtqueue = &vsession->virtqueue[q_idx];
470 		vhost_session_vq_used_signal(virtqueue);
471 	}
472 }
473 
474 /*
475  * Enqueue id and len to used ring.
476  */
477 void
478 vhost_vq_used_ring_enqueue(struct spdk_vhost_session *vsession,
479 			   struct spdk_vhost_virtqueue *virtqueue,
480 			   uint16_t id, uint32_t len)
481 {
482 	struct rte_vhost_vring *vring = &virtqueue->vring;
483 	struct vring_used *used = vring->used;
484 	uint16_t last_idx = virtqueue->last_used_idx & (vring->size - 1);
485 	uint16_t vq_idx = virtqueue->vring_idx;
486 
487 	SPDK_DEBUGLOG(vhost_ring,
488 		      "Queue %td - USED RING: last_idx=%"PRIu16" req id=%"PRIu16" len=%"PRIu32"\n",
489 		      virtqueue - vsession->virtqueue, virtqueue->last_used_idx, id, len);
490 
491 	vhost_log_req_desc(vsession, virtqueue, id);
492 
493 	virtqueue->last_used_idx++;
494 	used->ring[last_idx].id = id;
495 	used->ring[last_idx].len = len;
496 
497 	/* Ensure the used ring is updated before we log it or increment used->idx. */
498 	spdk_smp_wmb();
499 
500 	rte_vhost_set_last_inflight_io_split(vsession->vid, vq_idx, id);
501 
502 	vhost_log_used_vring_elem(vsession, virtqueue, last_idx);
503 	* (volatile uint16_t *) &used->idx = virtqueue->last_used_idx;
504 	vhost_log_used_vring_idx(vsession, virtqueue);
505 
506 	rte_vhost_clr_inflight_desc_split(vsession->vid, vq_idx, virtqueue->last_used_idx, id);
507 
508 	virtqueue->used_req_cnt++;
509 
510 	if (vsession->interrupt_mode) {
511 		if (virtqueue->vring.desc == NULL || vhost_vq_event_is_suppressed(virtqueue)) {
512 			return;
513 		}
514 
515 		vhost_vq_used_signal(vsession, virtqueue);
516 	}
517 }
518 
519 void
520 vhost_vq_packed_ring_enqueue(struct spdk_vhost_session *vsession,
521 			     struct spdk_vhost_virtqueue *virtqueue,
522 			     uint16_t num_descs, uint16_t buffer_id,
523 			     uint32_t length, uint16_t inflight_head)
524 {
525 	struct vring_packed_desc *desc = &virtqueue->vring.desc_packed[virtqueue->last_used_idx];
526 	bool used, avail;
527 
528 	SPDK_DEBUGLOG(vhost_ring,
529 		      "Queue %td - RING: buffer_id=%"PRIu16"\n",
530 		      virtqueue - vsession->virtqueue, buffer_id);
531 
532 	/* When the descriptor is used, two flags in descriptor
533 	 * avail flag and used flag are set to equal
534 	 * and used flag value == used_wrap_counter.
535 	 */
536 	used = !!(desc->flags & VRING_DESC_F_USED);
537 	avail = !!(desc->flags & VRING_DESC_F_AVAIL);
538 	if (spdk_unlikely(used == virtqueue->packed.used_phase && used == avail)) {
539 		SPDK_ERRLOG("descriptor has been used before\n");
540 		return;
541 	}
542 
543 	/* In used desc addr is unused and len specifies the buffer length
544 	 * that has been written to by the device.
545 	 */
546 	desc->addr = 0;
547 	desc->len = length;
548 
549 	/* This bit specifies whether any data has been written by the device */
550 	if (length != 0) {
551 		desc->flags |= VRING_DESC_F_WRITE;
552 	}
553 
554 	/* Buffer ID is included in the last descriptor in the list.
555 	 * The driver needs to keep track of the size of the list corresponding
556 	 * to each buffer ID.
557 	 */
558 	desc->id = buffer_id;
559 
560 	/* A device MUST NOT make the descriptor used before buffer_id is
561 	 * written to the descriptor.
562 	 */
563 	spdk_smp_wmb();
564 
565 	rte_vhost_set_last_inflight_io_packed(vsession->vid, virtqueue->vring_idx, inflight_head);
566 	/* To mark a desc as used, the device sets the F_USED bit in flags to match
567 	 * the internal Device ring wrap counter. It also sets the F_AVAIL bit to
568 	 * match the same value.
569 	 */
570 	if (virtqueue->packed.used_phase) {
571 		desc->flags |= VRING_DESC_F_AVAIL_USED;
572 	} else {
573 		desc->flags &= ~VRING_DESC_F_AVAIL_USED;
574 	}
575 	rte_vhost_clr_inflight_desc_packed(vsession->vid, virtqueue->vring_idx, inflight_head);
576 
577 	vhost_log_used_vring_elem(vsession, virtqueue, virtqueue->last_used_idx);
578 	virtqueue->last_used_idx += num_descs;
579 	if (virtqueue->last_used_idx >= virtqueue->vring.size) {
580 		virtqueue->last_used_idx -= virtqueue->vring.size;
581 		virtqueue->packed.used_phase = !virtqueue->packed.used_phase;
582 	}
583 
584 	virtqueue->used_req_cnt++;
585 }
586 
587 bool
588 vhost_vq_packed_ring_is_avail(struct spdk_vhost_virtqueue *virtqueue)
589 {
590 	uint16_t flags = virtqueue->vring.desc_packed[virtqueue->last_avail_idx].flags;
591 
592 	/* To mark a desc as available, the driver sets the F_AVAIL bit in flags
593 	 * to match the internal avail wrap counter. It also sets the F_USED bit to
594 	 * match the inverse value but it's not mandatory.
595 	 */
596 	return (!!(flags & VRING_DESC_F_AVAIL) == virtqueue->packed.avail_phase);
597 }
598 
599 bool
600 vhost_vring_packed_desc_is_wr(struct vring_packed_desc *cur_desc)
601 {
602 	return (cur_desc->flags & VRING_DESC_F_WRITE) != 0;
603 }
604 
605 bool
606 vhost_vring_inflight_desc_is_wr(spdk_vhost_inflight_desc *cur_desc)
607 {
608 	return (cur_desc->flags & VRING_DESC_F_WRITE) != 0;
609 }
610 
611 int
612 vhost_vring_packed_desc_get_next(struct vring_packed_desc **desc, uint16_t *req_idx,
613 				 struct spdk_vhost_virtqueue *vq,
614 				 struct vring_packed_desc *desc_table,
615 				 uint32_t desc_table_size)
616 {
617 	if (desc_table != NULL) {
618 		/* When the desc_table isn't NULL means it's indirect and we get the next
619 		 * desc by req_idx and desc_table_size. The return value is NULL means
620 		 * we reach the last desc of this request.
621 		 */
622 		(*req_idx)++;
623 		if (*req_idx < desc_table_size) {
624 			*desc = &desc_table[*req_idx];
625 		} else {
626 			*desc = NULL;
627 		}
628 	} else {
629 		/* When the desc_table is NULL means it's non-indirect and we get the next
630 		 * desc by req_idx and F_NEXT in flags. The return value is NULL means
631 		 * we reach the last desc of this request. When return new desc
632 		 * we update the req_idx too.
633 		 */
634 		if (((*desc)->flags & VRING_DESC_F_NEXT) == 0) {
635 			*desc = NULL;
636 			return 0;
637 		}
638 
639 		*req_idx = (*req_idx + 1) % vq->vring.size;
640 		*desc = &vq->vring.desc_packed[*req_idx];
641 	}
642 
643 	return 0;
644 }
645 
646 static int
647 vhost_vring_desc_payload_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
648 				uint16_t *iov_index, uintptr_t payload, uint64_t remaining)
649 {
650 	uintptr_t vva;
651 	uint64_t len;
652 
653 	do {
654 		if (*iov_index >= SPDK_VHOST_IOVS_MAX) {
655 			SPDK_ERRLOG("SPDK_VHOST_IOVS_MAX(%d) reached\n", SPDK_VHOST_IOVS_MAX);
656 			return -1;
657 		}
658 		len = remaining;
659 		vva = (uintptr_t)rte_vhost_va_from_guest_pa(vsession->mem, payload, &len);
660 		if (vva == 0 || len == 0) {
661 			SPDK_ERRLOG("gpa_to_vva(%p) == NULL\n", (void *)payload);
662 			return -1;
663 		}
664 		iov[*iov_index].iov_base = (void *)vva;
665 		iov[*iov_index].iov_len = len;
666 		remaining -= len;
667 		payload += len;
668 		(*iov_index)++;
669 	} while (remaining);
670 
671 	return 0;
672 }
673 
674 int
675 vhost_vring_packed_desc_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
676 			       uint16_t *iov_index, const struct vring_packed_desc *desc)
677 {
678 	return vhost_vring_desc_payload_to_iov(vsession, iov, iov_index,
679 					       desc->addr, desc->len);
680 }
681 
682 int
683 vhost_vring_inflight_desc_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
684 				 uint16_t *iov_index, const spdk_vhost_inflight_desc *desc)
685 {
686 	return vhost_vring_desc_payload_to_iov(vsession, iov, iov_index,
687 					       desc->addr, desc->len);
688 }
689 
690 /* 1, Traverse the desc chain to get the buffer_id and return buffer_id as task_idx.
691  * 2, Update the vq->last_avail_idx to point next available desc chain.
692  * 3, Update the avail_wrap_counter if last_avail_idx overturn.
693  */
694 uint16_t
695 vhost_vring_packed_desc_get_buffer_id(struct spdk_vhost_virtqueue *vq, uint16_t req_idx,
696 				      uint16_t *num_descs)
697 {
698 	struct vring_packed_desc *desc;
699 	uint16_t desc_head = req_idx;
700 
701 	*num_descs = 1;
702 
703 	desc =  &vq->vring.desc_packed[req_idx];
704 	if (!vhost_vring_packed_desc_is_indirect(desc)) {
705 		while ((desc->flags & VRING_DESC_F_NEXT) != 0) {
706 			req_idx = (req_idx + 1) % vq->vring.size;
707 			desc = &vq->vring.desc_packed[req_idx];
708 			(*num_descs)++;
709 		}
710 	}
711 
712 	/* Queue Size doesn't have to be a power of 2
713 	 * Device maintains last_avail_idx so we can make sure
714 	 * the value is valid(0 ~ vring.size - 1)
715 	 */
716 	vq->last_avail_idx = (req_idx + 1) % vq->vring.size;
717 	if (vq->last_avail_idx < desc_head) {
718 		vq->packed.avail_phase = !vq->packed.avail_phase;
719 	}
720 
721 	return desc->id;
722 }
723 
724 int
725 vhost_vring_desc_get_next(struct vring_desc **desc,
726 			  struct vring_desc *desc_table, uint32_t desc_table_size)
727 {
728 	struct vring_desc *old_desc = *desc;
729 	uint16_t next_idx;
730 
731 	if ((old_desc->flags & VRING_DESC_F_NEXT) == 0) {
732 		*desc = NULL;
733 		return 0;
734 	}
735 
736 	next_idx = old_desc->next;
737 	if (spdk_unlikely(next_idx >= desc_table_size)) {
738 		*desc = NULL;
739 		return -1;
740 	}
741 
742 	*desc = &desc_table[next_idx];
743 	return 0;
744 }
745 
746 int
747 vhost_vring_desc_to_iov(struct spdk_vhost_session *vsession, struct iovec *iov,
748 			uint16_t *iov_index, const struct vring_desc *desc)
749 {
750 	return vhost_vring_desc_payload_to_iov(vsession, iov, iov_index,
751 					       desc->addr, desc->len);
752 }
753 
754 static inline void
755 vhost_session_mem_region_calc(uint64_t *previous_start, uint64_t *start, uint64_t *end,
756 			      uint64_t *len, struct rte_vhost_mem_region *region)
757 {
758 	*start = FLOOR_2MB(region->mmap_addr);
759 	*end = CEIL_2MB(region->mmap_addr + region->mmap_size);
760 	if (*start == *previous_start) {
761 		*start += (size_t) VALUE_2MB;
762 	}
763 	*previous_start = *start;
764 	*len = *end - *start;
765 }
766 
767 void
768 vhost_session_mem_register(struct rte_vhost_memory *mem)
769 {
770 	uint64_t start, end, len;
771 	uint32_t i;
772 	uint64_t previous_start = UINT64_MAX;
773 
774 
775 	for (i = 0; i < mem->nregions; i++) {
776 		vhost_session_mem_region_calc(&previous_start, &start, &end, &len, &mem->regions[i]);
777 		SPDK_INFOLOG(vhost, "Registering VM memory for vtophys translation - 0x%jx len:0x%jx\n",
778 			     start, len);
779 
780 		if (spdk_mem_register((void *)start, len) != 0) {
781 			SPDK_WARNLOG("Failed to register memory region %"PRIu32". Future vtophys translation might fail.\n",
782 				     i);
783 			continue;
784 		}
785 	}
786 }
787 
788 void
789 vhost_session_mem_unregister(struct rte_vhost_memory *mem)
790 {
791 	uint64_t start, end, len;
792 	uint32_t i;
793 	uint64_t previous_start = UINT64_MAX;
794 
795 	for (i = 0; i < mem->nregions; i++) {
796 		vhost_session_mem_region_calc(&previous_start, &start, &end, &len, &mem->regions[i]);
797 		if (spdk_vtophys((void *) start, NULL) == SPDK_VTOPHYS_ERROR) {
798 			continue; /* region has not been registered */
799 		}
800 
801 		if (spdk_mem_unregister((void *)start, len) != 0) {
802 			assert(false);
803 		}
804 	}
805 }
806 
807 static int
808 _stop_session(struct spdk_vhost_session *vsession)
809 {
810 	struct spdk_vhost_dev *vdev = vsession->vdev;
811 	struct spdk_vhost_user_dev *user_vdev = to_user_dev(vdev);
812 	struct spdk_vhost_virtqueue *q;
813 	int rc;
814 	uint16_t i;
815 
816 	rc = user_vdev->user_backend->stop_session(vsession);
817 	if (rc != 0) {
818 		SPDK_ERRLOG("Couldn't stop device with vid %d.\n", vsession->vid);
819 		return rc;
820 	}
821 
822 	for (i = 0; i < vsession->max_queues; i++) {
823 		q = &vsession->virtqueue[i];
824 
825 		/* vring.desc and vring.desc_packed are in a union struct
826 		 * so q->vring.desc can replace q->vring.desc_packed.
827 		 */
828 		if (q->vring.desc == NULL) {
829 			continue;
830 		}
831 
832 		/* Packed virtqueues support up to 2^15 entries each
833 		 * so left one bit can be used as wrap counter.
834 		 */
835 		if (q->packed.packed_ring) {
836 			q->last_avail_idx = q->last_avail_idx |
837 					    ((uint16_t)q->packed.avail_phase << 15);
838 			q->last_used_idx = q->last_used_idx |
839 					   ((uint16_t)q->packed.used_phase << 15);
840 		}
841 
842 		rte_vhost_set_vring_base(vsession->vid, i, q->last_avail_idx, q->last_used_idx);
843 	}
844 
845 	vhost_session_mem_unregister(vsession->mem);
846 	free(vsession->mem);
847 
848 	return 0;
849 }
850 
851 static int
852 new_connection(int vid)
853 {
854 	struct spdk_vhost_dev *vdev;
855 	struct spdk_vhost_user_dev *user_dev;
856 	struct spdk_vhost_session *vsession;
857 	size_t dev_dirname_len;
858 	char ifname[PATH_MAX];
859 	char *ctrlr_name;
860 
861 	if (rte_vhost_get_ifname(vid, ifname, PATH_MAX) < 0) {
862 		SPDK_ERRLOG("Couldn't get a valid ifname for device with vid %d\n", vid);
863 		return -1;
864 	}
865 
866 	spdk_vhost_lock();
867 
868 	ctrlr_name = &ifname[0];
869 	dev_dirname_len = strlen(g_vhost_user_dev_dirname);
870 	if (strncmp(ctrlr_name, g_vhost_user_dev_dirname, dev_dirname_len) == 0) {
871 		ctrlr_name += dev_dirname_len;
872 	}
873 
874 	vdev = spdk_vhost_dev_find(ctrlr_name);
875 	if (vdev == NULL) {
876 		SPDK_ERRLOG("Couldn't find device with vid %d to create connection for.\n", vid);
877 		spdk_vhost_unlock();
878 		return -1;
879 	}
880 	user_dev = to_user_dev(vdev);
881 
882 	/* We expect sessions inside user_dev->vsessions to be sorted in ascending
883 	 * order in regard of vsession->id. For now we always set id = vsessions_cnt++
884 	 * and append each session to the very end of the vsessions list.
885 	 * This is required for vhost_user_dev_foreach_session() to work.
886 	 */
887 	if (user_dev->vsessions_num == UINT_MAX) {
888 		assert(false);
889 		return -EINVAL;
890 	}
891 
892 	if (posix_memalign((void **)&vsession, SPDK_CACHE_LINE_SIZE, sizeof(*vsession) +
893 			   user_dev->user_backend->session_ctx_size)) {
894 		SPDK_ERRLOG("vsession alloc failed\n");
895 		spdk_vhost_unlock();
896 		return -1;
897 	}
898 	memset(vsession, 0, sizeof(*vsession) + user_dev->user_backend->session_ctx_size);
899 
900 	vsession->vdev = vdev;
901 	vsession->vid = vid;
902 	vsession->id = user_dev->vsessions_num++;
903 	vsession->name = spdk_sprintf_alloc("%ss%u", vdev->name, vsession->vid);
904 	if (vsession->name == NULL) {
905 		SPDK_ERRLOG("vsession alloc failed\n");
906 		spdk_vhost_unlock();
907 		free(vsession);
908 		return -1;
909 	}
910 	vsession->started = false;
911 	vsession->initialized = false;
912 	vsession->next_stats_check_time = 0;
913 	vsession->stats_check_interval = SPDK_VHOST_STATS_CHECK_INTERVAL_MS *
914 					 spdk_get_ticks_hz() / 1000UL;
915 	TAILQ_INSERT_TAIL(&user_dev->vsessions, vsession, tailq);
916 
917 	vhost_session_install_rte_compat_hooks(vsession);
918 	spdk_vhost_unlock();
919 	return 0;
920 }
921 
922 static int
923 start_device(int vid)
924 {
925 	struct spdk_vhost_dev *vdev;
926 	struct spdk_vhost_session *vsession;
927 	int rc = -1;
928 	uint16_t i;
929 	bool packed_ring;
930 
931 	spdk_vhost_lock();
932 
933 	vsession = vhost_session_find_by_vid(vid);
934 	if (vsession == NULL) {
935 		SPDK_ERRLOG("Couldn't find session with vid %d.\n", vid);
936 		goto out;
937 	}
938 
939 	vdev = vsession->vdev;
940 	if (vsession->started) {
941 		/* already started, nothing to do */
942 		rc = 0;
943 		goto out;
944 	}
945 
946 	if (vhost_get_negotiated_features(vid, &vsession->negotiated_features) != 0) {
947 		SPDK_ERRLOG("vhost device %d: Failed to get negotiated driver features\n", vid);
948 		goto out;
949 	}
950 
951 	packed_ring = ((vsession->negotiated_features & (1ULL << VIRTIO_F_RING_PACKED)) != 0);
952 
953 	vsession->max_queues = 0;
954 	memset(vsession->virtqueue, 0, sizeof(vsession->virtqueue));
955 	for (i = 0; i < SPDK_VHOST_MAX_VQUEUES; i++) {
956 		struct spdk_vhost_virtqueue *q = &vsession->virtqueue[i];
957 
958 		q->vsession = vsession;
959 		q->vring_idx = -1;
960 		if (rte_vhost_get_vhost_vring(vid, i, &q->vring)) {
961 			continue;
962 		}
963 		q->vring_idx = i;
964 		rte_vhost_get_vhost_ring_inflight(vid, i, &q->vring_inflight);
965 
966 		/* vring.desc and vring.desc_packed are in a union struct
967 		 * so q->vring.desc can replace q->vring.desc_packed.
968 		 */
969 		if (q->vring.desc == NULL || q->vring.size == 0) {
970 			continue;
971 		}
972 
973 		if (rte_vhost_get_vring_base(vsession->vid, i, &q->last_avail_idx, &q->last_used_idx)) {
974 			q->vring.desc = NULL;
975 			continue;
976 		}
977 
978 		if (packed_ring) {
979 			/* Use the inflight mem to restore the last_avail_idx and last_used_idx.
980 			 * When the vring format is packed, there is no used_idx in the
981 			 * used ring, so VM can't resend the used_idx to VHOST when reconnect.
982 			 * QEMU version 5.2.0 supports the packed inflight before that it only
983 			 * supports split ring inflight because it doesn't send negotiated features
984 			 * before get inflight fd. Users can use RPC to enable this function.
985 			 */
986 			if (spdk_unlikely(vdev->packed_ring_recovery)) {
987 				rte_vhost_get_vring_base_from_inflight(vsession->vid, i,
988 								       &q->last_avail_idx,
989 								       &q->last_used_idx);
990 			}
991 
992 			/* Packed virtqueues support up to 2^15 entries each
993 			 * so left one bit can be used as wrap counter.
994 			 */
995 			q->packed.avail_phase = q->last_avail_idx >> 15;
996 			q->last_avail_idx = q->last_avail_idx & 0x7FFF;
997 			q->packed.used_phase = q->last_used_idx >> 15;
998 			q->last_used_idx = q->last_used_idx & 0x7FFF;
999 
1000 			if (!vsession->interrupt_mode) {
1001 				/* Disable I/O submission notifications, we'll be polling. */
1002 				q->vring.device_event->flags = VRING_PACKED_EVENT_FLAG_DISABLE;
1003 			}
1004 		} else {
1005 			if (!vsession->interrupt_mode) {
1006 				/* Disable I/O submission notifications, we'll be polling. */
1007 				q->vring.used->flags = VRING_USED_F_NO_NOTIFY;
1008 			}
1009 		}
1010 
1011 		q->packed.packed_ring = packed_ring;
1012 		vsession->max_queues = i + 1;
1013 	}
1014 
1015 	if (vhost_get_mem_table(vid, &vsession->mem) != 0) {
1016 		SPDK_ERRLOG("vhost device %d: Failed to get guest memory table\n", vid);
1017 		goto out;
1018 	}
1019 
1020 	/*
1021 	 * Not sure right now but this look like some kind of QEMU bug and guest IO
1022 	 * might be frozed without kicking all queues after live-migration. This look like
1023 	 * the previous vhost instance failed to effectively deliver all interrupts before
1024 	 * the GET_VRING_BASE message. This shouldn't harm guest since spurious interrupts
1025 	 * should be ignored by guest virtio driver.
1026 	 *
1027 	 * Tested on QEMU 2.10.91 and 2.11.50.
1028 	 */
1029 	for (i = 0; i < vsession->max_queues; i++) {
1030 		struct spdk_vhost_virtqueue *q = &vsession->virtqueue[i];
1031 
1032 		/* vring.desc and vring.desc_packed are in a union struct
1033 		 * so q->vring.desc can replace q->vring.desc_packed.
1034 		 */
1035 		if (q->vring.desc != NULL && q->vring.size > 0) {
1036 			rte_vhost_vring_call(vsession->vid, q->vring_idx);
1037 		}
1038 	}
1039 
1040 	vhost_user_session_set_coalescing(vdev, vsession, NULL);
1041 	vhost_session_mem_register(vsession->mem);
1042 	vsession->initialized = true;
1043 	rc = to_user_dev(vdev)->user_backend->start_session(vsession);
1044 	if (rc != 0) {
1045 		vhost_session_mem_unregister(vsession->mem);
1046 		free(vsession->mem);
1047 		goto out;
1048 	}
1049 
1050 out:
1051 	spdk_vhost_unlock();
1052 	return rc;
1053 }
1054 
1055 static void
1056 stop_device(int vid)
1057 {
1058 	struct spdk_vhost_session *vsession;
1059 
1060 	spdk_vhost_lock();
1061 	vsession = vhost_session_find_by_vid(vid);
1062 	if (vsession == NULL) {
1063 		SPDK_ERRLOG("Couldn't find session with vid %d.\n", vid);
1064 		spdk_vhost_unlock();
1065 		return;
1066 	}
1067 
1068 	if (!vsession->started) {
1069 		/* already stopped, nothing to do */
1070 		spdk_vhost_unlock();
1071 		return;
1072 	}
1073 
1074 	_stop_session(vsession);
1075 	spdk_vhost_unlock();
1076 
1077 	return;
1078 }
1079 
1080 static void
1081 destroy_connection(int vid)
1082 {
1083 	struct spdk_vhost_session *vsession;
1084 
1085 	spdk_vhost_lock();
1086 	vsession = vhost_session_find_by_vid(vid);
1087 	if (vsession == NULL) {
1088 		SPDK_ERRLOG("Couldn't find session with vid %d.\n", vid);
1089 		spdk_vhost_unlock();
1090 		return;
1091 	}
1092 
1093 	if (vsession->started) {
1094 		if (_stop_session(vsession) != 0) {
1095 			spdk_vhost_unlock();
1096 			return;
1097 		}
1098 	}
1099 
1100 	TAILQ_REMOVE(&to_user_dev(vsession->vdev)->vsessions, vsession, tailq);
1101 	free(vsession->name);
1102 	free(vsession);
1103 	spdk_vhost_unlock();
1104 }
1105 
1106 #if RTE_VERSION >= RTE_VERSION_NUM(21, 11, 0, 0)
1107 static const struct rte_vhost_device_ops g_spdk_vhost_ops = {
1108 #else
1109 static const struct vhost_device_ops g_spdk_vhost_ops = {
1110 #endif
1111 	.new_device =  start_device,
1112 	.destroy_device = stop_device,
1113 	.new_connection = new_connection,
1114 	.destroy_connection = destroy_connection,
1115 };
1116 
1117 static struct spdk_vhost_session *
1118 vhost_session_find_by_id(struct spdk_vhost_dev *vdev, unsigned id)
1119 {
1120 	struct spdk_vhost_session *vsession;
1121 
1122 	TAILQ_FOREACH(vsession, &to_user_dev(vdev)->vsessions, tailq) {
1123 		if (vsession->id == id) {
1124 			return vsession;
1125 		}
1126 	}
1127 
1128 	return NULL;
1129 }
1130 
1131 struct spdk_vhost_session *
1132 vhost_session_find_by_vid(int vid)
1133 {
1134 	struct spdk_vhost_dev *vdev;
1135 	struct spdk_vhost_session *vsession;
1136 
1137 	for (vdev = spdk_vhost_dev_next(NULL); vdev != NULL;
1138 	     vdev = spdk_vhost_dev_next(vdev)) {
1139 		TAILQ_FOREACH(vsession, &to_user_dev(vdev)->vsessions, tailq) {
1140 			if (vsession->vid == vid) {
1141 				return vsession;
1142 			}
1143 		}
1144 	}
1145 
1146 	return NULL;
1147 }
1148 
1149 static void
1150 wait_for_semaphore(int timeout_sec, const char *errmsg)
1151 {
1152 	struct timespec timeout;
1153 	int rc;
1154 
1155 	clock_gettime(CLOCK_REALTIME, &timeout);
1156 	timeout.tv_sec += timeout_sec;
1157 	rc = sem_timedwait(&g_dpdk_sem, &timeout);
1158 	if (rc != 0) {
1159 		SPDK_ERRLOG("Timeout waiting for event: %s.\n", errmsg);
1160 		sem_wait(&g_dpdk_sem);
1161 	}
1162 }
1163 
1164 static void
1165 vhost_session_cb_done(int rc)
1166 {
1167 	g_dpdk_response = rc;
1168 	sem_post(&g_dpdk_sem);
1169 }
1170 
1171 void
1172 vhost_user_session_start_done(struct spdk_vhost_session *vsession, int response)
1173 {
1174 	struct spdk_vhost_user_dev *user_dev = to_user_dev(vsession->vdev);
1175 	if (response == 0) {
1176 		vsession->started = true;
1177 
1178 		assert(user_dev->active_session_num < UINT32_MAX);
1179 		user_dev->active_session_num++;
1180 	}
1181 
1182 	vhost_session_cb_done(response);
1183 }
1184 
1185 void
1186 vhost_user_session_stop_done(struct spdk_vhost_session *vsession, int response)
1187 {
1188 	struct spdk_vhost_user_dev *user_dev = to_user_dev(vsession->vdev);
1189 
1190 	if (response == 0) {
1191 		vsession->started = false;
1192 
1193 		assert(user_dev->active_session_num > 0);
1194 		user_dev->active_session_num--;
1195 	}
1196 
1197 	vhost_session_cb_done(response);
1198 }
1199 
1200 static void
1201 vhost_event_cb(void *arg1)
1202 {
1203 	struct vhost_session_fn_ctx *ctx = arg1;
1204 	struct spdk_vhost_session *vsession;
1205 
1206 	if (spdk_vhost_trylock() != 0) {
1207 		spdk_thread_send_msg(spdk_get_thread(), vhost_event_cb, arg1);
1208 		return;
1209 	}
1210 
1211 	vsession = vhost_session_find_by_id(ctx->vdev, ctx->vsession_id);
1212 	ctx->cb_fn(ctx->vdev, vsession, NULL);
1213 	spdk_vhost_unlock();
1214 }
1215 
1216 int
1217 vhost_user_session_send_event(struct spdk_vhost_session *vsession,
1218 			 spdk_vhost_session_fn cb_fn, unsigned timeout_sec,
1219 			 const char *errmsg)
1220 {
1221 	struct vhost_session_fn_ctx ev_ctx = {0};
1222 	struct spdk_vhost_dev *vdev = vsession->vdev;
1223 
1224 	ev_ctx.vdev = vdev;
1225 	ev_ctx.vsession_id = vsession->id;
1226 	ev_ctx.cb_fn = cb_fn;
1227 
1228 	spdk_thread_send_msg(vdev->thread, vhost_event_cb, &ev_ctx);
1229 
1230 	spdk_vhost_unlock();
1231 	wait_for_semaphore(timeout_sec, errmsg);
1232 	spdk_vhost_lock();
1233 
1234 	return g_dpdk_response;
1235 }
1236 
1237 static void
1238 foreach_session_finish_cb(void *arg1)
1239 {
1240 	struct vhost_session_fn_ctx *ev_ctx = arg1;
1241 	struct spdk_vhost_dev *vdev = ev_ctx->vdev;
1242 	struct spdk_vhost_user_dev *user_dev = to_user_dev(vdev);
1243 
1244 	if (spdk_vhost_trylock() != 0) {
1245 		spdk_thread_send_msg(spdk_get_thread(),
1246 				     foreach_session_finish_cb, arg1);
1247 		return;
1248 	}
1249 
1250 	assert(user_dev->pending_async_op_num > 0);
1251 	user_dev->pending_async_op_num--;
1252 	if (ev_ctx->cpl_fn != NULL) {
1253 		ev_ctx->cpl_fn(vdev, ev_ctx->user_ctx);
1254 	}
1255 
1256 	spdk_vhost_unlock();
1257 	free(ev_ctx);
1258 }
1259 
1260 static void
1261 foreach_session(void *arg1)
1262 {
1263 	struct vhost_session_fn_ctx *ev_ctx = arg1;
1264 	struct spdk_vhost_session *vsession;
1265 	struct spdk_vhost_dev *vdev = ev_ctx->vdev;
1266 	int rc;
1267 
1268 	if (spdk_vhost_trylock() != 0) {
1269 		spdk_thread_send_msg(spdk_get_thread(), foreach_session, arg1);
1270 		return;
1271 	}
1272 
1273 	TAILQ_FOREACH(vsession, &to_user_dev(vdev)->vsessions, tailq) {
1274 		if (vsession->initialized) {
1275 			rc = ev_ctx->cb_fn(vdev, vsession, ev_ctx->user_ctx);
1276 			if (rc < 0) {
1277 				goto out;
1278 			}
1279 		}
1280 	}
1281 
1282 out:
1283 	spdk_vhost_unlock();
1284 
1285 	spdk_thread_send_msg(g_vhost_user_init_thread, foreach_session_finish_cb, arg1);
1286 }
1287 
1288 void
1289 vhost_user_dev_foreach_session(struct spdk_vhost_dev *vdev,
1290 			  spdk_vhost_session_fn fn,
1291 			  spdk_vhost_dev_fn cpl_fn,
1292 			  void *arg)
1293 {
1294 	struct vhost_session_fn_ctx *ev_ctx;
1295 	struct spdk_vhost_user_dev *user_dev = to_user_dev(vdev);
1296 
1297 	ev_ctx = calloc(1, sizeof(*ev_ctx));
1298 	if (ev_ctx == NULL) {
1299 		SPDK_ERRLOG("Failed to alloc vhost event.\n");
1300 		assert(false);
1301 		return;
1302 	}
1303 
1304 	ev_ctx->vdev = vdev;
1305 	ev_ctx->cb_fn = fn;
1306 	ev_ctx->cpl_fn = cpl_fn;
1307 	ev_ctx->user_ctx = arg;
1308 
1309 	assert(user_dev->pending_async_op_num < UINT32_MAX);
1310 	user_dev->pending_async_op_num++;
1311 
1312 	spdk_thread_send_msg(vdev->thread, foreach_session, ev_ctx);
1313 }
1314 
1315 void
1316 vhost_user_session_set_interrupt_mode(struct spdk_vhost_session *vsession, bool interrupt_mode)
1317 {
1318 	uint16_t i;
1319 	bool packed_ring;
1320 	int rc = 0;
1321 
1322 	packed_ring = ((vsession->negotiated_features & (1ULL << VIRTIO_F_RING_PACKED)) != 0);
1323 
1324 	for (i = 0; i < vsession->max_queues; i++) {
1325 		struct spdk_vhost_virtqueue *q = &vsession->virtqueue[i];
1326 		uint64_t num_events = 1;
1327 
1328 		/* vring.desc and vring.desc_packed are in a union struct
1329 		 * so q->vring.desc can replace q->vring.desc_packed.
1330 		 */
1331 		if (q->vring.desc == NULL || q->vring.size == 0) {
1332 			continue;
1333 		}
1334 
1335 		if (interrupt_mode) {
1336 			/* Enable I/O submission notifications, we'll be interrupting. */
1337 			if (packed_ring) {
1338 				* (volatile uint16_t *) &q->vring.device_event->flags = VRING_PACKED_EVENT_FLAG_ENABLE;
1339 			} else {
1340 				* (volatile uint16_t *) &q->vring.used->flags = 0;
1341 			}
1342 
1343 			/* In case of race condition, always kick vring when switch to intr */
1344 			rc = write(q->vring.kickfd, &num_events, sizeof(num_events));
1345 			if (rc < 0) {
1346 				SPDK_ERRLOG("failed to kick vring: %s.\n", spdk_strerror(errno));
1347 			}
1348 
1349 			vsession->interrupt_mode = true;
1350 		} else {
1351 			/* Disable I/O submission notifications, we'll be polling. */
1352 			if (packed_ring) {
1353 				* (volatile uint16_t *) &q->vring.device_event->flags = VRING_PACKED_EVENT_FLAG_DISABLE;
1354 			} else {
1355 				* (volatile uint16_t *) &q->vring.used->flags = VRING_USED_F_NO_NOTIFY;
1356 			}
1357 
1358 			vsession->interrupt_mode = false;
1359 		}
1360 	}
1361 }
1362 
1363 
1364 static enum rte_vhost_msg_result
1365 extern_vhost_pre_msg_handler(int vid, void *_msg)
1366 {
1367 	struct vhost_user_msg *msg = _msg;
1368 	struct spdk_vhost_session *vsession;
1369 
1370 	vsession = vhost_session_find_by_vid(vid);
1371 	if (vsession == NULL) {
1372 		SPDK_ERRLOG("Received a message to unitialized session (vid %d).\n", vid);
1373 		assert(false);
1374 		return RTE_VHOST_MSG_RESULT_ERR;
1375 	}
1376 
1377 	switch (msg->request) {
1378 	case VHOST_USER_GET_VRING_BASE:
1379 		if (vsession->forced_polling && vsession->started) {
1380 			/* Our queue is stopped for whatever reason, but we may still
1381 			 * need to poll it after it's initialized again.
1382 			 */
1383 			g_spdk_vhost_ops.destroy_device(vid);
1384 		}
1385 		break;
1386 	case VHOST_USER_SET_VRING_BASE:
1387 	case VHOST_USER_SET_VRING_ADDR:
1388 	case VHOST_USER_SET_VRING_NUM:
1389 		if (vsession->forced_polling && vsession->started) {
1390 			/* Additional queues are being initialized, so we either processed
1391 			 * enough I/Os and are switching from SeaBIOS to the OS now, or
1392 			 * we were never in SeaBIOS in the first place. Either way, we
1393 			 * don't need our workaround anymore.
1394 			 */
1395 			g_spdk_vhost_ops.destroy_device(vid);
1396 			vsession->forced_polling = false;
1397 		}
1398 		break;
1399 	case VHOST_USER_SET_VRING_KICK:
1400 		/* rte_vhost(after 20.08) will call new_device after one active vring is
1401 		 * configured, we will start the session before all vrings are available,
1402 		 * so for each new vring, if the session is started, we need to restart it
1403 		 * again.
1404 		 */
1405 	case VHOST_USER_SET_VRING_CALL:
1406 		/* rte_vhost will close the previous callfd and won't notify
1407 		 * us about any change. This will effectively make SPDK fail
1408 		 * to deliver any subsequent interrupts until a session is
1409 		 * restarted. We stop the session here before closing the previous
1410 		 * fd (so that all interrupts must have been delivered by the
1411 		 * time the descriptor is closed) and start right after (which
1412 		 * will make SPDK retrieve the latest, up-to-date callfd from
1413 		 * rte_vhost.
1414 		 */
1415 	case VHOST_USER_SET_MEM_TABLE:
1416 		/* rte_vhost will unmap previous memory that SPDK may still
1417 		 * have pending DMA operations on. We can't let that happen,
1418 		 * so stop the device before letting rte_vhost unmap anything.
1419 		 * This will block until all pending I/Os are finished.
1420 		 * We will start the device again from the post-processing
1421 		 * message handler.
1422 		 */
1423 		if (vsession->started) {
1424 			g_spdk_vhost_ops.destroy_device(vid);
1425 			vsession->needs_restart = true;
1426 		}
1427 		break;
1428 	case VHOST_USER_GET_CONFIG: {
1429 		int rc = 0;
1430 
1431 		spdk_vhost_lock();
1432 		if (vsession->vdev->backend->vhost_get_config) {
1433 			rc = vsession->vdev->backend->vhost_get_config(vsession->vdev,
1434 				msg->payload.cfg.region, msg->payload.cfg.size);
1435 			if (rc != 0) {
1436 				msg->size = 0;
1437 			}
1438 		}
1439 		spdk_vhost_unlock();
1440 
1441 		return RTE_VHOST_MSG_RESULT_REPLY;
1442 	}
1443 	case VHOST_USER_SET_CONFIG: {
1444 		int rc = 0;
1445 
1446 		spdk_vhost_lock();
1447 		if (vsession->vdev->backend->vhost_set_config) {
1448 			rc = vsession->vdev->backend->vhost_set_config(vsession->vdev,
1449 				msg->payload.cfg.region, msg->payload.cfg.offset,
1450 				msg->payload.cfg.size, msg->payload.cfg.flags);
1451 		}
1452 		spdk_vhost_unlock();
1453 
1454 		return rc == 0 ? RTE_VHOST_MSG_RESULT_OK : RTE_VHOST_MSG_RESULT_ERR;
1455 	}
1456 	default:
1457 		break;
1458 	}
1459 
1460 	return RTE_VHOST_MSG_RESULT_NOT_HANDLED;
1461 }
1462 
1463 static enum rte_vhost_msg_result
1464 extern_vhost_post_msg_handler(int vid, void *_msg)
1465 {
1466 	struct vhost_user_msg *msg = _msg;
1467 	struct spdk_vhost_session *vsession;
1468 
1469 	vsession = vhost_session_find_by_vid(vid);
1470 	if (vsession == NULL) {
1471 		SPDK_ERRLOG("Received a message to unitialized session (vid %d).\n", vid);
1472 		assert(false);
1473 		return RTE_VHOST_MSG_RESULT_ERR;
1474 	}
1475 
1476 	if (vsession->needs_restart) {
1477 		g_spdk_vhost_ops.new_device(vid);
1478 		vsession->needs_restart = false;
1479 		return RTE_VHOST_MSG_RESULT_NOT_HANDLED;
1480 	}
1481 
1482 	switch (msg->request) {
1483 	case VHOST_USER_SET_FEATURES:
1484 		/* rte_vhost requires all queues to be fully initialized in order
1485 		 * to start I/O processing. This behavior is not compliant with the
1486 		 * vhost-user specification and doesn't work with QEMU 2.12+, which
1487 		 * will only initialize 1 I/O queue for the SeaBIOS boot.
1488 		 * Theoretically, we should start polling each virtqueue individually
1489 		 * after receiving its SET_VRING_KICK message, but rte_vhost is not
1490 		 * designed to poll individual queues. So here we use a workaround
1491 		 * to detect when the vhost session could be potentially at that SeaBIOS
1492 		 * stage and we mark it to start polling as soon as its first virtqueue
1493 		 * gets initialized. This doesn't hurt any non-QEMU vhost slaves
1494 		 * and allows QEMU 2.12+ to boot correctly. SET_FEATURES could be sent
1495 		 * at any time, but QEMU will send it at least once on SeaBIOS
1496 		 * initialization - whenever powered-up or rebooted.
1497 		 */
1498 		vsession->forced_polling = true;
1499 		break;
1500 	case VHOST_USER_SET_VRING_KICK:
1501 		/* vhost-user spec tells us to start polling a queue after receiving
1502 		 * its SET_VRING_KICK message. Let's do it!
1503 		 */
1504 		if (vsession->forced_polling && !vsession->started) {
1505 			g_spdk_vhost_ops.new_device(vid);
1506 		}
1507 		break;
1508 	default:
1509 		break;
1510 	}
1511 
1512 	return RTE_VHOST_MSG_RESULT_NOT_HANDLED;
1513 }
1514 
1515 struct rte_vhost_user_extern_ops g_spdk_extern_vhost_ops = {
1516 	.pre_msg_handle = extern_vhost_pre_msg_handler,
1517 	.post_msg_handle = extern_vhost_post_msg_handler,
1518 };
1519 
1520 void
1521 vhost_session_install_rte_compat_hooks(struct spdk_vhost_session *vsession)
1522 {
1523 	int rc;
1524 
1525 	rc = rte_vhost_extern_callback_register(vsession->vid, &g_spdk_extern_vhost_ops, NULL);
1526 	if (rc != 0) {
1527 		SPDK_ERRLOG("rte_vhost_extern_callback_register() failed for vid = %d\n",
1528 			    vsession->vid);
1529 		return;
1530 	}
1531 }
1532 
1533 int
1534 vhost_register_unix_socket(const char *path, const char *ctrl_name,
1535 			   uint64_t virtio_features, uint64_t disabled_features, uint64_t protocol_features)
1536 {
1537 	struct stat file_stat;
1538 	uint64_t features = 0;
1539 
1540 	/* Register vhost driver to handle vhost messages. */
1541 	if (stat(path, &file_stat) != -1) {
1542 		if (!S_ISSOCK(file_stat.st_mode)) {
1543 			SPDK_ERRLOG("Cannot create a domain socket at path \"%s\": "
1544 				    "The file already exists and is not a socket.\n",
1545 				    path);
1546 			return -EIO;
1547 		} else if (unlink(path) != 0) {
1548 			SPDK_ERRLOG("Cannot create a domain socket at path \"%s\": "
1549 				    "The socket already exists and failed to unlink.\n",
1550 				    path);
1551 			return -EIO;
1552 		}
1553 	}
1554 
1555 #if RTE_VERSION < RTE_VERSION_NUM(20, 8, 0, 0)
1556 	if (rte_vhost_driver_register(path, 0) != 0) {
1557 #else
1558 	if (rte_vhost_driver_register(path, RTE_VHOST_USER_ASYNC_COPY) != 0) {
1559 #endif
1560 		SPDK_ERRLOG("Could not register controller %s with vhost library\n", ctrl_name);
1561 		SPDK_ERRLOG("Check if domain socket %s already exists\n", path);
1562 		return -EIO;
1563 	}
1564 	if (rte_vhost_driver_set_features(path, virtio_features) ||
1565 	    rte_vhost_driver_disable_features(path, disabled_features)) {
1566 		SPDK_ERRLOG("Couldn't set vhost features for controller %s\n", ctrl_name);
1567 
1568 		rte_vhost_driver_unregister(path);
1569 		return -EIO;
1570 	}
1571 
1572 	if (rte_vhost_driver_callback_register(path, &g_spdk_vhost_ops) != 0) {
1573 		rte_vhost_driver_unregister(path);
1574 		SPDK_ERRLOG("Couldn't register callbacks for controller %s\n", ctrl_name);
1575 		return -EIO;
1576 	}
1577 
1578 	rte_vhost_driver_get_protocol_features(path, &features);
1579 	features |= protocol_features;
1580 	rte_vhost_driver_set_protocol_features(path, features);
1581 
1582 	if (rte_vhost_driver_start(path) != 0) {
1583 		SPDK_ERRLOG("Failed to start vhost driver for controller %s (%d): %s\n",
1584 			    ctrl_name, errno, spdk_strerror(errno));
1585 		rte_vhost_driver_unregister(path);
1586 		return -EIO;
1587 	}
1588 
1589 	return 0;
1590 }
1591 
1592 int
1593 vhost_get_mem_table(int vid, struct rte_vhost_memory **mem)
1594 {
1595 	return rte_vhost_get_mem_table(vid, mem);
1596 }
1597 
1598 int
1599 vhost_driver_unregister(const char *path)
1600 {
1601 	return rte_vhost_driver_unregister(path);
1602 }
1603 
1604 int
1605 vhost_get_negotiated_features(int vid, uint64_t *negotiated_features)
1606 {
1607 	return rte_vhost_get_negotiated_features(vid, negotiated_features);
1608 }
1609 
1610 int
1611 vhost_user_dev_set_coalescing(struct spdk_vhost_user_dev *user_dev, uint32_t delay_base_us,
1612 			 uint32_t iops_threshold)
1613 {
1614 	uint64_t delay_time_base = delay_base_us * spdk_get_ticks_hz() / 1000000ULL;
1615 	uint32_t io_rate = iops_threshold * SPDK_VHOST_STATS_CHECK_INTERVAL_MS / 1000U;
1616 
1617 	if (delay_time_base >= UINT32_MAX) {
1618 		SPDK_ERRLOG("Delay time of %"PRIu32" is to big\n", delay_base_us);
1619 		return -EINVAL;
1620 	} else if (io_rate == 0) {
1621 		SPDK_ERRLOG("IOPS rate of %"PRIu32" is too low. Min is %u\n", io_rate,
1622 			    1000U / SPDK_VHOST_STATS_CHECK_INTERVAL_MS);
1623 		return -EINVAL;
1624 	}
1625 
1626 	user_dev->coalescing_delay_us = delay_base_us;
1627 	user_dev->coalescing_iops_threshold = iops_threshold;
1628 	return 0;
1629 }
1630 
1631 int
1632 vhost_user_session_set_coalescing(struct spdk_vhost_dev *vdev,
1633 			     struct spdk_vhost_session *vsession, void *ctx)
1634 {
1635 	vsession->coalescing_delay_time_base =
1636 		to_user_dev(vdev)->coalescing_delay_us * spdk_get_ticks_hz() / 1000000ULL;
1637 	vsession->coalescing_io_rate_threshold =
1638 		to_user_dev(vdev)->coalescing_iops_threshold * SPDK_VHOST_STATS_CHECK_INTERVAL_MS / 1000U;
1639 	return 0;
1640 }
1641 
1642 int
1643 spdk_vhost_set_coalescing(struct spdk_vhost_dev *vdev, uint32_t delay_base_us,
1644 			  uint32_t iops_threshold)
1645 {
1646 	int rc;
1647 
1648 	rc = vhost_user_dev_set_coalescing(to_user_dev(vdev), delay_base_us, iops_threshold);
1649 	if (rc != 0) {
1650 		return rc;
1651 	}
1652 
1653 	vhost_user_dev_foreach_session(vdev, vhost_user_session_set_coalescing, NULL, NULL);
1654 	return 0;
1655 }
1656 
1657 void
1658 spdk_vhost_get_coalescing(struct spdk_vhost_dev *vdev, uint32_t *delay_base_us,
1659 			  uint32_t *iops_threshold)
1660 {
1661 	struct spdk_vhost_user_dev *user_dev = to_user_dev(vdev);
1662 
1663 	if (delay_base_us) {
1664 		*delay_base_us = user_dev->coalescing_delay_us;
1665 	}
1666 
1667 	if (iops_threshold) {
1668 		*iops_threshold = user_dev->coalescing_iops_threshold;
1669 	}
1670 }
1671 
1672 int
1673 spdk_vhost_set_socket_path(const char *basename)
1674 {
1675 	int ret;
1676 
1677 	if (basename && strlen(basename) > 0) {
1678 		ret = snprintf(g_vhost_user_dev_dirname, sizeof(g_vhost_user_dev_dirname) - 2, "%s", basename);
1679 		if (ret <= 0) {
1680 			return -EINVAL;
1681 		}
1682 		if ((size_t)ret >= sizeof(g_vhost_user_dev_dirname) - 2) {
1683 			SPDK_ERRLOG("Char dev dir path length %d is too long\n", ret);
1684 			return -EINVAL;
1685 		}
1686 
1687 		if (g_vhost_user_dev_dirname[ret - 1] != '/') {
1688 			g_vhost_user_dev_dirname[ret] = '/';
1689 			g_vhost_user_dev_dirname[ret + 1]  = '\0';
1690 		}
1691 	}
1692 
1693 	return 0;
1694 }
1695 
1696 static void
1697 vhost_dev_thread_exit(void *arg1)
1698 {
1699 	spdk_thread_exit(spdk_get_thread());
1700 }
1701 
1702 int
1703 vhost_user_dev_register(struct spdk_vhost_dev *vdev, const char *name, struct spdk_cpuset *cpumask,
1704 			const struct spdk_vhost_user_dev_backend *user_backend)
1705 {
1706 	char path[PATH_MAX];
1707 	struct spdk_vhost_user_dev *user_dev;
1708 
1709 	if (snprintf(path, sizeof(path), "%s%s", g_vhost_user_dev_dirname, name) >= (int)sizeof(path)) {
1710 		SPDK_ERRLOG("Resulting socket path for controller %s is too long: %s%s\n",
1711 				name,g_vhost_user_dev_dirname, name);
1712 		return -EINVAL;
1713 	}
1714 
1715 	vdev->path = strdup(path);
1716 	if (vdev->path == NULL) {
1717 		return -EIO;
1718 	}
1719 
1720 	user_dev = calloc(1, sizeof(*user_dev));
1721 	if (user_dev == NULL) {
1722 		free(vdev->path);
1723 		return -ENOMEM;
1724 	}
1725 	vdev->ctxt = user_dev;
1726 
1727 	vdev->thread = spdk_thread_create(vdev->name, cpumask);
1728 	if (vdev->thread == NULL) {
1729 		free(user_dev);
1730 		free(vdev->path);
1731 		SPDK_ERRLOG("Failed to create thread for vhost controller %s.\n", name);
1732 		return -EIO;
1733 	}
1734 
1735 	vdev->registered = true;
1736 	user_dev->user_backend = user_backend;
1737 	user_dev->vdev = vdev;
1738 	TAILQ_INIT(&user_dev->vsessions);
1739 
1740 	vhost_user_dev_set_coalescing(user_dev, SPDK_VHOST_COALESCING_DELAY_BASE_US,
1741 				 SPDK_VHOST_VQ_IOPS_COALESCING_THRESHOLD);
1742 
1743 	if (vhost_register_unix_socket(path, name, vdev->virtio_features, vdev->disabled_features,
1744 				       vdev->protocol_features)) {
1745 		spdk_thread_send_msg(vdev->thread, vhost_dev_thread_exit, NULL);
1746 		free(user_dev);
1747 		free(vdev->path);
1748 		return -EIO;
1749 	}
1750 
1751 	return 0;
1752 }
1753 
1754 int
1755 vhost_user_dev_unregister(struct spdk_vhost_dev *vdev)
1756 {
1757 	struct spdk_vhost_user_dev *user_dev = to_user_dev(vdev);
1758 
1759 	if (user_dev->pending_async_op_num) {
1760 		return -EBUSY;
1761 	}
1762 
1763 	if (!TAILQ_EMPTY(&user_dev->vsessions)) {
1764 		SPDK_ERRLOG("Controller %s has still valid connection.\n", vdev->name);
1765 		return -EBUSY;
1766 	}
1767 
1768 	if (vdev->registered && vhost_driver_unregister(vdev->path) != 0) {
1769 		SPDK_ERRLOG("Could not unregister controller %s with vhost library\n"
1770 			    "Check if domain socket %s still exists\n",
1771 			    vdev->name, vdev->path);
1772 		return -EIO;
1773 	}
1774 
1775 	spdk_thread_send_msg(vdev->thread, vhost_dev_thread_exit, NULL);
1776 	free(user_dev);
1777 	free(vdev->path);
1778 
1779 	return 0;
1780 }
1781 
1782 static bool g_vhost_user_started = false;
1783 
1784 int
1785 vhost_user_init(void)
1786 {
1787 	size_t len;
1788 
1789 	if (g_vhost_user_started) {
1790 		return 0;
1791 	}
1792 
1793 	if (g_vhost_user_dev_dirname[0] == '\0') {
1794 		if (getcwd(g_vhost_user_dev_dirname, sizeof(g_vhost_user_dev_dirname) - 1) == NULL) {
1795 			SPDK_ERRLOG("getcwd failed (%d): %s\n", errno, spdk_strerror(errno));
1796 			return -1;
1797 		}
1798 
1799 		len = strlen(g_vhost_user_dev_dirname);
1800 		if (g_vhost_user_dev_dirname[len - 1] != '/') {
1801 			g_vhost_user_dev_dirname[len] = '/';
1802 			g_vhost_user_dev_dirname[len + 1] = '\0';
1803 		}
1804 	}
1805 
1806 	g_vhost_user_started = true;
1807 
1808 	g_vhost_user_init_thread = spdk_get_thread();
1809 	assert(g_vhost_user_init_thread != NULL);
1810 
1811 	return 0;
1812 }
1813 
1814 static void
1815 vhost_user_session_shutdown_on_init(void *vhost_cb)
1816 {
1817 	spdk_vhost_fini_cb fn = vhost_cb;
1818 
1819 	fn();
1820 }
1821 
1822 static void *
1823 vhost_user_session_shutdown(void *vhost_cb)
1824 {
1825 	struct spdk_vhost_dev *vdev = NULL;
1826 	struct spdk_vhost_session *vsession;
1827 
1828 	for (vdev = spdk_vhost_dev_next(NULL); vdev != NULL;
1829 	     vdev = spdk_vhost_dev_next(vdev)) {
1830 		spdk_vhost_lock();
1831 		TAILQ_FOREACH(vsession, &to_user_dev(vdev)->vsessions, tailq) {
1832 			if (vsession->started) {
1833 				_stop_session(vsession);
1834 			}
1835 		}
1836 		spdk_vhost_unlock();
1837 		vhost_driver_unregister(vdev->path);
1838 		vdev->registered = false;
1839 	}
1840 
1841 	SPDK_INFOLOG(vhost, "Exiting\n");
1842 	spdk_thread_send_msg(g_vhost_user_init_thread, vhost_user_session_shutdown_on_init, vhost_cb);
1843 	return NULL;
1844 }
1845 
1846 void
1847 vhost_user_fini(spdk_vhost_fini_cb vhost_cb)
1848 {
1849 	pthread_t tid;
1850 	int rc;
1851 
1852 	if (!g_vhost_user_started) {
1853 		vhost_cb();
1854 		return;
1855 	}
1856 
1857 	g_vhost_user_started = false;
1858 
1859 	/* rte_vhost API for removing sockets is not asynchronous. Since it may call SPDK
1860 	 * ops for stopping a device or removing a connection, we need to call it from
1861 	 * a separate thread to avoid deadlock.
1862 	 */
1863 	rc = pthread_create(&tid, NULL, &vhost_user_session_shutdown, vhost_cb);
1864 	if (rc < 0) {
1865 		SPDK_ERRLOG("Failed to start session shutdown thread (%d): %s\n", rc, spdk_strerror(rc));
1866 		abort();
1867 	}
1868 	pthread_detach(tid);
1869 }
1870