xref: /openbsd-src/sys/dev/pv/hyperv.c (revision 1ad61ae0a79a724d2d3ec69e69c8e1d1ff6b53a0)
1 /*-
2  * Copyright (c) 2009-2012 Microsoft Corp.
3  * Copyright (c) 2012 NetApp Inc.
4  * Copyright (c) 2012 Citrix Inc.
5  * Copyright (c) 2016 Mike Belopuhov <mike@esdenera.com>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice unmodified, this list of conditions, and the following
13  *    disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*
31  * The OpenBSD port was done under funding by Esdenera Networks GmbH.
32  */
33 
34 #include <sys/param.h>
35 
36 /* Hyperv requires locked atomic operations */
37 #ifndef MULTIPROCESSOR
38 #define _HYPERVMPATOMICS
39 #define MULTIPROCESSOR
40 #endif
41 #include <sys/atomic.h>
42 #ifdef _HYPERVMPATOMICS
43 #undef MULTIPROCESSOR
44 #undef _HYPERVMPATOMICS
45 #endif
46 
47 #include <sys/systm.h>
48 #include <sys/proc.h>
49 #include <sys/signal.h>
50 #include <sys/signalvar.h>
51 #include <sys/malloc.h>
52 #include <sys/kernel.h>
53 #include <sys/device.h>
54 #include <sys/timetc.h>
55 #include <sys/task.h>
56 #include <sys/syslog.h>
57 
58 #include <machine/bus.h>
59 #include <machine/cpu.h>
60 #include <machine/cpufunc.h>
61 
62 #include <uvm/uvm_extern.h>
63 
64 #include <machine/i82489var.h>
65 
66 #include <dev/pv/pvvar.h>
67 #include <dev/pv/pvreg.h>
68 #include <dev/pv/hypervreg.h>
69 #include <dev/pv/hypervvar.h>
70 
71 /* Command submission flags */
72 #define HCF_SLEEPOK	0x0001	/* M_WAITOK */
73 #define HCF_NOSLEEP	0x0002	/* M_NOWAIT */
74 #define HCF_NOREPLY	0x0004
75 
76 struct hv_softc *hv_sc;
77 
78 int 	hv_match(struct device *, void *, void *);
79 void	hv_attach(struct device *, struct device *, void *);
80 void	hv_set_version(struct hv_softc *);
81 u_int	hv_gettime(struct timecounter *);
82 int	hv_init_hypercall(struct hv_softc *);
83 uint64_t hv_hypercall(struct hv_softc *, uint64_t, void *, void *);
84 int	hv_init_interrupts(struct hv_softc *);
85 int	hv_init_synic(struct hv_softc *);
86 int	hv_cmd(struct hv_softc *, void *, size_t, void *, size_t, int);
87 int	hv_start(struct hv_softc *, struct hv_msg *);
88 int	hv_reply(struct hv_softc *, struct hv_msg *);
89 void	hv_wait(struct hv_softc *, int (*done)(struct hv_softc *,
90 	    struct hv_msg *), struct hv_msg *, void *, const char *);
91 uint16_t hv_intr_signal(struct hv_softc *, void *);
92 void	hv_intr(void);
93 void	hv_event_intr(struct hv_softc *);
94 void	hv_message_intr(struct hv_softc *);
95 int	hv_vmbus_connect(struct hv_softc *);
96 void	hv_channel_response(struct hv_softc *, struct vmbus_chanmsg_hdr *);
97 void	hv_channel_offer(struct hv_softc *, struct vmbus_chanmsg_hdr *);
98 void	hv_channel_rescind(struct hv_softc *, struct vmbus_chanmsg_hdr *);
99 void	hv_channel_delivered(struct hv_softc *, struct vmbus_chanmsg_hdr *);
100 int	hv_channel_scan(struct hv_softc *);
101 void	hv_process_offer(struct hv_softc *, struct hv_offer *);
102 struct hv_channel *
103 	hv_channel_lookup(struct hv_softc *, uint32_t);
104 int	hv_channel_ring_create(struct hv_channel *, uint32_t);
105 void	hv_channel_ring_destroy(struct hv_channel *);
106 void	hv_channel_pause(struct hv_channel *);
107 uint	hv_channel_unpause(struct hv_channel *);
108 uint	hv_channel_ready(struct hv_channel *);
109 extern void hv_attach_icdevs(struct hv_softc *);
110 int	hv_attach_devices(struct hv_softc *);
111 
112 struct {
113 	int		  hmd_response;
114 	int		  hmd_request;
115 	void		(*hmd_handler)(struct hv_softc *,
116 			    struct vmbus_chanmsg_hdr *);
117 } hv_msg_dispatch[] = {
118 	{ 0,					0, NULL },
119 	{ VMBUS_CHANMSG_CHOFFER,		0, hv_channel_offer },
120 	{ VMBUS_CHANMSG_CHRESCIND,		0, hv_channel_rescind },
121 	{ VMBUS_CHANMSG_CHREQUEST,		VMBUS_CHANMSG_CHOFFER,
122 	  NULL },
123 	{ VMBUS_CHANMSG_CHOFFER_DONE,		0,
124 	  hv_channel_delivered },
125 	{ VMBUS_CHANMSG_CHOPEN,			0, NULL },
126 	{ VMBUS_CHANMSG_CHOPEN_RESP,		VMBUS_CHANMSG_CHOPEN,
127 	  hv_channel_response },
128 	{ VMBUS_CHANMSG_CHCLOSE,		0, NULL },
129 	{ VMBUS_CHANMSG_GPADL_CONN,		0, NULL },
130 	{ VMBUS_CHANMSG_GPADL_SUBCONN,		0, NULL },
131 	{ VMBUS_CHANMSG_GPADL_CONNRESP,		VMBUS_CHANMSG_GPADL_CONN,
132 	  hv_channel_response },
133 	{ VMBUS_CHANMSG_GPADL_DISCONN,		0, NULL },
134 	{ VMBUS_CHANMSG_GPADL_DISCONNRESP,	VMBUS_CHANMSG_GPADL_DISCONN,
135 	  hv_channel_response },
136 	{ VMBUS_CHANMSG_CHFREE,			0, NULL },
137 	{ VMBUS_CHANMSG_CONNECT,		0, NULL },
138 	{ VMBUS_CHANMSG_CONNECT_RESP,		VMBUS_CHANMSG_CONNECT,
139 	  hv_channel_response },
140 	{ VMBUS_CHANMSG_DISCONNECT,		0, NULL },
141 };
142 
143 struct timecounter hv_timecounter = {
144 	.tc_get_timecount = hv_gettime,
145 	.tc_counter_mask = 0xffffffff,
146 	.tc_frequency = 10000000,
147 	.tc_name = "hyperv",
148 	.tc_quality = 9001,
149 	.tc_priv = NULL,
150 	.tc_user = 0,
151 };
152 
153 struct cfdriver hyperv_cd = {
154 	NULL, "hyperv", DV_DULL
155 };
156 
157 const struct cfattach hyperv_ca = {
158 	sizeof(struct hv_softc), hv_match, hv_attach
159 };
160 
161 const struct hv_guid hv_guid_network = {
162 	{ 0x63, 0x51, 0x61, 0xf8, 0x3e, 0xdf, 0xc5, 0x46,
163 	  0x91, 0x3f, 0xf2, 0xd2, 0xf9, 0x65, 0xed, 0x0e }
164 };
165 
166 const struct hv_guid hv_guid_ide = {
167 	{ 0x32, 0x26, 0x41, 0x32, 0xcb, 0x86, 0xa2, 0x44,
168 	  0x9b, 0x5c, 0x50, 0xd1, 0x41, 0x73, 0x54, 0xf5 }
169 };
170 
171 const struct hv_guid hv_guid_scsi = {
172 	{ 0xd9, 0x63, 0x61, 0xba, 0xa1, 0x04, 0x29, 0x4d,
173 	  0xb6, 0x05, 0x72, 0xe2, 0xff, 0xb1, 0xdc, 0x7f }
174 };
175 
176 const struct hv_guid hv_guid_shutdown = {
177 	{ 0x31, 0x60, 0x0b, 0x0e, 0x13, 0x52, 0x34, 0x49,
178 	  0x81, 0x8b, 0x38, 0xd9, 0x0c, 0xed, 0x39, 0xdb }
179 };
180 
181 const struct hv_guid hv_guid_timesync = {
182 	{ 0x30, 0xe6, 0x27, 0x95, 0xae, 0xd0, 0x7b, 0x49,
183 	  0xad, 0xce, 0xe8, 0x0a, 0xb0, 0x17, 0x5c, 0xaf }
184 };
185 
186 const struct hv_guid hv_guid_heartbeat = {
187 	{ 0x39, 0x4f, 0x16, 0x57, 0x15, 0x91, 0x78, 0x4e,
188 	  0xab, 0x55, 0x38, 0x2f, 0x3b, 0xd5, 0x42, 0x2d }
189 };
190 
191 const struct hv_guid hv_guid_kvp = {
192 	{ 0xe7, 0xf4, 0xa0, 0xa9, 0x45, 0x5a, 0x96, 0x4d,
193 	  0xb8, 0x27, 0x8a, 0x84, 0x1e, 0x8c, 0x03, 0xe6 }
194 };
195 
196 #ifdef HYPERV_DEBUG
197 const struct hv_guid hv_guid_vss = {
198 	{ 0x29, 0x2e, 0xfa, 0x35, 0x23, 0xea, 0x36, 0x42,
199 	  0x96, 0xae, 0x3a, 0x6e, 0xba, 0xcb, 0xa4, 0x40 }
200 };
201 
202 const struct hv_guid hv_guid_dynmem = {
203 	{ 0xdc, 0x74, 0x50, 0x52, 0x85, 0x89, 0xe2, 0x46,
204 	  0x80, 0x57, 0xa3, 0x07, 0xdc, 0x18, 0xa5, 0x02 }
205 };
206 
207 const struct hv_guid hv_guid_mouse = {
208 	{ 0x9e, 0xb6, 0xa8, 0xcf, 0x4a, 0x5b, 0xc0, 0x4c,
209 	  0xb9, 0x8b, 0x8b, 0xa1, 0xa1, 0xf3, 0xf9, 0x5a }
210 };
211 
212 const struct hv_guid hv_guid_kbd = {
213 	{ 0x6d, 0xad, 0x12, 0xf9, 0x17, 0x2b, 0xea, 0x48,
214 	  0xbd, 0x65, 0xf9, 0x27, 0xa6, 0x1c, 0x76, 0x84 }
215 };
216 
217 const struct hv_guid hv_guid_video = {
218 	{ 0x02, 0x78, 0x0a, 0xda, 0x77, 0xe3, 0xac, 0x4a,
219 	  0x8e, 0x77, 0x05, 0x58, 0xeb, 0x10, 0x73, 0xf8 }
220 };
221 
222 const struct hv_guid hv_guid_fc = {
223 	{ 0x4a, 0xcc, 0x9b, 0x2f, 0x69, 0x00, 0xf3, 0x4a,
224 	  0xb7, 0x6b, 0x6f, 0xd0, 0xbe, 0x52, 0x8c, 0xda }
225 };
226 
227 const struct hv_guid hv_guid_fcopy = {
228 	{ 0xe3, 0x4b, 0xd1, 0x34, 0xe4, 0xde, 0xc8, 0x41,
229 	  0x9a, 0xe7, 0x6b, 0x17, 0x49, 0x77, 0xc1, 0x92 }
230 };
231 
232 const struct hv_guid hv_guid_pcie = {
233 	{ 0x1d, 0xf6, 0xc4, 0x44, 0x44, 0x44, 0x00, 0x44,
234 	  0x9d, 0x52, 0x80, 0x2e, 0x27, 0xed, 0xe1, 0x9f }
235 };
236 
237 const struct hv_guid hv_guid_netdir = {
238 	{ 0x3d, 0xaf, 0x2e, 0x8c, 0xa7, 0x32, 0x09, 0x4b,
239 	  0xab, 0x99, 0xbd, 0x1f, 0x1c, 0x86, 0xb5, 0x01 }
240 };
241 
242 const struct hv_guid hv_guid_rdesktop = {
243 	{ 0xf4, 0xac, 0x6a, 0x27, 0x15, 0xac, 0x6c, 0x42,
244 	  0x98, 0xdd, 0x75, 0x21, 0xad, 0x3f, 0x01, 0xfe }
245 };
246 
247 /* Automatic Virtual Machine Activation (AVMA) Services */
248 const struct hv_guid hv_guid_avma1 = {
249 	{ 0x55, 0xb2, 0x87, 0x44, 0x8c, 0xb8, 0x3f, 0x40,
250 	  0xbb, 0x51, 0xd1, 0xf6, 0x9c, 0xf1, 0x7f, 0x87 }
251 };
252 
253 const struct hv_guid hv_guid_avma2 = {
254 	{ 0xf4, 0xba, 0x75, 0x33, 0x15, 0x9e, 0x30, 0x4b,
255 	  0xb7, 0x65, 0x67, 0xac, 0xb1, 0x0d, 0x60, 0x7b }
256 };
257 
258 const struct hv_guid hv_guid_avma3 = {
259 	{ 0xa0, 0x1f, 0x22, 0x99, 0xad, 0x24, 0xe2, 0x11,
260 	  0xbe, 0x98, 0x00, 0x1a, 0xa0, 0x1b, 0xbf, 0x6e }
261 };
262 
263 const struct hv_guid hv_guid_avma4 = {
264 	{ 0x16, 0x57, 0xe6, 0xf8, 0xb3, 0x3c, 0x06, 0x4a,
265 	  0x9a, 0x60, 0x18, 0x89, 0xc5, 0xcc, 0xca, 0xb5 }
266 };
267 #endif	/* HYPERV_DEBUG */
268 
269 int
270 hv_match(struct device *parent, void *match, void *aux)
271 {
272 	struct pv_attach_args *pva = aux;
273 	struct pvbus_hv *hv = &pva->pva_hv[PVBUS_HYPERV];
274 
275 	if ((hv->hv_major == 0 && hv->hv_minor == 0) || hv->hv_base == 0)
276 		return (0);
277 
278 	return (1);
279 }
280 
281 void
282 hv_attach(struct device *parent, struct device *self, void *aux)
283 {
284 	struct hv_softc *sc = (struct hv_softc *)self;
285 	struct pv_attach_args *pva = aux;
286 	struct pvbus_hv *hv = &pva->pva_hv[PVBUS_HYPERV];
287 
288 	sc->sc_pvbus = hv;
289 	sc->sc_dmat = pva->pva_dmat;
290 
291 	if (!(hv->hv_features & CPUID_HV_MSR_HYPERCALL) ||
292 	    !(hv->hv_features & CPUID_HV_MSR_SYNIC)) {
293 		printf(": not functional\n");
294 		return;
295 	}
296 
297 	DPRINTF("\n");
298 
299 	hv_set_version(sc);
300 
301 	if (hv->hv_features & CPUID_HV_MSR_TIME_REFCNT)
302 		tc_init(&hv_timecounter);
303 
304 	if (hv_init_hypercall(sc))
305 		return;
306 
307 	/* Wire it up to the global */
308 	hv_sc = sc;
309 
310 	if (hv_init_interrupts(sc))
311 		return;
312 
313 	if (hv_vmbus_connect(sc))
314 		return;
315 
316 	DPRINTF("%s", sc->sc_dev.dv_xname);
317 	printf(": protocol %d.%d, features %#x\n",
318 	    VMBUS_VERSION_MAJOR(sc->sc_proto),
319 	    VMBUS_VERSION_MINOR(sc->sc_proto),
320 	    hv->hv_features);
321 
322 	if (hv_channel_scan(sc))
323 		return;
324 
325 	/* Attach heartbeat, KVP and other "internal" services */
326 	hv_attach_icdevs(sc);
327 
328 	/* Attach devices with external drivers */
329 	hv_attach_devices(sc);
330 }
331 
332 void
333 hv_set_version(struct hv_softc *sc)
334 {
335 	uint64_t ver;
336 
337 	/* OpenBSD build date */
338 	ver = MSR_HV_GUESTID_OSTYPE_OPENBSD;
339 	ver |= (uint64_t)OpenBSD << MSR_HV_GUESTID_VERSION_SHIFT;
340 	wrmsr(MSR_HV_GUEST_OS_ID, ver);
341 }
342 
343 u_int
344 hv_gettime(struct timecounter *tc)
345 {
346 	u_int now = rdmsr(MSR_HV_TIME_REF_COUNT);
347 
348 	return (now);
349 }
350 
351 void
352 hv_delay(int usecs)
353 {
354 	uint64_t interval, start;
355 
356 	/* 10 MHz fixed frequency */
357 	interval = (uint64_t)usecs * 10;
358 	start = rdmsr(MSR_HV_TIME_REF_COUNT);
359 	while (rdmsr(MSR_HV_TIME_REF_COUNT) - start < interval)
360 		CPU_BUSY_CYCLE();
361 }
362 
363 int
364 hv_init_hypercall(struct hv_softc *sc)
365 {
366 	extern void *hv_hypercall_page;
367 	uint64_t msr;
368 	paddr_t pa;
369 
370 	sc->sc_hc = &hv_hypercall_page;
371 
372 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_hc, &pa)) {
373 		printf(": hypercall page PA extraction failed\n");
374 		return (-1);
375 	}
376 
377 	msr = (atop(pa) << MSR_HV_HYPERCALL_PGSHIFT) | MSR_HV_HYPERCALL_ENABLE;
378 	wrmsr(MSR_HV_HYPERCALL, msr);
379 
380 	if (!(rdmsr(MSR_HV_HYPERCALL) & MSR_HV_HYPERCALL_ENABLE)) {
381 		printf(": failed to set up a hypercall page\n");
382 		return (-1);
383 	}
384 
385 	return (0);
386 }
387 
388 uint64_t
389 hv_hypercall(struct hv_softc *sc, uint64_t control, void *input,
390     void *output)
391 {
392 	paddr_t input_pa = 0, output_pa = 0;
393 	uint64_t status = 0;
394 
395 	if (input != NULL &&
396 	    pmap_extract(pmap_kernel(), (vaddr_t)input, &input_pa) == 0) {
397 		printf("%s: hypercall input PA extraction failed\n",
398 		    sc->sc_dev.dv_xname);
399 		return (~HYPERCALL_STATUS_SUCCESS);
400 	}
401 
402 	if (output != NULL &&
403 	    pmap_extract(pmap_kernel(), (vaddr_t)output, &output_pa) == 0) {
404 		printf("%s: hypercall output PA extraction failed\n",
405 		    sc->sc_dev.dv_xname);
406 		return (~HYPERCALL_STATUS_SUCCESS);
407 	}
408 
409 #ifdef __amd64__
410 	extern uint64_t hv_hypercall_trampoline(uint64_t, paddr_t, paddr_t);
411 	status = hv_hypercall_trampoline(control, input_pa, output_pa);
412 #else  /* __i386__ */
413 	{
414 		uint32_t control_hi = control >> 32;
415 		uint32_t control_lo = control & 0xfffffffff;
416 		uint32_t status_hi = 1;
417 		uint32_t status_lo = 1;
418 
419 		__asm__ volatile ("call *%8" :
420 		    "=d" (status_hi), "=a"(status_lo) :
421 		    "d" (control_hi), "a" (control_lo),
422 		    "b" (0), "c" (input_pa), "D" (0), "S" (output_pa),
423 		    "m" (sc->sc_hc));
424 
425 		status = status_lo | ((uint64_t)status_hi << 32);
426 	}
427 #endif	/* __amd64__ */
428 
429 	return (status);
430 }
431 
432 int
433 hv_init_interrupts(struct hv_softc *sc)
434 {
435 	struct cpu_info *ci = curcpu();
436 	int cpu = CPU_INFO_UNIT(ci);
437 
438 	sc->sc_idtvec = LAPIC_HYPERV_VECTOR;
439 
440 	TAILQ_INIT(&sc->sc_reqs);
441 	mtx_init(&sc->sc_reqlck, IPL_NET);
442 
443 	TAILQ_INIT(&sc->sc_rsps);
444 	mtx_init(&sc->sc_rsplck, IPL_NET);
445 
446 	sc->sc_simp[cpu] = km_alloc(PAGE_SIZE, &kv_any, &kp_zero, &kd_nowait);
447 	if (sc->sc_simp[cpu] == NULL) {
448 		printf(": failed to allocate SIMP\n");
449 		return (-1);
450 	}
451 
452 	sc->sc_siep[cpu] = km_alloc(PAGE_SIZE, &kv_any, &kp_zero, &kd_nowait);
453 	if (sc->sc_siep[cpu] == NULL) {
454 		printf(": failed to allocate SIEP\n");
455 		km_free(sc->sc_simp[cpu], PAGE_SIZE, &kv_any, &kp_zero);
456 		return (-1);
457 	}
458 
459 	sc->sc_proto = VMBUS_VERSION_WS2008;
460 
461 	return (hv_init_synic(sc));
462 }
463 
464 int
465 hv_init_synic(struct hv_softc *sc)
466 {
467 	struct cpu_info *ci = curcpu();
468 	int cpu = CPU_INFO_UNIT(ci);
469 	uint64_t simp, siefp, sctrl, sint;
470 	paddr_t pa;
471 
472 	/*
473 	 * Setup the Synic's message page
474 	 */
475 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_simp[cpu], &pa)) {
476 		printf(": SIMP PA extraction failed\n");
477 		return (-1);
478 	}
479 	simp = rdmsr(MSR_HV_SIMP);
480 	simp &= (1 << MSR_HV_SIMP_PGSHIFT) - 1;
481 	simp |= (atop(pa) << MSR_HV_SIMP_PGSHIFT);
482 	simp |= MSR_HV_SIMP_ENABLE;
483 	wrmsr(MSR_HV_SIMP, simp);
484 
485 	/*
486 	 * Setup the Synic's event page
487 	 */
488 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_siep[cpu], &pa)) {
489 		printf(": SIEP PA extraction failed\n");
490 		return (-1);
491 	}
492 	siefp = rdmsr(MSR_HV_SIEFP);
493 	siefp &= (1<<MSR_HV_SIEFP_PGSHIFT) - 1;
494 	siefp |= (atop(pa) << MSR_HV_SIEFP_PGSHIFT);
495 	siefp |= MSR_HV_SIEFP_ENABLE;
496 	wrmsr(MSR_HV_SIEFP, siefp);
497 
498 	/*
499 	 * Configure and unmask SINT for message and event flags
500 	 */
501 	sint = rdmsr(MSR_HV_SINT0 + VMBUS_SINT_MESSAGE);
502 	sint = sc->sc_idtvec | MSR_HV_SINT_AUTOEOI |
503 	    (sint & MSR_HV_SINT_RSVD_MASK);
504 	wrmsr(MSR_HV_SINT0 + VMBUS_SINT_MESSAGE, sint);
505 
506 	/* Enable the global synic bit */
507 	sctrl = rdmsr(MSR_HV_SCONTROL);
508 	sctrl |= MSR_HV_SCTRL_ENABLE;
509 	wrmsr(MSR_HV_SCONTROL, sctrl);
510 
511 	sc->sc_vcpus[cpu] = rdmsr(MSR_HV_VP_INDEX);
512 
513 	DPRINTF("vcpu%u: SIMP %#llx SIEFP %#llx SCTRL %#llx\n",
514 	    sc->sc_vcpus[cpu], simp, siefp, sctrl);
515 
516 	return (0);
517 }
518 
519 int
520 hv_cmd(struct hv_softc *sc, void *cmd, size_t cmdlen, void *rsp,
521     size_t rsplen, int flags)
522 {
523 	struct hv_msg msg;
524 	int rv;
525 
526 	if (cmdlen > VMBUS_MSG_DSIZE_MAX) {
527 		printf("%s: payload too large (%lu)\n", sc->sc_dev.dv_xname,
528 		    cmdlen);
529 		return (EMSGSIZE);
530 	}
531 
532 	memset(&msg, 0, sizeof(msg));
533 
534 	msg.msg_req.hc_dsize = cmdlen;
535 	memcpy(msg.msg_req.hc_data, cmd, cmdlen);
536 
537 	if (!(flags & HCF_NOREPLY)) {
538 		msg.msg_rsp = rsp;
539 		msg.msg_rsplen = rsplen;
540 	} else
541 		msg.msg_flags |= MSGF_NOQUEUE;
542 
543 	if (flags & HCF_NOSLEEP)
544 		msg.msg_flags |= MSGF_NOSLEEP;
545 
546 	if ((rv = hv_start(sc, &msg)) != 0)
547 		return (rv);
548 	return (hv_reply(sc, &msg));
549 }
550 
551 int
552 hv_start(struct hv_softc *sc, struct hv_msg *msg)
553 {
554 	const int delays[] = { 100, 100, 100, 500, 500, 5000, 5000, 5000 };
555 	const char *wchan = "hvstart";
556 	uint16_t status;
557 	int i, s;
558 
559 	msg->msg_req.hc_connid = VMBUS_CONNID_MESSAGE;
560 	msg->msg_req.hc_msgtype = 1;
561 
562 	if (!(msg->msg_flags & MSGF_NOQUEUE)) {
563 		mtx_enter(&sc->sc_reqlck);
564 		TAILQ_INSERT_TAIL(&sc->sc_reqs, msg, msg_entry);
565 		mtx_leave(&sc->sc_reqlck);
566 	}
567 
568 	for (i = 0; i < nitems(delays); i++) {
569 		status = hv_hypercall(sc, HYPERCALL_POST_MESSAGE,
570 		    &msg->msg_req, NULL);
571 		if (status == HYPERCALL_STATUS_SUCCESS)
572 			break;
573 		if (msg->msg_flags & MSGF_NOSLEEP) {
574 			delay(delays[i]);
575 			s = splnet();
576 			hv_intr();
577 			splx(s);
578 		} else {
579 			tsleep_nsec(wchan, PRIBIO, wchan,
580 			    USEC_TO_NSEC(delays[i]));
581 		}
582 	}
583 	if (status != 0) {
584 		printf("%s: posting vmbus message failed with %d\n",
585 		    sc->sc_dev.dv_xname, status);
586 		if (!(msg->msg_flags & MSGF_NOQUEUE)) {
587 			mtx_enter(&sc->sc_reqlck);
588 			TAILQ_REMOVE(&sc->sc_reqs, msg, msg_entry);
589 			mtx_leave(&sc->sc_reqlck);
590 		}
591 		return (EIO);
592 	}
593 
594 	return (0);
595 }
596 
597 static int
598 hv_reply_done(struct hv_softc *sc, struct hv_msg *msg)
599 {
600 	struct hv_msg *m;
601 
602 	mtx_enter(&sc->sc_rsplck);
603 	TAILQ_FOREACH(m, &sc->sc_rsps, msg_entry) {
604 		if (m == msg) {
605 			mtx_leave(&sc->sc_rsplck);
606 			return (1);
607 		}
608 	}
609 	mtx_leave(&sc->sc_rsplck);
610 	return (0);
611 }
612 
613 int
614 hv_reply(struct hv_softc *sc, struct hv_msg *msg)
615 {
616 	if (msg->msg_flags & MSGF_NOQUEUE)
617 		return (0);
618 
619 	hv_wait(sc, hv_reply_done, msg, msg, "hvreply");
620 
621 	mtx_enter(&sc->sc_rsplck);
622 	TAILQ_REMOVE(&sc->sc_rsps, msg, msg_entry);
623 	mtx_leave(&sc->sc_rsplck);
624 
625 	return (0);
626 }
627 
628 void
629 hv_wait(struct hv_softc *sc, int (*cond)(struct hv_softc *, struct hv_msg *),
630     struct hv_msg *msg, void *wchan, const char *wmsg)
631 {
632 	int s;
633 
634 	KASSERT(cold ? msg->msg_flags & MSGF_NOSLEEP : 1);
635 
636 	while (!cond(sc, msg)) {
637 		if (msg->msg_flags & MSGF_NOSLEEP) {
638 			delay(1000);
639 			s = splnet();
640 			hv_intr();
641 			splx(s);
642 		} else {
643 			tsleep_nsec(wchan, PRIBIO, wmsg ? wmsg : "hvwait",
644 			    USEC_TO_NSEC(1000));
645 		}
646 	}
647 }
648 
649 uint16_t
650 hv_intr_signal(struct hv_softc *sc, void *con)
651 {
652 	uint64_t status;
653 
654 	status = hv_hypercall(sc, HYPERCALL_SIGNAL_EVENT, con, NULL);
655 	return ((uint16_t)status);
656 }
657 
658 void
659 hv_intr(void)
660 {
661 	struct hv_softc *sc = hv_sc;
662 
663 	hv_event_intr(sc);
664 	hv_message_intr(sc);
665 }
666 
667 void
668 hv_event_intr(struct hv_softc *sc)
669 {
670 	struct vmbus_evtflags *evt;
671 	struct cpu_info *ci = curcpu();
672 	int cpu = CPU_INFO_UNIT(ci);
673 	int bit, row, maxrow, chanid;
674 	struct hv_channel *ch;
675 	u_long *revents, pending;
676 
677 	evt = (struct vmbus_evtflags *)sc->sc_siep[cpu] +
678 	    VMBUS_SINT_MESSAGE;
679 	if ((sc->sc_proto == VMBUS_VERSION_WS2008) ||
680 	    (sc->sc_proto == VMBUS_VERSION_WIN7)) {
681 		if (!test_bit(0, &evt->evt_flags[0]))
682 			return;
683 		clear_bit(0, &evt->evt_flags[0]);
684 		maxrow = VMBUS_CHAN_MAX_COMPAT / VMBUS_EVTFLAG_LEN;
685 		/*
686 		 * receive size is 1/2 page and divide that by 4 bytes
687 		 */
688 		revents = sc->sc_revents;
689 	} else {
690 		maxrow = nitems(evt->evt_flags);
691 		/*
692 		 * On Host with Win8 or above, the event page can be
693 		 * checked directly to get the id of the channel
694 		 * that has the pending interrupt.
695 		 */
696 		revents = &evt->evt_flags[0];
697 	}
698 
699 	for (row = 0; row < maxrow; row++) {
700 		if (revents[row] == 0)
701 			continue;
702 		pending = atomic_swap_ulong(&revents[row], 0);
703 		for (bit = 0; pending > 0; pending >>= 1, bit++) {
704 			if ((pending & 1) == 0)
705 				continue;
706 			chanid = (row * LONG_BIT) + bit;
707 			/* vmbus channel protocol message */
708 			if (chanid == 0)
709 				continue;
710 			ch = hv_channel_lookup(sc, chanid);
711 			if (ch == NULL) {
712 				printf("%s: unhandled event on %d\n",
713 				    sc->sc_dev.dv_xname, chanid);
714 				continue;
715 			}
716 			if (ch->ch_state != HV_CHANSTATE_OPENED) {
717 				printf("%s: channel %d is not active\n",
718 				    sc->sc_dev.dv_xname, chanid);
719 				continue;
720 			}
721 			ch->ch_evcnt.ec_count++;
722 			hv_channel_schedule(ch);
723 		}
724 	}
725 }
726 
727 void
728 hv_message_intr(struct hv_softc *sc)
729 {
730 	struct vmbus_message *msg;
731 	struct vmbus_chanmsg_hdr *hdr;
732 	struct cpu_info *ci = curcpu();
733 	int cpu = CPU_INFO_UNIT(ci);
734 
735 	for (;;) {
736 		msg = (struct vmbus_message *)sc->sc_simp[cpu] +
737 		    VMBUS_SINT_MESSAGE;
738 		if (msg->msg_type == VMBUS_MSGTYPE_NONE)
739 			break;
740 
741 		hdr = (struct vmbus_chanmsg_hdr *)msg->msg_data;
742 		if (hdr->chm_type >= VMBUS_CHANMSG_COUNT) {
743 			printf("%s: unhandled message type %u flags %#x\n",
744 			    sc->sc_dev.dv_xname, hdr->chm_type,
745 			    msg->msg_flags);
746 			goto skip;
747 		}
748 		if (hv_msg_dispatch[hdr->chm_type].hmd_handler)
749 			hv_msg_dispatch[hdr->chm_type].hmd_handler(sc, hdr);
750 		else
751 			printf("%s: unhandled message type %u\n",
752 			    sc->sc_dev.dv_xname, hdr->chm_type);
753  skip:
754 		msg->msg_type = VMBUS_MSGTYPE_NONE;
755 		virtio_membar_sync();
756 		if (msg->msg_flags & VMBUS_MSGFLAG_PENDING)
757 			wrmsr(MSR_HV_EOM, 0);
758 	}
759 }
760 
761 void
762 hv_channel_response(struct hv_softc *sc, struct vmbus_chanmsg_hdr *rsphdr)
763 {
764 	struct hv_msg *msg;
765 	struct vmbus_chanmsg_hdr *reqhdr;
766 	int req;
767 
768 	req = hv_msg_dispatch[rsphdr->chm_type].hmd_request;
769 	mtx_enter(&sc->sc_reqlck);
770 	TAILQ_FOREACH(msg, &sc->sc_reqs, msg_entry) {
771 		reqhdr = (struct vmbus_chanmsg_hdr *)&msg->msg_req.hc_data;
772 		if (reqhdr->chm_type == req) {
773 			TAILQ_REMOVE(&sc->sc_reqs, msg, msg_entry);
774 			break;
775 		}
776 	}
777 	mtx_leave(&sc->sc_reqlck);
778 	if (msg != NULL) {
779 		memcpy(msg->msg_rsp, rsphdr, msg->msg_rsplen);
780 		mtx_enter(&sc->sc_rsplck);
781 		TAILQ_INSERT_TAIL(&sc->sc_rsps, msg, msg_entry);
782 		mtx_leave(&sc->sc_rsplck);
783 		wakeup(msg);
784 	}
785 }
786 
787 void
788 hv_channel_offer(struct hv_softc *sc, struct vmbus_chanmsg_hdr *hdr)
789 {
790 	struct hv_offer *co;
791 
792 	co = malloc(sizeof(*co), M_DEVBUF, M_NOWAIT | M_ZERO);
793 	if (co == NULL) {
794 		printf("%s: failed to allocate an offer object\n",
795 		    sc->sc_dev.dv_xname);
796 		return;
797 	}
798 
799 	memcpy(&co->co_chan, hdr, sizeof(co->co_chan));
800 
801 	mtx_enter(&sc->sc_offerlck);
802 	SIMPLEQ_INSERT_TAIL(&sc->sc_offers, co, co_entry);
803 	mtx_leave(&sc->sc_offerlck);
804 }
805 
806 void
807 hv_channel_rescind(struct hv_softc *sc, struct vmbus_chanmsg_hdr *hdr)
808 {
809 	const struct vmbus_chanmsg_chrescind *cmd;
810 
811 	cmd = (const struct vmbus_chanmsg_chrescind *)hdr;
812 	printf("%s: revoking channel %u\n", sc->sc_dev.dv_xname,
813 	    cmd->chm_chanid);
814 }
815 
816 void
817 hv_channel_delivered(struct hv_softc *sc, struct vmbus_chanmsg_hdr *hdr)
818 {
819 	atomic_setbits_int(&sc->sc_flags, HSF_OFFERS_DELIVERED);
820 	wakeup(&sc->sc_offers);
821 }
822 
823 int
824 hv_vmbus_connect(struct hv_softc *sc)
825 {
826 	const uint32_t versions[] = {
827 		VMBUS_VERSION_WIN10,
828 		VMBUS_VERSION_WIN8_1, VMBUS_VERSION_WIN8,
829 		VMBUS_VERSION_WIN7, VMBUS_VERSION_WS2008
830 	};
831 	struct vmbus_chanmsg_connect cmd;
832 	struct vmbus_chanmsg_connect_resp rsp;
833 	paddr_t epa, mpa1, mpa2;
834 	int i;
835 
836 	sc->sc_events = km_alloc(PAGE_SIZE, &kv_any, &kp_zero, &kd_nowait);
837 	if (sc->sc_events == NULL) {
838 		printf(": failed to allocate channel port events page\n");
839 		goto errout;
840 	}
841 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_events, &epa)) {
842 		printf(": channel port events page PA extraction failed\n");
843 		goto errout;
844 	}
845 
846 	sc->sc_wevents = (u_long *)sc->sc_events;
847 	sc->sc_revents = (u_long *)((caddr_t)sc->sc_events + (PAGE_SIZE >> 1));
848 
849 	sc->sc_monitor[0] = km_alloc(PAGE_SIZE, &kv_any, &kp_zero, &kd_nowait);
850 	if (sc->sc_monitor[0] == NULL) {
851 		printf(": failed to allocate monitor page 1\n");
852 		goto errout;
853 	}
854 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_monitor[0], &mpa1)) {
855 		printf(": monitor page 1 PA extraction failed\n");
856 		goto errout;
857 	}
858 
859 	sc->sc_monitor[1] = km_alloc(PAGE_SIZE, &kv_any, &kp_zero, &kd_nowait);
860 	if (sc->sc_monitor[1] == NULL) {
861 		printf(": failed to allocate monitor page 2\n");
862 		goto errout;
863 	}
864 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_monitor[1], &mpa2)) {
865 		printf(": monitor page 2 PA extraction failed\n");
866 		goto errout;
867 	}
868 
869 	memset(&cmd, 0, sizeof(cmd));
870 	cmd.chm_hdr.chm_type = VMBUS_CHANMSG_CONNECT;
871 	cmd.chm_evtflags = (uint64_t)epa;
872 	cmd.chm_mnf1 = (uint64_t)mpa1;
873 	cmd.chm_mnf2 = (uint64_t)mpa2;
874 
875 	memset(&rsp, 0, sizeof(rsp));
876 
877 	for (i = 0; i < nitems(versions); i++) {
878 		cmd.chm_ver = versions[i];
879 		if (hv_cmd(sc, &cmd, sizeof(cmd), &rsp, sizeof(rsp),
880 		    HCF_NOSLEEP)) {
881 			DPRINTF("%s: CONNECT failed\n",
882 			    sc->sc_dev.dv_xname);
883 			goto errout;
884 		}
885 		if (rsp.chm_done) {
886 			sc->sc_flags |= HSF_CONNECTED;
887 			sc->sc_proto = versions[i];
888 			sc->sc_handle = VMBUS_GPADL_START;
889 			break;
890 		}
891 	}
892 	if (i == nitems(versions)) {
893 		printf("%s: failed to negotiate protocol version\n",
894 		    sc->sc_dev.dv_xname);
895 		goto errout;
896 	}
897 
898 	return (0);
899 
900  errout:
901 	if (sc->sc_events) {
902 		km_free(sc->sc_events, PAGE_SIZE, &kv_any, &kp_zero);
903 		sc->sc_events = NULL;
904 		sc->sc_wevents = NULL;
905 		sc->sc_revents = NULL;
906 	}
907 	if (sc->sc_monitor[0]) {
908 		km_free(sc->sc_monitor[0], PAGE_SIZE, &kv_any, &kp_zero);
909 		sc->sc_monitor[0] = NULL;
910 	}
911 	if (sc->sc_monitor[1]) {
912 		km_free(sc->sc_monitor[1], PAGE_SIZE, &kv_any, &kp_zero);
913 		sc->sc_monitor[1] = NULL;
914 	}
915 	return (-1);
916 }
917 
918 #ifdef HYPERV_DEBUG
919 static inline char *
920 guidprint(struct hv_guid *a)
921 {
922 	/* 3     0  5  4 7 6  8 9  10        15 */
923 	/* 33221100-5544-7766-9988-FFEEDDCCBBAA */
924 	static char buf[16 * 2 + 4 + 1];
925 	int i, j = 0;
926 
927 	for (i = 3; i != -1; i -= 1, j += 2)
928 		snprintf(&buf[j], 3, "%02x", (uint8_t)a->data[i]);
929 	buf[j++] = '-';
930 	for (i = 5; i != 3; i -= 1, j += 2)
931 		snprintf(&buf[j], 3, "%02x", (uint8_t)a->data[i]);
932 	buf[j++] = '-';
933 	for (i = 7; i != 5; i -= 1, j += 2)
934 		snprintf(&buf[j], 3, "%02x", (uint8_t)a->data[i]);
935 	buf[j++] = '-';
936 	for (i = 8; i < 10; i += 1, j += 2)
937 		snprintf(&buf[j], 3, "%02x", (uint8_t)a->data[i]);
938 	buf[j++] = '-';
939 	for (i = 10; i < 16; i += 1, j += 2)
940 		snprintf(&buf[j], 3, "%02x", (uint8_t)a->data[i]);
941 	return (&buf[0]);
942 }
943 #endif	/* HYPERV_DEBUG */
944 
945 void
946 hv_guid_sprint(struct hv_guid *guid, char *str, size_t size)
947 {
948 	const struct {
949 		const struct hv_guid	*guid;
950 		const char		*ident;
951 	} map[] = {
952 		{ &hv_guid_network,	"network" },
953 		{ &hv_guid_ide,		"ide" },
954 		{ &hv_guid_scsi,	"scsi" },
955 		{ &hv_guid_shutdown,	"shutdown" },
956 		{ &hv_guid_timesync,	"timesync" },
957 		{ &hv_guid_heartbeat,	"heartbeat" },
958 		{ &hv_guid_kvp,		"kvp" },
959 #ifdef HYPERV_DEBUG
960 		{ &hv_guid_vss,		"vss" },
961 		{ &hv_guid_dynmem,	"dynamic-memory" },
962 		{ &hv_guid_mouse,	"mouse" },
963 		{ &hv_guid_kbd,		"keyboard" },
964 		{ &hv_guid_video,	"video" },
965 		{ &hv_guid_fc,		"fiber-channel" },
966 		{ &hv_guid_fcopy,	"file-copy" },
967 		{ &hv_guid_pcie,	"pcie-passthrough" },
968 		{ &hv_guid_netdir,	"network-direct" },
969 		{ &hv_guid_rdesktop,	"remote-desktop" },
970 		{ &hv_guid_avma1,	"avma-1" },
971 		{ &hv_guid_avma2,	"avma-2" },
972 		{ &hv_guid_avma3,	"avma-3" },
973 		{ &hv_guid_avma4,	"avma-4" },
974 #endif
975 	};
976 	int i;
977 
978 	for (i = 0; i < nitems(map); i++) {
979 		if (memcmp(guid, map[i].guid, sizeof(*guid)) == 0) {
980 			strlcpy(str, map[i].ident, size);
981 			return;
982 		}
983 	}
984 #ifdef HYPERV_DEBUG
985 	strlcpy(str, guidprint(guid), size);
986 #endif
987 }
988 
989 static int
990 hv_channel_scan_done(struct hv_softc *sc, struct hv_msg *msg __unused)
991 {
992 	return (sc->sc_flags & HSF_OFFERS_DELIVERED);
993 }
994 
995 int
996 hv_channel_scan(struct hv_softc *sc)
997 {
998 	struct vmbus_chanmsg_hdr hdr;
999 	struct vmbus_chanmsg_choffer rsp;
1000 	struct hv_offer *co;
1001 
1002 	SIMPLEQ_INIT(&sc->sc_offers);
1003 	mtx_init(&sc->sc_offerlck, IPL_NET);
1004 
1005 	memset(&hdr, 0, sizeof(hdr));
1006 	hdr.chm_type = VMBUS_CHANMSG_CHREQUEST;
1007 
1008 	if (hv_cmd(sc, &hdr, sizeof(hdr), &rsp, sizeof(rsp),
1009 	    HCF_NOSLEEP | HCF_NOREPLY)) {
1010 		DPRINTF("%s: CHREQUEST failed\n", sc->sc_dev.dv_xname);
1011 		return (-1);
1012 	}
1013 
1014 	hv_wait(sc, hv_channel_scan_done, (struct hv_msg *)&hdr,
1015 	    &sc->sc_offers, "hvscan");
1016 
1017 	TAILQ_INIT(&sc->sc_channels);
1018 	mtx_init(&sc->sc_channelck, IPL_NET);
1019 
1020 	mtx_enter(&sc->sc_offerlck);
1021 	while (!SIMPLEQ_EMPTY(&sc->sc_offers)) {
1022 		co = SIMPLEQ_FIRST(&sc->sc_offers);
1023 		SIMPLEQ_REMOVE_HEAD(&sc->sc_offers, co_entry);
1024 		mtx_leave(&sc->sc_offerlck);
1025 
1026 		hv_process_offer(sc, co);
1027 		free(co, M_DEVBUF, sizeof(*co));
1028 
1029 		mtx_enter(&sc->sc_offerlck);
1030 	}
1031 	mtx_leave(&sc->sc_offerlck);
1032 
1033 	return (0);
1034 }
1035 
1036 void
1037 hv_process_offer(struct hv_softc *sc, struct hv_offer *co)
1038 {
1039 	struct hv_channel *ch, *nch;
1040 
1041 	nch = malloc(sizeof(*nch), M_DEVBUF, M_ZERO | M_NOWAIT);
1042 	if (nch == NULL) {
1043 		printf("%s: failed to allocate memory for the channel\n",
1044 		    sc->sc_dev.dv_xname);
1045 		return;
1046 	}
1047 	nch->ch_sc = sc;
1048 	hv_guid_sprint(&co->co_chan.chm_chtype, nch->ch_ident,
1049 	    sizeof(nch->ch_ident));
1050 
1051 	/*
1052 	 * By default we setup state to enable batched reading.
1053 	 * A specific service can choose to disable this prior
1054 	 * to opening the channel.
1055 	 */
1056 	nch->ch_flags |= CHF_BATCHED;
1057 
1058 	KASSERT((((vaddr_t)&nch->ch_monprm) & 0x7) == 0);
1059 	memset(&nch->ch_monprm, 0, sizeof(nch->ch_monprm));
1060 	nch->ch_monprm.mp_connid = VMBUS_CONNID_EVENT;
1061 
1062 	if (sc->sc_proto != VMBUS_VERSION_WS2008)
1063 		nch->ch_monprm.mp_connid = co->co_chan.chm_connid;
1064 
1065 	if (co->co_chan.chm_flags1 & VMBUS_CHOFFER_FLAG1_HASMNF) {
1066 		nch->ch_mgroup = co->co_chan.chm_montrig / VMBUS_MONTRIG_LEN;
1067 		nch->ch_mindex = co->co_chan.chm_montrig % VMBUS_MONTRIG_LEN;
1068 		nch->ch_flags |= CHF_MONITOR;
1069 	}
1070 
1071 	nch->ch_id = co->co_chan.chm_chanid;
1072 
1073 	memcpy(&nch->ch_type, &co->co_chan.chm_chtype, sizeof(ch->ch_type));
1074 	memcpy(&nch->ch_inst, &co->co_chan.chm_chinst, sizeof(ch->ch_inst));
1075 
1076 	mtx_enter(&sc->sc_channelck);
1077 	TAILQ_FOREACH(ch, &sc->sc_channels, ch_entry) {
1078 		if (!memcmp(&ch->ch_type, &nch->ch_type, sizeof(ch->ch_type)) &&
1079 		    !memcmp(&ch->ch_inst, &nch->ch_inst, sizeof(ch->ch_inst)))
1080 			break;
1081 	}
1082 	if (ch != NULL) {
1083 		if (co->co_chan.chm_subidx == 0) {
1084 			printf("%s: unknown offer \"%s\"\n",
1085 			    sc->sc_dev.dv_xname, nch->ch_ident);
1086 			mtx_leave(&sc->sc_channelck);
1087 			free(nch, M_DEVBUF, sizeof(*nch));
1088 			return;
1089 		}
1090 #ifdef HYPERV_DEBUG
1091 		printf("%s: subchannel %u for \"%s\"\n", sc->sc_dev.dv_xname,
1092 		    co->co_chan.chm_subidx, ch->ch_ident);
1093 #endif
1094 		mtx_leave(&sc->sc_channelck);
1095 		free(nch, M_DEVBUF, sizeof(*nch));
1096 		return;
1097 	}
1098 
1099 	nch->ch_state = HV_CHANSTATE_OFFERED;
1100 
1101 	TAILQ_INSERT_TAIL(&sc->sc_channels, nch, ch_entry);
1102 	mtx_leave(&sc->sc_channelck);
1103 
1104 #ifdef HYPERV_DEBUG
1105 	printf("%s: channel %u: \"%s\"", sc->sc_dev.dv_xname, nch->ch_id,
1106 	    nch->ch_ident);
1107 	if (nch->ch_flags & CHF_MONITOR)
1108 		printf(", monitor %u\n", co->co_chan.chm_montrig);
1109 	else
1110 		printf("\n");
1111 #endif
1112 }
1113 
1114 struct hv_channel *
1115 hv_channel_lookup(struct hv_softc *sc, uint32_t relid)
1116 {
1117 	struct hv_channel *ch;
1118 
1119 	TAILQ_FOREACH(ch, &sc->sc_channels, ch_entry) {
1120 		if (ch->ch_id == relid)
1121 			return (ch);
1122 	}
1123 	return (NULL);
1124 }
1125 
1126 int
1127 hv_channel_ring_create(struct hv_channel *ch, uint32_t buflen)
1128 {
1129 	struct hv_softc *sc = ch->ch_sc;
1130 
1131 	buflen = roundup(buflen, PAGE_SIZE) + sizeof(struct vmbus_bufring);
1132 	ch->ch_ring = km_alloc(2 * buflen, &kv_any, &kp_zero, cold ?
1133 	    &kd_nowait : &kd_waitok);
1134 	if (ch->ch_ring == NULL) {
1135 		printf("%s: failed to allocate channel ring\n",
1136 		    sc->sc_dev.dv_xname);
1137 		return (-1);
1138 	}
1139 	ch->ch_ring_size = 2 * buflen;
1140 
1141 	memset(&ch->ch_wrd, 0, sizeof(ch->ch_wrd));
1142 	ch->ch_wrd.rd_ring = (struct vmbus_bufring *)ch->ch_ring;
1143 	ch->ch_wrd.rd_size = buflen;
1144 	ch->ch_wrd.rd_dsize = buflen - sizeof(struct vmbus_bufring);
1145 	mtx_init(&ch->ch_wrd.rd_lock, IPL_NET);
1146 
1147 	memset(&ch->ch_rrd, 0, sizeof(ch->ch_rrd));
1148 	ch->ch_rrd.rd_ring = (struct vmbus_bufring *)((uint8_t *)ch->ch_ring +
1149 	    buflen);
1150 	ch->ch_rrd.rd_size = buflen;
1151 	ch->ch_rrd.rd_dsize = buflen - sizeof(struct vmbus_bufring);
1152 	mtx_init(&ch->ch_rrd.rd_lock, IPL_NET);
1153 
1154 	if (hv_handle_alloc(ch, ch->ch_ring, 2 * buflen, &ch->ch_ring_gpadl)) {
1155 		printf("%s: failed to obtain a PA handle for the ring\n",
1156 		    sc->sc_dev.dv_xname);
1157 		hv_channel_ring_destroy(ch);
1158 		return (-1);
1159 	}
1160 
1161 	return (0);
1162 }
1163 
1164 void
1165 hv_channel_ring_destroy(struct hv_channel *ch)
1166 {
1167 	km_free(ch->ch_ring, ch->ch_ring_size, &kv_any, &kp_zero);
1168 	ch->ch_ring = NULL;
1169 	hv_handle_free(ch, ch->ch_ring_gpadl);
1170 
1171 	memset(&ch->ch_wrd, 0, sizeof(ch->ch_wrd));
1172 	memset(&ch->ch_rrd, 0, sizeof(ch->ch_rrd));
1173 }
1174 
1175 int
1176 hv_channel_open(struct hv_channel *ch, size_t buflen, void *udata,
1177     size_t udatalen, void (*handler)(void *), void *arg)
1178 {
1179 	struct hv_softc *sc = ch->ch_sc;
1180 	struct vmbus_chanmsg_chopen cmd;
1181 	struct vmbus_chanmsg_chopen_resp rsp;
1182 	int rv;
1183 
1184 	if (ch->ch_ring == NULL &&
1185 	    hv_channel_ring_create(ch, buflen)) {
1186 		DPRINTF("%s: failed to create channel ring\n",
1187 		    sc->sc_dev.dv_xname);
1188 		return (-1);
1189 	}
1190 
1191 	memset(&cmd, 0, sizeof(cmd));
1192 	cmd.chm_hdr.chm_type = VMBUS_CHANMSG_CHOPEN;
1193 	cmd.chm_openid = ch->ch_id;
1194 	cmd.chm_chanid = ch->ch_id;
1195 	cmd.chm_gpadl = ch->ch_ring_gpadl;
1196 	cmd.chm_txbr_pgcnt = ch->ch_wrd.rd_size >> PAGE_SHIFT;
1197 	cmd.chm_vcpuid = ch->ch_vcpu;
1198 
1199 	if (udata && udatalen > 0)
1200 		memcpy(cmd.chm_udata, udata, udatalen);
1201 
1202 	memset(&rsp, 0, sizeof(rsp));
1203 
1204 	ch->ch_handler = handler;
1205 	ch->ch_ctx = arg;
1206 
1207 	ch->ch_state = HV_CHANSTATE_OPENED;
1208 
1209 	rv = hv_cmd(sc, &cmd, sizeof(cmd), &rsp, sizeof(rsp),
1210 	    cold ? HCF_NOSLEEP : HCF_SLEEPOK);
1211 	if (rv) {
1212 		hv_channel_ring_destroy(ch);
1213 		DPRINTF("%s: CHOPEN failed with %d\n",
1214 		    sc->sc_dev.dv_xname, rv);
1215 		ch->ch_handler = NULL;
1216 		ch->ch_ctx = NULL;
1217 		ch->ch_state = HV_CHANSTATE_OFFERED;
1218 		return (-1);
1219 	}
1220 
1221 	return (0);
1222 }
1223 
1224 int
1225 hv_channel_close(struct hv_channel *ch)
1226 {
1227 	struct hv_softc *sc = ch->ch_sc;
1228 	struct vmbus_chanmsg_chclose cmd;
1229 	int rv;
1230 
1231 	memset(&cmd, 0, sizeof(cmd));
1232 	cmd.chm_hdr.chm_type = VMBUS_CHANMSG_CHCLOSE;
1233 	cmd.chm_chanid = ch->ch_id;
1234 
1235 	ch->ch_state = HV_CHANSTATE_CLOSING;
1236 	rv = hv_cmd(sc, &cmd, sizeof(cmd), NULL, 0, HCF_NOREPLY);
1237 	if (rv) {
1238 		DPRINTF("%s: CHCLOSE failed with %d\n",
1239 		    sc->sc_dev.dv_xname, rv);
1240 		return (-1);
1241 	}
1242 	ch->ch_state = HV_CHANSTATE_CLOSED;
1243 	hv_channel_ring_destroy(ch);
1244 	return (0);
1245 }
1246 
1247 static inline void
1248 hv_channel_setevent(struct hv_softc *sc, struct hv_channel *ch)
1249 {
1250 	struct vmbus_mon_trig *mtg;
1251 
1252 	/* Each uint32_t represents 32 channels */
1253 	set_bit(ch->ch_id, sc->sc_wevents);
1254 	if (ch->ch_flags & CHF_MONITOR) {
1255 		mtg = &sc->sc_monitor[1]->mnf_trigs[ch->ch_mgroup];
1256 		set_bit(ch->ch_mindex, &mtg->mt_pending);
1257 	} else
1258 		hv_intr_signal(sc, &ch->ch_monprm);
1259 }
1260 
1261 void
1262 hv_channel_intr(void *arg)
1263 {
1264 	struct hv_channel *ch = arg;
1265 
1266 	if (hv_channel_ready(ch))
1267 		ch->ch_handler(ch->ch_ctx);
1268 
1269 	if (hv_channel_unpause(ch) == 0)
1270 		return;
1271 
1272 	hv_channel_pause(ch);
1273 	hv_channel_schedule(ch);
1274 }
1275 
1276 int
1277 hv_channel_setdeferred(struct hv_channel *ch, const char *name)
1278 {
1279 	ch->ch_taskq = taskq_create(name, 1, IPL_NET, TASKQ_MPSAFE);
1280 	if (ch->ch_taskq == NULL)
1281 		return (-1);
1282 	task_set(&ch->ch_task, hv_channel_intr, ch);
1283 	return (0);
1284 }
1285 
1286 void
1287 hv_channel_schedule(struct hv_channel *ch)
1288 {
1289 	if (ch->ch_handler) {
1290 		if (!cold && (ch->ch_flags & CHF_BATCHED)) {
1291 			hv_channel_pause(ch);
1292 			task_add(ch->ch_taskq, &ch->ch_task);
1293 		} else
1294 			ch->ch_handler(ch->ch_ctx);
1295 	}
1296 }
1297 
1298 static inline void
1299 hv_ring_put(struct hv_ring_data *wrd, uint8_t *data, uint32_t datalen)
1300 {
1301 	int left = MIN(datalen, wrd->rd_dsize - wrd->rd_prod);
1302 
1303 	memcpy(&wrd->rd_ring->br_data[wrd->rd_prod], data, left);
1304 	memcpy(&wrd->rd_ring->br_data[0], data + left, datalen - left);
1305 	wrd->rd_prod += datalen;
1306 	if (wrd->rd_prod >= wrd->rd_dsize)
1307 		wrd->rd_prod -= wrd->rd_dsize;
1308 }
1309 
1310 static inline void
1311 hv_ring_get(struct hv_ring_data *rrd, uint8_t *data, uint32_t datalen,
1312     int peek)
1313 {
1314 	int left = MIN(datalen, rrd->rd_dsize - rrd->rd_cons);
1315 
1316 	memcpy(data, &rrd->rd_ring->br_data[rrd->rd_cons], left);
1317 	memcpy(data + left, &rrd->rd_ring->br_data[0], datalen - left);
1318 	if (!peek) {
1319 		rrd->rd_cons += datalen;
1320 		if (rrd->rd_cons >= rrd->rd_dsize)
1321 			rrd->rd_cons -= rrd->rd_dsize;
1322 	}
1323 }
1324 
1325 static inline void
1326 hv_ring_avail(struct hv_ring_data *rd, uint32_t *towrite, uint32_t *toread)
1327 {
1328 	uint32_t ridx = rd->rd_ring->br_rindex;
1329 	uint32_t widx = rd->rd_ring->br_windex;
1330 	uint32_t r, w;
1331 
1332 	if (widx >= ridx)
1333 		w = rd->rd_dsize - (widx - ridx);
1334 	else
1335 		w = ridx - widx;
1336 	r = rd->rd_dsize - w;
1337 	if (towrite)
1338 		*towrite = w;
1339 	if (toread)
1340 		*toread = r;
1341 }
1342 
1343 int
1344 hv_ring_write(struct hv_ring_data *wrd, struct iovec *iov, int iov_cnt,
1345     int *needsig)
1346 {
1347 	uint64_t indices = 0;
1348 	uint32_t avail, oprod, datalen = sizeof(indices);
1349 	int i;
1350 
1351 	for (i = 0; i < iov_cnt; i++)
1352 		datalen += iov[i].iov_len;
1353 
1354 	KASSERT(datalen <= wrd->rd_dsize);
1355 
1356 	hv_ring_avail(wrd, &avail, NULL);
1357 	if (avail <= datalen) {
1358 		DPRINTF("%s: avail %u datalen %u\n", __func__, avail, datalen);
1359 		return (EAGAIN);
1360 	}
1361 
1362 	oprod = wrd->rd_prod;
1363 
1364 	for (i = 0; i < iov_cnt; i++)
1365 		hv_ring_put(wrd, iov[i].iov_base, iov[i].iov_len);
1366 
1367 	indices = (uint64_t)oprod << 32;
1368 	hv_ring_put(wrd, (uint8_t *)&indices, sizeof(indices));
1369 
1370 	virtio_membar_sync();
1371 	wrd->rd_ring->br_windex = wrd->rd_prod;
1372 	virtio_membar_sync();
1373 
1374 	/* Signal when the ring transitions from being empty to non-empty */
1375 	if (wrd->rd_ring->br_imask == 0 &&
1376 	    wrd->rd_ring->br_rindex == oprod)
1377 		*needsig = 1;
1378 	else
1379 		*needsig = 0;
1380 
1381 	return (0);
1382 }
1383 
1384 int
1385 hv_channel_send(struct hv_channel *ch, void *data, uint32_t datalen,
1386     uint64_t rid, int type, uint32_t flags)
1387 {
1388 	struct hv_softc *sc = ch->ch_sc;
1389 	struct vmbus_chanpkt cp;
1390 	struct iovec iov[3];
1391 	uint32_t pktlen, pktlen_aligned;
1392 	uint64_t zeropad = 0;
1393 	int rv, needsig = 0;
1394 
1395 	pktlen = sizeof(cp) + datalen;
1396 	pktlen_aligned = roundup(pktlen, sizeof(uint64_t));
1397 
1398 	cp.cp_hdr.cph_type = type;
1399 	cp.cp_hdr.cph_flags = flags;
1400 	VMBUS_CHANPKT_SETLEN(cp.cp_hdr.cph_hlen, sizeof(cp));
1401 	VMBUS_CHANPKT_SETLEN(cp.cp_hdr.cph_tlen, pktlen_aligned);
1402 	cp.cp_hdr.cph_tid = rid;
1403 
1404 	iov[0].iov_base = &cp;
1405 	iov[0].iov_len = sizeof(cp);
1406 
1407 	iov[1].iov_base = data;
1408 	iov[1].iov_len = datalen;
1409 
1410 	iov[2].iov_base = &zeropad;
1411 	iov[2].iov_len = pktlen_aligned - pktlen;
1412 
1413 	mtx_enter(&ch->ch_wrd.rd_lock);
1414 	rv = hv_ring_write(&ch->ch_wrd, iov, 3, &needsig);
1415 	mtx_leave(&ch->ch_wrd.rd_lock);
1416 	if (rv == 0 && needsig)
1417 		hv_channel_setevent(sc, ch);
1418 
1419 	return (rv);
1420 }
1421 
1422 int
1423 hv_channel_send_sgl(struct hv_channel *ch, struct vmbus_gpa *sgl,
1424     uint32_t nsge, void *data, uint32_t datalen, uint64_t rid)
1425 {
1426 	struct hv_softc *sc = ch->ch_sc;
1427 	struct vmbus_chanpkt_sglist cp;
1428 	struct iovec iov[4];
1429 	uint32_t buflen, pktlen, pktlen_aligned;
1430 	uint64_t zeropad = 0;
1431 	int rv, needsig = 0;
1432 
1433 	buflen = sizeof(struct vmbus_gpa) * nsge;
1434 	pktlen = sizeof(cp) + datalen + buflen;
1435 	pktlen_aligned = roundup(pktlen, sizeof(uint64_t));
1436 
1437 	cp.cp_hdr.cph_type = VMBUS_CHANPKT_TYPE_GPA;
1438 	cp.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
1439 	VMBUS_CHANPKT_SETLEN(cp.cp_hdr.cph_hlen, sizeof(cp) + buflen);
1440 	VMBUS_CHANPKT_SETLEN(cp.cp_hdr.cph_tlen, pktlen_aligned);
1441 	cp.cp_hdr.cph_tid = rid;
1442 	cp.cp_gpa_cnt = nsge;
1443 	cp.cp_rsvd = 0;
1444 
1445 	iov[0].iov_base = &cp;
1446 	iov[0].iov_len = sizeof(cp);
1447 
1448 	iov[1].iov_base = sgl;
1449 	iov[1].iov_len = buflen;
1450 
1451 	iov[2].iov_base = data;
1452 	iov[2].iov_len = datalen;
1453 
1454 	iov[3].iov_base = &zeropad;
1455 	iov[3].iov_len = pktlen_aligned - pktlen;
1456 
1457 	mtx_enter(&ch->ch_wrd.rd_lock);
1458 	rv = hv_ring_write(&ch->ch_wrd, iov, 4, &needsig);
1459 	mtx_leave(&ch->ch_wrd.rd_lock);
1460 	if (rv == 0 && needsig)
1461 		hv_channel_setevent(sc, ch);
1462 
1463 	return (rv);
1464 }
1465 
1466 int
1467 hv_channel_send_prpl(struct hv_channel *ch, struct vmbus_gpa_range *prpl,
1468     uint32_t nprp, void *data, uint32_t datalen, uint64_t rid)
1469 {
1470 	struct hv_softc *sc = ch->ch_sc;
1471 	struct vmbus_chanpkt_prplist cp;
1472 	struct iovec iov[4];
1473 	uint32_t buflen, pktlen, pktlen_aligned;
1474 	uint64_t zeropad = 0;
1475 	int rv, needsig = 0;
1476 
1477 	buflen = sizeof(struct vmbus_gpa_range) * (nprp + 1);
1478 	pktlen = sizeof(cp) + datalen + buflen;
1479 	pktlen_aligned = roundup(pktlen, sizeof(uint64_t));
1480 
1481 	cp.cp_hdr.cph_type = VMBUS_CHANPKT_TYPE_GPA;
1482 	cp.cp_hdr.cph_flags = VMBUS_CHANPKT_FLAG_RC;
1483 	VMBUS_CHANPKT_SETLEN(cp.cp_hdr.cph_hlen, sizeof(cp) + buflen);
1484 	VMBUS_CHANPKT_SETLEN(cp.cp_hdr.cph_tlen, pktlen_aligned);
1485 	cp.cp_hdr.cph_tid = rid;
1486 	cp.cp_range_cnt = 1;
1487 	cp.cp_rsvd = 0;
1488 
1489 	iov[0].iov_base = &cp;
1490 	iov[0].iov_len = sizeof(cp);
1491 
1492 	iov[1].iov_base = prpl;
1493 	iov[1].iov_len = buflen;
1494 
1495 	iov[2].iov_base = data;
1496 	iov[2].iov_len = datalen;
1497 
1498 	iov[3].iov_base = &zeropad;
1499 	iov[3].iov_len = pktlen_aligned - pktlen;
1500 
1501 	mtx_enter(&ch->ch_wrd.rd_lock);
1502 	rv = hv_ring_write(&ch->ch_wrd, iov, 4, &needsig);
1503 	mtx_leave(&ch->ch_wrd.rd_lock);
1504 	if (rv == 0 && needsig)
1505 		hv_channel_setevent(sc, ch);
1506 
1507 	return (rv);
1508 }
1509 
1510 int
1511 hv_ring_peek(struct hv_ring_data *rrd, void *data, uint32_t datalen)
1512 {
1513 	uint32_t avail;
1514 
1515 	KASSERT(datalen <= rrd->rd_dsize);
1516 
1517 	hv_ring_avail(rrd, NULL, &avail);
1518 	if (avail < datalen)
1519 		return (EAGAIN);
1520 
1521 	hv_ring_get(rrd, (uint8_t *)data, datalen, 1);
1522 	return (0);
1523 }
1524 
1525 int
1526 hv_ring_read(struct hv_ring_data *rrd, void *data, uint32_t datalen,
1527     uint32_t offset)
1528 {
1529 	uint64_t indices;
1530 	uint32_t avail;
1531 
1532 	KASSERT(datalen <= rrd->rd_dsize);
1533 
1534 	hv_ring_avail(rrd, NULL, &avail);
1535 	if (avail < datalen) {
1536 		DPRINTF("%s: avail %u datalen %u\n", __func__, avail, datalen);
1537 		return (EAGAIN);
1538 	}
1539 
1540 	if (offset) {
1541 		rrd->rd_cons += offset;
1542 		if (rrd->rd_cons >= rrd->rd_dsize)
1543 			rrd->rd_cons -= rrd->rd_dsize;
1544 	}
1545 
1546 	hv_ring_get(rrd, (uint8_t *)data, datalen, 0);
1547 	hv_ring_get(rrd, (uint8_t *)&indices, sizeof(indices), 0);
1548 
1549 	virtio_membar_sync();
1550 	rrd->rd_ring->br_rindex = rrd->rd_cons;
1551 
1552 	return (0);
1553 }
1554 
1555 int
1556 hv_channel_recv(struct hv_channel *ch, void *data, uint32_t datalen,
1557     uint32_t *rlen, uint64_t *rid, int raw)
1558 {
1559 	struct vmbus_chanpkt_hdr cph;
1560 	uint32_t offset, pktlen;
1561 	int rv;
1562 
1563 	*rlen = 0;
1564 
1565 	mtx_enter(&ch->ch_rrd.rd_lock);
1566 
1567 	if ((rv = hv_ring_peek(&ch->ch_rrd, &cph, sizeof(cph))) != 0) {
1568 		mtx_leave(&ch->ch_rrd.rd_lock);
1569 		return (rv);
1570 	}
1571 
1572 	offset = raw ? 0 : VMBUS_CHANPKT_GETLEN(cph.cph_hlen);
1573 	pktlen = VMBUS_CHANPKT_GETLEN(cph.cph_tlen) - offset;
1574 	if (pktlen > datalen) {
1575 		mtx_leave(&ch->ch_rrd.rd_lock);
1576 		printf("%s: pktlen %u datalen %u\n", __func__, pktlen, datalen);
1577 		return (EINVAL);
1578 	}
1579 
1580 	rv = hv_ring_read(&ch->ch_rrd, data, pktlen, offset);
1581 	if (rv == 0) {
1582 		*rlen = pktlen;
1583 		*rid = cph.cph_tid;
1584 	}
1585 
1586 	mtx_leave(&ch->ch_rrd.rd_lock);
1587 
1588 	return (rv);
1589 }
1590 
1591 static inline void
1592 hv_ring_mask(struct hv_ring_data *rd)
1593 {
1594 	virtio_membar_sync();
1595 	rd->rd_ring->br_imask = 1;
1596 	virtio_membar_sync();
1597 }
1598 
1599 static inline void
1600 hv_ring_unmask(struct hv_ring_data *rd)
1601 {
1602 	virtio_membar_sync();
1603 	rd->rd_ring->br_imask = 0;
1604 	virtio_membar_sync();
1605 }
1606 
1607 void
1608 hv_channel_pause(struct hv_channel *ch)
1609 {
1610 	hv_ring_mask(&ch->ch_rrd);
1611 }
1612 
1613 uint
1614 hv_channel_unpause(struct hv_channel *ch)
1615 {
1616 	uint32_t avail;
1617 
1618 	hv_ring_unmask(&ch->ch_rrd);
1619 	hv_ring_avail(&ch->ch_rrd, NULL, &avail);
1620 
1621 	return (avail);
1622 }
1623 
1624 uint
1625 hv_channel_ready(struct hv_channel *ch)
1626 {
1627 	uint32_t avail;
1628 
1629 	hv_ring_avail(&ch->ch_rrd, NULL, &avail);
1630 
1631 	return (avail);
1632 }
1633 
1634 /* How many PFNs can be referenced by the header */
1635 #define HV_NPFNHDR	((VMBUS_MSG_DSIZE_MAX -	\
1636 	  sizeof(struct vmbus_chanmsg_gpadl_conn)) / sizeof(uint64_t))
1637 
1638 /* How many PFNs can be referenced by the body */
1639 #define HV_NPFNBODY	((VMBUS_MSG_DSIZE_MAX -	\
1640 	  sizeof(struct vmbus_chanmsg_gpadl_subconn)) / sizeof(uint64_t))
1641 
1642 int
1643 hv_handle_alloc(struct hv_channel *ch, void *buffer, uint32_t buflen,
1644     uint32_t *handle)
1645 {
1646 	struct hv_softc *sc = ch->ch_sc;
1647 	struct vmbus_chanmsg_gpadl_conn *hdr;
1648 	struct vmbus_chanmsg_gpadl_subconn *cmd;
1649 	struct vmbus_chanmsg_gpadl_connresp rsp;
1650 	struct hv_msg *msg;
1651 	int i, j, last, left, rv;
1652 	int bodylen = 0, ncmds = 0, pfn = 0;
1653 	int waitflag = cold ? M_NOWAIT : M_WAITOK;
1654 	uint64_t *frames;
1655 	paddr_t pa;
1656 	caddr_t body;
1657 	/* Total number of pages to reference */
1658 	int total = atop(buflen);
1659 	/* Number of pages that will fit the header */
1660 	int inhdr = MIN(total, HV_NPFNHDR);
1661 
1662 	KASSERT((buflen & (PAGE_SIZE - 1)) == 0);
1663 
1664 	if ((msg = malloc(sizeof(*msg), M_DEVBUF, M_ZERO | waitflag)) == NULL)
1665 		return (ENOMEM);
1666 
1667 	/* Prepare array of frame addresses */
1668 	if ((frames = mallocarray(total, sizeof(*frames), M_DEVBUF, M_ZERO |
1669 	    waitflag)) == NULL) {
1670 		free(msg, M_DEVBUF, sizeof(*msg));
1671 		return (ENOMEM);
1672 	}
1673 	for (i = 0; i < total; i++) {
1674 		if (!pmap_extract(pmap_kernel(), (vaddr_t)buffer +
1675 		    PAGE_SIZE * i, &pa)) {
1676 			free(msg, M_DEVBUF, sizeof(*msg));
1677 			free(frames, M_DEVBUF, total * sizeof(*frames));
1678 			return (EFAULT);
1679 		}
1680 		frames[i] = atop(pa);
1681 	}
1682 
1683 	msg->msg_req.hc_dsize = sizeof(struct vmbus_chanmsg_gpadl_conn) +
1684 	    inhdr * sizeof(uint64_t);
1685 	hdr = (struct vmbus_chanmsg_gpadl_conn *)msg->msg_req.hc_data;
1686 	msg->msg_rsp = &rsp;
1687 	msg->msg_rsplen = sizeof(rsp);
1688 	if (waitflag == M_NOWAIT)
1689 		msg->msg_flags = MSGF_NOSLEEP;
1690 
1691 	left = total - inhdr;
1692 
1693 	/* Allocate additional gpadl_body structures if required */
1694 	if (left > 0) {
1695 		ncmds = MAX(1, left / HV_NPFNBODY + left % HV_NPFNBODY);
1696 		bodylen = ncmds * VMBUS_MSG_DSIZE_MAX;
1697 		body = malloc(bodylen, M_DEVBUF, M_ZERO | waitflag);
1698 		if (body == NULL) {
1699 			free(msg, M_DEVBUF, sizeof(*msg));
1700 			free(frames, M_DEVBUF, atop(buflen) * sizeof(*frames));
1701 			return (ENOMEM);
1702 		}
1703 	}
1704 
1705 	*handle = atomic_inc_int_nv(&sc->sc_handle);
1706 
1707 	hdr->chm_hdr.chm_type = VMBUS_CHANMSG_GPADL_CONN;
1708 	hdr->chm_chanid = ch->ch_id;
1709 	hdr->chm_gpadl = *handle;
1710 
1711 	/* Single range for a contiguous buffer */
1712 	hdr->chm_range_cnt = 1;
1713 	hdr->chm_range_len = sizeof(struct vmbus_gpa_range) + total *
1714 	    sizeof(uint64_t);
1715 	hdr->chm_range.gpa_ofs = 0;
1716 	hdr->chm_range.gpa_len = buflen;
1717 
1718 	/* Fit as many pages as possible into the header */
1719 	for (i = 0; i < inhdr; i++)
1720 		hdr->chm_range.gpa_page[i] = frames[pfn++];
1721 
1722 	for (i = 0; i < ncmds; i++) {
1723 		cmd = (struct vmbus_chanmsg_gpadl_subconn *)(body +
1724 		    VMBUS_MSG_DSIZE_MAX * i);
1725 		cmd->chm_hdr.chm_type = VMBUS_CHANMSG_GPADL_SUBCONN;
1726 		cmd->chm_gpadl = *handle;
1727 		last = MIN(left, HV_NPFNBODY);
1728 		for (j = 0; j < last; j++)
1729 			cmd->chm_gpa_page[j] = frames[pfn++];
1730 		left -= last;
1731 	}
1732 
1733 	rv = hv_start(sc, msg);
1734 	if (rv != 0) {
1735 		DPRINTF("%s: GPADL_CONN failed\n", sc->sc_dev.dv_xname);
1736 		goto out;
1737 	}
1738 	for (i = 0; i < ncmds; i++) {
1739 		int cmdlen = sizeof(*cmd);
1740 		cmd = (struct vmbus_chanmsg_gpadl_subconn *)(body +
1741 		    VMBUS_MSG_DSIZE_MAX * i);
1742 		/* Last element can be short */
1743 		if (i == ncmds - 1)
1744 			cmdlen += last * sizeof(uint64_t);
1745 		else
1746 			cmdlen += HV_NPFNBODY * sizeof(uint64_t);
1747 		rv = hv_cmd(sc, cmd, cmdlen, NULL, 0, waitflag | HCF_NOREPLY);
1748 		if (rv != 0) {
1749 			DPRINTF("%s: GPADL_SUBCONN (iteration %d/%d) failed "
1750 			    "with %d\n", sc->sc_dev.dv_xname, i, ncmds, rv);
1751 			goto out;
1752 		}
1753 	}
1754 	rv = hv_reply(sc, msg);
1755 	if (rv != 0)
1756 		DPRINTF("%s: GPADL allocation failed with %d\n",
1757 		    sc->sc_dev.dv_xname, rv);
1758 
1759  out:
1760 	free(msg, M_DEVBUF, sizeof(*msg));
1761 	free(frames, M_DEVBUF, total * sizeof(*frames));
1762 	if (bodylen > 0)
1763 		free(body, M_DEVBUF, bodylen);
1764 	if (rv != 0)
1765 		return (rv);
1766 
1767 	KASSERT(*handle == rsp.chm_gpadl);
1768 
1769 	return (0);
1770 }
1771 
1772 void
1773 hv_handle_free(struct hv_channel *ch, uint32_t handle)
1774 {
1775 	struct hv_softc *sc = ch->ch_sc;
1776 	struct vmbus_chanmsg_gpadl_disconn cmd;
1777 	struct vmbus_chanmsg_gpadl_disconn rsp;
1778 	int rv;
1779 
1780 	memset(&cmd, 0, sizeof(cmd));
1781 	cmd.chm_hdr.chm_type = VMBUS_CHANMSG_GPADL_DISCONN;
1782 	cmd.chm_chanid = ch->ch_id;
1783 	cmd.chm_gpadl = handle;
1784 
1785 	rv = hv_cmd(sc, &cmd, sizeof(cmd), &rsp, sizeof(rsp), cold ?
1786 	    HCF_NOSLEEP : 0);
1787 	if (rv)
1788 		DPRINTF("%s: GPADL_DISCONN failed with %d\n",
1789 		    sc->sc_dev.dv_xname, rv);
1790 }
1791 
1792 static int
1793 hv_attach_print(void *aux, const char *name)
1794 {
1795 	struct hv_attach_args *aa = aux;
1796 
1797 	if (name)
1798 		printf("\"%s\" at %s", aa->aa_ident, name);
1799 
1800 	return (UNCONF);
1801 }
1802 
1803 int
1804 hv_attach_devices(struct hv_softc *sc)
1805 {
1806 	struct hv_dev *dv;
1807 	struct hv_channel *ch;
1808 
1809 	SLIST_INIT(&sc->sc_devs);
1810 	mtx_init(&sc->sc_devlck, IPL_NET);
1811 
1812 	TAILQ_FOREACH(ch, &sc->sc_channels, ch_entry) {
1813 		if (ch->ch_state != HV_CHANSTATE_OFFERED)
1814 			continue;
1815 		if (!(ch->ch_flags & CHF_MONITOR))
1816 			continue;
1817 		dv = malloc(sizeof(*dv), M_DEVBUF, M_ZERO | M_NOWAIT);
1818 		if (dv == NULL) {
1819 			printf("%s: failed to allocate device object\n",
1820 			    sc->sc_dev.dv_xname);
1821 			return (-1);
1822 		}
1823 		dv->dv_aa.aa_parent = sc;
1824 		dv->dv_aa.aa_type = &ch->ch_type;
1825 		dv->dv_aa.aa_inst = &ch->ch_inst;
1826 		dv->dv_aa.aa_ident = ch->ch_ident;
1827 		dv->dv_aa.aa_chan = ch;
1828 		dv->dv_aa.aa_dmat = sc->sc_dmat;
1829 		mtx_enter(&sc->sc_devlck);
1830 		SLIST_INSERT_HEAD(&sc->sc_devs, dv, dv_entry);
1831 		mtx_leave(&sc->sc_devlck);
1832 		config_found((struct device *)sc, &dv->dv_aa, hv_attach_print);
1833 	}
1834 	return (0);
1835 }
1836 
1837 void
1838 hv_evcount_attach(struct hv_channel *ch, const char *name)
1839 {
1840 	struct hv_softc *sc = ch->ch_sc;
1841 
1842 	evcount_attach(&ch->ch_evcnt, name, &sc->sc_idtvec);
1843 }
1844