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