xref: /dflybsd-src/sys/kern/kern_intr.c (revision 63823918841fb49563040cdc77c4b4474ea39b93)
1  /*
2   * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com> All rights reserved.
3   * Copyright (c) 1997, Stefan Esser <se@freebsd.org> All rights reserved.
4   *
5   * Redistribution and use in source and binary forms, with or without
6   * modification, are permitted provided that the following conditions
7   * are met:
8   * 1. Redistributions of source code must retain the above copyright
9   *    notice unmodified, this list of conditions, and the following
10   *    disclaimer.
11   * 2. Redistributions in binary form must reproduce the above copyright
12   *    notice, this list of conditions and the following disclaimer in the
13   *    documentation and/or other materials provided with the distribution.
14   *
15   * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16   * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18   * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19   * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21   * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22   * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24   * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25   *
26   * $FreeBSD: src/sys/kern/kern_intr.c,v 1.24.2.1 2001/10/14 20:05:50 luigi Exp $
27   *
28   */
29  
30  #include <sys/param.h>
31  #include <sys/systm.h>
32  #include <sys/malloc.h>
33  #include <sys/kernel.h>
34  #include <sys/sysctl.h>
35  #include <sys/thread.h>
36  #include <sys/proc.h>
37  #include <sys/random.h>
38  #include <sys/serialize.h>
39  #include <sys/interrupt.h>
40  #include <sys/bus.h>
41  #include <sys/machintr.h>
42  
43  #include <machine/frame.h>
44  
45  #include <sys/thread2.h>
46  #include <sys/mplock2.h>
47  
48  struct intr_info;
49  
50  typedef struct intrec {
51      struct intrec *next;
52      struct intr_info *info;
53      inthand2_t	*handler;
54      void	*argument;
55      char	*name;
56      int		intr;
57      int		intr_flags;
58      struct lwkt_serialize *serializer;
59  } *intrec_t;
60  
61  struct intr_info {
62  	intrec_t	i_reclist;
63  	struct thread	*i_thread;	/* don't embed struct thread */
64  	struct random_softc i_random;
65  	long		i_count;	/* interrupts dispatched */
66  	int		i_running;
67  	short		i_mplock_required;
68  	short		i_flags;
69  	int		i_fast;
70  	int		i_slow;
71  	int		i_state;
72  	int		i_errorticks;
73  	unsigned long	i_straycount;
74  	int		i_cpuid;
75  	int		i_intr;
76  };
77  
78  struct intr_info_block {
79  	struct intr_info ary[MAXCPU][MAX_INTS];
80  };
81  
82  static struct intr_info_block *intr_block;
83  static struct intr_info *swi_info_ary[MAX_SOFTINTS];
84  
85  static int max_installed_hard_intr[MAXCPU];
86  
87  MALLOC_DEFINE(M_INTRMNG, "intrmng", "interrupt management");
88  
89  
90  #define EMERGENCY_INTR_POLLING_FREQ_MAX 20000
91  
92  /*
93   * Assert that callers into interrupt handlers don't return with
94   * dangling tokens, spinlocks, or mp locks.
95   */
96  #ifdef INVARIANTS
97  
98  #define TD_INVARIANTS_DECLARE   \
99          int spincount;          \
100          lwkt_tokref_t curstop
101  
102  #define TD_INVARIANTS_GET(td)                                   \
103          do {                                                    \
104                  spincount = (td)->td_gd->gd_spinlocks;		\
105                  curstop = (td)->td_toks_stop;                   \
106          } while(0)
107  
108  #define TD_INVARIANTS_TEST(td, name)                                    \
109          do {                                                            \
110                  KASSERT(spincount == (td)->td_gd->gd_spinlocks,		\
111                          ("spincount mismatch after interrupt handler %s", \
112                          name));                                         \
113                  KASSERT(curstop == (td)->td_toks_stop,                  \
114                          ("token count mismatch after interrupt handler %s", \
115                          name));                                         \
116          } while(0)
117  
118  #else
119  
120  /* !INVARIANTS */
121  
122  #define TD_INVARIANTS_DECLARE
123  #define TD_INVARIANTS_GET(td)
124  #define TD_INVARIANTS_TEST(td, name)
125  
126  #endif /* ndef INVARIANTS */
127  
128  static int sysctl_emergency_freq(SYSCTL_HANDLER_ARGS);
129  static int sysctl_emergency_enable(SYSCTL_HANDLER_ARGS);
130  static void emergency_intr_timer_callback(systimer_t, int, struct intrframe *);
131  static void ithread_handler(void *arg);
132  static void ithread_emergency(void *arg);
133  static void report_stray_interrupt(struct intr_info *info, const char *func);
134  static void int_moveto_destcpu(int *, int);
135  static void int_moveto_origcpu(int, int);
136  static void sched_ithd_intern(struct intr_info *info);
137  
138  static struct systimer emergency_intr_timer[MAXCPU];
139  static struct thread *emergency_intr_thread[MAXCPU];
140  
141  #define ISTATE_NOTHREAD		0
142  #define ISTATE_NORMAL		1
143  #define ISTATE_LIVELOCKED	2
144  
145  static int livelock_limit = 40000;
146  static int livelock_limit_hi = 120000;
147  static int livelock_lowater = 20000;
148  static int livelock_debug = -1;
149  SYSCTL_INT(_kern, OID_AUTO, livelock_limit,
150          CTLFLAG_RW, &livelock_limit, 0, "Livelock interrupt rate limit");
151  SYSCTL_INT(_kern, OID_AUTO, livelock_limit_hi,
152          CTLFLAG_RW, &livelock_limit_hi, 0,
153  	"Livelock interrupt rate limit (high frequency)");
154  SYSCTL_INT(_kern, OID_AUTO, livelock_lowater,
155          CTLFLAG_RW, &livelock_lowater, 0, "Livelock low-water mark restore");
156  SYSCTL_INT(_kern, OID_AUTO, livelock_debug,
157          CTLFLAG_RW, &livelock_debug, 0, "Livelock debug intr#");
158  
159  static int emergency_intr_enable = 0;	/* emergency interrupt polling */
160  TUNABLE_INT("kern.emergency_intr_enable", &emergency_intr_enable);
161  SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_enable, CTLTYPE_INT | CTLFLAG_RW,
162          0, 0, sysctl_emergency_enable, "I", "Emergency Interrupt Poll Enable");
163  
164  static int emergency_intr_freq = 10;	/* emergency polling frequency */
165  TUNABLE_INT("kern.emergency_intr_freq", &emergency_intr_freq);
166  SYSCTL_PROC(_kern, OID_AUTO, emergency_intr_freq, CTLTYPE_INT | CTLFLAG_RW,
167          0, 0, sysctl_emergency_freq, "I", "Emergency Interrupt Poll Frequency");
168  
169  /*
170   * Sysctl support routines
171   */
172  static int
sysctl_emergency_enable(SYSCTL_HANDLER_ARGS)173  sysctl_emergency_enable(SYSCTL_HANDLER_ARGS)
174  {
175  	int error, enabled, cpuid, freq, origcpu;
176  
177  	enabled = emergency_intr_enable;
178  	error = sysctl_handle_int(oidp, &enabled, 0, req);
179  	if (error || req->newptr == NULL)
180  		return error;
181  	emergency_intr_enable = enabled;
182  	if (emergency_intr_enable)
183  		freq = emergency_intr_freq;
184  	else
185  		freq = 1;
186  
187  	origcpu = mycpuid;
188  	for (cpuid = 0; cpuid < ncpus; ++cpuid) {
189  		lwkt_migratecpu(cpuid);
190  		systimer_adjust_periodic(&emergency_intr_timer[cpuid], freq);
191  	}
192  	lwkt_migratecpu(origcpu);
193  	return 0;
194  }
195  
196  static int
sysctl_emergency_freq(SYSCTL_HANDLER_ARGS)197  sysctl_emergency_freq(SYSCTL_HANDLER_ARGS)
198  {
199          int error, phz, cpuid, freq, origcpu;
200  
201          phz = emergency_intr_freq;
202          error = sysctl_handle_int(oidp, &phz, 0, req);
203          if (error || req->newptr == NULL)
204                  return error;
205          if (phz <= 0)
206                  return EINVAL;
207          else if (phz > EMERGENCY_INTR_POLLING_FREQ_MAX)
208                  phz = EMERGENCY_INTR_POLLING_FREQ_MAX;
209  
210          emergency_intr_freq = phz;
211  	if (emergency_intr_enable)
212  		freq = emergency_intr_freq;
213  	else
214  		freq = 1;
215  
216  	origcpu = mycpuid;
217  	for (cpuid = 0; cpuid < ncpus; ++cpuid) {
218  		lwkt_migratecpu(cpuid);
219  		systimer_adjust_periodic(&emergency_intr_timer[cpuid], freq);
220  	}
221  	lwkt_migratecpu(origcpu);
222          return 0;
223  }
224  
225  /*
226   * Register an SWI or INTerrupt handler.
227   */
228  void *
register_swi(int intr,inthand2_t * handler,void * arg,const char * name,struct lwkt_serialize * serializer,int cpuid)229  register_swi(int intr, inthand2_t *handler, void *arg, const char *name,
230  		struct lwkt_serialize *serializer, int cpuid)
231  {
232      if (intr < FIRST_SOFTINT || intr >= MAX_INTS)
233  	panic("register_swi: bad intr %d", intr);
234  
235      if (cpuid < 0)
236  	cpuid = intr % ncpus;
237      return(register_int(intr, handler, arg, name, serializer, 0, cpuid));
238  }
239  
240  void *
register_swi_mp(int intr,inthand2_t * handler,void * arg,const char * name,struct lwkt_serialize * serializer,int cpuid)241  register_swi_mp(int intr, inthand2_t *handler, void *arg, const char *name,
242  		struct lwkt_serialize *serializer, int cpuid)
243  {
244      if (intr < FIRST_SOFTINT || intr >= MAX_INTS)
245  	panic("register_swi: bad intr %d", intr);
246  
247      if (cpuid < 0)
248  	cpuid = intr % ncpus;
249      return(register_int(intr, handler, arg, name, serializer,
250  			INTR_MPSAFE, cpuid));
251  }
252  
253  void *
register_int(int intr,inthand2_t * handler,void * arg,const char * name,struct lwkt_serialize * serializer,int intr_flags,int cpuid)254  register_int(int intr, inthand2_t *handler, void *arg, const char *name,
255  		struct lwkt_serialize *serializer, int intr_flags, int cpuid)
256  {
257      struct intr_info *info;
258      struct intrec **list;
259      intrec_t rec = NULL;
260      int orig_cpuid;
261  
262      KKASSERT(cpuid >= 0 && cpuid < ncpus);
263  
264      if (intr < 0 || intr >= MAX_INTS)
265  	panic("register_int: bad intr %d", intr);
266      if (name == NULL)
267  	name = "???";
268      info = &intr_block->ary[cpuid][intr];
269  
270      int_moveto_destcpu(&orig_cpuid, cpuid);
271  
272      /*
273       * This intr has been registered as exclusive one, so
274       * it can't shared.
275       */
276      if (info->i_flags & INTR_EXCL)
277  	goto done;
278  
279      /*
280       * This intr has been registered as shared one, so it
281       * can't be used for exclusive handler.
282       */
283      list = &info->i_reclist;
284      if ((intr_flags & INTR_EXCL) && *list != NULL)
285  	goto done;
286  
287      /*
288       * Construct an interrupt handler record
289       */
290      rec = kmalloc(sizeof(struct intrec), M_DEVBUF, M_INTWAIT);
291      rec->name = kmalloc(strlen(name) + 1, M_DEVBUF, M_INTWAIT);
292      strcpy(rec->name, name);
293  
294      rec->info = info;
295      rec->handler = handler;
296      rec->argument = arg;
297      rec->intr = intr;
298      rec->intr_flags = intr_flags;
299      rec->next = NULL;
300      rec->serializer = serializer;
301  
302      /*
303       * Create an emergency polling thread and set up a systimer to wake
304       * it up.  objcache isn't operational yet so use kmalloc.
305       *
306       * objcache may not be operational yet, use kmalloc().
307       */
308      if (emergency_intr_thread[cpuid] == NULL) {
309  	emergency_intr_thread[cpuid] = kmalloc(sizeof(struct thread), M_DEVBUF,
310  					       M_INTWAIT | M_ZERO);
311  	lwkt_create(ithread_emergency, NULL, NULL,
312  		    emergency_intr_thread[cpuid],
313  		    TDF_NOSTART | TDF_INTTHREAD, cpuid, "ithreadE %d",
314  		    cpuid);
315  	systimer_init_periodic_nq(&emergency_intr_timer[cpuid],
316  		    emergency_intr_timer_callback,
317  		    emergency_intr_thread[cpuid],
318  		    (emergency_intr_enable ? emergency_intr_freq : 1));
319      }
320  
321      /*
322       * Create an interrupt thread if necessary, leave it in an unscheduled
323       * state.
324       */
325      if (info->i_state == ISTATE_NOTHREAD) {
326  	info->i_state = ISTATE_NORMAL;
327  	info->i_thread = kmalloc(sizeof(struct thread), M_DEVBUF,
328  				 M_INTWAIT | M_ZERO);
329  	lwkt_create(ithread_handler, (void *)(intptr_t)intr, NULL,
330  		    info->i_thread, TDF_NOSTART | TDF_INTTHREAD, cpuid,
331  		    "ithread%d %d", intr, cpuid);
332  	if (intr >= FIRST_SOFTINT)
333  	    lwkt_setpri(info->i_thread, TDPRI_SOFT_NORM);
334  	else
335  	    lwkt_setpri(info->i_thread, TDPRI_INT_MED);
336  	info->i_thread->td_preemptable = lwkt_preempt;
337      }
338  
339      /*
340       * Keep track of how many fast and slow interrupts we have.
341       * Set i_mplock_required if any handler in the chain requires
342       * the MP lock to operate.
343       */
344      if ((intr_flags & INTR_MPSAFE) == 0) {
345  	info->i_mplock_required = 1;
346  	kprintf("interrupt uses mplock: %s\n", name);
347      }
348      if (intr_flags & INTR_CLOCK) {
349  	atomic_set_int(&info->i_thread->td_flags, TDF_CLKTHREAD);
350  	++info->i_fast;
351      } else {
352  	++info->i_slow;
353      }
354  
355      info->i_flags |= (intr_flags & INTR_EXCL);
356      if (info->i_slow + info->i_fast == 1 && (intr_flags & INTR_HIFREQ)) {
357  	/*
358  	 * Allow high frequency interrupt, if this intr is not
359  	 * shared yet.
360  	 */
361  	info->i_flags |= INTR_HIFREQ;
362      } else {
363  	info->i_flags &= ~INTR_HIFREQ;
364      }
365  
366      /*
367       * Enable random number generation keying off of this interrupt.
368       */
369      if ((intr_flags & INTR_NOENTROPY) == 0 && info->i_random.sc_enabled == 0) {
370  	info->i_random.sc_enabled = 1;
371  	info->i_random.sc_intr = intr;
372      }
373  
374      /*
375       * Add the record to the interrupt list.
376       */
377      crit_enter();
378      while (*list != NULL)
379  	list = &(*list)->next;
380      *list = rec;
381      crit_exit();
382  
383      /*
384       * Update max_installed_hard_intr to make the emergency intr poll
385       * a bit more efficient.
386       */
387      if (intr < FIRST_SOFTINT) {
388  	if (max_installed_hard_intr[cpuid] <= intr)
389  	    max_installed_hard_intr[cpuid] = intr + 1;
390      }
391  
392      if (intr >= FIRST_SOFTINT)
393  	swi_info_ary[intr - FIRST_SOFTINT] = info;
394  
395      /*
396       * Setup the machine level interrupt vector
397       */
398      if (intr < FIRST_SOFTINT && info->i_slow + info->i_fast == 1)
399  	machintr_intr_setup(intr, intr_flags);
400  
401  done:
402      int_moveto_origcpu(orig_cpuid, cpuid);
403      return(rec);
404  }
405  
406  void
unregister_swi(void * id,int intr,int cpuid)407  unregister_swi(void *id, int intr, int cpuid)
408  {
409      if (cpuid < 0)
410  	cpuid = intr % ncpus;
411  
412      unregister_int(id, cpuid);
413  }
414  
415  void
unregister_int(void * id,int cpuid)416  unregister_int(void *id, int cpuid)
417  {
418      struct intr_info *info;
419      struct intrec **list;
420      intrec_t rec;
421      int intr, orig_cpuid;
422  
423      KKASSERT(cpuid >= 0 && cpuid < ncpus);
424  
425      intr = ((intrec_t)id)->intr;
426  
427      if (intr < 0 || intr >= MAX_INTS)
428  	panic("register_int: bad intr %d", intr);
429  
430      info = &intr_block->ary[cpuid][intr];
431  
432      int_moveto_destcpu(&orig_cpuid, cpuid);
433  
434      /*
435       * Remove the interrupt descriptor, adjust the descriptor count,
436       * and teardown the machine level vector if this was the last interrupt.
437       */
438      crit_enter();
439      list = &info->i_reclist;
440      while ((rec = *list) != NULL) {
441  	if (rec == id)
442  	    break;
443  	list = &rec->next;
444      }
445      if (rec) {
446  	intrec_t rec0;
447  
448  	*list = rec->next;
449  	if (rec->intr_flags & INTR_CLOCK)
450  	    --info->i_fast;
451  	else
452  	    --info->i_slow;
453  	if (intr < FIRST_SOFTINT && info->i_fast + info->i_slow == 0)
454  	    machintr_intr_teardown(intr);
455  
456  	/*
457  	 * Clear i_mplock_required if no handlers in the chain require the
458  	 * MP lock.
459  	 */
460  	for (rec0 = info->i_reclist; rec0; rec0 = rec0->next) {
461  	    if ((rec0->intr_flags & INTR_MPSAFE) == 0)
462  		break;
463  	}
464  	if (rec0 == NULL)
465  	    info->i_mplock_required = 0;
466      }
467  
468      if (info->i_reclist == NULL) {
469  	info->i_flags = 0;
470  	if (intr >= FIRST_SOFTINT)
471  	    swi_info_ary[intr - FIRST_SOFTINT] = NULL;
472      } else if (info->i_fast + info->i_slow == 1 &&
473  	(info->i_reclist->intr_flags & INTR_HIFREQ)) {
474  	/* Unshared high frequency interrupt. */
475  	info->i_flags |= INTR_HIFREQ;
476      }
477  
478      crit_exit();
479  
480      int_moveto_origcpu(orig_cpuid, cpuid);
481  
482      /*
483       * Free the record.
484       */
485      if (rec != NULL) {
486  	kfree(rec->name, M_DEVBUF);
487  	kfree(rec, M_DEVBUF);
488      } else {
489  	kprintf("warning: unregister_int: int %d handler for %s not found\n",
490  		intr, ((intrec_t)id)->name);
491      }
492  }
493  
494  long
get_interrupt_counter(int intr,int cpuid)495  get_interrupt_counter(int intr, int cpuid)
496  {
497      struct intr_info *info;
498  
499      KKASSERT(cpuid >= 0 && cpuid < ncpus);
500  
501      if (intr < 0 || intr >= MAX_INTS)
502  	panic("register_int: bad intr %d", intr);
503      info = &intr_block->ary[cpuid][intr];
504      return(info->i_count);
505  }
506  
507  void
register_randintr(int intr)508  register_randintr(int intr)
509  {
510      struct intr_info *info;
511      int cpuid;
512  
513      if (intr < 0 || intr >= MAX_INTS)
514  	panic("register_randintr: bad intr %d", intr);
515  
516      for (cpuid = 0; cpuid < ncpus; ++cpuid) {
517  	info = &intr_block->ary[cpuid][intr];
518  	info->i_random.sc_intr = intr;
519  	info->i_random.sc_enabled = 1;
520      }
521  }
522  
523  void
unregister_randintr(int intr)524  unregister_randintr(int intr)
525  {
526      struct intr_info *info;
527      int cpuid;
528  
529      if (intr < 0 || intr >= MAX_INTS)
530  	panic("register_swi: bad intr %d", intr);
531  
532      for (cpuid = 0; cpuid < ncpus; ++cpuid) {
533  	info = &intr_block->ary[cpuid][intr];
534  	info->i_random.sc_enabled = -1;
535      }
536  }
537  
538  int
next_registered_randintr(int intr)539  next_registered_randintr(int intr)
540  {
541      struct intr_info *info;
542  
543      if (intr < 0 || intr >= MAX_INTS)
544  	panic("register_swi: bad intr %d", intr);
545  
546      while (intr < MAX_INTS) {
547  	int cpuid;
548  
549  	for (cpuid = 0; cpuid < ncpus; ++cpuid) {
550  	    info = &intr_block->ary[cpuid][intr];
551  	    if (info->i_random.sc_enabled > 0)
552  		return intr;
553  	}
554  	++intr;
555      }
556      return intr;
557  }
558  
559  /*
560   * Dispatch an interrupt.  If there's nothing to do we have a stray
561   * interrupt and can just return, leaving the interrupt masked.
562   *
563   * We need to schedule the interrupt and set its i_running bit.  If
564   * we are not on the interrupt thread's cpu we have to send a message
565   * to the correct cpu that will issue the desired action (interlocking
566   * with the interrupt thread's critical section).  We do NOT attempt to
567   * reschedule interrupts whos i_running bit is already set because
568   * this would prematurely wakeup a livelock-limited interrupt thread.
569   *
570   * i_running is only tested/set on the same cpu as the interrupt thread.
571   *
572   * We are NOT in a critical section, which will allow the scheduled
573   * interrupt to preempt us.  The MP lock might *NOT* be held here.
574   */
575  static void
sched_ithd_remote(void * arg)576  sched_ithd_remote(void *arg)
577  {
578      sched_ithd_intern(arg);
579  }
580  
581  static void
sched_ithd_intern(struct intr_info * info)582  sched_ithd_intern(struct intr_info *info)
583  {
584      ++info->i_count;
585      if (info->i_state != ISTATE_NOTHREAD) {
586  	if (info->i_reclist == NULL) {
587  	    report_stray_interrupt(info, "sched_ithd");
588  	} else {
589  	    if (info->i_thread->td_gd == mycpu) {
590  		if (info->i_running == 0) {
591  		    info->i_running = 1;
592  		    if (info->i_state != ISTATE_LIVELOCKED)
593  			lwkt_schedule(info->i_thread); /* MIGHT PREEMPT */
594  		}
595  	    } else {
596  		lwkt_send_ipiq(info->i_thread->td_gd, sched_ithd_remote, info);
597  	    }
598  	}
599      } else {
600  	report_stray_interrupt(info, "sched_ithd");
601      }
602  }
603  
604  void
sched_ithd_soft(int intr)605  sched_ithd_soft(int intr)
606  {
607  	struct intr_info *info;
608  
609  	KKASSERT(intr >= FIRST_SOFTINT && intr < MAX_INTS);
610  
611  	info = swi_info_ary[intr - FIRST_SOFTINT];
612  	if (info != NULL) {
613  		sched_ithd_intern(info);
614  	} else {
615  		kprintf("unregistered softint %d got scheduled on cpu%d\n",
616  		    intr, mycpuid);
617  	}
618  }
619  
620  void
sched_ithd_hard(int intr)621  sched_ithd_hard(int intr)
622  {
623  	KKASSERT(intr >= 0 && intr < MAX_HARDINTS);
624  	sched_ithd_intern(&intr_block->ary[mycpuid][intr]);
625  }
626  
627  #ifdef _KERNEL_VIRTUAL
628  
629  void
sched_ithd_hard_virtual(int intr)630  sched_ithd_hard_virtual(int intr)
631  {
632  	KKASSERT(intr >= 0 && intr < MAX_HARDINTS);
633  	sched_ithd_intern(&intr_block->ary[0][intr]);
634  }
635  
636  void *
register_int_virtual(int intr,inthand2_t * handler,void * arg,const char * name,struct lwkt_serialize * serializer,int intr_flags)637  register_int_virtual(int intr, inthand2_t *handler, void *arg, const char *name,
638      struct lwkt_serialize *serializer, int intr_flags)
639  {
640  	return register_int(intr, handler, arg, name, serializer, intr_flags, 0);
641  }
642  
643  void
unregister_int_virtual(void * id)644  unregister_int_virtual(void *id)
645  {
646  	unregister_int(id, 0);
647  }
648  
649  #endif	/* _KERN_VIRTUAL */
650  
651  static void
report_stray_interrupt(struct intr_info * info,const char * func)652  report_stray_interrupt(struct intr_info *info, const char *func)
653  {
654  	++info->i_straycount;
655  	if (info->i_straycount < 10) {
656  		if (info->i_errorticks == ticks)
657  			return;
658  		info->i_errorticks = ticks;
659  		kprintf("%s: stray interrupt %d on cpu%d\n",
660  		    func, info->i_intr, mycpuid);
661  	} else if (info->i_straycount == 10) {
662  		kprintf("%s: %ld stray interrupts %d on cpu%d - "
663  			"there will be no further reports\n", func,
664  			info->i_straycount, info->i_intr, mycpuid);
665  	}
666  }
667  
668  /*
669   * This is run from a periodic SYSTIMER (and thus must be MP safe, the BGL
670   * might not be held).
671   */
672  static void
ithread_livelock_wakeup(systimer_t st,int in_ipi __unused,struct intrframe * frame __unused)673  ithread_livelock_wakeup(systimer_t st, int in_ipi __unused,
674      struct intrframe *frame __unused)
675  {
676      struct intr_info *info;
677  
678      info = &intr_block->ary[mycpuid][(int)(intptr_t)st->data];
679      if (info->i_state != ISTATE_NOTHREAD)
680  	lwkt_schedule(info->i_thread);
681  }
682  
683  /*
684   * Schedule ithread within fast intr handler
685   *
686   * Temporarily bump the current thread's td_nest_count to prevent deep
687   * preemptions and splz/doreti stacks.
688   */
689  static __inline void
ithread_fast_sched(int intr,thread_t td)690  ithread_fast_sched(int intr, thread_t td)
691  {
692      ++td->td_nest_count;
693      crit_exit_quick(td);
694      sched_ithd_hard(intr);
695      crit_enter_quick(td);
696      --td->td_nest_count;
697  }
698  
699  /*
700   * This function is called directly from the ICU or APIC vector code assembly
701   * to process an interrupt.  The critical section and interrupt deferral
702   * checks have already been done but the function is entered WITHOUT
703   * a critical section held.  The BGL may or may not be held.
704   *
705   * Must return non-zero if we do not want the vector code to re-enable
706   * the interrupt (which we don't if we have to schedule the interrupt)
707   */
708  int ithread_fast_handler(struct intrframe *frame);
709  
710  int
ithread_fast_handler(struct intrframe * frame)711  ithread_fast_handler(struct intrframe *frame)
712  {
713      int intr;
714      struct intr_info *info;
715      struct intrec **list;
716      int must_schedule;
717      int got_mplock;
718      TD_INVARIANTS_DECLARE;
719      intrec_t rec, nrec;
720      globaldata_t gd;
721      thread_t td;
722  
723      intr = frame->if_vec;
724      gd = mycpu;
725      td = curthread;
726  
727      /* We must be in critical section. */
728      KKASSERT(td->td_critcount);
729  
730      /* Race condition during early boot */
731      if (intr_block == NULL)
732  	return 0;
733  
734      info = &intr_block->ary[mycpuid][intr];
735  
736      /*
737       * If we are not processing any FAST interrupts, just schedule the thing.
738       */
739      if (info->i_fast == 0) {
740      	++gd->gd_cnt.v_intr;
741  	ithread_fast_sched(intr, td);
742  	return(1);
743      }
744  
745      /*
746       * This should not normally occur since interrupts ought to be
747       * masked if the ithread has been scheduled or is running.
748       */
749      if (info->i_running)
750  	return(1);
751  
752      /*
753       * Bump the interrupt nesting level to process any FAST interrupts.
754       * Obtain the MP lock as necessary.  If the MP lock cannot be obtained,
755       * schedule the interrupt thread to deal with the issue instead.
756       *
757       * To reduce overhead, just leave the MP lock held once it has been
758       * obtained.
759       */
760      ++gd->gd_intr_nesting_level;
761      ++gd->gd_cnt.v_intr;
762      must_schedule = info->i_slow;
763      got_mplock = 0;
764  
765      TD_INVARIANTS_GET(td);
766      list = &info->i_reclist;
767  
768      for (rec = *list; rec; rec = nrec) {
769  	/* rec may be invalid after call */
770  	nrec = rec->next;
771  
772  	if (rec->intr_flags & INTR_CLOCK) {
773  	    if ((rec->intr_flags & INTR_MPSAFE) == 0 && got_mplock == 0) {
774  		if (try_mplock() == 0) {
775  		    /* Couldn't get the MP lock; just schedule it. */
776  		    must_schedule = 1;
777  		    break;
778  		}
779  		got_mplock = 1;
780  	    }
781  	    if (rec->serializer) {
782  		must_schedule += lwkt_serialize_handler_try(
783  					rec->serializer, rec->handler,
784  					rec->argument, frame);
785  	    } else {
786  		rec->handler(rec->argument, frame);
787  	    }
788  	    TD_INVARIANTS_TEST(td, rec->name);
789  	}
790      }
791  
792      /*
793       * Cleanup
794       */
795      --gd->gd_intr_nesting_level;
796      if (got_mplock)
797  	rel_mplock();
798  
799      /*
800       * If we had a problem, or mixed fast and slow interrupt handlers are
801       * registered, schedule the ithread to catch the missed records (it
802       * will just re-run all of them).  A return value of 0 indicates that
803       * all handlers have been run and the interrupt can be re-enabled, and
804       * a non-zero return indicates that the interrupt thread controls
805       * re-enablement.
806       */
807      if (must_schedule > 0)
808  	ithread_fast_sched(intr, td);
809      else if (must_schedule == 0)
810  	++info->i_count;
811      return(must_schedule);
812  }
813  
814  /*
815   * Interrupt threads run this as their main loop.
816   *
817   * The handler begins execution outside a critical section and no MP lock.
818   *
819   * The i_running state starts at 0.  When an interrupt occurs, the hardware
820   * interrupt is disabled and sched_ithd_hard().  The HW interrupt remains
821   * disabled until all routines have run.  We then call machintr_intr_enable()
822   * to reenable the HW interrupt and deschedule us until the next interrupt.
823   *
824   * We are responsible for atomically checking i_running.  i_running for our
825   * irq is only set in the context of our cpu, so a critical section is a
826   * sufficient interlock.
827   */
828  #define LIVELOCK_TIMEFRAME(freq)	((freq) >> 2)	/* 1/4 second */
829  
830  static void
ithread_handler(void * arg)831  ithread_handler(void *arg)
832  {
833      struct intr_info *info;
834      int use_limit;
835      uint32_t lseconds;
836      int intr, cpuid = mycpuid;
837      int mpheld;
838      struct intrec **list;
839      intrec_t rec, nrec;
840      globaldata_t gd;
841      struct systimer ill_timer;	/* enforced freq. timer */
842      u_int ill_count;		/* interrupt livelock counter */
843      int upper_limit;		/* interrupt livelock upper limit */
844      TD_INVARIANTS_DECLARE;
845  
846      ill_count = 0;
847      intr = (int)(intptr_t)arg;
848      info = &intr_block->ary[cpuid][intr];
849      list = &info->i_reclist;
850  
851      /*
852       * The loop must be entered with one critical section held.  The thread
853       * does not hold the mplock on startup.
854       */
855      gd = mycpu;
856      lseconds = gd->gd_time_seconds;
857      crit_enter_gd(gd);
858      mpheld = 0;
859  
860      for (;;) {
861  	/*
862  	 * The chain is only considered MPSAFE if all its interrupt handlers
863  	 * are MPSAFE.  However, if intr_mpsafe has been turned off we
864  	 * always operate with the BGL.
865  	 */
866  	if (info->i_mplock_required != mpheld) {
867  	    if (info->i_mplock_required) {
868  		KKASSERT(mpheld == 0);
869  		get_mplock();
870  		mpheld = 1;
871  	    } else {
872  		KKASSERT(mpheld != 0);
873  		rel_mplock();
874  		mpheld = 0;
875  	    }
876  	}
877  
878  	TD_INVARIANTS_GET(gd->gd_curthread);
879  
880  	/*
881  	 * If an interrupt is pending, clear i_running and execute the
882  	 * handlers.  Note that certain types of interrupts can re-trigger
883  	 * and set i_running again.
884  	 *
885  	 * Each handler is run in a critical section.  Note that we run both
886  	 * FAST and SLOW designated service routines.
887  	 */
888  	if (info->i_running) {
889  	    ++ill_count;
890  	    info->i_running = 0;
891  
892  	    if (*list == NULL)
893  		report_stray_interrupt(info, "ithread_handler");
894  
895  	    for (rec = *list; rec; rec = nrec) {
896  		/* rec may be invalid after call */
897  		nrec = rec->next;
898  		if (rec->handler == NULL) {
899  		    kprintf("NULL HANDLER %s\n", rec->name);
900  		} else
901  		if (rec->serializer) {
902  		    lwkt_serialize_handler_call(rec->serializer, rec->handler,
903  						rec->argument, NULL);
904  		} else {
905  		    rec->handler(rec->argument, NULL);
906  		}
907  		TD_INVARIANTS_TEST(gd->gd_curthread, rec->name);
908  	    }
909  	}
910  
911  	/*
912  	 * This is our interrupt hook to add rate randomness to the random
913  	 * number generator.
914  	 */
915  	if (info->i_random.sc_enabled > 0)
916  	    add_interrupt_randomness(intr);
917  
918  	/*
919  	 * Unmask the interrupt to allow it to trigger again.  This only
920  	 * applies to certain types of interrupts (typ level interrupts).
921  	 * This can result in the interrupt retriggering, but the retrigger
922  	 * will not be processed until we cycle our critical section.
923  	 *
924  	 * Only unmask interrupts while handlers are installed.  It is
925  	 * possible to hit a situation where no handlers are installed
926  	 * due to a device driver livelocking and then tearing down its
927  	 * interrupt on close (the parallel bus being a good example).
928  	 */
929  	if (intr < FIRST_SOFTINT && *list)
930  	    machintr_intr_enable(intr);
931  
932  	/*
933  	 * Do a quick exit/enter to catch any higher-priority interrupt
934  	 * sources, such as the statclock, so thread time accounting
935  	 * will still work.  This may also cause an interrupt to re-trigger.
936  	 */
937  	crit_exit_gd(gd);
938  	crit_enter_gd(gd);
939  
940  	/*
941  	 * LIVELOCK STATE MACHINE
942  	 */
943  	switch(info->i_state) {
944  	case ISTATE_NORMAL:
945  	    /*
946  	     * Reset the count each second.
947  	     */
948  	    if (lseconds != gd->gd_time_seconds) {
949  		lseconds = gd->gd_time_seconds;
950  		ill_count = 0;
951  	    }
952  
953  	    /*
954  	     * If we did not exceed the frequency limit, we are done.
955  	     * If the interrupt has not retriggered we deschedule ourselves.
956  	     */
957  	    if (info->i_flags & INTR_HIFREQ)
958  		upper_limit = livelock_limit_hi;
959  	    else
960  		upper_limit = livelock_limit;
961  	    if (ill_count <= upper_limit) {
962  		if (info->i_running == 0) {
963  		    lwkt_deschedule_self(gd->gd_curthread);
964  		    lwkt_switch();
965  		}
966  		break;
967  	    }
968  
969  	    /*
970  	     * Otherwise we are livelocked.  Set up a periodic systimer
971  	     * to wake the thread up at the limit frequency.
972  	     */
973  	    kprintf("intr %d on cpu%d at %d/%d hz, livelocked limit engaged!\n",
974  		    intr, cpuid, ill_count, upper_limit);
975  	    info->i_state = ISTATE_LIVELOCKED;
976  	    if ((use_limit = upper_limit) < 100)
977  		use_limit = 100;
978  	    else if (use_limit > 500000)
979  		use_limit = 500000;
980  	    systimer_init_periodic_nq(&ill_timer, ithread_livelock_wakeup,
981  				      (void *)(intptr_t)intr, use_limit);
982  	    /* fall through */
983  	case ISTATE_LIVELOCKED:
984  	    /*
985  	     * Wait for our periodic timer to go off.  Since the interrupt
986  	     * has re-armed it can still set i_running, but it will not
987  	     * reschedule us while we are in a livelocked state.
988  	     */
989  	    lwkt_deschedule_self(gd->gd_curthread);
990  	    lwkt_switch();
991  
992  	    /*
993  	     * Check once a second to see if the livelock condition no
994  	     * longer applies.
995  	     */
996  	    if (lseconds != gd->gd_time_seconds) {
997  		lseconds = gd->gd_time_seconds;
998  		if (ill_count < livelock_lowater) {
999  		    info->i_state = ISTATE_NORMAL;
1000  		    systimer_del(&ill_timer);
1001  		    kprintf("intr %d on cpu%d at %d/%d hz, livelock removed\n",
1002  			    intr, cpuid, ill_count, livelock_lowater);
1003  		} else if (livelock_debug == intr ||
1004  			   (bootverbose && cold)) {
1005  		    kprintf("intr %d on cpu%d at %d/%d hz, in livelock\n",
1006  			    intr, cpuid, ill_count, livelock_lowater);
1007  		}
1008  		ill_count = 0;
1009  	    }
1010  	    break;
1011  	}
1012      }
1013      /* NOT REACHED */
1014  }
1015  
1016  /*
1017   * Emergency interrupt polling thread.  The thread begins execution
1018   * outside a critical section with the BGL held.
1019   *
1020   * If emergency interrupt polling is enabled, this thread will
1021   * execute all system interrupts not marked INTR_NOPOLL at the
1022   * specified polling frequency.
1023   *
1024   * WARNING!  This thread runs *ALL* interrupt service routines that
1025   * are not marked INTR_NOPOLL, which basically means everything except
1026   * the 8254 clock interrupt and the ATA interrupt.  It has very high
1027   * overhead and should only be used in situations where the machine
1028   * cannot otherwise be made to work.  Due to the severe performance
1029   * degredation, it should not be enabled on production machines.
1030   */
1031  static void
ithread_emergency(void * arg __unused)1032  ithread_emergency(void *arg __unused)
1033  {
1034      globaldata_t gd = mycpu;
1035      struct intr_info *info;
1036      intrec_t rec, nrec;
1037      int intr, cpuid = mycpuid;
1038      TD_INVARIANTS_DECLARE;
1039  
1040      get_mplock();
1041      crit_enter_gd(gd);
1042      TD_INVARIANTS_GET(gd->gd_curthread);
1043  
1044      for (;;) {
1045  	for (intr = 0; intr < max_installed_hard_intr[cpuid]; ++intr) {
1046  	    info = &intr_block->ary[cpuid][intr];
1047  	    for (rec = info->i_reclist; rec; rec = nrec) {
1048  		/* rec may be invalid after call */
1049  		nrec = rec->next;
1050  		if ((rec->intr_flags & INTR_NOPOLL) == 0) {
1051  		    if (rec->serializer) {
1052  			lwkt_serialize_handler_try(rec->serializer,
1053  						rec->handler, rec->argument, NULL);
1054  		    } else {
1055  			rec->handler(rec->argument, NULL);
1056  		    }
1057  		    TD_INVARIANTS_TEST(gd->gd_curthread, rec->name);
1058  		}
1059  	    }
1060  	}
1061  	lwkt_deschedule_self(gd->gd_curthread);
1062  	lwkt_switch();
1063      }
1064      /* NOT REACHED */
1065  }
1066  
1067  /*
1068   * Systimer callback - schedule the emergency interrupt poll thread
1069   * 		       if emergency polling is enabled.
1070   */
1071  static
1072  void
emergency_intr_timer_callback(systimer_t info,int in_ipi __unused,struct intrframe * frame __unused)1073  emergency_intr_timer_callback(systimer_t info, int in_ipi __unused,
1074      struct intrframe *frame __unused)
1075  {
1076      if (emergency_intr_enable)
1077  	lwkt_schedule(info->data);
1078  }
1079  
1080  /*
1081   * Sysctls used by systat and others: hw.intrnames and hw.intrcnt.
1082   * The data for this machine dependent, and the declarations are in machine
1083   * dependent code.  The layout of intrnames and intrcnt however is machine
1084   * independent.
1085   *
1086   * We do not know the length of intrcnt and intrnames at compile time, so
1087   * calculate things at run time.
1088   */
1089  
1090  static int
sysctl_intrnames(SYSCTL_HANDLER_ARGS)1091  sysctl_intrnames(SYSCTL_HANDLER_ARGS)
1092  {
1093      struct intr_info *info;
1094      intrec_t rec;
1095      int error = 0;
1096      int len;
1097      int intr, cpuid;
1098      char buf[64];
1099  
1100      for (cpuid = 0; cpuid < ncpus; ++cpuid) {
1101  	for (intr = 0; error == 0 && intr < MAX_INTS; ++intr) {
1102  	    info = &intr_block->ary[cpuid][intr];
1103  
1104  	    len = 0;
1105  	    buf[0] = 0;
1106  	    for (rec = info->i_reclist; rec; rec = rec->next) {
1107  		ksnprintf(buf + len, sizeof(buf) - len, "%s%s",
1108  		    (len ? "/" : ""), rec->name);
1109  		len += strlen(buf + len);
1110  	    }
1111  	    if (len == 0) {
1112  		ksnprintf(buf, sizeof(buf), "irq%d", intr);
1113  		len = strlen(buf);
1114  	    }
1115  	    error = SYSCTL_OUT(req, buf, len + 1);
1116  	}
1117      }
1118      return (error);
1119  }
1120  
1121  SYSCTL_PROC(_hw, OID_AUTO, intrnames, CTLTYPE_OPAQUE | CTLFLAG_RD,
1122  	NULL, 0, sysctl_intrnames, "", "Interrupt Names");
1123  
1124  static int
sysctl_intrcnt_all(SYSCTL_HANDLER_ARGS)1125  sysctl_intrcnt_all(SYSCTL_HANDLER_ARGS)
1126  {
1127      struct intr_info *info;
1128      int error = 0;
1129      int intr, cpuid;
1130  
1131      for (cpuid = 0; cpuid < ncpus; ++cpuid) {
1132  	for (intr = 0; intr < MAX_INTS; ++intr) {
1133  	    info = &intr_block->ary[cpuid][intr];
1134  
1135  	    error = SYSCTL_OUT(req, &info->i_count, sizeof(info->i_count));
1136  	    if (error)
1137  		goto failed;
1138  	}
1139      }
1140  failed:
1141      return(error);
1142  }
1143  
1144  SYSCTL_PROC(_hw, OID_AUTO, intrcnt_all, CTLTYPE_OPAQUE | CTLFLAG_RD,
1145  	NULL, 0, sysctl_intrcnt_all, "", "Interrupt Counts");
1146  
1147  SYSCTL_PROC(_hw, OID_AUTO, intrcnt, CTLTYPE_OPAQUE | CTLFLAG_RD,
1148  	NULL, 0, sysctl_intrcnt_all, "", "Interrupt Counts");
1149  
1150  static void
int_moveto_destcpu(int * orig_cpuid0,int cpuid)1151  int_moveto_destcpu(int *orig_cpuid0, int cpuid)
1152  {
1153      int orig_cpuid = mycpuid;
1154  
1155      if (cpuid != orig_cpuid)
1156  	lwkt_migratecpu(cpuid);
1157  
1158      *orig_cpuid0 = orig_cpuid;
1159  }
1160  
1161  static void
int_moveto_origcpu(int orig_cpuid,int cpuid)1162  int_moveto_origcpu(int orig_cpuid, int cpuid)
1163  {
1164      if (cpuid != orig_cpuid)
1165  	lwkt_migratecpu(orig_cpuid);
1166  }
1167  
1168  static void
intr_init(void * dummy __unused)1169  intr_init(void *dummy __unused)
1170  {
1171  	int cpuid;
1172  
1173  	kprintf("Initialize MI interrupts for %d cpus\n", ncpus);
1174  
1175  	intr_block = kmalloc(offsetof(struct intr_info_block, ary[ncpus][0]),
1176  			     M_INTRMNG, M_INTWAIT | M_ZERO);
1177  
1178  	for (cpuid = 0; cpuid < ncpus; ++cpuid) {
1179  		int intr;
1180  
1181  		for (intr = 0; intr < MAX_INTS; ++intr) {
1182  			struct intr_info *info = &intr_block->ary[cpuid][intr];
1183  
1184  			info->i_cpuid = cpuid;
1185  			info->i_intr = intr;
1186  		}
1187  	}
1188  }
1189  SYSINIT(intr_init, SI_BOOT2_FINISH_PIC, SI_ORDER_ANY, intr_init, NULL);
1190