]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/xen/xen_intr.c
Import lib9p 7ddb1164407da19b9b1afb83df83ae65a71a9a66.
[FreeBSD/FreeBSD.git] / sys / x86 / xen / xen_intr.c
1 /******************************************************************************
2  * xen_intr.c
3  *
4  * Xen event and interrupt services for x86 HVM guests.
5  *
6  * Copyright (c) 2002-2005, K A Fraser
7  * Copyright (c) 2005, Intel Corporation <xiaofeng.ling@intel.com>
8  * Copyright (c) 2012, Spectra Logic Corporation
9  *
10  * This file may be distributed separately from the Linux kernel, or
11  * incorporated into other software packages, subject to the following license:
12  *
13  * Permission is hereby granted, free of charge, to any person obtaining a copy
14  * of this source file (the "Software"), to deal in the Software without
15  * restriction, including without limitation the rights to use, copy, modify,
16  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
17  * and to permit persons to whom the Software is furnished to do so, subject to
18  * the following conditions:
19  *
20  * The above copyright notice and this permission notice shall be included in
21  * all copies or substantial portions of the Software.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
29  * IN THE SOFTWARE.
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "opt_ddb.h"
36
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/bus.h>
40 #include <sys/malloc.h>
41 #include <sys/kernel.h>
42 #include <sys/limits.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/interrupt.h>
46 #include <sys/pcpu.h>
47 #include <sys/smp.h>
48 #include <sys/refcount.h>
49
50 #include <vm/vm.h>
51 #include <vm/pmap.h>
52
53 #include <machine/intr_machdep.h>
54 #include <x86/apicvar.h>
55 #include <x86/apicreg.h>
56 #include <machine/smp.h>
57 #include <machine/stdarg.h>
58
59 #include <machine/xen/synch_bitops.h>
60 #include <machine/xen/xen-os.h>
61
62 #include <xen/xen-os.h>
63 #include <xen/hvm.h>
64 #include <xen/hypervisor.h>
65 #include <xen/xen_intr.h>
66 #include <xen/evtchn/evtchnvar.h>
67
68 #include <dev/xen/xenpci/xenpcivar.h>
69 #include <dev/pci/pcivar.h>
70
71 #ifdef DDB
72 #include <ddb/ddb.h>
73 #endif
74
75 static MALLOC_DEFINE(M_XENINTR, "xen_intr", "Xen Interrupt Services");
76
77 static u_int first_evtchn_irq;
78
79 /**
80  * Per-cpu event channel processing state.
81  */
82 struct xen_intr_pcpu_data {
83         /**
84          * The last event channel bitmap section (level one bit) processed.
85          * This is used to ensure we scan all ports before
86          * servicing an already servied port again.
87          */
88         u_int   last_processed_l1i;
89
90         /**
91          * The last event channel processed within the event channel
92          * bitmap being scanned.
93          */
94         u_int   last_processed_l2i;
95
96         /** Pointer to this CPU's interrupt statistic counter. */
97         u_long *evtchn_intrcnt;
98
99         /**
100          * A bitmap of ports that can be serviced from this CPU.
101          * A set bit means interrupt handling is enabled.
102          */
103         u_long  evtchn_enabled[sizeof(u_long) * 8];
104 };
105
106 /*
107  * Start the scan at port 0 by initializing the last scanned
108  * location as the highest numbered event channel port.
109  */
110 DPCPU_DEFINE_STATIC(struct xen_intr_pcpu_data, xen_intr_pcpu) = {
111         .last_processed_l1i = LONG_BIT - 1,
112         .last_processed_l2i = LONG_BIT - 1
113 };
114
115 DPCPU_DECLARE(struct vcpu_info *, vcpu_info);
116
117 #define XEN_EEXIST              17 /* Xen "already exists" error */
118 #define XEN_ALLOCATE_VECTOR     0 /* Allocate a vector for this event channel */
119 #define XEN_INVALID_EVTCHN      0 /* Invalid event channel */
120
121 #define is_valid_evtchn(x)      ((x) != XEN_INVALID_EVTCHN)
122
123 struct xenisrc {
124         struct intsrc   xi_intsrc;
125         enum evtchn_type xi_type;
126         int             xi_cpu;         /* VCPU for delivery. */
127         int             xi_vector;      /* Global isrc vector number. */
128         evtchn_port_t   xi_port;
129         int             xi_pirq;
130         int             xi_virq;
131         void            *xi_cookie;
132         u_int           xi_close:1;     /* close on unbind? */
133         u_int           xi_activehi:1;
134         u_int           xi_edgetrigger:1;
135         u_int           xi_masked:1;
136         volatile u_int  xi_refcount;
137 };
138
139 static void     xen_intr_suspend(struct pic *);
140 static void     xen_intr_resume(struct pic *, bool suspend_cancelled);
141 static void     xen_intr_enable_source(struct intsrc *isrc);
142 static void     xen_intr_disable_source(struct intsrc *isrc, int eoi);
143 static void     xen_intr_eoi_source(struct intsrc *isrc);
144 static void     xen_intr_enable_intr(struct intsrc *isrc);
145 static void     xen_intr_disable_intr(struct intsrc *isrc);
146 static int      xen_intr_vector(struct intsrc *isrc);
147 static int      xen_intr_source_pending(struct intsrc *isrc);
148 static int      xen_intr_config_intr(struct intsrc *isrc,
149                      enum intr_trigger trig, enum intr_polarity pol);
150 static int      xen_intr_assign_cpu(struct intsrc *isrc, u_int apic_id);
151
152 static void     xen_intr_pirq_enable_source(struct intsrc *isrc);
153 static void     xen_intr_pirq_disable_source(struct intsrc *isrc, int eoi);
154 static void     xen_intr_pirq_eoi_source(struct intsrc *isrc);
155 static void     xen_intr_pirq_enable_intr(struct intsrc *isrc);
156 static void     xen_intr_pirq_disable_intr(struct intsrc *isrc);
157 static int      xen_intr_pirq_config_intr(struct intsrc *isrc,
158                      enum intr_trigger trig, enum intr_polarity pol);
159
160 /**
161  * PIC interface for all event channel port types except physical IRQs.
162  */
163 struct pic xen_intr_pic = {
164         .pic_enable_source  = xen_intr_enable_source,
165         .pic_disable_source = xen_intr_disable_source,
166         .pic_eoi_source     = xen_intr_eoi_source,
167         .pic_enable_intr    = xen_intr_enable_intr,
168         .pic_disable_intr   = xen_intr_disable_intr,
169         .pic_vector         = xen_intr_vector,
170         .pic_source_pending = xen_intr_source_pending,
171         .pic_suspend        = xen_intr_suspend,
172         .pic_resume         = xen_intr_resume,
173         .pic_config_intr    = xen_intr_config_intr,
174         .pic_assign_cpu     = xen_intr_assign_cpu
175 };
176
177 /**
178  * PIC interface for all event channel representing
179  * physical interrupt sources.
180  */
181 struct pic xen_intr_pirq_pic = {
182 #ifdef __amd64__
183         .pic_register_sources = xenpv_register_pirqs,
184 #endif
185         .pic_enable_source  = xen_intr_pirq_enable_source,
186         .pic_disable_source = xen_intr_pirq_disable_source,
187         .pic_eoi_source     = xen_intr_pirq_eoi_source,
188         .pic_enable_intr    = xen_intr_pirq_enable_intr,
189         .pic_disable_intr   = xen_intr_pirq_disable_intr,
190         .pic_vector         = xen_intr_vector,
191         .pic_source_pending = xen_intr_source_pending,
192         .pic_config_intr    = xen_intr_pirq_config_intr,
193         .pic_assign_cpu     = xen_intr_assign_cpu
194 };
195
196 static struct mtx        xen_intr_isrc_lock;
197 static u_int             xen_intr_auto_vector_count;
198 static struct xenisrc   *xen_intr_port_to_isrc[NR_EVENT_CHANNELS];
199 static u_long           *xen_intr_pirq_eoi_map;
200 static boolean_t         xen_intr_pirq_eoi_map_enabled;
201
202 /*------------------------- Private Functions --------------------------------*/
203 /**
204  * Disable signal delivery for an event channel port on the
205  * specified CPU.
206  *
207  * \param port  The event channel port to mask.
208  *
209  * This API is used to manage the port<=>CPU binding of event
210  * channel handlers.
211  *
212  * \note  This operation does not preclude reception of an event
213  *        for this event channel on another CPU.  To mask the
214  *        event channel globally, use evtchn_mask().
215  */
216 static inline void
217 evtchn_cpu_mask_port(u_int cpu, evtchn_port_t port)
218 {
219         struct xen_intr_pcpu_data *pcpu;
220
221         pcpu = DPCPU_ID_PTR(cpu, xen_intr_pcpu);
222         xen_clear_bit(port, pcpu->evtchn_enabled);
223 }
224
225 /**
226  * Enable signal delivery for an event channel port on the
227  * specified CPU.
228  *
229  * \param port  The event channel port to unmask.
230  *
231  * This API is used to manage the port<=>CPU binding of event
232  * channel handlers.
233  *
234  * \note  This operation does not guarantee that event delivery
235  *        is enabled for this event channel port.  The port must
236  *        also be globally enabled.  See evtchn_unmask().
237  */
238 static inline void
239 evtchn_cpu_unmask_port(u_int cpu, evtchn_port_t port)
240 {
241         struct xen_intr_pcpu_data *pcpu;
242
243         pcpu = DPCPU_ID_PTR(cpu, xen_intr_pcpu);
244         xen_set_bit(port, pcpu->evtchn_enabled);
245 }
246
247 /**
248  * Allocate and register a per-cpu Xen upcall interrupt counter.
249  *
250  * \param cpu  The cpu for which to register this interrupt count.
251  */
252 static void
253 xen_intr_intrcnt_add(u_int cpu)
254 {
255         char buf[MAXCOMLEN + 1];
256         struct xen_intr_pcpu_data *pcpu;
257
258         pcpu = DPCPU_ID_PTR(cpu, xen_intr_pcpu);
259         if (pcpu->evtchn_intrcnt != NULL)
260                 return;
261
262         snprintf(buf, sizeof(buf), "cpu%d:xen", cpu);
263         intrcnt_add(buf, &pcpu->evtchn_intrcnt);
264 }
265
266 /**
267  * Search for an already allocated but currently unused Xen interrupt
268  * source object.
269  *
270  * \param type  Restrict the search to interrupt sources of the given
271  *              type.
272  *
273  * \return  A pointer to a free Xen interrupt source object or NULL.
274  */
275 static struct xenisrc *
276 xen_intr_find_unused_isrc(enum evtchn_type type)
277 {
278         int isrc_idx;
279
280         KASSERT(mtx_owned(&xen_intr_isrc_lock), ("Evtchn isrc lock not held"));
281
282         for (isrc_idx = 0; isrc_idx < xen_intr_auto_vector_count; isrc_idx ++) {
283                 struct xenisrc *isrc;
284                 u_int vector;
285
286                 vector = first_evtchn_irq + isrc_idx;
287                 isrc = (struct xenisrc *)intr_lookup_source(vector);
288                 if (isrc != NULL
289                  && isrc->xi_type == EVTCHN_TYPE_UNBOUND) {
290                         KASSERT(isrc->xi_intsrc.is_handlers == 0,
291                             ("Free evtchn still has handlers"));
292                         isrc->xi_type = type;
293                         return (isrc);
294                 }
295         }
296         return (NULL);
297 }
298
299 /**
300  * Allocate a Xen interrupt source object.
301  *
302  * \param type  The type of interrupt source to create.
303  *
304  * \return  A pointer to a newly allocated Xen interrupt source
305  *          object or NULL.
306  */
307 static struct xenisrc *
308 xen_intr_alloc_isrc(enum evtchn_type type, int vector)
309 {
310         static int warned;
311         struct xenisrc *isrc;
312
313         KASSERT(mtx_owned(&xen_intr_isrc_lock), ("Evtchn alloc lock not held"));
314
315         if (xen_intr_auto_vector_count > NR_EVENT_CHANNELS) {
316                 if (!warned) {
317                         warned = 1;
318                         printf("xen_intr_alloc: Event channels exhausted.\n");
319                 }
320                 return (NULL);
321         }
322
323         if (type != EVTCHN_TYPE_PIRQ) {
324                 vector = first_evtchn_irq + xen_intr_auto_vector_count;
325                 xen_intr_auto_vector_count++;
326         }
327
328         KASSERT((intr_lookup_source(vector) == NULL),
329             ("Trying to use an already allocated vector"));
330
331         mtx_unlock(&xen_intr_isrc_lock);
332         isrc = malloc(sizeof(*isrc), M_XENINTR, M_WAITOK | M_ZERO);
333         isrc->xi_intsrc.is_pic =
334             (type == EVTCHN_TYPE_PIRQ) ? &xen_intr_pirq_pic : &xen_intr_pic;
335         isrc->xi_vector = vector;
336         isrc->xi_type = type;
337         intr_register_source(&isrc->xi_intsrc);
338         mtx_lock(&xen_intr_isrc_lock);
339
340         return (isrc);
341 }
342
343 /**
344  * Attempt to free an active Xen interrupt source object.
345  *
346  * \param isrc  The interrupt source object to release.
347  *
348  * \returns  EBUSY if the source is still in use, otherwise 0.
349  */
350 static int
351 xen_intr_release_isrc(struct xenisrc *isrc)
352 {
353
354         mtx_lock(&xen_intr_isrc_lock);
355         KASSERT(isrc->xi_intsrc.is_handlers == 0,
356             ("Release called, but xenisrc still in use"));
357         evtchn_mask_port(isrc->xi_port);
358         evtchn_clear_port(isrc->xi_port);
359
360         /* Rebind port to CPU 0. */
361         evtchn_cpu_mask_port(isrc->xi_cpu, isrc->xi_port);
362         evtchn_cpu_unmask_port(0, isrc->xi_port);
363
364         if (isrc->xi_close != 0 && is_valid_evtchn(isrc->xi_port)) {
365                 struct evtchn_close close = { .port = isrc->xi_port };
366                 if (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close))
367                         panic("EVTCHNOP_close failed");
368         }
369
370         xen_intr_port_to_isrc[isrc->xi_port] = NULL;
371         isrc->xi_cpu = 0;
372         isrc->xi_type = EVTCHN_TYPE_UNBOUND;
373         isrc->xi_port = 0;
374         isrc->xi_cookie = NULL;
375         mtx_unlock(&xen_intr_isrc_lock);
376         return (0);
377 }
378
379 /**
380  * Associate an interrupt handler with an already allocated local Xen
381  * event channel port.
382  *
383  * \param isrcp       The returned Xen interrupt object associated with
384  *                    the specified local port.
385  * \param local_port  The event channel to bind.
386  * \param type        The event channel type of local_port.
387  * \param intr_owner  The device making this bind request.
388  * \param filter      An interrupt filter handler.  Specify NULL
389  *                    to always dispatch to the ithread handler.
390  * \param handler     An interrupt ithread handler.  Optional (can
391  *                    specify NULL) if all necessary event actions
392  *                    are performed by filter.
393  * \param arg         Argument to present to both filter and handler.
394  * \param irqflags    Interrupt handler flags.  See sys/bus.h.
395  * \param handlep     Pointer to an opaque handle used to manage this
396  *                    registration.
397  *
398  * \returns  0 on success, otherwise an errno.
399  */
400 static int
401 xen_intr_bind_isrc(struct xenisrc **isrcp, evtchn_port_t local_port,
402     enum evtchn_type type, const char *intr_owner, driver_filter_t filter,
403     driver_intr_t handler, void *arg, enum intr_type flags,
404     xen_intr_handle_t *port_handlep)
405 {
406         struct xenisrc *isrc;
407         int error;
408
409         *isrcp = NULL;
410         if (port_handlep == NULL) {
411                 printf("%s: xen_intr_bind_isrc: Bad event handle\n",
412                     intr_owner);
413                 return (EINVAL);
414         }
415
416         mtx_lock(&xen_intr_isrc_lock);
417         isrc = xen_intr_find_unused_isrc(type);
418         if (isrc == NULL) {
419                 isrc = xen_intr_alloc_isrc(type, XEN_ALLOCATE_VECTOR);
420                 if (isrc == NULL) {
421                         mtx_unlock(&xen_intr_isrc_lock);
422                         return (ENOSPC);
423                 }
424         }
425         isrc->xi_port = local_port;
426         xen_intr_port_to_isrc[local_port] = isrc;
427         refcount_init(&isrc->xi_refcount, 1);
428         mtx_unlock(&xen_intr_isrc_lock);
429
430         /* Assign the opaque handler (the event channel port) */
431         *port_handlep = &isrc->xi_vector;
432
433 #ifdef SMP
434         if (type == EVTCHN_TYPE_PORT) {
435                 /*
436                  * By default all interrupts are assigned to vCPU#0
437                  * unless specified otherwise, so shuffle them to balance
438                  * the interrupt load.
439                  */
440                 xen_intr_assign_cpu(&isrc->xi_intsrc, intr_next_cpu(0));
441         }
442 #endif
443
444         if (filter == NULL && handler == NULL) {
445                 /*
446                  * No filter/handler provided, leave the event channel
447                  * masked and without a valid handler, the caller is
448                  * in charge of setting that up.
449                  */
450                 *isrcp = isrc;
451                 return (0);
452         }
453
454         error = xen_intr_add_handler(intr_owner, filter, handler, arg, flags,
455             *port_handlep);
456         if (error != 0) {
457                 xen_intr_release_isrc(isrc);
458                 return (error);
459         }
460         *isrcp = isrc;
461         return (0);
462 }
463
464 /**
465  * Lookup a Xen interrupt source object given an interrupt binding handle.
466  * 
467  * \param handle  A handle initialized by a previous call to
468  *                xen_intr_bind_isrc().
469  *
470  * \returns  A pointer to the Xen interrupt source object associated
471  *           with the given interrupt handle.  NULL if no association
472  *           currently exists.
473  */
474 static struct xenisrc *
475 xen_intr_isrc(xen_intr_handle_t handle)
476 {
477         int vector;
478
479         if (handle == NULL)
480                 return (NULL);
481
482         vector = *(int *)handle;
483         KASSERT(vector >= first_evtchn_irq &&
484             vector < (first_evtchn_irq + xen_intr_auto_vector_count),
485             ("Xen interrupt vector is out of range"));
486
487         return ((struct xenisrc *)intr_lookup_source(vector));
488 }
489
490 /**
491  * Determine the event channel ports at the given section of the
492  * event port bitmap which have pending events for the given cpu.
493  * 
494  * \param pcpu  The Xen interrupt pcpu data for the cpu being querried.
495  * \param sh    The Xen shared info area.
496  * \param idx   The index of the section of the event channel bitmap to
497  *              inspect.
498  *
499  * \returns  A u_long with bits set for every event channel with pending
500  *           events.
501  */
502 static inline u_long
503 xen_intr_active_ports(struct xen_intr_pcpu_data *pcpu, shared_info_t *sh,
504     u_int idx)
505 {
506
507         CTASSERT(sizeof(sh->evtchn_mask[0]) == sizeof(sh->evtchn_pending[0]));
508         CTASSERT(sizeof(sh->evtchn_mask[0]) == sizeof(pcpu->evtchn_enabled[0]));
509         CTASSERT(sizeof(sh->evtchn_mask) == sizeof(sh->evtchn_pending));
510         CTASSERT(sizeof(sh->evtchn_mask) == sizeof(pcpu->evtchn_enabled));
511         return (sh->evtchn_pending[idx]
512               & ~sh->evtchn_mask[idx]
513               & pcpu->evtchn_enabled[idx]);
514 }
515
516 /**
517  * Interrupt handler for processing all Xen event channel events.
518  * 
519  * \param trap_frame  The trap frame context for the current interrupt.
520  */
521 void
522 xen_intr_handle_upcall(struct trapframe *trap_frame)
523 {
524         u_int l1i, l2i, port, cpu;
525         u_long masked_l1, masked_l2;
526         struct xenisrc *isrc;
527         shared_info_t *s;
528         vcpu_info_t *v;
529         struct xen_intr_pcpu_data *pc;
530         u_long l1, l2;
531
532         /*
533          * Disable preemption in order to always check and fire events
534          * on the right vCPU
535          */
536         critical_enter();
537
538         cpu = PCPU_GET(cpuid);
539         pc  = DPCPU_PTR(xen_intr_pcpu);
540         s   = HYPERVISOR_shared_info;
541         v   = DPCPU_GET(vcpu_info);
542
543         if (xen_hvm_domain() && !xen_vector_callback_enabled) {
544                 KASSERT((cpu == 0), ("Fired PCI event callback on wrong CPU"));
545         }
546
547         v->evtchn_upcall_pending = 0;
548
549 #if 0
550 #ifndef CONFIG_X86 /* No need for a barrier -- XCHG is a barrier on x86. */
551         /* Clear master flag /before/ clearing selector flag. */
552         wmb();
553 #endif
554 #endif
555
556         l1 = atomic_readandclear_long(&v->evtchn_pending_sel);
557
558         l1i = pc->last_processed_l1i;
559         l2i = pc->last_processed_l2i;
560         (*pc->evtchn_intrcnt)++;
561
562         while (l1 != 0) {
563
564                 l1i = (l1i + 1) % LONG_BIT;
565                 masked_l1 = l1 & ((~0UL) << l1i);
566
567                 if (masked_l1 == 0) {
568                         /*
569                          * if we masked out all events, wrap around
570                          * to the beginning.
571                          */
572                         l1i = LONG_BIT - 1;
573                         l2i = LONG_BIT - 1;
574                         continue;
575                 }
576                 l1i = ffsl(masked_l1) - 1;
577
578                 do {
579                         l2 = xen_intr_active_ports(pc, s, l1i);
580
581                         l2i = (l2i + 1) % LONG_BIT;
582                         masked_l2 = l2 & ((~0UL) << l2i);
583
584                         if (masked_l2 == 0) {
585                                 /* if we masked out all events, move on */
586                                 l2i = LONG_BIT - 1;
587                                 break;
588                         }
589                         l2i = ffsl(masked_l2) - 1;
590
591                         /* process port */
592                         port = (l1i * LONG_BIT) + l2i;
593                         synch_clear_bit(port, &s->evtchn_pending[0]);
594
595                         isrc = xen_intr_port_to_isrc[port];
596                         if (__predict_false(isrc == NULL))
597                                 continue;
598
599                         /* Make sure we are firing on the right vCPU */
600                         KASSERT((isrc->xi_cpu == PCPU_GET(cpuid)),
601                                 ("Received unexpected event on vCPU#%d, event bound to vCPU#%d",
602                                 PCPU_GET(cpuid), isrc->xi_cpu));
603
604                         intr_execute_handlers(&isrc->xi_intsrc, trap_frame);
605
606                         /*
607                          * If this is the final port processed,
608                          * we'll pick up here+1 next time.
609                          */
610                         pc->last_processed_l1i = l1i;
611                         pc->last_processed_l2i = l2i;
612
613                 } while (l2i != LONG_BIT - 1);
614
615                 l2 = xen_intr_active_ports(pc, s, l1i);
616                 if (l2 == 0) {
617                         /*
618                          * We handled all ports, so we can clear the
619                          * selector bit.
620                          */
621                         l1 &= ~(1UL << l1i);
622                 }
623         }
624
625         if (xen_evtchn_needs_ack)
626                 lapic_eoi();
627
628         critical_exit();
629 }
630
631 static int
632 xen_intr_init(void *dummy __unused)
633 {
634         shared_info_t *s = HYPERVISOR_shared_info;
635         struct xen_intr_pcpu_data *pcpu;
636         struct physdev_pirq_eoi_gmfn eoi_gmfn;
637         int i, rc;
638
639         if (!xen_domain())
640                 return (0);
641
642         mtx_init(&xen_intr_isrc_lock, "xen-irq-lock", NULL, MTX_DEF);
643
644         /*
645          * Set the per-cpu mask of CPU#0 to enable all, since by default all
646          * event channels are bound to CPU#0.
647          */
648         CPU_FOREACH(i) {
649                 pcpu = DPCPU_ID_PTR(i, xen_intr_pcpu);
650                 memset(pcpu->evtchn_enabled, i == 0 ? ~0 : 0,
651                     sizeof(pcpu->evtchn_enabled));
652         }
653
654         for (i = 0; i < nitems(s->evtchn_mask); i++)
655                 atomic_store_rel_long(&s->evtchn_mask[i], ~0);
656
657         /* Try to register PIRQ EOI map */
658         xen_intr_pirq_eoi_map = malloc(PAGE_SIZE, M_XENINTR, M_WAITOK | M_ZERO);
659         eoi_gmfn.gmfn = atop(vtophys(xen_intr_pirq_eoi_map));
660         rc = HYPERVISOR_physdev_op(PHYSDEVOP_pirq_eoi_gmfn_v2, &eoi_gmfn);
661         if (rc != 0 && bootverbose)
662                 printf("Xen interrupts: unable to register PIRQ EOI map\n");
663         else
664                 xen_intr_pirq_eoi_map_enabled = true;
665
666         intr_register_pic(&xen_intr_pic);
667         if (xen_pv_domain() && xen_initial_domain())
668                 intr_register_pic(&xen_intr_pirq_pic);
669
670         if (bootverbose)
671                 printf("Xen interrupt system initialized\n");
672
673         return (0);
674 }
675 SYSINIT(xen_intr_init, SI_SUB_INTR, SI_ORDER_SECOND, xen_intr_init, NULL);
676
677 static void
678 xen_intrcnt_init(void *dummy __unused)
679 {
680         unsigned int i;
681
682         if (!xen_domain())
683                 return;
684
685         /*
686          * Register interrupt count manually as we aren't guaranteed to see a
687          * call to xen_intr_assign_cpu() before our first interrupt.
688          */
689         CPU_FOREACH(i)
690                 xen_intr_intrcnt_add(i);
691 }
692 SYSINIT(xen_intrcnt_init, SI_SUB_INTR, SI_ORDER_MIDDLE, xen_intrcnt_init, NULL);
693
694 void
695 xen_intr_alloc_irqs(void)
696 {
697
698         if (num_io_irqs > UINT_MAX - NR_EVENT_CHANNELS)
699                 panic("IRQ allocation overflow (num_msi_irqs too high?)");
700         first_evtchn_irq = num_io_irqs;
701         num_io_irqs += NR_EVENT_CHANNELS;
702 }
703
704 /*--------------------------- Common PIC Functions ---------------------------*/
705 /**
706  * Prepare this PIC for system suspension.
707  */
708 static void
709 xen_intr_suspend(struct pic *unused)
710 {
711 }
712
713 static void
714 xen_rebind_ipi(struct xenisrc *isrc)
715 {
716 #ifdef SMP
717         int cpu = isrc->xi_cpu;
718         int vcpu_id = pcpu_find(cpu)->pc_vcpu_id;
719         int error;
720         struct evtchn_bind_ipi bind_ipi = { .vcpu = vcpu_id };
721
722         error = HYPERVISOR_event_channel_op(EVTCHNOP_bind_ipi,
723                                             &bind_ipi);
724         if (error != 0)
725                 panic("unable to rebind xen IPI: %d", error);
726
727         isrc->xi_port = bind_ipi.port;
728         isrc->xi_cpu = 0;
729         xen_intr_port_to_isrc[bind_ipi.port] = isrc;
730
731         error = xen_intr_assign_cpu(&isrc->xi_intsrc,
732                                     cpu_apic_ids[cpu]);
733         if (error)
734                 panic("unable to bind xen IPI to CPU#%d: %d",
735                       cpu, error);
736
737         evtchn_unmask_port(bind_ipi.port);
738 #else
739         panic("Resume IPI event channel on UP");
740 #endif
741 }
742
743 static void
744 xen_rebind_virq(struct xenisrc *isrc)
745 {
746         int cpu = isrc->xi_cpu;
747         int vcpu_id = pcpu_find(cpu)->pc_vcpu_id;
748         int error;
749         struct evtchn_bind_virq bind_virq = { .virq = isrc->xi_virq,
750                                               .vcpu = vcpu_id };
751
752         error = HYPERVISOR_event_channel_op(EVTCHNOP_bind_virq,
753                                             &bind_virq);
754         if (error != 0)
755                 panic("unable to rebind xen VIRQ#%d: %d", isrc->xi_virq, error);
756
757         isrc->xi_port = bind_virq.port;
758         isrc->xi_cpu = 0;
759         xen_intr_port_to_isrc[bind_virq.port] = isrc;
760
761 #ifdef SMP
762         error = xen_intr_assign_cpu(&isrc->xi_intsrc,
763                                     cpu_apic_ids[cpu]);
764         if (error)
765                 panic("unable to bind xen VIRQ#%d to CPU#%d: %d",
766                       isrc->xi_virq, cpu, error);
767 #endif
768
769         evtchn_unmask_port(bind_virq.port);
770 }
771
772 /**
773  * Return this PIC to service after being suspended.
774  */
775 static void
776 xen_intr_resume(struct pic *unused, bool suspend_cancelled)
777 {
778         shared_info_t *s = HYPERVISOR_shared_info;
779         struct xenisrc *isrc;
780         u_int isrc_idx;
781         int i;
782
783         if (suspend_cancelled)
784                 return;
785
786         /* Reset the per-CPU masks */
787         CPU_FOREACH(i) {
788                 struct xen_intr_pcpu_data *pcpu;
789
790                 pcpu = DPCPU_ID_PTR(i, xen_intr_pcpu);
791                 memset(pcpu->evtchn_enabled, i == 0 ? ~0 : 0,
792                     sizeof(pcpu->evtchn_enabled));
793         }
794
795         /* Mask all event channels. */
796         for (i = 0; i < nitems(s->evtchn_mask); i++)
797                 atomic_store_rel_long(&s->evtchn_mask[i], ~0);
798
799         /* Remove port -> isrc mappings */
800         memset(xen_intr_port_to_isrc, 0, sizeof(xen_intr_port_to_isrc));
801
802         /* Free unused isrcs and rebind VIRQs and IPIs */
803         for (isrc_idx = 0; isrc_idx < xen_intr_auto_vector_count; isrc_idx++) {
804                 u_int vector;
805
806                 vector = first_evtchn_irq + isrc_idx;
807                 isrc = (struct xenisrc *)intr_lookup_source(vector);
808                 if (isrc != NULL) {
809                         isrc->xi_port = 0;
810                         switch (isrc->xi_type) {
811                         case EVTCHN_TYPE_IPI:
812                                 xen_rebind_ipi(isrc);
813                                 break;
814                         case EVTCHN_TYPE_VIRQ:
815                                 xen_rebind_virq(isrc);
816                                 break;
817                         default:
818                                 break;
819                         }
820                 }
821         }
822 }
823
824 /**
825  * Disable a Xen interrupt source.
826  *
827  * \param isrc  The interrupt source to disable.
828  */
829 static void
830 xen_intr_disable_intr(struct intsrc *base_isrc)
831 {
832         struct xenisrc *isrc = (struct xenisrc *)base_isrc;
833
834         evtchn_mask_port(isrc->xi_port);
835 }
836
837 /**
838  * Determine the global interrupt vector number for
839  * a Xen interrupt source.
840  *
841  * \param isrc  The interrupt source to query.
842  *
843  * \return  The vector number corresponding to the given interrupt source.
844  */
845 static int
846 xen_intr_vector(struct intsrc *base_isrc)
847 {
848         struct xenisrc *isrc = (struct xenisrc *)base_isrc;
849
850         return (isrc->xi_vector);
851 }
852
853 /**
854  * Determine whether or not interrupt events are pending on the
855  * the given interrupt source.
856  *
857  * \param isrc  The interrupt source to query.
858  *
859  * \returns  0 if no events are pending, otherwise non-zero.
860  */
861 static int
862 xen_intr_source_pending(struct intsrc *isrc)
863 {
864         /*
865          * EventChannels are edge triggered and never masked.
866          * There can be no pending events.
867          */
868         return (0);
869 }
870
871 /**
872  * Perform configuration of an interrupt source.
873  *
874  * \param isrc  The interrupt source to configure.
875  * \param trig  Edge or level.
876  * \param pol   Active high or low.
877  *
878  * \returns  0 if no events are pending, otherwise non-zero.
879  */
880 static int
881 xen_intr_config_intr(struct intsrc *isrc, enum intr_trigger trig,
882     enum intr_polarity pol)
883 {
884         /* Configuration is only possible via the evtchn apis. */
885         return (ENODEV);
886 }
887
888 /**
889  * Configure CPU affinity for interrupt source event delivery.
890  *
891  * \param isrc     The interrupt source to configure.
892  * \param apic_id  The apic id of the CPU for handling future events.
893  *
894  * \returns  0 if successful, otherwise an errno.
895  */
896 static int
897 xen_intr_assign_cpu(struct intsrc *base_isrc, u_int apic_id)
898 {
899 #ifdef SMP
900         struct evtchn_bind_vcpu bind_vcpu;
901         struct xenisrc *isrc;
902         u_int to_cpu, vcpu_id;
903         int error, masked;
904
905         if (xen_vector_callback_enabled == 0)
906                 return (EOPNOTSUPP);
907
908         to_cpu = apic_cpuid(apic_id);
909         vcpu_id = pcpu_find(to_cpu)->pc_vcpu_id;
910
911         mtx_lock(&xen_intr_isrc_lock);
912         isrc = (struct xenisrc *)base_isrc;
913         if (!is_valid_evtchn(isrc->xi_port)) {
914                 mtx_unlock(&xen_intr_isrc_lock);
915                 return (EINVAL);
916         }
917
918         /*
919          * Mask the event channel while binding it to prevent interrupt
920          * delivery with an inconsistent state in isrc->xi_cpu.
921          */
922         masked = evtchn_test_and_set_mask(isrc->xi_port);
923         if ((isrc->xi_type == EVTCHN_TYPE_VIRQ) ||
924                 (isrc->xi_type == EVTCHN_TYPE_IPI)) {
925                 /*
926                  * Virtual IRQs are associated with a cpu by
927                  * the Hypervisor at evtchn_bind_virq time, so
928                  * all we need to do is update the per-CPU masks.
929                  */
930                 evtchn_cpu_mask_port(isrc->xi_cpu, isrc->xi_port);
931                 isrc->xi_cpu = to_cpu;
932                 evtchn_cpu_unmask_port(isrc->xi_cpu, isrc->xi_port);
933                 goto out;
934         }
935
936         bind_vcpu.port = isrc->xi_port;
937         bind_vcpu.vcpu = vcpu_id;
938
939         error = HYPERVISOR_event_channel_op(EVTCHNOP_bind_vcpu, &bind_vcpu);
940         if (isrc->xi_cpu != to_cpu) {
941                 if (error == 0) {
942                         /* Commit to new binding by removing the old one. */
943                         evtchn_cpu_mask_port(isrc->xi_cpu, isrc->xi_port);
944                         isrc->xi_cpu = to_cpu;
945                         evtchn_cpu_unmask_port(isrc->xi_cpu, isrc->xi_port);
946                 }
947         }
948
949 out:
950         if (masked == 0)
951                 evtchn_unmask_port(isrc->xi_port);
952         mtx_unlock(&xen_intr_isrc_lock);
953         return (0);
954 #else
955         return (EOPNOTSUPP);
956 #endif
957 }
958
959 /*------------------- Virtual Interrupt Source PIC Functions -----------------*/
960 /*
961  * Mask a level triggered interrupt source.
962  *
963  * \param isrc  The interrupt source to mask (if necessary).
964  * \param eoi   If non-zero, perform any necessary end-of-interrupt
965  *              acknowledgements.
966  */
967 static void
968 xen_intr_disable_source(struct intsrc *base_isrc, int eoi)
969 {
970         struct xenisrc *isrc;
971
972         isrc = (struct xenisrc *)base_isrc;
973
974         /*
975          * NB: checking if the event channel is already masked is
976          * needed because the event channel user-space device
977          * masks event channels on its filter as part of its
978          * normal operation, and those shouldn't be automatically
979          * unmasked by the generic interrupt code. The event channel
980          * device will unmask them when needed.
981          */
982         isrc->xi_masked = !!evtchn_test_and_set_mask(isrc->xi_port);
983 }
984
985 /*
986  * Unmask a level triggered interrupt source.
987  *
988  * \param isrc  The interrupt source to unmask (if necessary).
989  */
990 static void
991 xen_intr_enable_source(struct intsrc *base_isrc)
992 {
993         struct xenisrc *isrc;
994
995         isrc = (struct xenisrc *)base_isrc;
996
997         if (isrc->xi_masked == 0)
998                 evtchn_unmask_port(isrc->xi_port);
999 }
1000
1001 /*
1002  * Perform any necessary end-of-interrupt acknowledgements.
1003  *
1004  * \param isrc  The interrupt source to EOI.
1005  */
1006 static void
1007 xen_intr_eoi_source(struct intsrc *base_isrc)
1008 {
1009 }
1010
1011 /*
1012  * Enable and unmask the interrupt source.
1013  *
1014  * \param isrc  The interrupt source to enable.
1015  */
1016 static void
1017 xen_intr_enable_intr(struct intsrc *base_isrc)
1018 {
1019         struct xenisrc *isrc = (struct xenisrc *)base_isrc;
1020
1021         evtchn_unmask_port(isrc->xi_port);
1022 }
1023
1024 /*------------------ Physical Interrupt Source PIC Functions -----------------*/
1025 /*
1026  * Mask a level triggered interrupt source.
1027  *
1028  * \param isrc  The interrupt source to mask (if necessary).
1029  * \param eoi   If non-zero, perform any necessary end-of-interrupt
1030  *              acknowledgements.
1031  */
1032 static void
1033 xen_intr_pirq_disable_source(struct intsrc *base_isrc, int eoi)
1034 {
1035         struct xenisrc *isrc;
1036
1037         isrc = (struct xenisrc *)base_isrc;
1038
1039         if (isrc->xi_edgetrigger == 0)
1040                 evtchn_mask_port(isrc->xi_port);
1041         if (eoi == PIC_EOI)
1042                 xen_intr_pirq_eoi_source(base_isrc);
1043 }
1044
1045 /*
1046  * Unmask a level triggered interrupt source.
1047  *
1048  * \param isrc  The interrupt source to unmask (if necessary).
1049  */
1050 static void
1051 xen_intr_pirq_enable_source(struct intsrc *base_isrc)
1052 {
1053         struct xenisrc *isrc;
1054
1055         isrc = (struct xenisrc *)base_isrc;
1056
1057         if (isrc->xi_edgetrigger == 0)
1058                 evtchn_unmask_port(isrc->xi_port);
1059 }
1060
1061 /*
1062  * Perform any necessary end-of-interrupt acknowledgements.
1063  *
1064  * \param isrc  The interrupt source to EOI.
1065  */
1066 static void
1067 xen_intr_pirq_eoi_source(struct intsrc *base_isrc)
1068 {
1069         struct xenisrc *isrc;
1070         int error;
1071
1072         isrc = (struct xenisrc *)base_isrc;
1073
1074         if (xen_test_bit(isrc->xi_pirq, xen_intr_pirq_eoi_map)) {
1075                 struct physdev_eoi eoi = { .irq = isrc->xi_pirq };
1076
1077                 error = HYPERVISOR_physdev_op(PHYSDEVOP_eoi, &eoi);
1078                 if (error != 0)
1079                         panic("Unable to EOI PIRQ#%d: %d\n",
1080                             isrc->xi_pirq, error);
1081         }
1082 }
1083
1084 /*
1085  * Enable and unmask the interrupt source.
1086  *
1087  * \param isrc  The interrupt source to enable.
1088  */
1089 static void
1090 xen_intr_pirq_enable_intr(struct intsrc *base_isrc)
1091 {
1092         struct xenisrc *isrc;
1093         struct evtchn_bind_pirq bind_pirq;
1094         struct physdev_irq_status_query irq_status;
1095         int error;
1096
1097         isrc = (struct xenisrc *)base_isrc;
1098
1099         if (!xen_intr_pirq_eoi_map_enabled) {
1100                 irq_status.irq = isrc->xi_pirq;
1101                 error = HYPERVISOR_physdev_op(PHYSDEVOP_irq_status_query,
1102                     &irq_status);
1103                 if (error)
1104                         panic("unable to get status of IRQ#%d", isrc->xi_pirq);
1105
1106                 if (irq_status.flags & XENIRQSTAT_needs_eoi) {
1107                         /*
1108                          * Since the dynamic PIRQ EOI map is not available
1109                          * mark the PIRQ as needing EOI unconditionally.
1110                          */
1111                         xen_set_bit(isrc->xi_pirq, xen_intr_pirq_eoi_map);
1112                 }
1113         }
1114
1115         bind_pirq.pirq = isrc->xi_pirq;
1116         bind_pirq.flags = isrc->xi_edgetrigger ? 0 : BIND_PIRQ__WILL_SHARE;
1117         error = HYPERVISOR_event_channel_op(EVTCHNOP_bind_pirq, &bind_pirq);
1118         if (error)
1119                 panic("unable to bind IRQ#%d", isrc->xi_pirq);
1120
1121         isrc->xi_port = bind_pirq.port;
1122
1123         mtx_lock(&xen_intr_isrc_lock);
1124         KASSERT((xen_intr_port_to_isrc[bind_pirq.port] == NULL),
1125             ("trying to override an already setup event channel port"));
1126         xen_intr_port_to_isrc[bind_pirq.port] = isrc;
1127         mtx_unlock(&xen_intr_isrc_lock);
1128
1129         evtchn_unmask_port(isrc->xi_port);
1130 }
1131
1132 /*
1133  * Disable an interrupt source.
1134  *
1135  * \param isrc  The interrupt source to disable.
1136  */
1137 static void
1138 xen_intr_pirq_disable_intr(struct intsrc *base_isrc)
1139 {
1140         struct xenisrc *isrc;
1141         struct evtchn_close close;
1142         int error;
1143
1144         isrc = (struct xenisrc *)base_isrc;
1145
1146         evtchn_mask_port(isrc->xi_port);
1147
1148         close.port = isrc->xi_port;
1149         error = HYPERVISOR_event_channel_op(EVTCHNOP_close, &close);
1150         if (error)
1151                 panic("unable to close event channel %d IRQ#%d",
1152                     isrc->xi_port, isrc->xi_pirq);
1153
1154         mtx_lock(&xen_intr_isrc_lock);
1155         xen_intr_port_to_isrc[isrc->xi_port] = NULL;
1156         mtx_unlock(&xen_intr_isrc_lock);
1157
1158         isrc->xi_port = 0;
1159 }
1160
1161 /**
1162  * Perform configuration of an interrupt source.
1163  *
1164  * \param isrc  The interrupt source to configure.
1165  * \param trig  Edge or level.
1166  * \param pol   Active high or low.
1167  *
1168  * \returns  0 if no events are pending, otherwise non-zero.
1169  */
1170 static int
1171 xen_intr_pirq_config_intr(struct intsrc *base_isrc, enum intr_trigger trig,
1172     enum intr_polarity pol)
1173 {
1174         struct xenisrc *isrc = (struct xenisrc *)base_isrc;
1175         struct physdev_setup_gsi setup_gsi;
1176         int error;
1177
1178         KASSERT(!(trig == INTR_TRIGGER_CONFORM || pol == INTR_POLARITY_CONFORM),
1179             ("%s: Conforming trigger or polarity\n", __func__));
1180
1181         setup_gsi.gsi = isrc->xi_pirq;
1182         setup_gsi.triggering = trig == INTR_TRIGGER_EDGE ? 0 : 1;
1183         setup_gsi.polarity = pol == INTR_POLARITY_HIGH ? 0 : 1;
1184
1185         error = HYPERVISOR_physdev_op(PHYSDEVOP_setup_gsi, &setup_gsi);
1186         if (error == -XEN_EEXIST) {
1187                 if ((isrc->xi_edgetrigger && (trig != INTR_TRIGGER_EDGE)) ||
1188                     (isrc->xi_activehi && (pol != INTR_POLARITY_HIGH)))
1189                         panic("unable to reconfigure interrupt IRQ#%d",
1190                             isrc->xi_pirq);
1191                 error = 0;
1192         }
1193         if (error)
1194                 panic("unable to configure IRQ#%d\n", isrc->xi_pirq);
1195
1196         isrc->xi_activehi = pol == INTR_POLARITY_HIGH ? 1 : 0;
1197         isrc->xi_edgetrigger = trig == INTR_TRIGGER_EDGE ? 1 : 0;
1198
1199         return (0);
1200 }
1201
1202 /*--------------------------- Public Functions -------------------------------*/
1203 /*------- API comments for these methods can be found in xen/xenintr.h -------*/
1204 int
1205 xen_intr_bind_local_port(device_t dev, evtchn_port_t local_port,
1206     driver_filter_t filter, driver_intr_t handler, void *arg,
1207     enum intr_type flags, xen_intr_handle_t *port_handlep)
1208 {
1209         struct xenisrc *isrc;
1210         int error;
1211
1212         error = xen_intr_bind_isrc(&isrc, local_port, EVTCHN_TYPE_PORT,
1213             device_get_nameunit(dev), filter, handler, arg, flags,
1214             port_handlep);
1215         if (error != 0)
1216                 return (error);
1217
1218         /*
1219          * The Event Channel API didn't open this port, so it is not
1220          * responsible for closing it automatically on unbind.
1221          */
1222         isrc->xi_close = 0;
1223         return (0);
1224 }
1225
1226 int
1227 xen_intr_alloc_and_bind_local_port(device_t dev, u_int remote_domain,
1228     driver_filter_t filter, driver_intr_t handler, void *arg,
1229     enum intr_type flags, xen_intr_handle_t *port_handlep)
1230 {
1231         struct xenisrc *isrc;
1232         struct evtchn_alloc_unbound alloc_unbound;
1233         int error;
1234
1235         alloc_unbound.dom        = DOMID_SELF;
1236         alloc_unbound.remote_dom = remote_domain;
1237         error = HYPERVISOR_event_channel_op(EVTCHNOP_alloc_unbound,
1238                     &alloc_unbound);
1239         if (error != 0) {
1240                 /*
1241                  * XXX Trap Hypercall error code Linuxisms in
1242                  *     the HYPERCALL layer.
1243                  */
1244                 return (-error);
1245         }
1246
1247         error = xen_intr_bind_isrc(&isrc, alloc_unbound.port, EVTCHN_TYPE_PORT,
1248             device_get_nameunit(dev), filter, handler, arg, flags,
1249             port_handlep);
1250         if (error != 0) {
1251                 evtchn_close_t close = { .port = alloc_unbound.port };
1252                 if (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close))
1253                         panic("EVTCHNOP_close failed");
1254                 return (error);
1255         }
1256
1257         isrc->xi_close = 1;
1258         return (0);
1259 }
1260
1261 int 
1262 xen_intr_bind_remote_port(device_t dev, u_int remote_domain,
1263     u_int remote_port, driver_filter_t filter, driver_intr_t handler,
1264     void *arg, enum intr_type flags, xen_intr_handle_t *port_handlep)
1265 {
1266         struct xenisrc *isrc;
1267         struct evtchn_bind_interdomain bind_interdomain;
1268         int error;
1269
1270         bind_interdomain.remote_dom  = remote_domain;
1271         bind_interdomain.remote_port = remote_port;
1272         error = HYPERVISOR_event_channel_op(EVTCHNOP_bind_interdomain,
1273                                             &bind_interdomain);
1274         if (error != 0) {
1275                 /*
1276                  * XXX Trap Hypercall error code Linuxisms in
1277                  *     the HYPERCALL layer.
1278                  */
1279                 return (-error);
1280         }
1281
1282         error = xen_intr_bind_isrc(&isrc, bind_interdomain.local_port,
1283             EVTCHN_TYPE_PORT, device_get_nameunit(dev), filter, handler, arg,
1284             flags, port_handlep);
1285         if (error) {
1286                 evtchn_close_t close = { .port = bind_interdomain.local_port };
1287                 if (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close))
1288                         panic("EVTCHNOP_close failed");
1289                 return (error);
1290         }
1291
1292         /*
1293          * The Event Channel API opened this port, so it is
1294          * responsible for closing it automatically on unbind.
1295          */
1296         isrc->xi_close = 1;
1297         return (0);
1298 }
1299
1300 int 
1301 xen_intr_bind_virq(device_t dev, u_int virq, u_int cpu,
1302     driver_filter_t filter, driver_intr_t handler, void *arg,
1303     enum intr_type flags, xen_intr_handle_t *port_handlep)
1304 {
1305         int vcpu_id = pcpu_find(cpu)->pc_vcpu_id;
1306         struct xenisrc *isrc;
1307         struct evtchn_bind_virq bind_virq = { .virq = virq, .vcpu = vcpu_id };
1308         int error;
1309
1310         isrc = NULL;
1311         error = HYPERVISOR_event_channel_op(EVTCHNOP_bind_virq, &bind_virq);
1312         if (error != 0) {
1313                 /*
1314                  * XXX Trap Hypercall error code Linuxisms in
1315                  *     the HYPERCALL layer.
1316                  */
1317                 return (-error);
1318         }
1319
1320         error = xen_intr_bind_isrc(&isrc, bind_virq.port, EVTCHN_TYPE_VIRQ,
1321             device_get_nameunit(dev), filter, handler, arg, flags,
1322             port_handlep);
1323
1324 #ifdef SMP
1325         if (error == 0)
1326                 error = intr_event_bind(isrc->xi_intsrc.is_event, cpu);
1327 #endif
1328
1329         if (error != 0) {
1330                 evtchn_close_t close = { .port = bind_virq.port };
1331
1332                 xen_intr_unbind(*port_handlep);
1333                 if (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close))
1334                         panic("EVTCHNOP_close failed");
1335                 return (error);
1336         }
1337
1338 #ifdef SMP
1339         if (isrc->xi_cpu != cpu) {
1340                 /*
1341                  * Too early in the boot process for the generic interrupt
1342                  * code to perform the binding.  Update our event channel
1343                  * masks manually so events can't fire on the wrong cpu
1344                  * during AP startup.
1345                  */
1346                 xen_intr_assign_cpu(&isrc->xi_intsrc, cpu_apic_ids[cpu]);
1347         }
1348 #endif
1349
1350         /*
1351          * The Event Channel API opened this port, so it is
1352          * responsible for closing it automatically on unbind.
1353          */
1354         isrc->xi_close = 1;
1355         isrc->xi_virq = virq;
1356
1357         return (0);
1358 }
1359
1360 int
1361 xen_intr_alloc_and_bind_ipi(u_int cpu, driver_filter_t filter,
1362     enum intr_type flags, xen_intr_handle_t *port_handlep)
1363 {
1364 #ifdef SMP
1365         int vcpu_id = pcpu_find(cpu)->pc_vcpu_id;
1366         struct xenisrc *isrc;
1367         struct evtchn_bind_ipi bind_ipi = { .vcpu = vcpu_id };
1368         /* Same size as the one used by intr_handler->ih_name. */
1369         char name[MAXCOMLEN + 1];
1370         int error;
1371
1372         isrc = NULL;
1373         error = HYPERVISOR_event_channel_op(EVTCHNOP_bind_ipi, &bind_ipi);
1374         if (error != 0) {
1375                 /*
1376                  * XXX Trap Hypercall error code Linuxisms in
1377                  *     the HYPERCALL layer.
1378                  */
1379                 return (-error);
1380         }
1381
1382         snprintf(name, sizeof(name), "cpu%u", cpu);
1383
1384         error = xen_intr_bind_isrc(&isrc, bind_ipi.port, EVTCHN_TYPE_IPI,
1385             name, filter, NULL, NULL, flags, port_handlep);
1386         if (error != 0) {
1387                 evtchn_close_t close = { .port = bind_ipi.port };
1388
1389                 xen_intr_unbind(*port_handlep);
1390                 if (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close))
1391                         panic("EVTCHNOP_close failed");
1392                 return (error);
1393         }
1394
1395         if (isrc->xi_cpu != cpu) {
1396                 /*
1397                  * Too early in the boot process for the generic interrupt
1398                  * code to perform the binding.  Update our event channel
1399                  * masks manually so events can't fire on the wrong cpu
1400                  * during AP startup.
1401                  */
1402                 xen_intr_assign_cpu(&isrc->xi_intsrc, cpu_apic_ids[cpu]);
1403         }
1404
1405         /*
1406          * The Event Channel API opened this port, so it is
1407          * responsible for closing it automatically on unbind.
1408          */
1409         isrc->xi_close = 1;
1410         return (0);
1411 #else
1412         return (EOPNOTSUPP);
1413 #endif
1414 }
1415
1416 int
1417 xen_register_pirq(int vector, enum intr_trigger trig, enum intr_polarity pol)
1418 {
1419         struct physdev_map_pirq map_pirq;
1420         struct xenisrc *isrc;
1421         int error;
1422
1423         if (vector == 0)
1424                 return (EINVAL);
1425
1426         if (bootverbose)
1427                 printf("xen: register IRQ#%d\n", vector);
1428
1429         map_pirq.domid = DOMID_SELF;
1430         map_pirq.type = MAP_PIRQ_TYPE_GSI;
1431         map_pirq.index = vector;
1432         map_pirq.pirq = vector;
1433
1434         error = HYPERVISOR_physdev_op(PHYSDEVOP_map_pirq, &map_pirq);
1435         if (error) {
1436                 printf("xen: unable to map IRQ#%d\n", vector);
1437                 return (error);
1438         }
1439
1440         mtx_lock(&xen_intr_isrc_lock);
1441         isrc = xen_intr_alloc_isrc(EVTCHN_TYPE_PIRQ, vector);
1442         mtx_unlock(&xen_intr_isrc_lock);
1443         KASSERT((isrc != NULL), ("xen: unable to allocate isrc for interrupt"));
1444         isrc->xi_pirq = vector;
1445         isrc->xi_activehi = pol == INTR_POLARITY_HIGH ? 1 : 0;
1446         isrc->xi_edgetrigger = trig == INTR_TRIGGER_EDGE ? 1 : 0;
1447
1448         return (0);
1449 }
1450
1451 int
1452 xen_register_msi(device_t dev, int vector, int count)
1453 {
1454         struct physdev_map_pirq msi_irq;
1455         struct xenisrc *isrc;
1456         int ret;
1457
1458         memset(&msi_irq, 0, sizeof(msi_irq));
1459         msi_irq.domid = DOMID_SELF;
1460         msi_irq.type = count == 1 ?
1461             MAP_PIRQ_TYPE_MSI_SEG : MAP_PIRQ_TYPE_MULTI_MSI;
1462         msi_irq.index = -1;
1463         msi_irq.pirq = -1;
1464         msi_irq.bus = pci_get_bus(dev) | (pci_get_domain(dev) << 16);
1465         msi_irq.devfn = (pci_get_slot(dev) << 3) | pci_get_function(dev);
1466         msi_irq.entry_nr = count;
1467
1468         ret = HYPERVISOR_physdev_op(PHYSDEVOP_map_pirq, &msi_irq);
1469         if (ret != 0)
1470                 return (ret);
1471         if (count != msi_irq.entry_nr) {
1472                 panic("unable to setup all requested MSI vectors "
1473                     "(expected %d got %d)", count, msi_irq.entry_nr);
1474         }
1475
1476         mtx_lock(&xen_intr_isrc_lock);
1477         for (int i = 0; i < count; i++) {
1478                 isrc = xen_intr_alloc_isrc(EVTCHN_TYPE_PIRQ, vector + i);
1479                 KASSERT(isrc != NULL,
1480                     ("xen: unable to allocate isrc for interrupt"));
1481                 isrc->xi_pirq = msi_irq.pirq + i;
1482                 /* MSI interrupts are always edge triggered */
1483                 isrc->xi_edgetrigger = 1;
1484         }
1485         mtx_unlock(&xen_intr_isrc_lock);
1486
1487         return (0);
1488 }
1489
1490 int
1491 xen_release_msi(int vector)
1492 {
1493         struct physdev_unmap_pirq unmap;
1494         struct xenisrc *isrc;
1495         int ret;
1496
1497         isrc = (struct xenisrc *)intr_lookup_source(vector);
1498         if (isrc == NULL)
1499                 return (ENXIO);
1500
1501         unmap.pirq = isrc->xi_pirq;
1502         ret = HYPERVISOR_physdev_op(PHYSDEVOP_unmap_pirq, &unmap);
1503         if (ret != 0)
1504                 return (ret);
1505
1506         xen_intr_release_isrc(isrc);
1507
1508         return (0);
1509 }
1510
1511 int
1512 xen_intr_describe(xen_intr_handle_t port_handle, const char *fmt, ...)
1513 {
1514         char descr[MAXCOMLEN + 1];
1515         struct xenisrc *isrc;
1516         va_list ap;
1517
1518         isrc = xen_intr_isrc(port_handle);
1519         if (isrc == NULL)
1520                 return (EINVAL);
1521
1522         va_start(ap, fmt);
1523         vsnprintf(descr, sizeof(descr), fmt, ap);
1524         va_end(ap);
1525         return (intr_describe(isrc->xi_vector, isrc->xi_cookie, descr));
1526 }
1527
1528 void
1529 xen_intr_unbind(xen_intr_handle_t *port_handlep)
1530 {
1531         struct xenisrc *isrc;
1532
1533         KASSERT(port_handlep != NULL,
1534             ("NULL xen_intr_handle_t passed to xen_intr_unbind"));
1535
1536         isrc = xen_intr_isrc(*port_handlep);
1537         *port_handlep = NULL;
1538         if (isrc == NULL)
1539                 return;
1540
1541         mtx_lock(&xen_intr_isrc_lock);
1542         if (refcount_release(&isrc->xi_refcount) == 0) {
1543                 mtx_unlock(&xen_intr_isrc_lock);
1544                 return;
1545         }
1546         mtx_unlock(&xen_intr_isrc_lock);
1547
1548         if (isrc->xi_cookie != NULL)
1549                 intr_remove_handler(isrc->xi_cookie);
1550         xen_intr_release_isrc(isrc);
1551 }
1552
1553 void
1554 xen_intr_signal(xen_intr_handle_t handle)
1555 {
1556         struct xenisrc *isrc;
1557
1558         isrc = xen_intr_isrc(handle);
1559         if (isrc != NULL) {
1560                 KASSERT(isrc->xi_type == EVTCHN_TYPE_PORT ||
1561                         isrc->xi_type == EVTCHN_TYPE_IPI,
1562                         ("evtchn_signal on something other than a local port"));
1563                 struct evtchn_send send = { .port = isrc->xi_port };
1564                 (void)HYPERVISOR_event_channel_op(EVTCHNOP_send, &send);
1565         }
1566 }
1567
1568 evtchn_port_t
1569 xen_intr_port(xen_intr_handle_t handle)
1570 {
1571         struct xenisrc *isrc;
1572
1573         isrc = xen_intr_isrc(handle);
1574         if (isrc == NULL)
1575                 return (0);
1576         
1577         return (isrc->xi_port);
1578 }
1579
1580 int
1581 xen_intr_add_handler(const char *name, driver_filter_t filter,
1582     driver_intr_t handler, void *arg, enum intr_type flags,
1583     xen_intr_handle_t handle)
1584 {
1585         struct xenisrc *isrc;
1586         int error;
1587
1588         isrc = xen_intr_isrc(handle);
1589         if (isrc == NULL || isrc->xi_cookie != NULL)
1590                 return (EINVAL);
1591
1592         error = intr_add_handler(name, isrc->xi_vector,filter, handler, arg,
1593             flags|INTR_EXCL, &isrc->xi_cookie, 0);
1594         if (error != 0) {
1595                 printf(
1596                     "%s: xen_intr_add_handler: intr_add_handler failed: %d\n",
1597                     name, error);
1598         }
1599
1600         return (error);
1601 }
1602
1603 int
1604 xen_intr_get_evtchn_from_port(evtchn_port_t port, xen_intr_handle_t *handlep)
1605 {
1606
1607         if (!is_valid_evtchn(port) || port >= NR_EVENT_CHANNELS)
1608                 return (EINVAL);
1609
1610         if (handlep == NULL) {
1611                 return (EINVAL);
1612         }
1613
1614         mtx_lock(&xen_intr_isrc_lock);
1615         if (xen_intr_port_to_isrc[port] == NULL) {
1616                 mtx_unlock(&xen_intr_isrc_lock);
1617                 return (EINVAL);
1618         }
1619         refcount_acquire(&xen_intr_port_to_isrc[port]->xi_refcount);
1620         mtx_unlock(&xen_intr_isrc_lock);
1621
1622         /* Assign the opaque handler (the event channel port) */
1623         *handlep = &xen_intr_port_to_isrc[port]->xi_vector;
1624
1625         return (0);
1626 }
1627
1628 #ifdef DDB
1629 static const char *
1630 xen_intr_print_type(enum evtchn_type type)
1631 {
1632         static const char *evtchn_type_to_string[EVTCHN_TYPE_COUNT] = {
1633                 [EVTCHN_TYPE_UNBOUND]   = "UNBOUND",
1634                 [EVTCHN_TYPE_PIRQ]      = "PIRQ",
1635                 [EVTCHN_TYPE_VIRQ]      = "VIRQ",
1636                 [EVTCHN_TYPE_IPI]       = "IPI",
1637                 [EVTCHN_TYPE_PORT]      = "PORT",
1638         };
1639
1640         if (type >= EVTCHN_TYPE_COUNT)
1641                 return ("UNKNOWN");
1642
1643         return (evtchn_type_to_string[type]);
1644 }
1645
1646 static void
1647 xen_intr_dump_port(struct xenisrc *isrc)
1648 {
1649         struct xen_intr_pcpu_data *pcpu;
1650         shared_info_t *s = HYPERVISOR_shared_info;
1651         int i;
1652
1653         db_printf("Port %d Type: %s\n",
1654             isrc->xi_port, xen_intr_print_type(isrc->xi_type));
1655         if (isrc->xi_type == EVTCHN_TYPE_PIRQ) {
1656                 db_printf("\tPirq: %d ActiveHi: %d EdgeTrigger: %d "
1657                     "NeedsEOI: %d\n",
1658                     isrc->xi_pirq, isrc->xi_activehi, isrc->xi_edgetrigger,
1659                     !!xen_test_bit(isrc->xi_pirq, xen_intr_pirq_eoi_map));
1660         }
1661         if (isrc->xi_type == EVTCHN_TYPE_VIRQ)
1662                 db_printf("\tVirq: %d\n", isrc->xi_virq);
1663
1664         db_printf("\tMasked: %d Pending: %d\n",
1665             !!xen_test_bit(isrc->xi_port, &s->evtchn_mask[0]),
1666             !!xen_test_bit(isrc->xi_port, &s->evtchn_pending[0]));
1667
1668         db_printf("\tPer-CPU Masks: ");
1669         CPU_FOREACH(i) {
1670                 pcpu = DPCPU_ID_PTR(i, xen_intr_pcpu);
1671                 db_printf("cpu#%d: %d ", i,
1672                     !!xen_test_bit(isrc->xi_port, pcpu->evtchn_enabled));
1673         }
1674         db_printf("\n");
1675 }
1676
1677 DB_SHOW_COMMAND(xen_evtchn, db_show_xen_evtchn)
1678 {
1679         int i;
1680
1681         if (!xen_domain()) {
1682                 db_printf("Only available on Xen guests\n");
1683                 return;
1684         }
1685
1686         for (i = 0; i < NR_EVENT_CHANNELS; i++) {
1687                 struct xenisrc *isrc;
1688
1689                 isrc = xen_intr_port_to_isrc[i];
1690                 if (isrc == NULL)
1691                         continue;
1692
1693                 xen_intr_dump_port(isrc);
1694         }
1695 }
1696 #endif /* DDB */