xref: /openbsd-src/sys/dev/pv/xen.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: xen.c,v 1.95 2020/02/13 15:39:02 mikeb Exp $	*/
2 
3 /*
4  * Copyright (c) 2015, 2016, 2017 Mike Belopuhov
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/param.h>
20 
21 /* Xen requires locked atomic operations */
22 #ifndef MULTIPROCESSOR
23 #define _XENMPATOMICS
24 #define MULTIPROCESSOR
25 #endif
26 #include <sys/atomic.h>
27 #ifdef _XENMPATOMICS
28 #undef MULTIPROCESSOR
29 #undef _XENMPATOMICS
30 #endif
31 
32 #include <sys/systm.h>
33 #include <sys/proc.h>
34 #include <sys/signal.h>
35 #include <sys/signalvar.h>
36 #include <sys/refcnt.h>
37 #include <sys/malloc.h>
38 #include <sys/kernel.h>
39 #include <sys/stdint.h>
40 #include <sys/device.h>
41 #include <sys/task.h>
42 #include <sys/syslog.h>
43 
44 #include <machine/bus.h>
45 #include <machine/cpu.h>
46 #include <machine/cpufunc.h>
47 
48 #include <uvm/uvm_extern.h>
49 
50 #include <machine/i82489var.h>
51 
52 #include <dev/rndvar.h>
53 
54 #include <dev/pv/pvvar.h>
55 #include <dev/pv/pvreg.h>
56 #include <dev/pv/xenreg.h>
57 #include <dev/pv/xenvar.h>
58 
59 /* #define XEN_DEBUG */
60 
61 #ifdef XEN_DEBUG
62 #define DPRINTF(x...)		printf(x)
63 #else
64 #define DPRINTF(x...)
65 #endif
66 
67 struct xen_softc *xen_sc;
68 
69 int	xen_init_hypercall(struct xen_softc *);
70 int	xen_getfeatures(struct xen_softc *);
71 int	xen_init_info_page(struct xen_softc *);
72 int	xen_init_cbvec(struct xen_softc *);
73 int	xen_init_interrupts(struct xen_softc *);
74 void	xen_intr_dispatch(void *);
75 int	xen_init_grant_tables(struct xen_softc *);
76 struct xen_gntent *
77 	xen_grant_table_grow(struct xen_softc *);
78 int	xen_grant_table_alloc(struct xen_softc *, grant_ref_t *);
79 void	xen_grant_table_free(struct xen_softc *, grant_ref_t);
80 void	xen_grant_table_enter(struct xen_softc *, grant_ref_t, paddr_t,
81 	    int, int);
82 void	xen_grant_table_remove(struct xen_softc *, grant_ref_t);
83 void	xen_disable_emulated_devices(struct xen_softc *);
84 
85 int 	xen_match(struct device *, void *, void *);
86 void	xen_attach(struct device *, struct device *, void *);
87 void	xen_deferred(struct device *);
88 void	xen_control(void *);
89 void	xen_hotplug(void *);
90 void	xen_resume(struct device *);
91 int	xen_activate(struct device *, int);
92 int	xen_attach_device(struct xen_softc *, struct xen_devlist *,
93 	    const char *, const char *);
94 int	xen_probe_devices(struct xen_softc *);
95 
96 int	xen_bus_dmamap_create(bus_dma_tag_t, bus_size_t, int, bus_size_t,
97 	    bus_size_t, int, bus_dmamap_t *);
98 void	xen_bus_dmamap_destroy(bus_dma_tag_t, bus_dmamap_t);
99 int	xen_bus_dmamap_load(bus_dma_tag_t, bus_dmamap_t, void *, bus_size_t,
100 	    struct proc *, int);
101 int	xen_bus_dmamap_load_mbuf(bus_dma_tag_t, bus_dmamap_t, struct mbuf *,
102 	    int);
103 void	xen_bus_dmamap_unload(bus_dma_tag_t, bus_dmamap_t);
104 void	xen_bus_dmamap_sync(bus_dma_tag_t, bus_dmamap_t, bus_addr_t,
105 	    bus_size_t, int);
106 
107 int	xs_attach(struct xen_softc *);
108 
109 struct cfdriver xen_cd = {
110 	NULL, "xen", DV_DULL
111 };
112 
113 const struct cfattach xen_ca = {
114 	sizeof(struct xen_softc), xen_match, xen_attach, NULL, xen_activate
115 };
116 
117 struct bus_dma_tag xen_bus_dma_tag = {
118 	NULL,
119 	xen_bus_dmamap_create,
120 	xen_bus_dmamap_destroy,
121 	xen_bus_dmamap_load,
122 	xen_bus_dmamap_load_mbuf,
123 	NULL,
124 	NULL,
125 	xen_bus_dmamap_unload,
126 	xen_bus_dmamap_sync,
127 	_bus_dmamem_alloc,
128 	NULL,
129 	_bus_dmamem_free,
130 	_bus_dmamem_map,
131 	_bus_dmamem_unmap,
132 	NULL,
133 };
134 
135 int
136 xen_match(struct device *parent, void *match, void *aux)
137 {
138 	struct pv_attach_args *pva = aux;
139 	struct pvbus_hv *hv = &pva->pva_hv[PVBUS_XEN];
140 
141 	if (hv->hv_base == 0)
142 		return (0);
143 
144 	return (1);
145 }
146 
147 void
148 xen_attach(struct device *parent, struct device *self, void *aux)
149 {
150 	struct pv_attach_args *pva = (struct pv_attach_args *)aux;
151 	struct pvbus_hv *hv = &pva->pva_hv[PVBUS_XEN];
152 	struct xen_softc *sc = (struct xen_softc *)self;
153 
154 	sc->sc_base = hv->hv_base;
155 	sc->sc_dmat = pva->pva_dmat;
156 
157 	if (xen_init_hypercall(sc))
158 		return;
159 
160 	/* Wire it up to the global */
161 	xen_sc = sc;
162 
163 	if (xen_getfeatures(sc))
164 		return;
165 
166 	if (xen_init_info_page(sc))
167 		return;
168 
169 	xen_init_cbvec(sc);
170 
171 	if (xen_init_interrupts(sc))
172 		return;
173 
174 	if (xen_init_grant_tables(sc))
175 		return;
176 
177 	if (xs_attach(sc))
178 		return;
179 
180 	xen_probe_devices(sc);
181 
182 	/* pvbus(4) key/value interface */
183 	hv->hv_kvop = xs_kvop;
184 	hv->hv_arg = sc;
185 
186 	xen_disable_emulated_devices(sc);
187 
188 	config_mountroot(self, xen_deferred);
189 }
190 
191 void
192 xen_deferred(struct device *self)
193 {
194 	struct xen_softc *sc = (struct xen_softc *)self;
195 
196 	if (!(sc->sc_flags & XSF_CBVEC)) {
197 		DPRINTF("%s: callback vector hasn't been established\n",
198 		    sc->sc_dev.dv_xname);
199 		return;
200 	}
201 
202 	xen_intr_enable();
203 
204 	if (xs_watch(sc, "control", "shutdown", &sc->sc_ctltsk,
205 	    xen_control, sc))
206 		printf("%s: failed to setup shutdown control watch\n",
207 		    sc->sc_dev.dv_xname);
208 }
209 
210 void
211 xen_control(void *arg)
212 {
213 	struct xen_softc *sc = arg;
214 	struct xs_transaction xst;
215 	char action[128];
216 	int error;
217 
218 	memset(&xst, 0, sizeof(xst));
219 	xst.xst_id = 0;
220 	xst.xst_cookie = sc->sc_xs;
221 
222 	error = xs_getprop(sc, "control", "shutdown", action, sizeof(action));
223 	if (error) {
224 		if (error != ENOENT)
225 			printf("%s: failed to process control event\n",
226 			    sc->sc_dev.dv_xname);
227 		return;
228 	}
229 
230 	if (strlen(action) == 0)
231 		return;
232 
233 	/* Acknowledge the event */
234 	xs_setprop(sc, "control", "shutdown", "", 0);
235 
236 	if (strcmp(action, "halt") == 0 || strcmp(action, "poweroff") == 0) {
237 		pvbus_shutdown(&sc->sc_dev);
238 	} else if (strcmp(action, "reboot") == 0) {
239 		pvbus_reboot(&sc->sc_dev);
240 	} else if (strcmp(action, "crash") == 0) {
241 		panic("xen told us to do this");
242 	} else if (strcmp(action, "suspend") == 0) {
243 		/* Not implemented yet */
244 	} else {
245 		printf("%s: unknown shutdown event \"%s\"\n",
246 		    sc->sc_dev.dv_xname, action);
247 	}
248 }
249 
250 void
251 xen_resume(struct device *self)
252 {
253 }
254 
255 int
256 xen_activate(struct device *self, int act)
257 {
258 	int rv = 0;
259 
260 	switch (act) {
261 	case DVACT_RESUME:
262 		xen_resume(self);
263 		break;
264 	}
265 	return (rv);
266 }
267 
268 int
269 xen_init_hypercall(struct xen_softc *sc)
270 {
271 	extern void *xen_hypercall_page;
272 	uint32_t regs[4];
273 	paddr_t pa;
274 
275 	/* Get hypercall page configuration MSR */
276 	CPUID(sc->sc_base + CPUID_OFFSET_XEN_HYPERCALL,
277 	    regs[0], regs[1], regs[2], regs[3]);
278 
279 	/* We don't support more than one hypercall page */
280 	if (regs[0] != 1) {
281 		printf(": requested %u hypercall pages\n", regs[0]);
282 		return (-1);
283 	}
284 
285 	sc->sc_hc = &xen_hypercall_page;
286 
287 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_hc, &pa)) {
288 		printf(": hypercall page PA extraction failed\n");
289 		return (-1);
290 	}
291 	wrmsr(regs[1], pa);
292 
293 	return (0);
294 }
295 
296 int
297 xen_hypercall(struct xen_softc *sc, int op, int argc, ...)
298 {
299 	va_list ap;
300 	ulong argv[5];
301 	int i;
302 
303 	if (argc < 0 || argc > 5)
304 		return (-1);
305 	va_start(ap, argc);
306 	for (i = 0; i < argc; i++)
307 		argv[i] = (ulong)va_arg(ap, ulong);
308 	va_end(ap);
309 	return (xen_hypercallv(sc, op, argc, argv));
310 }
311 
312 int
313 xen_hypercallv(struct xen_softc *sc, int op, int argc, ulong *argv)
314 {
315 	ulong hcall;
316 	int rv = 0;
317 
318 	hcall = (ulong)sc->sc_hc + op * 32;
319 
320 #if defined(XEN_DEBUG) && disabled
321 	{
322 		int i;
323 
324 		printf("hypercall %d", op);
325 		if (argc > 0) {
326 			printf(", args {");
327 			for (i = 0; i < argc; i++)
328 				printf(" %#lx", argv[i]);
329 			printf(" }\n");
330 		} else
331 			printf("\n");
332 	}
333 #endif
334 
335 	switch (argc) {
336 	case 0: {
337 		HYPERCALL_RES1;
338 		__asm__ volatile (			\
339 			  HYPERCALL_LABEL		\
340 			: HYPERCALL_OUT1		\
341 			: HYPERCALL_PTR(hcall)		\
342 			: HYPERCALL_CLOBBER		\
343 		);
344 		HYPERCALL_RET(rv);
345 		break;
346 	}
347 	case 1: {
348 		HYPERCALL_RES1; HYPERCALL_RES2;
349 		HYPERCALL_ARG1(argv[0]);
350 		__asm__ volatile (			\
351 			  HYPERCALL_LABEL		\
352 			: HYPERCALL_OUT1 HYPERCALL_OUT2	\
353 			: HYPERCALL_IN1			\
354 			, HYPERCALL_PTR(hcall)		\
355 			: HYPERCALL_CLOBBER		\
356 		);
357 		HYPERCALL_RET(rv);
358 		break;
359 	}
360 	case 2: {
361 		HYPERCALL_RES1; HYPERCALL_RES2; HYPERCALL_RES3;
362 		HYPERCALL_ARG1(argv[0]); HYPERCALL_ARG2(argv[1]);
363 		__asm__ volatile (			\
364 			  HYPERCALL_LABEL		\
365 			: HYPERCALL_OUT1 HYPERCALL_OUT2	\
366 			  HYPERCALL_OUT3		\
367 			: HYPERCALL_IN1	HYPERCALL_IN2	\
368 			, HYPERCALL_PTR(hcall)		\
369 			: HYPERCALL_CLOBBER		\
370 		);
371 		HYPERCALL_RET(rv);
372 		break;
373 	}
374 	case 3: {
375 		HYPERCALL_RES1; HYPERCALL_RES2; HYPERCALL_RES3;
376 		HYPERCALL_RES4;
377 		HYPERCALL_ARG1(argv[0]); HYPERCALL_ARG2(argv[1]);
378 		HYPERCALL_ARG3(argv[2]);
379 		__asm__ volatile (			\
380 			  HYPERCALL_LABEL		\
381 			: HYPERCALL_OUT1 HYPERCALL_OUT2	\
382 			  HYPERCALL_OUT3 HYPERCALL_OUT4	\
383 			: HYPERCALL_IN1	HYPERCALL_IN2	\
384 			  HYPERCALL_IN3			\
385 			, HYPERCALL_PTR(hcall)		\
386 			: HYPERCALL_CLOBBER		\
387 		);
388 		HYPERCALL_RET(rv);
389 		break;
390 	}
391 	case 4: {
392 		HYPERCALL_RES1; HYPERCALL_RES2; HYPERCALL_RES3;
393 		HYPERCALL_RES4; HYPERCALL_RES5;
394 		HYPERCALL_ARG1(argv[0]); HYPERCALL_ARG2(argv[1]);
395 		HYPERCALL_ARG3(argv[2]); HYPERCALL_ARG4(argv[3]);
396 		__asm__ volatile (			\
397 			  HYPERCALL_LABEL		\
398 			: HYPERCALL_OUT1 HYPERCALL_OUT2	\
399 			  HYPERCALL_OUT3 HYPERCALL_OUT4	\
400 			  HYPERCALL_OUT5		\
401 			: HYPERCALL_IN1	HYPERCALL_IN2	\
402 			  HYPERCALL_IN3	HYPERCALL_IN4	\
403 			, HYPERCALL_PTR(hcall)		\
404 			: HYPERCALL_CLOBBER		\
405 		);
406 		HYPERCALL_RET(rv);
407 		break;
408 	}
409 	case 5: {
410 		HYPERCALL_RES1; HYPERCALL_RES2; HYPERCALL_RES3;
411 		HYPERCALL_RES4; HYPERCALL_RES5; HYPERCALL_RES6;
412 		HYPERCALL_ARG1(argv[0]); HYPERCALL_ARG2(argv[1]);
413 		HYPERCALL_ARG3(argv[2]); HYPERCALL_ARG4(argv[3]);
414 		HYPERCALL_ARG5(argv[4]);
415 		__asm__ volatile (			\
416 			  HYPERCALL_LABEL		\
417 			: HYPERCALL_OUT1 HYPERCALL_OUT2	\
418 			  HYPERCALL_OUT3 HYPERCALL_OUT4	\
419 			  HYPERCALL_OUT5 HYPERCALL_OUT6	\
420 			: HYPERCALL_IN1	HYPERCALL_IN2	\
421 			  HYPERCALL_IN3	HYPERCALL_IN4	\
422 			  HYPERCALL_IN5			\
423 			, HYPERCALL_PTR(hcall)		\
424 			: HYPERCALL_CLOBBER		\
425 		);
426 		HYPERCALL_RET(rv);
427 		break;
428 	}
429 	default:
430 		DPRINTF("%s: wrong number of arguments: %d\n", __func__, argc);
431 		rv = -1;
432 		break;
433 	}
434 	return (rv);
435 }
436 
437 int
438 xen_getfeatures(struct xen_softc *sc)
439 {
440 	struct xen_feature_info xfi;
441 
442 	memset(&xfi, 0, sizeof(xfi));
443 	if (xen_hypercall(sc, XC_VERSION, 2, XENVER_get_features, &xfi) < 0) {
444 		printf(": failed to fetch features\n");
445 		return (-1);
446 	}
447 	sc->sc_features = xfi.submap;
448 #ifdef XEN_DEBUG
449 	printf(": features %b", sc->sc_features,
450 	    "\20\014DOM0\013PIRQ\012PVCLOCK\011CBVEC\010GNTFLAGS\007HMA"
451 	    "\006PTUPD\005PAE4G\004SUPERVISOR\003AUTOPMAP\002WDT\001WPT");
452 #else
453 	printf(": features %#x", sc->sc_features);
454 #endif
455 	return (0);
456 }
457 
458 #ifdef XEN_DEBUG
459 void
460 xen_print_info_page(void)
461 {
462 	struct xen_softc *sc = xen_sc;
463 	struct shared_info *s = sc->sc_ipg;
464 	struct vcpu_info *v;
465 	int i;
466 
467 	virtio_membar_sync();
468 	for (i = 0; i < XEN_LEGACY_MAX_VCPUS; i++) {
469 		v = &s->vcpu_info[i];
470 		if (!v->evtchn_upcall_pending && !v->evtchn_upcall_mask &&
471 		    !v->evtchn_pending_sel && !v->time.version &&
472 		    !v->time.tsc_timestamp && !v->time.system_time &&
473 		    !v->time.tsc_to_system_mul && !v->time.tsc_shift)
474 			continue;
475 		printf("vcpu%d:\n"
476 		    "   upcall_pending=%02x upcall_mask=%02x pending_sel=%#lx\n"
477 		    "   time version=%u tsc=%llu system=%llu\n"
478 		    "   time mul=%u shift=%d\n",
479 		    i, v->evtchn_upcall_pending, v->evtchn_upcall_mask,
480 		    v->evtchn_pending_sel, v->time.version,
481 		    v->time.tsc_timestamp, v->time.system_time,
482 		    v->time.tsc_to_system_mul, v->time.tsc_shift);
483 	}
484 	printf("pending events: ");
485 	for (i = 0; i < nitems(s->evtchn_pending); i++) {
486 		if (s->evtchn_pending[i] == 0)
487 			continue;
488 		printf(" %d:%#lx", i, s->evtchn_pending[i]);
489 	}
490 	printf("\nmasked events: ");
491 	for (i = 0; i < nitems(s->evtchn_mask); i++) {
492 		if (s->evtchn_mask[i] == 0xffffffffffffffffULL)
493 			continue;
494 		printf(" %d:%#lx", i, s->evtchn_mask[i]);
495 	}
496 	printf("\nwc ver=%u sec=%u nsec=%u\n", s->wc_version, s->wc_sec,
497 	    s->wc_nsec);
498 	printf("arch maxpfn=%lu framelist=%lu nmi=%lu\n", s->arch.max_pfn,
499 	    s->arch.pfn_to_mfn_frame_list, s->arch.nmi_reason);
500 }
501 #endif	/* XEN_DEBUG */
502 
503 int
504 xen_init_info_page(struct xen_softc *sc)
505 {
506 	struct xen_add_to_physmap xatp;
507 	paddr_t pa;
508 
509 	sc->sc_ipg = malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT | M_ZERO);
510 	if (sc->sc_ipg == NULL) {
511 		printf(": failed to allocate shared info page\n");
512 		return (-1);
513 	}
514 	if (!pmap_extract(pmap_kernel(), (vaddr_t)sc->sc_ipg, &pa)) {
515 		printf(": shared info page PA extraction failed\n");
516 		free(sc->sc_ipg, M_DEVBUF, PAGE_SIZE);
517 		return (-1);
518 	}
519 	xatp.domid = DOMID_SELF;
520 	xatp.idx = 0;
521 	xatp.space = XENMAPSPACE_shared_info;
522 	xatp.gpfn = atop(pa);
523 	if (xen_hypercall(sc, XC_MEMORY, 2, XENMEM_add_to_physmap, &xatp)) {
524 		printf(": failed to register shared info page\n");
525 		free(sc->sc_ipg, M_DEVBUF, PAGE_SIZE);
526 		return (-1);
527 	}
528 	return (0);
529 }
530 
531 int
532 xen_init_cbvec(struct xen_softc *sc)
533 {
534 	struct xen_hvm_param xhp;
535 
536 	if ((sc->sc_features & XENFEAT_CBVEC) == 0)
537 		return (ENOENT);
538 
539 	xhp.domid = DOMID_SELF;
540 	xhp.index = HVM_PARAM_CALLBACK_IRQ;
541 	xhp.value = HVM_CALLBACK_VECTOR(LAPIC_XEN_VECTOR);
542 	if (xen_hypercall(sc, XC_HVM, 2, HVMOP_set_param, &xhp)) {
543 		/* Will retry with the xspd(4) PCI interrupt */
544 		return (ENOENT);
545 	}
546 	DPRINTF(", idtvec %d", LAPIC_XEN_VECTOR);
547 
548 	sc->sc_flags |= XSF_CBVEC;
549 
550 	return (0);
551 }
552 
553 int
554 xen_init_interrupts(struct xen_softc *sc)
555 {
556 	int i;
557 
558 	sc->sc_irq = LAPIC_XEN_VECTOR;
559 
560 	/*
561 	 * Clear all pending events and mask all interrupts
562 	 */
563 	for (i = 0; i < nitems(sc->sc_ipg->evtchn_pending); i++) {
564 		sc->sc_ipg->evtchn_pending[i] = 0;
565 		sc->sc_ipg->evtchn_mask[i] = ~0UL;
566 	}
567 
568 	SLIST_INIT(&sc->sc_intrs);
569 
570 	mtx_init(&sc->sc_islck, IPL_NET);
571 
572 	return (0);
573 }
574 
575 static int
576 xen_evtchn_hypercall(struct xen_softc *sc, int cmd, void *arg, size_t len)
577 {
578 	struct evtchn_op compat;
579 	int error;
580 
581 	error = xen_hypercall(sc, XC_EVTCHN, 2, cmd, arg);
582 	if (error == -ENOXENSYS) {
583 		memset(&compat, 0, sizeof(compat));
584 		compat.cmd = cmd;
585 		memcpy(&compat.u, arg, len);
586 		error = xen_hypercall(sc, XC_OEVTCHN, 1, &compat);
587 	}
588 	return (error);
589 }
590 
591 static inline void
592 xen_intsrc_add(struct xen_softc *sc, struct xen_intsrc *xi)
593 {
594 	refcnt_init(&xi->xi_refcnt);
595 	mtx_enter(&sc->sc_islck);
596 	SLIST_INSERT_HEAD(&sc->sc_intrs, xi, xi_entry);
597 	mtx_leave(&sc->sc_islck);
598 }
599 
600 static inline struct xen_intsrc *
601 xen_intsrc_acquire(struct xen_softc *sc, evtchn_port_t port)
602 {
603 	struct xen_intsrc *xi = NULL;
604 
605 	mtx_enter(&sc->sc_islck);
606 	SLIST_FOREACH(xi, &sc->sc_intrs, xi_entry) {
607 		if (xi->xi_port == port) {
608 			refcnt_take(&xi->xi_refcnt);
609 			break;
610 		}
611 	}
612 	mtx_leave(&sc->sc_islck);
613 	return (xi);
614 }
615 
616 static inline void
617 xen_intsrc_release(struct xen_softc *sc, struct xen_intsrc *xi)
618 {
619 	refcnt_rele_wake(&xi->xi_refcnt);
620 }
621 
622 static inline struct xen_intsrc *
623 xen_intsrc_remove(struct xen_softc *sc, evtchn_port_t port)
624 {
625 	struct xen_intsrc *xi;
626 
627 	mtx_enter(&sc->sc_islck);
628 	SLIST_FOREACH(xi, &sc->sc_intrs, xi_entry) {
629 		if (xi->xi_port == port) {
630 			SLIST_REMOVE(&sc->sc_intrs, xi, xen_intsrc, xi_entry);
631 			break;
632 		}
633 	}
634 	mtx_leave(&sc->sc_islck);
635 	if (xi != NULL)
636 		refcnt_finalize(&xi->xi_refcnt, "xenisrm");
637 	return (xi);
638 }
639 
640 static inline void
641 xen_intr_mask_acquired(struct xen_softc *sc, struct xen_intsrc *xi)
642 {
643 	xi->xi_masked = 1;
644 	set_bit(xi->xi_port, &sc->sc_ipg->evtchn_mask[0]);
645 }
646 
647 static inline int
648 xen_intr_unmask_release(struct xen_softc *sc, struct xen_intsrc *xi)
649 {
650 	struct evtchn_unmask eu;
651 
652 	xi->xi_masked = 0;
653 	if (!test_bit(xi->xi_port, &sc->sc_ipg->evtchn_mask[0])) {
654 		xen_intsrc_release(sc, xi);
655 		return (0);
656 	}
657 	eu.port = xi->xi_port;
658 	xen_intsrc_release(sc, xi);
659 	return (xen_evtchn_hypercall(sc, EVTCHNOP_unmask, &eu, sizeof(eu)));
660 }
661 
662 void
663 xen_intr_ack(void)
664 {
665 	struct xen_softc *sc = xen_sc;
666 	struct shared_info *s = sc->sc_ipg;
667 	struct cpu_info *ci = curcpu();
668 	struct vcpu_info *v = &s->vcpu_info[CPU_INFO_UNIT(ci)];
669 
670 	v->evtchn_upcall_pending = 0;
671 	virtio_membar_sync();
672 }
673 
674 void
675 xen_intr(void)
676 {
677 	struct xen_softc *sc = xen_sc;
678 	struct xen_intsrc *xi;
679 	struct shared_info *s = sc->sc_ipg;
680 	struct cpu_info *ci = curcpu();
681 	struct vcpu_info *v = &s->vcpu_info[CPU_INFO_UNIT(ci)];
682 	ulong pending, selector;
683 	int port, bit, row;
684 
685 	v->evtchn_upcall_pending = 0;
686 	selector = atomic_swap_ulong(&v->evtchn_pending_sel, 0);
687 
688 	for (row = 0; selector > 0; selector >>= 1, row++) {
689 		if ((selector & 1) == 0)
690 			continue;
691 		if ((sc->sc_ipg->evtchn_pending[row] &
692 		    ~(sc->sc_ipg->evtchn_mask[row])) == 0)
693 			continue;
694 		pending = atomic_swap_ulong(&sc->sc_ipg->evtchn_pending[row],
695 		    0) & ~(sc->sc_ipg->evtchn_mask[row]);
696 		for (bit = 0; pending > 0; pending >>= 1, bit++) {
697 			if ((pending & 1) == 0)
698 				continue;
699 			port = (row * LONG_BIT) + bit;
700 			if ((xi = xen_intsrc_acquire(sc, port)) == NULL) {
701 				printf("%s: unhandled interrupt on port %d\n",
702 				    sc->sc_dev.dv_xname, port);
703 				continue;
704 			}
705 			xi->xi_evcnt.ec_count++;
706 			xen_intr_mask_acquired(sc, xi);
707 			if (!task_add(xi->xi_taskq, &xi->xi_task))
708 				xen_intsrc_release(sc, xi);
709 		}
710 	}
711 }
712 
713 void
714 xen_intr_schedule(xen_intr_handle_t xih)
715 {
716 	struct xen_softc *sc = xen_sc;
717 	struct xen_intsrc *xi;
718 
719 	if ((xi = xen_intsrc_acquire(sc, (evtchn_port_t)xih)) != NULL) {
720 		xen_intr_mask_acquired(sc, xi);
721 		if (!task_add(xi->xi_taskq, &xi->xi_task))
722 			xen_intsrc_release(sc, xi);
723 	}
724 }
725 
726 /*
727  * This code achieves two goals: 1) makes sure that *after* masking
728  * the interrupt source we're not getting more task_adds: intr_barrier
729  * will take care of that, and 2) makes sure that the interrupt task
730  * has finished executing the current task and won't be called again:
731  * it sets up a barrier task to await completion of the current task
732  * and relies on the interrupt masking to prevent submission of new
733  * tasks in the future.
734  */
735 void
736 xen_intr_barrier(xen_intr_handle_t xih)
737 {
738 	struct xen_softc *sc = xen_sc;
739 	struct xen_intsrc *xi;
740 
741 	/*
742 	 * XXX This will need to be revised once intr_barrier starts
743 	 * using its argument.
744 	 */
745 	intr_barrier(NULL);
746 
747 	if ((xi = xen_intsrc_acquire(sc, (evtchn_port_t)xih)) != NULL) {
748 		taskq_barrier(xi->xi_taskq);
749 		xen_intsrc_release(sc, xi);
750 	}
751 }
752 
753 void
754 xen_intr_signal(xen_intr_handle_t xih)
755 {
756 	struct xen_softc *sc = xen_sc;
757 	struct xen_intsrc *xi;
758 	struct evtchn_send es;
759 
760 	if ((xi = xen_intsrc_acquire(sc, (evtchn_port_t)xih)) != NULL) {
761 		es.port = xi->xi_port;
762 		xen_intsrc_release(sc, xi);
763 		xen_evtchn_hypercall(sc, EVTCHNOP_send, &es, sizeof(es));
764 	}
765 }
766 
767 int
768 xen_intr_establish(evtchn_port_t port, xen_intr_handle_t *xih, int domain,
769     void (*handler)(void *), void *arg, char *name)
770 {
771 	struct xen_softc *sc = xen_sc;
772 	struct xen_intsrc *xi;
773 	struct evtchn_alloc_unbound eau;
774 #ifdef notyet
775 	struct evtchn_bind_vcpu ebv;
776 #endif
777 #if defined(XEN_DEBUG) && disabled
778 	struct evtchn_status es;
779 #endif
780 
781 	if (port && (xi = xen_intsrc_acquire(sc, port)) != NULL) {
782 		xen_intsrc_release(sc, xi);
783 		DPRINTF("%s: interrupt handler has already been established "
784 		    "for port %u\n", sc->sc_dev.dv_xname, port);
785 		return (-1);
786 	}
787 
788 	xi = malloc(sizeof(*xi), M_DEVBUF, M_NOWAIT | M_ZERO);
789 	if (xi == NULL)
790 		return (-1);
791 
792 	xi->xi_port = (evtchn_port_t)*xih;
793 
794 	xi->xi_handler = handler;
795 	xi->xi_ctx = arg;
796 
797 	xi->xi_taskq = taskq_create(name, 1, IPL_NET, TASKQ_MPSAFE);
798 	if (!xi->xi_taskq) {
799 		printf("%s: failed to create interrupt task for %s\n",
800 		    sc->sc_dev.dv_xname, name);
801 		free(xi, M_DEVBUF, sizeof(*xi));
802 		return (-1);
803 	}
804 	task_set(&xi->xi_task, xen_intr_dispatch, xi);
805 
806 	if (port == 0) {
807 		/* We're being asked to allocate a new event port */
808 		memset(&eau, 0, sizeof(eau));
809 		eau.dom = DOMID_SELF;
810 		eau.remote_dom = domain;
811 		if (xen_evtchn_hypercall(sc, EVTCHNOP_alloc_unbound, &eau,
812 		    sizeof(eau)) != 0) {
813 			DPRINTF("%s: failed to allocate new event port\n",
814 			    sc->sc_dev.dv_xname);
815 			free(xi, M_DEVBUF, sizeof(*xi));
816 			return (-1);
817 		}
818 		*xih = xi->xi_port = eau.port;
819 	} else {
820 		*xih = xi->xi_port = port;
821 		/*
822 		 * The Event Channel API didn't open this port, so it is not
823 		 * responsible for closing it automatically on unbind.
824 		 */
825 		xi->xi_noclose = 1;
826 	}
827 
828 #ifdef notyet
829 	/* Bind interrupt to VCPU#0 */
830 	memset(&ebv, 0, sizeof(ebv));
831 	ebv.port = xi->xi_port;
832 	ebv.vcpu = 0;
833 	if (xen_evtchn_hypercall(sc, EVTCHNOP_bind_vcpu, &ebv, sizeof(ebv))) {
834 		printf("%s: failed to bind interrupt on port %u to vcpu%d\n",
835 		    sc->sc_dev.dv_xname, ebv.port, ebv.vcpu);
836 	}
837 #endif
838 
839 	evcount_attach(&xi->xi_evcnt, name, &sc->sc_irq);
840 
841 	xen_intsrc_add(sc, xi);
842 
843 	/* Mask the event port */
844 	set_bit(xi->xi_port, &sc->sc_ipg->evtchn_mask[0]);
845 
846 #if defined(XEN_DEBUG) && disabled
847 	memset(&es, 0, sizeof(es));
848 	es.dom = DOMID_SELF;
849 	es.port = xi->xi_port;
850 	if (xen_evtchn_hypercall(sc, EVTCHNOP_status, &es, sizeof(es))) {
851 		printf("%s: failed to obtain status for port %d\n",
852 		    sc->sc_dev.dv_xname, es.port);
853 	}
854 	printf("%s: port %u bound to vcpu%u", sc->sc_dev.dv_xname,
855 	    es.port, es.vcpu);
856 	if (es.status == EVTCHNSTAT_interdomain)
857 		printf(": domain %d port %u\n", es.u.interdomain.dom,
858 		    es.u.interdomain.port);
859 	else if (es.status == EVTCHNSTAT_unbound)
860 		printf(": domain %d\n", es.u.unbound.dom);
861 	else if (es.status == EVTCHNSTAT_pirq)
862 		printf(": pirq %u\n", es.u.pirq);
863 	else if (es.status == EVTCHNSTAT_virq)
864 		printf(": virq %u\n", es.u.virq);
865 	else
866 		printf("\n");
867 #endif
868 
869 	return (0);
870 }
871 
872 int
873 xen_intr_disestablish(xen_intr_handle_t xih)
874 {
875 	struct xen_softc *sc = xen_sc;
876 	evtchn_port_t port = (evtchn_port_t)xih;
877 	struct evtchn_close ec;
878 	struct xen_intsrc *xi;
879 
880 	if ((xi = xen_intsrc_remove(sc, port)) == NULL)
881 		return (-1);
882 
883 	evcount_detach(&xi->xi_evcnt);
884 
885 	taskq_destroy(xi->xi_taskq);
886 
887 	set_bit(xi->xi_port, &sc->sc_ipg->evtchn_mask[0]);
888 	clear_bit(xi->xi_port, &sc->sc_ipg->evtchn_pending[0]);
889 
890 	if (!xi->xi_noclose) {
891 		ec.port = xi->xi_port;
892 		if (xen_evtchn_hypercall(sc, EVTCHNOP_close, &ec, sizeof(ec))) {
893 			DPRINTF("%s: failed to close event port %u\n",
894 			    sc->sc_dev.dv_xname, xi->xi_port);
895 		}
896 	}
897 
898 	free(xi, M_DEVBUF, sizeof(*xi));
899 	return (0);
900 }
901 
902 void
903 xen_intr_dispatch(void *arg)
904 {
905 	struct xen_softc *sc = xen_sc;
906 	struct xen_intsrc *xi = arg;
907 
908 	if (xi->xi_handler)
909 		xi->xi_handler(xi->xi_ctx);
910 
911 	xen_intr_unmask_release(sc, xi);
912 }
913 
914 void
915 xen_intr_enable(void)
916 {
917 	struct xen_softc *sc = xen_sc;
918 	struct xen_intsrc *xi;
919 	struct evtchn_unmask eu;
920 
921 	mtx_enter(&sc->sc_islck);
922 	SLIST_FOREACH(xi, &sc->sc_intrs, xi_entry) {
923 		if (!xi->xi_masked) {
924 			eu.port = xi->xi_port;
925 			if (xen_evtchn_hypercall(sc, EVTCHNOP_unmask, &eu,
926 			    sizeof(eu)))
927 				printf("%s: unmasking port %u failed\n",
928 				    sc->sc_dev.dv_xname, xi->xi_port);
929 			virtio_membar_sync();
930 			if (test_bit(xi->xi_port, &sc->sc_ipg->evtchn_mask[0]))
931 				printf("%s: port %u is still masked\n",
932 				    sc->sc_dev.dv_xname, xi->xi_port);
933 		}
934 	}
935 	mtx_leave(&sc->sc_islck);
936 }
937 
938 void
939 xen_intr_mask(xen_intr_handle_t xih)
940 {
941 	struct xen_softc *sc = xen_sc;
942 	evtchn_port_t port = (evtchn_port_t)xih;
943 	struct xen_intsrc *xi;
944 
945 	if ((xi = xen_intsrc_acquire(sc, port)) != NULL) {
946 		xen_intr_mask_acquired(sc, xi);
947 		xen_intsrc_release(sc, xi);
948 	}
949 }
950 
951 int
952 xen_intr_unmask(xen_intr_handle_t xih)
953 {
954 	struct xen_softc *sc = xen_sc;
955 	evtchn_port_t port = (evtchn_port_t)xih;
956 	struct xen_intsrc *xi;
957 
958 	if ((xi = xen_intsrc_acquire(sc, port)) != NULL)
959 		return (xen_intr_unmask_release(sc, xi));
960 
961 	return (0);
962 }
963 
964 int
965 xen_init_grant_tables(struct xen_softc *sc)
966 {
967 	struct gnttab_query_size gqs;
968 
969 	gqs.dom = DOMID_SELF;
970 	if (xen_hypercall(sc, XC_GNTTAB, 3, GNTTABOP_query_size, &gqs, 1)) {
971 		printf(": failed the query for grant table pages\n");
972 		return (-1);
973 	}
974 	if (gqs.nr_frames == 0 || gqs.nr_frames > gqs.max_nr_frames) {
975 		printf(": invalid number of grant table pages: %u/%u\n",
976 		    gqs.nr_frames, gqs.max_nr_frames);
977 		return (-1);
978 	}
979 
980 	sc->sc_gntmax = gqs.max_nr_frames;
981 
982 	sc->sc_gnt = mallocarray(sc->sc_gntmax + 1, sizeof(struct xen_gntent),
983 	    M_DEVBUF, M_ZERO | M_NOWAIT);
984 	if (sc->sc_gnt == NULL) {
985 		printf(": failed to allocate grant table lookup table\n");
986 		return (-1);
987 	}
988 
989 	mtx_init(&sc->sc_gntlck, IPL_NET);
990 
991 	if (xen_grant_table_grow(sc) == NULL) {
992 		free(sc->sc_gnt, M_DEVBUF, sc->sc_gntmax *
993 		    sizeof(struct xen_gntent));
994 		return (-1);
995 	}
996 
997 	printf(", %d grant table frames", sc->sc_gntmax);
998 
999 	xen_bus_dma_tag._cookie = sc;
1000 
1001 	return (0);
1002 }
1003 
1004 struct xen_gntent *
1005 xen_grant_table_grow(struct xen_softc *sc)
1006 {
1007 	struct xen_add_to_physmap xatp;
1008 	struct xen_gntent *ge;
1009 	void *va;
1010 	paddr_t pa;
1011 
1012 	if (sc->sc_gntcnt == sc->sc_gntmax) {
1013 		printf("%s: grant table frame allotment limit reached\n",
1014 		    sc->sc_dev.dv_xname);
1015 		return (NULL);
1016 	}
1017 
1018 	va = km_alloc(PAGE_SIZE, &kv_any, &kp_zero, &kd_nowait);
1019 	if (va == NULL)
1020 		return (NULL);
1021 	if (!pmap_extract(pmap_kernel(), (vaddr_t)va, &pa)) {
1022 		printf("%s: grant table page PA extraction failed\n",
1023 		    sc->sc_dev.dv_xname);
1024 		km_free(va, PAGE_SIZE, &kv_any, &kp_zero);
1025 		return (NULL);
1026 	}
1027 
1028 	mtx_enter(&sc->sc_gntlck);
1029 
1030 	ge = &sc->sc_gnt[sc->sc_gntcnt];
1031 	ge->ge_table = va;
1032 
1033 	xatp.domid = DOMID_SELF;
1034 	xatp.idx = sc->sc_gntcnt;
1035 	xatp.space = XENMAPSPACE_grant_table;
1036 	xatp.gpfn = atop(pa);
1037 	if (xen_hypercall(sc, XC_MEMORY, 2, XENMEM_add_to_physmap, &xatp)) {
1038 		printf("%s: failed to add a grant table page\n",
1039 		    sc->sc_dev.dv_xname);
1040 		km_free(ge->ge_table, PAGE_SIZE, &kv_any, &kp_zero);
1041 		mtx_leave(&sc->sc_gntlck);
1042 		return (NULL);
1043 	}
1044 	ge->ge_start = sc->sc_gntcnt * GNTTAB_NEPG;
1045 	/* First page has 8 reserved entries */
1046 	ge->ge_reserved = ge->ge_start == 0 ? GNTTAB_NR_RESERVED_ENTRIES : 0;
1047 	ge->ge_free = GNTTAB_NEPG - ge->ge_reserved;
1048 	ge->ge_next = ge->ge_reserved;
1049 	mtx_init(&ge->ge_lock, IPL_NET);
1050 
1051 	sc->sc_gntcnt++;
1052 	mtx_leave(&sc->sc_gntlck);
1053 
1054 	return (ge);
1055 }
1056 
1057 int
1058 xen_grant_table_alloc(struct xen_softc *sc, grant_ref_t *ref)
1059 {
1060 	struct xen_gntent *ge;
1061 	int i;
1062 
1063 	/* Start with a previously allocated table page */
1064 	ge = &sc->sc_gnt[sc->sc_gntcnt - 1];
1065 	if (ge->ge_free > 0) {
1066 		mtx_enter(&ge->ge_lock);
1067 		if (ge->ge_free > 0)
1068 			goto search;
1069 		mtx_leave(&ge->ge_lock);
1070 	}
1071 
1072 	/* Try other existing table pages */
1073 	for (i = 0; i < sc->sc_gntcnt; i++) {
1074 		ge = &sc->sc_gnt[i];
1075 		if (ge->ge_free == 0)
1076 			continue;
1077 		mtx_enter(&ge->ge_lock);
1078 		if (ge->ge_free > 0)
1079 			goto search;
1080 		mtx_leave(&ge->ge_lock);
1081 	}
1082 
1083  alloc:
1084 	/* Allocate a new table page */
1085 	if ((ge = xen_grant_table_grow(sc)) == NULL)
1086 		return (-1);
1087 
1088 	mtx_enter(&ge->ge_lock);
1089 	if (ge->ge_free == 0) {
1090 		/* We were not fast enough... */
1091 		mtx_leave(&ge->ge_lock);
1092 		goto alloc;
1093 	}
1094 
1095  search:
1096 	for (i = ge->ge_next;
1097 	     /* Math works here because GNTTAB_NEPG is a power of 2 */
1098 	     i != ((ge->ge_next + GNTTAB_NEPG - 1) & (GNTTAB_NEPG - 1));
1099 	     i++) {
1100 		if (i == GNTTAB_NEPG)
1101 			i = 0;
1102 		if (ge->ge_reserved && i < ge->ge_reserved)
1103 			continue;
1104 		if (ge->ge_table[i].frame != 0)
1105 			continue;
1106 		*ref = ge->ge_start + i;
1107 		ge->ge_table[i].flags = GTF_invalid;
1108 		ge->ge_table[i].frame = 0xffffffff; /* Mark as taken */
1109 		if ((ge->ge_next = i + 1) == GNTTAB_NEPG)
1110 			ge->ge_next = ge->ge_reserved;
1111 		ge->ge_free--;
1112 		mtx_leave(&ge->ge_lock);
1113 		return (0);
1114 	}
1115 	mtx_leave(&ge->ge_lock);
1116 
1117 	panic("page full, sc %p gnt %p (%d) ge %p", sc, sc->sc_gnt,
1118 	    sc->sc_gntcnt, ge);
1119 	return (-1);
1120 }
1121 
1122 void
1123 xen_grant_table_free(struct xen_softc *sc, grant_ref_t ref)
1124 {
1125 	struct xen_gntent *ge;
1126 
1127 #ifdef XEN_DEBUG
1128 	if (ref > sc->sc_gntcnt * GNTTAB_NEPG)
1129 		panic("unmanaged ref %u sc %p gnt %p (%d)", ref, sc,
1130 		    sc->sc_gnt, sc->sc_gntcnt);
1131 #endif
1132 	ge = &sc->sc_gnt[ref / GNTTAB_NEPG];
1133 	mtx_enter(&ge->ge_lock);
1134 #ifdef XEN_DEBUG
1135 	if (ref < ge->ge_start || ref > ge->ge_start + GNTTAB_NEPG) {
1136 		mtx_leave(&ge->ge_lock);
1137 		panic("out of bounds ref %u ge %p start %u sc %p gnt %p",
1138 		    ref, ge, ge->ge_start, sc, sc->sc_gnt);
1139 	}
1140 #endif
1141 	ref -= ge->ge_start;
1142 	if (ge->ge_table[ref].flags != GTF_invalid) {
1143 		mtx_leave(&ge->ge_lock);
1144 		panic("reference %u is still in use, flags %#x frame %#x",
1145 		    ref + ge->ge_start, ge->ge_table[ref].flags,
1146 		    ge->ge_table[ref].frame);
1147 	}
1148 	ge->ge_table[ref].frame = 0;
1149 	ge->ge_next = ref;
1150 	ge->ge_free++;
1151 	mtx_leave(&ge->ge_lock);
1152 }
1153 
1154 void
1155 xen_grant_table_enter(struct xen_softc *sc, grant_ref_t ref, paddr_t pa,
1156     int domain, int flags)
1157 {
1158 	struct xen_gntent *ge;
1159 
1160 #ifdef XEN_DEBUG
1161 	if (ref > sc->sc_gntcnt * GNTTAB_NEPG)
1162 		panic("unmanaged ref %u sc %p gnt %p (%d)", ref, sc,
1163 		    sc->sc_gnt, sc->sc_gntcnt);
1164 #endif
1165 	ge = &sc->sc_gnt[ref / GNTTAB_NEPG];
1166 #ifdef XEN_DEBUG
1167 	if (ref < ge->ge_start || ref > ge->ge_start + GNTTAB_NEPG) {
1168 		panic("out of bounds ref %u ge %p start %u sc %p gnt %p",
1169 		    ref, ge, ge->ge_start, sc, sc->sc_gnt);
1170 	}
1171 #endif
1172 	ref -= ge->ge_start;
1173 	if (ge->ge_table[ref].flags != GTF_invalid) {
1174 		panic("reference %u is still in use, flags %#x frame %#x",
1175 		    ref + ge->ge_start, ge->ge_table[ref].flags,
1176 		    ge->ge_table[ref].frame);
1177 	}
1178 	ge->ge_table[ref].frame = atop(pa);
1179 	ge->ge_table[ref].domid = domain;
1180 	virtio_membar_sync();
1181 	ge->ge_table[ref].flags = GTF_permit_access | flags;
1182 	virtio_membar_sync();
1183 }
1184 
1185 void
1186 xen_grant_table_remove(struct xen_softc *sc, grant_ref_t ref)
1187 {
1188 	struct xen_gntent *ge;
1189 	uint32_t flags, *ptr;
1190 	int loop;
1191 
1192 #ifdef XEN_DEBUG
1193 	if (ref > sc->sc_gntcnt * GNTTAB_NEPG)
1194 		panic("unmanaged ref %u sc %p gnt %p (%d)", ref, sc,
1195 		    sc->sc_gnt, sc->sc_gntcnt);
1196 #endif
1197 	ge = &sc->sc_gnt[ref / GNTTAB_NEPG];
1198 #ifdef XEN_DEBUG
1199 	if (ref < ge->ge_start || ref > ge->ge_start + GNTTAB_NEPG) {
1200 		panic("out of bounds ref %u ge %p start %u sc %p gnt %p",
1201 		    ref, ge, ge->ge_start, sc, sc->sc_gnt);
1202 	}
1203 #endif
1204 	ref -= ge->ge_start;
1205 	/* Invalidate the grant reference */
1206 	virtio_membar_sync();
1207 	ptr = (uint32_t *)&ge->ge_table[ref];
1208 	flags = (ge->ge_table[ref].flags & ~(GTF_reading|GTF_writing)) |
1209 	    (ge->ge_table[ref].domid << 16);
1210 	loop = 0;
1211 	while (atomic_cas_uint(ptr, flags, GTF_invalid) != flags) {
1212 		if (loop++ > 10) {
1213 			panic("grant table reference %u is held "
1214 			    "by domain %d: frame %#x flags %#x",
1215 			    ref + ge->ge_start, ge->ge_table[ref].domid,
1216 			    ge->ge_table[ref].frame, ge->ge_table[ref].flags);
1217 		}
1218 #if (defined(__amd64__) || defined(__i386__))
1219 		__asm volatile("pause": : : "memory");
1220 #endif
1221 	}
1222 	ge->ge_table[ref].frame = 0xffffffff;
1223 }
1224 
1225 int
1226 xen_bus_dmamap_create(bus_dma_tag_t t, bus_size_t size, int nsegments,
1227     bus_size_t maxsegsz, bus_size_t boundary, int flags, bus_dmamap_t *dmamp)
1228 {
1229 	struct xen_softc *sc = t->_cookie;
1230 	struct xen_gntmap *gm;
1231 	int i, error;
1232 
1233 	if (maxsegsz < PAGE_SIZE)
1234 		return (EINVAL);
1235 
1236 	/* Allocate a dma map structure */
1237 	error = bus_dmamap_create(sc->sc_dmat, size, nsegments, maxsegsz,
1238 	    boundary, flags, dmamp);
1239 	if (error)
1240 		return (error);
1241 	/* Allocate an array of grant table pa<->ref maps */
1242 	gm = mallocarray(nsegments, sizeof(struct xen_gntmap), M_DEVBUF,
1243 	    M_ZERO | ((flags & BUS_DMA_NOWAIT) ? M_NOWAIT : M_WAITOK));
1244 	if (gm == NULL) {
1245 		bus_dmamap_destroy(sc->sc_dmat, *dmamp);
1246 		*dmamp = NULL;
1247 		return (ENOMEM);
1248 	}
1249 	/* Wire it to the dma map */
1250 	(*dmamp)->_dm_cookie = gm;
1251 	/* Claim references from the grant table */
1252 	for (i = 0; i < (*dmamp)->_dm_segcnt; i++) {
1253 		if (xen_grant_table_alloc(sc, &gm[i].gm_ref)) {
1254 			xen_bus_dmamap_destroy(t, *dmamp);
1255 			*dmamp = NULL;
1256 			return (ENOBUFS);
1257 		}
1258 	}
1259 	return (0);
1260 }
1261 
1262 void
1263 xen_bus_dmamap_destroy(bus_dma_tag_t t, bus_dmamap_t map)
1264 {
1265 	struct xen_softc *sc = t->_cookie;
1266 	struct xen_gntmap *gm;
1267 	int i;
1268 
1269 	gm = map->_dm_cookie;
1270 	for (i = 0; i < map->_dm_segcnt; i++) {
1271 		if (gm[i].gm_ref == 0)
1272 			continue;
1273 		xen_grant_table_free(sc, gm[i].gm_ref);
1274 	}
1275 	free(gm, M_DEVBUF, map->_dm_segcnt * sizeof(struct xen_gntmap));
1276 	bus_dmamap_destroy(sc->sc_dmat, map);
1277 }
1278 
1279 int
1280 xen_bus_dmamap_load(bus_dma_tag_t t, bus_dmamap_t map, void *buf,
1281     bus_size_t buflen, struct proc *p, int flags)
1282 {
1283 	struct xen_softc *sc = t->_cookie;
1284 	struct xen_gntmap *gm = map->_dm_cookie;
1285 	int i, domain, error;
1286 
1287 	domain = flags >> 16;
1288 	flags &= 0xffff;
1289 	error = bus_dmamap_load(sc->sc_dmat, map, buf, buflen, p, flags);
1290 	if (error)
1291 		return (error);
1292 	for (i = 0; i < map->dm_nsegs; i++) {
1293 		xen_grant_table_enter(sc, gm[i].gm_ref, map->dm_segs[i].ds_addr,
1294 		    domain, flags & BUS_DMA_WRITE ? GTF_readonly : 0);
1295 		gm[i].gm_paddr = map->dm_segs[i].ds_addr;
1296 		map->dm_segs[i].ds_addr = gm[i].gm_ref;
1297 	}
1298 	return (0);
1299 }
1300 
1301 int
1302 xen_bus_dmamap_load_mbuf(bus_dma_tag_t t, bus_dmamap_t map, struct mbuf *m0,
1303     int flags)
1304 {
1305 	struct xen_softc *sc = t->_cookie;
1306 	struct xen_gntmap *gm = map->_dm_cookie;
1307 	int i, domain, error;
1308 
1309 	domain = flags >> 16;
1310 	flags &= 0xffff;
1311 	error = bus_dmamap_load_mbuf(sc->sc_dmat, map, m0, flags);
1312 	if (error)
1313 		return (error);
1314 	for (i = 0; i < map->dm_nsegs; i++) {
1315 		xen_grant_table_enter(sc, gm[i].gm_ref, map->dm_segs[i].ds_addr,
1316 		    domain, flags & BUS_DMA_WRITE ? GTF_readonly : 0);
1317 		gm[i].gm_paddr = map->dm_segs[i].ds_addr;
1318 		map->dm_segs[i].ds_addr = gm[i].gm_ref;
1319 	}
1320 	return (0);
1321 }
1322 
1323 void
1324 xen_bus_dmamap_unload(bus_dma_tag_t t, bus_dmamap_t map)
1325 {
1326 	struct xen_softc *sc = t->_cookie;
1327 	struct xen_gntmap *gm = map->_dm_cookie;
1328 	int i;
1329 
1330 	for (i = 0; i < map->dm_nsegs; i++) {
1331 		if (gm[i].gm_paddr == 0)
1332 			continue;
1333 		xen_grant_table_remove(sc, gm[i].gm_ref);
1334 		map->dm_segs[i].ds_addr = gm[i].gm_paddr;
1335 		gm[i].gm_paddr = 0;
1336 	}
1337 	bus_dmamap_unload(sc->sc_dmat, map);
1338 }
1339 
1340 void
1341 xen_bus_dmamap_sync(bus_dma_tag_t t, bus_dmamap_t map, bus_addr_t addr,
1342     bus_size_t size, int op)
1343 {
1344 	if ((op == (BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE)) ||
1345 	    (op == (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE)))
1346 		virtio_membar_sync();
1347 }
1348 
1349 static int
1350 xen_attach_print(void *aux, const char *name)
1351 {
1352 	struct xen_attach_args *xa = aux;
1353 
1354 	if (name)
1355 		printf("\"%s\" at %s: %s", xa->xa_name, name, xa->xa_node);
1356 
1357 	return (UNCONF);
1358 }
1359 
1360 int
1361 xen_attach_device(struct xen_softc *sc, struct xen_devlist *xdl,
1362     const char *name, const char *unit)
1363 {
1364 	struct xen_attach_args xa;
1365 	struct xen_device *xdv;
1366 	unsigned long long res;
1367 
1368 	xa.xa_dmat = &xen_bus_dma_tag;
1369 
1370 	strlcpy(xa.xa_name, name, sizeof(xa.xa_name));
1371 	snprintf(xa.xa_node, sizeof(xa.xa_node), "device/%s/%s", name, unit);
1372 
1373 	if (xs_getprop(sc, xa.xa_node, "backend", xa.xa_backend,
1374 	    sizeof(xa.xa_backend))) {
1375 		DPRINTF("%s: failed to identify \"backend\" for "
1376 		    "\"%s\"\n", sc->sc_dev.dv_xname, xa.xa_node);
1377 		return (EIO);
1378 	}
1379 
1380 	if (xs_getnum(sc, xa.xa_node, "backend-id", &res) || res > UINT16_MAX) {
1381 		DPRINTF("%s: invalid \"backend-id\" for \"%s\"\n",
1382 		    sc->sc_dev.dv_xname, xa.xa_node);
1383 		return (EIO);
1384 	}
1385 	xa.xa_domid = (uint16_t)res;
1386 
1387 	xdv = malloc(sizeof(struct xen_device), M_DEVBUF, M_ZERO | M_NOWAIT);
1388 	if (xdv == NULL)
1389 		return (ENOMEM);
1390 
1391 	strlcpy(xdv->dv_unit, unit, sizeof(xdv->dv_unit));
1392 	LIST_INSERT_HEAD(&xdl->dl_devs, xdv, dv_entry);
1393 
1394 	xdv->dv_dev = config_found((struct device *)sc, &xa, xen_attach_print);
1395 
1396 	return (0);
1397 }
1398 
1399 int
1400 xen_probe_devices(struct xen_softc *sc)
1401 {
1402 	struct xen_devlist *xdl;
1403 	struct xs_transaction xst;
1404 	struct iovec *iovp1 = NULL, *iovp2 = NULL;
1405 	int i, j, error, iov1_cnt = 0, iov2_cnt = 0;
1406 	char path[256];
1407 
1408 	memset(&xst, 0, sizeof(xst));
1409 	xst.xst_id = 0;
1410 	xst.xst_cookie = sc->sc_xs;
1411 
1412 	if ((error = xs_cmd(&xst, XS_LIST, "device", &iovp1, &iov1_cnt)) != 0)
1413 		return (error);
1414 
1415 	for (i = 0; i < iov1_cnt; i++) {
1416 		if (strcmp("suspend", (char *)iovp1[i].iov_base) == 0)
1417 			continue;
1418 		snprintf(path, sizeof(path), "device/%s",
1419 		    (char *)iovp1[i].iov_base);
1420 		if ((error = xs_cmd(&xst, XS_LIST, path, &iovp2,
1421 		    &iov2_cnt)) != 0)
1422 			goto out;
1423 		if ((xdl = malloc(sizeof(struct xen_devlist), M_DEVBUF,
1424 		    M_ZERO | M_NOWAIT)) == NULL) {
1425 			error = ENOMEM;
1426 			goto out;
1427 		}
1428 		xdl->dl_xen = sc;
1429 		strlcpy(xdl->dl_node, (const char *)iovp1[i].iov_base,
1430 		    XEN_MAX_NODE_LEN);
1431 		for (j = 0; j < iov2_cnt; j++) {
1432 			error = xen_attach_device(sc, xdl,
1433 			    (const char *)iovp1[i].iov_base,
1434 			    (const char *)iovp2[j].iov_base);
1435 			if (error) {
1436 				printf("%s: failed to attach \"%s/%s\"\n",
1437 				    sc->sc_dev.dv_xname, path,
1438 				    (const char *)iovp2[j].iov_base);
1439 				goto out;
1440 			}
1441 		}
1442 		/* Setup a watch for every device subtree */
1443 		if (xs_watch(sc, "device", (char *)iovp1[i].iov_base,
1444 		    &xdl->dl_task, xen_hotplug, xdl))
1445 			printf("%s: failed to setup hotplug watch for \"%s\"\n",
1446 			    sc->sc_dev.dv_xname, (char *)iovp1[i].iov_base);
1447 		SLIST_INSERT_HEAD(&sc->sc_devlists, xdl, dl_entry);
1448 		xs_resfree(&xst, iovp2, iov2_cnt);
1449 		iovp2 = NULL;
1450 		iov2_cnt = 0;
1451 	}
1452 
1453  out:
1454 	if (iovp2)
1455 		xs_resfree(&xst, iovp2, iov2_cnt);
1456 	xs_resfree(&xst, iovp1, iov1_cnt);
1457 	return (error);
1458 }
1459 
1460 void
1461 xen_hotplug(void *arg)
1462 {
1463 	struct xen_devlist *xdl = arg;
1464 	struct xen_softc *sc = xdl->dl_xen;
1465 	struct xen_device *xdv, *xvdn;
1466 	struct xs_transaction xst;
1467 	struct iovec *iovp = NULL;
1468 	int error, i, keep, iov_cnt = 0;
1469 	char path[256];
1470 	int8_t *seen;
1471 
1472 	memset(&xst, 0, sizeof(xst));
1473 	xst.xst_id = 0;
1474 	xst.xst_cookie = sc->sc_xs;
1475 
1476 	snprintf(path, sizeof(path), "device/%s", xdl->dl_node);
1477 	if ((error = xs_cmd(&xst, XS_LIST, path, &iovp, &iov_cnt)) != 0)
1478 		return;
1479 
1480 	seen = malloc(iov_cnt, M_TEMP, M_ZERO | M_WAITOK);
1481 
1482 	/* Detect all removed and kept devices */
1483 	LIST_FOREACH_SAFE(xdv, &xdl->dl_devs, dv_entry, xvdn) {
1484 		for (i = 0, keep = 0; i < iov_cnt; i++) {
1485 			if (!seen[i] &&
1486 			    !strcmp(xdv->dv_unit, (char *)iovp[i].iov_base)) {
1487 				seen[i]++;
1488 				keep++;
1489 				break;
1490 			}
1491 		}
1492 		if (!keep) {
1493 			DPRINTF("%s: removing \"%s/%s\"\n", sc->sc_dev.dv_xname,
1494 			    xdl->dl_node, xdv->dv_unit);
1495 			LIST_REMOVE(xdv, dv_entry);
1496 			config_detach(xdv->dv_dev, 0);
1497 			free(xdv, M_DEVBUF, sizeof(struct xen_device));
1498 		}
1499 	}
1500 
1501 	/* Attach all new devices */
1502 	for (i = 0; i < iov_cnt; i++) {
1503 		if (seen[i])
1504 			continue;
1505 		DPRINTF("%s: attaching \"%s/%s\"\n", sc->sc_dev.dv_xname,
1506 			    xdl->dl_node, (const char *)iovp[i].iov_base);
1507 		error = xen_attach_device(sc, xdl, xdl->dl_node,
1508 		    (const char *)iovp[i].iov_base);
1509 		if (error) {
1510 			printf("%s: failed to attach \"%s/%s\"\n",
1511 			    sc->sc_dev.dv_xname, path,
1512 			    (const char *)iovp[i].iov_base);
1513 			continue;
1514 		}
1515 	}
1516 
1517 	free(seen, M_TEMP, iov_cnt);
1518 
1519 	xs_resfree(&xst, iovp, iov_cnt);
1520 }
1521 
1522 #include <machine/pio.h>
1523 
1524 #define	XMI_PORT		0x10
1525 #define XMI_MAGIC		0x49d2
1526 #define XMI_UNPLUG_IDE		0x01
1527 #define XMI_UNPLUG_NIC		0x02
1528 #define XMI_UNPLUG_IDESEC	0x04
1529 
1530 void
1531 xen_disable_emulated_devices(struct xen_softc *sc)
1532 {
1533 #if defined(__i386__) || defined(__amd64__)
1534 	ushort unplug = 0;
1535 
1536 	if (inw(XMI_PORT) != XMI_MAGIC) {
1537 		printf("%s: failed to disable emulated devices\n",
1538 		    sc->sc_dev.dv_xname);
1539 		return;
1540 	}
1541 	if (sc->sc_unplug & XEN_UNPLUG_IDE)
1542 		unplug |= XMI_UNPLUG_IDE;
1543 	if (sc->sc_unplug & XEN_UNPLUG_IDESEC)
1544 		unplug |= XMI_UNPLUG_IDESEC;
1545 	if (sc->sc_unplug & XEN_UNPLUG_NIC)
1546 		unplug |= XMI_UNPLUG_NIC;
1547 	if (unplug)
1548 		outw(XMI_PORT, unplug);
1549 #endif	/* __i386__ || __amd64__ */
1550 }
1551 
1552 void
1553 xen_unplug_emulated(void *xsc, int what)
1554 {
1555 	struct xen_softc *sc = xsc;
1556 
1557 	sc->sc_unplug |= what;
1558 }
1559