Index: head/sys/amd64/amd64/fpu.c =================================================================== --- head/sys/amd64/amd64/fpu.c (revision 328523) +++ head/sys/amd64/amd64/fpu.c (revision 328524) @@ -1,1112 +1,1113 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 1990 William Jolitz. * Copyright (c) 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)npx.c 7.2 (Berkeley) 5/12/91 */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * Floating point support. */ #if defined(__GNUCLIKE_ASM) && !defined(lint) #define fldcw(cw) __asm __volatile("fldcw %0" : : "m" (cw)) #define fnclex() __asm __volatile("fnclex") #define fninit() __asm __volatile("fninit") #define fnstcw(addr) __asm __volatile("fnstcw %0" : "=m" (*(addr))) #define fnstsw(addr) __asm __volatile("fnstsw %0" : "=am" (*(addr))) #define fxrstor(addr) __asm __volatile("fxrstor %0" : : "m" (*(addr))) #define fxsave(addr) __asm __volatile("fxsave %0" : "=m" (*(addr))) #define ldmxcsr(csr) __asm __volatile("ldmxcsr %0" : : "m" (csr)) #define stmxcsr(addr) __asm __volatile("stmxcsr %0" : : "m" (*(addr))) static __inline void xrstor(char *addr, uint64_t mask) { uint32_t low, hi; low = mask; hi = mask >> 32; __asm __volatile("xrstor %0" : : "m" (*addr), "a" (low), "d" (hi)); } static __inline void xsave(char *addr, uint64_t mask) { uint32_t low, hi; low = mask; hi = mask >> 32; __asm __volatile("xsave %0" : "=m" (*addr) : "a" (low), "d" (hi) : "memory"); } #else /* !(__GNUCLIKE_ASM && !lint) */ void fldcw(u_short cw); void fnclex(void); void fninit(void); void fnstcw(caddr_t addr); void fnstsw(caddr_t addr); void fxsave(caddr_t addr); void fxrstor(caddr_t addr); void ldmxcsr(u_int csr); void stmxcsr(u_int *csr); void xrstor(char *addr, uint64_t mask); void xsave(char *addr, uint64_t mask); #endif /* __GNUCLIKE_ASM && !lint */ #define start_emulating() load_cr0(rcr0() | CR0_TS) #define stop_emulating() clts() CTASSERT(sizeof(struct savefpu) == 512); CTASSERT(sizeof(struct xstate_hdr) == 64); CTASSERT(sizeof(struct savefpu_ymm) == 832); /* * This requirement is to make it easier for asm code to calculate * offset of the fpu save area from the pcb address. FPU save area * must be 64-byte aligned. */ CTASSERT(sizeof(struct pcb) % XSAVE_AREA_ALIGN == 0); /* * Ensure the copy of XCR0 saved in a core is contained in the padding * area. */ CTASSERT(X86_XSTATE_XCR0_OFFSET >= offsetof(struct savefpu, sv_pad) && X86_XSTATE_XCR0_OFFSET + sizeof(uint64_t) <= sizeof(struct savefpu)); static void fpu_clean_state(void); SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD, SYSCTL_NULL_INT_PTR, 1, "Floating point instructions executed in hardware"); int use_xsave; /* non-static for cpu_switch.S */ uint64_t xsave_mask; /* the same */ static uma_zone_t fpu_save_area_zone; static struct savefpu *fpu_initialstate; struct xsave_area_elm_descr { u_int offset; u_int size; } *xsave_area_desc; void fpusave(void *addr) { if (use_xsave) xsave((char *)addr, xsave_mask); else fxsave((char *)addr); } void fpurestore(void *addr) { if (use_xsave) xrstor((char *)addr, xsave_mask); else fxrstor((char *)addr); } void fpususpend(void *addr) { u_long cr0; cr0 = rcr0(); stop_emulating(); fpusave(addr); load_cr0(cr0); } void fpuresume(void *addr) { u_long cr0; cr0 = rcr0(); stop_emulating(); fninit(); if (use_xsave) load_xcr(XCR0, xsave_mask); fpurestore(addr); load_cr0(cr0); } /* * Enable XSAVE if supported and allowed by user. * Calculate the xsave_mask. */ static void fpuinit_bsp1(void) { u_int cp[4]; uint64_t xsave_mask_user; if ((cpu_feature2 & CPUID2_XSAVE) != 0) { use_xsave = 1; TUNABLE_INT_FETCH("hw.use_xsave", &use_xsave); } if (!use_xsave) return; cpuid_count(0xd, 0x0, cp); xsave_mask = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE; if ((cp[0] & xsave_mask) != xsave_mask) panic("CPU0 does not support X87 or SSE: %x", cp[0]); xsave_mask = ((uint64_t)cp[3] << 32) | cp[0]; xsave_mask_user = xsave_mask; TUNABLE_ULONG_FETCH("hw.xsave_mask", &xsave_mask_user); xsave_mask_user |= XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE; xsave_mask &= xsave_mask_user; if ((xsave_mask & XFEATURE_AVX512) != XFEATURE_AVX512) xsave_mask &= ~XFEATURE_AVX512; if ((xsave_mask & XFEATURE_MPX) != XFEATURE_MPX) xsave_mask &= ~XFEATURE_MPX; cpuid_count(0xd, 0x1, cp); if ((cp[0] & CPUID_EXTSTATE_XSAVEOPT) != 0) { /* * Patch the XSAVE instruction in the cpu_switch code * to XSAVEOPT. We assume that XSAVE encoding used * REX byte, and set the bit 4 of the r/m byte. */ ctx_switch_xsave[3] |= 0x10; } } /* * Calculate the fpu save area size. */ static void fpuinit_bsp2(void) { u_int cp[4]; if (use_xsave) { cpuid_count(0xd, 0x0, cp); cpu_max_ext_state_size = cp[1]; /* * Reload the cpu_feature2, since we enabled OSXSAVE. */ do_cpuid(1, cp); cpu_feature2 = cp[2]; } else cpu_max_ext_state_size = sizeof(struct savefpu); } /* * Initialize the floating point unit. */ void fpuinit(void) { register_t saveintr; u_int mxcsr; u_short control; if (IS_BSP()) fpuinit_bsp1(); if (use_xsave) { load_cr4(rcr4() | CR4_XSAVE); load_xcr(XCR0, xsave_mask); } /* * XCR0 shall be set up before CPU can report the save area size. */ if (IS_BSP()) fpuinit_bsp2(); /* * It is too early for critical_enter() to work on AP. */ saveintr = intr_disable(); stop_emulating(); fninit(); control = __INITIAL_FPUCW__; fldcw(control); mxcsr = __INITIAL_MXCSR__; ldmxcsr(mxcsr); start_emulating(); intr_restore(saveintr); } /* * On the boot CPU we generate a clean state that is used to * initialize the floating point unit when it is first used by a * process. */ static void fpuinitstate(void *arg __unused) { register_t saveintr; int cp[4], i, max_ext_n; fpu_initialstate = malloc(cpu_max_ext_state_size, M_DEVBUF, M_WAITOK | M_ZERO); saveintr = intr_disable(); stop_emulating(); fpusave(fpu_initialstate); if (fpu_initialstate->sv_env.en_mxcsr_mask) cpu_mxcsr_mask = fpu_initialstate->sv_env.en_mxcsr_mask; else cpu_mxcsr_mask = 0xFFBF; /* * The fninit instruction does not modify XMM registers or x87 * registers (MM/ST). The fpusave call dumped the garbage * contained in the registers after reset to the initial state * saved. Clear XMM and x87 registers file image to make the * startup program state and signal handler XMM/x87 register * content predictable. */ bzero(fpu_initialstate->sv_fp, sizeof(fpu_initialstate->sv_fp)); bzero(fpu_initialstate->sv_xmm, sizeof(fpu_initialstate->sv_xmm)); /* * Create a table describing the layout of the CPU Extended * Save Area. */ if (use_xsave) { max_ext_n = flsl(xsave_mask); xsave_area_desc = malloc(max_ext_n * sizeof(struct xsave_area_elm_descr), M_DEVBUF, M_WAITOK | M_ZERO); /* x87 state */ xsave_area_desc[0].offset = 0; xsave_area_desc[0].size = 160; /* XMM */ xsave_area_desc[1].offset = 160; xsave_area_desc[1].size = 288 - 160; for (i = 2; i < max_ext_n; i++) { cpuid_count(0xd, i, cp); xsave_area_desc[i].offset = cp[1]; xsave_area_desc[i].size = cp[0]; } } fpu_save_area_zone = uma_zcreate("FPU_save_area", cpu_max_ext_state_size, NULL, NULL, NULL, NULL, XSAVE_AREA_ALIGN - 1, 0); start_emulating(); intr_restore(saveintr); } SYSINIT(fpuinitstate, SI_SUB_DRIVERS, SI_ORDER_ANY, fpuinitstate, NULL); /* * Free coprocessor (if we have it). */ void fpuexit(struct thread *td) { critical_enter(); if (curthread == PCPU_GET(fpcurthread)) { stop_emulating(); fpusave(curpcb->pcb_save); start_emulating(); PCPU_SET(fpcurthread, NULL); } critical_exit(); } int fpuformat(void) { return (_MC_FPFMT_XMM); } /* * The following mechanism is used to ensure that the FPE_... value * that is passed as a trapcode to the signal handler of the user * process does not have more than one bit set. * * Multiple bits may be set if the user process modifies the control * word while a status word bit is already set. While this is a sign * of bad coding, we have no choise than to narrow them down to one * bit, since we must not send a trapcode that is not exactly one of * the FPE_ macros. * * The mechanism has a static table with 127 entries. Each combination * of the 7 FPU status word exception bits directly translates to a * position in this table, where a single FPE_... value is stored. * This FPE_... value stored there is considered the "most important" * of the exception bits and will be sent as the signal code. The * precedence of the bits is based upon Intel Document "Numerical * Applications", Chapter "Special Computational Situations". * * The macro to choose one of these values does these steps: 1) Throw * away status word bits that cannot be masked. 2) Throw away the bits * currently masked in the control word, assuming the user isn't * interested in them anymore. 3) Reinsert status word bit 7 (stack * fault) if it is set, which cannot be masked but must be presered. * 4) Use the remaining bits to point into the trapcode table. * * The 6 maskable bits in order of their preference, as stated in the * above referenced Intel manual: * 1 Invalid operation (FP_X_INV) * 1a Stack underflow * 1b Stack overflow * 1c Operand of unsupported format * 1d SNaN operand. * 2 QNaN operand (not an exception, irrelavant here) * 3 Any other invalid-operation not mentioned above or zero divide * (FP_X_INV, FP_X_DZ) * 4 Denormal operand (FP_X_DNML) * 5 Numeric over/underflow (FP_X_OFL, FP_X_UFL) * 6 Inexact result (FP_X_IMP) */ static char fpetable[128] = { 0, FPE_FLTINV, /* 1 - INV */ FPE_FLTUND, /* 2 - DNML */ FPE_FLTINV, /* 3 - INV | DNML */ FPE_FLTDIV, /* 4 - DZ */ FPE_FLTINV, /* 5 - INV | DZ */ FPE_FLTDIV, /* 6 - DNML | DZ */ FPE_FLTINV, /* 7 - INV | DNML | DZ */ FPE_FLTOVF, /* 8 - OFL */ FPE_FLTINV, /* 9 - INV | OFL */ FPE_FLTUND, /* A - DNML | OFL */ FPE_FLTINV, /* B - INV | DNML | OFL */ FPE_FLTDIV, /* C - DZ | OFL */ FPE_FLTINV, /* D - INV | DZ | OFL */ FPE_FLTDIV, /* E - DNML | DZ | OFL */ FPE_FLTINV, /* F - INV | DNML | DZ | OFL */ FPE_FLTUND, /* 10 - UFL */ FPE_FLTINV, /* 11 - INV | UFL */ FPE_FLTUND, /* 12 - DNML | UFL */ FPE_FLTINV, /* 13 - INV | DNML | UFL */ FPE_FLTDIV, /* 14 - DZ | UFL */ FPE_FLTINV, /* 15 - INV | DZ | UFL */ FPE_FLTDIV, /* 16 - DNML | DZ | UFL */ FPE_FLTINV, /* 17 - INV | DNML | DZ | UFL */ FPE_FLTOVF, /* 18 - OFL | UFL */ FPE_FLTINV, /* 19 - INV | OFL | UFL */ FPE_FLTUND, /* 1A - DNML | OFL | UFL */ FPE_FLTINV, /* 1B - INV | DNML | OFL | UFL */ FPE_FLTDIV, /* 1C - DZ | OFL | UFL */ FPE_FLTINV, /* 1D - INV | DZ | OFL | UFL */ FPE_FLTDIV, /* 1E - DNML | DZ | OFL | UFL */ FPE_FLTINV, /* 1F - INV | DNML | DZ | OFL | UFL */ FPE_FLTRES, /* 20 - IMP */ FPE_FLTINV, /* 21 - INV | IMP */ FPE_FLTUND, /* 22 - DNML | IMP */ FPE_FLTINV, /* 23 - INV | DNML | IMP */ FPE_FLTDIV, /* 24 - DZ | IMP */ FPE_FLTINV, /* 25 - INV | DZ | IMP */ FPE_FLTDIV, /* 26 - DNML | DZ | IMP */ FPE_FLTINV, /* 27 - INV | DNML | DZ | IMP */ FPE_FLTOVF, /* 28 - OFL | IMP */ FPE_FLTINV, /* 29 - INV | OFL | IMP */ FPE_FLTUND, /* 2A - DNML | OFL | IMP */ FPE_FLTINV, /* 2B - INV | DNML | OFL | IMP */ FPE_FLTDIV, /* 2C - DZ | OFL | IMP */ FPE_FLTINV, /* 2D - INV | DZ | OFL | IMP */ FPE_FLTDIV, /* 2E - DNML | DZ | OFL | IMP */ FPE_FLTINV, /* 2F - INV | DNML | DZ | OFL | IMP */ FPE_FLTUND, /* 30 - UFL | IMP */ FPE_FLTINV, /* 31 - INV | UFL | IMP */ FPE_FLTUND, /* 32 - DNML | UFL | IMP */ FPE_FLTINV, /* 33 - INV | DNML | UFL | IMP */ FPE_FLTDIV, /* 34 - DZ | UFL | IMP */ FPE_FLTINV, /* 35 - INV | DZ | UFL | IMP */ FPE_FLTDIV, /* 36 - DNML | DZ | UFL | IMP */ FPE_FLTINV, /* 37 - INV | DNML | DZ | UFL | IMP */ FPE_FLTOVF, /* 38 - OFL | UFL | IMP */ FPE_FLTINV, /* 39 - INV | OFL | UFL | IMP */ FPE_FLTUND, /* 3A - DNML | OFL | UFL | IMP */ FPE_FLTINV, /* 3B - INV | DNML | OFL | UFL | IMP */ FPE_FLTDIV, /* 3C - DZ | OFL | UFL | IMP */ FPE_FLTINV, /* 3D - INV | DZ | OFL | UFL | IMP */ FPE_FLTDIV, /* 3E - DNML | DZ | OFL | UFL | IMP */ FPE_FLTINV, /* 3F - INV | DNML | DZ | OFL | UFL | IMP */ FPE_FLTSUB, /* 40 - STK */ FPE_FLTSUB, /* 41 - INV | STK */ FPE_FLTUND, /* 42 - DNML | STK */ FPE_FLTSUB, /* 43 - INV | DNML | STK */ FPE_FLTDIV, /* 44 - DZ | STK */ FPE_FLTSUB, /* 45 - INV | DZ | STK */ FPE_FLTDIV, /* 46 - DNML | DZ | STK */ FPE_FLTSUB, /* 47 - INV | DNML | DZ | STK */ FPE_FLTOVF, /* 48 - OFL | STK */ FPE_FLTSUB, /* 49 - INV | OFL | STK */ FPE_FLTUND, /* 4A - DNML | OFL | STK */ FPE_FLTSUB, /* 4B - INV | DNML | OFL | STK */ FPE_FLTDIV, /* 4C - DZ | OFL | STK */ FPE_FLTSUB, /* 4D - INV | DZ | OFL | STK */ FPE_FLTDIV, /* 4E - DNML | DZ | OFL | STK */ FPE_FLTSUB, /* 4F - INV | DNML | DZ | OFL | STK */ FPE_FLTUND, /* 50 - UFL | STK */ FPE_FLTSUB, /* 51 - INV | UFL | STK */ FPE_FLTUND, /* 52 - DNML | UFL | STK */ FPE_FLTSUB, /* 53 - INV | DNML | UFL | STK */ FPE_FLTDIV, /* 54 - DZ | UFL | STK */ FPE_FLTSUB, /* 55 - INV | DZ | UFL | STK */ FPE_FLTDIV, /* 56 - DNML | DZ | UFL | STK */ FPE_FLTSUB, /* 57 - INV | DNML | DZ | UFL | STK */ FPE_FLTOVF, /* 58 - OFL | UFL | STK */ FPE_FLTSUB, /* 59 - INV | OFL | UFL | STK */ FPE_FLTUND, /* 5A - DNML | OFL | UFL | STK */ FPE_FLTSUB, /* 5B - INV | DNML | OFL | UFL | STK */ FPE_FLTDIV, /* 5C - DZ | OFL | UFL | STK */ FPE_FLTSUB, /* 5D - INV | DZ | OFL | UFL | STK */ FPE_FLTDIV, /* 5E - DNML | DZ | OFL | UFL | STK */ FPE_FLTSUB, /* 5F - INV | DNML | DZ | OFL | UFL | STK */ FPE_FLTRES, /* 60 - IMP | STK */ FPE_FLTSUB, /* 61 - INV | IMP | STK */ FPE_FLTUND, /* 62 - DNML | IMP | STK */ FPE_FLTSUB, /* 63 - INV | DNML | IMP | STK */ FPE_FLTDIV, /* 64 - DZ | IMP | STK */ FPE_FLTSUB, /* 65 - INV | DZ | IMP | STK */ FPE_FLTDIV, /* 66 - DNML | DZ | IMP | STK */ FPE_FLTSUB, /* 67 - INV | DNML | DZ | IMP | STK */ FPE_FLTOVF, /* 68 - OFL | IMP | STK */ FPE_FLTSUB, /* 69 - INV | OFL | IMP | STK */ FPE_FLTUND, /* 6A - DNML | OFL | IMP | STK */ FPE_FLTSUB, /* 6B - INV | DNML | OFL | IMP | STK */ FPE_FLTDIV, /* 6C - DZ | OFL | IMP | STK */ FPE_FLTSUB, /* 6D - INV | DZ | OFL | IMP | STK */ FPE_FLTDIV, /* 6E - DNML | DZ | OFL | IMP | STK */ FPE_FLTSUB, /* 6F - INV | DNML | DZ | OFL | IMP | STK */ FPE_FLTUND, /* 70 - UFL | IMP | STK */ FPE_FLTSUB, /* 71 - INV | UFL | IMP | STK */ FPE_FLTUND, /* 72 - DNML | UFL | IMP | STK */ FPE_FLTSUB, /* 73 - INV | DNML | UFL | IMP | STK */ FPE_FLTDIV, /* 74 - DZ | UFL | IMP | STK */ FPE_FLTSUB, /* 75 - INV | DZ | UFL | IMP | STK */ FPE_FLTDIV, /* 76 - DNML | DZ | UFL | IMP | STK */ FPE_FLTSUB, /* 77 - INV | DNML | DZ | UFL | IMP | STK */ FPE_FLTOVF, /* 78 - OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 79 - INV | OFL | UFL | IMP | STK */ FPE_FLTUND, /* 7A - DNML | OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 7B - INV | DNML | OFL | UFL | IMP | STK */ FPE_FLTDIV, /* 7C - DZ | OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 7D - INV | DZ | OFL | UFL | IMP | STK */ FPE_FLTDIV, /* 7E - DNML | DZ | OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */ }; /* * Read the FP status and control words, then generate si_code value * for SIGFPE. The error code chosen will be one of the * FPE_... macros. It will be sent as the second argument to old * BSD-style signal handlers and as "siginfo_t->si_code" (second * argument) to SA_SIGINFO signal handlers. * * Some time ago, we cleared the x87 exceptions with FNCLEX there. * Clearing exceptions was necessary mainly to avoid IRQ13 bugs. The * usermode code which understands the FPU hardware enough to enable * the exceptions, can also handle clearing the exception state in the * handler. The only consequence of not clearing the exception is the * rethrow of the SIGFPE on return from the signal handler and * reexecution of the corresponding instruction. * * For XMM traps, the exceptions were never cleared. */ int fputrap_x87(void) { struct savefpu *pcb_save; u_short control, status; critical_enter(); /* * Interrupt handling (for another interrupt) may have pushed the * state to memory. Fetch the relevant parts of the state from * wherever they are. */ if (PCPU_GET(fpcurthread) != curthread) { pcb_save = curpcb->pcb_save; control = pcb_save->sv_env.en_cw; status = pcb_save->sv_env.en_sw; } else { fnstcw(&control); fnstsw(&status); } critical_exit(); return (fpetable[status & ((~control & 0x3f) | 0x40)]); } int fputrap_sse(void) { u_int mxcsr; critical_enter(); if (PCPU_GET(fpcurthread) != curthread) mxcsr = curpcb->pcb_save->sv_env.en_mxcsr; else stmxcsr(&mxcsr); critical_exit(); return (fpetable[(mxcsr & (~mxcsr >> 7)) & 0x3f]); } /* * Device Not Available (DNA, #NM) exception handler. * * It would be better to switch FP context here (if curthread != * fpcurthread) and not necessarily for every context switch, but it * is too hard to access foreign pcb's. */ void fpudna(void) { /* * This handler is entered with interrupts enabled, so context * switches may occur before critical_enter() is executed. If * a context switch occurs, then when we regain control, our * state will have been completely restored. The CPU may * change underneath us, but the only part of our context that * lives in the CPU is CR0.TS and that will be "restored" by * setting it on the new CPU. */ critical_enter(); KASSERT((curpcb->pcb_flags & PCB_FPUNOSAVE) == 0, ("fpudna while in fpu_kern_enter(FPU_KERN_NOCTX)")); if (PCPU_GET(fpcurthread) == curthread) { printf("fpudna: fpcurthread == curthread\n"); stop_emulating(); critical_exit(); return; } if (PCPU_GET(fpcurthread) != NULL) { panic("fpudna: fpcurthread = %p (%d), curthread = %p (%d)\n", PCPU_GET(fpcurthread), PCPU_GET(fpcurthread)->td_tid, curthread, curthread->td_tid); } stop_emulating(); /* * Record new context early in case frstor causes a trap. */ PCPU_SET(fpcurthread, curthread); fpu_clean_state(); if ((curpcb->pcb_flags & PCB_FPUINITDONE) == 0) { /* * This is the first time this thread has used the FPU or * the PCB doesn't contain a clean FPU state. Explicitly * load an initial state. * * We prefer to restore the state from the actual save * area in PCB instead of directly loading from * fpu_initialstate, to ignite the XSAVEOPT * tracking engine. */ bcopy(fpu_initialstate, curpcb->pcb_save, cpu_max_ext_state_size); fpurestore(curpcb->pcb_save); if (curpcb->pcb_initial_fpucw != __INITIAL_FPUCW__) fldcw(curpcb->pcb_initial_fpucw); if (PCB_USER_FPU(curpcb)) set_pcb_flags(curpcb, PCB_FPUINITDONE | PCB_USERFPUINITDONE); else set_pcb_flags(curpcb, PCB_FPUINITDONE); } else fpurestore(curpcb->pcb_save); critical_exit(); } void fpudrop(void) { struct thread *td; td = PCPU_GET(fpcurthread); KASSERT(td == curthread, ("fpudrop: fpcurthread != curthread")); CRITICAL_ASSERT(td); PCPU_SET(fpcurthread, NULL); clear_pcb_flags(td->td_pcb, PCB_FPUINITDONE); start_emulating(); } /* * Get the user state of the FPU into pcb->pcb_user_save without * dropping ownership (if possible). It returns the FPU ownership * status. */ int fpugetregs(struct thread *td) { struct pcb *pcb; uint64_t *xstate_bv, bit; char *sa; int max_ext_n, i, owned; pcb = td->td_pcb; if ((pcb->pcb_flags & PCB_USERFPUINITDONE) == 0) { bcopy(fpu_initialstate, get_pcb_user_save_pcb(pcb), cpu_max_ext_state_size); get_pcb_user_save_pcb(pcb)->sv_env.en_cw = pcb->pcb_initial_fpucw; fpuuserinited(td); return (_MC_FPOWNED_PCB); } critical_enter(); if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) { fpusave(get_pcb_user_save_pcb(pcb)); owned = _MC_FPOWNED_FPU; } else { owned = _MC_FPOWNED_PCB; } critical_exit(); if (use_xsave) { /* * Handle partially saved state. */ sa = (char *)get_pcb_user_save_pcb(pcb); xstate_bv = (uint64_t *)(sa + sizeof(struct savefpu) + offsetof(struct xstate_hdr, xstate_bv)); max_ext_n = flsl(xsave_mask); for (i = 0; i < max_ext_n; i++) { bit = 1ULL << i; if ((xsave_mask & bit) == 0 || (*xstate_bv & bit) != 0) continue; bcopy((char *)fpu_initialstate + xsave_area_desc[i].offset, sa + xsave_area_desc[i].offset, xsave_area_desc[i].size); *xstate_bv |= bit; } } return (owned); } void fpuuserinited(struct thread *td) { struct pcb *pcb; pcb = td->td_pcb; if (PCB_USER_FPU(pcb)) set_pcb_flags(pcb, PCB_FPUINITDONE | PCB_USERFPUINITDONE); else set_pcb_flags(pcb, PCB_FPUINITDONE); } int fpusetxstate(struct thread *td, char *xfpustate, size_t xfpustate_size) { struct xstate_hdr *hdr, *ehdr; size_t len, max_len; uint64_t bv; /* XXXKIB should we clear all extended state in xstate_bv instead ? */ if (xfpustate == NULL) return (0); if (!use_xsave) return (EOPNOTSUPP); len = xfpustate_size; if (len < sizeof(struct xstate_hdr)) return (EINVAL); max_len = cpu_max_ext_state_size - sizeof(struct savefpu); if (len > max_len) return (EINVAL); ehdr = (struct xstate_hdr *)xfpustate; bv = ehdr->xstate_bv; /* * Avoid #gp. */ if (bv & ~xsave_mask) return (EINVAL); hdr = (struct xstate_hdr *)(get_pcb_user_save_td(td) + 1); hdr->xstate_bv = bv; bcopy(xfpustate + sizeof(struct xstate_hdr), (char *)(hdr + 1), len - sizeof(struct xstate_hdr)); return (0); } /* * Set the state of the FPU. */ int fpusetregs(struct thread *td, struct savefpu *addr, char *xfpustate, size_t xfpustate_size) { struct pcb *pcb; int error; addr->sv_env.en_mxcsr &= cpu_mxcsr_mask; pcb = td->td_pcb; critical_enter(); if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) { error = fpusetxstate(td, xfpustate, xfpustate_size); if (error != 0) { critical_exit(); return (error); } bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr)); fpurestore(get_pcb_user_save_td(td)); critical_exit(); set_pcb_flags(pcb, PCB_FPUINITDONE | PCB_USERFPUINITDONE); } else { critical_exit(); error = fpusetxstate(td, xfpustate, xfpustate_size); if (error != 0) return (error); bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr)); fpuuserinited(td); } return (0); } /* * On AuthenticAMD processors, the fxrstor instruction does not restore * the x87's stored last instruction pointer, last data pointer, and last * opcode values, except in the rare case in which the exception summary * (ES) bit in the x87 status word is set to 1. * * In order to avoid leaking this information across processes, we clean * these values by performing a dummy load before executing fxrstor(). */ static void fpu_clean_state(void) { static float dummy_variable = 0.0; u_short status; /* * Clear the ES bit in the x87 status word if it is currently * set, in order to avoid causing a fault in the upcoming load. */ fnstsw(&status); if (status & 0x80) fnclex(); /* * Load the dummy variable into the x87 stack. This mangles * the x87 stack, but we don't care since we're about to call * fxrstor() anyway. */ __asm __volatile("ffree %%st(7); flds %0" : : "m" (dummy_variable)); } /* * This really sucks. We want the acpi version only, but it requires * the isa_if.h file in order to get the definitions. */ #include "opt_isa.h" #ifdef DEV_ISA #include /* * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI. */ static struct isa_pnp_id fpupnp_ids[] = { { 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */ { 0 } }; static int fpupnp_probe(device_t dev) { int result; result = ISA_PNP_PROBE(device_get_parent(dev), dev, fpupnp_ids); if (result <= 0) device_quiet(dev); return (result); } static int fpupnp_attach(device_t dev) { return (0); } static device_method_t fpupnp_methods[] = { /* Device interface */ DEVMETHOD(device_probe, fpupnp_probe), DEVMETHOD(device_attach, fpupnp_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), { 0, 0 } }; static driver_t fpupnp_driver = { "fpupnp", fpupnp_methods, 1, /* no softc */ }; static devclass_t fpupnp_devclass; DRIVER_MODULE(fpupnp, acpi, fpupnp_driver, fpupnp_devclass, 0, 0); +ISA_PNP_INFO(fpupnp_ids); #endif /* DEV_ISA */ static MALLOC_DEFINE(M_FPUKERN_CTX, "fpukern_ctx", "Kernel contexts for FPU state"); #define FPU_KERN_CTX_FPUINITDONE 0x01 #define FPU_KERN_CTX_DUMMY 0x02 /* avoided save for the kern thread */ #define FPU_KERN_CTX_INUSE 0x04 struct fpu_kern_ctx { struct savefpu *prev; uint32_t flags; char hwstate1[]; }; struct fpu_kern_ctx * fpu_kern_alloc_ctx(u_int flags) { struct fpu_kern_ctx *res; size_t sz; sz = sizeof(struct fpu_kern_ctx) + XSAVE_AREA_ALIGN + cpu_max_ext_state_size; res = malloc(sz, M_FPUKERN_CTX, ((flags & FPU_KERN_NOWAIT) ? M_NOWAIT : M_WAITOK) | M_ZERO); return (res); } void fpu_kern_free_ctx(struct fpu_kern_ctx *ctx) { KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) == 0, ("free'ing inuse ctx")); /* XXXKIB clear the memory ? */ free(ctx, M_FPUKERN_CTX); } static struct savefpu * fpu_kern_ctx_savefpu(struct fpu_kern_ctx *ctx) { vm_offset_t p; p = (vm_offset_t)&ctx->hwstate1; p = roundup2(p, XSAVE_AREA_ALIGN); return ((struct savefpu *)p); } int fpu_kern_enter(struct thread *td, struct fpu_kern_ctx *ctx, u_int flags) { struct pcb *pcb; pcb = td->td_pcb; KASSERT((flags & FPU_KERN_NOCTX) != 0 || ctx != NULL, ("ctx is required when !FPU_KERN_NOCTX")); KASSERT(ctx == NULL || (ctx->flags & FPU_KERN_CTX_INUSE) == 0, ("using inuse ctx")); KASSERT((pcb->pcb_flags & PCB_FPUNOSAVE) == 0, ("recursive fpu_kern_enter while in PCB_FPUNOSAVE state")); if ((flags & FPU_KERN_NOCTX) != 0) { critical_enter(); stop_emulating(); if (curthread == PCPU_GET(fpcurthread)) { fpusave(curpcb->pcb_save); PCPU_SET(fpcurthread, NULL); } else { KASSERT(PCPU_GET(fpcurthread) == NULL, ("invalid fpcurthread")); } /* * This breaks XSAVEOPT tracker, but * PCB_FPUNOSAVE state is supposed to never need to * save FPU context at all. */ fpurestore(fpu_initialstate); set_pcb_flags(pcb, PCB_KERNFPU | PCB_FPUNOSAVE | PCB_FPUINITDONE); return (0); } if ((flags & FPU_KERN_KTHR) != 0 && is_fpu_kern_thread(0)) { ctx->flags = FPU_KERN_CTX_DUMMY | FPU_KERN_CTX_INUSE; return (0); } KASSERT(!PCB_USER_FPU(pcb) || pcb->pcb_save == get_pcb_user_save_pcb(pcb), ("mangled pcb_save")); ctx->flags = FPU_KERN_CTX_INUSE; if ((pcb->pcb_flags & PCB_FPUINITDONE) != 0) ctx->flags |= FPU_KERN_CTX_FPUINITDONE; fpuexit(td); ctx->prev = pcb->pcb_save; pcb->pcb_save = fpu_kern_ctx_savefpu(ctx); set_pcb_flags(pcb, PCB_KERNFPU); clear_pcb_flags(pcb, PCB_FPUINITDONE); return (0); } int fpu_kern_leave(struct thread *td, struct fpu_kern_ctx *ctx) { struct pcb *pcb; pcb = td->td_pcb; if ((pcb->pcb_flags & PCB_FPUNOSAVE) != 0) { KASSERT(ctx == NULL, ("non-null ctx after FPU_KERN_NOCTX")); KASSERT(PCPU_GET(fpcurthread) == NULL, ("non-NULL fpcurthread for PCB_FPUNOSAVE")); CRITICAL_ASSERT(td); clear_pcb_flags(pcb, PCB_FPUNOSAVE | PCB_FPUINITDONE); start_emulating(); critical_exit(); } else { KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) != 0, ("leaving not inuse ctx")); ctx->flags &= ~FPU_KERN_CTX_INUSE; if (is_fpu_kern_thread(0) && (ctx->flags & FPU_KERN_CTX_DUMMY) != 0) return (0); KASSERT((ctx->flags & FPU_KERN_CTX_DUMMY) == 0, ("dummy ctx")); critical_enter(); if (curthread == PCPU_GET(fpcurthread)) fpudrop(); critical_exit(); pcb->pcb_save = ctx->prev; } if (pcb->pcb_save == get_pcb_user_save_pcb(pcb)) { if ((pcb->pcb_flags & PCB_USERFPUINITDONE) != 0) { set_pcb_flags(pcb, PCB_FPUINITDONE); clear_pcb_flags(pcb, PCB_KERNFPU); } else clear_pcb_flags(pcb, PCB_FPUINITDONE | PCB_KERNFPU); } else { if ((ctx->flags & FPU_KERN_CTX_FPUINITDONE) != 0) set_pcb_flags(pcb, PCB_FPUINITDONE); else clear_pcb_flags(pcb, PCB_FPUINITDONE); KASSERT(!PCB_USER_FPU(pcb), ("unpaired fpu_kern_leave")); } return (0); } int fpu_kern_thread(u_int flags) { KASSERT((curthread->td_pflags & TDP_KTHREAD) != 0, ("Only kthread may use fpu_kern_thread")); KASSERT(curpcb->pcb_save == get_pcb_user_save_pcb(curpcb), ("mangled pcb_save")); KASSERT(PCB_USER_FPU(curpcb), ("recursive call")); set_pcb_flags(curpcb, PCB_KERNFPU); return (0); } int is_fpu_kern_thread(u_int flags) { if ((curthread->td_pflags & TDP_KTHREAD) == 0) return (0); return ((curpcb->pcb_flags & PCB_KERNFPU) != 0); } /* * FPU save area alloc/free/init utility routines */ struct savefpu * fpu_save_area_alloc(void) { return (uma_zalloc(fpu_save_area_zone, 0)); } void fpu_save_area_free(struct savefpu *fsa) { uma_zfree(fpu_save_area_zone, fsa); } void fpu_save_area_reset(struct savefpu *fsa) { bcopy(fpu_initialstate, fsa, cpu_max_ext_state_size); } Index: head/sys/dev/ata/ata-isa.c =================================================================== --- head/sys/dev/ata/ata-isa.c (revision 328523) +++ head/sys/dev/ata/ata-isa.c (revision 328524) @@ -1,209 +1,210 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1998 - 2008 Søren Schmidt * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer, * without modification, immediately at the beginning of the file. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* local vars */ static struct isa_pnp_id ata_ids[] = { {0x0006d041, "Generic ESDI/IDE/ATA controller"}, /* PNP0600 */ {0x0106d041, "Plus Hardcard II"}, /* PNP0601 */ {0x0206d041, "Plus Hardcard IIXL/EZ"}, /* PNP0602 */ {0x0306d041, "Generic ATA"}, /* PNP0603 */ /* PNP0680 */ {0x8006d041, "Standard bus mastering IDE hard disk controller"}, {0} }; static int ata_isa_probe(device_t dev) { struct resource *io = NULL, *ctlio = NULL; rman_res_t tmp; int rid; /* check isapnp ids */ if (ISA_PNP_PROBE(device_get_parent(dev), dev, ata_ids) == ENXIO) return ENXIO; /* allocate the io port range */ rid = ATA_IOADDR_RID; if (!(io = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &rid, ATA_IOSIZE, RF_ACTIVE))) return ENXIO; /* set the altport range */ if (bus_get_resource(dev, SYS_RES_IOPORT, ATA_CTLADDR_RID, &tmp, &tmp)) { bus_set_resource(dev, SYS_RES_IOPORT, ATA_CTLADDR_RID, rman_get_start(io) + ATA_CTLOFFSET, ATA_CTLIOSIZE); } /* allocate the altport range */ rid = ATA_CTLADDR_RID; if (!(ctlio = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &rid, ATA_CTLIOSIZE, RF_ACTIVE))) { bus_release_resource(dev, SYS_RES_IOPORT, ATA_IOADDR_RID, io); return ENXIO; } /* Release resources to reallocate on attach. */ bus_release_resource(dev, SYS_RES_IOPORT, ATA_CTLADDR_RID, ctlio); bus_release_resource(dev, SYS_RES_IOPORT, ATA_IOADDR_RID, io); device_set_desc(dev, "ATA channel"); return (ata_probe(dev)); } static int ata_isa_attach(device_t dev) { struct ata_channel *ch = device_get_softc(dev); struct resource *io = NULL, *ctlio = NULL; rman_res_t tmp; int i, rid; if (ch->attached) return (0); ch->attached = 1; /* allocate the io port range */ rid = ATA_IOADDR_RID; if (!(io = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &rid, ATA_IOSIZE, RF_ACTIVE))) return ENXIO; /* set the altport range */ if (bus_get_resource(dev, SYS_RES_IOPORT, ATA_CTLADDR_RID, &tmp, &tmp)) { bus_set_resource(dev, SYS_RES_IOPORT, ATA_CTLADDR_RID, rman_get_start(io) + ATA_CTLOFFSET, ATA_CTLIOSIZE); } /* allocate the altport range */ rid = ATA_CTLADDR_RID; if (!(ctlio = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &rid, ATA_CTLIOSIZE, RF_ACTIVE))) { bus_release_resource(dev, SYS_RES_IOPORT, ATA_IOADDR_RID, io); return ENXIO; } /* setup the resource vectors */ for (i = ATA_DATA; i <= ATA_COMMAND; i++) { ch->r_io[i].res = io; ch->r_io[i].offset = i; } ch->r_io[ATA_CONTROL].res = ctlio; ch->r_io[ATA_CONTROL].offset = 0; ch->r_io[ATA_IDX_ADDR].res = io; ata_default_registers(dev); /* initialize softc for this channel */ ch->unit = 0; ch->flags |= ATA_USE_16BIT; ata_generic_hw(dev); return ata_attach(dev); } static int ata_isa_detach(device_t dev) { struct ata_channel *ch = device_get_softc(dev); int error; if (!ch->attached) return (0); ch->attached = 0; error = ata_detach(dev); bus_release_resource(dev, SYS_RES_IOPORT, ATA_CTLADDR_RID, ch->r_io[ATA_CONTROL].res); bus_release_resource(dev, SYS_RES_IOPORT, ATA_IOADDR_RID, ch->r_io[ATA_IDX_ADDR].res); return (error); } static int ata_isa_suspend(device_t dev) { struct ata_channel *ch = device_get_softc(dev); if (!ch->attached) return (0); return ata_suspend(dev); } static int ata_isa_resume(device_t dev) { struct ata_channel *ch = device_get_softc(dev); if (!ch->attached) return (0); return ata_resume(dev); } static device_method_t ata_isa_methods[] = { /* device interface */ DEVMETHOD(device_probe, ata_isa_probe), DEVMETHOD(device_attach, ata_isa_attach), DEVMETHOD(device_detach, ata_isa_detach), DEVMETHOD(device_suspend, ata_isa_suspend), DEVMETHOD(device_resume, ata_isa_resume), DEVMETHOD_END }; static driver_t ata_isa_driver = { "ata", ata_isa_methods, sizeof(struct ata_channel), }; DRIVER_MODULE(ata, isa, ata_isa_driver, ata_devclass, NULL, NULL); MODULE_DEPEND(ata, ata, 1, 1, 1); +ISA_PNP_INFO(ata_ids); Index: head/sys/dev/atkbdc/psm.c =================================================================== --- head/sys/dev/atkbdc/psm.c (revision 328523) +++ head/sys/dev/atkbdc/psm.c (revision 328524) @@ -1,7190 +1,7190 @@ /*- * Copyright (c) 1992, 1993 Erik Forsberg. * Copyright (c) 1996, 1997 Kazutaka YOKOTA. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL I BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Ported to 386bsd Oct 17, 1992 * Sandi Donno, Computer Science, University of Cape Town, South Africa * Please send bug reports to sandi@cs.uct.ac.za * * Thanks are also due to Rick Macklem, rick@snowhite.cis.uoguelph.ca - * although I was only partially successful in getting the alpha release * of his "driver for the Logitech and ATI Inport Bus mice for use with * 386bsd and the X386 port" to work with my Microsoft mouse, I nevertheless * found his code to be an invaluable reference when porting this driver * to 386bsd. * * Further modifications for latest 386BSD+patchkit and port to NetBSD, * Andrew Herbert - 8 June 1993 * * Cloned from the Microsoft Bus Mouse driver, also by Erik Forsberg, by * Andrew Herbert - 12 June 1993 * * Modified for PS/2 mouse by Charles Hannum * - 13 June 1993 * * Modified for PS/2 AUX mouse by Shoji Yuen * - 24 October 1993 * * Hardware access routines and probe logic rewritten by * Kazutaka Yokota * - 3, 14, 22 October 1996. * - 12 November 1996. IOCTLs and rearranging `psmread', `psmioctl'... * - 14, 30 November 1996. Uses `kbdio.c'. * - 13 December 1996. Uses queuing version of `kbdio.c'. * - January/February 1997. Tweaked probe logic for * HiNote UltraII/Latitude/Armada laptops. * - 30 July 1997. Added APM support. * - 5 March 1997. Defined driver configuration flags (PSM_CONFIG_XXX). * Improved sync check logic. * Vendor specific support routines. */ #include __FBSDID("$FreeBSD$"); #include "opt_isa.h" #include "opt_psm.h" #include "opt_evdev.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef DEV_ISA #include #endif #ifdef EVDEV_SUPPORT #include #include #endif #include #include /* * Driver specific options: the following options may be set by * `options' statements in the kernel configuration file. */ /* debugging */ #ifndef PSM_DEBUG #define PSM_DEBUG 0 /* * logging: 0: none, 1: brief, 2: verbose * 3: sync errors, 4: all packets */ #endif #define VLOG(level, args) do { \ if (verbose >= level) \ log args; \ } while (0) #ifndef PSM_INPUT_TIMEOUT #define PSM_INPUT_TIMEOUT 2000000 /* 2 sec */ #endif #ifndef PSM_TAP_TIMEOUT #define PSM_TAP_TIMEOUT 125000 #endif #ifndef PSM_TAP_THRESHOLD #define PSM_TAP_THRESHOLD 25 #endif /* end of driver specific options */ #define PSMCPNP_DRIVER_NAME "psmcpnp" /* input queue */ #define PSM_BUFSIZE 960 #define PSM_SMALLBUFSIZE 240 /* operation levels */ #define PSM_LEVEL_BASE 0 #define PSM_LEVEL_STANDARD 1 #define PSM_LEVEL_NATIVE 2 #define PSM_LEVEL_MIN PSM_LEVEL_BASE #define PSM_LEVEL_MAX PSM_LEVEL_NATIVE /* Logitech PS2++ protocol */ #define MOUSE_PS2PLUS_CHECKBITS(b) \ ((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f)) #define MOUSE_PS2PLUS_PACKET_TYPE(b) \ (((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4)) /* ring buffer */ typedef struct ringbuf { int count; /* # of valid elements in the buffer */ int head; /* head pointer */ int tail; /* tail poiner */ u_char buf[PSM_BUFSIZE]; } ringbuf_t; /* data buffer */ typedef struct packetbuf { u_char ipacket[16]; /* interim input buffer */ int inputbytes; /* # of bytes in the input buffer */ } packetbuf_t; #ifndef PSM_PACKETQUEUE #define PSM_PACKETQUEUE 128 #endif typedef struct synapticsinfo { struct sysctl_ctx_list sysctl_ctx; struct sysctl_oid *sysctl_tree; int directional_scrolls; int two_finger_scroll; int min_pressure; int max_pressure; int max_width; int margin_top; int margin_right; int margin_bottom; int margin_left; int na_top; int na_right; int na_bottom; int na_left; int window_min; int window_max; int multiplicator; int weight_current; int weight_previous; int weight_previous_na; int weight_len_squared; int div_min; int div_max; int div_max_na; int div_len; int tap_max_delta; int tap_min_queue; int taphold_timeout; int vscroll_ver_area; int vscroll_hor_area; int vscroll_min_delta; int vscroll_div_min; int vscroll_div_max; int touchpad_off; int softbuttons_y; int softbutton2_x; int softbutton3_x; int max_x; int max_y; } synapticsinfo_t; typedef struct synapticspacket { int x; int y; } synapticspacket_t; #define SYNAPTICS_PACKETQUEUE 10 #define SYNAPTICS_QUEUE_CURSOR(x) \ (x + SYNAPTICS_PACKETQUEUE) % SYNAPTICS_PACKETQUEUE #define SYNAPTICS_VERSION_GE(synhw, major, minor) \ ((synhw).infoMajor > (major) || \ ((synhw).infoMajor == (major) && (synhw).infoMinor >= (minor))) typedef struct smoother { synapticspacket_t queue[SYNAPTICS_PACKETQUEUE]; int queue_len; int queue_cursor; int start_x; int start_y; int avg_dx; int avg_dy; int squelch_x; int squelch_y; int is_fuzzy; int active; } smoother_t; typedef struct gesture { int window_min; int fingers_nb; int tap_button; int in_taphold; int in_vscroll; int zmax; /* maximum pressure value */ struct timeval taptimeout; /* tap timeout for touchpads */ } gesture_t; enum { TRACKPOINT_SYSCTL_SENSITIVITY, TRACKPOINT_SYSCTL_NEGATIVE_INERTIA, TRACKPOINT_SYSCTL_UPPER_PLATEAU, TRACKPOINT_SYSCTL_BACKUP_RANGE, TRACKPOINT_SYSCTL_DRAG_HYSTERESIS, TRACKPOINT_SYSCTL_MINIMUM_DRAG, TRACKPOINT_SYSCTL_UP_THRESHOLD, TRACKPOINT_SYSCTL_THRESHOLD, TRACKPOINT_SYSCTL_JENKS_CURVATURE, TRACKPOINT_SYSCTL_Z_TIME, TRACKPOINT_SYSCTL_PRESS_TO_SELECT, TRACKPOINT_SYSCTL_SKIP_BACKUPS }; typedef struct trackpointinfo { struct sysctl_ctx_list sysctl_ctx; struct sysctl_oid *sysctl_tree; int sensitivity; int inertia; int uplateau; int reach; int draghys; int mindrag; int upthresh; int threshold; int jenks; int ztime; int pts; int skipback; } trackpointinfo_t; typedef struct finger { int x; int y; int p; int w; int flags; } finger_t; #define PSM_FINGERS 2 /* # of processed fingers */ #define PSM_FINGER_IS_PEN (1<<0) #define PSM_FINGER_FUZZY (1<<1) #define PSM_FINGER_DEFAULT_P tap_threshold #define PSM_FINGER_DEFAULT_W 1 #define PSM_FINGER_IS_SET(f) ((f).x != -1 && (f).y != -1 && (f).p != 0) #define PSM_FINGER_RESET(f) do { \ (f) = (finger_t) { .x = -1, .y = -1, .p = 0, .w = 0, .flags = 0 }; \ } while (0) typedef struct elantechhw { int hwversion; int fwversion; int sizex; int sizey; int dpmmx; int dpmmy; int ntracesx; int ntracesy; int dptracex; int dptracey; int issemimt; int isclickpad; int hascrc; int hastrackpoint; int haspressure; } elantechhw_t; /* minimum versions supported by this driver */ #define ELANTECH_HW_IS_V1(fwver) ((fwver) < 0x020030 || (fwver) == 0x020600) #define ELANTECH_MAGIC(magic) \ ((magic)[0] == 0x3c && (magic)[1] == 0x03 && \ ((magic)[2] == 0xc8 || (magic)[2] == 0x00)) #define ELANTECH_FW_ID 0x00 #define ELANTECH_FW_VERSION 0x01 #define ELANTECH_CAPABILITIES 0x02 #define ELANTECH_SAMPLE 0x03 #define ELANTECH_RESOLUTION 0x04 #define ELANTECH_REG_READ 0x10 #define ELANTECH_REG_WRITE 0x11 #define ELANTECH_REG_RDWR 0x00 #define ELANTECH_CUSTOM_CMD 0xf8 #ifdef EVDEV_SUPPORT #define ELANTECH_MAX_FINGERS 5 #else #define ELANTECH_MAX_FINGERS PSM_FINGERS #endif #define ELANTECH_FINGER_MAX_P 255 #define ELANTECH_FINGER_MAX_W 15 #define ELANTECH_FINGER_SET_XYP(pb) (finger_t) { \ .x = (((pb)->ipacket[1] & 0x0f) << 8) | (pb)->ipacket[2], \ .y = (((pb)->ipacket[4] & 0x0f) << 8) | (pb)->ipacket[5], \ .p = ((pb)->ipacket[1] & 0xf0) | (((pb)->ipacket[4] >> 4) & 0x0f), \ .w = PSM_FINGER_DEFAULT_W, \ .flags = 0 \ } enum { ELANTECH_PKT_NOP, ELANTECH_PKT_TRACKPOINT, ELANTECH_PKT_V2_COMMON, ELANTECH_PKT_V2_2FINGER, ELANTECH_PKT_V3, ELANTECH_PKT_V4_STATUS, ELANTECH_PKT_V4_HEAD, ELANTECH_PKT_V4_MOTION }; #define ELANTECH_PKT_IS_TRACKPOINT(pb) (((pb)->ipacket[3] & 0x0f) == 0x06) #define ELANTECH_PKT_IS_DEBOUNCE(pb, hwversion) ((hwversion) == 4 ? 0 : \ (pb)->ipacket[0] == ((hwversion) == 2 ? 0x84 : 0xc4) && \ (pb)->ipacket[1] == 0xff && (pb)->ipacket[2] == 0xff && \ (pb)->ipacket[3] == 0x02 && (pb)->ipacket[4] == 0xff && \ (pb)->ipacket[5] == 0xff) #define ELANTECH_PKT_IS_V2(pb) \ (((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0x0f) == 0x02) #define ELANTECH_PKT_IS_V3_HEAD(pb, hascrc) ((hascrc) ? \ ((pb)->ipacket[3] & 0x09) == 0x08 : \ ((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0xcf) == 0x02) #define ELANTECH_PKT_IS_V3_TAIL(pb, hascrc) ((hascrc) ? \ ((pb)->ipacket[3] & 0x09) == 0x09 : \ ((pb)->ipacket[0] & 0x0c) == 0x0c && ((pb)->ipacket[3] & 0xce) == 0x0c) #define ELANTECH_PKT_IS_V4(pb, hascrc) ((hascrc) ? \ ((pb)->ipacket[3] & 0x08) == 0x00 : \ ((pb)->ipacket[0] & 0x0c) == 0x04 && ((pb)->ipacket[3] & 0x1c) == 0x10) typedef struct elantechaction { finger_t fingers[ELANTECH_MAX_FINGERS]; int mask; int mask_v4wait; } elantechaction_t; /* driver control block */ struct psm_softc { /* Driver status information */ int unit; struct selinfo rsel; /* Process selecting for Input */ u_char state; /* Mouse driver state */ int config; /* driver configuration flags */ int flags; /* other flags */ KBDC kbdc; /* handle to access kbd controller */ struct resource *intr; /* IRQ resource */ void *ih; /* interrupt handle */ mousehw_t hw; /* hardware information */ synapticshw_t synhw; /* Synaptics hardware information */ synapticsinfo_t syninfo; /* Synaptics configuration */ smoother_t smoother[PSM_FINGERS]; /* Motion smoothing */ gesture_t gesture; /* Gesture context */ elantechhw_t elanhw; /* Elantech hardware information */ elantechaction_t elanaction; /* Elantech action context */ int tphw; /* TrackPoint hardware information */ trackpointinfo_t tpinfo; /* TrackPoint configuration */ mousemode_t mode; /* operation mode */ mousemode_t dflt_mode; /* default operation mode */ mousestatus_t status; /* accumulated mouse movement */ ringbuf_t queue; /* mouse status queue */ packetbuf_t pqueue[PSM_PACKETQUEUE]; /* mouse data queue */ int pqueue_start; /* start of data in queue */ int pqueue_end; /* end of data in queue */ int button; /* the latest button state */ int xold; /* previous absolute X position */ int yold; /* previous absolute Y position */ int xaverage; /* average X position */ int yaverage; /* average Y position */ int squelch; /* level to filter movement at low speed */ int syncerrors; /* # of bytes discarded to synchronize */ int pkterrors; /* # of packets failed during quaranteen. */ struct timeval inputtimeout; struct timeval lastsoftintr; /* time of last soft interrupt */ struct timeval lastinputerr; /* time last sync error happened */ struct timeval idletimeout; packetbuf_t idlepacket; /* packet to send after idle timeout */ int watchdog; /* watchdog timer flag */ struct callout callout; /* watchdog timer call out */ struct callout softcallout; /* buffer timer call out */ struct cdev *dev; struct cdev *bdev; int lasterr; int cmdcount; struct sigio *async; /* Processes waiting for SIGIO */ int extended_buttons; #ifdef EVDEV_SUPPORT struct evdev_dev *evdev_a; /* Absolute reporting device */ struct evdev_dev *evdev_r; /* Relative reporting device */ #endif }; static devclass_t psm_devclass; /* driver state flags (state) */ #define PSM_VALID 0x80 #define PSM_OPEN 1 /* Device is open */ #define PSM_ASLP 2 /* Waiting for mouse data */ #define PSM_SOFTARMED 4 /* Software interrupt armed */ #define PSM_NEED_SYNCBITS 8 /* Set syncbits using next data pkt */ #define PSM_EV_OPEN_R 0x10 /* Relative evdev device is open */ #define PSM_EV_OPEN_A 0x20 /* Absolute evdev device is open */ /* driver configuration flags (config) */ #define PSM_CONFIG_RESOLUTION 0x000f /* resolution */ #define PSM_CONFIG_ACCEL 0x00f0 /* acceleration factor */ #define PSM_CONFIG_NOCHECKSYNC 0x0100 /* disable sync. test */ #define PSM_CONFIG_NOIDPROBE 0x0200 /* disable mouse model probe */ #define PSM_CONFIG_NORESET 0x0400 /* don't reset the mouse */ #define PSM_CONFIG_FORCETAP 0x0800 /* assume `tap' action exists */ #define PSM_CONFIG_IGNPORTERROR 0x1000 /* ignore error in aux port test */ #define PSM_CONFIG_HOOKRESUME 0x2000 /* hook the system resume event */ #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */ #define PSM_CONFIG_FLAGS \ (PSM_CONFIG_RESOLUTION | \ PSM_CONFIG_ACCEL | \ PSM_CONFIG_NOCHECKSYNC | \ PSM_CONFIG_NOIDPROBE | \ PSM_CONFIG_NORESET | \ PSM_CONFIG_FORCETAP | \ PSM_CONFIG_IGNPORTERROR | \ PSM_CONFIG_HOOKRESUME | \ PSM_CONFIG_INITAFTERSUSPEND) /* other flags (flags) */ #define PSM_FLAGS_FINGERDOWN 0x0001 /* VersaPad finger down */ #define kbdcp(p) ((atkbdc_softc_t *)(p)) #define ALWAYS_RESTORE_CONTROLLER(kbdc) !(kbdcp(kbdc)->quirks \ & KBDC_QUIRK_KEEP_ACTIVATED) /* Tunables */ static int tap_enabled = -1; static int verbose = PSM_DEBUG; static int synaptics_support = 0; static int trackpoint_support = 0; static int elantech_support = 0; /* for backward compatibility */ #define OLD_MOUSE_GETHWINFO _IOR('M', 1, old_mousehw_t) #define OLD_MOUSE_GETMODE _IOR('M', 2, old_mousemode_t) #define OLD_MOUSE_SETMODE _IOW('M', 3, old_mousemode_t) typedef struct old_mousehw { int buttons; int iftype; int type; int hwid; } old_mousehw_t; typedef struct old_mousemode { int protocol; int rate; int resolution; int accelfactor; } old_mousemode_t; #define SYN_OFFSET(field) offsetof(struct psm_softc, syninfo.field) enum { SYNAPTICS_SYSCTL_MIN_PRESSURE = SYN_OFFSET(min_pressure), SYNAPTICS_SYSCTL_MAX_PRESSURE = SYN_OFFSET(max_pressure), SYNAPTICS_SYSCTL_MAX_WIDTH = SYN_OFFSET(max_width), SYNAPTICS_SYSCTL_MARGIN_TOP = SYN_OFFSET(margin_top), SYNAPTICS_SYSCTL_MARGIN_RIGHT = SYN_OFFSET(margin_right), SYNAPTICS_SYSCTL_MARGIN_BOTTOM = SYN_OFFSET(margin_bottom), SYNAPTICS_SYSCTL_MARGIN_LEFT = SYN_OFFSET(margin_left), SYNAPTICS_SYSCTL_NA_TOP = SYN_OFFSET(na_top), SYNAPTICS_SYSCTL_NA_RIGHT = SYN_OFFSET(na_right), SYNAPTICS_SYSCTL_NA_BOTTOM = SYN_OFFSET(na_bottom), SYNAPTICS_SYSCTL_NA_LEFT = SYN_OFFSET(na_left), SYNAPTICS_SYSCTL_WINDOW_MIN = SYN_OFFSET(window_min), SYNAPTICS_SYSCTL_WINDOW_MAX = SYN_OFFSET(window_max), SYNAPTICS_SYSCTL_MULTIPLICATOR = SYN_OFFSET(multiplicator), SYNAPTICS_SYSCTL_WEIGHT_CURRENT = SYN_OFFSET(weight_current), SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS = SYN_OFFSET(weight_previous), SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA = SYN_OFFSET(weight_previous_na), SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED = SYN_OFFSET(weight_len_squared), SYNAPTICS_SYSCTL_DIV_MIN = SYN_OFFSET(div_min), SYNAPTICS_SYSCTL_DIV_MAX = SYN_OFFSET(div_max), SYNAPTICS_SYSCTL_DIV_MAX_NA = SYN_OFFSET(div_max_na), SYNAPTICS_SYSCTL_DIV_LEN = SYN_OFFSET(div_len), SYNAPTICS_SYSCTL_TAP_MAX_DELTA = SYN_OFFSET(tap_max_delta), SYNAPTICS_SYSCTL_TAP_MIN_QUEUE = SYN_OFFSET(tap_min_queue), SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT = SYN_OFFSET(taphold_timeout), SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA = SYN_OFFSET(vscroll_hor_area), SYNAPTICS_SYSCTL_VSCROLL_VER_AREA = SYN_OFFSET(vscroll_ver_area), SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA = SYN_OFFSET(vscroll_min_delta), SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN = SYN_OFFSET(vscroll_div_min), SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX = SYN_OFFSET(vscroll_div_max), SYNAPTICS_SYSCTL_TOUCHPAD_OFF = SYN_OFFSET(touchpad_off), SYNAPTICS_SYSCTL_SOFTBUTTONS_Y = SYN_OFFSET(softbuttons_y), SYNAPTICS_SYSCTL_SOFTBUTTON2_X = SYN_OFFSET(softbutton2_x), SYNAPTICS_SYSCTL_SOFTBUTTON3_X = SYN_OFFSET(softbutton3_x), }; /* packet formatting function */ typedef int packetfunc_t(struct psm_softc *, u_char *, int *, int, mousestatus_t *); /* function prototypes */ static void psmidentify(driver_t *, device_t); static int psmprobe(device_t); static int psmattach(device_t); static int psmdetach(device_t); static int psmresume(device_t); static d_open_t psm_cdev_open; static d_close_t psm_cdev_close; static d_read_t psmread; static d_write_t psmwrite; static d_ioctl_t psmioctl; static d_poll_t psmpoll; static int psmopen(struct psm_softc *); static int psmclose(struct psm_softc *); #ifdef EVDEV_SUPPORT static evdev_open_t psm_ev_open_r; static evdev_close_t psm_ev_close_r; static evdev_open_t psm_ev_open_a; static evdev_close_t psm_ev_close_a; #endif static int enable_aux_dev(KBDC); static int disable_aux_dev(KBDC); static int get_mouse_status(KBDC, int *, int, int); static int get_aux_id(KBDC); static int set_mouse_sampling_rate(KBDC, int); static int set_mouse_scaling(KBDC, int); static int set_mouse_resolution(KBDC, int); static int set_mouse_mode(KBDC); static int get_mouse_buttons(KBDC); static int is_a_mouse(int); static void recover_from_error(KBDC); static int restore_controller(KBDC, int); static int doinitialize(struct psm_softc *, mousemode_t *); static int doopen(struct psm_softc *, int); static int reinitialize(struct psm_softc *, int); static char *model_name(int); static void psmsoftintr(void *); static void psmsoftintridle(void *); static void psmintr(void *); static void psmtimeout(void *); static int timeelapsed(const struct timeval *, int, int, const struct timeval *); static void dropqueue(struct psm_softc *); static void flushpackets(struct psm_softc *); static void proc_mmanplus(struct psm_softc *, packetbuf_t *, mousestatus_t *, int *, int *, int *); static int proc_synaptics(struct psm_softc *, packetbuf_t *, mousestatus_t *, int *, int *, int *); static void proc_versapad(struct psm_softc *, packetbuf_t *, mousestatus_t *, int *, int *, int *); static int proc_elantech(struct psm_softc *, packetbuf_t *, mousestatus_t *, int *, int *, int *); static int psmpalmdetect(struct psm_softc *, finger_t *, int); static void psmgestures(struct psm_softc *, finger_t *, int, mousestatus_t *); static void psmsmoother(struct psm_softc *, finger_t *, int, mousestatus_t *, int *, int *); static int tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *, u_char *); /* vendor specific features */ enum probearg { PROBE, REINIT }; typedef int probefunc_t(struct psm_softc *, enum probearg); static int mouse_id_proc1(KBDC, int, int, int *); static int mouse_ext_command(KBDC, int); static probefunc_t enable_groller; static probefunc_t enable_gmouse; static probefunc_t enable_aglide; static probefunc_t enable_kmouse; static probefunc_t enable_msexplorer; static probefunc_t enable_msintelli; static probefunc_t enable_4dmouse; static probefunc_t enable_4dplus; static probefunc_t enable_mmanplus; static probefunc_t enable_synaptics; static probefunc_t enable_trackpoint; static probefunc_t enable_versapad; static probefunc_t enable_elantech; static void set_trackpoint_parameters(struct psm_softc *sc); static void synaptics_passthrough_on(struct psm_softc *sc); static void synaptics_passthrough_off(struct psm_softc *sc); static int synaptics_preferred_mode(struct psm_softc *sc); static void synaptics_set_mode(struct psm_softc *sc, int mode_byte); static struct { int model; u_char syncmask; int packetsize; probefunc_t *probefunc; } vendortype[] = { /* * WARNING: the order of probe is very important. Don't mess it * unless you know what you are doing. */ { MOUSE_MODEL_NET, /* Genius NetMouse */ 0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse }, { MOUSE_MODEL_NETSCROLL, /* Genius NetScroll */ 0xc8, 6, enable_groller }, { MOUSE_MODEL_MOUSEMANPLUS, /* Logitech MouseMan+ */ 0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus }, { MOUSE_MODEL_EXPLORER, /* Microsoft IntelliMouse Explorer */ 0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer }, { MOUSE_MODEL_4D, /* A4 Tech 4D Mouse */ 0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse }, { MOUSE_MODEL_4DPLUS, /* A4 Tech 4D+ Mouse */ 0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus }, { MOUSE_MODEL_SYNAPTICS, /* Synaptics Touchpad */ 0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics }, { MOUSE_MODEL_ELANTECH, /* Elantech Touchpad */ 0x04, MOUSE_ELANTECH_PACKETSIZE, enable_elantech }, { MOUSE_MODEL_INTELLI, /* Microsoft IntelliMouse */ 0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli }, { MOUSE_MODEL_GLIDEPOINT, /* ALPS GlidePoint */ 0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide }, { MOUSE_MODEL_THINK, /* Kensington ThinkingMouse */ 0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse }, { MOUSE_MODEL_VERSAPAD, /* Interlink electronics VersaPad */ 0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad }, { MOUSE_MODEL_TRACKPOINT, /* IBM/Lenovo TrackPoint */ 0xc0, MOUSE_PS2_PACKETSIZE, enable_trackpoint }, { MOUSE_MODEL_GENERIC, 0xc0, MOUSE_PS2_PACKETSIZE, NULL }, }; #define GENERIC_MOUSE_ENTRY (nitems(vendortype) - 1) /* device driver declarateion */ static device_method_t psm_methods[] = { /* Device interface */ DEVMETHOD(device_identify, psmidentify), DEVMETHOD(device_probe, psmprobe), DEVMETHOD(device_attach, psmattach), DEVMETHOD(device_detach, psmdetach), DEVMETHOD(device_resume, psmresume), { 0, 0 } }; static driver_t psm_driver = { PSM_DRIVER_NAME, psm_methods, sizeof(struct psm_softc), }; static struct cdevsw psm_cdevsw = { .d_version = D_VERSION, .d_flags = D_NEEDGIANT, .d_open = psm_cdev_open, .d_close = psm_cdev_close, .d_read = psmread, .d_write = psmwrite, .d_ioctl = psmioctl, .d_poll = psmpoll, .d_name = PSM_DRIVER_NAME, }; #ifdef EVDEV_SUPPORT static const struct evdev_methods psm_ev_methods_r = { .ev_open = psm_ev_open_r, .ev_close = psm_ev_close_r, }; static const struct evdev_methods psm_ev_methods_a = { .ev_open = psm_ev_open_a, .ev_close = psm_ev_close_a, }; #endif /* device I/O routines */ static int enable_aux_dev(KBDC kbdc) { int res; res = send_aux_command(kbdc, PSMC_ENABLE_DEV); VLOG(2, (LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res)); return (res == PSM_ACK); } static int disable_aux_dev(KBDC kbdc) { int res; res = send_aux_command(kbdc, PSMC_DISABLE_DEV); VLOG(2, (LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res)); return (res == PSM_ACK); } static int get_mouse_status(KBDC kbdc, int *status, int flag, int len) { int cmd; int res; int i; switch (flag) { case 0: default: cmd = PSMC_SEND_DEV_STATUS; break; case 1: cmd = PSMC_SEND_DEV_DATA; break; } empty_aux_buffer(kbdc, 5); res = send_aux_command(kbdc, cmd); VLOG(2, (LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n", (flag == 1) ? "DATA" : "STATUS", res)); if (res != PSM_ACK) return (0); for (i = 0; i < len; ++i) { status[i] = read_aux_data(kbdc); if (status[i] < 0) break; } VLOG(1, (LOG_DEBUG, "psm: %s %02x %02x %02x\n", (flag == 1) ? "data" : "status", status[0], status[1], status[2])); return (i); } static int get_aux_id(KBDC kbdc) { int res; int id; empty_aux_buffer(kbdc, 5); res = send_aux_command(kbdc, PSMC_SEND_DEV_ID); VLOG(2, (LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res)); if (res != PSM_ACK) return (-1); /* 10ms delay */ DELAY(10000); id = read_aux_data(kbdc); VLOG(2, (LOG_DEBUG, "psm: device ID: %04x\n", id)); return (id); } static int set_mouse_sampling_rate(KBDC kbdc, int rate) { int res; res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate); VLOG(2, (LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res)); return ((res == PSM_ACK) ? rate : -1); } static int set_mouse_scaling(KBDC kbdc, int scale) { int res; switch (scale) { case 1: default: scale = PSMC_SET_SCALING11; break; case 2: scale = PSMC_SET_SCALING21; break; } res = send_aux_command(kbdc, scale); VLOG(2, (LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n", (scale == PSMC_SET_SCALING21) ? "21" : "11", res)); return (res == PSM_ACK); } /* `val' must be 0 through PSMD_MAX_RESOLUTION */ static int set_mouse_resolution(KBDC kbdc, int val) { int res; res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val); VLOG(2, (LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res)); return ((res == PSM_ACK) ? val : -1); } /* * NOTE: once `set_mouse_mode()' is called, the mouse device must be * re-enabled by calling `enable_aux_dev()' */ static int set_mouse_mode(KBDC kbdc) { int res; res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE); VLOG(2, (LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res)); return (res == PSM_ACK); } static int get_mouse_buttons(KBDC kbdc) { int c = 2; /* assume two buttons by default */ int status[3]; /* * NOTE: a special sequence to obtain Logitech Mouse specific * information: set resolution to 25 ppi, set scaling to 1:1, set * scaling to 1:1, set scaling to 1:1. Then the second byte of the * mouse status bytes is the number of available buttons. * Some manufactures also support this sequence. */ if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW) return (c); if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1) && get_mouse_status(kbdc, status, 0, 3) >= 3 && status[1] != 0) return (status[1]); return (c); } /* misc subroutines */ /* * Someday, I will get the complete list of valid pointing devices and * their IDs... XXX */ static int is_a_mouse(int id) { #if 0 static int valid_ids[] = { PSM_MOUSE_ID, /* mouse */ PSM_BALLPOINT_ID, /* ballpoint device */ PSM_INTELLI_ID, /* Intellimouse */ PSM_EXPLORER_ID, /* Intellimouse Explorer */ -1 /* end of table */ }; int i; for (i = 0; valid_ids[i] >= 0; ++i) if (valid_ids[i] == id) return (TRUE); return (FALSE); #else return (TRUE); #endif } static char * model_name(int model) { static struct { int model_code; char *model_name; } models[] = { { MOUSE_MODEL_NETSCROLL, "NetScroll" }, { MOUSE_MODEL_NET, "NetMouse/NetScroll Optical" }, { MOUSE_MODEL_GLIDEPOINT, "GlidePoint" }, { MOUSE_MODEL_THINK, "ThinkingMouse" }, { MOUSE_MODEL_INTELLI, "IntelliMouse" }, { MOUSE_MODEL_MOUSEMANPLUS, "MouseMan+" }, { MOUSE_MODEL_VERSAPAD, "VersaPad" }, { MOUSE_MODEL_EXPLORER, "IntelliMouse Explorer" }, { MOUSE_MODEL_4D, "4D Mouse" }, { MOUSE_MODEL_4DPLUS, "4D+ Mouse" }, { MOUSE_MODEL_SYNAPTICS, "Synaptics Touchpad" }, { MOUSE_MODEL_TRACKPOINT, "IBM/Lenovo TrackPoint" }, { MOUSE_MODEL_ELANTECH, "Elantech Touchpad" }, { MOUSE_MODEL_GENERIC, "Generic PS/2 mouse" }, { MOUSE_MODEL_UNKNOWN, "Unknown" }, }; int i; for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) if (models[i].model_code == model) break; return (models[i].model_name); } static void recover_from_error(KBDC kbdc) { /* discard anything left in the output buffer */ empty_both_buffers(kbdc, 10); #if 0 /* * NOTE: KBDC_RESET_KBD may not restore the communication between the * keyboard and the controller. */ reset_kbd(kbdc); #else /* * NOTE: somehow diagnostic and keyboard port test commands bring the * keyboard back. */ if (!test_controller(kbdc)) log(LOG_ERR, "psm: keyboard controller failed.\n"); /* if there isn't a keyboard in the system, the following error is OK */ if (test_kbd_port(kbdc) != 0) VLOG(1, (LOG_ERR, "psm: keyboard port failed.\n")); #endif } static int restore_controller(KBDC kbdc, int command_byte) { empty_both_buffers(kbdc, 10); if (!set_controller_command_byte(kbdc, 0xff, command_byte)) { log(LOG_ERR, "psm: failed to restore the keyboard controller " "command byte.\n"); empty_both_buffers(kbdc, 10); return (FALSE); } else { empty_both_buffers(kbdc, 10); return (TRUE); } } /* * Re-initialize the aux port and device. The aux port must be enabled * and its interrupt must be disabled before calling this routine. * The aux device will be disabled before returning. * The keyboard controller must be locked via `kbdc_lock()' before * calling this routine. */ static int doinitialize(struct psm_softc *sc, mousemode_t *mode) { KBDC kbdc = sc->kbdc; int stat[3]; int i; switch((i = test_aux_port(kbdc))) { case 1: /* ignore these errors */ case 2: case 3: case PSM_ACK: if (verbose) log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n", sc->unit, i); /* FALLTHROUGH */ case 0: /* no error */ break; case -1: /* time out */ default: /* error */ recover_from_error(kbdc); if (sc->config & PSM_CONFIG_IGNPORTERROR) break; log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n", sc->unit, i); return (FALSE); } if (sc->config & PSM_CONFIG_NORESET) { /* * Don't try to reset the pointing device. It may possibly * be left in the unknown state, though... */ } else { /* * NOTE: some controllers appears to hang the `keyboard' when * the aux port doesn't exist and `PSMC_RESET_DEV' is issued. */ if (!reset_aux_dev(kbdc)) { recover_from_error(kbdc); log(LOG_ERR, "psm%d: failed to reset the aux device.\n", sc->unit); return (FALSE); } } /* * both the aux port and the aux device is functioning, see * if the device can be enabled. */ if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) { log(LOG_ERR, "psm%d: failed to enable the aux device.\n", sc->unit); return (FALSE); } empty_both_buffers(kbdc, 10); /* remove stray data if any */ /* Re-enable the mouse. */ for (i = 0; vendortype[i].probefunc != NULL; ++i) if (vendortype[i].model == sc->hw.model) (*vendortype[i].probefunc)(sc, REINIT); /* set mouse parameters */ if (mode != (mousemode_t *)NULL) { if (mode->rate > 0) mode->rate = set_mouse_sampling_rate(kbdc, mode->rate); if (mode->resolution >= 0) mode->resolution = set_mouse_resolution(kbdc, mode->resolution); set_mouse_scaling(kbdc, 1); set_mouse_mode(kbdc); } /* Record sync on the next data packet we see. */ sc->flags |= PSM_NEED_SYNCBITS; /* just check the status of the mouse */ if (get_mouse_status(kbdc, stat, 0, 3) < 3) log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n", sc->unit); return (TRUE); } static int doopen(struct psm_softc *sc, int command_byte) { int stat[3]; /* * FIXME: Synaptics TouchPad seems to go back to Relative Mode with * no obvious reason. Thus we check the current mode and restore the * Absolute Mode if it was cleared. * * The previous hack at the end of psmprobe() wasn't efficient when * moused(8) was restarted. * * A Reset (FF) or Set Defaults (F6) command would clear the * Absolute Mode bit. But a verbose boot or debug.psm.loglevel=5 * doesn't show any evidence of such a command. */ if (sc->hw.model == MOUSE_MODEL_SYNAPTICS) { mouse_ext_command(sc->kbdc, 1); get_mouse_status(sc->kbdc, stat, 0, 3); if ((SYNAPTICS_VERSION_GE(sc->synhw, 7, 5) || stat[1] == 0x47) && stat[2] == 0x40) { synaptics_set_mode(sc, synaptics_preferred_mode(sc)); VLOG(5, (LOG_DEBUG, "psm%d: Synaptis Absolute Mode " "hopefully restored\n", sc->unit)); } } /* * A user may want to disable tap and drag gestures on a Synaptics * TouchPad when it operates in Relative Mode. */ if (sc->hw.model == MOUSE_MODEL_GENERIC) { if (tap_enabled > 0) { VLOG(2, (LOG_DEBUG, "psm%d: enable tap and drag gestures\n", sc->unit)); synaptics_set_mode(sc, synaptics_preferred_mode(sc)); } else if (tap_enabled == 0) { VLOG(2, (LOG_DEBUG, "psm%d: disable tap and drag gestures\n", sc->unit)); synaptics_set_mode(sc, synaptics_preferred_mode(sc)); } } /* enable the mouse device */ if (!enable_aux_dev(sc->kbdc)) { /* MOUSE ERROR: failed to enable the mouse because: * 1) the mouse is faulty, * 2) the mouse has been removed(!?) * In the latter case, the keyboard may have hung, and need * recovery procedure... */ recover_from_error(sc->kbdc); #if 0 /* FIXME: we could reset the mouse here and try to enable * it again. But it will take long time and it's not a good * idea to disable the keyboard that long... */ if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) { recover_from_error(sc->kbdc); #else { #endif restore_controller(sc->kbdc, command_byte); /* mark this device is no longer available */ sc->state &= ~PSM_VALID; log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n", sc->unit); return (EIO); } } if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", sc->unit); /* enable the aux port and interrupt */ if (!set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), (command_byte & KBD_KBD_CONTROL_BITS) | KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) { /* CONTROLLER ERROR */ disable_aux_dev(sc->kbdc); restore_controller(sc->kbdc, command_byte); log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n", sc->unit); return (EIO); } /* start the watchdog timer */ sc->watchdog = FALSE; callout_reset(&sc->callout, hz * 2, psmtimeout, sc); return (0); } static int reinitialize(struct psm_softc *sc, int doinit) { int err; int c; int s; /* don't let anybody mess with the aux device */ if (!kbdc_lock(sc->kbdc, TRUE)) return (EIO); s = spltty(); /* block our watchdog timer */ sc->watchdog = FALSE; callout_stop(&sc->callout); /* save the current controller command byte */ empty_both_buffers(sc->kbdc, 10); c = get_controller_command_byte(sc->kbdc); VLOG(2, (LOG_DEBUG, "psm%d: current command byte: %04x (reinitialize).\n", sc->unit, c)); /* enable the aux port but disable the aux interrupt and the keyboard */ if ((c == -1) || !set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { /* CONTROLLER ERROR */ splx(s); kbdc_lock(sc->kbdc, FALSE); log(LOG_ERR, "psm%d: unable to set the command byte (reinitialize).\n", sc->unit); return (EIO); } /* flush any data */ if (sc->state & PSM_VALID) { /* this may fail; but never mind... */ disable_aux_dev(sc->kbdc); empty_aux_buffer(sc->kbdc, 10); } flushpackets(sc); sc->syncerrors = 0; sc->pkterrors = 0; memset(&sc->lastinputerr, 0, sizeof(sc->lastinputerr)); /* try to detect the aux device; are you still there? */ err = 0; if (doinit) { if (doinitialize(sc, &sc->mode)) { /* yes */ sc->state |= PSM_VALID; } else { /* the device has gone! */ restore_controller(sc->kbdc, c); sc->state &= ~PSM_VALID; log(LOG_ERR, "psm%d: the aux device has gone! (reinitialize).\n", sc->unit); err = ENXIO; } } splx(s); /* restore the driver state */ if ((sc->state & (PSM_OPEN | PSM_EV_OPEN_R | PSM_EV_OPEN_A)) && (err == 0)) { /* enable the aux device and the port again */ err = doopen(sc, c); if (err != 0) log(LOG_ERR, "psm%d: failed to enable the device " "(reinitialize).\n", sc->unit); } else { /* restore the keyboard port and disable the aux port */ if (!set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), (c & KBD_KBD_CONTROL_BITS) | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { /* CONTROLLER ERROR */ log(LOG_ERR, "psm%d: failed to disable the aux port " "(reinitialize).\n", sc->unit); err = EIO; } } kbdc_lock(sc->kbdc, FALSE); return (err); } /* psm driver entry points */ static void psmidentify(driver_t *driver, device_t parent) { device_t psmc; device_t psm; u_long irq; int unit; unit = device_get_unit(parent); /* always add at least one child */ psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit); if (psm == NULL) return; irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX); if (irq > 0) return; /* * If the PS/2 mouse device has already been reported by ACPI or * PnP BIOS, obtain the IRQ resource from it. * (See psmcpnp_attach() below.) */ psmc = device_find_child(device_get_parent(parent), PSMCPNP_DRIVER_NAME, unit); if (psmc == NULL) return; irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0); if (irq <= 0) return; bus_delete_resource(psmc, SYS_RES_IRQ, 0); bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1); } #define endprobe(v) do { \ if (bootverbose) \ --verbose; \ kbdc_set_device_mask(sc->kbdc, mask); \ kbdc_lock(sc->kbdc, FALSE); \ return (v); \ } while (0) static int psmprobe(device_t dev) { int unit = device_get_unit(dev); struct psm_softc *sc = device_get_softc(dev); int stat[3]; int command_byte; int mask; int rid; int i; #if 0 kbdc_debug(TRUE); #endif /* see if IRQ is available */ rid = KBDC_RID_AUX; sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE); if (sc->intr == NULL) { if (bootverbose) device_printf(dev, "unable to allocate IRQ\n"); return (ENXIO); } bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr); sc->unit = unit; sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev))); sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS; /* XXX: for backward compatibility */ #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM) sc->config |= #ifdef PSM_RESETAFTERSUSPEND PSM_CONFIG_INITAFTERSUSPEND; #else PSM_CONFIG_HOOKRESUME; #endif #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */ sc->flags = 0; if (bootverbose) ++verbose; device_set_desc(dev, "PS/2 Mouse"); if (!kbdc_lock(sc->kbdc, TRUE)) { printf("psm%d: unable to lock the controller.\n", unit); if (bootverbose) --verbose; return (ENXIO); } /* * NOTE: two bits in the command byte controls the operation of the * aux port (mouse port): the aux port disable bit (bit 5) and the aux * port interrupt (IRQ 12) enable bit (bit 2). */ /* discard anything left after the keyboard initialization */ empty_both_buffers(sc->kbdc, 10); /* save the current command byte; it will be used later */ mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS; command_byte = get_controller_command_byte(sc->kbdc); if (verbose) printf("psm%d: current command byte:%04x\n", unit, command_byte); if (command_byte == -1) { /* CONTROLLER ERROR */ printf("psm%d: unable to get the current command byte value.\n", unit); endprobe(ENXIO); } /* * disable the keyboard port while probing the aux port, which must be * enabled during this routine */ if (!set_controller_command_byte(sc->kbdc, KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS, KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { /* * this is CONTROLLER ERROR; I don't know how to recover * from this error... */ if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc)) restore_controller(sc->kbdc, command_byte); printf("psm%d: unable to set the command byte.\n", unit); endprobe(ENXIO); } write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT); /* * NOTE: `test_aux_port()' is designed to return with zero if the aux * port exists and is functioning. However, some controllers appears * to respond with zero even when the aux port doesn't exist. (It may * be that this is only the case when the controller DOES have the aux * port but the port is not wired on the motherboard.) The keyboard * controllers without the port, such as the original AT, are * supposed to return with an error code or simply time out. In any * case, we have to continue probing the port even when the controller * passes this test. * * XXX: some controllers erroneously return the error code 1, 2 or 3 * when it has a perfectly functional aux port. We have to ignore * this error code. Even if the controller HAS error with the aux * port, it will be detected later... * XXX: another incompatible controller returns PSM_ACK (0xfa)... */ switch ((i = test_aux_port(sc->kbdc))) { case 1: /* ignore these errors */ case 2: case 3: case PSM_ACK: if (verbose) printf("psm%d: strange result for test aux port " "(%d).\n", unit, i); /* FALLTHROUGH */ case 0: /* no error */ break; case -1: /* time out */ default: /* error */ recover_from_error(sc->kbdc); if (sc->config & PSM_CONFIG_IGNPORTERROR) break; if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc)) restore_controller(sc->kbdc, command_byte); if (verbose) printf("psm%d: the aux port is not functioning (%d).\n", unit, i); endprobe(ENXIO); } if (sc->config & PSM_CONFIG_NORESET) { /* * Don't try to reset the pointing device. It may possibly be * left in an unknown state, though... */ } else { /* * NOTE: some controllers appears to hang the `keyboard' when * the aux port doesn't exist and `PSMC_RESET_DEV' is issued. * * Attempt to reset the controller twice -- this helps * pierce through some KVM switches. The second reset * is non-fatal. */ if (!reset_aux_dev(sc->kbdc)) { recover_from_error(sc->kbdc); if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc)) restore_controller(sc->kbdc, command_byte); if (verbose) printf("psm%d: failed to reset the aux " "device.\n", unit); endprobe(ENXIO); } else if (!reset_aux_dev(sc->kbdc)) { recover_from_error(sc->kbdc); if (verbose >= 2) printf("psm%d: failed to reset the aux device " "(2).\n", unit); } } /* * both the aux port and the aux device are functioning, see if the * device can be enabled. NOTE: when enabled, the device will start * sending data; we shall immediately disable the device once we know * the device can be enabled. */ if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) { /* MOUSE ERROR */ recover_from_error(sc->kbdc); if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc)) restore_controller(sc->kbdc, command_byte); if (verbose) printf("psm%d: failed to enable the aux device.\n", unit); endprobe(ENXIO); } /* save the default values after reset */ if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) { sc->dflt_mode.rate = sc->mode.rate = stat[2]; sc->dflt_mode.resolution = sc->mode.resolution = stat[1]; } else { sc->dflt_mode.rate = sc->mode.rate = -1; sc->dflt_mode.resolution = sc->mode.resolution = -1; } /* hardware information */ sc->hw.iftype = MOUSE_IF_PS2; /* verify the device is a mouse */ sc->hw.hwid = get_aux_id(sc->kbdc); if (!is_a_mouse(sc->hw.hwid)) { if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc)) restore_controller(sc->kbdc, command_byte); if (verbose) printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid); endprobe(ENXIO); } switch (sc->hw.hwid) { case PSM_BALLPOINT_ID: sc->hw.type = MOUSE_TRACKBALL; break; case PSM_MOUSE_ID: case PSM_INTELLI_ID: case PSM_EXPLORER_ID: case PSM_4DMOUSE_ID: case PSM_4DPLUS_ID: sc->hw.type = MOUSE_MOUSE; break; default: sc->hw.type = MOUSE_UNKNOWN; break; } if (sc->config & PSM_CONFIG_NOIDPROBE) { sc->hw.buttons = 2; i = GENERIC_MOUSE_ENTRY; } else { /* # of buttons */ sc->hw.buttons = get_mouse_buttons(sc->kbdc); /* other parameters */ for (i = 0; vendortype[i].probefunc != NULL; ++i) if ((*vendortype[i].probefunc)(sc, PROBE)) { if (verbose >= 2) printf("psm%d: found %s\n", unit, model_name(vendortype[i].model)); break; } } sc->hw.model = vendortype[i].model; sc->dflt_mode.level = PSM_LEVEL_BASE; sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE; sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4; if (sc->config & PSM_CONFIG_NOCHECKSYNC) sc->dflt_mode.syncmask[0] = 0; else sc->dflt_mode.syncmask[0] = vendortype[i].syncmask; if (sc->config & PSM_CONFIG_FORCETAP) sc->dflt_mode.syncmask[0] &= ~MOUSE_PS2_TAP; sc->dflt_mode.syncmask[1] = 0; /* syncbits */ sc->mode = sc->dflt_mode; sc->mode.packetsize = vendortype[i].packetsize; /* set mouse parameters */ #if 0 /* * A version of Logitech FirstMouse+ won't report wheel movement, * if SET_DEFAULTS is sent... Don't use this command. * This fix was found by Takashi Nishida. */ i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS); if (verbose >= 2) printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i); #endif if (sc->config & PSM_CONFIG_RESOLUTION) sc->mode.resolution = set_mouse_resolution(sc->kbdc, (sc->config & PSM_CONFIG_RESOLUTION) - 1); else if (sc->mode.resolution >= 0) sc->mode.resolution = set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution); if (sc->mode.rate > 0) sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate); set_mouse_scaling(sc->kbdc, 1); /* Record sync on the next data packet we see. */ sc->flags |= PSM_NEED_SYNCBITS; /* just check the status of the mouse */ /* * NOTE: XXX there are some arcane controller/mouse combinations out * there, which hung the controller unless there is data transmission * after ACK from the mouse. */ if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) printf("psm%d: failed to get status.\n", unit); else { /* * When in its native mode, some mice operate with different * default parameters than in the PS/2 compatible mode. */ sc->dflt_mode.rate = sc->mode.rate = stat[2]; sc->dflt_mode.resolution = sc->mode.resolution = stat[1]; } /* disable the aux port for now... */ if (!set_controller_command_byte(sc->kbdc, KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS, (command_byte & KBD_KBD_CONTROL_BITS) | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { /* * this is CONTROLLER ERROR; I don't know the proper way to * recover from this error... */ if (ALWAYS_RESTORE_CONTROLLER(sc->kbdc)) restore_controller(sc->kbdc, command_byte); printf("psm%d: unable to set the command byte.\n", unit); endprobe(ENXIO); } /* done */ kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS); kbdc_lock(sc->kbdc, FALSE); return (0); } #ifdef EVDEV_SUPPORT /* Values are taken from Linux drivers for userland software compatibility */ #define PS2_MOUSE_VENDOR 0x0002 #define PS2_MOUSE_GENERIC_PRODUCT 0x0001 #define PS2_MOUSE_SYNAPTICS_NAME "SynPS/2 Synaptics TouchPad" #define PS2_MOUSE_SYNAPTICS_PRODUCT 0x0007 #define PS2_MOUSE_TRACKPOINT_NAME "TPPS/2 IBM TrackPoint" #define PS2_MOUSE_TRACKPOINT_PRODUCT 0x000A #define PS2_MOUSE_ELANTECH_NAME "ETPS/2 Elantech Touchpad" #define PS2_MOUSE_ELANTECH_ST_NAME "ETPS/2 Elantech TrackPoint" #define PS2_MOUSE_ELANTECH_PRODUCT 0x000E #define ABSINFO_END { ABS_CNT, 0, 0, 0 } static void psm_support_abs_bulk(struct evdev_dev *evdev, const uint16_t info[][4]) { size_t i; for (i = 0; info[i][0] != ABS_CNT; i++) evdev_support_abs(evdev, info[i][0], 0, info[i][1], info[i][2], 0, 0, info[i][3]); } static void psm_push_mt_finger(struct psm_softc *sc, int id, const finger_t *f) { int y = sc->synhw.minimumYCoord + sc->synhw.maximumYCoord - f->y; evdev_push_abs(sc->evdev_a, ABS_MT_SLOT, id); evdev_push_abs(sc->evdev_a, ABS_MT_TRACKING_ID, id); evdev_push_abs(sc->evdev_a, ABS_MT_POSITION_X, f->x); evdev_push_abs(sc->evdev_a, ABS_MT_POSITION_Y, y); evdev_push_abs(sc->evdev_a, ABS_MT_PRESSURE, f->p); } static void psm_push_st_finger(struct psm_softc *sc, const finger_t *f) { int y = sc->synhw.minimumYCoord + sc->synhw.maximumYCoord - f->y; evdev_push_abs(sc->evdev_a, ABS_X, f->x); evdev_push_abs(sc->evdev_a, ABS_Y, y); evdev_push_abs(sc->evdev_a, ABS_PRESSURE, f->p); if (sc->synhw.capPalmDetect) evdev_push_abs(sc->evdev_a, ABS_TOOL_WIDTH, f->w); } static void psm_release_mt_slot(struct evdev_dev *evdev, int32_t slot) { evdev_push_abs(evdev, ABS_MT_SLOT, slot); evdev_push_abs(evdev, ABS_MT_TRACKING_ID, -1); } static int psm_register(device_t dev, int model_code) { struct psm_softc *sc = device_get_softc(dev); struct evdev_dev *evdev_r; int error, i, nbuttons, nwheels, product; bool is_pointing_stick; const char *name; name = model_name(model_code); nbuttons = sc->hw.buttons; product = PS2_MOUSE_GENERIC_PRODUCT; nwheels = 0; is_pointing_stick = false; switch (model_code) { case MOUSE_MODEL_TRACKPOINT: name = PS2_MOUSE_TRACKPOINT_NAME; product = PS2_MOUSE_TRACKPOINT_PRODUCT; nbuttons = 3; is_pointing_stick = true; break; case MOUSE_MODEL_ELANTECH: name = PS2_MOUSE_ELANTECH_ST_NAME; product = PS2_MOUSE_ELANTECH_PRODUCT; nbuttons = 3; is_pointing_stick = true; break; case MOUSE_MODEL_MOUSEMANPLUS: case MOUSE_MODEL_4D: nwheels = 2; break; case MOUSE_MODEL_EXPLORER: case MOUSE_MODEL_INTELLI: case MOUSE_MODEL_NET: case MOUSE_MODEL_NETSCROLL: case MOUSE_MODEL_4DPLUS: nwheels = 1; break; } evdev_r = evdev_alloc(); evdev_set_name(evdev_r, name); evdev_set_phys(evdev_r, device_get_nameunit(dev)); evdev_set_id(evdev_r, BUS_I8042, PS2_MOUSE_VENDOR, product, 0); evdev_set_methods(evdev_r, sc, &psm_ev_methods_r); evdev_support_prop(evdev_r, INPUT_PROP_POINTER); if (is_pointing_stick) evdev_support_prop(evdev_r, INPUT_PROP_POINTING_STICK); evdev_support_event(evdev_r, EV_SYN); evdev_support_event(evdev_r, EV_KEY); evdev_support_event(evdev_r, EV_REL); evdev_support_rel(evdev_r, REL_X); evdev_support_rel(evdev_r, REL_Y); switch (nwheels) { case 2: evdev_support_rel(evdev_r, REL_HWHEEL); /* FALLTHROUGH */ case 1: evdev_support_rel(evdev_r, REL_WHEEL); } for (i = 0; i < nbuttons; i++) evdev_support_key(evdev_r, BTN_MOUSE + i); error = evdev_register_mtx(evdev_r, &Giant); if (error) evdev_free(evdev_r); else sc->evdev_r = evdev_r; return (error); } static int psm_register_synaptics(device_t dev) { struct psm_softc *sc = device_get_softc(dev); const uint16_t synaptics_absinfo_st[][4] = { { ABS_X, sc->synhw.minimumXCoord, sc->synhw.maximumXCoord, sc->synhw.infoXupmm }, { ABS_Y, sc->synhw.minimumYCoord, sc->synhw.maximumYCoord, sc->synhw.infoYupmm }, { ABS_PRESSURE, 0, ELANTECH_FINGER_MAX_P, 0 }, ABSINFO_END, }; const uint16_t synaptics_absinfo_mt[][4] = { { ABS_MT_SLOT, 0, PSM_FINGERS-1, 0}, { ABS_MT_TRACKING_ID, -1, PSM_FINGERS-1, 0}, { ABS_MT_POSITION_X, sc->synhw.minimumXCoord, sc->synhw.maximumXCoord, sc->synhw.infoXupmm }, { ABS_MT_POSITION_Y, sc->synhw.minimumYCoord, sc->synhw.maximumYCoord, sc->synhw.infoYupmm }, { ABS_MT_PRESSURE, 0, ELANTECH_FINGER_MAX_P, 0 }, ABSINFO_END, }; struct evdev_dev *evdev_a; int error, i, guest_model; evdev_a = evdev_alloc(); evdev_set_name(evdev_a, PS2_MOUSE_SYNAPTICS_NAME); evdev_set_phys(evdev_a, device_get_nameunit(dev)); evdev_set_id(evdev_a, BUS_I8042, PS2_MOUSE_VENDOR, PS2_MOUSE_SYNAPTICS_PRODUCT, 0); evdev_set_methods(evdev_a, sc, &psm_ev_methods_a); evdev_support_event(evdev_a, EV_SYN); evdev_support_event(evdev_a, EV_KEY); evdev_support_event(evdev_a, EV_ABS); evdev_support_prop(evdev_a, INPUT_PROP_POINTER); if (sc->synhw.capAdvancedGestures) evdev_support_prop(evdev_a, INPUT_PROP_SEMI_MT); if (sc->synhw.capClickPad) evdev_support_prop(evdev_a, INPUT_PROP_BUTTONPAD); evdev_support_key(evdev_a, BTN_TOUCH); evdev_support_nfingers(evdev_a, 3); psm_support_abs_bulk(evdev_a, synaptics_absinfo_st); if (sc->synhw.capAdvancedGestures || sc->synhw.capReportsV) psm_support_abs_bulk(evdev_a, synaptics_absinfo_mt); if (sc->synhw.capPalmDetect) evdev_support_abs(evdev_a, ABS_TOOL_WIDTH, 0, 0, 15, 0, 0, 0); evdev_support_key(evdev_a, BTN_LEFT); if (!sc->synhw.capClickPad) { evdev_support_key(evdev_a, BTN_RIGHT); if (sc->synhw.capExtended && sc->synhw.capMiddle) evdev_support_key(evdev_a, BTN_MIDDLE); } if (sc->synhw.capExtended && sc->synhw.capFourButtons) { evdev_support_key(evdev_a, BTN_BACK); evdev_support_key(evdev_a, BTN_FORWARD); } if (sc->synhw.capExtended && (sc->synhw.nExtendedButtons > 0)) for (i = 0; i < sc->synhw.nExtendedButtons; i++) evdev_support_key(evdev_a, BTN_0 + i); error = evdev_register_mtx(evdev_a, &Giant); if (!error && sc->synhw.capPassthrough) { guest_model = sc->tpinfo.sysctl_tree != NULL ? MOUSE_MODEL_TRACKPOINT : MOUSE_MODEL_GENERIC; error = psm_register(dev, guest_model); } if (error) evdev_free(evdev_a); else sc->evdev_a = evdev_a; return (error); } static int psm_register_elantech(device_t dev) { struct psm_softc *sc = device_get_softc(dev); const uint16_t elantech_absinfo[][4] = { { ABS_X, 0, sc->elanhw.sizex, sc->elanhw.dpmmx }, { ABS_Y, 0, sc->elanhw.sizey, sc->elanhw.dpmmy }, { ABS_PRESSURE, 0, ELANTECH_FINGER_MAX_P, 0 }, { ABS_TOOL_WIDTH, 0, ELANTECH_FINGER_MAX_W, 0 }, { ABS_MT_SLOT, 0, ELANTECH_MAX_FINGERS - 1, 0 }, { ABS_MT_TRACKING_ID, -1, ELANTECH_MAX_FINGERS - 1, 0 }, { ABS_MT_POSITION_X, 0, sc->elanhw.sizex, sc->elanhw.dpmmx }, { ABS_MT_POSITION_Y, 0, sc->elanhw.sizey, sc->elanhw.dpmmy }, { ABS_MT_PRESSURE, 0, ELANTECH_FINGER_MAX_P, 0 }, { ABS_MT_TOUCH_MAJOR, 0, ELANTECH_FINGER_MAX_W * sc->elanhw.dptracex, 0 }, ABSINFO_END, }; struct evdev_dev *evdev_a; int error; evdev_a = evdev_alloc(); evdev_set_name(evdev_a, PS2_MOUSE_ELANTECH_NAME); evdev_set_phys(evdev_a, device_get_nameunit(dev)); evdev_set_id(evdev_a, BUS_I8042, PS2_MOUSE_VENDOR, PS2_MOUSE_ELANTECH_PRODUCT, 0); evdev_set_methods(evdev_a, sc, &psm_ev_methods_a); evdev_support_event(evdev_a, EV_SYN); evdev_support_event(evdev_a, EV_KEY); evdev_support_event(evdev_a, EV_ABS); evdev_support_prop(evdev_a, INPUT_PROP_POINTER); if (sc->elanhw.issemimt) evdev_support_prop(evdev_a, INPUT_PROP_SEMI_MT); if (sc->elanhw.isclickpad) evdev_support_prop(evdev_a, INPUT_PROP_BUTTONPAD); evdev_support_key(evdev_a, BTN_TOUCH); evdev_support_nfingers(evdev_a, ELANTECH_MAX_FINGERS); evdev_support_key(evdev_a, BTN_LEFT); if (!sc->elanhw.isclickpad) evdev_support_key(evdev_a, BTN_RIGHT); psm_support_abs_bulk(evdev_a, elantech_absinfo); error = evdev_register_mtx(evdev_a, &Giant); if (!error && sc->elanhw.hastrackpoint) error = psm_register(dev, MOUSE_MODEL_ELANTECH); if (error) evdev_free(evdev_a); else sc->evdev_a = evdev_a; return (error); } #endif static int psmattach(device_t dev) { int unit = device_get_unit(dev); struct psm_softc *sc = device_get_softc(dev); int error; int rid; /* Setup initial state */ sc->state = PSM_VALID; callout_init(&sc->callout, 0); callout_init(&sc->softcallout, 0); /* Setup our interrupt handler */ rid = KBDC_RID_AUX; sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE); if (sc->intr == NULL) return (ENXIO); error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, psmintr, sc, &sc->ih); if (error) { bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr); return (error); } /* Done */ sc->dev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "psm%d", unit); sc->dev->si_drv1 = sc; sc->bdev = make_dev(&psm_cdevsw, 0, 0, 0, 0666, "bpsm%d", unit); sc->bdev->si_drv1 = sc; #ifdef EVDEV_SUPPORT switch (sc->hw.model) { case MOUSE_MODEL_SYNAPTICS: error = psm_register_synaptics(dev); break; case MOUSE_MODEL_ELANTECH: error = psm_register_elantech(dev); break; default: error = psm_register(dev, sc->hw.model); } if (error) return (error); #endif /* Some touchpad devices need full reinitialization after suspend. */ switch (sc->hw.model) { case MOUSE_MODEL_SYNAPTICS: case MOUSE_MODEL_GLIDEPOINT: case MOUSE_MODEL_VERSAPAD: case MOUSE_MODEL_ELANTECH: sc->config |= PSM_CONFIG_INITAFTERSUSPEND; break; default: if (sc->synhw.infoMajor >= 4 || sc->tphw > 0) sc->config |= PSM_CONFIG_INITAFTERSUSPEND; break; } /* Elantech trackpad`s sync bit differs from touchpad`s one */ if (sc->hw.model == MOUSE_MODEL_ELANTECH && (sc->elanhw.hascrc || sc->elanhw.hastrackpoint)) { sc->config |= PSM_CONFIG_NOCHECKSYNC; sc->flags &= ~PSM_NEED_SYNCBITS; } if (!verbose) printf("psm%d: model %s, device ID %d\n", unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff); else { printf("psm%d: model %s, device ID %d-%02x, %d buttons\n", unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff, sc->hw.hwid >> 8, sc->hw.buttons); printf("psm%d: config:%08x, flags:%08x, packet size:%d\n", unit, sc->config, sc->flags, sc->mode.packetsize); printf("psm%d: syncmask:%02x, syncbits:%02x%s\n", unit, sc->mode.syncmask[0], sc->mode.syncmask[1], sc->config & PSM_CONFIG_NOCHECKSYNC ? " (sync not checked)" : ""); } if (bootverbose) --verbose; return (0); } static int psmdetach(device_t dev) { struct psm_softc *sc; int rid; sc = device_get_softc(dev); if (sc->state & PSM_OPEN) return (EBUSY); #ifdef EVDEV_SUPPORT evdev_free(sc->evdev_r); evdev_free(sc->evdev_a); #endif rid = KBDC_RID_AUX; bus_teardown_intr(dev, sc->intr, sc->ih); bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr); destroy_dev(sc->dev); destroy_dev(sc->bdev); callout_drain(&sc->callout); callout_drain(&sc->softcallout); return (0); } #ifdef EVDEV_SUPPORT static int psm_ev_open_r(struct evdev_dev *evdev, void *ev_softc) { struct psm_softc *sc = (struct psm_softc *)ev_softc; int err = 0; /* Get device data */ if ((sc->state & PSM_VALID) == 0) { /* the device is no longer valid/functioning */ return (ENXIO); } if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_A))) err = psmopen(sc); if (err == 0) sc->state |= PSM_EV_OPEN_R; return (err); } static void psm_ev_close_r(struct evdev_dev *evdev, void *ev_softc) { struct psm_softc *sc = (struct psm_softc *)ev_softc; sc->state &= ~PSM_EV_OPEN_R; if (sc->state & (PSM_OPEN | PSM_EV_OPEN_A)) return; if (sc->state & PSM_VALID) psmclose(sc); } static int psm_ev_open_a(struct evdev_dev *evdev, void *ev_softc) { struct psm_softc *sc = (struct psm_softc *)ev_softc; int err = 0; /* Get device data */ if ((sc->state & PSM_VALID) == 0) { /* the device is no longer valid/functioning */ return (ENXIO); } if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_R))) err = psmopen(sc); if (err == 0) sc->state |= PSM_EV_OPEN_A; return (err); } static void psm_ev_close_a(struct evdev_dev *evdev, void *ev_softc) { struct psm_softc *sc = (struct psm_softc *)ev_softc; sc->state &= ~PSM_EV_OPEN_A; if (sc->state & (PSM_OPEN | PSM_EV_OPEN_R)) return; if (sc->state & PSM_VALID) psmclose(sc); } #endif static int psm_cdev_open(struct cdev *dev, int flag, int fmt, struct thread *td) { struct psm_softc *sc; int err = 0; /* Get device data */ sc = dev->si_drv1; if ((sc == NULL) || (sc->state & PSM_VALID) == 0) { /* the device is no longer valid/functioning */ return (ENXIO); } /* Disallow multiple opens */ if (sc->state & PSM_OPEN) return (EBUSY); device_busy(devclass_get_device(psm_devclass, sc->unit)); #ifdef EVDEV_SUPPORT /* Already opened by evdev */ if (!(sc->state & (PSM_EV_OPEN_R | PSM_EV_OPEN_A))) #endif err = psmopen(sc); if (err == 0) sc->state |= PSM_OPEN; else device_unbusy(devclass_get_device(psm_devclass, sc->unit)); return (err); } static int psm_cdev_close(struct cdev *dev, int flag, int fmt, struct thread *td) { struct psm_softc *sc; int err = 0; /* Get device data */ sc = dev->si_drv1; if ((sc == NULL) || (sc->state & PSM_VALID) == 0) { /* the device is no longer valid/functioning */ return (ENXIO); } #ifdef EVDEV_SUPPORT /* Still opened by evdev */ if (!(sc->state & (PSM_EV_OPEN_R | PSM_EV_OPEN_A))) #endif err = psmclose(sc); if (err == 0) { sc->state &= ~PSM_OPEN; /* clean up and sigio requests */ if (sc->async != NULL) { funsetown(&sc->async); sc->async = NULL; } device_unbusy(devclass_get_device(psm_devclass, sc->unit)); } return (err); } static int psmopen(struct psm_softc *sc) { int command_byte; int err; int s; /* Initialize state */ sc->mode.level = sc->dflt_mode.level; sc->mode.protocol = sc->dflt_mode.protocol; sc->watchdog = FALSE; sc->async = NULL; /* flush the event queue */ sc->queue.count = 0; sc->queue.head = 0; sc->queue.tail = 0; sc->status.flags = 0; sc->status.button = 0; sc->status.obutton = 0; sc->status.dx = 0; sc->status.dy = 0; sc->status.dz = 0; sc->button = 0; sc->pqueue_start = 0; sc->pqueue_end = 0; /* empty input buffer */ flushpackets(sc); sc->syncerrors = 0; sc->pkterrors = 0; /* don't let timeout routines in the keyboard driver to poll the kbdc */ if (!kbdc_lock(sc->kbdc, TRUE)) return (EIO); /* save the current controller command byte */ s = spltty(); command_byte = get_controller_command_byte(sc->kbdc); /* enable the aux port and temporalily disable the keyboard */ if (command_byte == -1 || !set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { /* CONTROLLER ERROR; do you know how to get out of this? */ kbdc_lock(sc->kbdc, FALSE); splx(s); log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n", sc->unit); return (EIO); } /* * Now that the keyboard controller is told not to generate * the keyboard and mouse interrupts, call `splx()' to allow * the other tty interrupts. The clock interrupt may also occur, * but timeout routines will be blocked by the poll flag set * via `kbdc_lock()' */ splx(s); /* enable the mouse device */ err = doopen(sc, command_byte); /* done */ kbdc_lock(sc->kbdc, FALSE); return (err); } static int psmclose(struct psm_softc *sc) { int stat[3]; int command_byte; int s; /* don't let timeout routines in the keyboard driver to poll the kbdc */ if (!kbdc_lock(sc->kbdc, TRUE)) return (EIO); /* save the current controller command byte */ s = spltty(); command_byte = get_controller_command_byte(sc->kbdc); if (command_byte == -1) { kbdc_lock(sc->kbdc, FALSE); splx(s); return (EIO); } /* disable the aux interrupt and temporalily disable the keyboard */ if (!set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n", sc->unit); /* CONTROLLER ERROR; * NOTE: we shall force our way through. Because the only * ill effect we shall see is that we may not be able * to read ACK from the mouse, and it doesn't matter much * so long as the mouse will accept the DISABLE command. */ } splx(s); /* stop the watchdog timer */ callout_stop(&sc->callout); /* remove anything left in the output buffer */ empty_aux_buffer(sc->kbdc, 10); /* disable the aux device, port and interrupt */ if (sc->state & PSM_VALID) { if (!disable_aux_dev(sc->kbdc)) { /* MOUSE ERROR; * NOTE: we don't return (error) and continue, * pretending we have successfully disabled the device. * It's OK because the interrupt routine will discard * any data from the mouse hereafter. */ log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n", sc->unit); } if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n", sc->unit); } if (!set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), (command_byte & KBD_KBD_CONTROL_BITS) | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { /* * CONTROLLER ERROR; * we shall ignore this error; see the above comment. */ log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n", sc->unit); } /* remove anything left in the output buffer */ empty_aux_buffer(sc->kbdc, 10); /* close is almost always successful */ kbdc_lock(sc->kbdc, FALSE); return (0); } static int tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status, u_char *buf) { static u_char butmapps2[8] = { 0, MOUSE_PS2_BUTTON1DOWN, MOUSE_PS2_BUTTON2DOWN, MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN, MOUSE_PS2_BUTTON3DOWN, MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN, MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN, MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN, }; static u_char butmapmsc[8] = { MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP, MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP, MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP, MOUSE_MSC_BUTTON3UP, MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP, MOUSE_MSC_BUTTON2UP, MOUSE_MSC_BUTTON1UP, 0, }; int mapped; int i; if (sc->mode.level == PSM_LEVEL_BASE) { mapped = status->button & ~MOUSE_BUTTON4DOWN; if (status->button & MOUSE_BUTTON4DOWN) mapped |= MOUSE_BUTTON1DOWN; status->button = mapped; buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS]; i = imax(imin(status->dx, 255), -256); if (i < 0) buf[0] |= MOUSE_PS2_XNEG; buf[1] = i; i = imax(imin(status->dy, 255), -256); if (i < 0) buf[0] |= MOUSE_PS2_YNEG; buf[2] = i; return (MOUSE_PS2_PACKETSIZE); } else if (sc->mode.level == PSM_LEVEL_STANDARD) { buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS]; i = imax(imin(status->dx, 255), -256); buf[1] = i >> 1; buf[3] = i - buf[1]; i = imax(imin(status->dy, 255), -256); buf[2] = i >> 1; buf[4] = i - buf[2]; i = imax(imin(status->dz, 127), -128); buf[5] = (i >> 1) & 0x7f; buf[6] = (i - (i >> 1)) & 0x7f; buf[7] = (~status->button >> 3) & 0x7f; return (MOUSE_SYS_PACKETSIZE); } return (pb->inputbytes); } static int psmread(struct cdev *dev, struct uio *uio, int flag) { struct psm_softc *sc = dev->si_drv1; u_char buf[PSM_SMALLBUFSIZE]; int error = 0; int s; int l; if ((sc->state & PSM_VALID) == 0) return (EIO); /* block until mouse activity occurred */ s = spltty(); while (sc->queue.count <= 0) { if (dev != sc->bdev) { splx(s); return (EWOULDBLOCK); } sc->state |= PSM_ASLP; error = tsleep(sc, PZERO | PCATCH, "psmrea", 0); sc->state &= ~PSM_ASLP; if (error) { splx(s); return (error); } else if ((sc->state & PSM_VALID) == 0) { /* the device disappeared! */ splx(s); return (EIO); } } splx(s); /* copy data to the user land */ while ((sc->queue.count > 0) && (uio->uio_resid > 0)) { s = spltty(); l = imin(sc->queue.count, uio->uio_resid); if (l > sizeof(buf)) l = sizeof(buf); if (l > sizeof(sc->queue.buf) - sc->queue.head) { bcopy(&sc->queue.buf[sc->queue.head], &buf[0], sizeof(sc->queue.buf) - sc->queue.head); bcopy(&sc->queue.buf[0], &buf[sizeof(sc->queue.buf) - sc->queue.head], l - (sizeof(sc->queue.buf) - sc->queue.head)); } else bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l); sc->queue.count -= l; sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf); splx(s); error = uiomove(buf, l, uio); if (error) break; } return (error); } static int block_mouse_data(struct psm_softc *sc, int *c) { int s; if (!kbdc_lock(sc->kbdc, TRUE)) return (EIO); s = spltty(); *c = get_controller_command_byte(sc->kbdc); if ((*c == -1) || !set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) { /* this is CONTROLLER ERROR */ splx(s); kbdc_lock(sc->kbdc, FALSE); return (EIO); } /* * The device may be in the middle of status data transmission. * The transmission will be interrupted, thus, incomplete status * data must be discarded. Although the aux interrupt is disabled * at the keyboard controller level, at most one aux interrupt * may have already been pending and a data byte is in the * output buffer; throw it away. Note that the second argument * to `empty_aux_buffer()' is zero, so that the call will just * flush the internal queue. * `psmintr()' will be invoked after `splx()' if an interrupt is * pending; it will see no data and returns immediately. */ empty_aux_buffer(sc->kbdc, 0); /* flush the queue */ read_aux_data_no_wait(sc->kbdc); /* throw away data if any */ flushpackets(sc); splx(s); return (0); } static void dropqueue(struct psm_softc *sc) { sc->queue.count = 0; sc->queue.head = 0; sc->queue.tail = 0; if ((sc->state & PSM_SOFTARMED) != 0) { sc->state &= ~PSM_SOFTARMED; callout_stop(&sc->softcallout); } sc->pqueue_start = sc->pqueue_end; } static void flushpackets(struct psm_softc *sc) { dropqueue(sc); bzero(&sc->pqueue, sizeof(sc->pqueue)); } static int unblock_mouse_data(struct psm_softc *sc, int c) { int error = 0; /* * We may have seen a part of status data during `set_mouse_XXX()'. * they have been queued; flush it. */ empty_aux_buffer(sc->kbdc, 0); /* restore ports and interrupt */ if (!set_controller_command_byte(sc->kbdc, kbdc_get_device_mask(sc->kbdc), c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) { /* * CONTROLLER ERROR; this is serious, we may have * been left with the inaccessible keyboard and * the disabled mouse interrupt. */ error = EIO; } kbdc_lock(sc->kbdc, FALSE); return (error); } static int psmwrite(struct cdev *dev, struct uio *uio, int flag) { struct psm_softc *sc = dev->si_drv1; u_char buf[PSM_SMALLBUFSIZE]; int error = 0, i, l; if ((sc->state & PSM_VALID) == 0) return (EIO); if (sc->mode.level < PSM_LEVEL_NATIVE) return (ENODEV); /* copy data from the user land */ while (uio->uio_resid > 0) { l = imin(PSM_SMALLBUFSIZE, uio->uio_resid); error = uiomove(buf, l, uio); if (error) break; for (i = 0; i < l; i++) { VLOG(4, (LOG_DEBUG, "psm: cmd 0x%x\n", buf[i])); if (!write_aux_command(sc->kbdc, buf[i])) { VLOG(2, (LOG_DEBUG, "psm: cmd 0x%x failed.\n", buf[i])); return (reinitialize(sc, FALSE)); } } } return (error); } static int psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td) { struct psm_softc *sc = dev->si_drv1; mousemode_t mode; mousestatus_t status; #if (defined(MOUSE_GETVARS)) mousevar_t *var; #endif mousedata_t *data; int stat[3]; int command_byte; int error = 0; int s; /* Perform IOCTL command */ switch (cmd) { case OLD_MOUSE_GETHWINFO: s = spltty(); ((old_mousehw_t *)addr)->buttons = sc->hw.buttons; ((old_mousehw_t *)addr)->iftype = sc->hw.iftype; ((old_mousehw_t *)addr)->type = sc->hw.type; ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff; splx(s); break; case MOUSE_GETHWINFO: s = spltty(); *(mousehw_t *)addr = sc->hw; if (sc->mode.level == PSM_LEVEL_BASE) ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC; splx(s); break; case MOUSE_SYN_GETHWINFO: s = spltty(); if (sc->synhw.infoMajor >= 4) *(synapticshw_t *)addr = sc->synhw; else error = EINVAL; splx(s); break; case OLD_MOUSE_GETMODE: s = spltty(); switch (sc->mode.level) { case PSM_LEVEL_BASE: ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2; break; case PSM_LEVEL_STANDARD: ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE; break; case PSM_LEVEL_NATIVE: ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2; break; } ((old_mousemode_t *)addr)->rate = sc->mode.rate; ((old_mousemode_t *)addr)->resolution = sc->mode.resolution; ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor; splx(s); break; case MOUSE_GETMODE: s = spltty(); *(mousemode_t *)addr = sc->mode; if ((sc->flags & PSM_NEED_SYNCBITS) != 0) { ((mousemode_t *)addr)->syncmask[0] = 0; ((mousemode_t *)addr)->syncmask[1] = 0; } ((mousemode_t *)addr)->resolution = MOUSE_RES_LOW - sc->mode.resolution; switch (sc->mode.level) { case PSM_LEVEL_BASE: ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2; ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE; break; case PSM_LEVEL_STANDARD: ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE; ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE; ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK; ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC; break; case PSM_LEVEL_NATIVE: /* FIXME: this isn't quite correct... XXX */ ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2; break; } splx(s); break; case OLD_MOUSE_SETMODE: case MOUSE_SETMODE: if (cmd == OLD_MOUSE_SETMODE) { mode.rate = ((old_mousemode_t *)addr)->rate; /* * resolution old I/F new I/F * default 0 0 * low 1 -2 * medium low 2 -3 * medium high 3 -4 * high 4 -5 */ if (((old_mousemode_t *)addr)->resolution > 0) mode.resolution = -((old_mousemode_t *)addr)->resolution - 1; else mode.resolution = 0; mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor; mode.level = -1; } else mode = *(mousemode_t *)addr; /* adjust and validate parameters. */ if (mode.rate > UCHAR_MAX) return (EINVAL); if (mode.rate == 0) mode.rate = sc->dflt_mode.rate; else if (mode.rate == -1) /* don't change the current setting */ ; else if (mode.rate < 0) return (EINVAL); if (mode.resolution >= UCHAR_MAX) return (EINVAL); if (mode.resolution >= 200) mode.resolution = MOUSE_RES_HIGH; else if (mode.resolution >= 100) mode.resolution = MOUSE_RES_MEDIUMHIGH; else if (mode.resolution >= 50) mode.resolution = MOUSE_RES_MEDIUMLOW; else if (mode.resolution > 0) mode.resolution = MOUSE_RES_LOW; if (mode.resolution == MOUSE_RES_DEFAULT) mode.resolution = sc->dflt_mode.resolution; else if (mode.resolution == -1) /* don't change the current setting */ ; else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */ mode.resolution = MOUSE_RES_LOW - mode.resolution; if (mode.level == -1) /* don't change the current setting */ mode.level = sc->mode.level; else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX)) return (EINVAL); if (mode.accelfactor == -1) /* don't change the current setting */ mode.accelfactor = sc->mode.accelfactor; else if (mode.accelfactor < 0) return (EINVAL); /* don't allow anybody to poll the keyboard controller */ error = block_mouse_data(sc, &command_byte); if (error) return (error); /* set mouse parameters */ if (mode.rate > 0) mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate); if (mode.resolution >= 0) mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution); set_mouse_scaling(sc->kbdc, 1); get_mouse_status(sc->kbdc, stat, 0, 3); s = spltty(); sc->mode.rate = mode.rate; sc->mode.resolution = mode.resolution; sc->mode.accelfactor = mode.accelfactor; sc->mode.level = mode.level; splx(s); unblock_mouse_data(sc, command_byte); break; case MOUSE_GETLEVEL: *(int *)addr = sc->mode.level; break; case MOUSE_SETLEVEL: if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX)) return (EINVAL); sc->mode.level = *(int *)addr; break; case MOUSE_GETSTATUS: s = spltty(); status = sc->status; sc->status.flags = 0; sc->status.obutton = sc->status.button; sc->status.button = 0; sc->status.dx = 0; sc->status.dy = 0; sc->status.dz = 0; splx(s); *(mousestatus_t *)addr = status; break; #if (defined(MOUSE_GETVARS)) case MOUSE_GETVARS: var = (mousevar_t *)addr; bzero(var, sizeof(*var)); s = spltty(); var->var[0] = MOUSE_VARS_PS2_SIG; var->var[1] = sc->config; var->var[2] = sc->flags; splx(s); break; case MOUSE_SETVARS: return (ENODEV); #endif /* MOUSE_GETVARS */ case MOUSE_READSTATE: case MOUSE_READDATA: data = (mousedata_t *)addr; if (data->len > sizeof(data->buf)/sizeof(data->buf[0])) return (EINVAL); error = block_mouse_data(sc, &command_byte); if (error) return (error); if ((data->len = get_mouse_status(sc->kbdc, data->buf, (cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0) error = EIO; unblock_mouse_data(sc, command_byte); break; #if (defined(MOUSE_SETRESOLUTION)) case MOUSE_SETRESOLUTION: mode.resolution = *(int *)addr; if (mode.resolution >= UCHAR_MAX) return (EINVAL); else if (mode.resolution >= 200) mode.resolution = MOUSE_RES_HIGH; else if (mode.resolution >= 100) mode.resolution = MOUSE_RES_MEDIUMHIGH; else if (mode.resolution >= 50) mode.resolution = MOUSE_RES_MEDIUMLOW; else if (mode.resolution > 0) mode.resolution = MOUSE_RES_LOW; if (mode.resolution == MOUSE_RES_DEFAULT) mode.resolution = sc->dflt_mode.resolution; else if (mode.resolution == -1) mode.resolution = sc->mode.resolution; else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */ mode.resolution = MOUSE_RES_LOW - mode.resolution; error = block_mouse_data(sc, &command_byte); if (error) return (error); sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution); if (sc->mode.resolution != mode.resolution) error = EIO; unblock_mouse_data(sc, command_byte); break; #endif /* MOUSE_SETRESOLUTION */ #if (defined(MOUSE_SETRATE)) case MOUSE_SETRATE: mode.rate = *(int *)addr; if (mode.rate > UCHAR_MAX) return (EINVAL); if (mode.rate == 0) mode.rate = sc->dflt_mode.rate; else if (mode.rate < 0) mode.rate = sc->mode.rate; error = block_mouse_data(sc, &command_byte); if (error) return (error); sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate); if (sc->mode.rate != mode.rate) error = EIO; unblock_mouse_data(sc, command_byte); break; #endif /* MOUSE_SETRATE */ #if (defined(MOUSE_SETSCALING)) case MOUSE_SETSCALING: if ((*(int *)addr <= 0) || (*(int *)addr > 2)) return (EINVAL); error = block_mouse_data(sc, &command_byte); if (error) return (error); if (!set_mouse_scaling(sc->kbdc, *(int *)addr)) error = EIO; unblock_mouse_data(sc, command_byte); break; #endif /* MOUSE_SETSCALING */ #if (defined(MOUSE_GETHWID)) case MOUSE_GETHWID: error = block_mouse_data(sc, &command_byte); if (error) return (error); sc->hw.hwid &= ~0x00ff; sc->hw.hwid |= get_aux_id(sc->kbdc); *(int *)addr = sc->hw.hwid & 0x00ff; unblock_mouse_data(sc, command_byte); break; #endif /* MOUSE_GETHWID */ case FIONBIO: case FIOASYNC: break; case FIOSETOWN: error = fsetown(*(int *)addr, &sc->async); break; case FIOGETOWN: *(int *) addr = fgetown(&sc->async); break; default: return (ENOTTY); } return (error); } static void psmtimeout(void *arg) { struct psm_softc *sc; int s; sc = (struct psm_softc *)arg; s = spltty(); if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) { VLOG(4, (LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit)); psmintr(sc); kbdc_lock(sc->kbdc, FALSE); } sc->watchdog = TRUE; splx(s); callout_reset(&sc->callout, hz, psmtimeout, sc); } /* Add all sysctls under the debug.psm and hw.psm nodes */ static SYSCTL_NODE(_debug, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse"); static SYSCTL_NODE(_hw, OID_AUTO, psm, CTLFLAG_RD, 0, "ps/2 mouse"); SYSCTL_INT(_debug_psm, OID_AUTO, loglevel, CTLFLAG_RWTUN, &verbose, 0, "Verbosity level"); static int psmhz = 20; SYSCTL_INT(_debug_psm, OID_AUTO, hz, CTLFLAG_RW, &psmhz, 0, "Frequency of the softcallout (in hz)"); static int psmerrsecs = 2; SYSCTL_INT(_debug_psm, OID_AUTO, errsecs, CTLFLAG_RW, &psmerrsecs, 0, "Number of seconds during which packets will dropped after a sync error"); static int psmerrusecs = 0; SYSCTL_INT(_debug_psm, OID_AUTO, errusecs, CTLFLAG_RW, &psmerrusecs, 0, "Microseconds to add to psmerrsecs"); static int psmsecs = 0; SYSCTL_INT(_debug_psm, OID_AUTO, secs, CTLFLAG_RW, &psmsecs, 0, "Max number of seconds between soft interrupts"); static int psmusecs = 500000; SYSCTL_INT(_debug_psm, OID_AUTO, usecs, CTLFLAG_RW, &psmusecs, 0, "Microseconds to add to psmsecs"); static int pkterrthresh = 2; SYSCTL_INT(_debug_psm, OID_AUTO, pkterrthresh, CTLFLAG_RW, &pkterrthresh, 0, "Number of error packets allowed before reinitializing the mouse"); SYSCTL_INT(_hw_psm, OID_AUTO, tap_enabled, CTLFLAG_RWTUN, &tap_enabled, 0, "Enable tap and drag gestures"); static int tap_threshold = PSM_TAP_THRESHOLD; SYSCTL_INT(_hw_psm, OID_AUTO, tap_threshold, CTLFLAG_RW, &tap_threshold, 0, "Button tap threshold"); static int tap_timeout = PSM_TAP_TIMEOUT; SYSCTL_INT(_hw_psm, OID_AUTO, tap_timeout, CTLFLAG_RW, &tap_timeout, 0, "Tap timeout for touchpads"); /* Tunables */ SYSCTL_INT(_hw_psm, OID_AUTO, synaptics_support, CTLFLAG_RDTUN, &synaptics_support, 0, "Enable support for Synaptics touchpads"); SYSCTL_INT(_hw_psm, OID_AUTO, trackpoint_support, CTLFLAG_RDTUN, &trackpoint_support, 0, "Enable support for IBM/Lenovo TrackPoint"); SYSCTL_INT(_hw_psm, OID_AUTO, elantech_support, CTLFLAG_RDTUN, &elantech_support, 0, "Enable support for Elantech touchpads"); static void psmintr(void *arg) { struct psm_softc *sc = arg; struct timeval now; int c; packetbuf_t *pb; /* read until there is nothing to read */ while((c = read_aux_data_no_wait(sc->kbdc)) != -1) { pb = &sc->pqueue[sc->pqueue_end]; /* discard the byte if the device is not open */ if (!(sc->state & (PSM_OPEN | PSM_EV_OPEN_R | PSM_EV_OPEN_A))) continue; getmicrouptime(&now); if ((pb->inputbytes > 0) && timevalcmp(&now, &sc->inputtimeout, >)) { VLOG(3, (LOG_DEBUG, "psmintr: delay too long; " "resetting byte count\n")); pb->inputbytes = 0; sc->syncerrors = 0; sc->pkterrors = 0; } sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT / 1000000; sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT % 1000000; timevaladd(&sc->inputtimeout, &now); pb->ipacket[pb->inputbytes++] = c; if (sc->mode.level == PSM_LEVEL_NATIVE) { VLOG(4, (LOG_DEBUG, "psmintr: %02x\n", pb->ipacket[0])); sc->syncerrors = 0; sc->pkterrors = 0; goto next; } else { if (pb->inputbytes < sc->mode.packetsize) continue; VLOG(4, (LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n", pb->ipacket[0], pb->ipacket[1], pb->ipacket[2], pb->ipacket[3], pb->ipacket[4], pb->ipacket[5])); } c = pb->ipacket[0]; if ((sc->flags & PSM_NEED_SYNCBITS) != 0) { sc->mode.syncmask[1] = (c & sc->mode.syncmask[0]); sc->flags &= ~PSM_NEED_SYNCBITS; VLOG(2, (LOG_DEBUG, "psmintr: Sync bytes now %04x,%04x\n", sc->mode.syncmask[0], sc->mode.syncmask[1])); } else if ((sc->config & PSM_CONFIG_NOCHECKSYNC) == 0 && (c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) { VLOG(3, (LOG_DEBUG, "psmintr: out of sync " "(%04x != %04x) %d cmds since last error.\n", c & sc->mode.syncmask[0], sc->mode.syncmask[1], sc->cmdcount - sc->lasterr)); sc->lasterr = sc->cmdcount; /* * The sync byte test is a weak measure of packet * validity. Conservatively discard any input yet * to be seen by userland when we detect a sync * error since there is a good chance some of * the queued packets have undetected errors. */ dropqueue(sc); if (sc->syncerrors == 0) sc->pkterrors++; ++sc->syncerrors; sc->lastinputerr = now; if (sc->syncerrors >= sc->mode.packetsize * 2 || sc->pkterrors >= pkterrthresh) { /* * If we've failed to find a single sync byte * in 2 packets worth of data, or we've seen * persistent packet errors during the * validation period, reinitialize the mouse * in hopes of returning it to the expected * mode. */ VLOG(3, (LOG_DEBUG, "psmintr: reset the mouse.\n")); reinitialize(sc, TRUE); } else if (sc->syncerrors == sc->mode.packetsize) { /* * Try a soft reset after searching for a sync * byte through a packet length of bytes. */ VLOG(3, (LOG_DEBUG, "psmintr: re-enable the mouse.\n")); pb->inputbytes = 0; disable_aux_dev(sc->kbdc); enable_aux_dev(sc->kbdc); } else { VLOG(3, (LOG_DEBUG, "psmintr: discard a byte (%d)\n", sc->syncerrors)); pb->inputbytes--; bcopy(&pb->ipacket[1], &pb->ipacket[0], pb->inputbytes); } continue; } /* * We have what appears to be a valid packet. * Reset the error counters. */ sc->syncerrors = 0; /* * Drop even good packets if they occur within a timeout * period of a sync error. This allows the detection of * a change in the mouse's packet mode without exposing * erratic mouse behavior to the user. Some KVMs forget * enhanced mouse modes during switch events. */ if (!timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs, &now)) { pb->inputbytes = 0; continue; } /* * Now that we're out of the validation period, reset * the packet error count. */ sc->pkterrors = 0; sc->cmdcount++; next: if (++sc->pqueue_end >= PSM_PACKETQUEUE) sc->pqueue_end = 0; /* * If we've filled the queue then call the softintr ourselves, * otherwise schedule the interrupt for later. */ if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) || (sc->pqueue_end == sc->pqueue_start)) { if ((sc->state & PSM_SOFTARMED) != 0) { sc->state &= ~PSM_SOFTARMED; callout_stop(&sc->softcallout); } psmsoftintr(arg); } else if ((sc->state & PSM_SOFTARMED) == 0) { sc->state |= PSM_SOFTARMED; callout_reset(&sc->softcallout, psmhz < 1 ? 1 : (hz/psmhz), psmsoftintr, arg); } } } static void proc_mmanplus(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms, int *x, int *y, int *z) { /* * PS2++ protocol packet * * b7 b6 b5 b4 b3 b2 b1 b0 * byte 1: * 1 p3 p2 1 * * * * byte 2: c1 c2 p1 p0 d1 d0 1 0 * * p3-p0: packet type * c1, c2: c1 & c2 == 1, if p2 == 0 * c1 & c2 == 0, if p2 == 1 * * packet type: 0 (device type) * See comments in enable_mmanplus() below. * * packet type: 1 (wheel data) * * b7 b6 b5 b4 b3 b2 b1 b0 * byte 3: h * B5 B4 s d2 d1 d0 * * h: 1, if horizontal roller data * 0, if vertical roller data * B4, B5: button 4 and 5 * s: sign bit * d2-d0: roller data * * packet type: 2 (reserved) */ if (((pb->ipacket[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC) && (abs(*x) > 191) && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) { /* * the extended data packet encodes button * and wheel events */ switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) { case 1: /* wheel data packet */ *x = *y = 0; if (pb->ipacket[2] & 0x80) { /* XXX horizontal roller count - ignore it */ ; } else { /* vertical roller count */ *z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG) ? (pb->ipacket[2] & 0x0f) - 16 : (pb->ipacket[2] & 0x0f); } ms->button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN) ? MOUSE_BUTTON4DOWN : 0; ms->button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN) ? MOUSE_BUTTON5DOWN : 0; break; case 2: /* * this packet type is reserved by * Logitech... */ /* * IBM ScrollPoint Mouse uses this * packet type to encode both vertical * and horizontal scroll movement. */ *x = *y = 0; /* horizontal count */ if (pb->ipacket[2] & 0x0f) *z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2; /* vertical count */ if (pb->ipacket[2] & 0xf0) *z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1; break; case 0: /* device type packet - shouldn't happen */ /* FALLTHROUGH */ default: *x = *y = 0; ms->button = ms->obutton; VLOG(1, (LOG_DEBUG, "psmintr: unknown PS2++ packet " "type %d: 0x%02x 0x%02x 0x%02x\n", MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket), pb->ipacket[0], pb->ipacket[1], pb->ipacket[2])); break; } } else { /* preserve button states */ ms->button |= ms->obutton & MOUSE_EXTBUTTONS; } } static int proc_synaptics(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms, int *x, int *y, int *z) { static int touchpad_buttons; static int guest_buttons; static finger_t f[PSM_FINGERS]; int w, id, nfingers, ewcode, extended_buttons; extended_buttons = 0; /* TouchPad PS/2 absolute mode message format with capFourButtons: * * Bits: 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------------ * ipacket[0]: 1 0 W3 W2 0 W1 R L * ipacket[1]: Yb Ya Y9 Y8 Xb Xa X9 X8 * ipacket[2]: Z7 Z6 Z5 Z4 Z3 Z2 Z1 Z0 * ipacket[3]: 1 1 Yc Xc 0 W0 D^R U^L * ipacket[4]: X7 X6 X5 X4 X3 X2 X1 X0 * ipacket[5]: Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * * Legend: * L: left physical mouse button * R: right physical mouse button * D: down button * U: up button * W: "wrist" value * X: x position * Y: y position * Z: pressure * * Without capFourButtons but with nExtendeButtons and/or capMiddle * * Bits: 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------------------ * ipacket[3]: 1 1 Yc Xc 0 W0 E^R M^L * ipacket[4]: X7 X6 X5 X4 X3|b7 X2|b5 X1|b3 X0|b1 * ipacket[5]: Y7 Y6 Y5 Y4 Y3|b8 Y2|b6 Y1|b4 Y0|b2 * * Legend: * M: Middle physical mouse button * E: Extended mouse buttons reported instead of low bits of X and Y * b1-b8: Extended mouse buttons * Only ((nExtendedButtons + 1) >> 1) bits are used in packet * 4 and 5, for reading X and Y value they should be zeroed. * * Absolute reportable limits: 0 - 6143. * Typical bezel limits: 1472 - 5472. * Typical edge marings: 1632 - 5312. * * w = 3 Passthrough Packet * * Byte 2,5,6 == Byte 1,2,3 of "Guest" */ if (!synaptics_support) return (0); /* Sanity check for out of sync packets. */ if ((pb->ipacket[0] & 0xc8) != 0x80 || (pb->ipacket[3] & 0xc8) != 0xc0) return (-1); *x = *y = 0; ms->button = ms->obutton; /* * Pressure value. * Interpretation: * z = 0 No finger contact * z = 10 Finger hovering near the pad * z = 30 Very light finger contact * z = 80 Normal finger contact * z = 110 Very heavy finger contact * z = 200 Finger lying flat on pad surface * z = 255 Maximum reportable Z */ *z = pb->ipacket[2]; /* * Finger width value * Interpretation: * w = 0 Two finger on the pad (capMultiFinger needed) * w = 1 Three or more fingers (capMultiFinger needed) * w = 2 Pen (instead of finger) (capPen needed) * w = 3 Reserved (passthrough?) * w = 4-7 Finger of normal width (capPalmDetect needed) * w = 8-14 Very wide finger or palm (capPalmDetect needed) * w = 15 Maximum reportable width (capPalmDetect needed) */ /* XXX Is checking capExtended enough? */ if (sc->synhw.capExtended) w = ((pb->ipacket[0] & 0x30) >> 2) | ((pb->ipacket[0] & 0x04) >> 1) | ((pb->ipacket[3] & 0x04) >> 2); else { /* Assume a finger of regular width. */ w = 4; } switch (w) { case 3: /* * Handle packets from the guest device. See: * Synaptics PS/2 TouchPad Interfacing Guide, Section 5.1 */ if (sc->synhw.capPassthrough) { *x = ((pb->ipacket[1] & 0x10) ? pb->ipacket[4] - 256 : pb->ipacket[4]); *y = ((pb->ipacket[1] & 0x20) ? pb->ipacket[5] - 256 : pb->ipacket[5]); *z = 0; guest_buttons = 0; if (pb->ipacket[1] & 0x01) guest_buttons |= MOUSE_BUTTON1DOWN; if (pb->ipacket[1] & 0x04) guest_buttons |= MOUSE_BUTTON2DOWN; if (pb->ipacket[1] & 0x02) guest_buttons |= MOUSE_BUTTON3DOWN; #ifdef EVDEV_SUPPORT if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) { evdev_push_rel(sc->evdev_r, REL_X, *x); evdev_push_rel(sc->evdev_r, REL_Y, -*y); evdev_push_mouse_btn(sc->evdev_r, guest_buttons); evdev_sync(sc->evdev_r); } #endif ms->button = touchpad_buttons | guest_buttons | sc->extended_buttons; } goto SYNAPTICS_END; case 2: /* Handle Extended W mode packets */ ewcode = (pb->ipacket[5] & 0xf0) >> 4; #if PSM_FINGERS > 1 switch (ewcode) { case 1: /* Secondary finger */ if (sc->synhw.capAdvancedGestures) f[1] = (finger_t) { .x = (((pb->ipacket[4] & 0x0f) << 8) | pb->ipacket[1]) << 1, .y = (((pb->ipacket[4] & 0xf0) << 4) | pb->ipacket[2]) << 1, .p = ((pb->ipacket[3] & 0x30) | (pb->ipacket[5] & 0x0f)) << 1, .w = PSM_FINGER_DEFAULT_W, .flags = PSM_FINGER_FUZZY, }; else if (sc->synhw.capReportsV) f[1] = (finger_t) { .x = (((pb->ipacket[4] & 0x0f) << 8) | (pb->ipacket[1] & 0xfe)) << 1, .y = (((pb->ipacket[4] & 0xf0) << 4) | (pb->ipacket[2] & 0xfe)) << 1, .p = ((pb->ipacket[3] & 0x30) | (pb->ipacket[5] & 0x0e)) << 1, .w = (((pb->ipacket[5] & 0x01) << 2) | ((pb->ipacket[2] & 0x01) << 1) | (pb->ipacket[1] & 0x01)) + 8, .flags = PSM_FINGER_FUZZY, }; default: break; } #endif goto SYNAPTICS_END; case 1: case 0: nfingers = w + 2; break; default: nfingers = 1; } if (sc->syninfo.touchpad_off) goto SYNAPTICS_END; /* Button presses */ touchpad_buttons = 0; if (pb->ipacket[0] & 0x01) touchpad_buttons |= MOUSE_BUTTON1DOWN; if (pb->ipacket[0] & 0x02) touchpad_buttons |= MOUSE_BUTTON3DOWN; if (sc->synhw.capExtended && sc->synhw.capFourButtons) { if ((pb->ipacket[3] ^ pb->ipacket[0]) & 0x01) touchpad_buttons |= MOUSE_BUTTON4DOWN; if ((pb->ipacket[3] ^ pb->ipacket[0]) & 0x02) touchpad_buttons |= MOUSE_BUTTON5DOWN; } else if (sc->synhw.capExtended && sc->synhw.capMiddle && !sc->synhw.capClickPad) { /* Middle Button */ if ((pb->ipacket[0] ^ pb->ipacket[3]) & 0x01) touchpad_buttons |= MOUSE_BUTTON2DOWN; } else if (sc->synhw.capExtended && (sc->synhw.nExtendedButtons > 0)) { /* Extended Buttons */ if ((pb->ipacket[0] ^ pb->ipacket[3]) & 0x02) { if (sc->syninfo.directional_scrolls) { if (pb->ipacket[4] & 0x01) extended_buttons |= MOUSE_BUTTON4DOWN; if (pb->ipacket[5] & 0x01) extended_buttons |= MOUSE_BUTTON5DOWN; if (pb->ipacket[4] & 0x02) extended_buttons |= MOUSE_BUTTON6DOWN; if (pb->ipacket[5] & 0x02) extended_buttons |= MOUSE_BUTTON7DOWN; } else { if (pb->ipacket[4] & 0x01) extended_buttons |= MOUSE_BUTTON1DOWN; if (pb->ipacket[5] & 0x01) extended_buttons |= MOUSE_BUTTON3DOWN; if (pb->ipacket[4] & 0x02) extended_buttons |= MOUSE_BUTTON2DOWN; sc->extended_buttons = extended_buttons; } /* * Zero out bits used by extended buttons to avoid * misinterpretation of the data absolute position. * * The bits represented by * * (nExtendedButtons + 1) >> 1 * * will be masked out in both bytes. * The mask for n bits is computed with the formula * * (1 << n) - 1 */ int maskedbits = 0; int mask = 0; maskedbits = (sc->synhw.nExtendedButtons + 1) >> 1; mask = (1 << maskedbits) - 1; #ifdef EVDEV_SUPPORT int i; if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) { if (sc->synhw.capPassthrough) { evdev_push_mouse_btn(sc->evdev_r, extended_buttons); evdev_sync(sc->evdev_r); } for (i = 0; i < maskedbits; i++) { evdev_push_key(sc->evdev_a, BTN_0 + i * 2, pb->ipacket[4] & (1 << i)); evdev_push_key(sc->evdev_a, BTN_0 + i * 2 + 1, pb->ipacket[5] & (1 << i)); } } #endif pb->ipacket[4] &= ~(mask); pb->ipacket[5] &= ~(mask); } else if (!sc->syninfo.directional_scrolls && !sc->gesture.in_vscroll) { /* * Keep reporting MOUSE DOWN until we get a new packet * indicating otherwise. */ extended_buttons |= sc->extended_buttons; } } /* Handle ClickPad */ if (sc->synhw.capClickPad && ((pb->ipacket[0] ^ pb->ipacket[3]) & 0x01)) touchpad_buttons |= MOUSE_BUTTON1DOWN; if (sc->synhw.capReportsV && nfingers > 1) f[0] = (finger_t) { .x = ((pb->ipacket[3] & 0x10) << 8) | ((pb->ipacket[1] & 0x0f) << 8) | (pb->ipacket[4] & 0xfd), .y = ((pb->ipacket[3] & 0x20) << 7) | ((pb->ipacket[1] & 0xf0) << 4) | (pb->ipacket[5] & 0xfd), .p = *z & 0xfe, .w = (((pb->ipacket[2] & 0x01) << 2) | (pb->ipacket[5] & 0x02) | ((pb->ipacket[4] & 0x02) >> 1)) + 8, .flags = PSM_FINGER_FUZZY, }; else f[0] = (finger_t) { .x = ((pb->ipacket[3] & 0x10) << 8) | ((pb->ipacket[1] & 0x0f) << 8) | pb->ipacket[4], .y = ((pb->ipacket[3] & 0x20) << 7) | ((pb->ipacket[1] & 0xf0) << 4) | pb->ipacket[5], .p = *z, .w = w, .flags = nfingers > 1 ? PSM_FINGER_FUZZY : 0, }; /* Ignore hovering and unmeasurable touches */ if (f[0].p < sc->syninfo.min_pressure || f[0].x < 2) nfingers = 0; for (id = 0; id < PSM_FINGERS; id++) if (id >= nfingers) PSM_FINGER_RESET(f[id]); #ifdef EVDEV_SUPPORT if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) { for (id = 0; id < PSM_FINGERS; id++) { if (PSM_FINGER_IS_SET(f[id])) psm_push_mt_finger(sc, id, &f[id]); else psm_release_mt_slot(sc->evdev_a, id); } evdev_push_key(sc->evdev_a, BTN_TOUCH, nfingers > 0); evdev_push_nfingers(sc->evdev_a, nfingers); if (nfingers > 0) psm_push_st_finger(sc, &f[0]); else evdev_push_abs(sc->evdev_a, ABS_PRESSURE, 0); evdev_push_mouse_btn(sc->evdev_a, touchpad_buttons); if (sc->synhw.capExtended && sc->synhw.capFourButtons) { evdev_push_key(sc->evdev_a, BTN_FORWARD, touchpad_buttons & MOUSE_BUTTON4DOWN); evdev_push_key(sc->evdev_a, BTN_BACK, touchpad_buttons & MOUSE_BUTTON5DOWN); } evdev_sync(sc->evdev_a); } #endif ms->button = touchpad_buttons; psmgestures(sc, &f[0], nfingers, ms); for (id = 0; id < PSM_FINGERS; id++) psmsmoother(sc, &f[id], id, ms, x, y); /* Palm detection doesn't terminate the current action. */ if (psmpalmdetect(sc, &f[0], nfingers)) { *x = *y = *z = 0; ms->button = ms->obutton; return (0); } ms->button |= extended_buttons | guest_buttons; SYNAPTICS_END: /* * Use the extra buttons as a scrollwheel * * XXX X.Org uses the Z axis for vertical wheel only, * whereas moused(8) understands special values to differ * vertical and horizontal wheels. * * xf86-input-mouse needs therefore a small patch to * understand these special values. Without it, the * horizontal wheel acts as a vertical wheel in X.Org. * * That's why the horizontal wheel is disabled by * default for now. */ if (ms->button & MOUSE_BUTTON4DOWN) *z = -1; else if (ms->button & MOUSE_BUTTON5DOWN) *z = 1; else if (ms->button & MOUSE_BUTTON6DOWN) *z = -2; else if (ms->button & MOUSE_BUTTON7DOWN) *z = 2; else *z = 0; ms->button &= ~(MOUSE_BUTTON4DOWN | MOUSE_BUTTON5DOWN | MOUSE_BUTTON6DOWN | MOUSE_BUTTON7DOWN); return (0); } static int psmpalmdetect(struct psm_softc *sc, finger_t *f, int nfingers) { if (!( ((sc->synhw.capMultiFinger || sc->synhw.capAdvancedGestures) && !sc->synhw.capReportsV && nfingers > 1) || (sc->synhw.capReportsV && nfingers > 2) || (sc->synhw.capPalmDetect && f->w <= sc->syninfo.max_width) || (!sc->synhw.capPalmDetect && f->p <= sc->syninfo.max_pressure) || (sc->synhw.capPen && f->flags & PSM_FINGER_IS_PEN))) { /* * We consider the packet irrelevant for the current * action when: * - the width isn't comprised in: * [1; max_width] * - the pressure isn't comprised in: * [min_pressure; max_pressure] * - pen aren't supported but PSM_FINGER_IS_PEN is set */ VLOG(2, (LOG_DEBUG, "synaptics: palm detected! (%d)\n", f->w)); return (1); } return (0); } static void psmgestures(struct psm_softc *sc, finger_t *fingers, int nfingers, mousestatus_t *ms) { smoother_t *smoother; gesture_t *gest; finger_t *f; int y_ok, center_button, center_x, right_button, right_x, i; f = &fingers[0]; smoother = &sc->smoother[0]; gest = &sc->gesture; /* Find first active finger. */ if (nfingers > 0) { for (i = 0; i < PSM_FINGERS; i++) { if (PSM_FINGER_IS_SET(fingers[i])) { f = &fingers[i]; smoother = &sc->smoother[i]; break; } } } /* * Check pressure to detect a real wanted action on the * touchpad. */ if (f->p >= sc->syninfo.min_pressure) { int x0, y0; int dxp, dyp; int start_x, start_y; int queue_len; int margin_top, margin_right, margin_bottom, margin_left; int window_min, window_max; int vscroll_hor_area, vscroll_ver_area; int two_finger_scroll; int max_x, max_y; /* Read sysctl. */ /* XXX Verify values? */ margin_top = sc->syninfo.margin_top; margin_right = sc->syninfo.margin_right; margin_bottom = sc->syninfo.margin_bottom; margin_left = sc->syninfo.margin_left; window_min = sc->syninfo.window_min; window_max = sc->syninfo.window_max; vscroll_hor_area = sc->syninfo.vscroll_hor_area; vscroll_ver_area = sc->syninfo.vscroll_ver_area; two_finger_scroll = sc->syninfo.two_finger_scroll; max_x = sc->syninfo.max_x; max_y = sc->syninfo.max_y; /* Read current absolute position. */ x0 = f->x; y0 = f->y; /* * Limit the coordinates to the specified margins because * this area isn't very reliable. */ if (x0 <= margin_left) x0 = margin_left; else if (x0 >= max_x - margin_right) x0 = max_x - margin_right; if (y0 <= margin_bottom) y0 = margin_bottom; else if (y0 >= max_y - margin_top) y0 = max_y - margin_top; VLOG(3, (LOG_DEBUG, "synaptics: ipacket: [%d, %d], %d, %d\n", x0, y0, f->p, f->w)); /* * If the action is just beginning, init the structure and * compute tap timeout. */ if (!(sc->flags & PSM_FLAGS_FINGERDOWN)) { VLOG(3, (LOG_DEBUG, "synaptics: ----\n")); /* Initialize queue. */ gest->window_min = window_min; /* Reset pressure peak. */ gest->zmax = 0; /* Reset fingers count. */ gest->fingers_nb = 0; /* Reset virtual scrolling state. */ gest->in_vscroll = 0; /* Compute tap timeout. */ gest->taptimeout.tv_sec = tap_timeout / 1000000; gest->taptimeout.tv_usec = tap_timeout % 1000000; timevaladd(&gest->taptimeout, &sc->lastsoftintr); sc->flags |= PSM_FLAGS_FINGERDOWN; /* Smoother has not been reset yet */ queue_len = 1; start_x = x0; start_y = y0; } else { queue_len = smoother->queue_len + 1; start_x = smoother->start_x; start_y = smoother->start_y; } /* Process ClickPad softbuttons */ if (sc->synhw.capClickPad && ms->button & MOUSE_BUTTON1DOWN) { y_ok = sc->syninfo.softbuttons_y >= 0 ? start_y < sc->syninfo.softbuttons_y : start_y > max_y + sc->syninfo.softbuttons_y; center_button = MOUSE_BUTTON2DOWN; center_x = sc->syninfo.softbutton2_x; right_button = MOUSE_BUTTON3DOWN; right_x = sc->syninfo.softbutton3_x; if (center_x > 0 && right_x > 0 && center_x > right_x) { center_button = MOUSE_BUTTON3DOWN; center_x = sc->syninfo.softbutton3_x; right_button = MOUSE_BUTTON2DOWN; right_x = sc->syninfo.softbutton2_x; } if (right_x > 0 && start_x > right_x && y_ok) ms->button = (ms->button & ~MOUSE_BUTTON1DOWN) | right_button; else if (center_x > 0 && start_x > center_x && y_ok) ms->button = (ms->button & ~MOUSE_BUTTON1DOWN) | center_button; } /* If in tap-hold, add the recorded button. */ if (gest->in_taphold) ms->button |= gest->tap_button; /* * For tap, we keep the maximum number of fingers and the * pressure peak. Also with multiple fingers, we increase * the minimum window. */ if (nfingers > 1) gest->window_min = window_max; gest->fingers_nb = imax(nfingers, gest->fingers_nb); gest->zmax = imax(f->p, gest->zmax); /* Do we have enough packets to consider this a gesture? */ if (queue_len < gest->window_min) return; /* Is a scrolling action occurring? */ if (!gest->in_taphold && !ms->button && (!gest->in_vscroll || two_finger_scroll)) { /* * A scrolling action must not conflict with a tap * action. Here are the conditions to consider a * scrolling action: * - the action in a configurable area * - one of the following: * . the distance between the last packet and the * first should be above a configurable minimum * . tap timed out */ dxp = abs(x0 - start_x); dyp = abs(y0 - start_y); if (timevalcmp(&sc->lastsoftintr, &gest->taptimeout, >) || dxp >= sc->syninfo.vscroll_min_delta || dyp >= sc->syninfo.vscroll_min_delta) { /* * Handle two finger scrolling. * Note that we don't rely on fingers_nb * as that keeps the maximum number of fingers. */ if (two_finger_scroll) { if (nfingers == 2) { gest->in_vscroll += dyp ? 2 : 0; gest->in_vscroll += dxp ? 1 : 0; } } else { /* Check for horizontal scrolling. */ if ((vscroll_hor_area > 0 && start_y <= vscroll_hor_area) || (vscroll_hor_area < 0 && start_y >= max_y + vscroll_hor_area)) gest->in_vscroll += 2; /* Check for vertical scrolling. */ if ((vscroll_ver_area > 0 && start_x <= vscroll_ver_area) || (vscroll_ver_area < 0 && start_x >= max_x + vscroll_ver_area)) gest->in_vscroll += 1; } /* Avoid conflicts if area overlaps. */ if (gest->in_vscroll >= 3) gest->in_vscroll = (dxp > dyp) ? 2 : 1; } } /* * Reset two finger scrolling when the number of fingers * is different from two or any button is pressed. */ if (two_finger_scroll && gest->in_vscroll != 0 && (nfingers != 2 || ms->button)) gest->in_vscroll = 0; VLOG(5, (LOG_DEBUG, "synaptics: virtual scrolling: %s " "(direction=%d, dxp=%d, dyp=%d, fingers=%d)\n", gest->in_vscroll ? "YES" : "NO", gest->in_vscroll, dxp, dyp, gest->fingers_nb)); } else if (sc->flags & PSM_FLAGS_FINGERDOWN) { /* * An action is currently taking place but the pressure * dropped under the minimum, putting an end to it. */ int taphold_timeout, dx, dy, tap_max_delta; dx = abs(smoother->queue[smoother->queue_cursor].x - smoother->start_x); dy = abs(smoother->queue[smoother->queue_cursor].y - smoother->start_y); /* Max delta is disabled for multi-fingers tap. */ if (gest->fingers_nb > 1) tap_max_delta = imax(dx, dy); else tap_max_delta = sc->syninfo.tap_max_delta; sc->flags &= ~PSM_FLAGS_FINGERDOWN; /* Check for tap. */ VLOG(3, (LOG_DEBUG, "synaptics: zmax=%d, dx=%d, dy=%d, " "delta=%d, fingers=%d, queue=%d\n", gest->zmax, dx, dy, tap_max_delta, gest->fingers_nb, smoother->queue_len)); if (!gest->in_vscroll && gest->zmax >= tap_threshold && timevalcmp(&sc->lastsoftintr, &gest->taptimeout, <=) && dx <= tap_max_delta && dy <= tap_max_delta && smoother->queue_len >= sc->syninfo.tap_min_queue) { /* * We have a tap if: * - the maximum pressure went over tap_threshold * - the action ended before tap_timeout * * To handle tap-hold, we must delay any button push to * the next action. */ if (gest->in_taphold) { /* * This is the second and last tap of a * double tap action, not a tap-hold. */ gest->in_taphold = 0; /* * For double-tap to work: * - no button press is emitted (to * simulate a button release) * - PSM_FLAGS_FINGERDOWN is set to * force the next packet to emit a * button press) */ VLOG(2, (LOG_DEBUG, "synaptics: button RELEASE: %d\n", gest->tap_button)); sc->flags |= PSM_FLAGS_FINGERDOWN; /* Schedule button press on next interrupt */ sc->idletimeout.tv_sec = psmhz > 1 ? 0 : 1; sc->idletimeout.tv_usec = psmhz > 1 ? 1000000 / psmhz : 0; } else { /* * This is the first tap: we set the * tap-hold state and notify the button * down event. */ gest->in_taphold = 1; taphold_timeout = sc->syninfo.taphold_timeout; gest->taptimeout.tv_sec = taphold_timeout / 1000000; gest->taptimeout.tv_usec = taphold_timeout % 1000000; sc->idletimeout = gest->taptimeout; timevaladd(&gest->taptimeout, &sc->lastsoftintr); switch (gest->fingers_nb) { case 3: gest->tap_button = MOUSE_BUTTON2DOWN; break; case 2: gest->tap_button = MOUSE_BUTTON3DOWN; break; default: gest->tap_button = MOUSE_BUTTON1DOWN; } VLOG(2, (LOG_DEBUG, "synaptics: button PRESS: %d\n", gest->tap_button)); ms->button |= gest->tap_button; } } else { /* * Not enough pressure or timeout: reset * tap-hold state. */ if (gest->in_taphold) { VLOG(2, (LOG_DEBUG, "synaptics: button RELEASE: %d\n", gest->tap_button)); gest->in_taphold = 0; } else { VLOG(2, (LOG_DEBUG, "synaptics: not a tap-hold\n")); } } } else if (!(sc->flags & PSM_FLAGS_FINGERDOWN) && gest->in_taphold) { /* * For a tap-hold to work, the button must remain down at * least until timeout (where the in_taphold flags will be * cleared) or during the next action. */ if (timevalcmp(&sc->lastsoftintr, &gest->taptimeout, <=)) { ms->button |= gest->tap_button; } else { VLOG(2, (LOG_DEBUG, "synaptics: button RELEASE: %d\n", gest->tap_button)); gest->in_taphold = 0; } } return; } static void psmsmoother(struct psm_softc *sc, finger_t *f, int smoother_id, mousestatus_t *ms, int *x, int *y) { smoother_t *smoother = &sc->smoother[smoother_id]; gesture_t *gest = &(sc->gesture); /* * Check pressure to detect a real wanted action on the * touchpad. */ if (f->p >= sc->syninfo.min_pressure) { int x0, y0; int cursor, peer, window; int dx, dy, dxp, dyp; int max_width, max_pressure; int margin_top, margin_right, margin_bottom, margin_left; int na_top, na_right, na_bottom, na_left; int window_min, window_max; int multiplicator; int weight_current, weight_previous, weight_len_squared; int div_min, div_max, div_len; int vscroll_hor_area, vscroll_ver_area; int two_finger_scroll; int max_x, max_y; int len, weight_prev_x, weight_prev_y; int div_max_x, div_max_y, div_x, div_y; int is_fuzzy; /* Read sysctl. */ /* XXX Verify values? */ max_width = sc->syninfo.max_width; max_pressure = sc->syninfo.max_pressure; margin_top = sc->syninfo.margin_top; margin_right = sc->syninfo.margin_right; margin_bottom = sc->syninfo.margin_bottom; margin_left = sc->syninfo.margin_left; na_top = sc->syninfo.na_top; na_right = sc->syninfo.na_right; na_bottom = sc->syninfo.na_bottom; na_left = sc->syninfo.na_left; window_min = sc->syninfo.window_min; window_max = sc->syninfo.window_max; multiplicator = sc->syninfo.multiplicator; weight_current = sc->syninfo.weight_current; weight_previous = sc->syninfo.weight_previous; weight_len_squared = sc->syninfo.weight_len_squared; div_min = sc->syninfo.div_min; div_max = sc->syninfo.div_max; div_len = sc->syninfo.div_len; vscroll_hor_area = sc->syninfo.vscroll_hor_area; vscroll_ver_area = sc->syninfo.vscroll_ver_area; two_finger_scroll = sc->syninfo.two_finger_scroll; max_x = sc->syninfo.max_x; max_y = sc->syninfo.max_y; is_fuzzy = (f->flags & PSM_FINGER_FUZZY) != 0; /* Read current absolute position. */ x0 = f->x; y0 = f->y; /* * Limit the coordinates to the specified margins because * this area isn't very reliable. */ if (x0 <= margin_left) x0 = margin_left; else if (x0 >= max_x - margin_right) x0 = max_x - margin_right; if (y0 <= margin_bottom) y0 = margin_bottom; else if (y0 >= max_y - margin_top) y0 = max_y - margin_top; /* If the action is just beginning, init the structure. */ if (smoother->active == 0) { VLOG(3, (LOG_DEBUG, "smoother%d: ---\n", smoother_id)); /* Store the first point of this action. */ smoother->start_x = x0; smoother->start_y = y0; dx = dy = 0; /* Initialize queue. */ smoother->queue_cursor = SYNAPTICS_PACKETQUEUE; smoother->queue_len = 0; /* Reset average. */ smoother->avg_dx = 0; smoother->avg_dy = 0; /* Reset squelch. */ smoother->squelch_x = 0; smoother->squelch_y = 0; /* Activate queue */ smoother->active = 1; } else { /* Calculate the current delta. */ cursor = smoother->queue_cursor; dx = x0 - smoother->queue[cursor].x; dy = y0 - smoother->queue[cursor].y; } VLOG(3, (LOG_DEBUG, "smoother%d: ipacket: [%d, %d], %d, %d\n", smoother_id, x0, y0, f->p, f->w)); /* Queue this new packet. */ cursor = SYNAPTICS_QUEUE_CURSOR(smoother->queue_cursor - 1); smoother->queue[cursor].x = x0; smoother->queue[cursor].y = y0; smoother->queue_cursor = cursor; if (smoother->queue_len < SYNAPTICS_PACKETQUEUE) smoother->queue_len++; VLOG(5, (LOG_DEBUG, "smoother%d: cursor[%d]: x=%d, y=%d, dx=%d, dy=%d\n", smoother_id, cursor, x0, y0, dx, dy)); /* Do we have enough packets to consider this a movement? */ if (smoother->queue_len < gest->window_min) return; weight_prev_x = weight_prev_y = weight_previous; div_max_x = div_max_y = div_max; if (gest->in_vscroll) { /* Dividers are different with virtual scrolling. */ div_min = sc->syninfo.vscroll_div_min; div_max_x = div_max_y = sc->syninfo.vscroll_div_max; } else { /* * There's a lot of noise in coordinates when * the finger is on the touchpad's borders. When * using this area, we apply a special weight and * div. */ if (x0 <= na_left || x0 >= max_x - na_right) { weight_prev_x = sc->syninfo.weight_previous_na; div_max_x = sc->syninfo.div_max_na; } if (y0 <= na_bottom || y0 >= max_y - na_top) { weight_prev_y = sc->syninfo.weight_previous_na; div_max_y = sc->syninfo.div_max_na; } } /* * Calculate weights for the average operands and * the divisor. Both depend on the distance between * the current packet and a previous one (based on the * window width). */ window = imin(smoother->queue_len, window_max); peer = SYNAPTICS_QUEUE_CURSOR(cursor + window - 1); dxp = abs(x0 - smoother->queue[peer].x) + 1; dyp = abs(y0 - smoother->queue[peer].y) + 1; len = (dxp * dxp) + (dyp * dyp); weight_prev_x = imin(weight_prev_x, weight_len_squared * weight_prev_x / len); weight_prev_y = imin(weight_prev_y, weight_len_squared * weight_prev_y / len); len = (dxp + dyp) / 2; div_x = div_len * div_max_x / len; div_x = imin(div_max_x, div_x); div_x = imax(div_min, div_x); div_y = div_len * div_max_y / len; div_y = imin(div_max_y, div_y); div_y = imax(div_min, div_y); VLOG(3, (LOG_DEBUG, "smoother%d: peer=%d, len=%d, weight=%d/%d, div=%d/%d\n", smoother_id, peer, len, weight_prev_x, weight_prev_y, div_x, div_y)); /* Compute averages. */ smoother->avg_dx = (weight_current * dx * multiplicator + weight_prev_x * smoother->avg_dx) / (weight_current + weight_prev_x); smoother->avg_dy = (weight_current * dy * multiplicator + weight_prev_y * smoother->avg_dy) / (weight_current + weight_prev_y); VLOG(5, (LOG_DEBUG, "smoother%d: avg_dx~=%d, avg_dy~=%d\n", smoother_id, smoother->avg_dx / multiplicator, smoother->avg_dy / multiplicator)); /* Use these averages to calculate x & y. */ smoother->squelch_x += smoother->avg_dx; dxp = smoother->squelch_x / (div_x * multiplicator); smoother->squelch_x = smoother->squelch_x % (div_x * multiplicator); smoother->squelch_y += smoother->avg_dy; dyp = smoother->squelch_y / (div_y * multiplicator); smoother->squelch_y = smoother->squelch_y % (div_y * multiplicator); switch(gest->in_vscroll) { case 0: /* Pointer movement. */ /* On real<->fuzzy finger switch the x/y pos jumps */ if (is_fuzzy == smoother->is_fuzzy) { *x += dxp; *y += dyp; } VLOG(3, (LOG_DEBUG, "smoother%d: [%d, %d] -> [%d, %d]\n", smoother_id, dx, dy, dxp, dyp)); break; case 1: /* Vertical scrolling. */ if (dyp != 0) ms->button |= (dyp > 0) ? MOUSE_BUTTON4DOWN : MOUSE_BUTTON5DOWN; break; case 2: /* Horizontal scrolling. */ if (dxp != 0) ms->button |= (dxp > 0) ? MOUSE_BUTTON7DOWN : MOUSE_BUTTON6DOWN; break; } smoother->is_fuzzy = is_fuzzy; } else { /* * Deactivate queue. Note: We can not just reset queue here * as these values are still used by gesture processor. * So postpone reset till next touch. */ smoother->active = 0; } } static int proc_elantech(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms, int *x, int *y, int *z) { static int touchpad_button, trackpoint_button; finger_t fn, f[ELANTECH_MAX_FINGERS]; int pkt, id, scale, i, nfingers, mask; if (!elantech_support) return (0); /* Determine packet format and do a sanity check for out of sync packets. */ if (ELANTECH_PKT_IS_DEBOUNCE(pb, sc->elanhw.hwversion)) pkt = ELANTECH_PKT_NOP; else if (sc->elanhw.hastrackpoint && ELANTECH_PKT_IS_TRACKPOINT(pb)) pkt = ELANTECH_PKT_TRACKPOINT; else switch (sc->elanhw.hwversion) { case 2: if (!ELANTECH_PKT_IS_V2(pb)) return (-1); pkt = (pb->ipacket[0] & 0xc0) == 0x80 ? ELANTECH_PKT_V2_2FINGER : ELANTECH_PKT_V2_COMMON; break; case 3: if (!ELANTECH_PKT_IS_V3_HEAD(pb, sc->elanhw.hascrc) && !ELANTECH_PKT_IS_V3_TAIL(pb, sc->elanhw.hascrc)) return (-1); pkt = ELANTECH_PKT_V3; break; case 4: if (!ELANTECH_PKT_IS_V4(pb, sc->elanhw.hascrc)) return (-1); switch (pb->ipacket[3] & 0x03) { case 0x00: pkt = ELANTECH_PKT_V4_STATUS; break; case 0x01: pkt = ELANTECH_PKT_V4_HEAD; break; case 0x02: pkt = ELANTECH_PKT_V4_MOTION; break; default: return (-1); } break; default: return (-1); } VLOG(5, (LOG_DEBUG, "elantech: ipacket format: %d\n", pkt)); for (id = 0; id < ELANTECH_MAX_FINGERS; id++) PSM_FINGER_RESET(f[id]); *x = *y = *z = 0; ms->button = ms->obutton; if (sc->syninfo.touchpad_off) return (0); /* Common legend * L: Left mouse button pressed * R: Right mouse button pressed * N: number of fingers on touchpad * X: absolute x value (horizontal) * Y: absolute y value (vertical) * W; width of the finger touch * P: pressure */ switch (pkt) { case ELANTECH_PKT_V2_COMMON: /* HW V2. One/Three finger touch */ /* 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------- * ipacket[0]: N1 N0 W3 W2 . . R L * ipacket[1]: P7 P6 P5 P4 X11 X10 X9 X8 * ipacket[2]: X7 X6 X5 X4 X3 X2 X1 X0 * ipacket[3]: N4 VF W1 W0 . . . B2 * ipacket[4]: P3 P1 P2 P0 Y11 Y10 Y9 Y8 * ipacket[5]: Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * ------------------------------------------- * N4: set if more than 3 fingers (only in 3 fingers mode) * VF: a kind of flag? (only on EF123, 0 when finger * is over one of the buttons, 1 otherwise) * B2: (on EF113 only, 0 otherwise), one button pressed * P & W is not reported on EF113 touchpads */ nfingers = (pb->ipacket[0] & 0xc0) >> 6; if (nfingers == 3 && (pb->ipacket[3] & 0x80)) nfingers = 4; if (nfingers == 0) { mask = (1 << nfingers) - 1; /* = 0x00 */ break; } /* Map 3-rd and 4-th fingers to first finger */ mask = (1 << 1) - 1; /* = 0x01 */ f[0] = ELANTECH_FINGER_SET_XYP(pb); if (sc->elanhw.haspressure) { f[0].w = ((pb->ipacket[0] & 0x30) >> 2) | ((pb->ipacket[3] & 0x30) >> 4); } else { f[0].p = PSM_FINGER_DEFAULT_P; f[0].w = PSM_FINGER_DEFAULT_W; } /* * HW v2 dont report exact finger positions when 3 or more * fingers are on touchpad. */ if (nfingers > 2) f[0].flags = PSM_FINGER_FUZZY; break; case ELANTECH_PKT_V2_2FINGER: /*HW V2. Two finger touch */ /* 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------- * ipacket[0]: N1 N0 AY8 AX8 . . R L * ipacket[1]: AX7 AX6 AX5 AX4 AX3 AX2 AX1 AX0 * ipacket[2]: AY7 AY6 AY5 AY4 AY3 AY2 AY1 AY0 * ipacket[3]: . . BY8 BX8 . . . . * ipacket[4]: BX7 BX6 BX5 BX4 BX3 BX2 BX1 BX0 * ipacket[5]: BY7 BY6 BY5 BY4 BY3 BY2 BY1 BY0 * ------------------------------------------- * AX: lower-left finger absolute x value * AY: lower-left finger absolute y value * BX: upper-right finger absolute x value * BY: upper-right finger absolute y value */ nfingers = 2; mask = (1 << nfingers) - 1; for (id = 0; id < imin(2, ELANTECH_MAX_FINGERS); id ++) f[id] = (finger_t) { .x = (((pb->ipacket[id * 3] & 0x10) << 4) | pb->ipacket[id * 3 + 1]) << 2, .y = (((pb->ipacket[id * 3] & 0x20) << 3) | pb->ipacket[id * 3 + 2]) << 2, .p = PSM_FINGER_DEFAULT_P, .w = PSM_FINGER_DEFAULT_W, /* HW ver.2 sends bounding box */ .flags = PSM_FINGER_FUZZY }; break; case ELANTECH_PKT_V3: /* HW Version 3 */ /* 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------- * ipacket[0]: N1 N0 W3 W2 0 1 R L * ipacket[1]: P7 P6 P5 P4 X11 X10 X9 X8 * ipacket[2]: X7 X6 X5 X4 X3 X2 X1 X0 * ipacket[3]: 0 0 W1 W0 0 0 1 0 * ipacket[4]: P3 P1 P2 P0 Y11 Y10 Y9 Y8 * ipacket[5]: Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * ------------------------------------------- */ nfingers = (pb->ipacket[0] & 0xc0) >> 6; /* Map 3-rd finger to first finger */ id = nfingers > 2 ? 0 : nfingers - 1; mask = (1 << (id + 1)) - 1; if (nfingers == 0) break; fn = ELANTECH_FINGER_SET_XYP(pb); fn.w = ((pb->ipacket[0] & 0x30) >> 2) | ((pb->ipacket[3] & 0x30) >> 4); /* * HW v3 dont report exact finger positions when 3 or more * fingers are on touchpad. */ if (nfingers > 1) fn.flags = PSM_FINGER_FUZZY; if (nfingers == 2) { if (ELANTECH_PKT_IS_V3_HEAD(pb, sc->elanhw.hascrc)) { sc->elanaction.fingers[0] = fn; return (0); } else f[0] = sc->elanaction.fingers[0]; } f[id] = fn; break; case ELANTECH_PKT_V4_STATUS: /* HW Version 4. Status packet */ /* 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------- * ipacket[0]: . . . . 0 1 R L * ipacket[1]: . . . F4 F3 F2 F1 F0 * ipacket[2]: . . . . . . . . * ipacket[3]: . . . 1 0 0 0 0 * ipacket[4]: PL . . . . . . . * ipacket[5]: . . . . . . . . * ------------------------------------------- * Fn: finger n is on touchpad * PL: palm * HV ver4 sends a status packet to indicate that the numbers * or identities of the fingers has been changed */ mask = pb->ipacket[1] & 0x1f; nfingers = bitcount(mask); if (sc->elanaction.mask_v4wait != 0) VLOG(3, (LOG_DEBUG, "elantech: HW v4 status packet" " when not all previous head packets received\n")); /* Bitmap of fingers to receive before gesture processing */ sc->elanaction.mask_v4wait = mask & ~sc->elanaction.mask; /* Skip "new finger is on touchpad" packets */ if (sc->elanaction.mask_v4wait) { sc->elanaction.mask = mask; return (0); } break; case ELANTECH_PKT_V4_HEAD: /* HW Version 4. Head packet */ /* 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------- * ipacket[0]: W3 W2 W1 W0 0 1 R L * ipacket[1]: P7 P6 P5 P4 X11 X10 X9 X8 * ipacket[2]: X7 X6 X5 X4 X3 X2 X1 X0 * ipacket[3]: ID2 ID1 ID0 1 0 0 0 1 * ipacket[4]: P3 P1 P2 P0 Y11 Y10 Y9 Y8 * ipacket[5]: Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * ------------------------------------------- * ID: finger id * HW ver 4 sends head packets in two cases: * 1. One finger touch and movement. * 2. Next after status packet to tell new finger positions. */ mask = sc->elanaction.mask; nfingers = bitcount(mask); id = ((pb->ipacket[3] & 0xe0) >> 5) - 1; fn = ELANTECH_FINGER_SET_XYP(pb); fn.w =(pb->ipacket[0] & 0xf0) >> 4; if (id < 0) return (0); /* Packet is finger position update. Report it */ if (sc->elanaction.mask_v4wait == 0) { if (id < ELANTECH_MAX_FINGERS) f[id] = fn; break; } /* Remove finger from waiting bitmap and store into context */ sc->elanaction.mask_v4wait &= ~(1 << id); if (id < ELANTECH_MAX_FINGERS) sc->elanaction.fingers[id] = fn; /* Wait for other fingers if needed */ if (sc->elanaction.mask_v4wait != 0) return (0); /* All new fingers are received. Report them from context */ for (id = 0; id < ELANTECH_MAX_FINGERS; id++) if (sc->elanaction.mask & (1 << id)) f[id] = sc->elanaction.fingers[id]; break; case ELANTECH_PKT_V4_MOTION: /* HW Version 4. Motion packet */ /* 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------- * ipacket[0]: ID2 ID1 ID0 OF 0 1 R L * ipacket[1]: DX7 DX6 DX5 DX4 DX3 DX2 DX1 DX0 * ipacket[2]: DY7 DY6 DY5 DY4 DY3 DY2 DY1 DY0 * ipacket[3]: ID2 ID1 ID0 1 0 0 1 0 * ipacket[4]: DX7 DX6 DX5 DX4 DX3 DX2 DX1 DX0 * ipacket[5]: DY7 DY6 DY5 DY4 DY3 DY2 DY1 DY0 * ------------------------------------------- * OF: delta overflows (> 127 or < -128), in this case * firmware sends us (delta x / 5) and (delta y / 5) * ID: finger id * DX: delta x (two's complement) * XY: delta y (two's complement) * byte 0 ~ 2 for one finger * byte 3 ~ 5 for another finger */ mask = sc->elanaction.mask; nfingers = bitcount(mask); scale = (pb->ipacket[0] & 0x10) ? 5 : 1; for (i = 0; i <= 3; i += 3) { id = ((pb->ipacket[i] & 0xe0) >> 5) - 1; if (id < 0 || id >= ELANTECH_MAX_FINGERS) continue; if (PSM_FINGER_IS_SET(sc->elanaction.fingers[id])) { f[id] = sc->elanaction.fingers[id]; f[id].x += imax(-f[id].x, (signed char)pb->ipacket[i+1] * scale); f[id].y += imax(-f[id].y, (signed char)pb->ipacket[i+2] * scale); } else { VLOG(3, (LOG_DEBUG, "elantech: " "HW v4 motion packet skipped\n")); } } break; case ELANTECH_PKT_TRACKPOINT: /* 7 6 5 4 3 2 1 0 (LSB) * ------------------------------------------- * ipacket[0]: 0 0 SX SY 0 M R L * ipacket[1]: ~SX 0 0 0 0 0 0 0 * ipacket[2]: ~SY 0 0 0 0 0 0 0 * ipacket[3]: 0 0 ~SY ~SX 0 1 1 0 * ipacket[4]: X7 X6 X5 X4 X3 X2 X1 X0 * ipacket[5]: Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 * ------------------------------------------- * X and Y are written in two's complement spread * over 9 bits with SX/SY the relative top bit and * X7..X0 and Y7..Y0 the lower bits. */ *x = (pb->ipacket[0] & 0x20) ? pb->ipacket[4] - 256 : pb->ipacket[4]; *y = (pb->ipacket[0] & 0x10) ? pb->ipacket[5] - 256 : pb->ipacket[5]; trackpoint_button = ((pb->ipacket[0] & 0x01) ? MOUSE_BUTTON1DOWN : 0) | ((pb->ipacket[0] & 0x02) ? MOUSE_BUTTON3DOWN : 0) | ((pb->ipacket[0] & 0x04) ? MOUSE_BUTTON2DOWN : 0); #ifdef EVDEV_SUPPORT evdev_push_rel(sc->evdev_r, REL_X, *x); evdev_push_rel(sc->evdev_r, REL_Y, -*y); evdev_push_mouse_btn(sc->evdev_r, trackpoint_button); evdev_sync(sc->evdev_r); #endif ms->button = touchpad_button | trackpoint_button; return (0); case ELANTECH_PKT_NOP: return (0); default: return (-1); } for (id = 0; id < ELANTECH_MAX_FINGERS; id++) if (PSM_FINGER_IS_SET(f[id])) VLOG(2, (LOG_DEBUG, "elantech: " "finger %d: down [%d, %d], %d, %d, %d\n", id + 1, f[id].x, f[id].y, f[id].p, f[id].w, f[id].flags)); /* Touchpad button presses */ if (sc->elanhw.isclickpad) { touchpad_button = ((pb->ipacket[0] & 0x03) ? MOUSE_BUTTON1DOWN : 0); } else { touchpad_button = ((pb->ipacket[0] & 0x01) ? MOUSE_BUTTON1DOWN : 0) | ((pb->ipacket[0] & 0x02) ? MOUSE_BUTTON3DOWN : 0); } #ifdef EVDEV_SUPPORT if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE) { for (id = 0; id < ELANTECH_MAX_FINGERS; id++) { if (PSM_FINGER_IS_SET(f[id])) { psm_push_mt_finger(sc, id, &f[id]); /* Convert touch width to surface units */ evdev_push_abs(sc->evdev_a, ABS_MT_TOUCH_MAJOR, f[id].w * sc->elanhw.dptracex); } if (sc->elanaction.mask & (1 << id) && !(mask & (1 << id))) psm_release_mt_slot(sc->evdev_a, id); } evdev_push_key(sc->evdev_a, BTN_TOUCH, nfingers > 0); evdev_push_nfingers(sc->evdev_a, nfingers); if (nfingers > 0) { if (PSM_FINGER_IS_SET(f[0])) psm_push_st_finger(sc, &f[0]); } else evdev_push_abs(sc->evdev_a, ABS_PRESSURE, 0); evdev_push_mouse_btn(sc->evdev_a, touchpad_button); evdev_sync(sc->evdev_a); } #endif ms->button = touchpad_button | trackpoint_button; /* Send finger 1 position to gesture processor */ if (PSM_FINGER_IS_SET(f[0]) || PSM_FINGER_IS_SET(f[1]) || nfingers == 0) psmgestures(sc, &f[0], imin(nfingers, 3), ms); /* Send fingers positions to movement smoothers */ for (id = 0; id < PSM_FINGERS; id++) if (PSM_FINGER_IS_SET(f[id]) || !(mask & (1 << id))) psmsmoother(sc, &f[id], id, ms, x, y); /* Store current finger positions in action context */ for (id = 0; id < ELANTECH_MAX_FINGERS; id++) { if (PSM_FINGER_IS_SET(f[id])) sc->elanaction.fingers[id] = f[id]; if ((sc->elanaction.mask & (1 << id)) && !(mask & (1 << id))) PSM_FINGER_RESET(sc->elanaction.fingers[id]); } sc->elanaction.mask = mask; /* Palm detection doesn't terminate the current action. */ if (psmpalmdetect(sc, &f[0], nfingers)) { *x = *y = *z = 0; ms->button = ms->obutton; return (0); } /* Use the extra buttons as a scrollwheel */ if (ms->button & MOUSE_BUTTON4DOWN) *z = -1; else if (ms->button & MOUSE_BUTTON5DOWN) *z = 1; else if (ms->button & MOUSE_BUTTON6DOWN) *z = -2; else if (ms->button & MOUSE_BUTTON7DOWN) *z = 2; else *z = 0; ms->button &= ~(MOUSE_BUTTON4DOWN | MOUSE_BUTTON5DOWN | MOUSE_BUTTON6DOWN | MOUSE_BUTTON7DOWN); return (0); } static void proc_versapad(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *ms, int *x, int *y, int *z) { static int butmap_versapad[8] = { 0, MOUSE_BUTTON3DOWN, 0, MOUSE_BUTTON3DOWN, MOUSE_BUTTON1DOWN, MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, MOUSE_BUTTON1DOWN, MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN }; int c, x0, y0; /* VersaPad PS/2 absolute mode message format * * [packet1] 7 6 5 4 3 2 1 0(LSB) * ipacket[0]: 1 1 0 A 1 L T R * ipacket[1]: H7 H6 H5 H4 H3 H2 H1 H0 * ipacket[2]: V7 V6 V5 V4 V3 V2 V1 V0 * ipacket[3]: 1 1 1 A 1 L T R * ipacket[4]:V11 V10 V9 V8 H11 H10 H9 H8 * ipacket[5]: 0 P6 P5 P4 P3 P2 P1 P0 * * [note] * R: right physical mouse button (1=on) * T: touch pad virtual button (1=tapping) * L: left physical mouse button (1=on) * A: position data is valid (1=valid) * H: horizontal data (12bit signed integer. H11 is sign bit.) * V: vertical data (12bit signed integer. V11 is sign bit.) * P: pressure data * * Tapping is mapped to MOUSE_BUTTON4. */ c = pb->ipacket[0]; *x = *y = 0; ms->button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS]; ms->button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0; if (c & MOUSE_PS2VERSA_IN_USE) { x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8); y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4); if (x0 & 0x800) x0 -= 0x1000; if (y0 & 0x800) y0 -= 0x1000; if (sc->flags & PSM_FLAGS_FINGERDOWN) { *x = sc->xold - x0; *y = y0 - sc->yold; if (*x < 0) /* XXX */ ++*x; else if (*x) --*x; if (*y < 0) ++*y; else if (*y) --*y; } else sc->flags |= PSM_FLAGS_FINGERDOWN; sc->xold = x0; sc->yold = y0; } else sc->flags &= ~PSM_FLAGS_FINGERDOWN; } static void psmsoftintridle(void *arg) { struct psm_softc *sc = arg; packetbuf_t *pb; /* Invoke soft handler only when pqueue is empty. Otherwise it will be * invoked from psmintr soon with pqueue filled with real data */ if (sc->pqueue_start == sc->pqueue_end && sc->idlepacket.inputbytes > 0) { /* Grow circular queue backwards to avoid race with psmintr */ if (--sc->pqueue_start < 0) sc->pqueue_start = PSM_PACKETQUEUE - 1; pb = &sc->pqueue[sc->pqueue_start]; memcpy(pb, &sc->idlepacket, sizeof(packetbuf_t)); VLOG(4, (LOG_DEBUG, "psmsoftintridle: %02x %02x %02x %02x %02x %02x\n", pb->ipacket[0], pb->ipacket[1], pb->ipacket[2], pb->ipacket[3], pb->ipacket[4], pb->ipacket[5])); psmsoftintr(arg); } } static void psmsoftintr(void *arg) { /* * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN) * into `mousestatus' button bits (MOUSE_BUTTON?DOWN). */ static int butmap[8] = { 0, MOUSE_BUTTON1DOWN, MOUSE_BUTTON3DOWN, MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, MOUSE_BUTTON2DOWN, MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN, MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN, MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN }; struct psm_softc *sc = arg; mousestatus_t ms; packetbuf_t *pb; int x, y, z, c, l, s; getmicrouptime(&sc->lastsoftintr); s = spltty(); do { pb = &sc->pqueue[sc->pqueue_start]; if (sc->mode.level == PSM_LEVEL_NATIVE) goto next_native; c = pb->ipacket[0]; /* * A kludge for Kensington device! * The MSB of the horizontal count appears to be stored in * a strange place. */ if (sc->hw.model == MOUSE_MODEL_THINK) pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0; /* ignore the overflow bits... */ x = (c & MOUSE_PS2_XNEG) ? pb->ipacket[1] - 256 : pb->ipacket[1]; y = (c & MOUSE_PS2_YNEG) ? pb->ipacket[2] - 256 : pb->ipacket[2]; z = 0; ms.obutton = sc->button; /* previous button state */ ms.button = butmap[c & MOUSE_PS2_BUTTONS]; /* `tapping' action */ if (sc->config & PSM_CONFIG_FORCETAP) ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN; timevalclear(&sc->idletimeout); sc->idlepacket.inputbytes = 0; switch (sc->hw.model) { case MOUSE_MODEL_EXPLORER: /* * b7 b6 b5 b4 b3 b2 b1 b0 * byte 1: oy ox sy sx 1 M R L * byte 2: x x x x x x x x * byte 3: y y y y y y y y * byte 4: * * S2 S1 s d2 d1 d0 * * L, M, R, S1, S2: left, middle, right and side buttons * s: wheel data sign bit * d2-d0: wheel data */ z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG) ? (pb->ipacket[3] & 0x0f) - 16 : (pb->ipacket[3] & 0x0f); ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN) ? MOUSE_BUTTON4DOWN : 0; ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN) ? MOUSE_BUTTON5DOWN : 0; break; case MOUSE_MODEL_INTELLI: case MOUSE_MODEL_NET: /* wheel data is in the fourth byte */ z = (char)pb->ipacket[3]; /* * XXX some mice may send 7 when there is no Z movement? */ if ((z >= 7) || (z <= -7)) z = 0; /* some compatible mice have additional buttons */ ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN) ? MOUSE_BUTTON4DOWN : 0; ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN) ? MOUSE_BUTTON5DOWN : 0; break; case MOUSE_MODEL_MOUSEMANPLUS: proc_mmanplus(sc, pb, &ms, &x, &y, &z); break; case MOUSE_MODEL_GLIDEPOINT: /* `tapping' action */ ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN; break; case MOUSE_MODEL_NETSCROLL: /* * three additional bytes encode buttons and * wheel events */ ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN) ? MOUSE_BUTTON4DOWN : 0; ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN) ? MOUSE_BUTTON5DOWN : 0; z = (pb->ipacket[3] & MOUSE_PS2_XNEG) ? pb->ipacket[4] - 256 : pb->ipacket[4]; break; case MOUSE_MODEL_THINK: /* the fourth button state in the first byte */ ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0; break; case MOUSE_MODEL_VERSAPAD: proc_versapad(sc, pb, &ms, &x, &y, &z); c = ((x < 0) ? MOUSE_PS2_XNEG : 0) | ((y < 0) ? MOUSE_PS2_YNEG : 0); break; case MOUSE_MODEL_4D: /* * b7 b6 b5 b4 b3 b2 b1 b0 * byte 1: s2 d2 s1 d1 1 M R L * byte 2: sx x x x x x x x * byte 3: sy y y y y y y y * * s1: wheel 1 direction * d1: wheel 1 data * s2: wheel 2 direction * d2: wheel 2 data */ x = (pb->ipacket[1] & 0x80) ? pb->ipacket[1] - 256 : pb->ipacket[1]; y = (pb->ipacket[2] & 0x80) ? pb->ipacket[2] - 256 : pb->ipacket[2]; switch (c & MOUSE_4D_WHEELBITS) { case 0x10: z = 1; break; case 0x30: z = -1; break; case 0x40: /* XXX 2nd wheel turning right */ z = 2; break; case 0xc0: /* XXX 2nd wheel turning left */ z = -2; break; } break; case MOUSE_MODEL_4DPLUS: if ((x < 16 - 256) && (y < 16 - 256)) { /* * b7 b6 b5 b4 b3 b2 b1 b0 * byte 1: 0 0 1 1 1 M R L * byte 2: 0 0 0 0 1 0 0 0 * byte 3: 0 0 0 0 S s d1 d0 * * L, M, R, S: left, middle, right, * and side buttons * s: wheel data sign bit * d1-d0: wheel data */ x = y = 0; if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN) ms.button |= MOUSE_BUTTON4DOWN; z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG) ? ((pb->ipacket[2] & 0x07) - 8) : (pb->ipacket[2] & 0x07) ; } else { /* preserve previous button states */ ms.button |= ms.obutton & MOUSE_EXTBUTTONS; } break; case MOUSE_MODEL_SYNAPTICS: if (proc_synaptics(sc, pb, &ms, &x, &y, &z) != 0) goto next; break; case MOUSE_MODEL_ELANTECH: if (proc_elantech(sc, pb, &ms, &x, &y, &z) != 0) goto next; break; case MOUSE_MODEL_TRACKPOINT: case MOUSE_MODEL_GENERIC: default: break; } #ifdef EVDEV_SUPPORT if (evdev_rcpt_mask & EVDEV_RCPT_HW_MOUSE && sc->hw.model != MOUSE_MODEL_ELANTECH && sc->hw.model != MOUSE_MODEL_SYNAPTICS) { evdev_push_rel(sc->evdev_r, EV_REL, x); evdev_push_rel(sc->evdev_r, EV_REL, -y); switch (sc->hw.model) { case MOUSE_MODEL_EXPLORER: case MOUSE_MODEL_INTELLI: case MOUSE_MODEL_NET: case MOUSE_MODEL_NETSCROLL: case MOUSE_MODEL_4DPLUS: evdev_push_rel(sc->evdev_r, REL_WHEEL, -z); break; case MOUSE_MODEL_MOUSEMANPLUS: case MOUSE_MODEL_4D: switch (z) { case 1: case -1: evdev_push_rel(sc->evdev_r, REL_WHEEL, -z); break; case 2: case -2: evdev_push_rel(sc->evdev_r, REL_HWHEEL, z / 2); break; } break; } evdev_push_mouse_btn(sc->evdev_r, ms.button); evdev_sync(sc->evdev_r); } #endif /* scale values */ if (sc->mode.accelfactor >= 1) { if (x != 0) { x = x * x / sc->mode.accelfactor; if (x == 0) x = 1; if (c & MOUSE_PS2_XNEG) x = -x; } if (y != 0) { y = y * y / sc->mode.accelfactor; if (y == 0) y = 1; if (c & MOUSE_PS2_YNEG) y = -y; } } /* Store last packet for reinjection if it has not been set already */ if (timevalisset(&sc->idletimeout) && sc->idlepacket.inputbytes == 0) sc->idlepacket = *pb; ms.dx = x; ms.dy = y; ms.dz = z; ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0) | (ms.obutton ^ ms.button); pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket); sc->status.flags |= ms.flags; sc->status.dx += ms.dx; sc->status.dy += ms.dy; sc->status.dz += ms.dz; sc->status.button = ms.button; sc->button = ms.button; next_native: sc->watchdog = FALSE; /* queue data */ if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) { l = imin(pb->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail); bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l); if (pb->inputbytes > l) bcopy(&pb->ipacket[l], &sc->queue.buf[0], pb->inputbytes - l); sc->queue.tail = (sc->queue.tail + pb->inputbytes) % sizeof(sc->queue.buf); sc->queue.count += pb->inputbytes; } pb->inputbytes = 0; next: if (++sc->pqueue_start >= PSM_PACKETQUEUE) sc->pqueue_start = 0; } while (sc->pqueue_start != sc->pqueue_end); if (sc->state & PSM_ASLP) { sc->state &= ~PSM_ASLP; wakeup(sc); } selwakeuppri(&sc->rsel, PZERO); if (sc->async != NULL) { pgsigio(&sc->async, SIGIO, 0); } sc->state &= ~PSM_SOFTARMED; /* schedule injection of predefined packet after idletimeout * if no data packets have been received from psmintr */ if (timevalisset(&sc->idletimeout)) { sc->state |= PSM_SOFTARMED; callout_reset(&sc->softcallout, tvtohz(&sc->idletimeout), psmsoftintridle, sc); VLOG(2, (LOG_DEBUG, "softintr: callout set: %d ticks\n", tvtohz(&sc->idletimeout))); } splx(s); } static int psmpoll(struct cdev *dev, int events, struct thread *td) { struct psm_softc *sc = dev->si_drv1; int s; int revents = 0; /* Return true if a mouse event available */ s = spltty(); if (events & (POLLIN | POLLRDNORM)) { if (sc->queue.count > 0) revents |= events & (POLLIN | POLLRDNORM); else selrecord(td, &sc->rsel); } splx(s); return (revents); } /* vendor/model specific routines */ static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status) { if (set_mouse_resolution(kbdc, res) != res) return (FALSE); if (set_mouse_scaling(kbdc, scale) && set_mouse_scaling(kbdc, scale) && set_mouse_scaling(kbdc, scale) && (get_mouse_status(kbdc, status, 0, 3) >= 3)) return (TRUE); return (FALSE); } static int mouse_ext_command(KBDC kbdc, int command) { int c; c = (command >> 6) & 0x03; if (set_mouse_resolution(kbdc, c) != c) return (FALSE); c = (command >> 4) & 0x03; if (set_mouse_resolution(kbdc, c) != c) return (FALSE); c = (command >> 2) & 0x03; if (set_mouse_resolution(kbdc, c) != c) return (FALSE); c = (command >> 0) & 0x03; if (set_mouse_resolution(kbdc, c) != c) return (FALSE); return (TRUE); } #ifdef notyet /* Logitech MouseMan Cordless II */ static int enable_lcordless(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int status[3]; int ch; if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 2, status)) return (FALSE); if (status[1] == PSMD_RES_HIGH) return (FALSE); ch = (status[0] & 0x07) - 1; /* channel # */ if ((ch <= 0) || (ch > 4)) return (FALSE); /* * status[1]: always one? * status[2]: battery status? (0-100) */ return (TRUE); } #endif /* notyet */ /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */ static int enable_groller(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int status[3]; /* * The special sequence to enable the fourth button and the * roller. Immediately after this sequence check status bytes. * if the mouse is NetScroll, the second and the third bytes are * '3' and 'D'. */ /* * If the mouse is an ordinary PS/2 mouse, the status bytes should * look like the following. * * byte 1 bit 7 always 0 * bit 6 stream mode (0) * bit 5 disabled (0) * bit 4 1:1 scaling (0) * bit 3 always 0 * bit 0-2 button status * byte 2 resolution (PSMD_RES_HIGH) * byte 3 report rate (?) */ if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status)) return (FALSE); if ((status[1] != '3') || (status[2] != 'D')) return (FALSE); /* FIXME: SmartScroll Mouse has 5 buttons! XXX */ if (arg == PROBE) sc->hw.buttons = 4; return (TRUE); } /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */ static int enable_gmouse(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int status[3]; /* * The special sequence to enable the middle, "rubber" button. * Immediately after this sequence check status bytes. * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse, * the second and the third bytes are '3' and 'U'. * NOTE: NetMouse reports that it has three buttons although it has * two buttons and a rubber button. NetMouse Pro and MIE Mouse * say they have three buttons too and they do have a button on the * side... */ if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status)) return (FALSE); if ((status[1] != '3') || (status[2] != 'U')) return (FALSE); return (TRUE); } /* ALPS GlidePoint */ static int enable_aglide(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int status[3]; /* * The special sequence to obtain ALPS GlidePoint specific * information. Immediately after this sequence, status bytes will * contain something interesting. * NOTE: ALPS produces several models of GlidePoint. Some of those * do not respond to this sequence, thus, cannot be detected this way. */ if (set_mouse_sampling_rate(kbdc, 100) != 100) return (FALSE); if (!mouse_id_proc1(kbdc, PSMD_RES_LOW, 2, status)) return (FALSE); if ((status[1] == PSMD_RES_LOW) || (status[2] == 100)) return (FALSE); return (TRUE); } /* Kensington ThinkingMouse/Trackball */ static int enable_kmouse(struct psm_softc *sc, enum probearg arg) { static u_char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 }; KBDC kbdc = sc->kbdc; int status[3]; int id1; int id2; int i; id1 = get_aux_id(kbdc); if (set_mouse_sampling_rate(kbdc, 10) != 10) return (FALSE); /* * The device is now in the native mode? It returns a different * ID value... */ id2 = get_aux_id(kbdc); if ((id1 == id2) || (id2 != 2)) return (FALSE); if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW) return (FALSE); #if PSM_DEBUG >= 2 /* at this point, resolution is LOW, sampling rate is 10/sec */ if (get_mouse_status(kbdc, status, 0, 3) < 3) return (FALSE); #endif /* * The special sequence to enable the third and fourth buttons. * Otherwise they behave like the first and second buttons. */ for (i = 0; i < nitems(rate); ++i) if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i]) return (FALSE); /* * At this point, the device is using default resolution and * sampling rate for the native mode. */ if (get_mouse_status(kbdc, status, 0, 3) < 3) return (FALSE); if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1])) return (FALSE); /* the device appears be enabled by this sequence, diable it for now */ disable_aux_dev(kbdc); empty_aux_buffer(kbdc, 5); return (TRUE); } /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */ static int enable_mmanplus(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int data[3]; /* the special sequence to enable the fourth button and the roller. */ /* * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION * must be called exactly three times since the last RESET command * before this sequence. XXX */ if (!set_mouse_scaling(kbdc, 1)) return (FALSE); if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb)) return (FALSE); if (get_mouse_status(kbdc, data, 1, 3) < 3) return (FALSE); /* * PS2++ protocol, packet type 0 * * b7 b6 b5 b4 b3 b2 b1 b0 * byte 1: * 1 p3 p2 1 * * * * byte 2: 1 1 p1 p0 m1 m0 1 0 * byte 3: m7 m6 m5 m4 m3 m2 m1 m0 * * p3-p0: packet type: 0 * m7-m0: model ID: MouseMan+:0x50, * FirstMouse+:0x51, * ScrollPoint:0x58... */ /* check constant bits */ if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC) return (FALSE); if ((data[1] & 0xc3) != 0xc2) return (FALSE); /* check d3-d0 in byte 2 */ if (!MOUSE_PS2PLUS_CHECKBITS(data)) return (FALSE); /* check p3-p0 */ if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0) return (FALSE); if (arg == PROBE) { sc->hw.hwid &= 0x00ff; sc->hw.hwid |= data[2] << 8; /* save model ID */ } /* * MouseMan+ (or FirstMouse+) is now in its native mode, in which * the wheel and the fourth button events are encoded in the * special data packet. The mouse may be put in the IntelliMouse mode * if it is initialized by the IntelliMouse's method. */ return (TRUE); } /* MS IntelliMouse Explorer */ static int enable_msexplorer(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; static u_char rate0[] = { 200, 100, 80, }; static u_char rate1[] = { 200, 200, 80, }; int id; int i; /* * This is needed for at least A4Tech X-7xx mice - they do not go * straight to Explorer mode, but need to be set to Intelli mode * first. */ enable_msintelli(sc, arg); /* the special sequence to enable the extra buttons and the roller. */ for (i = 0; i < nitems(rate1); ++i) if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i]) return (FALSE); /* the device will give the genuine ID only after the above sequence */ id = get_aux_id(kbdc); if (id != PSM_EXPLORER_ID) return (FALSE); if (arg == PROBE) { sc->hw.buttons = 5; /* IntelliMouse Explorer XXX */ sc->hw.hwid = id; } /* * XXX: this is a kludge to fool some KVM switch products * which think they are clever enough to know the 4-byte IntelliMouse * protocol, and assume any other protocols use 3-byte packets. * They don't convey 4-byte data packets from the IntelliMouse Explorer * correctly to the host computer because of this! * The following sequence is actually IntelliMouse's "wake up" * sequence; it will make the KVM think the mouse is IntelliMouse * when it is in fact IntelliMouse Explorer. */ for (i = 0; i < nitems(rate0); ++i) if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i]) break; get_aux_id(kbdc); return (TRUE); } /* * MS IntelliMouse * Logitech MouseMan+ and FirstMouse+ will also respond to this * probe routine and act like IntelliMouse. */ static int enable_msintelli(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; static u_char rate[] = { 200, 100, 80, }; int id; int i; /* the special sequence to enable the third button and the roller. */ for (i = 0; i < nitems(rate); ++i) if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i]) return (FALSE); /* the device will give the genuine ID only after the above sequence */ id = get_aux_id(kbdc); if (id != PSM_INTELLI_ID) return (FALSE); if (arg == PROBE) { sc->hw.buttons = 3; sc->hw.hwid = id; } return (TRUE); } /* * A4 Tech 4D Mouse * Newer wheel mice from A4 Tech may use the 4D+ protocol. */ static int enable_4dmouse(struct psm_softc *sc, enum probearg arg) { static u_char rate[] = { 200, 100, 80, 60, 40, 20 }; KBDC kbdc = sc->kbdc; int id; int i; for (i = 0; i < nitems(rate); ++i) if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i]) return (FALSE); id = get_aux_id(kbdc); /* * WinEasy 4D, 4 Way Scroll 4D: 6 * Cable-Free 4D: 8 (4DPLUS) * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS) */ if (id != PSM_4DMOUSE_ID) return (FALSE); if (arg == PROBE) { sc->hw.buttons = 3; /* XXX some 4D mice have 4? */ sc->hw.hwid = id; } return (TRUE); } /* * A4 Tech 4D+ Mouse * Newer wheel mice from A4 Tech seem to use this protocol. * Older models are recognized as either 4D Mouse or IntelliMouse. */ static int enable_4dplus(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int id; /* * enable_4dmouse() already issued the following ID sequence... static u_char rate[] = { 200, 100, 80, 60, 40, 20 }; int i; for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i]) return (FALSE); */ id = get_aux_id(kbdc); switch (id) { case PSM_4DPLUS_ID: break; case PSM_4DPLUS_RFSW35_ID: break; default: return (FALSE); } if (arg == PROBE) { sc->hw.buttons = (id == PSM_4DPLUS_ID) ? 4 : 3; sc->hw.hwid = id; } return (TRUE); } /* Synaptics Touchpad */ static int synaptics_sysctl(SYSCTL_HANDLER_ARGS) { struct psm_softc *sc; int error, arg; if (oidp->oid_arg1 == NULL || oidp->oid_arg2 < 0 || oidp->oid_arg2 > SYNAPTICS_SYSCTL_SOFTBUTTON3_X) return (EINVAL); sc = oidp->oid_arg1; /* Read the current value. */ arg = *(int *)((char *)sc + oidp->oid_arg2); error = sysctl_handle_int(oidp, &arg, 0, req); /* Sanity check. */ if (error || !req->newptr) return (error); /* * Check that the new value is in the concerned node's range * of values. */ switch (oidp->oid_arg2) { case SYNAPTICS_SYSCTL_MIN_PRESSURE: case SYNAPTICS_SYSCTL_MAX_PRESSURE: if (arg < 0 || arg > 255) return (EINVAL); break; case SYNAPTICS_SYSCTL_MAX_WIDTH: if (arg < 4 || arg > 15) return (EINVAL); break; case SYNAPTICS_SYSCTL_MARGIN_TOP: case SYNAPTICS_SYSCTL_MARGIN_BOTTOM: case SYNAPTICS_SYSCTL_NA_TOP: case SYNAPTICS_SYSCTL_NA_BOTTOM: if (arg < 0 || arg > sc->synhw.maximumYCoord) return (EINVAL); break; case SYNAPTICS_SYSCTL_SOFTBUTTON2_X: case SYNAPTICS_SYSCTL_SOFTBUTTON3_X: /* Softbuttons is clickpad only feature */ if (!sc->synhw.capClickPad && arg != 0) return (EINVAL); /* FALLTHROUGH */ case SYNAPTICS_SYSCTL_MARGIN_RIGHT: case SYNAPTICS_SYSCTL_MARGIN_LEFT: case SYNAPTICS_SYSCTL_NA_RIGHT: case SYNAPTICS_SYSCTL_NA_LEFT: if (arg < 0 || arg > sc->synhw.maximumXCoord) return (EINVAL); break; case SYNAPTICS_SYSCTL_WINDOW_MIN: case SYNAPTICS_SYSCTL_WINDOW_MAX: case SYNAPTICS_SYSCTL_TAP_MIN_QUEUE: if (arg < 1 || arg > SYNAPTICS_PACKETQUEUE) return (EINVAL); break; case SYNAPTICS_SYSCTL_MULTIPLICATOR: case SYNAPTICS_SYSCTL_WEIGHT_CURRENT: case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS: case SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA: case SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED: case SYNAPTICS_SYSCTL_DIV_MIN: case SYNAPTICS_SYSCTL_DIV_MAX: case SYNAPTICS_SYSCTL_DIV_MAX_NA: case SYNAPTICS_SYSCTL_DIV_LEN: case SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN: case SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX: if (arg < 1) return (EINVAL); break; case SYNAPTICS_SYSCTL_TAP_MAX_DELTA: case SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT: case SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA: if (arg < 0) return (EINVAL); break; case SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA: if (arg < -sc->synhw.maximumXCoord || arg > sc->synhw.maximumXCoord) return (EINVAL); break; case SYNAPTICS_SYSCTL_SOFTBUTTONS_Y: /* Softbuttons is clickpad only feature */ if (!sc->synhw.capClickPad && arg != 0) return (EINVAL); /* FALLTHROUGH */ case SYNAPTICS_SYSCTL_VSCROLL_VER_AREA: if (arg < -sc->synhw.maximumYCoord || arg > sc->synhw.maximumYCoord) return (EINVAL); break; case SYNAPTICS_SYSCTL_TOUCHPAD_OFF: if (arg < 0 || arg > 1) return (EINVAL); break; default: return (EINVAL); } /* Update. */ *(int *)((char *)sc + oidp->oid_arg2) = arg; return (error); } static void synaptics_sysctl_create_softbuttons_tree(struct psm_softc *sc) { /* * Set predefined sizes for softbuttons. * Values are taken to match HP Pavilion dv6 clickpad drawings * with thin middle softbutton placed on separator */ /* hw.psm.synaptics.softbuttons_y */ sc->syninfo.softbuttons_y = 1700; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "softbuttons_y", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_SOFTBUTTONS_Y, synaptics_sysctl, "I", "Vertical size of softbuttons area"); /* hw.psm.synaptics.softbutton2_x */ sc->syninfo.softbutton2_x = 3100; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "softbutton2_x", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_SOFTBUTTON2_X, synaptics_sysctl, "I", "Horisontal position of 2-nd softbutton left edge (0-disable)"); /* hw.psm.synaptics.softbutton3_x */ sc->syninfo.softbutton3_x = 3900; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "softbutton3_x", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_SOFTBUTTON3_X, synaptics_sysctl, "I", "Horisontal position of 3-rd softbutton left edge (0-disable)"); } static void synaptics_sysctl_create_tree(struct psm_softc *sc, const char *name, const char *descr) { if (sc->syninfo.sysctl_tree != NULL) return; /* Attach extra synaptics sysctl nodes under hw.psm.synaptics */ sysctl_ctx_init(&sc->syninfo.sysctl_ctx); sc->syninfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->syninfo.sysctl_ctx, SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, name, CTLFLAG_RD, 0, descr); /* hw.psm.synaptics.directional_scrolls. */ sc->syninfo.directional_scrolls = 0; SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "directional_scrolls", CTLFLAG_RW|CTLFLAG_ANYBODY, &sc->syninfo.directional_scrolls, 0, "Enable hardware scrolling pad (if non-zero) or register it as " "extended buttons (if 0)"); /* hw.psm.synaptics.max_x. */ sc->syninfo.max_x = 6143; SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "max_x", CTLFLAG_RD|CTLFLAG_ANYBODY, &sc->syninfo.max_x, 0, "Horizontal reporting range"); /* hw.psm.synaptics.max_y. */ sc->syninfo.max_y = 6143; SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "max_y", CTLFLAG_RD|CTLFLAG_ANYBODY, &sc->syninfo.max_y, 0, "Vertical reporting range"); /* * Turn off two finger scroll if we have a * physical area reserved for scrolling or when * there's no multi finger support. */ if (sc->synhw.verticalScroll || (sc->synhw.capMultiFinger == 0 && sc->synhw.capAdvancedGestures == 0)) sc->syninfo.two_finger_scroll = 0; else sc->syninfo.two_finger_scroll = 1; /* hw.psm.synaptics.two_finger_scroll. */ SYSCTL_ADD_INT(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "two_finger_scroll", CTLFLAG_RW|CTLFLAG_ANYBODY, &sc->syninfo.two_finger_scroll, 0, "Enable two finger scrolling"); /* hw.psm.synaptics.min_pressure. */ sc->syninfo.min_pressure = 32; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "min_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MIN_PRESSURE, synaptics_sysctl, "I", "Minimum pressure required to start an action"); /* hw.psm.synaptics.max_pressure. */ sc->syninfo.max_pressure = 220; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "max_pressure", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MAX_PRESSURE, synaptics_sysctl, "I", "Maximum pressure to detect palm"); /* hw.psm.synaptics.max_width. */ sc->syninfo.max_width = 10; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "max_width", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MAX_WIDTH, synaptics_sysctl, "I", "Maximum finger width to detect palm"); /* hw.psm.synaptics.top_margin. */ sc->syninfo.margin_top = 200; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "margin_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MARGIN_TOP, synaptics_sysctl, "I", "Top margin"); /* hw.psm.synaptics.right_margin. */ sc->syninfo.margin_right = 200; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "margin_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MARGIN_RIGHT, synaptics_sysctl, "I", "Right margin"); /* hw.psm.synaptics.bottom_margin. */ sc->syninfo.margin_bottom = 200; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "margin_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MARGIN_BOTTOM, synaptics_sysctl, "I", "Bottom margin"); /* hw.psm.synaptics.left_margin. */ sc->syninfo.margin_left = 200; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "margin_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MARGIN_LEFT, synaptics_sysctl, "I", "Left margin"); /* hw.psm.synaptics.na_top. */ sc->syninfo.na_top = 1783; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "na_top", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_NA_TOP, synaptics_sysctl, "I", "Top noisy area, where weight_previous_na is used instead " "of weight_previous"); /* hw.psm.synaptics.na_right. */ sc->syninfo.na_right = 563; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "na_right", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_NA_RIGHT, synaptics_sysctl, "I", "Right noisy area, where weight_previous_na is used instead " "of weight_previous"); /* hw.psm.synaptics.na_bottom. */ sc->syninfo.na_bottom = 1408; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "na_bottom", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_NA_BOTTOM, synaptics_sysctl, "I", "Bottom noisy area, where weight_previous_na is used instead " "of weight_previous"); /* hw.psm.synaptics.na_left. */ sc->syninfo.na_left = 1600; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "na_left", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_NA_LEFT, synaptics_sysctl, "I", "Left noisy area, where weight_previous_na is used instead " "of weight_previous"); /* hw.psm.synaptics.window_min. */ sc->syninfo.window_min = 4; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "window_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_WINDOW_MIN, synaptics_sysctl, "I", "Minimum window size to start an action"); /* hw.psm.synaptics.window_max. */ sc->syninfo.window_max = 10; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "window_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_WINDOW_MAX, synaptics_sysctl, "I", "Maximum window size"); /* hw.psm.synaptics.multiplicator. */ sc->syninfo.multiplicator = 10000; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "multiplicator", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_MULTIPLICATOR, synaptics_sysctl, "I", "Multiplicator to increase precision in averages and divisions"); /* hw.psm.synaptics.weight_current. */ sc->syninfo.weight_current = 3; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "weight_current", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_WEIGHT_CURRENT, synaptics_sysctl, "I", "Weight of the current movement in the new average"); /* hw.psm.synaptics.weight_previous. */ sc->syninfo.weight_previous = 6; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "weight_previous", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS, synaptics_sysctl, "I", "Weight of the previous average"); /* hw.psm.synaptics.weight_previous_na. */ sc->syninfo.weight_previous_na = 20; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "weight_previous_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_WEIGHT_PREVIOUS_NA, synaptics_sysctl, "I", "Weight of the previous average (inside the noisy area)"); /* hw.psm.synaptics.weight_len_squared. */ sc->syninfo.weight_len_squared = 2000; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "weight_len_squared", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_WEIGHT_LEN_SQUARED, synaptics_sysctl, "I", "Length (squared) of segments where weight_previous " "starts to decrease"); /* hw.psm.synaptics.div_min. */ sc->syninfo.div_min = 9; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_DIV_MIN, synaptics_sysctl, "I", "Divisor for fast movements"); /* hw.psm.synaptics.div_max. */ sc->syninfo.div_max = 17; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_DIV_MAX, synaptics_sysctl, "I", "Divisor for slow movements"); /* hw.psm.synaptics.div_max_na. */ sc->syninfo.div_max_na = 30; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "div_max_na", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_DIV_MAX_NA, synaptics_sysctl, "I", "Divisor with slow movements (inside the noisy area)"); /* hw.psm.synaptics.div_len. */ sc->syninfo.div_len = 100; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "div_len", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_DIV_LEN, synaptics_sysctl, "I", "Length of segments where div_max starts to decrease"); /* hw.psm.synaptics.tap_max_delta. */ sc->syninfo.tap_max_delta = 80; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "tap_max_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_TAP_MAX_DELTA, synaptics_sysctl, "I", "Length of segments above which a tap is ignored"); /* hw.psm.synaptics.tap_min_queue. */ sc->syninfo.tap_min_queue = 2; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "tap_min_queue", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_TAP_MIN_QUEUE, synaptics_sysctl, "I", "Number of packets required to consider a tap"); /* hw.psm.synaptics.taphold_timeout. */ sc->gesture.in_taphold = 0; sc->syninfo.taphold_timeout = tap_timeout; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "taphold_timeout", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_TAPHOLD_TIMEOUT, synaptics_sysctl, "I", "Maximum elapsed time between two taps to consider a tap-hold " "action"); /* hw.psm.synaptics.vscroll_hor_area. */ sc->syninfo.vscroll_hor_area = 0; /* 1300 */ SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "vscroll_hor_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_VSCROLL_HOR_AREA, synaptics_sysctl, "I", "Area reserved for horizontal virtual scrolling"); /* hw.psm.synaptics.vscroll_ver_area. */ sc->syninfo.vscroll_ver_area = -400 - sc->syninfo.margin_right; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "vscroll_ver_area", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_VSCROLL_VER_AREA, synaptics_sysctl, "I", "Area reserved for vertical virtual scrolling"); /* hw.psm.synaptics.vscroll_min_delta. */ sc->syninfo.vscroll_min_delta = 50; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "vscroll_min_delta", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_VSCROLL_MIN_DELTA, synaptics_sysctl, "I", "Minimum movement to consider virtual scrolling"); /* hw.psm.synaptics.vscroll_div_min. */ sc->syninfo.vscroll_div_min = 100; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "vscroll_div_min", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_VSCROLL_DIV_MIN, synaptics_sysctl, "I", "Divisor for fast scrolling"); /* hw.psm.synaptics.vscroll_div_min. */ sc->syninfo.vscroll_div_max = 150; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "vscroll_div_max", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_VSCROLL_DIV_MAX, synaptics_sysctl, "I", "Divisor for slow scrolling"); /* hw.psm.synaptics.touchpad_off. */ sc->syninfo.touchpad_off = 0; SYSCTL_ADD_PROC(&sc->syninfo.sysctl_ctx, SYSCTL_CHILDREN(sc->syninfo.sysctl_tree), OID_AUTO, "touchpad_off", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, SYNAPTICS_SYSCTL_TOUCHPAD_OFF, synaptics_sysctl, "I", "Turn off touchpad"); sc->syninfo.softbuttons_y = 0; sc->syninfo.softbutton2_x = 0; sc->syninfo.softbutton3_x = 0; /* skip softbuttons sysctl on not clickpads */ if (sc->synhw.capClickPad) synaptics_sysctl_create_softbuttons_tree(sc); } static int synaptics_preferred_mode(struct psm_softc *sc) { int mode_byte; /* Check if we are in relative mode */ if (sc->hw.model != MOUSE_MODEL_SYNAPTICS) { if (tap_enabled == 0) /* * Disable tap & drag gestures. We use a Mode Byte * and set the DisGest bit (see §2.5 of Synaptics * TouchPad Interfacing Guide). */ return (0x04); else /* * Enable tap & drag gestures. We use a Mode Byte * and clear the DisGest bit (see §2.5 of Synaptics * TouchPad Interfacing Guide). */ return (0x00); } mode_byte = 0xc4; /* request wmode where available */ if (sc->synhw.capExtended) mode_byte |= 1; return mode_byte; } static void synaptics_set_mode(struct psm_softc *sc, int mode_byte) { mouse_ext_command(sc->kbdc, mode_byte); /* "Commit" the Set Mode Byte command sent above. */ set_mouse_sampling_rate(sc->kbdc, 20); /* * Enable advanced gestures mode if supported and we are not entering * passthrough or relative mode. */ if ((sc->synhw.capAdvancedGestures || sc->synhw.capReportsV) && sc->hw.model == MOUSE_MODEL_SYNAPTICS && !(mode_byte & (1 << 5))) { mouse_ext_command(sc->kbdc, 3); set_mouse_sampling_rate(sc->kbdc, 0xc8); } } static int enable_synaptics(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; synapticshw_t synhw; int status[3]; int buttons; VLOG(3, (LOG_DEBUG, "synaptics: BEGIN init\n")); /* * Just to be on the safe side: this avoids troubles with * following mouse_ext_command() when the previous command * was PSMC_SET_RESOLUTION. Set Scaling has no effect on * Synaptics Touchpad behaviour. */ set_mouse_scaling(kbdc, 1); /* Identify the Touchpad version. */ if (mouse_ext_command(kbdc, 0) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); if (status[1] != 0x47) return (FALSE); bzero(&synhw, sizeof(synhw)); synhw.infoMinor = status[0]; synhw.infoMajor = status[2] & 0x0f; if (verbose >= 2) printf("Synaptics Touchpad v%d.%d\n", synhw.infoMajor, synhw.infoMinor); if (synhw.infoMajor < 4) { printf(" Unsupported (pre-v4) Touchpad detected\n"); return (FALSE); } /* Get the Touchpad model information. */ if (mouse_ext_command(kbdc, 3) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); if ((status[1] & 0x01) != 0) { printf(" Failed to read model information\n"); return (FALSE); } synhw.infoRot180 = (status[0] & 0x80) != 0; synhw.infoPortrait = (status[0] & 0x40) != 0; synhw.infoSensor = status[0] & 0x3f; synhw.infoHardware = (status[1] & 0xfe) >> 1; synhw.infoNewAbs = (status[2] & 0x80) != 0; synhw.capPen = (status[2] & 0x40) != 0; synhw.infoSimplC = (status[2] & 0x20) != 0; synhw.infoGeometry = status[2] & 0x0f; if (verbose >= 2) { printf(" Model information:\n"); printf(" infoRot180: %d\n", synhw.infoRot180); printf(" infoPortrait: %d\n", synhw.infoPortrait); printf(" infoSensor: %d\n", synhw.infoSensor); printf(" infoHardware: %d\n", synhw.infoHardware); printf(" infoNewAbs: %d\n", synhw.infoNewAbs); printf(" capPen: %d\n", synhw.capPen); printf(" infoSimplC: %d\n", synhw.infoSimplC); printf(" infoGeometry: %d\n", synhw.infoGeometry); } /* Read the extended capability bits. */ if (mouse_ext_command(kbdc, 2) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != 0x47) { printf(" Failed to read extended capability bits\n"); return (FALSE); } /* Set the different capabilities when they exist. */ buttons = 0; synhw.capExtended = (status[0] & 0x80) != 0; if (synhw.capExtended) { synhw.nExtendedQueries = (status[0] & 0x70) >> 4; synhw.capMiddle = (status[0] & 0x04) != 0; synhw.capPassthrough = (status[2] & 0x80) != 0; synhw.capLowPower = (status[2] & 0x40) != 0; synhw.capMultiFingerReport = (status[2] & 0x20) != 0; synhw.capSleep = (status[2] & 0x10) != 0; synhw.capFourButtons = (status[2] & 0x08) != 0; synhw.capBallistics = (status[2] & 0x04) != 0; synhw.capMultiFinger = (status[2] & 0x02) != 0; synhw.capPalmDetect = (status[2] & 0x01) != 0; if (!set_mouse_scaling(kbdc, 1)) return (FALSE); if (mouse_ext_command(kbdc, 0x08) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); if (status[0] != 0 && (status[1] & 0x80) && status[2] != 0) { synhw.infoXupmm = status[0]; synhw.infoYupmm = status[2]; } if (verbose >= 2) { printf(" Extended capabilities:\n"); printf(" capExtended: %d\n", synhw.capExtended); printf(" capMiddle: %d\n", synhw.capMiddle); printf(" nExtendedQueries: %d\n", synhw.nExtendedQueries); printf(" capPassthrough: %d\n", synhw.capPassthrough); printf(" capLowPower: %d\n", synhw.capLowPower); printf(" capMultiFingerReport: %d\n", synhw.capMultiFingerReport); printf(" capSleep: %d\n", synhw.capSleep); printf(" capFourButtons: %d\n", synhw.capFourButtons); printf(" capBallistics: %d\n", synhw.capBallistics); printf(" capMultiFinger: %d\n", synhw.capMultiFinger); printf(" capPalmDetect: %d\n", synhw.capPalmDetect); printf(" infoXupmm: %d\n", synhw.infoXupmm); printf(" infoYupmm: %d\n", synhw.infoYupmm); } /* * If nExtendedQueries is 1 or greater, then the TouchPad * supports this number of extended queries. We can load * more information about buttons using query 0x09. */ if (synhw.nExtendedQueries >= 1) { if (!set_mouse_scaling(kbdc, 1)) return (FALSE); if (mouse_ext_command(kbdc, 0x09) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); synhw.verticalScroll = (status[0] & 0x01) != 0; synhw.horizontalScroll = (status[0] & 0x02) != 0; synhw.verticalWheel = (status[0] & 0x08) != 0; synhw.nExtendedButtons = (status[1] & 0xf0) >> 4; synhw.capEWmode = (status[0] & 0x04) != 0; if (verbose >= 2) { printf(" Extended model ID:\n"); printf(" verticalScroll: %d\n", synhw.verticalScroll); printf(" horizontalScroll: %d\n", synhw.horizontalScroll); printf(" verticalWheel: %d\n", synhw.verticalWheel); printf(" nExtendedButtons: %d\n", synhw.nExtendedButtons); printf(" capEWmode: %d\n", synhw.capEWmode); } /* * Add the number of extended buttons to the total * button support count, including the middle button * if capMiddle support bit is set. */ buttons = synhw.nExtendedButtons + synhw.capMiddle; } else /* * If the capFourButtons support bit is set, * add a fourth button to the total button count. */ buttons = synhw.capFourButtons ? 1 : 0; /* Read the continued capabilities bits. */ if (synhw.nExtendedQueries >= 4) { if (!set_mouse_scaling(kbdc, 1)) return (FALSE); if (mouse_ext_command(kbdc, 0x0c) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); synhw.capClickPad = (status[1] & 0x01) << 1; synhw.capClickPad |= (status[0] & 0x10) != 0; synhw.capDeluxeLEDs = (status[1] & 0x02) != 0; synhw.noAbsoluteFilter = (status[1] & 0x04) != 0; synhw.capReportsV = (status[1] & 0x08) != 0; synhw.capUniformClickPad = (status[1] & 0x10) != 0; synhw.capReportsMin = (status[1] & 0x20) != 0; synhw.capInterTouch = (status[1] & 0x40) != 0; synhw.capReportsMax = (status[0] & 0x02) != 0; synhw.capClearPad = (status[0] & 0x04) != 0; synhw.capAdvancedGestures = (status[0] & 0x08) != 0; synhw.capCoveredPad = (status[0] & 0x80) != 0; if (synhw.capReportsMax) { if (!set_mouse_scaling(kbdc, 1)) return (FALSE); if (mouse_ext_command(kbdc, 0x0d) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); synhw.maximumXCoord = (status[0] << 5) | ((status[1] & 0x0f) << 1); synhw.maximumYCoord = (status[2] << 5) | ((status[1] & 0xf0) >> 3); } else { /* * Typical bezel limits. Taken from 'Synaptics * PS/2 * TouchPad Interfacing Guide' p.3.2.3. */ synhw.maximumXCoord = 5472; synhw.maximumYCoord = 4448; } if (synhw.capReportsMin) { if (!set_mouse_scaling(kbdc, 1)) return (FALSE); if (mouse_ext_command(kbdc, 0x0f) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); synhw.minimumXCoord = (status[0] << 5) | ((status[1] & 0x0f) << 1); synhw.minimumYCoord = (status[2] << 5) | ((status[1] & 0xf0) >> 3); } else { /* * Typical bezel limits. Taken from 'Synaptics * PS/2 * TouchPad Interfacing Guide' p.3.2.3. */ synhw.minimumXCoord = 1472; synhw.minimumYCoord = 1408; } if (verbose >= 2) { printf(" Continued capabilities:\n"); printf(" capClickPad: %d\n", synhw.capClickPad); printf(" capDeluxeLEDs: %d\n", synhw.capDeluxeLEDs); printf(" noAbsoluteFilter: %d\n", synhw.noAbsoluteFilter); printf(" capReportsV: %d\n", synhw.capReportsV); printf(" capUniformClickPad: %d\n", synhw.capUniformClickPad); printf(" capReportsMin: %d\n", synhw.capReportsMin); printf(" capInterTouch: %d\n", synhw.capInterTouch); printf(" capReportsMax: %d\n", synhw.capReportsMax); printf(" capClearPad: %d\n", synhw.capClearPad); printf(" capAdvancedGestures: %d\n", synhw.capAdvancedGestures); printf(" capCoveredPad: %d\n", synhw.capCoveredPad); if (synhw.capReportsMax) { printf(" maximumXCoord: %d\n", synhw.maximumXCoord); printf(" maximumYCoord: %d\n", synhw.maximumYCoord); } if (synhw.capReportsMin) { printf(" minimumXCoord: %d\n", synhw.minimumXCoord); printf(" minimumYCoord: %d\n", synhw.minimumYCoord); } } buttons += synhw.capClickPad; } } if (verbose >= 2) { if (synhw.capExtended) printf(" Additional Buttons: %d\n", buttons); else printf(" No extended capabilities\n"); } /* * Add the default number of 3 buttons to the total * count of supported buttons reported above. */ buttons += 3; /* * Read the mode byte. * * XXX: Note the Synaptics documentation also defines the first * byte of the response to this query to be a constant 0x3b, this * does not appear to be true for Touchpads with guest devices. */ if (mouse_ext_command(kbdc, 1) == 0) return (FALSE); if (get_mouse_status(kbdc, status, 0, 3) != 3) return (FALSE); if (!SYNAPTICS_VERSION_GE(synhw, 7, 5) && status[1] != 0x47) { printf(" Failed to read mode byte\n"); return (FALSE); } if (arg == PROBE) sc->synhw = synhw; if (!synaptics_support) return (FALSE); /* Set mouse type just now for synaptics_set_mode() */ sc->hw.model = MOUSE_MODEL_SYNAPTICS; synaptics_set_mode(sc, synaptics_preferred_mode(sc)); if (trackpoint_support && synhw.capPassthrough) { enable_trackpoint(sc, arg); } VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n", buttons)); if (arg == PROBE) { /* Create sysctl tree. */ synaptics_sysctl_create_tree(sc, "synaptics", "Synaptics TouchPad"); sc->hw.buttons = buttons; } return (TRUE); } static void synaptics_passthrough_on(struct psm_softc *sc) { VLOG(2, (LOG_NOTICE, "psm: setting pass-through mode.\n")); synaptics_set_mode(sc, synaptics_preferred_mode(sc) | (1 << 5)); } static void synaptics_passthrough_off(struct psm_softc *sc) { VLOG(2, (LOG_NOTICE, "psm: turning pass-through mode off.\n")); set_mouse_scaling(sc->kbdc, 2); set_mouse_scaling(sc->kbdc, 1); synaptics_set_mode(sc, synaptics_preferred_mode(sc)); } /* IBM/Lenovo TrackPoint */ static int trackpoint_command(struct psm_softc *sc, int cmd, int loc, int val) { const int seq[] = { 0xe2, cmd, loc, val }; int i; if (sc->synhw.capPassthrough) synaptics_passthrough_on(sc); for (i = 0; i < nitems(seq); i++) { if (sc->synhw.capPassthrough && (seq[i] == 0xff || seq[i] == 0xe7)) if (send_aux_command(sc->kbdc, 0xe7) != PSM_ACK) { synaptics_passthrough_off(sc); return (EIO); } if (send_aux_command(sc->kbdc, seq[i]) != PSM_ACK) { if (sc->synhw.capPassthrough) synaptics_passthrough_off(sc); return (EIO); } } if (sc->synhw.capPassthrough) synaptics_passthrough_off(sc); return (0); } #define PSM_TPINFO(x) offsetof(struct psm_softc, tpinfo.x) #define TPMASK 0 #define TPLOC 1 #define TPINFO 2 static int trackpoint_sysctl(SYSCTL_HANDLER_ARGS) { static const int data[][3] = { { 0x00, 0x4a, PSM_TPINFO(sensitivity) }, { 0x00, 0x4d, PSM_TPINFO(inertia) }, { 0x00, 0x60, PSM_TPINFO(uplateau) }, { 0x00, 0x57, PSM_TPINFO(reach) }, { 0x00, 0x58, PSM_TPINFO(draghys) }, { 0x00, 0x59, PSM_TPINFO(mindrag) }, { 0x00, 0x5a, PSM_TPINFO(upthresh) }, { 0x00, 0x5c, PSM_TPINFO(threshold) }, { 0x00, 0x5d, PSM_TPINFO(jenks) }, { 0x00, 0x5e, PSM_TPINFO(ztime) }, { 0x01, 0x2c, PSM_TPINFO(pts) }, { 0x08, 0x2d, PSM_TPINFO(skipback) } }; struct psm_softc *sc; int error, newval, *oldvalp; const int *tp; if (arg1 == NULL || arg2 < 0 || arg2 >= nitems(data)) return (EINVAL); sc = arg1; tp = data[arg2]; oldvalp = (int *)((intptr_t)sc + tp[TPINFO]); newval = *oldvalp; error = sysctl_handle_int(oidp, &newval, 0, req); if (error != 0) return (error); if (newval == *oldvalp) return (0); if (newval < 0 || newval > (tp[TPMASK] == 0 ? 255 : 1)) return (EINVAL); error = trackpoint_command(sc, tp[TPMASK] == 0 ? 0x81 : 0x47, tp[TPLOC], tp[TPMASK] == 0 ? newval : tp[TPMASK]); if (error != 0) return (error); *oldvalp = newval; return (0); } static void trackpoint_sysctl_create_tree(struct psm_softc *sc) { if (sc->tpinfo.sysctl_tree != NULL) return; /* Attach extra trackpoint sysctl nodes under hw.psm.trackpoint */ sysctl_ctx_init(&sc->tpinfo.sysctl_ctx); sc->tpinfo.sysctl_tree = SYSCTL_ADD_NODE(&sc->tpinfo.sysctl_ctx, SYSCTL_STATIC_CHILDREN(_hw_psm), OID_AUTO, "trackpoint", CTLFLAG_RD, 0, "IBM/Lenovo TrackPoint"); /* hw.psm.trackpoint.sensitivity */ sc->tpinfo.sensitivity = 0x80; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "sensitivity", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_SENSITIVITY, trackpoint_sysctl, "I", "Sensitivity"); /* hw.psm.trackpoint.negative_inertia */ sc->tpinfo.inertia = 0x06; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "negative_inertia", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_NEGATIVE_INERTIA, trackpoint_sysctl, "I", "Negative inertia factor"); /* hw.psm.trackpoint.upper_plateau */ sc->tpinfo.uplateau = 0x61; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "upper_plateau", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_UPPER_PLATEAU, trackpoint_sysctl, "I", "Transfer function upper plateau speed"); /* hw.psm.trackpoint.backup_range */ sc->tpinfo.reach = 0x0a; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "backup_range", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_BACKUP_RANGE, trackpoint_sysctl, "I", "Backup range"); /* hw.psm.trackpoint.drag_hysteresis */ sc->tpinfo.draghys = 0xff; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "drag_hysteresis", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_DRAG_HYSTERESIS, trackpoint_sysctl, "I", "Drag hysteresis"); /* hw.psm.trackpoint.minimum_drag */ sc->tpinfo.mindrag = 0x14; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "minimum_drag", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_MINIMUM_DRAG, trackpoint_sysctl, "I", "Minimum drag"); /* hw.psm.trackpoint.up_threshold */ sc->tpinfo.upthresh = 0xff; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "up_threshold", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_UP_THRESHOLD, trackpoint_sysctl, "I", "Up threshold for release"); /* hw.psm.trackpoint.threshold */ sc->tpinfo.threshold = 0x08; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "threshold", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_THRESHOLD, trackpoint_sysctl, "I", "Threshold"); /* hw.psm.trackpoint.jenks_curvature */ sc->tpinfo.jenks = 0x87; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "jenks_curvature", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_JENKS_CURVATURE, trackpoint_sysctl, "I", "Jenks curvature"); /* hw.psm.trackpoint.z_time */ sc->tpinfo.ztime = 0x26; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "z_time", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_Z_TIME, trackpoint_sysctl, "I", "Z time constant"); /* hw.psm.trackpoint.press_to_select */ sc->tpinfo.pts = 0x00; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "press_to_select", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_PRESS_TO_SELECT, trackpoint_sysctl, "I", "Press to Select"); /* hw.psm.trackpoint.skip_backups */ sc->tpinfo.skipback = 0x00; SYSCTL_ADD_PROC(&sc->tpinfo.sysctl_ctx, SYSCTL_CHILDREN(sc->tpinfo.sysctl_tree), OID_AUTO, "skip_backups", CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_ANYBODY, sc, TRACKPOINT_SYSCTL_SKIP_BACKUPS, trackpoint_sysctl, "I", "Skip backups from drags"); } static void set_trackpoint_parameters(struct psm_softc *sc) { trackpoint_command(sc, 0x81, 0x4a, sc->tpinfo.sensitivity); trackpoint_command(sc, 0x81, 0x60, sc->tpinfo.uplateau); trackpoint_command(sc, 0x81, 0x4d, sc->tpinfo.inertia); trackpoint_command(sc, 0x81, 0x57, sc->tpinfo.reach); trackpoint_command(sc, 0x81, 0x58, sc->tpinfo.draghys); trackpoint_command(sc, 0x81, 0x59, sc->tpinfo.mindrag); trackpoint_command(sc, 0x81, 0x5a, sc->tpinfo.upthresh); trackpoint_command(sc, 0x81, 0x5c, sc->tpinfo.threshold); trackpoint_command(sc, 0x81, 0x5d, sc->tpinfo.jenks); trackpoint_command(sc, 0x81, 0x5e, sc->tpinfo.ztime); if (sc->tpinfo.pts == 0x01) trackpoint_command(sc, 0x47, 0x2c, 0x01); if (sc->tpinfo.skipback == 0x01) trackpoint_command(sc, 0x47, 0x2d, 0x08); } static int enable_trackpoint(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int id; /* * If called from enable_synaptics(), make sure that passthrough * mode is enabled so we can reach the trackpoint. * However, passthrough mode must be disabled before setting the * trackpoint parameters, as rackpoint_command() enables and disables * passthrough mode on its own. */ if (sc->synhw.capPassthrough) synaptics_passthrough_on(sc); if (send_aux_command(kbdc, 0xe1) != PSM_ACK || read_aux_data(kbdc) != 0x01) goto no_trackpoint; id = read_aux_data(kbdc); if (id < 0x01) goto no_trackpoint; if (arg == PROBE) sc->tphw = id; if (!trackpoint_support) goto no_trackpoint; if (sc->synhw.capPassthrough) synaptics_passthrough_off(sc); if (arg == PROBE) { trackpoint_sysctl_create_tree(sc); /* * Don't overwrite hwid and buttons when we are * a guest device. */ if (!sc->synhw.capPassthrough) { sc->hw.hwid = id; sc->hw.buttons = 3; } } set_trackpoint_parameters(sc); return (TRUE); no_trackpoint: if (sc->synhw.capPassthrough) synaptics_passthrough_off(sc); return (FALSE); } /* Interlink electronics VersaPad */ static int enable_versapad(struct psm_softc *sc, enum probearg arg) { KBDC kbdc = sc->kbdc; int data[3]; set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */ set_mouse_sampling_rate(kbdc, 100); /* set rate 100 */ set_mouse_scaling(kbdc, 1); /* set scale 1:1 */ set_mouse_scaling(kbdc, 1); /* set scale 1:1 */ set_mouse_scaling(kbdc, 1); /* set scale 1:1 */ set_mouse_scaling(kbdc, 1); /* set scale 1:1 */ if (get_mouse_status(kbdc, data, 0, 3) < 3) /* get status */ return (FALSE); if (data[2] != 0xa || data[1] != 0 ) /* rate == 0xa && res. == 0 */ return (FALSE); set_mouse_scaling(kbdc, 1); /* set scale 1:1 */ return (TRUE); /* PS/2 absolute mode */ } /* Elantech Touchpad */ static int elantech_read_1(KBDC kbdc, int hwversion, int reg, int *val) { int res, readcmd, retidx; int resp[3]; readcmd = hwversion == 2 ? ELANTECH_REG_READ : ELANTECH_REG_RDWR; retidx = hwversion == 4 ? 1 : 0; res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK; res |= send_aux_command(kbdc, readcmd) != PSM_ACK; res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK; res |= send_aux_command(kbdc, reg) != PSM_ACK; res |= get_mouse_status(kbdc, resp, 0, 3) != 3; if (res == 0) *val = resp[retidx]; return (res); } static int elantech_write_1(KBDC kbdc, int hwversion, int reg, int val) { int res, writecmd; writecmd = hwversion == 2 ? ELANTECH_REG_WRITE : ELANTECH_REG_RDWR; res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK; res |= send_aux_command(kbdc, writecmd) != PSM_ACK; res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK; res |= send_aux_command(kbdc, reg) != PSM_ACK; if (hwversion == 4) { res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK; res |= send_aux_command(kbdc, writecmd) != PSM_ACK; } res |= send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK; res |= send_aux_command(kbdc, val) != PSM_ACK; res |= set_mouse_scaling(kbdc, 1) == 0; return (res); } static int elantech_cmd(KBDC kbdc, int hwversion, int cmd, int *resp) { int res; if (hwversion == 2) { res = set_mouse_scaling(kbdc, 1) == 0; res |= mouse_ext_command(kbdc, cmd) == 0; } else { res = send_aux_command(kbdc, ELANTECH_CUSTOM_CMD) != PSM_ACK; res |= send_aux_command(kbdc, cmd) != PSM_ACK; } res |= get_mouse_status(kbdc, resp, 0, 3) != 3; return (res); } static int elantech_init(KBDC kbdc, elantechhw_t *elanhw) { int i, val, res, hwversion, reg10; /* set absolute mode */ hwversion = elanhw->hwversion; reg10 = -1; switch (hwversion) { case 2: reg10 = elanhw->fwversion == 0x020030 ? 0x54 : 0xc4; res = elantech_write_1(kbdc, hwversion, 0x10, reg10); if (res) break; res = elantech_write_1(kbdc, hwversion, 0x11, 0x8A); break; case 3: reg10 = 0x0b; res = elantech_write_1(kbdc, hwversion, 0x10, reg10); break; case 4: res = elantech_write_1(kbdc, hwversion, 0x07, 0x01); break; default: res = 1; } /* Read back reg 0x10 to ensure hardware is ready. */ if (res == 0 && reg10 >= 0) { for (i = 0; i < 5; i++) { if (elantech_read_1(kbdc, hwversion, 0x10, &val) == 0) break; DELAY(2000); } if (i == 5) res = 1; } if (res) printf("couldn't set absolute mode\n"); return (res); } static void elantech_init_synaptics(struct psm_softc *sc) { /* Set capabilites required by movement smother */ sc->synhw.infoMajor = sc->elanhw.hwversion; sc->synhw.infoMinor = sc->elanhw.fwversion; sc->synhw.infoXupmm = sc->elanhw.dpmmx; sc->synhw.infoYupmm = sc->elanhw.dpmmy; sc->synhw.verticalScroll = 0; sc->synhw.nExtendedQueries = 4; sc->synhw.capExtended = 1; sc->synhw.capPassthrough = sc->elanhw.hastrackpoint; sc->synhw.capClickPad = sc->elanhw.isclickpad; sc->synhw.capMultiFinger = 1; if (sc->elanhw.issemimt) sc->synhw.capAdvancedGestures = 1; else sc->synhw.capReportsV = 1; sc->synhw.capPalmDetect = 1; sc->synhw.capPen = 0; sc->synhw.capReportsMax = 1; sc->synhw.maximumXCoord = sc->elanhw.sizex; sc->synhw.maximumYCoord = sc->elanhw.sizey; sc->synhw.capReportsMin = 1; sc->synhw.minimumXCoord = 0; sc->synhw.minimumYCoord = 0; if (sc->syninfo.sysctl_tree == NULL) { synaptics_sysctl_create_tree(sc, "elantech", "Elantech Touchpad"); /* * Adjust synaptic smoother tunables * 1. Disable finger detection pressure threshold. Unlike * synaptics we assume the finger is acting when packet with * its X&Y arrives not when pressure exceedes some threshold * 2. Disable unrelated features like margins and noisy areas * 3. Disable virtual scroll areas as 2nd finger is preferable * 4. For clickpads set bottom quarter as 42% - 16% - 42% sized * softbuttons * 5. Scale down divisors and movement lengths by a factor of 3 * where 3 is Synaptics to Elantech (~2200/800) dpi ratio */ /* Set reporting range to be equal touchpad size */ sc->syninfo.max_x = sc->elanhw.sizex; sc->syninfo.max_y = sc->elanhw.sizey; /* Disable finger detection pressure threshold */ sc->syninfo.min_pressure = 1; /* Adjust palm width to nearly match synaptics w=10 */ sc->syninfo.max_width = 7; /* Elans often report double & triple taps as single event */ sc->syninfo.tap_min_queue = 1; /* Use full area of touchpad */ sc->syninfo.margin_top = 0; sc->syninfo.margin_right = 0; sc->syninfo.margin_bottom = 0; sc->syninfo.margin_left = 0; /* Disable noisy area */ sc->syninfo.na_top = 0; sc->syninfo.na_right = 0; sc->syninfo.na_bottom = 0; sc->syninfo.na_left = 0; /* Tune divisors and movement lengths */ sc->syninfo.weight_len_squared = 200; sc->syninfo.div_min = 3; sc->syninfo.div_max = 6; sc->syninfo.div_max_na = 10; sc->syninfo.div_len = 30; sc->syninfo.tap_max_delta = 25; /* Disable virtual scrolling areas and tune its divisors */ sc->syninfo.vscroll_hor_area = 0; sc->syninfo.vscroll_ver_area = 0; sc->syninfo.vscroll_min_delta = 15; sc->syninfo.vscroll_div_min = 30; sc->syninfo.vscroll_div_max = 50; /* Set bottom quarter as 42% - 16% - 42% sized softbuttons */ if (sc->elanhw.isclickpad) { sc->syninfo.softbuttons_y = sc->elanhw.sizey / 4; sc->syninfo.softbutton2_x = sc->elanhw.sizex * 11 / 25; sc->syninfo.softbutton3_x = sc->elanhw.sizex * 14 / 25; } } return; } static int enable_elantech(struct psm_softc *sc, enum probearg arg) { static const int ic2hw[] = /*IC: 0 1 2 3 4 5 6 7 8 9 a b c d e f */ { 0, 0, 2, 0, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0 }; static const int fw_sizes[][3] = { /* FW.vers MaxX MaxY */ { 0x020030, 1152, 768 }, { 0x020800, 1152, 768 }, { 0x020b00, 1152, 768 }, { 0x040215, 900, 500 }, { 0x040216, 819, 405 }, { 0x040219, 900, 500 }, }; elantechhw_t elanhw; int icversion, hwversion, xtr, i, id, resp[3], dpix, dpiy; KBDC kbdc = sc->kbdc; VLOG(3, (LOG_DEBUG, "elantech: BEGIN init\n")); set_mouse_scaling(kbdc, 1); set_mouse_scaling(kbdc, 1); set_mouse_scaling(kbdc, 1); if (get_mouse_status(kbdc, resp, 0, 3) != 3) return (FALSE); if (!ELANTECH_MAGIC(resp)) return (FALSE); /* Identify the Touchpad version. */ if (elantech_cmd(kbdc, 2, ELANTECH_FW_VERSION, resp)) return (FALSE); bzero(&elanhw, sizeof(elanhw)); elanhw.fwversion = (resp[0] << 16) | (resp[1] << 8) | resp[2]; icversion = resp[0] & 0x0f; hwversion = ic2hw[icversion]; if (verbose >= 2) printf("Elantech touchpad hardware v.%d firmware v.0x%06x\n", hwversion, elanhw.fwversion); if (ELANTECH_HW_IS_V1(elanhw.fwversion)) { printf (" Unsupported touchpad hardware (v1)\n"); return (FALSE); } if (hwversion == 0) { printf (" Unknown touchpad hardware (firmware v.0x%06x)\n", elanhw.fwversion); return (FALSE); } /* Get the Touchpad model information. */ elanhw.hwversion = hwversion; elanhw.issemimt = hwversion == 2; elanhw.isclickpad = (resp[1] & 0x10) != 0; elanhw.hascrc = (resp[1] & 0x40) != 0; elanhw.haspressure = elanhw.fwversion >= 0x020800; /* Read the capability bits. */ if (elantech_cmd(kbdc, hwversion, ELANTECH_CAPABILITIES, resp) != 0) { printf(" Failed to read capability bits\n"); return (FALSE); } elanhw.ntracesx = imax(resp[1], 3); elanhw.ntracesy = imax(resp[2], 3); elanhw.hastrackpoint = (resp[0] & 0x80) != 0; /* Get the touchpad resolution */ switch (hwversion) { case 4: if (elantech_cmd(kbdc, hwversion, ELANTECH_RESOLUTION, resp) == 0) { dpix = (resp[1] & 0x0f) * 10 + 790; dpiy = ((resp[1] & 0xf0) >> 4) * 10 + 790; elanhw.dpmmx = (dpix * 10 + 5) / 254; elanhw.dpmmy = (dpiy * 10 + 5) / 254; break; } /* FALLTHROUGH */ case 2: case 3: elanhw.dpmmx = elanhw.dpmmy = 32; /* 800 dpi */ break; } if (!elantech_support) return (FALSE); if (elantech_init(kbdc, &elanhw)) { printf("couldn't initialize elantech touchpad\n"); return (FALSE); } /* * Get the touchpad reporting range. * On HW v.3 touchpads it should be done after switching hardware * to real resolution mode (by setting bit 3 of reg10) */ elanhw.dptracex = elanhw.dptracey = 64; for (i = 0; i < nitems(fw_sizes); i++) { if (elanhw.fwversion == fw_sizes[i][0]) { elanhw.sizex = fw_sizes[i][1]; elanhw.sizey = fw_sizes[i][2]; goto found; } } if (elantech_cmd(kbdc, hwversion, ELANTECH_FW_ID, resp) != 0) { printf(" Failed to read touchpad size\n"); elanhw.sizex = 10000; /* Arbitrary high values to */ elanhw.sizey = 10000; /* prevent clipping in smoother */ } else if (hwversion == 2) { if ((elanhw.fwversion >> 16) == 0x14 && (resp[1] & 0x10) && !elantech_cmd(kbdc, hwversion, ELANTECH_SAMPLE, resp)) { elanhw.dptracex = resp[1] / 2; elanhw.dptracey = resp[2] / 2; } xtr = ((elanhw.fwversion >> 8) == 0x0208) ? 1 : 2; elanhw.sizex = (elanhw.ntracesx - xtr) * elanhw.dptracex; elanhw.sizey = (elanhw.ntracesy - xtr) * elanhw.dptracey; } else { elanhw.sizex = (resp[0] & 0x0f) << 8 | resp[1]; elanhw.sizey = (resp[0] & 0xf0) << 4 | resp[2]; xtr = (elanhw.sizex % (elanhw.ntracesx - 2) == 0) ? 2 : 1; elanhw.dptracex = elanhw.sizex / (elanhw.ntracesx - xtr); elanhw.dptracey = elanhw.sizey / (elanhw.ntracesy - xtr); } found: if (verbose >= 2) { printf(" Model information:\n"); printf(" MaxX: %d\n", elanhw.sizex); printf(" MaxY: %d\n", elanhw.sizey); printf(" DpmmX: %d\n", elanhw.dpmmx); printf(" DpmmY: %d\n", elanhw.dpmmy); printf(" TracesX: %d\n", elanhw.ntracesx); printf(" TracesY: %d\n", elanhw.ntracesy); printf(" DptraceX: %d\n", elanhw.dptracex); printf(" DptraceY: %d\n", elanhw.dptracey); printf(" SemiMT: %d\n", elanhw.issemimt); printf(" Clickpad: %d\n", elanhw.isclickpad); printf(" Trackpoint: %d\n", elanhw.hastrackpoint); printf(" CRC: %d\n", elanhw.hascrc); printf(" Pressure: %d\n", elanhw.haspressure); } VLOG(3, (LOG_DEBUG, "elantech: END init\n")); if (arg == PROBE) { sc->elanhw = elanhw; sc->hw.buttons = 3; /* Initialize synaptics movement smoother */ elantech_init_synaptics(sc); for (id = 0; id < ELANTECH_MAX_FINGERS; id++) PSM_FINGER_RESET(sc->elanaction.fingers[id]); } return (TRUE); } /* * Return true if 'now' is earlier than (start + (secs.usecs)). * Now may be NULL and the function will fetch the current time from * getmicrouptime(), or a cached 'now' can be passed in. * All values should be numbers derived from getmicrouptime(). */ static int timeelapsed(start, secs, usecs, now) const struct timeval *start, *now; int secs, usecs; { struct timeval snow, tv; /* if there is no 'now' passed in, the get it as a convience. */ if (now == NULL) { getmicrouptime(&snow); now = &snow; } tv.tv_sec = secs; tv.tv_usec = usecs; timevaladd(&tv, start); return (timevalcmp(&tv, now, <)); } static int psmresume(device_t dev) { struct psm_softc *sc = device_get_softc(dev); int unit = device_get_unit(dev); int err; VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit)); if ((sc->config & (PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND)) == 0) return (0); err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND); if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) { /* * Release the blocked process; it must be notified that * the device cannot be accessed anymore. */ sc->state &= ~PSM_ASLP; wakeup(sc); } VLOG(2, (LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit)); return (err); } DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0); #ifdef EVDEV_SUPPORT MODULE_DEPEND(psm, evdev, 1, 1, 1); #endif #ifdef DEV_ISA /* * This sucks up assignments from PNPBIOS and ACPI. */ /* * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may * appear BEFORE the AT keyboard controller. As the PS/2 mouse device * can be probed and attached only after the AT keyboard controller is * attached, we shall quietly reserve the IRQ resource for later use. * If the PS/2 mouse device is reported to us AFTER the keyboard controller, * copy the IRQ resource to the PS/2 mouse device instance hanging * under the keyboard controller, then probe and attach it. */ static devclass_t psmcpnp_devclass; static device_probe_t psmcpnp_probe; static device_attach_t psmcpnp_attach; static device_method_t psmcpnp_methods[] = { DEVMETHOD(device_probe, psmcpnp_probe), DEVMETHOD(device_attach, psmcpnp_attach), { 0, 0 } }; static driver_t psmcpnp_driver = { PSMCPNP_DRIVER_NAME, psmcpnp_methods, 1, /* no softc */ }; static struct isa_pnp_id psmcpnp_ids[] = { { 0x030fd041, "PS/2 mouse port" }, /* PNP0F03 */ { 0x0e0fd041, "PS/2 mouse port" }, /* PNP0F0E */ { 0x120fd041, "PS/2 mouse port" }, /* PNP0F12 */ { 0x130fd041, "PS/2 mouse port" }, /* PNP0F13 */ { 0x1303d041, "PS/2 port" }, /* PNP0313, XXX */ { 0x02002e4f, "Dell PS/2 mouse port" }, /* Lat. X200, Dell */ { 0x0002a906, "ALPS Glide Point" }, /* ALPS Glide Point */ { 0x80374d24, "IBM PS/2 mouse port" }, /* IBM3780, ThinkPad */ { 0x81374d24, "IBM PS/2 mouse port" }, /* IBM3781, ThinkPad */ { 0x0190d94d, "SONY VAIO PS/2 mouse port"}, /* SNY9001, Vaio */ { 0x0290d94d, "SONY VAIO PS/2 mouse port"}, /* SNY9002, Vaio */ { 0x0390d94d, "SONY VAIO PS/2 mouse port"}, /* SNY9003, Vaio */ { 0x0490d94d, "SONY VAIO PS/2 mouse port"}, /* SNY9004, Vaio */ { 0 } }; static int create_a_copy(device_t atkbdc, device_t me) { device_t psm; u_long irq; /* find the PS/2 mouse device instance under the keyboard controller */ psm = device_find_child(atkbdc, PSM_DRIVER_NAME, device_get_unit(atkbdc)); if (psm == NULL) return (ENXIO); if (device_get_state(psm) != DS_NOTPRESENT) return (0); /* move our resource to the found device */ irq = bus_get_resource_start(me, SYS_RES_IRQ, 0); bus_delete_resource(me, SYS_RES_IRQ, 0); bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1); /* ...then probe and attach it */ return (device_probe_and_attach(psm)); } static int psmcpnp_probe(device_t dev) { struct resource *res; u_long irq; int rid; if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids)) return (ENXIO); /* * The PnP BIOS and ACPI are supposed to assign an IRQ (12) * to the PS/2 mouse device node. But, some buggy PnP BIOS * declares the PS/2 mouse device node without an IRQ resource! * If this happens, we shall refer to device hints. * If we still don't find it there, use a hardcoded value... XXX */ rid = 0; irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid); if (irq <= 0) { if (resource_long_value(PSM_DRIVER_NAME, device_get_unit(dev),"irq", &irq) != 0) irq = 12; /* XXX */ device_printf(dev, "irq resource info is missing; " "assuming irq %ld\n", irq); bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1); } res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, 0); bus_release_resource(dev, SYS_RES_IRQ, rid, res); /* keep quiet */ if (!bootverbose) device_quiet(dev); return ((res == NULL) ? ENXIO : 0); } static int psmcpnp_attach(device_t dev) { device_t atkbdc; /* find the keyboard controller, which may be on acpi* or isa* bus */ atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME), device_get_unit(dev)); if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED)) create_a_copy(atkbdc, dev); return (0); } DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0); DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0); - +ISA_PNP_INFO(psmcpnp_ids); #endif /* DEV_ISA */ Index: head/sys/dev/sbni/if_sbni_isa.c =================================================================== --- head/sys/dev/sbni/if_sbni_isa.c (revision 328523) +++ head/sys/dev/sbni/if_sbni_isa.c (revision 328524) @@ -1,168 +1,169 @@ /*- * Copyright (c) 1997-2001 Granch, Ltd. All rights reserved. * Author: Denis I.Timofeev * * Redistributon and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice unmodified, this list of conditions, and the following * disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static int sbni_probe_isa(device_t); static int sbni_attach_isa(device_t); static device_method_t sbni_isa_methods[] = { /* Device interface */ DEVMETHOD(device_probe, sbni_probe_isa), DEVMETHOD(device_attach, sbni_attach_isa), { 0, 0 } }; static driver_t sbni_isa_driver = { "sbni", sbni_isa_methods, sizeof(struct sbni_softc) }; static devclass_t sbni_isa_devclass; static struct isa_pnp_id sbni_ids[] = { { 0, NULL } /* we have no pnp sbni cards atm. */ }; static int sbni_probe_isa(device_t dev) { struct sbni_softc *sc; int error; error = ISA_PNP_PROBE(device_get_parent(dev), dev, sbni_ids); if (error && error != ENOENT) return (error); sc = device_get_softc(dev); sc->io_res = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &sc->io_rid, SBNI_PORTS, RF_ACTIVE); if (!sc->io_res) { printf("sbni: cannot allocate io ports!\n"); return (ENOENT); } if (sbni_probe(sc) != 0) { sbni_release_resources(sc); return (ENXIO); } device_set_desc(dev, "Granch SBNI12/ISA adapter"); return (0); } static int sbni_attach_isa(device_t dev) { struct sbni_softc *sc; struct sbni_flags flags; int error; sc = device_get_softc(dev); sc->dev = dev; sc->irq_res = bus_alloc_resource_any( dev, SYS_RES_IRQ, &sc->irq_rid, RF_ACTIVE); #ifndef SBNI_DUAL_COMPOUND if (sc->irq_res == NULL) { device_printf(dev, "irq conflict!\n"); sbni_release_resources(sc); return (ENOENT); } #else /* SBNI_DUAL_COMPOUND */ if (sc->irq_res) { sbni_add(sc); } else { struct sbni_softc *master; if ((master = connect_to_master(sc)) == NULL) { device_printf(dev, "failed to alloc irq\n"); sbni_release_resources(sc); return (ENXIO); } else { device_printf(dev, "shared irq with %s\n", master->ifp->if_xname); } } #endif /* SBNI_DUAL_COMPOUND */ *(u_int32_t*)&flags = device_get_flags(dev); error = sbni_attach(sc, device_get_unit(dev) * 2, flags); if (error) { device_printf(dev, "cannot initialize driver\n"); sbni_release_resources(sc); return (error); } if (sc->irq_res) { error = bus_setup_intr( dev, sc->irq_res, INTR_TYPE_NET | INTR_MPSAFE, NULL, sbni_intr, sc, &sc->irq_handle); if (error) { device_printf(dev, "bus_setup_intr\n"); sbni_detach(sc); sbni_release_resources(sc); return (error); } } return (0); } DRIVER_MODULE(sbni, isa, sbni_isa_driver, sbni_isa_devclass, 0, 0); MODULE_DEPEND(sbni, isa, 1, 1, 1); +ISA_PNP_INFO(sbni_ids); Index: head/sys/dev/sound/isa/ess.c =================================================================== --- head/sys/dev/sound/isa/ess.c (revision 328523) +++ head/sys/dev/sound/isa/ess.c (revision 328524) @@ -1,1018 +1,1019 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1999 Cameron Grant * Copyright (c) 1997,1998 Luigi Rizzo * * Derived from files in the Voxware 3.5 distribution, * Copyright by Hannu Savolainen 1994, under the same copyright * conditions. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" #endif #include #include #include #include #include "mixer_if.h" SND_DECLARE_FILE("$FreeBSD$"); #define ESS_BUFFSIZE (4096) #define ABS(x) (((x) < 0)? -(x) : (x)) /* audio2 never generates irqs and sounds very noisy */ #undef ESS18XX_DUPLEX /* more accurate clocks and split audio1/audio2 rates */ #define ESS18XX_NEWSPEED static u_int32_t ess_pfmt[] = { SND_FORMAT(AFMT_U8, 1, 0), SND_FORMAT(AFMT_U8, 2, 0), SND_FORMAT(AFMT_S8, 1, 0), SND_FORMAT(AFMT_S8, 2, 0), SND_FORMAT(AFMT_S16_LE, 1, 0), SND_FORMAT(AFMT_S16_LE, 2, 0), SND_FORMAT(AFMT_U16_LE, 1, 0), SND_FORMAT(AFMT_U16_LE, 2, 0), 0 }; static struct pcmchan_caps ess_playcaps = {6000, 48000, ess_pfmt, 0}; static u_int32_t ess_rfmt[] = { SND_FORMAT(AFMT_U8, 1, 0), SND_FORMAT(AFMT_U8, 2, 0), SND_FORMAT(AFMT_S8, 1, 0), SND_FORMAT(AFMT_S8, 2, 0), SND_FORMAT(AFMT_S16_LE, 1, 0), SND_FORMAT(AFMT_S16_LE, 2, 0), SND_FORMAT(AFMT_U16_LE, 1, 0), SND_FORMAT(AFMT_U16_LE, 2, 0), 0 }; static struct pcmchan_caps ess_reccaps = {6000, 48000, ess_rfmt, 0}; struct ess_info; struct ess_chinfo { struct ess_info *parent; struct pcm_channel *channel; struct snd_dbuf *buffer; int dir, hwch, stopping, run; u_int32_t fmt, spd, blksz; }; struct ess_info { device_t parent_dev; struct resource *io_base; /* I/O address for the board */ struct resource *irq; struct resource *drq1; struct resource *drq2; void *ih; bus_dma_tag_t parent_dmat; unsigned int bufsize; int type; unsigned int duplex:1, newspeed:1; u_long bd_flags; /* board-specific flags */ struct ess_chinfo pch, rch; }; #if 0 static int ess_rd(struct ess_info *sc, int reg); static void ess_wr(struct ess_info *sc, int reg, u_int8_t val); static int ess_dspready(struct ess_info *sc); static int ess_cmd(struct ess_info *sc, u_char val); static int ess_cmd1(struct ess_info *sc, u_char cmd, int val); static int ess_get_byte(struct ess_info *sc); static void ess_setmixer(struct ess_info *sc, u_int port, u_int value); static int ess_getmixer(struct ess_info *sc, u_int port); static int ess_reset_dsp(struct ess_info *sc); static int ess_write(struct ess_info *sc, u_char reg, int val); static int ess_read(struct ess_info *sc, u_char reg); static void ess_intr(void *arg); static int ess_setupch(struct ess_info *sc, int ch, int dir, int spd, u_int32_t fmt, int len); static int ess_start(struct ess_chinfo *ch); static int ess_stop(struct ess_chinfo *ch); #endif /* * Common code for the midi and pcm functions * * ess_cmd write a single byte to the CMD port. * ess_cmd1 write a CMD + 1 byte arg * ess_cmd2 write a CMD + 2 byte arg * ess_get_byte returns a single byte from the DSP data port * * ess_write is actually ess_cmd1 * ess_read access ext. regs via ess_cmd(0xc0, reg) followed by ess_get_byte */ static void ess_lock(struct ess_info *sc) { sbc_lock(device_get_softc(sc->parent_dev)); } static void ess_unlock(struct ess_info *sc) { sbc_unlock(device_get_softc(sc->parent_dev)); } static int port_rd(struct resource *port, int off) { return bus_space_read_1(rman_get_bustag(port), rman_get_bushandle(port), off); } static void port_wr(struct resource *port, int off, u_int8_t data) { bus_space_write_1(rman_get_bustag(port), rman_get_bushandle(port), off, data); } static int ess_rd(struct ess_info *sc, int reg) { return port_rd(sc->io_base, reg); } static void ess_wr(struct ess_info *sc, int reg, u_int8_t val) { port_wr(sc->io_base, reg, val); } static int ess_dspready(struct ess_info *sc) { return ((ess_rd(sc, SBDSP_STATUS) & 0x80) == 0); } static int ess_dspwr(struct ess_info *sc, u_char val) { int i; for (i = 0; i < 1000; i++) { if (ess_dspready(sc)) { ess_wr(sc, SBDSP_CMD, val); return 1; } if (i > 10) DELAY((i > 100)? 1000 : 10); } printf("ess_dspwr(0x%02x) timed out.\n", val); return 0; } static int ess_cmd(struct ess_info *sc, u_char val) { #if 0 printf("ess_cmd: %x\n", val); #endif return ess_dspwr(sc, val); } static int ess_cmd1(struct ess_info *sc, u_char cmd, int val) { #if 0 printf("ess_cmd1: %x, %x\n", cmd, val); #endif if (ess_dspwr(sc, cmd)) { return ess_dspwr(sc, val & 0xff); } else return 0; } static void ess_setmixer(struct ess_info *sc, u_int port, u_int value) { DEB(printf("ess_setmixer: reg=%x, val=%x\n", port, value);) ess_wr(sc, SB_MIX_ADDR, (u_char) (port & 0xff)); /* Select register */ DELAY(10); ess_wr(sc, SB_MIX_DATA, (u_char) (value & 0xff)); DELAY(10); } static int ess_getmixer(struct ess_info *sc, u_int port) { int val; ess_wr(sc, SB_MIX_ADDR, (u_char) (port & 0xff)); /* Select register */ DELAY(10); val = ess_rd(sc, SB_MIX_DATA); DELAY(10); return val; } static int ess_get_byte(struct ess_info *sc) { int i; for (i = 1000; i > 0; i--) { if (ess_rd(sc, DSP_DATA_AVAIL) & 0x80) return ess_rd(sc, DSP_READ); else DELAY(20); } return -1; } static int ess_write(struct ess_info *sc, u_char reg, int val) { return ess_cmd1(sc, reg, val); } static int ess_read(struct ess_info *sc, u_char reg) { return (ess_cmd(sc, 0xc0) && ess_cmd(sc, reg))? ess_get_byte(sc) : -1; } static int ess_reset_dsp(struct ess_info *sc) { ess_wr(sc, SBDSP_RST, 3); DELAY(100); ess_wr(sc, SBDSP_RST, 0); if (ess_get_byte(sc) != 0xAA) { DEB(printf("ess_reset_dsp 0x%lx failed\n", rman_get_start(sc->io_base))); return ENXIO; /* Sorry */ } ess_cmd(sc, 0xc6); return 0; } static void ess_release_resources(struct ess_info *sc, device_t dev) { if (sc->irq) { if (sc->ih) bus_teardown_intr(dev, sc->irq, sc->ih); bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq); sc->irq = NULL; } if (sc->drq1) { isa_dma_release(rman_get_start(sc->drq1)); bus_release_resource(dev, SYS_RES_DRQ, 0, sc->drq1); sc->drq1 = NULL; } if (sc->drq2) { isa_dma_release(rman_get_start(sc->drq2)); bus_release_resource(dev, SYS_RES_DRQ, 1, sc->drq2); sc->drq2 = NULL; } if (sc->io_base) { bus_release_resource(dev, SYS_RES_IOPORT, 0, sc->io_base); sc->io_base = NULL; } if (sc->parent_dmat) { bus_dma_tag_destroy(sc->parent_dmat); sc->parent_dmat = 0; } free(sc, M_DEVBUF); } static int ess_alloc_resources(struct ess_info *sc, device_t dev) { int rid; rid = 0; if (!sc->io_base) sc->io_base = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid, RF_ACTIVE); rid = 0; if (!sc->irq) sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE); rid = 0; if (!sc->drq1) sc->drq1 = bus_alloc_resource_any(dev, SYS_RES_DRQ, &rid, RF_ACTIVE); rid = 1; if (!sc->drq2) sc->drq2 = bus_alloc_resource_any(dev, SYS_RES_DRQ, &rid, RF_ACTIVE); if (sc->io_base && sc->drq1 && sc->irq) { isa_dma_acquire(rman_get_start(sc->drq1)); isa_dmainit(rman_get_start(sc->drq1), sc->bufsize); if (sc->drq2) { isa_dma_acquire(rman_get_start(sc->drq2)); isa_dmainit(rman_get_start(sc->drq2), sc->bufsize); } return 0; } else return ENXIO; } static void ess_intr(void *arg) { struct ess_info *sc = (struct ess_info *)arg; int src, pirq, rirq; ess_lock(sc); src = 0; if (ess_getmixer(sc, 0x7a) & 0x80) src |= 2; if (ess_rd(sc, 0x0c) & 0x01) src |= 1; pirq = (src & sc->pch.hwch)? 1 : 0; rirq = (src & sc->rch.hwch)? 1 : 0; if (pirq) { if (sc->pch.run) { ess_unlock(sc); chn_intr(sc->pch.channel); ess_lock(sc); } if (sc->pch.stopping) { sc->pch.run = 0; sndbuf_dma(sc->pch.buffer, PCMTRIG_STOP); sc->pch.stopping = 0; if (sc->pch.hwch == 1) ess_write(sc, 0xb8, ess_read(sc, 0xb8) & ~0x01); else ess_setmixer(sc, 0x78, ess_getmixer(sc, 0x78) & ~0x03); } } if (rirq) { if (sc->rch.run) { ess_unlock(sc); chn_intr(sc->rch.channel); ess_lock(sc); } if (sc->rch.stopping) { sc->rch.run = 0; sndbuf_dma(sc->rch.buffer, PCMTRIG_STOP); sc->rch.stopping = 0; /* XXX: will this stop audio2? */ ess_write(sc, 0xb8, ess_read(sc, 0xb8) & ~0x01); } } if (src & 2) ess_setmixer(sc, 0x7a, ess_getmixer(sc, 0x7a) & ~0x80); if (src & 1) ess_rd(sc, DSP_DATA_AVAIL); ess_unlock(sc); } /* utility functions for ESS */ static u_int8_t ess_calcspeed8(int *spd) { int speed = *spd; u_int32_t t; if (speed > 22000) { t = (795500 + speed / 2) / speed; speed = (795500 + t / 2) / t; t = (256 - t) | 0x80; } else { t = (397700 + speed / 2) / speed; speed = (397700 + t / 2) / t; t = 128 - t; } *spd = speed; return t & 0x000000ff; } static u_int8_t ess_calcspeed9(int *spd) { int speed, s0, s1, use0; u_int8_t t0, t1; /* rate = source / (256 - divisor) */ /* divisor = 256 - (source / rate) */ speed = *spd; t0 = 128 - (793800 / speed); s0 = 793800 / (128 - t0); t1 = 128 - (768000 / speed); s1 = 768000 / (128 - t1); t1 |= 0x80; use0 = (ABS(speed - s0) < ABS(speed - s1))? 1 : 0; *spd = use0? s0 : s1; return use0? t0 : t1; } static u_int8_t ess_calcfilter(int spd) { int cutoff; /* cutoff = 7160000 / (256 - divisor) */ /* divisor = 256 - (7160000 / cutoff) */ cutoff = (spd * 9 * 82) / 20; return (256 - (7160000 / cutoff)); } static int ess_setupch(struct ess_info *sc, int ch, int dir, int spd, u_int32_t fmt, int len) { int play = (dir == PCMDIR_PLAY)? 1 : 0; int b16 = (fmt & AFMT_16BIT)? 1 : 0; int stereo = (AFMT_CHANNEL(fmt) > 1)? 1 : 0; int unsign = (fmt == AFMT_U8 || fmt == AFMT_U16_LE)? 1 : 0; u_int8_t spdval, fmtval; spdval = (sc->newspeed)? ess_calcspeed9(&spd) : ess_calcspeed8(&spd); len = -len; if (ch == 1) { KASSERT((dir == PCMDIR_PLAY) || (dir == PCMDIR_REC), ("ess_setupch: dir1 bad")); /* transfer length low */ ess_write(sc, 0xa4, len & 0x00ff); /* transfer length high */ ess_write(sc, 0xa5, (len & 0xff00) >> 8); /* autoinit, dma dir */ ess_write(sc, 0xb8, 0x04 | (play? 0x00 : 0x0a)); /* mono/stereo */ ess_write(sc, 0xa8, (ess_read(sc, 0xa8) & ~0x03) | (stereo? 0x01 : 0x02)); /* demand mode, 4 bytes/xfer */ ess_write(sc, 0xb9, 0x02); /* sample rate */ ess_write(sc, 0xa1, spdval); /* filter cutoff */ ess_write(sc, 0xa2, ess_calcfilter(spd)); /* setup dac/adc */ if (play) ess_write(sc, 0xb6, unsign? 0x80 : 0x00); /* mono, b16: signed, load signal */ ess_write(sc, 0xb7, 0x51 | (unsign? 0x00 : 0x20)); /* setup fifo */ ess_write(sc, 0xb7, 0x90 | (unsign? 0x00 : 0x20) | (b16? 0x04 : 0x00) | (stereo? 0x08 : 0x40)); /* irq control */ ess_write(sc, 0xb1, (ess_read(sc, 0xb1) & 0x0f) | 0x50); /* drq control */ ess_write(sc, 0xb2, (ess_read(sc, 0xb2) & 0x0f) | 0x50); } else if (ch == 2) { KASSERT(dir == PCMDIR_PLAY, ("ess_setupch: dir2 bad")); /* transfer length low */ ess_setmixer(sc, 0x74, len & 0x00ff); /* transfer length high */ ess_setmixer(sc, 0x76, (len & 0xff00) >> 8); /* autoinit, 4 bytes/req */ ess_setmixer(sc, 0x78, 0x90); fmtval = b16 | (stereo << 1) | (unsign << 2); /* enable irq, set format */ ess_setmixer(sc, 0x7a, 0x40 | fmtval); if (sc->newspeed) { /* sample rate */ ess_setmixer(sc, 0x70, spdval); /* filter cutoff */ ess_setmixer(sc, 0x72, ess_calcfilter(spd)); } } return 0; } static int ess_start(struct ess_chinfo *ch) { struct ess_info *sc = ch->parent; int play = (ch->dir == PCMDIR_PLAY)? 1 : 0; ess_lock(sc); ess_setupch(sc, ch->hwch, ch->dir, ch->spd, ch->fmt, ch->blksz); ch->stopping = 0; if (ch->hwch == 1) ess_write(sc, 0xb8, ess_read(sc, 0xb8) | 0x01); else ess_setmixer(sc, 0x78, ess_getmixer(sc, 0x78) | 0x03); if (play) ess_cmd(sc, DSP_CMD_SPKON); ess_unlock(sc); return 0; } static int ess_stop(struct ess_chinfo *ch) { struct ess_info *sc = ch->parent; int play = (ch->dir == PCMDIR_PLAY)? 1 : 0; ess_lock(sc); ch->stopping = 1; if (ch->hwch == 1) ess_write(sc, 0xb8, ess_read(sc, 0xb8) & ~0x04); else ess_setmixer(sc, 0x78, ess_getmixer(sc, 0x78) & ~0x10); if (play) ess_cmd(sc, DSP_CMD_SPKOFF); ess_unlock(sc); return 0; } /* -------------------------------------------------------------------- */ /* channel interface for ESS18xx */ static void * esschan_init(kobj_t obj, void *devinfo, struct snd_dbuf *b, struct pcm_channel *c, int dir) { struct ess_info *sc = devinfo; struct ess_chinfo *ch = (dir == PCMDIR_PLAY)? &sc->pch : &sc->rch; ch->parent = sc; ch->channel = c; ch->buffer = b; if (sndbuf_alloc(ch->buffer, sc->parent_dmat, 0, sc->bufsize) != 0) return NULL; ch->dir = dir; ch->hwch = 1; if ((dir == PCMDIR_PLAY) && (sc->duplex)) ch->hwch = 2; sndbuf_dmasetup(ch->buffer, (ch->hwch == 1)? sc->drq1 : sc->drq2); return ch; } static int esschan_setformat(kobj_t obj, void *data, u_int32_t format) { struct ess_chinfo *ch = data; ch->fmt = format; return 0; } static u_int32_t esschan_setspeed(kobj_t obj, void *data, u_int32_t speed) { struct ess_chinfo *ch = data; struct ess_info *sc = ch->parent; ch->spd = speed; if (sc->newspeed) ess_calcspeed9(&ch->spd); else ess_calcspeed8(&ch->spd); return ch->spd; } static u_int32_t esschan_setblocksize(kobj_t obj, void *data, u_int32_t blocksize) { struct ess_chinfo *ch = data; ch->blksz = blocksize; return ch->blksz; } static int esschan_trigger(kobj_t obj, void *data, int go) { struct ess_chinfo *ch = data; if (!PCMTRIG_COMMON(go)) return 0; switch (go) { case PCMTRIG_START: ch->run = 1; sndbuf_dma(ch->buffer, go); ess_start(ch); break; case PCMTRIG_STOP: case PCMTRIG_ABORT: default: ess_stop(ch); break; } return 0; } static u_int32_t esschan_getptr(kobj_t obj, void *data) { struct ess_chinfo *ch = data; return sndbuf_dmaptr(ch->buffer); } static struct pcmchan_caps * esschan_getcaps(kobj_t obj, void *data) { struct ess_chinfo *ch = data; return (ch->dir == PCMDIR_PLAY)? &ess_playcaps : &ess_reccaps; } static kobj_method_t esschan_methods[] = { KOBJMETHOD(channel_init, esschan_init), KOBJMETHOD(channel_setformat, esschan_setformat), KOBJMETHOD(channel_setspeed, esschan_setspeed), KOBJMETHOD(channel_setblocksize, esschan_setblocksize), KOBJMETHOD(channel_trigger, esschan_trigger), KOBJMETHOD(channel_getptr, esschan_getptr), KOBJMETHOD(channel_getcaps, esschan_getcaps), KOBJMETHOD_END }; CHANNEL_DECLARE(esschan); /************************************************************/ static int essmix_init(struct snd_mixer *m) { struct ess_info *sc = mix_getdevinfo(m); mix_setrecdevs(m, SOUND_MASK_CD | SOUND_MASK_MIC | SOUND_MASK_LINE | SOUND_MASK_IMIX); mix_setdevs(m, SOUND_MASK_SYNTH | SOUND_MASK_PCM | SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD | SOUND_MASK_VOLUME | SOUND_MASK_LINE1 | SOUND_MASK_SPEAKER); ess_setmixer(sc, 0, 0); /* reset */ return 0; } static int essmix_set(struct snd_mixer *m, unsigned dev, unsigned left, unsigned right) { struct ess_info *sc = mix_getdevinfo(m); int preg = 0, rreg = 0, l, r; l = (left * 15) / 100; r = (right * 15) / 100; switch (dev) { case SOUND_MIXER_SYNTH: preg = 0x36; rreg = 0x6b; break; case SOUND_MIXER_PCM: preg = 0x14; rreg = 0x7c; break; case SOUND_MIXER_LINE: preg = 0x3e; rreg = 0x6e; break; case SOUND_MIXER_MIC: preg = 0x1a; rreg = 0x68; break; case SOUND_MIXER_LINE1: preg = 0x3a; rreg = 0x6c; break; case SOUND_MIXER_CD: preg = 0x38; rreg = 0x6a; break; case SOUND_MIXER_SPEAKER: preg = 0x3c; break; case SOUND_MIXER_VOLUME: l = left? (left * 63) / 100 : 64; r = right? (right * 63) / 100 : 64; ess_setmixer(sc, 0x60, l); ess_setmixer(sc, 0x62, r); left = (l == 64)? 0 : (l * 100) / 63; right = (r == 64)? 0 : (r * 100) / 63; return left | (right << 8); } if (preg) ess_setmixer(sc, preg, (l << 4) | r); if (rreg) ess_setmixer(sc, rreg, (l << 4) | r); left = (l * 100) / 15; right = (r * 100) / 15; return left | (right << 8); } static u_int32_t essmix_setrecsrc(struct snd_mixer *m, u_int32_t src) { struct ess_info *sc = mix_getdevinfo(m); u_char recdev; switch (src) { case SOUND_MASK_CD: recdev = 0x02; break; case SOUND_MASK_LINE: recdev = 0x06; break; case SOUND_MASK_IMIX: recdev = 0x05; break; case SOUND_MASK_MIC: default: recdev = 0x00; src = SOUND_MASK_MIC; break; } ess_setmixer(sc, 0x1c, recdev); return src; } static kobj_method_t essmixer_methods[] = { KOBJMETHOD(mixer_init, essmix_init), KOBJMETHOD(mixer_set, essmix_set), KOBJMETHOD(mixer_setrecsrc, essmix_setrecsrc), KOBJMETHOD_END }; MIXER_DECLARE(essmixer); /************************************************************/ static int ess_probe(device_t dev) { uintptr_t func, ver, r, f; /* The parent device has already been probed. */ r = BUS_READ_IVAR(device_get_parent(dev), dev, 0, &func); if (func != SCF_PCM) return (ENXIO); r = BUS_READ_IVAR(device_get_parent(dev), dev, 1, &ver); f = (ver & 0xffff0000) >> 16; if (!(f & BD_F_ESS)) return (ENXIO); device_set_desc(dev, "ESS 18xx DSP"); return 0; } static int ess_attach(device_t dev) { struct ess_info *sc; char status[SND_STATUSLEN], buf[64]; int ver; sc = malloc(sizeof(*sc), M_DEVBUF, M_WAITOK | M_ZERO); sc->parent_dev = device_get_parent(dev); sc->bufsize = pcm_getbuffersize(dev, 4096, ESS_BUFFSIZE, 65536); if (ess_alloc_resources(sc, dev)) goto no; if (ess_reset_dsp(sc)) goto no; if (mixer_init(dev, &essmixer_class, sc)) goto no; sc->duplex = 0; sc->newspeed = 0; ver = (ess_getmixer(sc, 0x40) << 8) | ess_rd(sc, SB_MIX_DATA); snprintf(buf, sizeof buf, "ESS %x DSP", ver); device_set_desc_copy(dev, buf); if (bootverbose) device_printf(dev, "ESS%x detected", ver); switch (ver) { case 0x1869: case 0x1879: #ifdef ESS18XX_DUPLEX sc->duplex = sc->drq2? 1 : 0; #endif #ifdef ESS18XX_NEWSPEED sc->newspeed = 1; #endif break; } if (bootverbose) printf("%s%s\n", sc->duplex? ", duplex" : "", sc->newspeed? ", newspeed" : ""); if (sc->newspeed) ess_setmixer(sc, 0x71, 0x22); snd_setup_intr(dev, sc->irq, 0, ess_intr, sc, &sc->ih); if (!sc->duplex) pcm_setflags(dev, pcm_getflags(dev) | SD_F_SIMPLEX); if (bus_dma_tag_create(/*parent*/bus_get_dma_tag(dev), /*alignment*/2, /*boundary*/0, /*lowaddr*/BUS_SPACE_MAXADDR_24BIT, /*highaddr*/BUS_SPACE_MAXADDR, /*filter*/NULL, /*filterarg*/NULL, /*maxsize*/sc->bufsize, /*nsegments*/1, /*maxsegz*/0x3ffff, /*flags*/0, /*lockfunc*/busdma_lock_mutex, /*lockarg*/&Giant, &sc->parent_dmat) != 0) { device_printf(dev, "unable to create dma tag\n"); goto no; } if (sc->drq2) snprintf(buf, SND_STATUSLEN, ":%jd", rman_get_start(sc->drq2)); else buf[0] = '\0'; snprintf(status, SND_STATUSLEN, "at io 0x%jx irq %jd drq %jd%s bufsz %u %s", rman_get_start(sc->io_base), rman_get_start(sc->irq), rman_get_start(sc->drq1), buf, sc->bufsize, PCM_KLDSTRING(snd_ess)); if (pcm_register(dev, sc, 1, 1)) goto no; pcm_addchan(dev, PCMDIR_REC, &esschan_class, sc); pcm_addchan(dev, PCMDIR_PLAY, &esschan_class, sc); pcm_setstatus(dev, status); return 0; no: ess_release_resources(sc, dev); return ENXIO; } static int ess_detach(device_t dev) { int r; struct ess_info *sc; r = pcm_unregister(dev); if (r) return r; sc = pcm_getdevinfo(dev); ess_release_resources(sc, dev); return 0; } static int ess_resume(device_t dev) { struct ess_info *sc; sc = pcm_getdevinfo(dev); if (ess_reset_dsp(sc)) { device_printf(dev, "unable to reset DSP at resume\n"); return ENXIO; } if (mixer_reinit(dev)) { device_printf(dev, "unable to reinitialize mixer at resume\n"); return ENXIO; } return 0; } static device_method_t ess_methods[] = { /* Device interface */ DEVMETHOD(device_probe, ess_probe), DEVMETHOD(device_attach, ess_attach), DEVMETHOD(device_detach, ess_detach), DEVMETHOD(device_resume, ess_resume), { 0, 0 } }; static driver_t ess_driver = { "pcm", ess_methods, PCM_SOFTC_SIZE, }; DRIVER_MODULE(snd_ess, sbc, ess_driver, pcm_devclass, 0, 0); MODULE_DEPEND(snd_ess, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_DEPEND(snd_ess, snd_sbc, 1, 1, 1); MODULE_VERSION(snd_ess, 1); /************************************************************/ static devclass_t esscontrol_devclass; static struct isa_pnp_id essc_ids[] = { {0x06007316, "ESS Control"}, {0} }; static int esscontrol_probe(device_t dev) { int i; i = ISA_PNP_PROBE(device_get_parent(dev), dev, essc_ids); if (i == 0) device_quiet(dev); return i; } static int esscontrol_attach(device_t dev) { #ifdef notyet struct resource *io; int rid, i, x; rid = 0; io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid, RF_ACTIVE); x = 0; for (i = 0; i < 0x100; i++) { port_wr(io, 0, i); x = port_rd(io, 1); if ((i & 0x0f) == 0) printf("%3.3x: ", i); printf("%2.2x ", x); if ((i & 0x0f) == 0x0f) printf("\n"); } bus_release_resource(dev, SYS_RES_IOPORT, 0, io); io = NULL; #endif return 0; } static int esscontrol_detach(device_t dev) { return 0; } static device_method_t esscontrol_methods[] = { /* Device interface */ DEVMETHOD(device_probe, esscontrol_probe), DEVMETHOD(device_attach, esscontrol_attach), DEVMETHOD(device_detach, esscontrol_detach), { 0, 0 } }; static driver_t esscontrol_driver = { "esscontrol", esscontrol_methods, 1, }; DRIVER_MODULE(esscontrol, isa, esscontrol_driver, esscontrol_devclass, 0, 0); DRIVER_MODULE(esscontrol, acpi, esscontrol_driver, esscontrol_devclass, 0, 0); +ISA_PNP_INFO(essc_ids); Index: head/sys/dev/sound/isa/gusc.c =================================================================== --- head/sys/dev/sound/isa/gusc.c (revision 328523) +++ head/sys/dev/sound/isa/gusc.c (revision 328524) @@ -1,677 +1,676 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1999 Seigo Tanimura * Copyright (c) 1999 Ville-Pertti Keinonen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" #endif #include #include #include "bus_if.h" #include #include SND_DECLARE_FILE("$FreeBSD$"); #define LOGICALID_NOPNP 0 #define LOGICALID_PCM 0x0000561e #define LOGICALID_OPL 0x0300561e #define LOGICALID_MIDI 0x0400561e /* PnP IDs */ static struct isa_pnp_id gusc_ids[] = { {LOGICALID_PCM, "GRV0000 Gravis UltraSound PnP PCM"}, /* GRV0000 */ {LOGICALID_OPL, "GRV0003 Gravis UltraSound PnP OPL"}, /* GRV0003 */ {LOGICALID_MIDI, "GRV0004 Gravis UltraSound PnP MIDI"}, /* GRV0004 */ }; /* Interrupt handler. */ struct gusc_ihandler { void (*intr)(void *); void *arg; }; /* Here is the parameter structure per a device. */ struct gusc_softc { device_t dev; /* device */ int io_rid[3]; /* io port rids */ struct resource *io[3]; /* io port resources */ int io_alloced[3]; /* io port alloc flag */ int irq_rid; /* irq rids */ struct resource *irq; /* irq resources */ int irq_alloced; /* irq alloc flag */ int drq_rid[2]; /* drq rids */ struct resource *drq[2]; /* drq resources */ int drq_alloced[2]; /* drq alloc flag */ /* Interrupts are shared (XXX non-PnP only?) */ struct gusc_ihandler midi_intr; struct gusc_ihandler pcm_intr; }; typedef struct gusc_softc *sc_p; static int gusc_probe(device_t dev); static int gusc_attach(device_t dev); static int gusisa_probe(device_t dev); static void gusc_intr(void *); static struct resource *gusc_alloc_resource(device_t bus, device_t child, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags); static int gusc_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r); static device_t find_masterdev(sc_p scp); static int alloc_resource(sc_p scp); static int release_resource(sc_p scp); static devclass_t gusc_devclass; static int gusc_probe(device_t dev) { device_t child; u_int32_t logical_id; char *s; struct sndcard_func *func; int ret; logical_id = isa_get_logicalid(dev); s = NULL; /* Check isapnp ids */ if (logical_id != 0 && (ret = ISA_PNP_PROBE(device_get_parent(dev), dev, gusc_ids)) != 0) return (ret); else { if (logical_id == 0) return gusisa_probe(dev); } switch (logical_id) { case LOGICALID_PCM: s = "Gravis UltraSound Plug & Play PCM"; func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) return (ENOMEM); func->func = SCF_PCM; child = device_add_child(dev, "pcm", -1); device_set_ivars(child, func); break; case LOGICALID_OPL: s = "Gravis UltraSound Plug & Play OPL"; func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) return (ENOMEM); func->func = SCF_SYNTH; child = device_add_child(dev, "midi", -1); device_set_ivars(child, func); break; case LOGICALID_MIDI: s = "Gravis UltraSound Plug & Play MIDI"; func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) return (ENOMEM); func->func = SCF_MIDI; child = device_add_child(dev, "midi", -1); device_set_ivars(child, func); break; } if (s != NULL) { device_set_desc(dev, s); return (0); } return (ENXIO); } static void port_wr(struct resource *r, int i, unsigned char v) { bus_space_write_1(rman_get_bustag(r), rman_get_bushandle(r), i, v); } static int port_rd(struct resource *r, int i) { return bus_space_read_1(rman_get_bustag(r), rman_get_bushandle(r), i); } /* * Probe for an old (non-PnP) GUS card on the ISA bus. */ static int gusisa_probe(device_t dev) { device_t child; struct resource *res, *res2; int base, rid, rid2, s, flags; unsigned char val; base = isa_get_port(dev); flags = device_get_flags(dev); rid = 1; res = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid, base + 0x100, base + 0x107, 8, RF_ACTIVE); if (res == NULL) return ENXIO; res2 = NULL; /* * Check for the presence of some GUS card. Reset the card, * then see if we can access the memory on it. */ port_wr(res, 3, 0x4c); port_wr(res, 5, 0); DELAY(30 * 1000); port_wr(res, 3, 0x4c); port_wr(res, 5, 1); DELAY(30 * 1000); s = splhigh(); /* Write to DRAM. */ port_wr(res, 3, 0x43); /* Register select */ port_wr(res, 4, 0); /* Low addr */ port_wr(res, 5, 0); /* Med addr */ port_wr(res, 3, 0x44); /* Register select */ port_wr(res, 4, 0); /* High addr */ port_wr(res, 7, 0x55); /* DRAM */ /* Read from DRAM. */ port_wr(res, 3, 0x43); /* Register select */ port_wr(res, 4, 0); /* Low addr */ port_wr(res, 5, 0); /* Med addr */ port_wr(res, 3, 0x44); /* Register select */ port_wr(res, 4, 0); /* High addr */ val = port_rd(res, 7); /* DRAM */ splx(s); if (val != 0x55) goto fail; rid2 = 0; res2 = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid2, base, base, 1, RF_ACTIVE); if (res2 == NULL) goto fail; s = splhigh(); port_wr(res2, 0x0f, 0x20); val = port_rd(res2, 0x0f); splx(s); if (val == 0xff || (val & 0x06) == 0) val = 0; else { val = port_rd(res2, 0x506); /* XXX Out of range. */ if (val == 0xff) val = 0; } bus_release_resource(dev, SYS_RES_IOPORT, rid2, res2); bus_release_resource(dev, SYS_RES_IOPORT, rid, res); if (val >= 10) { struct sndcard_func *func; /* Looks like a GUS MAX. Set the rest of the resources. */ bus_set_resource(dev, SYS_RES_IOPORT, 2, base + 0x10c, 8); if (flags & DV_F_DUAL_DMA) bus_set_resource(dev, SYS_RES_DRQ, 1, flags & DV_F_DRQ_MASK, 1); /* We can support the CS4231 and MIDI devices. */ func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) return ENOMEM; func->func = SCF_MIDI; child = device_add_child(dev, "midi", -1); device_set_ivars(child, func); func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) printf("xxx: gus pcm not attached, out of memory\n"); else { func->func = SCF_PCM; child = device_add_child(dev, "pcm", -1); device_set_ivars(child, func); } device_set_desc(dev, "Gravis UltraSound MAX"); return 0; } else { /* * TODO: Support even older GUS cards. MIDI should work on * all models. */ return ENXIO; } fail: bus_release_resource(dev, SYS_RES_IOPORT, rid, res); return ENXIO; } static int gusc_attach(device_t dev) { sc_p scp; void *ih; scp = device_get_softc(dev); bzero(scp, sizeof(*scp)); scp->dev = dev; if (alloc_resource(scp)) { release_resource(scp); return (ENXIO); } if (scp->irq != NULL) snd_setup_intr(dev, scp->irq, 0, gusc_intr, scp, &ih); bus_generic_attach(dev); return (0); } /* * Handle interrupts on GUS devices until there aren't any left. */ static void gusc_intr(void *arg) { sc_p scp = (sc_p)arg; int did_something; do { did_something = 0; if (scp->pcm_intr.intr != NULL && (port_rd(scp->io[2], 2) & 1)) { (*scp->pcm_intr.intr)(scp->pcm_intr.arg); did_something = 1; } if (scp->midi_intr.intr != NULL && (port_rd(scp->io[1], 0) & 0x80)) { (*scp->midi_intr.intr)(scp->midi_intr.arg); did_something = 1; } } while (did_something != 0); } static struct resource * gusc_alloc_resource(device_t bus, device_t child, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) { sc_p scp; int *alloced, rid_max, alloced_max; struct resource **res; scp = device_get_softc(bus); switch (type) { case SYS_RES_IOPORT: alloced = scp->io_alloced; res = scp->io; rid_max = 2; alloced_max = 2; /* pcm + midi (more to include synth) */ break; case SYS_RES_IRQ: alloced = &scp->irq_alloced; res = &scp->irq; rid_max = 0; alloced_max = 2; /* pcm and midi share the single irq. */ break; case SYS_RES_DRQ: alloced = scp->drq_alloced; res = scp->drq; rid_max = 1; alloced_max = 1; break; default: return (NULL); } if (*rid > rid_max || alloced[*rid] == alloced_max) return (NULL); alloced[*rid]++; return (res[*rid]); } static int gusc_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r) { sc_p scp; int *alloced, rid_max; scp = device_get_softc(bus); switch (type) { case SYS_RES_IOPORT: alloced = scp->io_alloced; rid_max = 2; break; case SYS_RES_IRQ: alloced = &scp->irq_alloced; rid_max = 0; break; case SYS_RES_DRQ: alloced = scp->drq_alloced; rid_max = 1; break; default: return (1); } if (rid > rid_max || alloced[rid] == 0) return (1); alloced[rid]--; return (0); } static int gusc_setup_intr(device_t dev, device_t child, struct resource *irq, int flags, driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep) { sc_p scp = (sc_p)device_get_softc(dev); devclass_t devclass; if (filter != NULL) { printf("gusc.c: we cannot use a filter here\n"); return (EINVAL); } devclass = device_get_devclass(child); if (strcmp(devclass_get_name(devclass), "midi") == 0) { scp->midi_intr.intr = intr; scp->midi_intr.arg = arg; return 0; } else if (strcmp(devclass_get_name(devclass), "pcm") == 0) { scp->pcm_intr.intr = intr; scp->pcm_intr.arg = arg; return 0; } return bus_generic_setup_intr(dev, child, irq, flags, filter, intr, arg, cookiep); } static device_t find_masterdev(sc_p scp) { int i, units; devclass_t devclass; device_t dev; devclass = device_get_devclass(scp->dev); units = devclass_get_maxunit(devclass); dev = NULL; for (i = 0 ; i < units ; i++) { dev = devclass_get_device(devclass, i); if (isa_get_vendorid(dev) == isa_get_vendorid(scp->dev) && isa_get_logicalid(dev) == LOGICALID_PCM && isa_get_serial(dev) == isa_get_serial(scp->dev)) break; } if (i == units) return (NULL); return (dev); } static int io_range[3] = {0x10, 0x8 , 0x4 }; static int io_offset[3] = {0x0 , 0x100, 0x10c}; static int alloc_resource(sc_p scp) { int i, base, lid, flags; device_t dev; flags = 0; if (isa_get_vendorid(scp->dev)) lid = isa_get_logicalid(scp->dev); else { lid = LOGICALID_NOPNP; flags = device_get_flags(scp->dev); } switch(lid) { case LOGICALID_PCM: case LOGICALID_NOPNP: /* XXX Non-PnP */ if (lid == LOGICALID_NOPNP) base = isa_get_port(scp->dev); else base = 0; for (i = 0 ; i < nitems(scp->io); i++) { if (scp->io[i] == NULL) { scp->io_rid[i] = i; if (base == 0) scp->io[i] = bus_alloc_resource_anywhere(scp->dev, SYS_RES_IOPORT, &scp->io_rid[i], io_range[i], RF_ACTIVE); else scp->io[i] = bus_alloc_resource(scp->dev, SYS_RES_IOPORT, &scp->io_rid[i], base + io_offset[i], base + io_offset[i] + io_range[i] - 1 , io_range[i], RF_ACTIVE); if (scp->io[i] == NULL) return (1); scp->io_alloced[i] = 0; } } if (scp->irq == NULL) { scp->irq_rid = 0; scp->irq = bus_alloc_resource_any(scp->dev, SYS_RES_IRQ, &scp->irq_rid, RF_ACTIVE|RF_SHAREABLE); if (scp->irq == NULL) return (1); scp->irq_alloced = 0; } for (i = 0 ; i < nitems(scp->drq); i++) { if (scp->drq[i] == NULL) { scp->drq_rid[i] = i; if (base == 0 || i == 0) scp->drq[i] = bus_alloc_resource_any( scp->dev, SYS_RES_DRQ, &scp->drq_rid[i], RF_ACTIVE); else if ((flags & DV_F_DUAL_DMA) != 0) /* XXX The secondary drq is specified in the flag. */ scp->drq[i] = bus_alloc_resource(scp->dev, SYS_RES_DRQ, &scp->drq_rid[i], flags & DV_F_DRQ_MASK, flags & DV_F_DRQ_MASK, 1, RF_ACTIVE); if (scp->drq[i] == NULL) return (1); scp->drq_alloced[i] = 0; } } break; case LOGICALID_OPL: if (scp->io[0] == NULL) { scp->io_rid[0] = 0; scp->io[0] = bus_alloc_resource_anywhere(scp->dev, SYS_RES_IOPORT, &scp->io_rid[0], io_range[0], RF_ACTIVE); if (scp->io[0] == NULL) return (1); scp->io_alloced[0] = 0; } break; case LOGICALID_MIDI: if (scp->io[0] == NULL) { scp->io_rid[0] = 0; scp->io[0] = bus_alloc_resource_anywhere(scp->dev, SYS_RES_IOPORT, &scp->io_rid[0], io_range[0], RF_ACTIVE); if (scp->io[0] == NULL) return (1); scp->io_alloced[0] = 0; } if (scp->irq == NULL) { /* The irq is shared with pcm audio. */ dev = find_masterdev(scp); if (dev == NULL) return (1); scp->irq_rid = 0; scp->irq = BUS_ALLOC_RESOURCE(dev, NULL, SYS_RES_IRQ, &scp->irq_rid, 0, ~0, 1, RF_ACTIVE | RF_SHAREABLE); if (scp->irq == NULL) return (1); scp->irq_alloced = 0; } break; } return (0); } static int release_resource(sc_p scp) { int i, lid; device_t dev; if (isa_get_vendorid(scp->dev)) lid = isa_get_logicalid(scp->dev); else lid = LOGICALID_NOPNP; switch(lid) { case LOGICALID_PCM: case LOGICALID_NOPNP: /* XXX Non-PnP */ for (i = 0 ; i < nitems(scp->io); i++) { if (scp->io[i] != NULL) { bus_release_resource(scp->dev, SYS_RES_IOPORT, scp->io_rid[i], scp->io[i]); scp->io[i] = NULL; } } if (scp->irq != NULL) { bus_release_resource(scp->dev, SYS_RES_IRQ, scp->irq_rid, scp->irq); scp->irq = NULL; } for (i = 0 ; i < nitems(scp->drq); i++) { if (scp->drq[i] != NULL) { bus_release_resource(scp->dev, SYS_RES_DRQ, scp->drq_rid[i], scp->drq[i]); scp->drq[i] = NULL; } } break; case LOGICALID_OPL: if (scp->io[0] != NULL) { bus_release_resource(scp->dev, SYS_RES_IOPORT, scp->io_rid[0], scp->io[0]); scp->io[0] = NULL; } break; case LOGICALID_MIDI: if (scp->io[0] != NULL) { bus_release_resource(scp->dev, SYS_RES_IOPORT, scp->io_rid[0], scp->io[0]); scp->io[0] = NULL; } if (scp->irq != NULL) { /* The irq is shared with pcm audio. */ dev = find_masterdev(scp); if (dev == NULL) return (1); BUS_RELEASE_RESOURCE(dev, NULL, SYS_RES_IOPORT, scp->irq_rid, scp->irq); scp->irq = NULL; } break; } return (0); } static device_method_t gusc_methods[] = { /* Device interface */ DEVMETHOD(device_probe, gusc_probe), DEVMETHOD(device_attach, gusc_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), /* Bus interface */ DEVMETHOD(bus_alloc_resource, gusc_alloc_resource), DEVMETHOD(bus_release_resource, gusc_release_resource), DEVMETHOD(bus_activate_resource, bus_generic_activate_resource), DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource), DEVMETHOD(bus_setup_intr, gusc_setup_intr), DEVMETHOD(bus_teardown_intr, bus_generic_teardown_intr), DEVMETHOD_END }; static driver_t gusc_driver = { "gusc", gusc_methods, sizeof(struct gusc_softc), }; /* * gusc can be attached to an isa bus. */ DRIVER_MODULE(snd_gusc, isa, gusc_driver, gusc_devclass, 0, 0); DRIVER_MODULE(snd_gusc, acpi, gusc_driver, gusc_devclass, 0, 0); MODULE_DEPEND(snd_gusc, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_VERSION(snd_gusc, 1); - - +ISA_PNP_INFO(gusc_ids); Index: head/sys/dev/sound/isa/mss.c =================================================================== --- head/sys/dev/sound/isa/mss.c (revision 328523) +++ head/sys/dev/sound/isa/mss.c (revision 328524) @@ -1,2297 +1,2296 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2001 George Reid * Copyright (c) 1999 Cameron Grant * Copyright (c) 1997,1998 Luigi Rizzo * Copyright (c) 1994,1995 Hannu Savolainen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" #endif #include SND_DECLARE_FILE("$FreeBSD$"); /* board-specific include files */ #include #include #include #include #include "mixer_if.h" #define MSS_DEFAULT_BUFSZ (4096) #define MSS_INDEXED_REGS 0x20 #define OPL_INDEXED_REGS 0x19 struct mss_info; struct mss_chinfo { struct mss_info *parent; struct pcm_channel *channel; struct snd_dbuf *buffer; int dir; u_int32_t fmt, blksz; }; struct mss_info { struct resource *io_base; /* primary I/O address for the board */ int io_rid; struct resource *conf_base; /* and the opti931 also has a config space */ int conf_rid; struct resource *irq; int irq_rid; struct resource *drq1; /* play */ int drq1_rid; struct resource *drq2; /* rec */ int drq2_rid; void *ih; bus_dma_tag_t parent_dmat; struct mtx *lock; char mss_indexed_regs[MSS_INDEXED_REGS]; char opl_indexed_regs[OPL_INDEXED_REGS]; int bd_id; /* used to hold board-id info, eg. sb version, * mss codec type, etc. etc. */ int opti_offset; /* offset from config_base for opti931 */ u_long bd_flags; /* board-specific flags */ int optibase; /* base address for OPTi9xx config */ struct resource *indir; /* Indirect register index address */ int indir_rid; int password; /* password for opti9xx cards */ int passwdreg; /* password register */ unsigned int bufsize; struct mss_chinfo pch, rch; }; static int mss_probe(device_t dev); static int mss_attach(device_t dev); static driver_intr_t mss_intr; /* prototypes for local functions */ static int mss_detect(device_t dev, struct mss_info *mss); static int opti_detect(device_t dev, struct mss_info *mss); static char *ymf_test(device_t dev, struct mss_info *mss); static void ad_unmute(struct mss_info *mss); /* mixer set funcs */ static int mss_mixer_set(struct mss_info *mss, int dev, int left, int right); static int mss_set_recsrc(struct mss_info *mss, int mask); /* io funcs */ static int ad_wait_init(struct mss_info *mss, int x); static int ad_read(struct mss_info *mss, int reg); static void ad_write(struct mss_info *mss, int reg, u_char data); static void ad_write_cnt(struct mss_info *mss, int reg, u_short data); static void ad_enter_MCE(struct mss_info *mss); static void ad_leave_MCE(struct mss_info *mss); /* OPTi-specific functions */ static void opti_write(struct mss_info *mss, u_char reg, u_char data); static u_char opti_read(struct mss_info *mss, u_char reg); static int opti_init(device_t dev, struct mss_info *mss); /* io primitives */ static void conf_wr(struct mss_info *mss, u_char reg, u_char data); static u_char conf_rd(struct mss_info *mss, u_char reg); static int pnpmss_probe(device_t dev); static int pnpmss_attach(device_t dev); static driver_intr_t opti931_intr; static u_int32_t mss_fmt[] = { SND_FORMAT(AFMT_U8, 1, 0), SND_FORMAT(AFMT_U8, 2, 0), SND_FORMAT(AFMT_S16_LE, 1, 0), SND_FORMAT(AFMT_S16_LE, 2, 0), SND_FORMAT(AFMT_MU_LAW, 1, 0), SND_FORMAT(AFMT_MU_LAW, 2, 0), SND_FORMAT(AFMT_A_LAW, 1, 0), SND_FORMAT(AFMT_A_LAW, 2, 0), 0 }; static struct pcmchan_caps mss_caps = {4000, 48000, mss_fmt, 0}; static u_int32_t guspnp_fmt[] = { SND_FORMAT(AFMT_U8, 1, 0), SND_FORMAT(AFMT_U8, 2, 0), SND_FORMAT(AFMT_S16_LE, 1, 0), SND_FORMAT(AFMT_S16_LE, 2, 0), SND_FORMAT(AFMT_A_LAW, 1, 0), SND_FORMAT(AFMT_A_LAW, 2, 0), 0 }; static struct pcmchan_caps guspnp_caps = {4000, 48000, guspnp_fmt, 0}; static u_int32_t opti931_fmt[] = { SND_FORMAT(AFMT_U8, 1, 0), SND_FORMAT(AFMT_U8, 2, 0), SND_FORMAT(AFMT_S16_LE, 1, 0), SND_FORMAT(AFMT_S16_LE, 2, 0), 0 }; static struct pcmchan_caps opti931_caps = {4000, 48000, opti931_fmt, 0}; #define MD_AD1848 0x91 #define MD_AD1845 0x92 #define MD_CS42XX 0xA1 #define MD_CS423X 0xA2 #define MD_OPTI930 0xB0 #define MD_OPTI931 0xB1 #define MD_OPTI925 0xB2 #define MD_OPTI924 0xB3 #define MD_GUSPNP 0xB8 #define MD_GUSMAX 0xB9 #define MD_YM0020 0xC1 #define MD_VIVO 0xD1 #define DV_F_TRUE_MSS 0x00010000 /* mss _with_ base regs */ #define FULL_DUPLEX(x) ((x)->bd_flags & BD_F_DUPLEX) static void mss_lock(struct mss_info *mss) { snd_mtxlock(mss->lock); } static void mss_unlock(struct mss_info *mss) { snd_mtxunlock(mss->lock); } static int port_rd(struct resource *port, int off) { if (port) return bus_space_read_1(rman_get_bustag(port), rman_get_bushandle(port), off); else return -1; } static void port_wr(struct resource *port, int off, u_int8_t data) { if (port) bus_space_write_1(rman_get_bustag(port), rman_get_bushandle(port), off, data); } static int io_rd(struct mss_info *mss, int reg) { if (mss->bd_flags & BD_F_MSS_OFFSET) reg -= 4; return port_rd(mss->io_base, reg); } static void io_wr(struct mss_info *mss, int reg, u_int8_t data) { if (mss->bd_flags & BD_F_MSS_OFFSET) reg -= 4; port_wr(mss->io_base, reg, data); } static void conf_wr(struct mss_info *mss, u_char reg, u_char value) { port_wr(mss->conf_base, 0, reg); port_wr(mss->conf_base, 1, value); } static u_char conf_rd(struct mss_info *mss, u_char reg) { port_wr(mss->conf_base, 0, reg); return port_rd(mss->conf_base, 1); } static void opti_wr(struct mss_info *mss, u_char reg, u_char value) { port_wr(mss->conf_base, mss->opti_offset + 0, reg); port_wr(mss->conf_base, mss->opti_offset + 1, value); } static u_char opti_rd(struct mss_info *mss, u_char reg) { port_wr(mss->conf_base, mss->opti_offset + 0, reg); return port_rd(mss->conf_base, mss->opti_offset + 1); } static void gus_wr(struct mss_info *mss, u_char reg, u_char value) { port_wr(mss->conf_base, 3, reg); port_wr(mss->conf_base, 5, value); } static u_char gus_rd(struct mss_info *mss, u_char reg) { port_wr(mss->conf_base, 3, reg); return port_rd(mss->conf_base, 5); } static void mss_release_resources(struct mss_info *mss, device_t dev) { if (mss->irq) { if (mss->ih) bus_teardown_intr(dev, mss->irq, mss->ih); bus_release_resource(dev, SYS_RES_IRQ, mss->irq_rid, mss->irq); mss->irq = NULL; } if (mss->drq2) { if (mss->drq2 != mss->drq1) { isa_dma_release(rman_get_start(mss->drq2)); bus_release_resource(dev, SYS_RES_DRQ, mss->drq2_rid, mss->drq2); } mss->drq2 = NULL; } if (mss->drq1) { isa_dma_release(rman_get_start(mss->drq1)); bus_release_resource(dev, SYS_RES_DRQ, mss->drq1_rid, mss->drq1); mss->drq1 = NULL; } if (mss->io_base) { bus_release_resource(dev, SYS_RES_IOPORT, mss->io_rid, mss->io_base); mss->io_base = NULL; } if (mss->conf_base) { bus_release_resource(dev, SYS_RES_IOPORT, mss->conf_rid, mss->conf_base); mss->conf_base = NULL; } if (mss->indir) { bus_release_resource(dev, SYS_RES_IOPORT, mss->indir_rid, mss->indir); mss->indir = NULL; } if (mss->parent_dmat) { bus_dma_tag_destroy(mss->parent_dmat); mss->parent_dmat = 0; } if (mss->lock) snd_mtxfree(mss->lock); free(mss, M_DEVBUF); } static int mss_alloc_resources(struct mss_info *mss, device_t dev) { int pdma, rdma, ok = 1; if (!mss->io_base) mss->io_base = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &mss->io_rid, RF_ACTIVE); if (!mss->irq) mss->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &mss->irq_rid, RF_ACTIVE); if (!mss->drq1) mss->drq1 = bus_alloc_resource_any(dev, SYS_RES_DRQ, &mss->drq1_rid, RF_ACTIVE); if (mss->conf_rid >= 0 && !mss->conf_base) mss->conf_base = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &mss->conf_rid, RF_ACTIVE); if (mss->drq2_rid >= 0 && !mss->drq2) mss->drq2 = bus_alloc_resource_any(dev, SYS_RES_DRQ, &mss->drq2_rid, RF_ACTIVE); if (!mss->io_base || !mss->drq1 || !mss->irq) ok = 0; if (mss->conf_rid >= 0 && !mss->conf_base) ok = 0; if (mss->drq2_rid >= 0 && !mss->drq2) ok = 0; if (ok) { pdma = rman_get_start(mss->drq1); isa_dma_acquire(pdma); isa_dmainit(pdma, mss->bufsize); mss->bd_flags &= ~BD_F_DUPLEX; if (mss->drq2) { rdma = rman_get_start(mss->drq2); isa_dma_acquire(rdma); isa_dmainit(rdma, mss->bufsize); mss->bd_flags |= BD_F_DUPLEX; } else mss->drq2 = mss->drq1; } return ok; } /* * The various mixers use a variety of bitmasks etc. The Voxware * driver had a very nice technique to describe a mixer and interface * to it. A table defines, for each channel, which register, bits, * offset, polarity to use. This procedure creates the new value * using the table and the old value. */ static void change_bits(mixer_tab *t, u_char *regval, int dev, int chn, int newval) { u_char mask; int shift; DEB(printf("ch_bits dev %d ch %d val %d old 0x%02x " "r %d p %d bit %d off %d\n", dev, chn, newval, *regval, (*t)[dev][chn].regno, (*t)[dev][chn].polarity, (*t)[dev][chn].nbits, (*t)[dev][chn].bitoffs ) ); if ( (*t)[dev][chn].polarity == 1) /* reverse */ newval = 100 - newval ; mask = (1 << (*t)[dev][chn].nbits) - 1; newval = (int) ((newval * mask) + 50) / 100; /* Scale it */ shift = (*t)[dev][chn].bitoffs /*- (*t)[dev][LEFT_CHN].nbits + 1*/; *regval &= ~(mask << shift); /* Filter out the previous value */ *regval |= (newval & mask) << shift; /* Set the new value */ } /* -------------------------------------------------------------------- */ /* only one source can be set... */ static int mss_set_recsrc(struct mss_info *mss, int mask) { u_char recdev; switch (mask) { case SOUND_MASK_LINE: case SOUND_MASK_LINE3: recdev = 0; break; case SOUND_MASK_CD: case SOUND_MASK_LINE1: recdev = 0x40; break; case SOUND_MASK_IMIX: recdev = 0xc0; break; case SOUND_MASK_MIC: default: mask = SOUND_MASK_MIC; recdev = 0x80; } ad_write(mss, 0, (ad_read(mss, 0) & 0x3f) | recdev); ad_write(mss, 1, (ad_read(mss, 1) & 0x3f) | recdev); return mask; } /* there are differences in the mixer depending on the actual sound card. */ static int mss_mixer_set(struct mss_info *mss, int dev, int left, int right) { int regoffs; mixer_tab *mix_d; u_char old, val; switch (mss->bd_id) { case MD_OPTI931: mix_d = &opti931_devices; break; case MD_OPTI930: mix_d = &opti930_devices; break; default: mix_d = &mix_devices; } if ((*mix_d)[dev][LEFT_CHN].nbits == 0) { DEB(printf("nbits = 0 for dev %d\n", dev)); return -1; } if ((*mix_d)[dev][RIGHT_CHN].nbits == 0) right = left; /* mono */ /* Set the left channel */ regoffs = (*mix_d)[dev][LEFT_CHN].regno; old = val = ad_read(mss, regoffs); /* if volume is 0, mute chan. Otherwise, unmute. */ if (regoffs != 0) val = (left == 0)? old | 0x80 : old & 0x7f; change_bits(mix_d, &val, dev, LEFT_CHN, left); ad_write(mss, regoffs, val); DEB(printf("LEFT: dev %d reg %d old 0x%02x new 0x%02x\n", dev, regoffs, old, val)); if ((*mix_d)[dev][RIGHT_CHN].nbits != 0) { /* have stereo */ /* Set the right channel */ regoffs = (*mix_d)[dev][RIGHT_CHN].regno; old = val = ad_read(mss, regoffs); if (regoffs != 1) val = (right == 0)? old | 0x80 : old & 0x7f; change_bits(mix_d, &val, dev, RIGHT_CHN, right); ad_write(mss, regoffs, val); DEB(printf("RIGHT: dev %d reg %d old 0x%02x new 0x%02x\n", dev, regoffs, old, val)); } return 0; /* success */ } /* -------------------------------------------------------------------- */ static int mssmix_init(struct snd_mixer *m) { struct mss_info *mss = mix_getdevinfo(m); mix_setdevs(m, MODE2_MIXER_DEVICES); mix_setrecdevs(m, MSS_REC_DEVICES); switch(mss->bd_id) { case MD_OPTI930: mix_setdevs(m, OPTI930_MIXER_DEVICES); break; case MD_OPTI931: mix_setdevs(m, OPTI931_MIXER_DEVICES); mss_lock(mss); ad_write(mss, 20, 0x88); ad_write(mss, 21, 0x88); mss_unlock(mss); break; case MD_AD1848: mix_setdevs(m, MODE1_MIXER_DEVICES); break; case MD_GUSPNP: case MD_GUSMAX: /* this is only necessary in mode 3 ... */ mss_lock(mss); ad_write(mss, 22, 0x88); ad_write(mss, 23, 0x88); mss_unlock(mss); break; } return 0; } static int mssmix_set(struct snd_mixer *m, unsigned dev, unsigned left, unsigned right) { struct mss_info *mss = mix_getdevinfo(m); mss_lock(mss); mss_mixer_set(mss, dev, left, right); mss_unlock(mss); return left | (right << 8); } static u_int32_t mssmix_setrecsrc(struct snd_mixer *m, u_int32_t src) { struct mss_info *mss = mix_getdevinfo(m); mss_lock(mss); src = mss_set_recsrc(mss, src); mss_unlock(mss); return src; } static kobj_method_t mssmix_mixer_methods[] = { KOBJMETHOD(mixer_init, mssmix_init), KOBJMETHOD(mixer_set, mssmix_set), KOBJMETHOD(mixer_setrecsrc, mssmix_setrecsrc), KOBJMETHOD_END }; MIXER_DECLARE(mssmix_mixer); /* -------------------------------------------------------------------- */ static int ymmix_init(struct snd_mixer *m) { struct mss_info *mss = mix_getdevinfo(m); mssmix_init(m); mix_setdevs(m, mix_getdevs(m) | SOUND_MASK_VOLUME | SOUND_MASK_MIC | SOUND_MASK_BASS | SOUND_MASK_TREBLE); /* Set master volume */ mss_lock(mss); conf_wr(mss, OPL3SAx_VOLUMEL, 7); conf_wr(mss, OPL3SAx_VOLUMER, 7); mss_unlock(mss); return 0; } static int ymmix_set(struct snd_mixer *m, unsigned dev, unsigned left, unsigned right) { struct mss_info *mss = mix_getdevinfo(m); int t, l, r; mss_lock(mss); switch (dev) { case SOUND_MIXER_VOLUME: if (left) t = 15 - (left * 15) / 100; else t = 0x80; /* mute */ conf_wr(mss, OPL3SAx_VOLUMEL, t); if (right) t = 15 - (right * 15) / 100; else t = 0x80; /* mute */ conf_wr(mss, OPL3SAx_VOLUMER, t); break; case SOUND_MIXER_MIC: t = left; if (left) t = 31 - (left * 31) / 100; else t = 0x80; /* mute */ conf_wr(mss, OPL3SAx_MIC, t); break; case SOUND_MIXER_BASS: l = (left * 7) / 100; r = (right * 7) / 100; t = (r << 4) | l; conf_wr(mss, OPL3SAx_BASS, t); break; case SOUND_MIXER_TREBLE: l = (left * 7) / 100; r = (right * 7) / 100; t = (r << 4) | l; conf_wr(mss, OPL3SAx_TREBLE, t); break; default: mss_mixer_set(mss, dev, left, right); } mss_unlock(mss); return left | (right << 8); } static u_int32_t ymmix_setrecsrc(struct snd_mixer *m, u_int32_t src) { struct mss_info *mss = mix_getdevinfo(m); mss_lock(mss); src = mss_set_recsrc(mss, src); mss_unlock(mss); return src; } static kobj_method_t ymmix_mixer_methods[] = { KOBJMETHOD(mixer_init, ymmix_init), KOBJMETHOD(mixer_set, ymmix_set), KOBJMETHOD(mixer_setrecsrc, ymmix_setrecsrc), KOBJMETHOD_END }; MIXER_DECLARE(ymmix_mixer); /* -------------------------------------------------------------------- */ /* * XXX This might be better off in the gusc driver. */ static void gusmax_setup(struct mss_info *mss, device_t dev, struct resource *alt) { static const unsigned char irq_bits[16] = { 0, 0, 0, 3, 0, 2, 0, 4, 0, 1, 0, 5, 6, 0, 0, 7 }; static const unsigned char dma_bits[8] = { 0, 1, 0, 2, 0, 3, 4, 5 }; device_t parent = device_get_parent(dev); unsigned char irqctl, dmactl; int s; s = splhigh(); port_wr(alt, 0x0f, 0x05); port_wr(alt, 0x00, 0x0c); port_wr(alt, 0x0b, 0x00); port_wr(alt, 0x0f, 0x00); irqctl = irq_bits[isa_get_irq(parent)]; /* Share the IRQ with the MIDI driver. */ irqctl |= 0x40; dmactl = dma_bits[isa_get_drq(parent)]; if (device_get_flags(parent) & DV_F_DUAL_DMA) dmactl |= dma_bits[device_get_flags(parent) & DV_F_DRQ_MASK] << 3; /* * Set the DMA and IRQ control latches. */ port_wr(alt, 0x00, 0x0c); port_wr(alt, 0x0b, dmactl | 0x80); port_wr(alt, 0x00, 0x4c); port_wr(alt, 0x0b, irqctl); port_wr(alt, 0x00, 0x0c); port_wr(alt, 0x0b, dmactl); port_wr(alt, 0x00, 0x4c); port_wr(alt, 0x0b, irqctl); port_wr(mss->conf_base, 2, 0); port_wr(alt, 0x00, 0x0c); port_wr(mss->conf_base, 2, 0); splx(s); } static int mss_init(struct mss_info *mss, device_t dev) { u_char r6, r9; struct resource *alt; int rid, tmp; mss->bd_flags |= BD_F_MCE_BIT; switch(mss->bd_id) { case MD_OPTI931: /* * The MED3931 v.1.0 allocates 3 bytes for the config * space, whereas v.2.0 allocates 4 bytes. What I know * for sure is that the upper two ports must be used, * and they should end on a boundary of 4 bytes. So I * need the following trick. */ mss->opti_offset = (rman_get_start(mss->conf_base) & ~3) + 2 - rman_get_start(mss->conf_base); BVDDB(printf("mss_init: opti_offset=%d\n", mss->opti_offset)); opti_wr(mss, 4, 0xd6); /* fifo empty, OPL3, audio enable, SB3.2 */ ad_write(mss, 10, 2); /* enable interrupts */ opti_wr(mss, 6, 2); /* MCIR6: mss enable, sb disable */ opti_wr(mss, 5, 0x28); /* MCIR5: codec in exp. mode,fifo */ break; case MD_GUSPNP: case MD_GUSMAX: gus_wr(mss, 0x4c /* _URSTI */, 0);/* Pull reset */ DELAY(1000 * 30); /* release reset and enable DAC */ gus_wr(mss, 0x4c /* _URSTI */, 3); DELAY(1000 * 30); /* end of reset */ rid = 0; alt = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid, RF_ACTIVE); if (alt == NULL) { printf("XXX couldn't init GUS PnP/MAX\n"); break; } port_wr(alt, 0, 0xC); /* enable int and dma */ if (mss->bd_id == MD_GUSMAX) gusmax_setup(mss, dev, alt); bus_release_resource(dev, SYS_RES_IOPORT, rid, alt); /* * unmute left & right line. Need to go in mode3, unmute, * and back to mode 2 */ tmp = ad_read(mss, 0x0c); ad_write(mss, 0x0c, 0x6c); /* special value to enter mode 3 */ ad_write(mss, 0x19, 0); /* unmute left */ ad_write(mss, 0x1b, 0); /* unmute right */ ad_write(mss, 0x0c, tmp); /* restore old mode */ /* send codec interrupts on irq1 and only use that one */ gus_wr(mss, 0x5a, 0x4f); /* enable access to hidden regs */ tmp = gus_rd(mss, 0x5b /* IVERI */); gus_wr(mss, 0x5b, tmp | 1); BVDDB(printf("GUS: silicon rev %c\n", 'A' + ((tmp & 0xf) >> 4))); break; case MD_YM0020: conf_wr(mss, OPL3SAx_DMACONF, 0xa9); /* dma-b rec, dma-a play */ r6 = conf_rd(mss, OPL3SAx_DMACONF); r9 = conf_rd(mss, OPL3SAx_MISC); /* version */ BVDDB(printf("Yamaha: ver 0x%x DMA config 0x%x\n", r6, r9);) /* yamaha - set volume to max */ conf_wr(mss, OPL3SAx_VOLUMEL, 0); conf_wr(mss, OPL3SAx_VOLUMER, 0); conf_wr(mss, OPL3SAx_DMACONF, FULL_DUPLEX(mss)? 0xa9 : 0x8b); break; } if (FULL_DUPLEX(mss) && mss->bd_id != MD_OPTI931) ad_write(mss, 12, ad_read(mss, 12) | 0x40); /* mode 2 */ ad_enter_MCE(mss); ad_write(mss, 9, FULL_DUPLEX(mss)? 0 : 4); ad_leave_MCE(mss); ad_write(mss, 10, 2); /* int enable */ io_wr(mss, MSS_STATUS, 0); /* Clear interrupt status */ /* the following seem required on the CS4232 */ ad_unmute(mss); return 0; } /* * main irq handler for the CS423x. The OPTi931 code is * a separate one. * The correct way to operate for a device with multiple internal * interrupt sources is to loop on the status register and ack * interrupts until all interrupts are served and none are reported. At * this point the IRQ line to the ISA IRQ controller should go low * and be raised at the next interrupt. * * Since the ISA IRQ controller is sent EOI _before_ passing control * to the isr, it might happen that we serve an interrupt early, in * which case the status register at the next interrupt should just * say that there are no more interrupts... */ static void mss_intr(void *arg) { struct mss_info *mss = arg; u_char c = 0, served = 0; int i; DEB(printf("mss_intr\n")); mss_lock(mss); ad_read(mss, 11); /* fake read of status bits */ /* loop until there are interrupts, but no more than 10 times. */ for (i = 10; i > 0 && io_rd(mss, MSS_STATUS) & 1; i--) { /* get exact reason for full-duplex boards */ c = FULL_DUPLEX(mss)? ad_read(mss, 24) : 0x30; c &= ~served; if (sndbuf_runsz(mss->pch.buffer) && (c & 0x10)) { served |= 0x10; mss_unlock(mss); chn_intr(mss->pch.channel); mss_lock(mss); } if (sndbuf_runsz(mss->rch.buffer) && (c & 0x20)) { served |= 0x20; mss_unlock(mss); chn_intr(mss->rch.channel); mss_lock(mss); } /* now ack the interrupt */ if (FULL_DUPLEX(mss)) ad_write(mss, 24, ~c); /* ack selectively */ else io_wr(mss, MSS_STATUS, 0); /* Clear interrupt status */ } if (i == 10) { BVDDB(printf("mss_intr: irq, but not from mss\n")); } else if (served == 0) { BVDDB(printf("mss_intr: unexpected irq with reason %x\n", c)); /* * this should not happen... I have no idea what to do now. * maybe should do a sanity check and restart dmas ? */ io_wr(mss, MSS_STATUS, 0); /* Clear interrupt status */ } mss_unlock(mss); } /* * AD_WAIT_INIT waits if we are initializing the board and * we cannot modify its settings */ static int ad_wait_init(struct mss_info *mss, int x) { int arg = x, n = 0; /* to shut up the compiler... */ for (; x > 0; x--) if ((n = io_rd(mss, MSS_INDEX)) & MSS_IDXBUSY) DELAY(10); else return n; printf("AD_WAIT_INIT FAILED %d 0x%02x\n", arg, n); return n; } static int ad_read(struct mss_info *mss, int reg) { int x; ad_wait_init(mss, 201000); x = io_rd(mss, MSS_INDEX) & ~MSS_IDXMASK; io_wr(mss, MSS_INDEX, (u_char)(reg & MSS_IDXMASK) | x); x = io_rd(mss, MSS_IDATA); /* printf("ad_read %d, %x\n", reg, x); */ return x; } static void ad_write(struct mss_info *mss, int reg, u_char data) { int x; /* printf("ad_write %d, %x\n", reg, data); */ ad_wait_init(mss, 1002000); x = io_rd(mss, MSS_INDEX) & ~MSS_IDXMASK; io_wr(mss, MSS_INDEX, (u_char)(reg & MSS_IDXMASK) | x); io_wr(mss, MSS_IDATA, data); } static void ad_write_cnt(struct mss_info *mss, int reg, u_short cnt) { ad_write(mss, reg+1, cnt & 0xff); ad_write(mss, reg, cnt >> 8); /* upper base must be last */ } static void wait_for_calibration(struct mss_info *mss) { int t; /* * Wait until the auto calibration process has finished. * * 1) Wait until the chip becomes ready (reads don't return 0x80). * 2) Wait until the ACI bit of I11 gets on * 3) Wait until the ACI bit of I11 gets off */ t = ad_wait_init(mss, 1000000); if (t & MSS_IDXBUSY) printf("mss: Auto calibration timed out(1).\n"); /* * The calibration mode for chips that support it is set so that * we never see ACI go on. */ if (mss->bd_id == MD_GUSMAX || mss->bd_id == MD_GUSPNP) { for (t = 100; t > 0 && (ad_read(mss, 11) & 0x20) == 0; t--); } else { /* * XXX This should only be enabled for cards that *really* * need it. Are there any? */ for (t = 100; t > 0 && (ad_read(mss, 11) & 0x20) == 0; t--) DELAY(100); } for (t = 100; t > 0 && ad_read(mss, 11) & 0x20; t--) DELAY(100); } static void ad_unmute(struct mss_info *mss) { ad_write(mss, 6, ad_read(mss, 6) & ~I6_MUTE); ad_write(mss, 7, ad_read(mss, 7) & ~I6_MUTE); } static void ad_enter_MCE(struct mss_info *mss) { int prev; mss->bd_flags |= BD_F_MCE_BIT; ad_wait_init(mss, 203000); prev = io_rd(mss, MSS_INDEX); prev &= ~MSS_TRD; io_wr(mss, MSS_INDEX, prev | MSS_MCE); } static void ad_leave_MCE(struct mss_info *mss) { u_char prev; if ((mss->bd_flags & BD_F_MCE_BIT) == 0) { DEB(printf("--- hey, leave_MCE: MCE bit was not set!\n")); return; } ad_wait_init(mss, 1000000); mss->bd_flags &= ~BD_F_MCE_BIT; prev = io_rd(mss, MSS_INDEX); prev &= ~MSS_TRD; io_wr(mss, MSS_INDEX, prev & ~MSS_MCE); /* Clear the MCE bit */ wait_for_calibration(mss); } static int mss_speed(struct mss_chinfo *ch, int speed) { struct mss_info *mss = ch->parent; /* * In the CS4231, the low 4 bits of I8 are used to hold the * sample rate. Only a fixed number of values is allowed. This * table lists them. The speed-setting routines scans the table * looking for the closest match. This is the only supported method. * * In the CS4236, there is an alternate metod (which we do not * support yet) which provides almost arbitrary frequency setting. * In the AD1845, it looks like the sample rate can be * almost arbitrary, and written directly to a register. * In the OPTi931, there is a SB command which provides for * almost arbitrary frequency setting. * */ ad_enter_MCE(mss); if (mss->bd_id == MD_AD1845) { /* Use alternate speed select regs */ ad_write(mss, 22, (speed >> 8) & 0xff); /* Speed MSB */ ad_write(mss, 23, speed & 0xff); /* Speed LSB */ /* XXX must also do something in I27 for the ad1845 */ } else { int i, sel = 0; /* assume entry 0 does not contain -1 */ static int speeds[] = {8000, 5512, 16000, 11025, 27429, 18900, 32000, 22050, -1, 37800, -1, 44100, 48000, 33075, 9600, 6615}; for (i = 1; i < 16; i++) if (speeds[i] > 0 && abs(speed-speeds[i]) < abs(speed-speeds[sel])) sel = i; speed = speeds[sel]; ad_write(mss, 8, (ad_read(mss, 8) & 0xf0) | sel); ad_wait_init(mss, 10000); } ad_leave_MCE(mss); return speed; } /* * mss_format checks that the format is supported (or defaults to AFMT_U8) * and returns the bit setting for the 1848 register corresponding to * the desired format. * * fixed lr970724 */ static int mss_format(struct mss_chinfo *ch, u_int32_t format) { struct mss_info *mss = ch->parent; int i, arg = AFMT_ENCODING(format); /* * The data format uses 3 bits (just 2 on the 1848). For each * bit setting, the following array returns the corresponding format. * The code scans the array looking for a suitable format. In * case it is not found, default to AFMT_U8 (not such a good * choice, but let's do it for compatibility...). */ static int fmts[] = {AFMT_U8, AFMT_MU_LAW, AFMT_S16_LE, AFMT_A_LAW, -1, AFMT_IMA_ADPCM, AFMT_U16_BE, -1}; ch->fmt = format; for (i = 0; i < 8; i++) if (arg == fmts[i]) break; arg = i << 1; if (AFMT_CHANNEL(format) > 1) arg |= 1; arg <<= 4; ad_enter_MCE(mss); ad_write(mss, 8, (ad_read(mss, 8) & 0x0f) | arg); ad_wait_init(mss, 10000); if (ad_read(mss, 12) & 0x40) { /* mode2? */ ad_write(mss, 28, arg); /* capture mode */ ad_wait_init(mss, 10000); } ad_leave_MCE(mss); return format; } static int mss_trigger(struct mss_chinfo *ch, int go) { struct mss_info *mss = ch->parent; u_char m; int retry, wr, cnt, ss; ss = 1; ss <<= (AFMT_CHANNEL(ch->fmt) > 1)? 1 : 0; ss <<= (ch->fmt & AFMT_16BIT)? 1 : 0; wr = (ch->dir == PCMDIR_PLAY)? 1 : 0; m = ad_read(mss, 9); switch (go) { case PCMTRIG_START: cnt = (ch->blksz / ss) - 1; DEB(if (m & 4) printf("OUCH! reg 9 0x%02x\n", m);); m |= wr? I9_PEN : I9_CEN; /* enable DMA */ ad_write_cnt(mss, (wr || !FULL_DUPLEX(mss))? 14 : 30, cnt); break; case PCMTRIG_STOP: case PCMTRIG_ABORT: /* XXX check this... */ m &= ~(wr? I9_PEN : I9_CEN); /* Stop DMA */ #if 0 /* * try to disable DMA by clearing count registers. Not sure it * is needed, and it might cause false interrupts when the * DMA is re-enabled later. */ ad_write_cnt(mss, (wr || !FULL_DUPLEX(mss))? 14 : 30, 0); #endif } /* on the OPTi931 the enable bit seems hard to set... */ for (retry = 10; retry > 0; retry--) { ad_write(mss, 9, m); if (ad_read(mss, 9) == m) break; } if (retry == 0) BVDDB(printf("stop dma, failed to set bit 0x%02x 0x%02x\n", \ m, ad_read(mss, 9))); return 0; } /* * the opti931 seems to miss interrupts when working in full * duplex, so we try some heuristics to catch them. */ static void opti931_intr(void *arg) { struct mss_info *mss = (struct mss_info *)arg; u_char masked = 0, i11, mc11, c = 0; u_char reason; /* b0 = playback, b1 = capture, b2 = timer */ int loops = 10; #if 0 reason = io_rd(mss, MSS_STATUS); if (!(reason & 1)) {/* no int, maybe a shared line ? */ DEB(printf("intr: flag 0, mcir11 0x%02x\n", ad_read(mss, 11))); return; } #endif mss_lock(mss); i11 = ad_read(mss, 11); /* XXX what's for ? */ again: c = mc11 = FULL_DUPLEX(mss)? opti_rd(mss, 11) : 0xc; mc11 &= 0x0c; if (c & 0x10) { DEB(printf("Warning: CD interrupt\n");) mc11 |= 0x10; } if (c & 0x20) { DEB(printf("Warning: MPU interrupt\n");) mc11 |= 0x20; } if (mc11 & masked) BVDDB(printf("irq reset failed, mc11 0x%02x, 0x%02x\n",\ mc11, masked)); masked |= mc11; /* * the nice OPTi931 sets the IRQ line before setting the bits in * mc11. So, on some occasions I have to retry (max 10 times). */ if (mc11 == 0) { /* perhaps can return ... */ reason = io_rd(mss, MSS_STATUS); if (reason & 1) { DEB(printf("one more try...\n");) if (--loops) goto again; else BVDDB(printf("intr, but mc11 not set\n");) } if (loops == 0) BVDDB(printf("intr, nothing in mcir11 0x%02x\n", mc11)); mss_unlock(mss); return; } if (sndbuf_runsz(mss->rch.buffer) && (mc11 & 8)) { mss_unlock(mss); chn_intr(mss->rch.channel); mss_lock(mss); } if (sndbuf_runsz(mss->pch.buffer) && (mc11 & 4)) { mss_unlock(mss); chn_intr(mss->pch.channel); mss_lock(mss); } opti_wr(mss, 11, ~mc11); /* ack */ if (--loops) goto again; mss_unlock(mss); DEB(printf("xxx too many loops\n");) } /* -------------------------------------------------------------------- */ /* channel interface */ static void * msschan_init(kobj_t obj, void *devinfo, struct snd_dbuf *b, struct pcm_channel *c, int dir) { struct mss_info *mss = devinfo; struct mss_chinfo *ch = (dir == PCMDIR_PLAY)? &mss->pch : &mss->rch; ch->parent = mss; ch->channel = c; ch->buffer = b; ch->dir = dir; if (sndbuf_alloc(ch->buffer, mss->parent_dmat, 0, mss->bufsize) != 0) return NULL; sndbuf_dmasetup(ch->buffer, (dir == PCMDIR_PLAY)? mss->drq1 : mss->drq2); return ch; } static int msschan_setformat(kobj_t obj, void *data, u_int32_t format) { struct mss_chinfo *ch = data; struct mss_info *mss = ch->parent; mss_lock(mss); mss_format(ch, format); mss_unlock(mss); return 0; } static u_int32_t msschan_setspeed(kobj_t obj, void *data, u_int32_t speed) { struct mss_chinfo *ch = data; struct mss_info *mss = ch->parent; u_int32_t r; mss_lock(mss); r = mss_speed(ch, speed); mss_unlock(mss); return r; } static u_int32_t msschan_setblocksize(kobj_t obj, void *data, u_int32_t blocksize) { struct mss_chinfo *ch = data; ch->blksz = blocksize; sndbuf_resize(ch->buffer, 2, ch->blksz); return ch->blksz; } static int msschan_trigger(kobj_t obj, void *data, int go) { struct mss_chinfo *ch = data; struct mss_info *mss = ch->parent; if (!PCMTRIG_COMMON(go)) return 0; sndbuf_dma(ch->buffer, go); mss_lock(mss); mss_trigger(ch, go); mss_unlock(mss); return 0; } static u_int32_t msschan_getptr(kobj_t obj, void *data) { struct mss_chinfo *ch = data; return sndbuf_dmaptr(ch->buffer); } static struct pcmchan_caps * msschan_getcaps(kobj_t obj, void *data) { struct mss_chinfo *ch = data; switch(ch->parent->bd_id) { case MD_OPTI931: return &opti931_caps; break; case MD_GUSPNP: case MD_GUSMAX: return &guspnp_caps; break; default: return &mss_caps; break; } } static kobj_method_t msschan_methods[] = { KOBJMETHOD(channel_init, msschan_init), KOBJMETHOD(channel_setformat, msschan_setformat), KOBJMETHOD(channel_setspeed, msschan_setspeed), KOBJMETHOD(channel_setblocksize, msschan_setblocksize), KOBJMETHOD(channel_trigger, msschan_trigger), KOBJMETHOD(channel_getptr, msschan_getptr), KOBJMETHOD(channel_getcaps, msschan_getcaps), KOBJMETHOD_END }; CHANNEL_DECLARE(msschan); /* -------------------------------------------------------------------- */ /* * mss_probe() is the probe routine. Note, it is not necessary to * go through this for PnP devices, since they are already * indentified precisely using their PnP id. * * The base address supplied in the device refers to the old MSS * specs where the four 4 registers in io space contain configuration * information. Some boards (as an example, early MSS boards) * has such a block of registers, whereas others (generally CS42xx) * do not. In order to distinguish between the two and do not have * to supply two separate probe routines, the flags entry in isa_device * has a bit to mark this. * */ static int mss_probe(device_t dev) { u_char tmp, tmpx; int flags, irq, drq, result = ENXIO, setres = 0; struct mss_info *mss; if (isa_get_logicalid(dev)) return ENXIO; /* not yet */ mss = (struct mss_info *)malloc(sizeof *mss, M_DEVBUF, M_NOWAIT | M_ZERO); if (!mss) return ENXIO; mss->io_rid = 0; mss->conf_rid = -1; mss->irq_rid = 0; mss->drq1_rid = 0; mss->drq2_rid = -1; mss->io_base = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &mss->io_rid, 8, RF_ACTIVE); if (!mss->io_base) { BVDDB(printf("mss_probe: no address given, try 0x%x\n", 0x530)); mss->io_rid = 0; /* XXX verify this */ setres = 1; bus_set_resource(dev, SYS_RES_IOPORT, mss->io_rid, 0x530, 8); mss->io_base = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &mss->io_rid, 8, RF_ACTIVE); } if (!mss->io_base) goto no; /* got irq/dma regs? */ flags = device_get_flags(dev); irq = isa_get_irq(dev); drq = isa_get_drq(dev); if (!(device_get_flags(dev) & DV_F_TRUE_MSS)) goto mss_probe_end; /* * Check if the IO port returns valid signature. The original MS * Sound system returns 0x04 while some cards * (AudioTriX Pro for example) return 0x00 or 0x0f. */ device_set_desc(dev, "MSS"); tmpx = tmp = io_rd(mss, 3); if (tmp == 0xff) { /* Bus float */ BVDDB(printf("I/O addr inactive (%x), try pseudo_mss\n", tmp)); device_set_flags(dev, flags & ~DV_F_TRUE_MSS); goto mss_probe_end; } tmp &= 0x3f; if (!(tmp == 0x04 || tmp == 0x0f || tmp == 0x00 || tmp == 0x05)) { BVDDB(printf("No MSS signature detected on port 0x%jx (0x%x)\n", rman_get_start(mss->io_base), tmpx)); goto no; } if (irq > 11) { printf("MSS: Bad IRQ %d\n", irq); goto no; } if (!(drq == 0 || drq == 1 || drq == 3)) { printf("MSS: Bad DMA %d\n", drq); goto no; } if (tmpx & 0x80) { /* 8-bit board: only drq1/3 and irq7/9 */ if (drq == 0) { printf("MSS: Can't use DMA0 with a 8 bit card/slot\n"); goto no; } if (!(irq == 7 || irq == 9)) { printf("MSS: Can't use IRQ%d with a 8 bit card/slot\n", irq); goto no; } } mss_probe_end: result = mss_detect(dev, mss); no: mss_release_resources(mss, dev); #if 0 if (setres) ISA_DELETE_RESOURCE(device_get_parent(dev), dev, SYS_RES_IOPORT, mss->io_rid); /* XXX ? */ #endif return result; } static int mss_detect(device_t dev, struct mss_info *mss) { int i; u_char tmp = 0, tmp1, tmp2; char *name, *yamaha; if (mss->bd_id != 0) { device_printf(dev, "presel bd_id 0x%04x -- %s\n", mss->bd_id, device_get_desc(dev)); return 0; } name = "AD1848"; mss->bd_id = MD_AD1848; /* AD1848 or CS4248 */ if (opti_detect(dev, mss)) { switch (mss->bd_id) { case MD_OPTI924: name = "OPTi924"; break; case MD_OPTI930: name = "OPTi930"; break; } printf("Found OPTi device %s\n", name); if (opti_init(dev, mss) == 0) goto gotit; } /* * Check that the I/O address is in use. * * bit 7 of the base I/O port is known to be 0 after the chip has * performed its power on initialization. Just assume this has * happened before the OS is starting. * * If the I/O address is unused, it typically returns 0xff. */ for (i = 0; i < 10; i++) if ((tmp = io_rd(mss, MSS_INDEX)) & MSS_IDXBUSY) DELAY(10000); else break; if (i >= 10) { /* Not an AD1848 */ BVDDB(printf("mss_detect, busy still set (0x%02x)\n", tmp)); goto no; } /* * Test if it's possible to change contents of the indirect * registers. Registers 0 and 1 are ADC volume registers. The bit * 0x10 is read only so try to avoid using it. */ ad_write(mss, 0, 0xaa); ad_write(mss, 1, 0x45);/* 0x55 with bit 0x10 clear */ tmp1 = ad_read(mss, 0); tmp2 = ad_read(mss, 1); if (tmp1 != 0xaa || tmp2 != 0x45) { BVDDB(printf("mss_detect error - IREG (%x/%x)\n", tmp1, tmp2)); goto no; } ad_write(mss, 0, 0x45); ad_write(mss, 1, 0xaa); tmp1 = ad_read(mss, 0); tmp2 = ad_read(mss, 1); if (tmp1 != 0x45 || tmp2 != 0xaa) { BVDDB(printf("mss_detect error - IREG2 (%x/%x)\n", tmp1, tmp2)); goto no; } /* * The indirect register I12 has some read only bits. Lets try to * change them. */ tmp = ad_read(mss, 12); ad_write(mss, 12, (~tmp) & 0x0f); tmp1 = ad_read(mss, 12); if ((tmp & 0x0f) != (tmp1 & 0x0f)) { BVDDB(printf("mss_detect - I12 (0x%02x was 0x%02x)\n", tmp1, tmp)); goto no; } /* * NOTE! Last 4 bits of the reg I12 tell the chip revision. * 0x01=RevB * 0x0A=RevC. also CS4231/CS4231A and OPTi931 */ BVDDB(printf("mss_detect - chip revision 0x%02x\n", tmp & 0x0f);) /* * The original AD1848/CS4248 has just 16 indirect registers. This * means that I0 and I16 should return the same value (etc.). Ensure * that the Mode2 enable bit of I12 is 0. Otherwise this test fails * with new parts. */ ad_write(mss, 12, 0); /* Mode2=disabled */ #if 0 for (i = 0; i < 16; i++) { if ((tmp1 = ad_read(mss, i)) != (tmp2 = ad_read(mss, i + 16))) { BVDDB(printf("mss_detect warning - I%d: 0x%02x/0x%02x\n", i, tmp1, tmp2)); /* * note - this seems to fail on the 4232 on I11. So we just break * rather than fail. (which makes this test pointless - cg) */ break; /* return 0; */ } } #endif /* * Try to switch the chip to mode2 (CS4231) by setting the MODE2 bit * (0x40). The bit 0x80 is always 1 in CS4248 and CS4231. * * On the OPTi931, however, I12 is readonly and only contains the * chip revision ID (as in the CS4231A). The upper bits return 0. */ ad_write(mss, 12, 0x40); /* Set mode2, clear 0x80 */ tmp1 = ad_read(mss, 12); if (tmp1 & 0x80) name = "CS4248"; /* Our best knowledge just now */ if ((tmp1 & 0xf0) == 0x00) { BVDDB(printf("this should be an OPTi931\n");) } else if ((tmp1 & 0xc0) != 0xC0) goto gotit; /* * The 4231 has bit7=1 always, and bit6 we just set to 1. * We want to check that this is really a CS4231 * Verify that setting I0 doesn't change I16. */ ad_write(mss, 16, 0); /* Set I16 to known value */ ad_write(mss, 0, 0x45); if ((tmp1 = ad_read(mss, 16)) == 0x45) goto gotit; ad_write(mss, 0, 0xaa); if ((tmp1 = ad_read(mss, 16)) == 0xaa) { /* Rotten bits? */ BVDDB(printf("mss_detect error - step H(%x)\n", tmp1)); goto no; } /* Verify that some bits of I25 are read only. */ tmp1 = ad_read(mss, 25); /* Original bits */ ad_write(mss, 25, ~tmp1); /* Invert all bits */ if ((ad_read(mss, 25) & 0xe7) == (tmp1 & 0xe7)) { int id; /* It's at least CS4231 */ name = "CS4231"; mss->bd_id = MD_CS42XX; /* * It could be an AD1845 or CS4231A as well. * CS4231 and AD1845 report the same revision info in I25 * while the CS4231A reports different. */ id = ad_read(mss, 25) & 0xe7; /* * b7-b5 = version number; * 100 : all CS4231 * 101 : CS4231A * * b2-b0 = chip id; */ switch (id) { case 0xa0: name = "CS4231A"; mss->bd_id = MD_CS42XX; break; case 0xa2: name = "CS4232"; mss->bd_id = MD_CS42XX; break; case 0xb2: /* strange: the 4231 data sheet says b4-b3 are XX * so this should be the same as 0xa2 */ name = "CS4232A"; mss->bd_id = MD_CS42XX; break; case 0x80: /* * It must be a CS4231 or AD1845. The register I23 * of CS4231 is undefined and it appears to be read * only. AD1845 uses I23 for setting sample rate. * Assume the chip is AD1845 if I23 is changeable. */ tmp = ad_read(mss, 23); ad_write(mss, 23, ~tmp); if (ad_read(mss, 23) != tmp) { /* AD1845 ? */ name = "AD1845"; mss->bd_id = MD_AD1845; } ad_write(mss, 23, tmp); /* Restore */ yamaha = ymf_test(dev, mss); if (yamaha) { mss->bd_id = MD_YM0020; name = yamaha; } break; case 0x83: /* CS4236 */ case 0x03: /* CS4236 on Intel PR440FX motherboard XXX */ name = "CS4236"; mss->bd_id = MD_CS42XX; break; default: /* Assume CS4231 */ BVDDB(printf("unknown id 0x%02x, assuming CS4231\n", id);) mss->bd_id = MD_CS42XX; } } ad_write(mss, 25, tmp1); /* Restore bits */ gotit: BVDDB(printf("mss_detect() - Detected %s\n", name)); device_set_desc(dev, name); device_set_flags(dev, ((device_get_flags(dev) & ~DV_F_DEV_MASK) | ((mss->bd_id << DV_F_DEV_SHIFT) & DV_F_DEV_MASK))); return 0; no: return ENXIO; } static int opti_detect(device_t dev, struct mss_info *mss) { int c; static const struct opticard { int boardid; int passwdreg; int password; int base; int indir_reg; } cards[] = { { MD_OPTI930, 0, 0xe4, 0xf8f, 0xe0e }, /* 930 */ { MD_OPTI924, 3, 0xe5, 0xf8c, 0, }, /* 924 */ { 0 }, }; mss->conf_rid = 3; mss->indir_rid = 4; for (c = 0; cards[c].base; c++) { mss->optibase = cards[c].base; mss->password = cards[c].password; mss->passwdreg = cards[c].passwdreg; mss->bd_id = cards[c].boardid; if (cards[c].indir_reg) mss->indir = bus_alloc_resource(dev, SYS_RES_IOPORT, &mss->indir_rid, cards[c].indir_reg, cards[c].indir_reg+1, 1, RF_ACTIVE); mss->conf_base = bus_alloc_resource(dev, SYS_RES_IOPORT, &mss->conf_rid, mss->optibase, mss->optibase+9, 9, RF_ACTIVE); if (opti_read(mss, 1) != 0xff) { return 1; } else { if (mss->indir) bus_release_resource(dev, SYS_RES_IOPORT, mss->indir_rid, mss->indir); mss->indir = NULL; if (mss->conf_base) bus_release_resource(dev, SYS_RES_IOPORT, mss->conf_rid, mss->conf_base); mss->conf_base = NULL; } } return 0; } static char * ymf_test(device_t dev, struct mss_info *mss) { static int ports[] = {0x370, 0x310, 0x538}; int p, i, j, version; static char *chipset[] = { NULL, /* 0 */ "OPL3-SA2 (YMF711)", /* 1 */ "OPL3-SA3 (YMF715)", /* 2 */ "OPL3-SA3 (YMF715)", /* 3 */ "OPL3-SAx (YMF719)", /* 4 */ "OPL3-SAx (YMF719)", /* 5 */ "OPL3-SAx (YMF719)", /* 6 */ "OPL3-SAx (YMF719)", /* 7 */ }; for (p = 0; p < 3; p++) { mss->conf_rid = 1; mss->conf_base = bus_alloc_resource(dev, SYS_RES_IOPORT, &mss->conf_rid, ports[p], ports[p] + 1, 2, RF_ACTIVE); if (!mss->conf_base) return 0; /* Test the index port of the config registers */ i = port_rd(mss->conf_base, 0); port_wr(mss->conf_base, 0, OPL3SAx_DMACONF); j = (port_rd(mss->conf_base, 0) == OPL3SAx_DMACONF)? 1 : 0; port_wr(mss->conf_base, 0, i); if (!j) { bus_release_resource(dev, SYS_RES_IOPORT, mss->conf_rid, mss->conf_base); mss->conf_base = NULL; continue; } version = conf_rd(mss, OPL3SAx_MISC) & 0x07; return chipset[version]; } return NULL; } static int mss_doattach(device_t dev, struct mss_info *mss) { int pdma, rdma, flags = device_get_flags(dev); char status[SND_STATUSLEN], status2[SND_STATUSLEN]; mss->lock = snd_mtxcreate(device_get_nameunit(dev), "snd_mss softc"); mss->bufsize = pcm_getbuffersize(dev, 4096, MSS_DEFAULT_BUFSZ, 65536); if (!mss_alloc_resources(mss, dev)) goto no; mss_init(mss, dev); pdma = rman_get_start(mss->drq1); rdma = rman_get_start(mss->drq2); if (flags & DV_F_TRUE_MSS) { /* has IRQ/DMA registers, set IRQ and DMA addr */ static char interrupt_bits[12] = {-1, -1, -1, -1, -1, 0x28, -1, 0x08, -1, 0x10, 0x18, 0x20}; static char pdma_bits[4] = {1, 2, -1, 3}; static char valid_rdma[4] = {1, 0, -1, 0}; char bits; if (!mss->irq || (bits = interrupt_bits[rman_get_start(mss->irq)]) == -1) goto no; io_wr(mss, 0, bits | 0x40); /* config port */ if ((io_rd(mss, 3) & 0x40) == 0) device_printf(dev, "IRQ Conflict?\n"); /* Write IRQ+DMA setup */ if (pdma_bits[pdma] == -1) goto no; bits |= pdma_bits[pdma]; if (pdma != rdma) { if (rdma == valid_rdma[pdma]) bits |= 4; else { printf("invalid dual dma config %d:%d\n", pdma, rdma); goto no; } } io_wr(mss, 0, bits); printf("drq/irq conf %x\n", io_rd(mss, 0)); } mixer_init(dev, (mss->bd_id == MD_YM0020)? &ymmix_mixer_class : &mssmix_mixer_class, mss); switch (mss->bd_id) { case MD_OPTI931: snd_setup_intr(dev, mss->irq, 0, opti931_intr, mss, &mss->ih); break; default: snd_setup_intr(dev, mss->irq, 0, mss_intr, mss, &mss->ih); } if (pdma == rdma) pcm_setflags(dev, pcm_getflags(dev) | SD_F_SIMPLEX); if (bus_dma_tag_create(/*parent*/bus_get_dma_tag(dev), /*alignment*/2, /*boundary*/0, /*lowaddr*/BUS_SPACE_MAXADDR_24BIT, /*highaddr*/BUS_SPACE_MAXADDR, /*filter*/NULL, /*filterarg*/NULL, /*maxsize*/mss->bufsize, /*nsegments*/1, /*maxsegz*/0x3ffff, /*flags*/0, /*lockfunc*/busdma_lock_mutex, /*lockarg*/&Giant, &mss->parent_dmat) != 0) { device_printf(dev, "unable to create dma tag\n"); goto no; } if (pdma != rdma) snprintf(status2, SND_STATUSLEN, ":%d", rdma); else status2[0] = '\0'; snprintf(status, SND_STATUSLEN, "at io 0x%jx irq %jd drq %d%s bufsz %u", rman_get_start(mss->io_base), rman_get_start(mss->irq), pdma, status2, mss->bufsize); if (pcm_register(dev, mss, 1, 1)) goto no; pcm_addchan(dev, PCMDIR_REC, &msschan_class, mss); pcm_addchan(dev, PCMDIR_PLAY, &msschan_class, mss); pcm_setstatus(dev, status); return 0; no: mss_release_resources(mss, dev); return ENXIO; } static int mss_detach(device_t dev) { int r; struct mss_info *mss; r = pcm_unregister(dev); if (r) return r; mss = pcm_getdevinfo(dev); mss_release_resources(mss, dev); return 0; } static int mss_attach(device_t dev) { struct mss_info *mss; int flags = device_get_flags(dev); mss = (struct mss_info *)malloc(sizeof *mss, M_DEVBUF, M_NOWAIT | M_ZERO); if (!mss) return ENXIO; mss->io_rid = 0; mss->conf_rid = -1; mss->irq_rid = 0; mss->drq1_rid = 0; mss->drq2_rid = -1; if (flags & DV_F_DUAL_DMA) { bus_set_resource(dev, SYS_RES_DRQ, 1, flags & DV_F_DRQ_MASK, 1); mss->drq2_rid = 1; } mss->bd_id = (device_get_flags(dev) & DV_F_DEV_MASK) >> DV_F_DEV_SHIFT; if (mss->bd_id == MD_YM0020) ymf_test(dev, mss); return mss_doattach(dev, mss); } /* * mss_resume() is the code to allow a laptop to resume using the sound * card. * * This routine re-sets the state of the board to the state before going * to sleep. According to the yamaha docs this is the right thing to do, * but getting DMA restarted appears to be a bit of a trick, so the device * has to be closed and re-opened to be re-used, but there is no skipping * problem, and volume, bass/treble and most other things are restored * properly. * */ static int mss_resume(device_t dev) { /* * Restore the state taken below. */ struct mss_info *mss; int i; mss = pcm_getdevinfo(dev); if(mss->bd_id == MD_YM0020 || mss->bd_id == MD_CS423X) { /* This works on a Toshiba Libretto 100CT. */ for (i = 0; i < MSS_INDEXED_REGS; i++) ad_write(mss, i, mss->mss_indexed_regs[i]); for (i = 0; i < OPL_INDEXED_REGS; i++) conf_wr(mss, i, mss->opl_indexed_regs[i]); mss_intr(mss); } if (mss->bd_id == MD_CS423X) { /* Needed on IBM Thinkpad 600E */ mss_lock(mss); mss_format(&mss->pch, mss->pch.channel->format); mss_speed(&mss->pch, mss->pch.channel->speed); mss_unlock(mss); } return 0; } /* * mss_suspend() is the code that gets called right before a laptop * suspends. * * This code saves the state of the sound card right before shutdown * so it can be restored above. * */ static int mss_suspend(device_t dev) { int i; struct mss_info *mss; mss = pcm_getdevinfo(dev); if(mss->bd_id == MD_YM0020 || mss->bd_id == MD_CS423X) { /* this stops playback. */ conf_wr(mss, 0x12, 0x0c); for(i = 0; i < MSS_INDEXED_REGS; i++) mss->mss_indexed_regs[i] = ad_read(mss, i); for(i = 0; i < OPL_INDEXED_REGS; i++) mss->opl_indexed_regs[i] = conf_rd(mss, i); mss->opl_indexed_regs[0x12] = 0x0; } return 0; } static device_method_t mss_methods[] = { /* Device interface */ DEVMETHOD(device_probe, mss_probe), DEVMETHOD(device_attach, mss_attach), DEVMETHOD(device_detach, mss_detach), DEVMETHOD(device_suspend, mss_suspend), DEVMETHOD(device_resume, mss_resume), { 0, 0 } }; static driver_t mss_driver = { "pcm", mss_methods, PCM_SOFTC_SIZE, }; DRIVER_MODULE(snd_mss, isa, mss_driver, pcm_devclass, 0, 0); MODULE_DEPEND(snd_mss, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_VERSION(snd_mss, 1); static int azt2320_mss_mode(struct mss_info *mss, device_t dev) { struct resource *sbport; int i, ret, rid; rid = 0; ret = -1; sbport = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid, RF_ACTIVE); if (sbport) { for (i = 0; i < 1000; i++) { if ((port_rd(sbport, SBDSP_STATUS) & 0x80)) DELAY((i > 100) ? 1000 : 10); else { port_wr(sbport, SBDSP_CMD, 0x09); break; } } for (i = 0; i < 1000; i++) { if ((port_rd(sbport, SBDSP_STATUS) & 0x80)) DELAY((i > 100) ? 1000 : 10); else { port_wr(sbport, SBDSP_CMD, 0x00); ret = 0; break; } } DELAY(1000); bus_release_resource(dev, SYS_RES_IOPORT, rid, sbport); } return ret; } static struct isa_pnp_id pnpmss_ids[] = { {0x0000630e, "CS423x"}, /* CSC0000 */ {0x0001630e, "CS423x-PCI"}, /* CSC0100 */ {0x01000000, "CMI8330"}, /* @@@0001 */ {0x2100a865, "Yamaha OPL-SAx"}, /* YMH0021 */ {0x1110d315, "ENSONIQ SoundscapeVIVO"}, /* ENS1011 */ {0x1093143e, "OPTi931"}, /* OPT9310 */ {0x5092143e, "OPTi925"}, /* OPT9250 XXX guess */ {0x0000143e, "OPTi924"}, /* OPT0924 */ {0x1022b839, "Neomagic 256AV (non-ac97)"}, /* NMX2210 */ {0x01005407, "Aztech 2320"}, /* AZT0001 */ #if 0 {0x0000561e, "GusPnP"}, /* GRV0000 */ #endif {0}, }; static int pnpmss_probe(device_t dev) { u_int32_t lid, vid; lid = isa_get_logicalid(dev); vid = isa_get_vendorid(dev); if (lid == 0x01000000 && vid != 0x0100a90d) /* CMI0001 */ return ENXIO; return ISA_PNP_PROBE(device_get_parent(dev), dev, pnpmss_ids); } static int pnpmss_attach(device_t dev) { struct mss_info *mss; mss = malloc(sizeof(*mss), M_DEVBUF, M_WAITOK | M_ZERO); mss->io_rid = 0; mss->conf_rid = -1; mss->irq_rid = 0; mss->drq1_rid = 0; mss->drq2_rid = 1; mss->bd_id = MD_CS42XX; switch (isa_get_logicalid(dev)) { case 0x0000630e: /* CSC0000 */ case 0x0001630e: /* CSC0100 */ mss->bd_flags |= BD_F_MSS_OFFSET; mss->bd_id = MD_CS423X; break; case 0x2100a865: /* YHM0021 */ mss->io_rid = 1; mss->conf_rid = 4; mss->bd_id = MD_YM0020; break; case 0x1110d315: /* ENS1011 */ mss->io_rid = 1; mss->bd_id = MD_VIVO; break; case 0x1093143e: /* OPT9310 */ mss->bd_flags |= BD_F_MSS_OFFSET; mss->conf_rid = 3; mss->bd_id = MD_OPTI931; break; case 0x5092143e: /* OPT9250 XXX guess */ mss->io_rid = 1; mss->conf_rid = 3; mss->bd_id = MD_OPTI925; break; case 0x0000143e: /* OPT0924 */ mss->password = 0xe5; mss->passwdreg = 3; mss->optibase = 0xf0c; mss->io_rid = 2; mss->conf_rid = 3; mss->bd_id = MD_OPTI924; mss->bd_flags |= BD_F_924PNP; if(opti_init(dev, mss) != 0) { free(mss, M_DEVBUF); return ENXIO; } break; case 0x1022b839: /* NMX2210 */ mss->io_rid = 1; break; case 0x01005407: /* AZT0001 */ /* put into MSS mode first (snatched from NetBSD) */ if (azt2320_mss_mode(mss, dev) == -1) { free(mss, M_DEVBUF); return ENXIO; } mss->bd_flags |= BD_F_MSS_OFFSET; mss->io_rid = 2; break; #if 0 case 0x0000561e: /* GRV0000 */ mss->bd_flags |= BD_F_MSS_OFFSET; mss->io_rid = 2; mss->conf_rid = 1; mss->drq1_rid = 1; mss->drq2_rid = 0; mss->bd_id = MD_GUSPNP; break; #endif case 0x01000000: /* @@@0001 */ mss->drq2_rid = -1; break; /* Unknown MSS default. We could let the CSC0000 stuff match too */ default: mss->bd_flags |= BD_F_MSS_OFFSET; break; } return mss_doattach(dev, mss); } static int opti_init(device_t dev, struct mss_info *mss) { int flags = device_get_flags(dev); int basebits = 0; if (!mss->conf_base) { bus_set_resource(dev, SYS_RES_IOPORT, mss->conf_rid, mss->optibase, 0x9); mss->conf_base = bus_alloc_resource(dev, SYS_RES_IOPORT, &mss->conf_rid, mss->optibase, mss->optibase+0x9, 0x9, RF_ACTIVE); } if (!mss->conf_base) return ENXIO; if (!mss->io_base) mss->io_base = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &mss->io_rid, 8, RF_ACTIVE); if (!mss->io_base) /* No hint specified, use 0x530 */ mss->io_base = bus_alloc_resource(dev, SYS_RES_IOPORT, &mss->io_rid, 0x530, 0x537, 8, RF_ACTIVE); if (!mss->io_base) return ENXIO; switch (rman_get_start(mss->io_base)) { case 0x530: basebits = 0x0; break; case 0xe80: basebits = 0x10; break; case 0xf40: basebits = 0x20; break; case 0x604: basebits = 0x30; break; default: printf("opti_init: invalid MSS base address!\n"); return ENXIO; } switch (mss->bd_id) { case MD_OPTI924: opti_write(mss, 1, 0x80 | basebits); /* MSS mode */ opti_write(mss, 2, 0x00); /* Disable CD */ opti_write(mss, 3, 0xf0); /* Disable SB IRQ */ opti_write(mss, 4, 0xf0); opti_write(mss, 5, 0x00); opti_write(mss, 6, 0x02); /* MPU stuff */ break; case MD_OPTI930: opti_write(mss, 1, 0x00 | basebits); opti_write(mss, 3, 0x00); /* Disable SB IRQ/DMA */ opti_write(mss, 4, 0x52); /* Empty FIFO */ opti_write(mss, 5, 0x3c); /* Mode 2 */ opti_write(mss, 6, 0x02); /* Enable MSS */ break; } if (mss->bd_flags & BD_F_924PNP) { u_int32_t irq = isa_get_irq(dev); u_int32_t drq = isa_get_drq(dev); bus_set_resource(dev, SYS_RES_IRQ, 0, irq, 1); bus_set_resource(dev, SYS_RES_DRQ, mss->drq1_rid, drq, 1); if (flags & DV_F_DUAL_DMA) { bus_set_resource(dev, SYS_RES_DRQ, 1, flags & DV_F_DRQ_MASK, 1); mss->drq2_rid = 1; } } /* OPTixxx has I/DRQ registers */ device_set_flags(dev, device_get_flags(dev) | DV_F_TRUE_MSS); return 0; } static void opti_write(struct mss_info *mss, u_char reg, u_char val) { port_wr(mss->conf_base, mss->passwdreg, mss->password); switch(mss->bd_id) { case MD_OPTI924: if (reg > 7) { /* Indirect register */ port_wr(mss->conf_base, mss->passwdreg, reg); port_wr(mss->conf_base, mss->passwdreg, mss->password); port_wr(mss->conf_base, 9, val); return; } port_wr(mss->conf_base, reg, val); break; case MD_OPTI930: port_wr(mss->indir, 0, reg); port_wr(mss->conf_base, mss->passwdreg, mss->password); port_wr(mss->indir, 1, val); break; } } u_char opti_read(struct mss_info *mss, u_char reg) { port_wr(mss->conf_base, mss->passwdreg, mss->password); switch(mss->bd_id) { case MD_OPTI924: if (reg > 7) { /* Indirect register */ port_wr(mss->conf_base, mss->passwdreg, reg); port_wr(mss->conf_base, mss->passwdreg, mss->password); return(port_rd(mss->conf_base, 9)); } return(port_rd(mss->conf_base, reg)); break; case MD_OPTI930: port_wr(mss->indir, 0, reg); port_wr(mss->conf_base, mss->passwdreg, mss->password); return port_rd(mss->indir, 1); break; } return -1; } static device_method_t pnpmss_methods[] = { /* Device interface */ DEVMETHOD(device_probe, pnpmss_probe), DEVMETHOD(device_attach, pnpmss_attach), DEVMETHOD(device_detach, mss_detach), DEVMETHOD(device_suspend, mss_suspend), DEVMETHOD(device_resume, mss_resume), { 0, 0 } }; static driver_t pnpmss_driver = { "pcm", pnpmss_methods, PCM_SOFTC_SIZE, }; DRIVER_MODULE(snd_pnpmss, isa, pnpmss_driver, pcm_devclass, 0, 0); DRIVER_MODULE(snd_pnpmss, acpi, pnpmss_driver, pcm_devclass, 0, 0); MODULE_DEPEND(snd_pnpmss, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_VERSION(snd_pnpmss, 1); static int guspcm_probe(device_t dev) { struct sndcard_func *func; func = device_get_ivars(dev); if (func == NULL || func->func != SCF_PCM) return ENXIO; device_set_desc(dev, "GUS CS4231"); return 0; } static int guspcm_attach(device_t dev) { device_t parent = device_get_parent(dev); struct mss_info *mss; int base, flags; unsigned char ctl; mss = (struct mss_info *)malloc(sizeof *mss, M_DEVBUF, M_NOWAIT | M_ZERO); if (mss == NULL) return ENOMEM; mss->bd_flags = BD_F_MSS_OFFSET; mss->io_rid = 2; mss->conf_rid = 1; mss->irq_rid = 0; mss->drq1_rid = 1; mss->drq2_rid = -1; if (isa_get_logicalid(parent) == 0) mss->bd_id = MD_GUSMAX; else { mss->bd_id = MD_GUSPNP; mss->drq2_rid = 0; goto skip_setup; } flags = device_get_flags(parent); if (flags & DV_F_DUAL_DMA) mss->drq2_rid = 0; mss->conf_base = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &mss->conf_rid, 8, RF_ACTIVE); if (mss->conf_base == NULL) { mss_release_resources(mss, dev); return ENXIO; } base = isa_get_port(parent); ctl = 0x40; /* CS4231 enable */ if (isa_get_drq(dev) > 3) ctl |= 0x10; /* 16-bit dma channel 1 */ if ((flags & DV_F_DUAL_DMA) != 0 && (flags & DV_F_DRQ_MASK) > 3) ctl |= 0x20; /* 16-bit dma channel 2 */ ctl |= (base >> 4) & 0x0f; /* 2X0 -> 3XC */ port_wr(mss->conf_base, 6, ctl); skip_setup: return mss_doattach(dev, mss); } static device_method_t guspcm_methods[] = { DEVMETHOD(device_probe, guspcm_probe), DEVMETHOD(device_attach, guspcm_attach), DEVMETHOD(device_detach, mss_detach), { 0, 0 } }; static driver_t guspcm_driver = { "pcm", guspcm_methods, PCM_SOFTC_SIZE, }; DRIVER_MODULE(snd_guspcm, gusc, guspcm_driver, pcm_devclass, 0, 0); MODULE_DEPEND(snd_guspcm, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_VERSION(snd_guspcm, 1); - - +ISA_PNP_INFO(pnpmss_ids); Index: head/sys/dev/sound/isa/sbc.c =================================================================== --- head/sys/dev/sound/isa/sbc.c (revision 328523) +++ head/sys/dev/sound/isa/sbc.c (revision 328524) @@ -1,752 +1,753 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1999 Seigo Tanimura * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" #endif #include #include #include #include SND_DECLARE_FILE("$FreeBSD$"); #define IO_MAX 3 #define IRQ_MAX 1 #define DRQ_MAX 2 #define INTR_MAX 2 struct sbc_softc; struct sbc_ihl { driver_intr_t *intr[INTR_MAX]; void *intr_arg[INTR_MAX]; struct sbc_softc *parent; }; /* Here is the parameter structure per a device. */ struct sbc_softc { device_t dev; /* device */ device_t child_pcm, child_midi1, child_midi2; int io_rid[IO_MAX]; /* io port rids */ struct resource *io[IO_MAX]; /* io port resources */ int io_alloced[IO_MAX]; /* io port alloc flag */ int irq_rid[IRQ_MAX]; /* irq rids */ struct resource *irq[IRQ_MAX]; /* irq resources */ int irq_alloced[IRQ_MAX]; /* irq alloc flag */ int drq_rid[DRQ_MAX]; /* drq rids */ struct resource *drq[DRQ_MAX]; /* drq resources */ int drq_alloced[DRQ_MAX]; /* drq alloc flag */ struct sbc_ihl ihl[IRQ_MAX]; void *ih[IRQ_MAX]; struct mtx *lock; u_int32_t bd_ver; }; static int sbc_probe(device_t dev); static int sbc_attach(device_t dev); static void sbc_intr(void *p); static struct resource *sbc_alloc_resource(device_t bus, device_t child, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags); static int sbc_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r); static int sbc_setup_intr(device_t dev, device_t child, struct resource *irq, int flags, driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep); static int sbc_teardown_intr(device_t dev, device_t child, struct resource *irq, void *cookie); static int alloc_resource(struct sbc_softc *scp); static int release_resource(struct sbc_softc *scp); static devclass_t sbc_devclass; static int io_range[3] = {0x10, 0x2, 0x4}; static int sb_rd(struct resource *io, int reg); static void sb_wr(struct resource *io, int reg, u_int8_t val); static int sb_dspready(struct resource *io); static int sb_cmd(struct resource *io, u_char val); static u_int sb_get_byte(struct resource *io); static void sb_setmixer(struct resource *io, u_int port, u_int value); static void sbc_lockinit(struct sbc_softc *scp) { scp->lock = snd_mtxcreate(device_get_nameunit(scp->dev), "snd_sbc softc"); } static void sbc_lockdestroy(struct sbc_softc *scp) { snd_mtxfree(scp->lock); } void sbc_lock(struct sbc_softc *scp) { snd_mtxlock(scp->lock); } void sbc_lockassert(struct sbc_softc *scp) { snd_mtxassert(scp->lock); } void sbc_unlock(struct sbc_softc *scp) { snd_mtxunlock(scp->lock); } static int sb_rd(struct resource *io, int reg) { return bus_space_read_1(rman_get_bustag(io), rman_get_bushandle(io), reg); } static void sb_wr(struct resource *io, int reg, u_int8_t val) { bus_space_write_1(rman_get_bustag(io), rman_get_bushandle(io), reg, val); } static int sb_dspready(struct resource *io) { return ((sb_rd(io, SBDSP_STATUS) & 0x80) == 0); } static int sb_dspwr(struct resource *io, u_char val) { int i; for (i = 0; i < 1000; i++) { if (sb_dspready(io)) { sb_wr(io, SBDSP_CMD, val); return 1; } if (i > 10) DELAY((i > 100)? 1000 : 10); } printf("sb_dspwr(0x%02x) timed out.\n", val); return 0; } static int sb_cmd(struct resource *io, u_char val) { return sb_dspwr(io, val); } static void sb_setmixer(struct resource *io, u_int port, u_int value) { u_long flags; flags = spltty(); sb_wr(io, SB_MIX_ADDR, (u_char) (port & 0xff)); /* Select register */ DELAY(10); sb_wr(io, SB_MIX_DATA, (u_char) (value & 0xff)); DELAY(10); splx(flags); } static u_int sb_get_byte(struct resource *io) { int i; for (i = 1000; i > 0; i--) { if (sb_rd(io, DSP_DATA_AVAIL) & 0x80) return sb_rd(io, DSP_READ); else DELAY(20); } return 0xffff; } static int sb_reset_dsp(struct resource *io) { sb_wr(io, SBDSP_RST, 3); DELAY(100); sb_wr(io, SBDSP_RST, 0); return (sb_get_byte(io) == 0xAA)? 0 : ENXIO; } static int sb_identify_board(struct resource *io) { int ver, essver, rev; sb_cmd(io, DSP_CMD_GETVER); /* Get version */ ver = (sb_get_byte(io) << 8) | sb_get_byte(io); if (ver < 0x100 || ver > 0x4ff) return 0; if (ver == 0x0301) { /* Try to detect ESS chips. */ sb_cmd(io, DSP_CMD_GETID); /* Return ident. bytes. */ essver = (sb_get_byte(io) << 8) | sb_get_byte(io); rev = essver & 0x000f; essver &= 0xfff0; if (essver == 0x4880) ver |= 0x1000; else if (essver == 0x6880) ver = 0x0500 | rev; } return ver; } static struct isa_pnp_id sbc_ids[] = { {0x01008c0e, "Creative ViBRA16C"}, /* CTL0001 */ {0x31008c0e, "Creative SB16/SB32"}, /* CTL0031 */ {0x41008c0e, "Creative SB16/SB32"}, /* CTL0041 */ {0x42008c0e, "Creative SB AWE64"}, /* CTL0042 */ {0x43008c0e, "Creative ViBRA16X"}, /* CTL0043 */ {0x44008c0e, "Creative SB AWE64 Gold"}, /* CTL0044 */ {0x45008c0e, "Creative SB AWE64"}, /* CTL0045 */ {0x46008c0e, "Creative SB AWE64"}, /* CTL0046 */ {0x01000000, "Avance Logic ALS100+"}, /* @@@0001 - ViBRA16X clone */ {0x01100000, "Avance Asound 110"}, /* @@@1001 */ {0x01200000, "Avance Logic ALS120"}, /* @@@2001 - ViBRA16X clone */ {0x81167316, "ESS ES1681"}, /* ESS1681 */ {0x02017316, "ESS ES1688"}, /* ESS1688 */ {0x68097316, "ESS ES1688"}, /* ESS1688 */ {0x68187316, "ESS ES1868"}, /* ESS1868 */ {0x03007316, "ESS ES1869"}, /* ESS1869 */ {0x69187316, "ESS ES1869"}, /* ESS1869 */ {0xabb0110e, "ESS ES1869 (Compaq OEM)"}, /* CPQb0ab */ {0xacb0110e, "ESS ES1869 (Compaq OEM)"}, /* CPQb0ac */ {0x78187316, "ESS ES1878"}, /* ESS1878 */ {0x79187316, "ESS ES1879"}, /* ESS1879 */ {0x88187316, "ESS ES1888"}, /* ESS1888 */ {0x07017316, "ESS ES1888 (DEC OEM)"}, /* ESS0107 */ {0x06017316, "ESS ES1888 (Dell OEM)"}, /* ESS0106 */ {0} }; static int sbc_probe(device_t dev) { char *s = NULL; u_int32_t lid, vid; lid = isa_get_logicalid(dev); vid = isa_get_vendorid(dev); if (lid) { if (lid == 0x01000000 && vid != 0x01009305) /* ALS0001 */ return ENXIO; /* Check pnp ids */ return ISA_PNP_PROBE(device_get_parent(dev), dev, sbc_ids); } else { int rid = 0, ver; struct resource *io; io = bus_alloc_resource_anywhere(dev, SYS_RES_IOPORT, &rid, 16, RF_ACTIVE); if (!io) goto bad; if (sb_reset_dsp(io)) goto bad2; ver = sb_identify_board(io); if (ver == 0) goto bad2; switch ((ver & 0x00000f00) >> 8) { case 1: device_set_desc(dev, "SoundBlaster 1.0 (not supported)"); s = NULL; break; case 2: s = "SoundBlaster 2.0"; break; case 3: s = (ver & 0x0000f000)? "ESS 488" : "SoundBlaster Pro"; break; case 4: s = "SoundBlaster 16"; break; case 5: s = (ver & 0x00000008)? "ESS 688" : "ESS 1688"; break; } if (s) device_set_desc(dev, s); bad2: bus_release_resource(dev, SYS_RES_IOPORT, rid, io); bad: return s? 0 : ENXIO; } } static int sbc_attach(device_t dev) { char *err = NULL; struct sbc_softc *scp; struct sndcard_func *func; u_int32_t logical_id = isa_get_logicalid(dev); int flags = device_get_flags(dev); int f, dh, dl, x, irq, i; if (!logical_id && (flags & DV_F_DUAL_DMA)) { bus_set_resource(dev, SYS_RES_DRQ, 1, flags & DV_F_DRQ_MASK, 1); } scp = device_get_softc(dev); bzero(scp, sizeof(*scp)); scp->dev = dev; sbc_lockinit(scp); err = "alloc_resource"; if (alloc_resource(scp)) goto bad; err = "sb_reset_dsp"; if (sb_reset_dsp(scp->io[0])) goto bad; err = "sb_identify_board"; scp->bd_ver = sb_identify_board(scp->io[0]) & 0x00000fff; if (scp->bd_ver == 0) goto bad; f = 0; if (logical_id == 0x01200000 && scp->bd_ver < 0x0400) scp->bd_ver = 0x0499; switch ((scp->bd_ver & 0x0f00) >> 8) { case 1: /* old sound blaster has nothing... */ break; case 2: f |= BD_F_DUP_MIDI; if (scp->bd_ver > 0x200) f |= BD_F_MIX_CT1335; break; case 5: f |= BD_F_ESS; scp->bd_ver = 0x0301; case 3: f |= BD_F_DUP_MIDI | BD_F_MIX_CT1345; break; case 4: f |= BD_F_SB16 | BD_F_MIX_CT1745; if (scp->drq[0]) dl = rman_get_start(scp->drq[0]); else dl = -1; if (scp->drq[1]) dh = rman_get_start(scp->drq[1]); else dh = dl; if (!logical_id && (dh < dl)) { struct resource *r; r = scp->drq[0]; scp->drq[0] = scp->drq[1]; scp->drq[1] = r; dl = rman_get_start(scp->drq[0]); dh = rman_get_start(scp->drq[1]); } /* soft irq/dma configuration */ x = -1; irq = rman_get_start(scp->irq[0]); if (irq == 5) x = 2; else if (irq == 7) x = 4; else if (irq == 9) x = 1; else if (irq == 10) x = 8; if (x == -1) { err = "bad irq (5/7/9/10 valid)"; goto bad; } else sb_setmixer(scp->io[0], IRQ_NR, x); sb_setmixer(scp->io[0], DMA_NR, (1 << dh) | (1 << dl)); if (bootverbose) { device_printf(dev, "setting card to irq %d, drq %d", irq, dl); if (dl != dh) printf(", %d", dh); printf("\n"); } break; } switch (logical_id) { case 0x43008c0e: /* CTL0043 */ case 0x01200000: case 0x01000000: f |= BD_F_SB16X; break; } scp->bd_ver |= f << 16; err = "setup_intr"; for (i = 0; i < IRQ_MAX; i++) { scp->ihl[i].parent = scp; if (snd_setup_intr(dev, scp->irq[i], 0, sbc_intr, &scp->ihl[i], &scp->ih[i])) goto bad; } /* PCM Audio */ func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) goto bad; func->func = SCF_PCM; scp->child_pcm = device_add_child(dev, "pcm", -1); device_set_ivars(scp->child_pcm, func); /* Midi Interface */ func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) goto bad; func->func = SCF_MIDI; scp->child_midi1 = device_add_child(dev, "midi", -1); device_set_ivars(scp->child_midi1, func); /* OPL FM Synthesizer */ func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO); if (func == NULL) goto bad; func->func = SCF_SYNTH; scp->child_midi2 = device_add_child(dev, "midi", -1); device_set_ivars(scp->child_midi2, func); /* probe/attach kids */ bus_generic_attach(dev); return (0); bad: if (err) device_printf(dev, "%s\n", err); release_resource(scp); return (ENXIO); } static int sbc_detach(device_t dev) { struct sbc_softc *scp = device_get_softc(dev); sbc_lock(scp); device_delete_child(dev, scp->child_midi2); device_delete_child(dev, scp->child_midi1); device_delete_child(dev, scp->child_pcm); release_resource(scp); sbc_lockdestroy(scp); return bus_generic_detach(dev); } static void sbc_intr(void *p) { struct sbc_ihl *ihl = p; int i; /* sbc_lock(ihl->parent); */ i = 0; while (i < INTR_MAX) { if (ihl->intr[i] != NULL) ihl->intr[i](ihl->intr_arg[i]); i++; } /* sbc_unlock(ihl->parent); */ } static int sbc_setup_intr(device_t dev, device_t child, struct resource *irq, int flags, driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep) { struct sbc_softc *scp = device_get_softc(dev); struct sbc_ihl *ihl = NULL; int i, ret; if (filter != NULL) { printf("sbc.c: we cannot use a filter here\n"); return (EINVAL); } sbc_lock(scp); i = 0; while (i < IRQ_MAX) { if (irq == scp->irq[i]) ihl = &scp->ihl[i]; i++; } ret = 0; if (ihl == NULL) ret = EINVAL; i = 0; while ((ret == 0) && (i < INTR_MAX)) { if (ihl->intr[i] == NULL) { ihl->intr[i] = intr; ihl->intr_arg[i] = arg; *cookiep = &ihl->intr[i]; ret = -1; } else i++; } sbc_unlock(scp); return (ret > 0)? EINVAL : 0; } static int sbc_teardown_intr(device_t dev, device_t child, struct resource *irq, void *cookie) { struct sbc_softc *scp = device_get_softc(dev); struct sbc_ihl *ihl = NULL; int i, ret; sbc_lock(scp); i = 0; while (i < IRQ_MAX) { if (irq == scp->irq[i]) ihl = &scp->ihl[i]; i++; } ret = 0; if (ihl == NULL) ret = EINVAL; i = 0; while ((ret == 0) && (i < INTR_MAX)) { if (cookie == &ihl->intr[i]) { ihl->intr[i] = NULL; ihl->intr_arg[i] = NULL; return 0; } else i++; } sbc_unlock(scp); return (ret > 0)? EINVAL : 0; } static struct resource * sbc_alloc_resource(device_t bus, device_t child, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) { struct sbc_softc *scp; int *alloced, rid_max, alloced_max; struct resource **res; scp = device_get_softc(bus); switch (type) { case SYS_RES_IOPORT: alloced = scp->io_alloced; res = scp->io; rid_max = IO_MAX - 1; alloced_max = 1; break; case SYS_RES_DRQ: alloced = scp->drq_alloced; res = scp->drq; rid_max = DRQ_MAX - 1; alloced_max = 1; break; case SYS_RES_IRQ: alloced = scp->irq_alloced; res = scp->irq; rid_max = IRQ_MAX - 1; alloced_max = INTR_MAX; /* pcm and mpu may share the irq. */ break; default: return (NULL); } if (*rid > rid_max || alloced[*rid] == alloced_max) return (NULL); alloced[*rid]++; return (res[*rid]); } static int sbc_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r) { struct sbc_softc *scp; int *alloced, rid_max; scp = device_get_softc(bus); switch (type) { case SYS_RES_IOPORT: alloced = scp->io_alloced; rid_max = IO_MAX - 1; break; case SYS_RES_DRQ: alloced = scp->drq_alloced; rid_max = DRQ_MAX - 1; break; case SYS_RES_IRQ: alloced = scp->irq_alloced; rid_max = IRQ_MAX - 1; break; default: return (1); } if (rid > rid_max || alloced[rid] == 0) return (1); alloced[rid]--; return (0); } static int sbc_read_ivar(device_t bus, device_t dev, int index, uintptr_t * result) { struct sbc_softc *scp = device_get_softc(bus); struct sndcard_func *func = device_get_ivars(dev); switch (index) { case 0: *result = func->func; break; case 1: *result = scp->bd_ver; break; default: return ENOENT; } return 0; } static int sbc_write_ivar(device_t bus, device_t dev, int index, uintptr_t value) { switch (index) { case 0: case 1: return EINVAL; default: return (ENOENT); } } static int alloc_resource(struct sbc_softc *scp) { int i; for (i = 0 ; i < IO_MAX ; i++) { if (scp->io[i] == NULL) { scp->io_rid[i] = i; scp->io[i] = bus_alloc_resource_anywhere(scp->dev, SYS_RES_IOPORT, &scp->io_rid[i], io_range[i], RF_ACTIVE); if (i == 0 && scp->io[i] == NULL) return (1); scp->io_alloced[i] = 0; } } for (i = 0 ; i < DRQ_MAX ; i++) { if (scp->drq[i] == NULL) { scp->drq_rid[i] = i; scp->drq[i] = bus_alloc_resource_any(scp->dev, SYS_RES_DRQ, &scp->drq_rid[i], RF_ACTIVE); if (i == 0 && scp->drq[i] == NULL) return (1); scp->drq_alloced[i] = 0; } } for (i = 0 ; i < IRQ_MAX ; i++) { if (scp->irq[i] == NULL) { scp->irq_rid[i] = i; scp->irq[i] = bus_alloc_resource_any(scp->dev, SYS_RES_IRQ, &scp->irq_rid[i], RF_ACTIVE); if (i == 0 && scp->irq[i] == NULL) return (1); scp->irq_alloced[i] = 0; } } return (0); } static int release_resource(struct sbc_softc *scp) { int i; for (i = 0 ; i < IO_MAX ; i++) { if (scp->io[i] != NULL) { bus_release_resource(scp->dev, SYS_RES_IOPORT, scp->io_rid[i], scp->io[i]); scp->io[i] = NULL; } } for (i = 0 ; i < DRQ_MAX ; i++) { if (scp->drq[i] != NULL) { bus_release_resource(scp->dev, SYS_RES_DRQ, scp->drq_rid[i], scp->drq[i]); scp->drq[i] = NULL; } } for (i = 0 ; i < IRQ_MAX ; i++) { if (scp->irq[i] != NULL) { if (scp->ih[i] != NULL) bus_teardown_intr(scp->dev, scp->irq[i], scp->ih[i]); scp->ih[i] = NULL; bus_release_resource(scp->dev, SYS_RES_IRQ, scp->irq_rid[i], scp->irq[i]); scp->irq[i] = NULL; } } return (0); } static device_method_t sbc_methods[] = { /* Device interface */ DEVMETHOD(device_probe, sbc_probe), DEVMETHOD(device_attach, sbc_attach), DEVMETHOD(device_detach, sbc_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), /* Bus interface */ DEVMETHOD(bus_read_ivar, sbc_read_ivar), DEVMETHOD(bus_write_ivar, sbc_write_ivar), DEVMETHOD(bus_alloc_resource, sbc_alloc_resource), DEVMETHOD(bus_release_resource, sbc_release_resource), DEVMETHOD(bus_activate_resource, bus_generic_activate_resource), DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource), DEVMETHOD(bus_setup_intr, sbc_setup_intr), DEVMETHOD(bus_teardown_intr, sbc_teardown_intr), DEVMETHOD_END }; static driver_t sbc_driver = { "sbc", sbc_methods, sizeof(struct sbc_softc), }; /* sbc can be attached to an isa bus. */ DRIVER_MODULE(snd_sbc, isa, sbc_driver, sbc_devclass, 0, 0); DRIVER_MODULE(snd_sbc, acpi, sbc_driver, sbc_devclass, 0, 0); MODULE_DEPEND(snd_sbc, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_VERSION(snd_sbc, 1); +ISA_PNP_INFO(sbc_ids); Index: head/sys/i386/i386/npx.c =================================================================== --- head/sys/i386/i386/npx.c (revision 328523) +++ head/sys/i386/i386/npx.c (revision 328524) @@ -1,1430 +1,1431 @@ /*- * Copyright (c) 1990 William Jolitz. * Copyright (c) 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)npx.c 7.2 (Berkeley) 5/12/91 */ #include __FBSDID("$FreeBSD$"); #include "opt_cpu.h" #include "opt_isa.h" #include "opt_npx.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef NPX_DEBUG #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef DEV_ISA #include #endif /* * 387 and 287 Numeric Coprocessor Extension (NPX) Driver. */ #if defined(__GNUCLIKE_ASM) && !defined(lint) #define fldcw(cw) __asm __volatile("fldcw %0" : : "m" (cw)) #define fnclex() __asm __volatile("fnclex") #define fninit() __asm __volatile("fninit") #define fnsave(addr) __asm __volatile("fnsave %0" : "=m" (*(addr))) #define fnstcw(addr) __asm __volatile("fnstcw %0" : "=m" (*(addr))) #define fnstsw(addr) __asm __volatile("fnstsw %0" : "=am" (*(addr))) #define fp_divide_by_0() __asm __volatile( \ "fldz; fld1; fdiv %st,%st(1); fnop") #define frstor(addr) __asm __volatile("frstor %0" : : "m" (*(addr))) #define fxrstor(addr) __asm __volatile("fxrstor %0" : : "m" (*(addr))) #define fxsave(addr) __asm __volatile("fxsave %0" : "=m" (*(addr))) #define ldmxcsr(csr) __asm __volatile("ldmxcsr %0" : : "m" (csr)) #define stmxcsr(addr) __asm __volatile("stmxcsr %0" : : "m" (*(addr))) static __inline void xrstor(char *addr, uint64_t mask) { uint32_t low, hi; low = mask; hi = mask >> 32; __asm __volatile("xrstor %0" : : "m" (*addr), "a" (low), "d" (hi)); } static __inline void xsave(char *addr, uint64_t mask) { uint32_t low, hi; low = mask; hi = mask >> 32; __asm __volatile("xsave %0" : "=m" (*addr) : "a" (low), "d" (hi) : "memory"); } static __inline void xsaveopt(char *addr, uint64_t mask) { uint32_t low, hi; low = mask; hi = mask >> 32; __asm __volatile("xsaveopt %0" : "=m" (*addr) : "a" (low), "d" (hi) : "memory"); } #else /* !(__GNUCLIKE_ASM && !lint) */ void fldcw(u_short cw); void fnclex(void); void fninit(void); void fnsave(caddr_t addr); void fnstcw(caddr_t addr); void fnstsw(caddr_t addr); void fp_divide_by_0(void); void frstor(caddr_t addr); void fxsave(caddr_t addr); void fxrstor(caddr_t addr); void ldmxcsr(u_int csr); void stmxcsr(u_int *csr); void xrstor(char *addr, uint64_t mask); void xsave(char *addr, uint64_t mask); void xsaveopt(char *addr, uint64_t mask); #endif /* __GNUCLIKE_ASM && !lint */ #define start_emulating() load_cr0(rcr0() | CR0_TS) #define stop_emulating() clts() #define GET_FPU_CW(thread) \ (cpu_fxsr ? \ (thread)->td_pcb->pcb_save->sv_xmm.sv_env.en_cw : \ (thread)->td_pcb->pcb_save->sv_87.sv_env.en_cw) #define GET_FPU_SW(thread) \ (cpu_fxsr ? \ (thread)->td_pcb->pcb_save->sv_xmm.sv_env.en_sw : \ (thread)->td_pcb->pcb_save->sv_87.sv_env.en_sw) #define SET_FPU_CW(savefpu, value) do { \ if (cpu_fxsr) \ (savefpu)->sv_xmm.sv_env.en_cw = (value); \ else \ (savefpu)->sv_87.sv_env.en_cw = (value); \ } while (0) CTASSERT(sizeof(union savefpu) == 512); CTASSERT(sizeof(struct xstate_hdr) == 64); CTASSERT(sizeof(struct savefpu_ymm) == 832); /* * This requirement is to make it easier for asm code to calculate * offset of the fpu save area from the pcb address. FPU save area * must be 64-byte aligned. */ CTASSERT(sizeof(struct pcb) % XSAVE_AREA_ALIGN == 0); /* * Ensure the copy of XCR0 saved in a core is contained in the padding * area. */ CTASSERT(X86_XSTATE_XCR0_OFFSET >= offsetof(struct savexmm, sv_pad) && X86_XSTATE_XCR0_OFFSET + sizeof(uint64_t) <= sizeof(struct savexmm)); static void fpu_clean_state(void); static void fpusave(union savefpu *); static void fpurstor(union savefpu *); int hw_float; SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD, &hw_float, 0, "Floating point instructions executed in hardware"); int use_xsave; uint64_t xsave_mask; static uma_zone_t fpu_save_area_zone; static union savefpu *npx_initialstate; struct xsave_area_elm_descr { u_int offset; u_int size; } *xsave_area_desc; static int use_xsaveopt; static volatile u_int npx_traps_while_probing; alias_for_inthand_t probetrap; __asm(" \n\ .text \n\ .p2align 2,0x90 \n\ .type " __XSTRING(CNAME(probetrap)) ",@function \n\ " __XSTRING(CNAME(probetrap)) ": \n\ ss \n\ incl " __XSTRING(CNAME(npx_traps_while_probing)) " \n\ fnclex \n\ iret \n\ "); /* * Determine if an FPU is present and how to use it. */ static int npx_probe(void) { struct gate_descriptor save_idt_npxtrap; u_short control, status; /* * Modern CPUs all have an FPU that uses the INT16 interface * and provide a simple way to verify that, so handle the * common case right away. */ if (cpu_feature & CPUID_FPU) { hw_float = 1; return (1); } save_idt_npxtrap = idt[IDT_MF]; setidt(IDT_MF, probetrap, SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL)); /* * Don't trap while we're probing. */ stop_emulating(); /* * Finish resetting the coprocessor, if any. If there is an error * pending, then we may get a bogus IRQ13, but npx_intr() will handle * it OK. Bogus halts have never been observed, but we enabled * IRQ13 and cleared the BUSY# latch early to handle them anyway. */ fninit(); /* * Don't use fwait here because it might hang. * Don't use fnop here because it usually hangs if there is no FPU. */ DELAY(1000); /* wait for any IRQ13 */ #ifdef DIAGNOSTIC if (npx_traps_while_probing != 0) printf("fninit caused %u bogus npx trap(s)\n", npx_traps_while_probing); #endif /* * Check for a status of mostly zero. */ status = 0x5a5a; fnstsw(&status); if ((status & 0xb8ff) == 0) { /* * Good, now check for a proper control word. */ control = 0x5a5a; fnstcw(&control); if ((control & 0x1f3f) == 0x033f) { /* * We have an npx, now divide by 0 to see if exception * 16 works. */ control &= ~(1 << 2); /* enable divide by 0 trap */ fldcw(control); npx_traps_while_probing = 0; fp_divide_by_0(); if (npx_traps_while_probing != 0) { /* * Good, exception 16 works. */ hw_float = 1; goto cleanup; } printf( "FPU does not use exception 16 for error reporting\n"); goto cleanup; } } /* * Probe failed. Floating point simply won't work. * Notify user and disable FPU/MMX/SSE instruction execution. */ printf("WARNING: no FPU!\n"); __asm __volatile("smsw %%ax; orb %0,%%al; lmsw %%ax" : : "n" (CR0_EM | CR0_MP) : "ax"); cleanup: idt[IDT_MF] = save_idt_npxtrap; return (hw_float); } /* * Enable XSAVE if supported and allowed by user. * Calculate the xsave_mask. */ static void npxinit_bsp1(void) { u_int cp[4]; uint64_t xsave_mask_user; if (cpu_fxsr && (cpu_feature2 & CPUID2_XSAVE) != 0) { use_xsave = 1; TUNABLE_INT_FETCH("hw.use_xsave", &use_xsave); } if (!use_xsave) return; cpuid_count(0xd, 0x0, cp); xsave_mask = XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE; if ((cp[0] & xsave_mask) != xsave_mask) panic("CPU0 does not support X87 or SSE: %x", cp[0]); xsave_mask = ((uint64_t)cp[3] << 32) | cp[0]; xsave_mask_user = xsave_mask; TUNABLE_QUAD_FETCH("hw.xsave_mask", &xsave_mask_user); xsave_mask_user |= XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE; xsave_mask &= xsave_mask_user; if ((xsave_mask & XFEATURE_AVX512) != XFEATURE_AVX512) xsave_mask &= ~XFEATURE_AVX512; if ((xsave_mask & XFEATURE_MPX) != XFEATURE_MPX) xsave_mask &= ~XFEATURE_MPX; cpuid_count(0xd, 0x1, cp); if ((cp[0] & CPUID_EXTSTATE_XSAVEOPT) != 0) use_xsaveopt = 1; } /* * Calculate the fpu save area size. */ static void npxinit_bsp2(void) { u_int cp[4]; if (use_xsave) { cpuid_count(0xd, 0x0, cp); cpu_max_ext_state_size = cp[1]; /* * Reload the cpu_feature2, since we enabled OSXSAVE. */ do_cpuid(1, cp); cpu_feature2 = cp[2]; } else cpu_max_ext_state_size = sizeof(union savefpu); } /* * Initialize floating point unit. */ void npxinit(bool bsp) { static union savefpu dummy; register_t saveintr; u_int mxcsr; u_short control; if (bsp) { if (!npx_probe()) return; npxinit_bsp1(); } if (use_xsave) { load_cr4(rcr4() | CR4_XSAVE); load_xcr(XCR0, xsave_mask); } /* * XCR0 shall be set up before CPU can report the save area size. */ if (bsp) npxinit_bsp2(); /* * fninit has the same h/w bugs as fnsave. Use the detoxified * fnsave to throw away any junk in the fpu. fpusave() initializes * the fpu. * * It is too early for critical_enter() to work on AP. */ saveintr = intr_disable(); stop_emulating(); if (cpu_fxsr) fninit(); else fnsave(&dummy); control = __INITIAL_NPXCW__; fldcw(control); if (cpu_fxsr) { mxcsr = __INITIAL_MXCSR__; ldmxcsr(mxcsr); } start_emulating(); intr_restore(saveintr); } /* * On the boot CPU we generate a clean state that is used to * initialize the floating point unit when it is first used by a * process. */ static void npxinitstate(void *arg __unused) { register_t saveintr; int cp[4], i, max_ext_n; if (!hw_float) return; npx_initialstate = malloc(cpu_max_ext_state_size, M_DEVBUF, M_WAITOK | M_ZERO); saveintr = intr_disable(); stop_emulating(); fpusave(npx_initialstate); if (cpu_fxsr) { if (npx_initialstate->sv_xmm.sv_env.en_mxcsr_mask) cpu_mxcsr_mask = npx_initialstate->sv_xmm.sv_env.en_mxcsr_mask; else cpu_mxcsr_mask = 0xFFBF; /* * The fninit instruction does not modify XMM * registers or x87 registers (MM/ST). The fpusave * call dumped the garbage contained in the registers * after reset to the initial state saved. Clear XMM * and x87 registers file image to make the startup * program state and signal handler XMM/x87 register * content predictable. */ bzero(npx_initialstate->sv_xmm.sv_fp, sizeof(npx_initialstate->sv_xmm.sv_fp)); bzero(npx_initialstate->sv_xmm.sv_xmm, sizeof(npx_initialstate->sv_xmm.sv_xmm)); } else bzero(npx_initialstate->sv_87.sv_ac, sizeof(npx_initialstate->sv_87.sv_ac)); /* * Create a table describing the layout of the CPU Extended * Save Area. */ if (use_xsave) { if (xsave_mask >> 32 != 0) max_ext_n = fls(xsave_mask >> 32) + 32; else max_ext_n = fls(xsave_mask); xsave_area_desc = malloc(max_ext_n * sizeof(struct xsave_area_elm_descr), M_DEVBUF, M_WAITOK | M_ZERO); /* x87 state */ xsave_area_desc[0].offset = 0; xsave_area_desc[0].size = 160; /* XMM */ xsave_area_desc[1].offset = 160; xsave_area_desc[1].size = 288 - 160; for (i = 2; i < max_ext_n; i++) { cpuid_count(0xd, i, cp); xsave_area_desc[i].offset = cp[1]; xsave_area_desc[i].size = cp[0]; } } fpu_save_area_zone = uma_zcreate("FPU_save_area", cpu_max_ext_state_size, NULL, NULL, NULL, NULL, XSAVE_AREA_ALIGN - 1, 0); start_emulating(); intr_restore(saveintr); } SYSINIT(npxinitstate, SI_SUB_DRIVERS, SI_ORDER_ANY, npxinitstate, NULL); /* * Free coprocessor (if we have it). */ void npxexit(struct thread *td) { critical_enter(); if (curthread == PCPU_GET(fpcurthread)) { stop_emulating(); fpusave(curpcb->pcb_save); start_emulating(); PCPU_SET(fpcurthread, NULL); } critical_exit(); #ifdef NPX_DEBUG if (hw_float) { u_int masked_exceptions; masked_exceptions = GET_FPU_CW(td) & GET_FPU_SW(td) & 0x7f; /* * Log exceptions that would have trapped with the old * control word (overflow, divide by 0, and invalid operand). */ if (masked_exceptions & 0x0d) log(LOG_ERR, "pid %d (%s) exited with masked floating point exceptions 0x%02x\n", td->td_proc->p_pid, td->td_proc->p_comm, masked_exceptions); } #endif } int npxformat(void) { if (!hw_float) return (_MC_FPFMT_NODEV); if (cpu_fxsr) return (_MC_FPFMT_XMM); return (_MC_FPFMT_387); } /* * The following mechanism is used to ensure that the FPE_... value * that is passed as a trapcode to the signal handler of the user * process does not have more than one bit set. * * Multiple bits may be set if the user process modifies the control * word while a status word bit is already set. While this is a sign * of bad coding, we have no choise than to narrow them down to one * bit, since we must not send a trapcode that is not exactly one of * the FPE_ macros. * * The mechanism has a static table with 127 entries. Each combination * of the 7 FPU status word exception bits directly translates to a * position in this table, where a single FPE_... value is stored. * This FPE_... value stored there is considered the "most important" * of the exception bits and will be sent as the signal code. The * precedence of the bits is based upon Intel Document "Numerical * Applications", Chapter "Special Computational Situations". * * The macro to choose one of these values does these steps: 1) Throw * away status word bits that cannot be masked. 2) Throw away the bits * currently masked in the control word, assuming the user isn't * interested in them anymore. 3) Reinsert status word bit 7 (stack * fault) if it is set, which cannot be masked but must be presered. * 4) Use the remaining bits to point into the trapcode table. * * The 6 maskable bits in order of their preference, as stated in the * above referenced Intel manual: * 1 Invalid operation (FP_X_INV) * 1a Stack underflow * 1b Stack overflow * 1c Operand of unsupported format * 1d SNaN operand. * 2 QNaN operand (not an exception, irrelavant here) * 3 Any other invalid-operation not mentioned above or zero divide * (FP_X_INV, FP_X_DZ) * 4 Denormal operand (FP_X_DNML) * 5 Numeric over/underflow (FP_X_OFL, FP_X_UFL) * 6 Inexact result (FP_X_IMP) */ static char fpetable[128] = { 0, FPE_FLTINV, /* 1 - INV */ FPE_FLTUND, /* 2 - DNML */ FPE_FLTINV, /* 3 - INV | DNML */ FPE_FLTDIV, /* 4 - DZ */ FPE_FLTINV, /* 5 - INV | DZ */ FPE_FLTDIV, /* 6 - DNML | DZ */ FPE_FLTINV, /* 7 - INV | DNML | DZ */ FPE_FLTOVF, /* 8 - OFL */ FPE_FLTINV, /* 9 - INV | OFL */ FPE_FLTUND, /* A - DNML | OFL */ FPE_FLTINV, /* B - INV | DNML | OFL */ FPE_FLTDIV, /* C - DZ | OFL */ FPE_FLTINV, /* D - INV | DZ | OFL */ FPE_FLTDIV, /* E - DNML | DZ | OFL */ FPE_FLTINV, /* F - INV | DNML | DZ | OFL */ FPE_FLTUND, /* 10 - UFL */ FPE_FLTINV, /* 11 - INV | UFL */ FPE_FLTUND, /* 12 - DNML | UFL */ FPE_FLTINV, /* 13 - INV | DNML | UFL */ FPE_FLTDIV, /* 14 - DZ | UFL */ FPE_FLTINV, /* 15 - INV | DZ | UFL */ FPE_FLTDIV, /* 16 - DNML | DZ | UFL */ FPE_FLTINV, /* 17 - INV | DNML | DZ | UFL */ FPE_FLTOVF, /* 18 - OFL | UFL */ FPE_FLTINV, /* 19 - INV | OFL | UFL */ FPE_FLTUND, /* 1A - DNML | OFL | UFL */ FPE_FLTINV, /* 1B - INV | DNML | OFL | UFL */ FPE_FLTDIV, /* 1C - DZ | OFL | UFL */ FPE_FLTINV, /* 1D - INV | DZ | OFL | UFL */ FPE_FLTDIV, /* 1E - DNML | DZ | OFL | UFL */ FPE_FLTINV, /* 1F - INV | DNML | DZ | OFL | UFL */ FPE_FLTRES, /* 20 - IMP */ FPE_FLTINV, /* 21 - INV | IMP */ FPE_FLTUND, /* 22 - DNML | IMP */ FPE_FLTINV, /* 23 - INV | DNML | IMP */ FPE_FLTDIV, /* 24 - DZ | IMP */ FPE_FLTINV, /* 25 - INV | DZ | IMP */ FPE_FLTDIV, /* 26 - DNML | DZ | IMP */ FPE_FLTINV, /* 27 - INV | DNML | DZ | IMP */ FPE_FLTOVF, /* 28 - OFL | IMP */ FPE_FLTINV, /* 29 - INV | OFL | IMP */ FPE_FLTUND, /* 2A - DNML | OFL | IMP */ FPE_FLTINV, /* 2B - INV | DNML | OFL | IMP */ FPE_FLTDIV, /* 2C - DZ | OFL | IMP */ FPE_FLTINV, /* 2D - INV | DZ | OFL | IMP */ FPE_FLTDIV, /* 2E - DNML | DZ | OFL | IMP */ FPE_FLTINV, /* 2F - INV | DNML | DZ | OFL | IMP */ FPE_FLTUND, /* 30 - UFL | IMP */ FPE_FLTINV, /* 31 - INV | UFL | IMP */ FPE_FLTUND, /* 32 - DNML | UFL | IMP */ FPE_FLTINV, /* 33 - INV | DNML | UFL | IMP */ FPE_FLTDIV, /* 34 - DZ | UFL | IMP */ FPE_FLTINV, /* 35 - INV | DZ | UFL | IMP */ FPE_FLTDIV, /* 36 - DNML | DZ | UFL | IMP */ FPE_FLTINV, /* 37 - INV | DNML | DZ | UFL | IMP */ FPE_FLTOVF, /* 38 - OFL | UFL | IMP */ FPE_FLTINV, /* 39 - INV | OFL | UFL | IMP */ FPE_FLTUND, /* 3A - DNML | OFL | UFL | IMP */ FPE_FLTINV, /* 3B - INV | DNML | OFL | UFL | IMP */ FPE_FLTDIV, /* 3C - DZ | OFL | UFL | IMP */ FPE_FLTINV, /* 3D - INV | DZ | OFL | UFL | IMP */ FPE_FLTDIV, /* 3E - DNML | DZ | OFL | UFL | IMP */ FPE_FLTINV, /* 3F - INV | DNML | DZ | OFL | UFL | IMP */ FPE_FLTSUB, /* 40 - STK */ FPE_FLTSUB, /* 41 - INV | STK */ FPE_FLTUND, /* 42 - DNML | STK */ FPE_FLTSUB, /* 43 - INV | DNML | STK */ FPE_FLTDIV, /* 44 - DZ | STK */ FPE_FLTSUB, /* 45 - INV | DZ | STK */ FPE_FLTDIV, /* 46 - DNML | DZ | STK */ FPE_FLTSUB, /* 47 - INV | DNML | DZ | STK */ FPE_FLTOVF, /* 48 - OFL | STK */ FPE_FLTSUB, /* 49 - INV | OFL | STK */ FPE_FLTUND, /* 4A - DNML | OFL | STK */ FPE_FLTSUB, /* 4B - INV | DNML | OFL | STK */ FPE_FLTDIV, /* 4C - DZ | OFL | STK */ FPE_FLTSUB, /* 4D - INV | DZ | OFL | STK */ FPE_FLTDIV, /* 4E - DNML | DZ | OFL | STK */ FPE_FLTSUB, /* 4F - INV | DNML | DZ | OFL | STK */ FPE_FLTUND, /* 50 - UFL | STK */ FPE_FLTSUB, /* 51 - INV | UFL | STK */ FPE_FLTUND, /* 52 - DNML | UFL | STK */ FPE_FLTSUB, /* 53 - INV | DNML | UFL | STK */ FPE_FLTDIV, /* 54 - DZ | UFL | STK */ FPE_FLTSUB, /* 55 - INV | DZ | UFL | STK */ FPE_FLTDIV, /* 56 - DNML | DZ | UFL | STK */ FPE_FLTSUB, /* 57 - INV | DNML | DZ | UFL | STK */ FPE_FLTOVF, /* 58 - OFL | UFL | STK */ FPE_FLTSUB, /* 59 - INV | OFL | UFL | STK */ FPE_FLTUND, /* 5A - DNML | OFL | UFL | STK */ FPE_FLTSUB, /* 5B - INV | DNML | OFL | UFL | STK */ FPE_FLTDIV, /* 5C - DZ | OFL | UFL | STK */ FPE_FLTSUB, /* 5D - INV | DZ | OFL | UFL | STK */ FPE_FLTDIV, /* 5E - DNML | DZ | OFL | UFL | STK */ FPE_FLTSUB, /* 5F - INV | DNML | DZ | OFL | UFL | STK */ FPE_FLTRES, /* 60 - IMP | STK */ FPE_FLTSUB, /* 61 - INV | IMP | STK */ FPE_FLTUND, /* 62 - DNML | IMP | STK */ FPE_FLTSUB, /* 63 - INV | DNML | IMP | STK */ FPE_FLTDIV, /* 64 - DZ | IMP | STK */ FPE_FLTSUB, /* 65 - INV | DZ | IMP | STK */ FPE_FLTDIV, /* 66 - DNML | DZ | IMP | STK */ FPE_FLTSUB, /* 67 - INV | DNML | DZ | IMP | STK */ FPE_FLTOVF, /* 68 - OFL | IMP | STK */ FPE_FLTSUB, /* 69 - INV | OFL | IMP | STK */ FPE_FLTUND, /* 6A - DNML | OFL | IMP | STK */ FPE_FLTSUB, /* 6B - INV | DNML | OFL | IMP | STK */ FPE_FLTDIV, /* 6C - DZ | OFL | IMP | STK */ FPE_FLTSUB, /* 6D - INV | DZ | OFL | IMP | STK */ FPE_FLTDIV, /* 6E - DNML | DZ | OFL | IMP | STK */ FPE_FLTSUB, /* 6F - INV | DNML | DZ | OFL | IMP | STK */ FPE_FLTUND, /* 70 - UFL | IMP | STK */ FPE_FLTSUB, /* 71 - INV | UFL | IMP | STK */ FPE_FLTUND, /* 72 - DNML | UFL | IMP | STK */ FPE_FLTSUB, /* 73 - INV | DNML | UFL | IMP | STK */ FPE_FLTDIV, /* 74 - DZ | UFL | IMP | STK */ FPE_FLTSUB, /* 75 - INV | DZ | UFL | IMP | STK */ FPE_FLTDIV, /* 76 - DNML | DZ | UFL | IMP | STK */ FPE_FLTSUB, /* 77 - INV | DNML | DZ | UFL | IMP | STK */ FPE_FLTOVF, /* 78 - OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 79 - INV | OFL | UFL | IMP | STK */ FPE_FLTUND, /* 7A - DNML | OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 7B - INV | DNML | OFL | UFL | IMP | STK */ FPE_FLTDIV, /* 7C - DZ | OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 7D - INV | DZ | OFL | UFL | IMP | STK */ FPE_FLTDIV, /* 7E - DNML | DZ | OFL | UFL | IMP | STK */ FPE_FLTSUB, /* 7F - INV | DNML | DZ | OFL | UFL | IMP | STK */ }; /* * Read the FP status and control words, then generate si_code value * for SIGFPE. The error code chosen will be one of the * FPE_... macros. It will be sent as the second argument to old * BSD-style signal handlers and as "siginfo_t->si_code" (second * argument) to SA_SIGINFO signal handlers. * * Some time ago, we cleared the x87 exceptions with FNCLEX there. * Clearing exceptions was necessary mainly to avoid IRQ13 bugs. The * usermode code which understands the FPU hardware enough to enable * the exceptions, can also handle clearing the exception state in the * handler. The only consequence of not clearing the exception is the * rethrow of the SIGFPE on return from the signal handler and * reexecution of the corresponding instruction. * * For XMM traps, the exceptions were never cleared. */ int npxtrap_x87(void) { u_short control, status; if (!hw_float) { printf( "npxtrap_x87: fpcurthread = %p, curthread = %p, hw_float = %d\n", PCPU_GET(fpcurthread), curthread, hw_float); panic("npxtrap from nowhere"); } critical_enter(); /* * Interrupt handling (for another interrupt) may have pushed the * state to memory. Fetch the relevant parts of the state from * wherever they are. */ if (PCPU_GET(fpcurthread) != curthread) { control = GET_FPU_CW(curthread); status = GET_FPU_SW(curthread); } else { fnstcw(&control); fnstsw(&status); } critical_exit(); return (fpetable[status & ((~control & 0x3f) | 0x40)]); } int npxtrap_sse(void) { u_int mxcsr; if (!hw_float) { printf( "npxtrap_sse: fpcurthread = %p, curthread = %p, hw_float = %d\n", PCPU_GET(fpcurthread), curthread, hw_float); panic("npxtrap from nowhere"); } critical_enter(); if (PCPU_GET(fpcurthread) != curthread) mxcsr = curthread->td_pcb->pcb_save->sv_xmm.sv_env.en_mxcsr; else stmxcsr(&mxcsr); critical_exit(); return (fpetable[(mxcsr & (~mxcsr >> 7)) & 0x3f]); } /* * Implement device not available (DNA) exception * * It would be better to switch FP context here (if curthread != fpcurthread) * and not necessarily for every context switch, but it is too hard to * access foreign pcb's. */ static int err_count = 0; int npxdna(void) { if (!hw_float) return (0); critical_enter(); if (PCPU_GET(fpcurthread) == curthread) { printf("npxdna: fpcurthread == curthread %d times\n", ++err_count); stop_emulating(); critical_exit(); return (1); } if (PCPU_GET(fpcurthread) != NULL) { printf("npxdna: fpcurthread = %p (%d), curthread = %p (%d)\n", PCPU_GET(fpcurthread), PCPU_GET(fpcurthread)->td_proc->p_pid, curthread, curthread->td_proc->p_pid); panic("npxdna"); } stop_emulating(); /* * Record new context early in case frstor causes a trap. */ PCPU_SET(fpcurthread, curthread); if (cpu_fxsr) fpu_clean_state(); if ((curpcb->pcb_flags & PCB_NPXINITDONE) == 0) { /* * This is the first time this thread has used the FPU or * the PCB doesn't contain a clean FPU state. Explicitly * load an initial state. * * We prefer to restore the state from the actual save * area in PCB instead of directly loading from * npx_initialstate, to ignite the XSAVEOPT * tracking engine. */ bcopy(npx_initialstate, curpcb->pcb_save, cpu_max_ext_state_size); fpurstor(curpcb->pcb_save); if (curpcb->pcb_initial_npxcw != __INITIAL_NPXCW__) fldcw(curpcb->pcb_initial_npxcw); curpcb->pcb_flags |= PCB_NPXINITDONE; if (PCB_USER_FPU(curpcb)) curpcb->pcb_flags |= PCB_NPXUSERINITDONE; } else { fpurstor(curpcb->pcb_save); } critical_exit(); return (1); } /* * Wrapper for fpusave() called from context switch routines. * * npxsave() must be called with interrupts disabled, so that it clears * fpcurthread atomically with saving the state. We require callers to do the * disabling, since most callers need to disable interrupts anyway to call * npxsave() atomically with checking fpcurthread. */ void npxsave(addr) union savefpu *addr; { stop_emulating(); if (use_xsaveopt) xsaveopt((char *)addr, xsave_mask); else fpusave(addr); start_emulating(); PCPU_SET(fpcurthread, NULL); } /* * Unconditionally save the current co-processor state across suspend and * resume. */ void npxsuspend(union savefpu *addr) { register_t cr0; if (!hw_float) return; if (PCPU_GET(fpcurthread) == NULL) { bcopy(npx_initialstate, addr, cpu_max_ext_state_size); return; } cr0 = rcr0(); stop_emulating(); fpusave(addr); load_cr0(cr0); } void npxresume(union savefpu *addr) { register_t cr0; if (!hw_float) return; cr0 = rcr0(); npxinit(false); stop_emulating(); fpurstor(addr); load_cr0(cr0); } void npxdrop(void) { struct thread *td; /* * Discard pending exceptions in the !cpu_fxsr case so that unmasked * ones don't cause a panic on the next frstor. */ if (!cpu_fxsr) fnclex(); td = PCPU_GET(fpcurthread); KASSERT(td == curthread, ("fpudrop: fpcurthread != curthread")); CRITICAL_ASSERT(td); PCPU_SET(fpcurthread, NULL); td->td_pcb->pcb_flags &= ~PCB_NPXINITDONE; start_emulating(); } /* * Get the user state of the FPU into pcb->pcb_user_save without * dropping ownership (if possible). It returns the FPU ownership * status. */ int npxgetregs(struct thread *td) { struct pcb *pcb; uint64_t *xstate_bv, bit; char *sa; int max_ext_n, i; int owned; if (!hw_float) return (_MC_FPOWNED_NONE); pcb = td->td_pcb; if ((pcb->pcb_flags & PCB_NPXINITDONE) == 0) { bcopy(npx_initialstate, get_pcb_user_save_pcb(pcb), cpu_max_ext_state_size); SET_FPU_CW(get_pcb_user_save_pcb(pcb), pcb->pcb_initial_npxcw); npxuserinited(td); return (_MC_FPOWNED_PCB); } critical_enter(); if (td == PCPU_GET(fpcurthread)) { fpusave(get_pcb_user_save_pcb(pcb)); if (!cpu_fxsr) /* * fnsave initializes the FPU and destroys whatever * context it contains. Make sure the FPU owner * starts with a clean state next time. */ npxdrop(); owned = _MC_FPOWNED_FPU; } else { owned = _MC_FPOWNED_PCB; } critical_exit(); if (use_xsave) { /* * Handle partially saved state. */ sa = (char *)get_pcb_user_save_pcb(pcb); xstate_bv = (uint64_t *)(sa + sizeof(union savefpu) + offsetof(struct xstate_hdr, xstate_bv)); if (xsave_mask >> 32 != 0) max_ext_n = fls(xsave_mask >> 32) + 32; else max_ext_n = fls(xsave_mask); for (i = 0; i < max_ext_n; i++) { bit = 1ULL << i; if ((xsave_mask & bit) == 0 || (*xstate_bv & bit) != 0) continue; bcopy((char *)npx_initialstate + xsave_area_desc[i].offset, sa + xsave_area_desc[i].offset, xsave_area_desc[i].size); *xstate_bv |= bit; } } return (owned); } void npxuserinited(struct thread *td) { struct pcb *pcb; pcb = td->td_pcb; if (PCB_USER_FPU(pcb)) pcb->pcb_flags |= PCB_NPXINITDONE; pcb->pcb_flags |= PCB_NPXUSERINITDONE; } int npxsetxstate(struct thread *td, char *xfpustate, size_t xfpustate_size) { struct xstate_hdr *hdr, *ehdr; size_t len, max_len; uint64_t bv; /* XXXKIB should we clear all extended state in xstate_bv instead ? */ if (xfpustate == NULL) return (0); if (!use_xsave) return (EOPNOTSUPP); len = xfpustate_size; if (len < sizeof(struct xstate_hdr)) return (EINVAL); max_len = cpu_max_ext_state_size - sizeof(union savefpu); if (len > max_len) return (EINVAL); ehdr = (struct xstate_hdr *)xfpustate; bv = ehdr->xstate_bv; /* * Avoid #gp. */ if (bv & ~xsave_mask) return (EINVAL); hdr = (struct xstate_hdr *)(get_pcb_user_save_td(td) + 1); hdr->xstate_bv = bv; bcopy(xfpustate + sizeof(struct xstate_hdr), (char *)(hdr + 1), len - sizeof(struct xstate_hdr)); return (0); } int npxsetregs(struct thread *td, union savefpu *addr, char *xfpustate, size_t xfpustate_size) { struct pcb *pcb; int error; if (!hw_float) return (ENXIO); if (cpu_fxsr) addr->sv_xmm.sv_env.en_mxcsr &= cpu_mxcsr_mask; pcb = td->td_pcb; critical_enter(); if (td == PCPU_GET(fpcurthread) && PCB_USER_FPU(pcb)) { error = npxsetxstate(td, xfpustate, xfpustate_size); if (error != 0) { critical_exit(); return (error); } if (!cpu_fxsr) fnclex(); /* As in npxdrop(). */ bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr)); fpurstor(get_pcb_user_save_td(td)); critical_exit(); pcb->pcb_flags |= PCB_NPXUSERINITDONE | PCB_NPXINITDONE; } else { critical_exit(); error = npxsetxstate(td, xfpustate, xfpustate_size); if (error != 0) return (error); bcopy(addr, get_pcb_user_save_td(td), sizeof(*addr)); npxuserinited(td); } return (0); } static void fpusave(addr) union savefpu *addr; { if (use_xsave) xsave((char *)addr, xsave_mask); else if (cpu_fxsr) fxsave(addr); else fnsave(addr); } static void npx_fill_fpregs_xmm1(struct savexmm *sv_xmm, struct save87 *sv_87) { struct env87 *penv_87; struct envxmm *penv_xmm; int i; penv_87 = &sv_87->sv_env; penv_xmm = &sv_xmm->sv_env; /* FPU control/status */ penv_87->en_cw = penv_xmm->en_cw; penv_87->en_sw = penv_xmm->en_sw; penv_87->en_fip = penv_xmm->en_fip; penv_87->en_fcs = penv_xmm->en_fcs; penv_87->en_opcode = penv_xmm->en_opcode; penv_87->en_foo = penv_xmm->en_foo; penv_87->en_fos = penv_xmm->en_fos; /* FPU registers and tags */ penv_87->en_tw = 0xffff; for (i = 0; i < 8; ++i) { sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc; if ((penv_xmm->en_tw & (1 << i)) != 0) /* zero and special are set as valid */ penv_87->en_tw &= ~(3 << i * 2); } } void npx_fill_fpregs_xmm(struct savexmm *sv_xmm, struct save87 *sv_87) { bzero(sv_87, sizeof(*sv_87)); npx_fill_fpregs_xmm1(sv_xmm, sv_87); } void npx_set_fpregs_xmm(struct save87 *sv_87, struct savexmm *sv_xmm) { struct env87 *penv_87; struct envxmm *penv_xmm; int i; penv_87 = &sv_87->sv_env; penv_xmm = &sv_xmm->sv_env; /* FPU control/status */ penv_xmm->en_cw = penv_87->en_cw; penv_xmm->en_sw = penv_87->en_sw; penv_xmm->en_fip = penv_87->en_fip; penv_xmm->en_fcs = penv_87->en_fcs; penv_xmm->en_opcode = penv_87->en_opcode; penv_xmm->en_foo = penv_87->en_foo; penv_xmm->en_fos = penv_87->en_fos; /* * FPU registers and tags. * Abridged / Full translation (values in binary), see FXSAVE spec. * 0 11 * 1 00, 01, 10 */ penv_xmm->en_tw = 0; for (i = 0; i < 8; ++i) { sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i]; if ((penv_87->en_tw & (3 << i * 2)) != (3 << i * 2)) penv_xmm->en_tw |= 1 << i; } } void npx_get_fsave(void *addr) { struct thread *td; union savefpu *sv; td = curthread; npxgetregs(td); sv = get_pcb_user_save_td(td); if (cpu_fxsr) npx_fill_fpregs_xmm1(&sv->sv_xmm, addr); else bcopy(sv, addr, sizeof(struct env87) + sizeof(struct fpacc87[8])); } int npx_set_fsave(void *addr) { union savefpu sv; int error; bzero(&sv, sizeof(sv)); if (cpu_fxsr) npx_set_fpregs_xmm(addr, &sv.sv_xmm); else bcopy(addr, &sv, sizeof(struct env87) + sizeof(struct fpacc87[8])); error = npxsetregs(curthread, &sv, NULL, 0); return (error); } /* * On AuthenticAMD processors, the fxrstor instruction does not restore * the x87's stored last instruction pointer, last data pointer, and last * opcode values, except in the rare case in which the exception summary * (ES) bit in the x87 status word is set to 1. * * In order to avoid leaking this information across processes, we clean * these values by performing a dummy load before executing fxrstor(). */ static void fpu_clean_state(void) { static float dummy_variable = 0.0; u_short status; /* * Clear the ES bit in the x87 status word if it is currently * set, in order to avoid causing a fault in the upcoming load. */ fnstsw(&status); if (status & 0x80) fnclex(); /* * Load the dummy variable into the x87 stack. This mangles * the x87 stack, but we don't care since we're about to call * fxrstor() anyway. */ __asm __volatile("ffree %%st(7); flds %0" : : "m" (dummy_variable)); } static void fpurstor(union savefpu *addr) { if (use_xsave) xrstor((char *)addr, xsave_mask); else if (cpu_fxsr) fxrstor(addr); else frstor(addr); } #ifdef DEV_ISA /* * This sucks up the legacy ISA support assignments from PNPBIOS/ACPI. */ static struct isa_pnp_id npxisa_ids[] = { { 0x040cd041, "Legacy ISA coprocessor support" }, /* PNP0C04 */ { 0 } }; static int npxisa_probe(device_t dev) { int result; if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, npxisa_ids)) <= 0) { device_quiet(dev); } return(result); } static int npxisa_attach(device_t dev) { return (0); } static device_method_t npxisa_methods[] = { /* Device interface */ DEVMETHOD(device_probe, npxisa_probe), DEVMETHOD(device_attach, npxisa_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), { 0, 0 } }; static driver_t npxisa_driver = { "npxisa", npxisa_methods, 1, /* no softc */ }; static devclass_t npxisa_devclass; DRIVER_MODULE(npxisa, isa, npxisa_driver, npxisa_devclass, 0, 0); DRIVER_MODULE(npxisa, acpi, npxisa_driver, npxisa_devclass, 0, 0); +ISA_PNP_INFO(npxisa_ids); #endif /* DEV_ISA */ static MALLOC_DEFINE(M_FPUKERN_CTX, "fpukern_ctx", "Kernel contexts for FPU state"); #define FPU_KERN_CTX_NPXINITDONE 0x01 #define FPU_KERN_CTX_DUMMY 0x02 #define FPU_KERN_CTX_INUSE 0x04 struct fpu_kern_ctx { union savefpu *prev; uint32_t flags; char hwstate1[]; }; struct fpu_kern_ctx * fpu_kern_alloc_ctx(u_int flags) { struct fpu_kern_ctx *res; size_t sz; sz = sizeof(struct fpu_kern_ctx) + XSAVE_AREA_ALIGN + cpu_max_ext_state_size; res = malloc(sz, M_FPUKERN_CTX, ((flags & FPU_KERN_NOWAIT) ? M_NOWAIT : M_WAITOK) | M_ZERO); return (res); } void fpu_kern_free_ctx(struct fpu_kern_ctx *ctx) { KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) == 0, ("free'ing inuse ctx")); /* XXXKIB clear the memory ? */ free(ctx, M_FPUKERN_CTX); } static union savefpu * fpu_kern_ctx_savefpu(struct fpu_kern_ctx *ctx) { vm_offset_t p; p = (vm_offset_t)&ctx->hwstate1; p = roundup2(p, XSAVE_AREA_ALIGN); return ((union savefpu *)p); } int fpu_kern_enter(struct thread *td, struct fpu_kern_ctx *ctx, u_int flags) { struct pcb *pcb; KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) == 0, ("using inuse ctx")); if ((flags & FPU_KERN_KTHR) != 0 && is_fpu_kern_thread(0)) { ctx->flags = FPU_KERN_CTX_DUMMY | FPU_KERN_CTX_INUSE; return (0); } pcb = td->td_pcb; KASSERT(!PCB_USER_FPU(pcb) || pcb->pcb_save == get_pcb_user_save_pcb(pcb), ("mangled pcb_save")); ctx->flags = FPU_KERN_CTX_INUSE; if ((pcb->pcb_flags & PCB_NPXINITDONE) != 0) ctx->flags |= FPU_KERN_CTX_NPXINITDONE; npxexit(td); ctx->prev = pcb->pcb_save; pcb->pcb_save = fpu_kern_ctx_savefpu(ctx); pcb->pcb_flags |= PCB_KERNNPX; pcb->pcb_flags &= ~PCB_NPXINITDONE; return (0); } int fpu_kern_leave(struct thread *td, struct fpu_kern_ctx *ctx) { struct pcb *pcb; KASSERT((ctx->flags & FPU_KERN_CTX_INUSE) != 0, ("leaving not inuse ctx")); ctx->flags &= ~FPU_KERN_CTX_INUSE; if (is_fpu_kern_thread(0) && (ctx->flags & FPU_KERN_CTX_DUMMY) != 0) return (0); pcb = td->td_pcb; critical_enter(); if (curthread == PCPU_GET(fpcurthread)) npxdrop(); critical_exit(); pcb->pcb_save = ctx->prev; if (pcb->pcb_save == get_pcb_user_save_pcb(pcb)) { if ((pcb->pcb_flags & PCB_NPXUSERINITDONE) != 0) pcb->pcb_flags |= PCB_NPXINITDONE; else pcb->pcb_flags &= ~PCB_NPXINITDONE; pcb->pcb_flags &= ~PCB_KERNNPX; } else { if ((ctx->flags & FPU_KERN_CTX_NPXINITDONE) != 0) pcb->pcb_flags |= PCB_NPXINITDONE; else pcb->pcb_flags &= ~PCB_NPXINITDONE; KASSERT(!PCB_USER_FPU(pcb), ("unpaired fpu_kern_leave")); } return (0); } int fpu_kern_thread(u_int flags) { KASSERT((curthread->td_pflags & TDP_KTHREAD) != 0, ("Only kthread may use fpu_kern_thread")); KASSERT(curpcb->pcb_save == get_pcb_user_save_pcb(curpcb), ("mangled pcb_save")); KASSERT(PCB_USER_FPU(curpcb), ("recursive call")); curpcb->pcb_flags |= PCB_KERNNPX; return (0); } int is_fpu_kern_thread(u_int flags) { if ((curthread->td_pflags & TDP_KTHREAD) == 0) return (0); return ((curpcb->pcb_flags & PCB_KERNNPX) != 0); } /* * FPU save area alloc/free/init utility routines */ union savefpu * fpu_save_area_alloc(void) { return (uma_zalloc(fpu_save_area_zone, 0)); } void fpu_save_area_free(union savefpu *fsa) { uma_zfree(fpu_save_area_zone, fsa); } void fpu_save_area_reset(union savefpu *fsa) { bcopy(npx_initialstate, fsa, cpu_max_ext_state_size); } Index: head/sys/isa/vga_isa.c =================================================================== --- head/sys/isa/vga_isa.c (revision 328523) +++ head/sys/isa/vga_isa.c (revision 328524) @@ -1,385 +1,394 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1999 Kazutaka YOKOTA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer as * the first lines of this file unmodified. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include "opt_vga.h" #include "opt_fb.h" #include "opt_syscons.h" /* should be removed in the future, XXX */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef __i386__ #include #endif #include #include #include #include +#define VGA_ID 0x0009d041 /* PNP0900 */ + +static struct isa_pnp_id vga_ids[] = { + { VGA_ID, NULL }, /* PNP0900 */ + { 0, NULL }, +}; + static void vga_suspend(device_t dev) { vga_softc_t *sc; int nbytes; sc = device_get_softc(dev); /* Save the video state across the suspend. */ if (sc->state_buf != NULL) goto save_palette; nbytes = vidd_save_state(sc->adp, NULL, 0); if (nbytes <= 0) goto save_palette; sc->state_buf = malloc(nbytes, M_TEMP, M_NOWAIT); if (sc->state_buf == NULL) goto save_palette; if (bootverbose) device_printf(dev, "saving %d bytes of video state\n", nbytes); if (vidd_save_state(sc->adp, sc->state_buf, nbytes) != 0) { device_printf(dev, "failed to save state (nbytes=%d)\n", nbytes); free(sc->state_buf, M_TEMP); sc->state_buf = NULL; } save_palette: /* Save the color palette across the suspend. */ if (sc->pal_buf != NULL) return; sc->pal_buf = malloc(256 * 3, M_TEMP, M_NOWAIT); if (sc->pal_buf == NULL) return; if (bootverbose) device_printf(dev, "saving color palette\n"); if (vidd_save_palette(sc->adp, sc->pal_buf) != 0) { device_printf(dev, "failed to save palette\n"); free(sc->pal_buf, M_TEMP); sc->pal_buf = NULL; } } static void vga_resume(device_t dev) { vga_softc_t *sc; sc = device_get_softc(dev); if (sc->state_buf != NULL) { if (vidd_load_state(sc->adp, sc->state_buf) != 0) device_printf(dev, "failed to reload state\n"); free(sc->state_buf, M_TEMP); sc->state_buf = NULL; } if (sc->pal_buf != NULL) { if (vidd_load_palette(sc->adp, sc->pal_buf) != 0) device_printf(dev, "failed to reload palette\n"); free(sc->pal_buf, M_TEMP); sc->pal_buf = NULL; } } #define VGA_SOFTC(unit) \ ((vga_softc_t *)devclass_get_softc(isavga_devclass, unit)) static devclass_t isavga_devclass; #ifdef FB_INSTALL_CDEV static d_open_t isavga_open; static d_close_t isavga_close; static d_read_t isavga_read; static d_write_t isavga_write; static d_ioctl_t isavga_ioctl; static d_mmap_t isavga_mmap; static struct cdevsw isavga_cdevsw = { .d_version = D_VERSION, .d_flags = D_NEEDGIANT, .d_open = isavga_open, .d_close = isavga_close, .d_read = isavga_read, .d_write = isavga_write, .d_ioctl = isavga_ioctl, .d_mmap = isavga_mmap, .d_name = VGA_DRIVER_NAME, }; #endif /* FB_INSTALL_CDEV */ static void isavga_identify(driver_t *driver, device_t parent) { BUS_ADD_CHILD(parent, ISA_ORDER_SPECULATIVE, VGA_DRIVER_NAME, 0); } static int isavga_probe(device_t dev) { video_adapter_t adp; int error; /* No pnp support */ if (isa_get_vendorid(dev)) return (ENXIO); error = vga_probe_unit(device_get_unit(dev), &adp, device_get_flags(dev)); if (error == 0) { device_set_desc(dev, "Generic ISA VGA"); bus_set_resource(dev, SYS_RES_IOPORT, 0, adp.va_io_base, adp.va_io_size); bus_set_resource(dev, SYS_RES_MEMORY, 0, adp.va_mem_base, adp.va_mem_size); - isa_set_vendorid(dev, PNP_EISAID("PNP0900")); + isa_set_vendorid(dev, VGA_ID); + isa_set_logicalid(dev, VGA_ID); #if 0 isa_set_port(dev, adp.va_io_base); isa_set_portsize(dev, adp.va_io_size); isa_set_maddr(dev, adp.va_mem_base); isa_set_msize(dev, adp.va_mem_size); #endif } return (error); } static int isavga_attach(device_t dev) { vga_softc_t *sc; int unit; int rid; int error; unit = device_get_unit(dev); sc = device_get_softc(dev); rid = 0; bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid, RF_ACTIVE | RF_SHAREABLE); rid = 0; bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE | RF_SHAREABLE); error = vga_attach_unit(unit, sc, device_get_flags(dev)); if (error) return (error); #ifdef FB_INSTALL_CDEV /* attach a virtual frame buffer device */ error = fb_attach(VGA_MKMINOR(unit), sc->adp, &isavga_cdevsw); if (error) return (error); #endif /* FB_INSTALL_CDEV */ if (0 && bootverbose) vidd_diag(sc->adp, bootverbose); #if 0 /* experimental */ device_add_child(dev, "fb", -1); bus_generic_attach(dev); #endif return (0); } static int isavga_suspend(device_t dev) { int error; error = bus_generic_suspend(dev); if (error != 0) return (error); vga_suspend(dev); return (error); } static int isavga_resume(device_t dev) { vga_resume(dev); return (bus_generic_resume(dev)); } #ifdef FB_INSTALL_CDEV static int isavga_open(struct cdev *dev, int flag, int mode, struct thread *td) { return (vga_open(dev, VGA_SOFTC(VGA_UNIT(dev)), flag, mode, td)); } static int isavga_close(struct cdev *dev, int flag, int mode, struct thread *td) { return (vga_close(dev, VGA_SOFTC(VGA_UNIT(dev)), flag, mode, td)); } static int isavga_read(struct cdev *dev, struct uio *uio, int flag) { return (vga_read(dev, VGA_SOFTC(VGA_UNIT(dev)), uio, flag)); } static int isavga_write(struct cdev *dev, struct uio *uio, int flag) { return (vga_write(dev, VGA_SOFTC(VGA_UNIT(dev)), uio, flag)); } static int isavga_ioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td) { return (vga_ioctl(dev, VGA_SOFTC(VGA_UNIT(dev)), cmd, arg, flag, td)); } static int isavga_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr, int prot, vm_memattr_t *memattr) { return (vga_mmap(dev, VGA_SOFTC(VGA_UNIT(dev)), offset, paddr, prot, memattr)); } #endif /* FB_INSTALL_CDEV */ static device_method_t isavga_methods[] = { DEVMETHOD(device_identify, isavga_identify), DEVMETHOD(device_probe, isavga_probe), DEVMETHOD(device_attach, isavga_attach), DEVMETHOD(device_suspend, isavga_suspend), DEVMETHOD(device_resume, isavga_resume), DEVMETHOD_END }; static driver_t isavga_driver = { VGA_DRIVER_NAME, isavga_methods, sizeof(vga_softc_t), }; DRIVER_MODULE(vga, isa, isavga_driver, isavga_devclass, 0, 0); static devclass_t vgapm_devclass; static void vgapm_identify(driver_t *driver, device_t parent) { if (device_get_flags(parent) != 0) device_add_child(parent, "vgapm", 0); } static int vgapm_probe(device_t dev) { device_set_desc(dev, "VGA suspend/resume"); device_quiet(dev); return (BUS_PROBE_DEFAULT); } static int vgapm_attach(device_t dev) { bus_generic_probe(dev); bus_generic_attach(dev); return (0); } static int vgapm_suspend(device_t dev) { device_t vga_dev; int error; error = bus_generic_suspend(dev); if (error != 0) return (error); vga_dev = devclass_get_device(isavga_devclass, 0); if (vga_dev == NULL) return (0); vga_suspend(vga_dev); return (0); } static int vgapm_resume(device_t dev) { device_t vga_dev; vga_dev = devclass_get_device(isavga_devclass, 0); if (vga_dev != NULL) vga_resume(vga_dev); return (bus_generic_resume(dev)); } static device_method_t vgapm_methods[] = { DEVMETHOD(device_identify, vgapm_identify), DEVMETHOD(device_probe, vgapm_probe), DEVMETHOD(device_attach, vgapm_attach), DEVMETHOD(device_suspend, vgapm_suspend), DEVMETHOD(device_resume, vgapm_resume), { 0, 0 } }; static driver_t vgapm_driver = { "vgapm", vgapm_methods, 0 }; DRIVER_MODULE(vgapm, vgapci, vgapm_driver, vgapm_devclass, 0, 0); +ISA_PNP_INFO(vga_ids); Index: head/sys/powerpc/mpc85xx/atpic.c =================================================================== --- head/sys/powerpc/mpc85xx/atpic.c (revision 328523) +++ head/sys/powerpc/mpc85xx/atpic.c (revision 328524) @@ -1,366 +1,366 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2009 Marcel Moolenaar * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "pic_if.h" #define ATPIC_MASTER 0 #define ATPIC_SLAVE 1 struct atpic_softc { device_t sc_dev; /* I/O port resources for master & slave. */ struct resource *sc_res[2]; int sc_rid[2]; /* Our "routing" interrupt */ struct resource *sc_ires; void *sc_icookie; int sc_irid; int sc_vector[16]; uint8_t sc_mask[2]; }; static int atpic_isa_attach(device_t); static void atpic_isa_identify(driver_t *, device_t); static int atpic_isa_probe(device_t); static void atpic_config(device_t, u_int, enum intr_trigger, enum intr_polarity); static void atpic_dispatch(device_t, struct trapframe *); static void atpic_enable(device_t, u_int, u_int); static void atpic_eoi(device_t, u_int); static void atpic_ipi(device_t, u_int); static void atpic_mask(device_t, u_int); static void atpic_unmask(device_t, u_int); static void atpic_ofw_translate_code(device_t, u_int irq, int code, enum intr_trigger *trig, enum intr_polarity *pol); static device_method_t atpic_isa_methods[] = { /* Device interface */ DEVMETHOD(device_identify, atpic_isa_identify), DEVMETHOD(device_probe, atpic_isa_probe), DEVMETHOD(device_attach, atpic_isa_attach), /* PIC interface */ DEVMETHOD(pic_config, atpic_config), DEVMETHOD(pic_dispatch, atpic_dispatch), DEVMETHOD(pic_enable, atpic_enable), DEVMETHOD(pic_eoi, atpic_eoi), DEVMETHOD(pic_ipi, atpic_ipi), DEVMETHOD(pic_mask, atpic_mask), DEVMETHOD(pic_unmask, atpic_unmask), DEVMETHOD(pic_translate_code, atpic_ofw_translate_code), { 0, 0 }, }; static driver_t atpic_isa_driver = { "atpic", atpic_isa_methods, sizeof(struct atpic_softc) }; static devclass_t atpic_devclass; -DRIVER_MODULE(atpic, isa, atpic_isa_driver, atpic_devclass, 0, 0); - static struct isa_pnp_id atpic_ids[] = { { 0x0000d041 /* PNP0000 */, "AT interrupt controller" }, { 0 } }; +DRIVER_MODULE(atpic, isa, atpic_isa_driver, atpic_devclass, 0, 0); +ISA_PNP_INFO(atpic_ids); + static __inline uint8_t atpic_read(struct atpic_softc *sc, int icu, int ofs) { uint8_t val; val = bus_read_1(sc->sc_res[icu], ofs); return (val); } static __inline void atpic_write(struct atpic_softc *sc, int icu, int ofs, uint8_t val) { bus_write_1(sc->sc_res[icu], ofs, val); bus_barrier(sc->sc_res[icu], ofs, 2 - ofs, BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE); } static void atpic_intr(void *arg) { atpic_dispatch(arg, NULL); } static void atpic_isa_identify(driver_t *drv, device_t parent) { device_t child; child = BUS_ADD_CHILD(parent, ISA_ORDER_SENSITIVE, drv->name, -1); device_set_driver(child, drv); isa_set_logicalid(child, atpic_ids[0].ip_id); isa_set_vendorid(child, atpic_ids[0].ip_id); bus_set_resource(child, SYS_RES_IOPORT, ATPIC_MASTER, IO_ICU1, 2); bus_set_resource(child, SYS_RES_IOPORT, ATPIC_SLAVE, IO_ICU2, 2); /* ISA interrupts are routed through external interrupt 0. */ bus_set_resource(child, SYS_RES_IRQ, 0, 16, 1); } static int atpic_isa_probe(device_t dev) { int res; res = ISA_PNP_PROBE(device_get_parent(dev), dev, atpic_ids); if (res > 0) return (res); device_set_desc(dev, "PC/AT compatible PIC"); return (res); } static void atpic_init(struct atpic_softc *sc, int icu) { sc->sc_mask[icu] = 0xff - ((icu == ATPIC_MASTER) ? 4 : 0); atpic_write(sc, icu, 0, ICW1_RESET | ICW1_IC4); atpic_write(sc, icu, 1, (icu == ATPIC_SLAVE) ? 8 : 0); atpic_write(sc, icu, 1, (icu == ATPIC_SLAVE) ? 2 : 4); atpic_write(sc, icu, 1, ICW4_8086); atpic_write(sc, icu, 1, sc->sc_mask[icu]); atpic_write(sc, icu, 0, OCW3_SEL | OCW3_RR); } static int atpic_isa_attach(device_t dev) { struct atpic_softc *sc; int error; sc = device_get_softc(dev); sc->sc_dev = dev; error = ENXIO; sc->sc_rid[ATPIC_MASTER] = 0; sc->sc_res[ATPIC_MASTER] = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &sc->sc_rid[ATPIC_MASTER], RF_ACTIVE); if (sc->sc_res[ATPIC_MASTER] == NULL) goto fail; sc->sc_rid[ATPIC_SLAVE] = 1; sc->sc_res[ATPIC_SLAVE] = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &sc->sc_rid[ATPIC_SLAVE], RF_ACTIVE); if (sc->sc_res[ATPIC_SLAVE] == NULL) goto fail; sc->sc_irid = 0; sc->sc_ires = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->sc_irid, RF_ACTIVE); if (sc->sc_ires == NULL) goto fail; error = bus_setup_intr(dev, sc->sc_ires, INTR_TYPE_MISC | INTR_MPSAFE, NULL, atpic_intr, dev, &sc->sc_icookie); if (error) goto fail; atpic_init(sc, ATPIC_SLAVE); atpic_init(sc, ATPIC_MASTER); powerpc_register_pic(dev, 0, 16, 0, TRUE); return (0); fail: if (sc->sc_ires != NULL) bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irid, sc->sc_ires); if (sc->sc_res[ATPIC_SLAVE] != NULL) bus_release_resource(dev, SYS_RES_IOPORT, sc->sc_rid[ATPIC_SLAVE], sc->sc_res[ATPIC_SLAVE]); if (sc->sc_res[ATPIC_MASTER] != NULL) bus_release_resource(dev, SYS_RES_IOPORT, sc->sc_rid[ATPIC_MASTER], sc->sc_res[ATPIC_MASTER]); return (error); } /* * PIC interface. */ static void atpic_config(device_t dev, u_int irq, enum intr_trigger trig, enum intr_polarity pol) { } static void atpic_dispatch(device_t dev, struct trapframe *tf) { struct atpic_softc *sc; uint8_t irq; sc = device_get_softc(dev); atpic_write(sc, ATPIC_MASTER, 0, OCW3_SEL | OCW3_P); irq = atpic_read(sc, ATPIC_MASTER, 0); atpic_write(sc, ATPIC_MASTER, 0, OCW3_SEL | OCW3_RR); if ((irq & 0x80) == 0) return; if (irq == 0x82) { atpic_write(sc, ATPIC_SLAVE, 0, OCW3_SEL | OCW3_P); irq = atpic_read(sc, ATPIC_SLAVE, 0) + 8; atpic_write(sc, ATPIC_SLAVE, 0, OCW3_SEL | OCW3_RR); if ((irq & 0x80) == 0) return; } powerpc_dispatch_intr(sc->sc_vector[irq & 0x0f], tf); } static void atpic_enable(device_t dev, u_int irq, u_int vector) { struct atpic_softc *sc; sc = device_get_softc(dev); sc->sc_vector[irq] = vector; atpic_unmask(dev, irq); } static void atpic_eoi(device_t dev, u_int irq) { struct atpic_softc *sc; sc = device_get_softc(dev); if (irq > 7) atpic_write(sc, ATPIC_SLAVE, 0, OCW2_EOI); atpic_write(sc, ATPIC_MASTER, 0, OCW2_EOI); } static void atpic_ipi(device_t dev, u_int cpu) { /* No SMP support. */ } static void atpic_mask(device_t dev, u_int irq) { struct atpic_softc *sc; sc = device_get_softc(dev); if (irq > 7) { sc->sc_mask[ATPIC_SLAVE] |= 1 << (irq - 8); atpic_write(sc, ATPIC_SLAVE, 1, sc->sc_mask[ATPIC_SLAVE]); } else { sc->sc_mask[ATPIC_MASTER] |= 1 << irq; atpic_write(sc, ATPIC_MASTER, 1, sc->sc_mask[ATPIC_MASTER]); } } static void atpic_unmask(device_t dev, u_int irq) { struct atpic_softc *sc; sc = device_get_softc(dev); if (irq > 7) { sc->sc_mask[ATPIC_SLAVE] &= ~(1 << (irq - 8)); atpic_write(sc, ATPIC_SLAVE, 1, sc->sc_mask[ATPIC_SLAVE]); } else { sc->sc_mask[ATPIC_MASTER] &= ~(1 << irq); atpic_write(sc, ATPIC_MASTER, 1, sc->sc_mask[ATPIC_MASTER]); } } static void atpic_ofw_translate_code(device_t dev, u_int irq, int code, enum intr_trigger *trig, enum intr_polarity *pol) { switch (code) { case 0: /* Active L level */ *trig = INTR_TRIGGER_LEVEL; *pol = INTR_POLARITY_LOW; break; case 1: /* Active H level */ *trig = INTR_TRIGGER_LEVEL; *pol = INTR_POLARITY_HIGH; break; case 2: /* H to L edge */ *trig = INTR_TRIGGER_EDGE; *pol = INTR_POLARITY_LOW; break; case 3: /* L to H edge */ *trig = INTR_TRIGGER_EDGE; *pol = INTR_POLARITY_HIGH; break; default: *trig = INTR_TRIGGER_CONFORM; *pol = INTR_POLARITY_CONFORM; } } - Index: head/sys/sparc64/sparc64/rtc.c =================================================================== --- head/sys/sparc64/sparc64/rtc.c (revision 328523) +++ head/sys/sparc64/sparc64/rtc.c (revision 328524) @@ -1,254 +1,255 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2004 Marius Strobl * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * The `rtc' device is found on the ISA bus and the EBus. The ISA version * always is a MC146818 compatible clock while the EBus variant either is the * MC146818 compatible Real-Time Clock function of a National Semiconductor * PC87317/PC97317 which also provides Advanced Power Control functionality * or a Texas Instruments bq4802. */ #include "opt_isa.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "clock_if.h" #define RTC_DESC "Real-Time Clock" #define RTC_READ mc146818_def_read #define RTC_WRITE mc146818_def_write #define PC87317_COMMON MC_REGA_DV0 /* bank 0 */ #define PC87317_RTC (MC_REGA_DV1 | MC_REGA_DV0) /* bank 1 */ #define PC87317_RTC_CR 0x48 /* Century Register */ #define PC87317_APC MC_REGA_DV2 /* bank 2 */ #define PC87317_APC_CADDR 0x51 /* Century Address Register */ #define PC87317_APC_CADDR_BANK0 0x00 /* locate CR in bank 0 */ #define PC87317_APC_CADDR_BANK1 0x80 /* locate CR in bank 1 */ static devclass_t rtc_devclass; static device_attach_t rtc_attach; static device_probe_t rtc_ebus_probe; #ifdef DEV_ISA static device_probe_t rtc_isa_probe; #endif static device_method_t rtc_ebus_methods[] = { /* Device interface */ DEVMETHOD(device_probe, rtc_ebus_probe), DEVMETHOD(device_attach, rtc_attach), /* clock interface */ DEVMETHOD(clock_gettime, mc146818_gettime), DEVMETHOD(clock_settime, mc146818_settime), DEVMETHOD_END }; static driver_t rtc_ebus_driver = { "rtc", rtc_ebus_methods, sizeof(struct mc146818_softc), }; DRIVER_MODULE(rtc, ebus, rtc_ebus_driver, rtc_devclass, 0, 0); #ifdef DEV_ISA static device_method_t rtc_isa_methods[] = { /* Device interface */ DEVMETHOD(device_probe, rtc_isa_probe), DEVMETHOD(device_attach, rtc_attach), /* clock interface */ DEVMETHOD(clock_gettime, mc146818_gettime), DEVMETHOD(clock_settime, mc146818_settime), DEVMETHOD_END }; static driver_t rtc_isa_driver = { "rtc", rtc_isa_methods, sizeof(struct mc146818_softc), }; +static struct isa_pnp_id rtc_isa_ids[] = { + { 0x000bd041, RTC_DESC }, /* PNP0B00 */ + { 0 } +}; + DRIVER_MODULE(rtc, isa, rtc_isa_driver, rtc_devclass, 0, 0); +ISA_PNP_INFO(rtc_isa_ids); #endif static u_int pc87317_getcent(device_t dev); static void pc87317_setcent(device_t dev, u_int cent); static int rtc_ebus_probe(device_t dev) { if (strcmp(ofw_bus_get_name(dev), "rtc") == 0) { /* The bq4802 is not supported, yet. */ if (ofw_bus_get_compat(dev) != NULL && strcmp(ofw_bus_get_compat(dev), "bq4802") == 0) return (ENXIO); device_set_desc(dev, RTC_DESC); return (0); } return (ENXIO); } #ifdef DEV_ISA -static struct isa_pnp_id rtc_isa_ids[] = { - { 0x000bd041, RTC_DESC }, /* PNP0B00 */ - { 0 } -}; - static int rtc_isa_probe(device_t dev) { if (ISA_PNP_PROBE(device_get_parent(dev), dev, rtc_isa_ids) == 0) return (0); return (ENXIO); } #endif static int rtc_attach(device_t dev) { struct timespec ts; struct mc146818_softc *sc; struct resource *res; int ebus, error, rid; sc = device_get_softc(dev); mtx_init(&sc->sc_mtx, "rtc_mtx", NULL, MTX_SPIN); ebus = 0; if (strcmp(device_get_name(device_get_parent(dev)), "ebus") == 0) ebus = 1; rid = 0; res = bus_alloc_resource_any(dev, ebus ? SYS_RES_MEMORY : SYS_RES_IOPORT, &rid, RF_ACTIVE); if (res == NULL) { device_printf(dev, "cannot allocate resources\n"); error = ENXIO; goto fail_mtx; } sc->sc_bst = rman_get_bustag(res); sc->sc_bsh = rman_get_bushandle(res); sc->sc_mcread = RTC_READ; sc->sc_mcwrite = RTC_WRITE; /* The TOD clock year 0 is 0. */ sc->sc_year0 = 0; /* * For ISA use the default century get/set functions, for EBus we * provide our own versions. */ sc->sc_flag = MC146818_NO_CENT_ADJUST; if (ebus) { /* * Make sure the CR is at the default location (also used * by Solaris). */ RTC_WRITE(dev, MC_REGA, PC87317_APC); RTC_WRITE(dev, PC87317_APC_CADDR, PC87317_APC_CADDR_BANK1 | PC87317_RTC_CR); RTC_WRITE(dev, MC_REGA, PC87317_COMMON); sc->sc_getcent = pc87317_getcent; sc->sc_setcent = pc87317_setcent; } if ((error = mc146818_attach(dev)) != 0) { device_printf(dev, "cannot attach time of day clock\n"); goto fail_res; } if (bootverbose) { if (mc146818_gettime(dev, &ts) != 0) device_printf(dev, "invalid time"); else device_printf(dev, "current time: %ld.%09ld\n", (long)ts.tv_sec, ts.tv_nsec); } return (0); fail_res: bus_release_resource(dev, ebus ? SYS_RES_MEMORY : SYS_RES_IOPORT, rid, res); fail_mtx: mtx_destroy(&sc->sc_mtx); return (error); } static u_int pc87317_getcent(device_t dev) { u_int cent; RTC_WRITE(dev, MC_REGA, PC87317_RTC); cent = RTC_READ(dev, PC87317_RTC_CR); RTC_WRITE(dev, MC_REGA, PC87317_COMMON); return (cent); } static void pc87317_setcent(device_t dev, u_int cent) { RTC_WRITE(dev, MC_REGA, PC87317_RTC); RTC_WRITE(dev, PC87317_RTC_CR, cent); RTC_WRITE(dev, MC_REGA, PC87317_COMMON); } Index: head/sys/x86/isa/atpic.c =================================================================== --- head/sys/x86/isa/atpic.c (revision 328523) +++ head/sys/x86/isa/atpic.c (revision 328524) @@ -1,604 +1,605 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2003 John Baldwin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * PIC driver for the 8259A Master and Slave PICs in PC/AT machines. */ #include __FBSDID("$FreeBSD$"); #include "opt_auto_eoi.h" #include "opt_isa.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef __amd64__ #define SDT_ATPIC SDT_SYSIGT #define GSEL_ATPIC 0 #else #define SDT_ATPIC SDT_SYS386IGT #define GSEL_ATPIC GSEL(GCODE_SEL, SEL_KPL) #endif #define MASTER 0 #define SLAVE 1 #define NUM_ISA_IRQS 16 static void atpic_init(void *dummy); unsigned int imen; /* XXX */ inthand_t IDTVEC(atpic_intr0), IDTVEC(atpic_intr1), IDTVEC(atpic_intr2), IDTVEC(atpic_intr3), IDTVEC(atpic_intr4), IDTVEC(atpic_intr5), IDTVEC(atpic_intr6), IDTVEC(atpic_intr7), IDTVEC(atpic_intr8), IDTVEC(atpic_intr9), IDTVEC(atpic_intr10), IDTVEC(atpic_intr11), IDTVEC(atpic_intr12), IDTVEC(atpic_intr13), IDTVEC(atpic_intr14), IDTVEC(atpic_intr15); /* XXXKIB i386 uses stubs until pti comes */ inthand_t IDTVEC(atpic_intr0_pti), IDTVEC(atpic_intr1_pti), IDTVEC(atpic_intr2_pti), IDTVEC(atpic_intr3_pti), IDTVEC(atpic_intr4_pti), IDTVEC(atpic_intr5_pti), IDTVEC(atpic_intr6_pti), IDTVEC(atpic_intr7_pti), IDTVEC(atpic_intr8_pti), IDTVEC(atpic_intr9_pti), IDTVEC(atpic_intr10_pti), IDTVEC(atpic_intr11_pti), IDTVEC(atpic_intr12_pti), IDTVEC(atpic_intr13_pti), IDTVEC(atpic_intr14_pti), IDTVEC(atpic_intr15_pti); #define IRQ(ap, ai) ((ap)->at_irqbase + (ai)->at_irq) #define ATPIC(io, base, eoi, imenptr) \ { { atpic_enable_source, atpic_disable_source, (eoi), \ atpic_enable_intr, atpic_disable_intr, atpic_vector, \ atpic_source_pending, NULL, atpic_resume, atpic_config_intr,\ atpic_assign_cpu }, (io), (base), IDT_IO_INTS + (base), \ (imenptr) } #define INTSRC(irq) \ { { &atpics[(irq) / 8].at_pic }, IDTVEC(atpic_intr ## irq ), \ IDTVEC(atpic_intr ## irq ## _pti), (irq) % 8 } struct atpic { struct pic at_pic; int at_ioaddr; int at_irqbase; uint8_t at_intbase; uint8_t *at_imen; }; struct atpic_intsrc { struct intsrc at_intsrc; inthand_t *at_intr, *at_intr_pti; int at_irq; /* Relative to PIC base. */ enum intr_trigger at_trigger; u_long at_count; u_long at_straycount; }; static void atpic_enable_source(struct intsrc *isrc); static void atpic_disable_source(struct intsrc *isrc, int eoi); static void atpic_eoi_master(struct intsrc *isrc); static void atpic_eoi_slave(struct intsrc *isrc); static void atpic_enable_intr(struct intsrc *isrc); static void atpic_disable_intr(struct intsrc *isrc); static int atpic_vector(struct intsrc *isrc); static void atpic_resume(struct pic *pic, bool suspend_cancelled); static int atpic_source_pending(struct intsrc *isrc); static int atpic_config_intr(struct intsrc *isrc, enum intr_trigger trig, enum intr_polarity pol); static int atpic_assign_cpu(struct intsrc *isrc, u_int apic_id); static void i8259_init(struct atpic *pic, int slave); static struct atpic atpics[] = { ATPIC(IO_ICU1, 0, atpic_eoi_master, (uint8_t *)&imen), ATPIC(IO_ICU2, 8, atpic_eoi_slave, ((uint8_t *)&imen) + 1) }; static struct atpic_intsrc atintrs[] = { INTSRC(0), INTSRC(1), INTSRC(2), INTSRC(3), INTSRC(4), INTSRC(5), INTSRC(6), INTSRC(7), INTSRC(8), INTSRC(9), INTSRC(10), INTSRC(11), INTSRC(12), INTSRC(13), INTSRC(14), INTSRC(15), }; CTASSERT(nitems(atintrs) == NUM_ISA_IRQS); static __inline void _atpic_eoi_master(struct intsrc *isrc) { KASSERT(isrc->is_pic == &atpics[MASTER].at_pic, ("%s: mismatched pic", __func__)); #ifndef AUTO_EOI_1 outb(atpics[MASTER].at_ioaddr, OCW2_EOI); #endif } /* * The data sheet says no auto-EOI on slave, but it sometimes works. * So, if AUTO_EOI_2 is enabled, we use it. */ static __inline void _atpic_eoi_slave(struct intsrc *isrc) { KASSERT(isrc->is_pic == &atpics[SLAVE].at_pic, ("%s: mismatched pic", __func__)); #ifndef AUTO_EOI_2 outb(atpics[SLAVE].at_ioaddr, OCW2_EOI); #ifndef AUTO_EOI_1 outb(atpics[MASTER].at_ioaddr, OCW2_EOI); #endif #endif } static void atpic_enable_source(struct intsrc *isrc) { struct atpic_intsrc *ai = (struct atpic_intsrc *)isrc; struct atpic *ap = (struct atpic *)isrc->is_pic; spinlock_enter(); if (*ap->at_imen & IMEN_MASK(ai)) { *ap->at_imen &= ~IMEN_MASK(ai); outb(ap->at_ioaddr + ICU_IMR_OFFSET, *ap->at_imen); } spinlock_exit(); } static void atpic_disable_source(struct intsrc *isrc, int eoi) { struct atpic_intsrc *ai = (struct atpic_intsrc *)isrc; struct atpic *ap = (struct atpic *)isrc->is_pic; spinlock_enter(); if (ai->at_trigger != INTR_TRIGGER_EDGE) { *ap->at_imen |= IMEN_MASK(ai); outb(ap->at_ioaddr + ICU_IMR_OFFSET, *ap->at_imen); } /* * Take care to call these functions directly instead of through * a function pointer. All of the referenced variables should * still be hot in the cache. */ if (eoi == PIC_EOI) { if (isrc->is_pic == &atpics[MASTER].at_pic) _atpic_eoi_master(isrc); else _atpic_eoi_slave(isrc); } spinlock_exit(); } static void atpic_eoi_master(struct intsrc *isrc) { #ifndef AUTO_EOI_1 spinlock_enter(); _atpic_eoi_master(isrc); spinlock_exit(); #endif } static void atpic_eoi_slave(struct intsrc *isrc) { #ifndef AUTO_EOI_2 spinlock_enter(); _atpic_eoi_slave(isrc); spinlock_exit(); #endif } static void atpic_enable_intr(struct intsrc *isrc) { } static void atpic_disable_intr(struct intsrc *isrc) { } static int atpic_vector(struct intsrc *isrc) { struct atpic_intsrc *ai = (struct atpic_intsrc *)isrc; struct atpic *ap = (struct atpic *)isrc->is_pic; return (IRQ(ap, ai)); } static int atpic_source_pending(struct intsrc *isrc) { struct atpic_intsrc *ai = (struct atpic_intsrc *)isrc; struct atpic *ap = (struct atpic *)isrc->is_pic; return (inb(ap->at_ioaddr) & IMEN_MASK(ai)); } static void atpic_resume(struct pic *pic, bool suspend_cancelled) { struct atpic *ap = (struct atpic *)pic; i8259_init(ap, ap == &atpics[SLAVE]); if (ap == &atpics[SLAVE] && elcr_found) elcr_resume(); } static int atpic_config_intr(struct intsrc *isrc, enum intr_trigger trig, enum intr_polarity pol) { struct atpic_intsrc *ai = (struct atpic_intsrc *)isrc; u_int vector; /* Map conforming values to edge/hi and sanity check the values. */ if (trig == INTR_TRIGGER_CONFORM) trig = INTR_TRIGGER_EDGE; if (pol == INTR_POLARITY_CONFORM) pol = INTR_POLARITY_HIGH; vector = atpic_vector(isrc); if ((trig == INTR_TRIGGER_EDGE && pol == INTR_POLARITY_LOW) || (trig == INTR_TRIGGER_LEVEL && pol == INTR_POLARITY_HIGH)) { printf( "atpic: Mismatched config for IRQ%u: trigger %s, polarity %s\n", vector, trig == INTR_TRIGGER_EDGE ? "edge" : "level", pol == INTR_POLARITY_HIGH ? "high" : "low"); return (EINVAL); } /* If there is no change, just return. */ if (ai->at_trigger == trig) return (0); /* * Certain IRQs can never be level/lo, so don't try to set them * that way if asked. At least some ELCR registers ignore setting * these bits as well. */ if ((vector == 0 || vector == 1 || vector == 2 || vector == 13) && trig == INTR_TRIGGER_LEVEL) { if (bootverbose) printf( "atpic: Ignoring invalid level/low configuration for IRQ%u\n", vector); return (EINVAL); } if (!elcr_found) { if (bootverbose) printf("atpic: No ELCR to configure IRQ%u as %s\n", vector, trig == INTR_TRIGGER_EDGE ? "edge/high" : "level/low"); return (ENXIO); } if (bootverbose) printf("atpic: Programming IRQ%u as %s\n", vector, trig == INTR_TRIGGER_EDGE ? "edge/high" : "level/low"); spinlock_enter(); elcr_write_trigger(atpic_vector(isrc), trig); ai->at_trigger = trig; spinlock_exit(); return (0); } static int atpic_assign_cpu(struct intsrc *isrc, u_int apic_id) { /* * 8259A's are only used in UP in which case all interrupts always * go to the sole CPU and this function shouldn't even be called. */ panic("%s: bad cookie", __func__); } static void i8259_init(struct atpic *pic, int slave) { int imr_addr; /* Reset the PIC and program with next four bytes. */ spinlock_enter(); outb(pic->at_ioaddr, ICW1_RESET | ICW1_IC4); imr_addr = pic->at_ioaddr + ICU_IMR_OFFSET; /* Start vector. */ outb(imr_addr, pic->at_intbase); /* * Setup slave links. For the master pic, indicate what line * the slave is configured on. For the slave indicate * which line on the master we are connected to. */ if (slave) outb(imr_addr, ICU_SLAVEID); else outb(imr_addr, IRQ_MASK(ICU_SLAVEID)); /* Set mode. */ if (slave) outb(imr_addr, SLAVE_MODE); else outb(imr_addr, MASTER_MODE); /* Set interrupt enable mask. */ outb(imr_addr, *pic->at_imen); /* Reset is finished, default to IRR on read. */ outb(pic->at_ioaddr, OCW3_SEL | OCW3_RR); /* OCW2_L1 sets priority order to 3-7, 0-2 (com2 first). */ if (!slave) outb(pic->at_ioaddr, OCW2_R | OCW2_SL | OCW2_L1); spinlock_exit(); } void atpic_startup(void) { struct atpic_intsrc *ai; int i; /* Start off with all interrupts disabled. */ imen = 0xffff; i8259_init(&atpics[MASTER], 0); i8259_init(&atpics[SLAVE], 1); atpic_enable_source((struct intsrc *)&atintrs[ICU_SLAVEID]); /* Install low-level interrupt handlers for all of our IRQs. */ for (i = 0, ai = atintrs; i < NUM_ISA_IRQS; i++, ai++) { if (i == ICU_SLAVEID) continue; ai->at_intsrc.is_count = &ai->at_count; ai->at_intsrc.is_straycount = &ai->at_straycount; setidt(((struct atpic *)ai->at_intsrc.is_pic)->at_intbase + ai->at_irq, pti ? ai->at_intr_pti : ai->at_intr, SDT_ATPIC, SEL_KPL, GSEL_ATPIC); } /* * Look for an ELCR. If we find one, update the trigger modes. * If we don't find one, assume that IRQs 0, 1, 2, and 13 are * edge triggered and that everything else is level triggered. * We only use the trigger information to reprogram the ELCR if * we have one and as an optimization to avoid masking edge * triggered interrupts. For the case that we don't have an ELCR, * it doesn't hurt to mask an edge triggered interrupt, so we * assume level trigger for any interrupt that we aren't sure is * edge triggered. */ if (elcr_found) { for (i = 0, ai = atintrs; i < NUM_ISA_IRQS; i++, ai++) ai->at_trigger = elcr_read_trigger(i); } else { for (i = 0, ai = atintrs; i < NUM_ISA_IRQS; i++, ai++) switch (i) { case 0: case 1: case 2: case 8: case 13: ai->at_trigger = INTR_TRIGGER_EDGE; break; default: ai->at_trigger = INTR_TRIGGER_LEVEL; break; } } } static void atpic_init(void *dummy __unused) { struct atpic_intsrc *ai; int i; /* * Register our PICs, even if we aren't going to use any of their * pins so that they are suspended and resumed. */ if (intr_register_pic(&atpics[0].at_pic) != 0 || intr_register_pic(&atpics[1].at_pic) != 0) panic("Unable to register ATPICs"); /* * If any of the ISA IRQs have an interrupt source already, then * assume that the APICs are being used and don't register any * of our interrupt sources. This makes sure we don't accidentally * use mixed mode. The "accidental" use could otherwise occur on * machines that route the ACPI SCI interrupt to a different ISA * IRQ (at least one machines routes it to IRQ 13) thus disabling * that APIC ISA routing and allowing the ATPIC source for that IRQ * to leak through. We used to depend on this feature for routing * IRQ0 via mixed mode, but now we don't use mixed mode at all. */ for (i = 0; i < NUM_ISA_IRQS; i++) if (intr_lookup_source(i) != NULL) return; /* Loop through all interrupt sources and add them. */ for (i = 0, ai = atintrs; i < NUM_ISA_IRQS; i++, ai++) { if (i == ICU_SLAVEID) continue; intr_register_source(&ai->at_intsrc); } } SYSINIT(atpic_init, SI_SUB_INTR, SI_ORDER_FOURTH, atpic_init, NULL); void atpic_handle_intr(u_int vector, struct trapframe *frame) { struct intsrc *isrc; KASSERT(vector < NUM_ISA_IRQS, ("unknown int %u\n", vector)); isrc = &atintrs[vector].at_intsrc; /* * If we don't have an event, see if this is a spurious * interrupt. */ if (isrc->is_event == NULL && (vector == 7 || vector == 15)) { int port, isr; /* * Read the ISR register to see if IRQ 7/15 is really * pending. Reset read register back to IRR when done. */ port = ((struct atpic *)isrc->is_pic)->at_ioaddr; spinlock_enter(); outb(port, OCW3_SEL | OCW3_RR | OCW3_RIS); isr = inb(port); outb(port, OCW3_SEL | OCW3_RR); spinlock_exit(); if ((isr & IRQ_MASK(7)) == 0) return; } intr_execute_handlers(isrc, frame); } #ifdef DEV_ISA /* * Bus attachment for the ISA PIC. */ static struct isa_pnp_id atpic_ids[] = { { 0x0000d041 /* PNP0000 */, "AT interrupt controller" }, { 0 } }; static int atpic_probe(device_t dev) { int result; result = ISA_PNP_PROBE(device_get_parent(dev), dev, atpic_ids); if (result <= 0) device_quiet(dev); return (result); } /* * We might be granted IRQ 2, as this is typically consumed by chaining * between the two PIC components. If we're using the APIC, however, * this may not be the case, and as such we should free the resource. * (XXX untested) * * The generic ISA attachment code will handle allocating any other resources * that we don't explicitly claim here. */ static int atpic_attach(device_t dev) { struct resource *res; int rid; /* Try to allocate our IRQ and then free it. */ rid = 0; res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, 0); if (res != NULL) bus_release_resource(dev, SYS_RES_IRQ, rid, res); return (0); } +/* + * Return a bitmap of the current interrupt requests. This is 8259-specific + * and is only suitable for use at probe time. + */ +intrmask_t +isa_irq_pending(void) +{ + u_char irr1; + u_char irr2; + + irr1 = inb(IO_ICU1); + irr2 = inb(IO_ICU2); + return ((irr2 << 8) | irr1); +} + static device_method_t atpic_methods[] = { /* Device interface */ DEVMETHOD(device_probe, atpic_probe), DEVMETHOD(device_attach, atpic_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), { 0, 0 } }; static driver_t atpic_driver = { "atpic", atpic_methods, 1, /* no softc */ }; static devclass_t atpic_devclass; DRIVER_MODULE(atpic, isa, atpic_driver, atpic_devclass, 0, 0); DRIVER_MODULE(atpic, acpi, atpic_driver, atpic_devclass, 0, 0); - -/* - * Return a bitmap of the current interrupt requests. This is 8259-specific - * and is only suitable for use at probe time. - */ -intrmask_t -isa_irq_pending(void) -{ - u_char irr1; - u_char irr2; - - irr1 = inb(IO_ICU1); - irr2 = inb(IO_ICU2); - return ((irr2 << 8) | irr1); -} +ISA_PNP_INFO(atpic_ids); #endif /* DEV_ISA */ Index: head/sys/x86/isa/atrtc.c =================================================================== --- head/sys/x86/isa/atrtc.c (revision 328523) +++ head/sys/x86/isa/atrtc.c (revision 328524) @@ -1,430 +1,431 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2008 Poul-Henning Kamp * Copyright (c) 2010 Alexander Motin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include __FBSDID("$FreeBSD$"); #include "opt_isa.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef DEV_ISA #include #include #endif #include #include "clock_if.h" /* * clock_lock protects low-level access to individual hardware registers. * atrtc_time_lock protects the entire sequence of accessing multiple registers * to read or write the date and time. */ #define RTC_LOCK do { if (!kdb_active) mtx_lock_spin(&clock_lock); } while (0) #define RTC_UNLOCK do { if (!kdb_active) mtx_unlock_spin(&clock_lock); } while (0) struct mtx atrtc_time_lock; MTX_SYSINIT(atrtc_lock_init, &atrtc_time_lock, "atrtc", MTX_DEF); int atrtcclock_disable = 0; static int rtc_reg = -1; static u_char rtc_statusa = RTCSA_DIVIDER | RTCSA_NOPROF; static u_char rtc_statusb = RTCSB_24HR; /* * RTC support routines */ static inline u_char rtcin_locked(int reg) { if (rtc_reg != reg) { inb(0x84); outb(IO_RTC, reg); rtc_reg = reg; inb(0x84); } return (inb(IO_RTC + 1)); } static inline void rtcout_locked(int reg, u_char val) { if (rtc_reg != reg) { inb(0x84); outb(IO_RTC, reg); rtc_reg = reg; inb(0x84); } outb(IO_RTC + 1, val); inb(0x84); } int rtcin(int reg) { u_char val; RTC_LOCK; val = rtcin_locked(reg); RTC_UNLOCK; return (val); } void writertc(int reg, u_char val) { RTC_LOCK; rtcout_locked(reg, val); RTC_UNLOCK; } static void atrtc_start(void) { writertc(RTC_STATUSA, rtc_statusa); writertc(RTC_STATUSB, RTCSB_24HR); } static void atrtc_rate(unsigned rate) { rtc_statusa = RTCSA_DIVIDER | rate; writertc(RTC_STATUSA, rtc_statusa); } static void atrtc_enable_intr(void) { rtc_statusb |= RTCSB_PINTR; writertc(RTC_STATUSB, rtc_statusb); rtcin(RTC_INTR); } static void atrtc_disable_intr(void) { rtc_statusb &= ~RTCSB_PINTR; writertc(RTC_STATUSB, rtc_statusb); rtcin(RTC_INTR); } void atrtc_restore(void) { /* Restore all of the RTC's "status" (actually, control) registers. */ rtcin(RTC_STATUSA); /* dummy to get rtc_reg set */ writertc(RTC_STATUSB, RTCSB_24HR); writertc(RTC_STATUSA, rtc_statusa); writertc(RTC_STATUSB, rtc_statusb); rtcin(RTC_INTR); } /********************************************************************** * RTC driver for subr_rtc */ struct atrtc_softc { int port_rid, intr_rid; struct resource *port_res; struct resource *intr_res; void *intr_handler; struct eventtimer et; }; static int rtc_start(struct eventtimer *et, sbintime_t first, sbintime_t period) { atrtc_rate(max(fls(period + (period >> 1)) - 17, 1)); atrtc_enable_intr(); return (0); } static int rtc_stop(struct eventtimer *et) { atrtc_disable_intr(); return (0); } /* * This routine receives statistical clock interrupts from the RTC. * As explained above, these occur at 128 interrupts per second. * When profiling, we receive interrupts at a rate of 1024 Hz. * * This does not actually add as much overhead as it sounds, because * when the statistical clock is active, the hardclock driver no longer * needs to keep (inaccurate) statistics on its own. This decouples * statistics gathering from scheduling interrupts. * * The RTC chip requires that we read status register C (RTC_INTR) * to acknowledge an interrupt, before it will generate the next one. * Under high interrupt load, rtcintr() can be indefinitely delayed and * the clock can tick immediately after the read from RTC_INTR. In this * case, the mc146818A interrupt signal will not drop for long enough * to register with the 8259 PIC. If an interrupt is missed, the stat * clock will halt, considerably degrading system performance. This is * why we use 'while' rather than a more straightforward 'if' below. * Stat clock ticks can still be lost, causing minor loss of accuracy * in the statistics, but the stat clock will no longer stop. */ static int rtc_intr(void *arg) { struct atrtc_softc *sc = (struct atrtc_softc *)arg; int flag = 0; while (rtcin(RTC_INTR) & RTCIR_PERIOD) { flag = 1; if (sc->et.et_active) sc->et.et_event_cb(&sc->et, sc->et.et_arg); } return(flag ? FILTER_HANDLED : FILTER_STRAY); } /* * Attach to the ISA PnP descriptors for the timer and realtime clock. */ static struct isa_pnp_id atrtc_ids[] = { { 0x000bd041 /* PNP0B00 */, "AT realtime clock" }, { 0 } }; static int atrtc_probe(device_t dev) { int result; result = ISA_PNP_PROBE(device_get_parent(dev), dev, atrtc_ids); /* ENOENT means no PnP-ID, device is hinted. */ if (result == ENOENT) { device_set_desc(dev, "AT realtime clock"); return (BUS_PROBE_LOW_PRIORITY); } return (result); } static int atrtc_attach(device_t dev) { struct atrtc_softc *sc; rman_res_t s; int i; sc = device_get_softc(dev); sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT, &sc->port_rid, IO_RTC, IO_RTC + 1, 2, RF_ACTIVE); if (sc->port_res == NULL) device_printf(dev, "Warning: Couldn't map I/O.\n"); atrtc_start(); clock_register(dev, 1000000); bzero(&sc->et, sizeof(struct eventtimer)); if (!atrtcclock_disable && (resource_int_value(device_get_name(dev), device_get_unit(dev), "clock", &i) != 0 || i != 0)) { sc->intr_rid = 0; while (bus_get_resource(dev, SYS_RES_IRQ, sc->intr_rid, &s, NULL) == 0 && s != 8) sc->intr_rid++; sc->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ, &sc->intr_rid, 8, 8, 1, RF_ACTIVE); if (sc->intr_res == NULL) { device_printf(dev, "Can't map interrupt.\n"); return (0); } else if ((bus_setup_intr(dev, sc->intr_res, INTR_TYPE_CLK, rtc_intr, NULL, sc, &sc->intr_handler))) { device_printf(dev, "Can't setup interrupt.\n"); return (0); } else { /* Bind IRQ to BSP to avoid live migration. */ bus_bind_intr(dev, sc->intr_res, 0); } sc->et.et_name = "RTC"; sc->et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_POW2DIV; sc->et.et_quality = 0; sc->et.et_frequency = 32768; sc->et.et_min_period = 0x00080000; sc->et.et_max_period = 0x80000000; sc->et.et_start = rtc_start; sc->et.et_stop = rtc_stop; sc->et.et_priv = dev; et_register(&sc->et); } return(0); } static int atrtc_resume(device_t dev) { atrtc_restore(); return(0); } static int atrtc_settime(device_t dev __unused, struct timespec *ts) { struct bcd_clocktime bct; clock_ts_to_bcd(ts, &bct, false); mtx_lock(&atrtc_time_lock); RTC_LOCK; /* Disable RTC updates and interrupts. */ rtcout_locked(RTC_STATUSB, RTCSB_HALT | RTCSB_24HR); /* Write all the time registers. */ rtcout_locked(RTC_SEC, bct.sec); rtcout_locked(RTC_MIN, bct.min); rtcout_locked(RTC_HRS, bct.hour); rtcout_locked(RTC_WDAY, bct.dow + 1); rtcout_locked(RTC_DAY, bct.day); rtcout_locked(RTC_MONTH, bct.mon); rtcout_locked(RTC_YEAR, bct.year & 0xff); #ifdef USE_RTC_CENTURY rtcout_locked(RTC_CENTURY, bct.year >> 8); #endif /* * Re-enable RTC updates and interrupts. */ rtcout_locked(RTC_STATUSB, rtc_statusb); rtcin_locked(RTC_INTR); RTC_UNLOCK; mtx_unlock(&atrtc_time_lock); return (0); } static int atrtc_gettime(device_t dev, struct timespec *ts) { struct bcd_clocktime bct; /* Look if we have a RTC present and the time is valid */ if (!(rtcin(RTC_STATUSD) & RTCSD_PWR)) { device_printf(dev, "WARNING: Battery failure indication\n"); return (EINVAL); } /* * wait for time update to complete * If RTCSA_TUP is zero, we have at least 244us before next update. * This is fast enough on most hardware, but a refinement would be * to make sure that no more than 240us pass after we start reading, * and try again if so. */ mtx_lock(&atrtc_time_lock); while (rtcin(RTC_STATUSA) & RTCSA_TUP) continue; RTC_LOCK; bct.sec = rtcin_locked(RTC_SEC); bct.min = rtcin_locked(RTC_MIN); bct.hour = rtcin_locked(RTC_HRS); bct.day = rtcin_locked(RTC_DAY); bct.mon = rtcin_locked(RTC_MONTH); bct.year = rtcin_locked(RTC_YEAR); #ifdef USE_RTC_CENTURY bct.year |= rtcin_locked(RTC_CENTURY) << 8; #endif RTC_UNLOCK; mtx_unlock(&atrtc_time_lock); /* dow is unused in timespec conversion and we have no nsec info. */ bct.dow = 0; bct.nsec = 0; return (clock_bcd_to_ts(&bct, ts, false)); } static device_method_t atrtc_methods[] = { /* Device interface */ DEVMETHOD(device_probe, atrtc_probe), DEVMETHOD(device_attach, atrtc_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), /* XXX stop statclock? */ DEVMETHOD(device_resume, atrtc_resume), /* clock interface */ DEVMETHOD(clock_gettime, atrtc_gettime), DEVMETHOD(clock_settime, atrtc_settime), { 0, 0 } }; static driver_t atrtc_driver = { "atrtc", atrtc_methods, sizeof(struct atrtc_softc), }; static devclass_t atrtc_devclass; DRIVER_MODULE(atrtc, isa, atrtc_driver, atrtc_devclass, 0, 0); DRIVER_MODULE(atrtc, acpi, atrtc_driver, atrtc_devclass, 0, 0); +ISA_PNP_INFO(atrtc_ids); #include "opt_ddb.h" #ifdef DDB #include DB_SHOW_COMMAND(rtc, rtc) { printf("%02x/%02x/%02x %02x:%02x:%02x, A = %02x, B = %02x, C = %02x\n", rtcin(RTC_YEAR), rtcin(RTC_MONTH), rtcin(RTC_DAY), rtcin(RTC_HRS), rtcin(RTC_MIN), rtcin(RTC_SEC), rtcin(RTC_STATUSA), rtcin(RTC_STATUSB), rtcin(RTC_INTR)); } #endif /* DDB */ Index: head/sys/x86/isa/clock.c =================================================================== --- head/sys/x86/isa/clock.c (revision 328523) +++ head/sys/x86/isa/clock.c (revision 328524) @@ -1,671 +1,672 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 1990 The Regents of the University of California. * Copyright (c) 2010 Alexander Motin * All rights reserved. * * This code is derived from software contributed to Berkeley by * William Jolitz and Don Ahn. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)clock.c 7.2 (Berkeley) 5/12/91 */ #include __FBSDID("$FreeBSD$"); /* * Routines to handle clock hardware. */ #include "opt_clock.h" #include "opt_isa.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef DEV_ISA #include #include #endif int clkintr_pending; #ifndef TIMER_FREQ #define TIMER_FREQ 1193182 #endif u_int i8254_freq = TIMER_FREQ; TUNABLE_INT("hw.i8254.freq", &i8254_freq); int i8254_max_count; static int i8254_timecounter = 1; struct mtx clock_lock; static struct intsrc *i8254_intsrc; static uint16_t i8254_lastcount; static uint16_t i8254_offset; static int (*i8254_pending)(struct intsrc *); static int i8254_ticked; struct attimer_softc { int intr_en; int port_rid, intr_rid; struct resource *port_res; struct resource *intr_res; void *intr_handler; struct timecounter tc; struct eventtimer et; int mode; #define MODE_STOP 0 #define MODE_PERIODIC 1 #define MODE_ONESHOT 2 uint32_t period; }; static struct attimer_softc *attimer_sc = NULL; static int timer0_period = -2; static int timer0_mode = 0xffff; static int timer0_last = 0xffff; /* Values for timerX_state: */ #define RELEASED 0 #define RELEASE_PENDING 1 #define ACQUIRED 2 #define ACQUIRE_PENDING 3 static u_char timer2_state; static unsigned i8254_get_timecount(struct timecounter *tc); static void set_i8254_freq(int mode, uint32_t period); void clock_init(void) { /* Init the clock lock */ mtx_init(&clock_lock, "clk", NULL, MTX_SPIN | MTX_NOPROFILE); /* Init the clock in order to use DELAY */ init_ops.early_clock_source_init(); } static int clkintr(void *arg) { struct attimer_softc *sc = (struct attimer_softc *)arg; if (i8254_timecounter && sc->period != 0) { mtx_lock_spin(&clock_lock); if (i8254_ticked) i8254_ticked = 0; else { i8254_offset += i8254_max_count; i8254_lastcount = 0; } clkintr_pending = 0; mtx_unlock_spin(&clock_lock); } if (sc->et.et_active && sc->mode != MODE_STOP) sc->et.et_event_cb(&sc->et, sc->et.et_arg); return (FILTER_HANDLED); } int timer_spkr_acquire(void) { int mode; mode = TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT; if (timer2_state != RELEASED) return (-1); timer2_state = ACQUIRED; /* * This access to the timer registers is as atomic as possible * because it is a single instruction. We could do better if we * knew the rate. Use of splclock() limits glitches to 10-100us, * and this is probably good enough for timer2, so we aren't as * careful with it as with timer0. */ outb(TIMER_MODE, TIMER_SEL2 | (mode & 0x3f)); ppi_spkr_on(); /* enable counter2 output to speaker */ return (0); } int timer_spkr_release(void) { if (timer2_state != ACQUIRED) return (-1); timer2_state = RELEASED; outb(TIMER_MODE, TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT); ppi_spkr_off(); /* disable counter2 output to speaker */ return (0); } void timer_spkr_setfreq(int freq) { freq = i8254_freq / freq; mtx_lock_spin(&clock_lock); outb(TIMER_CNTR2, freq & 0xff); outb(TIMER_CNTR2, freq >> 8); mtx_unlock_spin(&clock_lock); } static int getit(void) { int high, low; mtx_lock_spin(&clock_lock); /* Select timer0 and latch counter value. */ outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); low = inb(TIMER_CNTR0); high = inb(TIMER_CNTR0); mtx_unlock_spin(&clock_lock); return ((high << 8) | low); } /* * Wait "n" microseconds. * Relies on timer 1 counting down from (i8254_freq / hz) * Note: timer had better have been programmed before this is first used! */ void i8254_delay(int n) { int delta, prev_tick, tick, ticks_left; #ifdef DELAYDEBUG int getit_calls = 1; int n1; static int state = 0; if (state == 0) { state = 1; for (n1 = 1; n1 <= 10000000; n1 *= 10) DELAY(n1); state = 2; } if (state == 1) printf("DELAY(%d)...", n); #endif /* * Read the counter first, so that the rest of the setup overhead is * counted. Guess the initial overhead is 20 usec (on most systems it * takes about 1.5 usec for each of the i/o's in getit(). The loop * takes about 6 usec on a 486/33 and 13 usec on a 386/20. The * multiplications and divisions to scale the count take a while). * * However, if ddb is active then use a fake counter since reading * the i8254 counter involves acquiring a lock. ddb must not do * locking for many reasons, but it calls here for at least atkbd * input. */ #ifdef KDB if (kdb_active) prev_tick = 1; else #endif prev_tick = getit(); n -= 0; /* XXX actually guess no initial overhead */ /* * Calculate (n * (i8254_freq / 1e6)) without using floating point * and without any avoidable overflows. */ if (n <= 0) ticks_left = 0; else if (n < 256) /* * Use fixed point to avoid a slow division by 1000000. * 39099 = 1193182 * 2^15 / 10^6 rounded to nearest. * 2^15 is the first power of 2 that gives exact results * for n between 0 and 256. */ ticks_left = ((u_int)n * 39099 + (1 << 15) - 1) >> 15; else /* * Don't bother using fixed point, although gcc-2.7.2 * generates particularly poor code for the long long * division, since even the slow way will complete long * before the delay is up (unless we're interrupted). */ ticks_left = ((u_int)n * (long long)i8254_freq + 999999) / 1000000; while (ticks_left > 0) { #ifdef KDB if (kdb_active) { inb(0x84); tick = prev_tick - 1; if (tick <= 0) tick = i8254_max_count; } else #endif tick = getit(); #ifdef DELAYDEBUG ++getit_calls; #endif delta = prev_tick - tick; prev_tick = tick; if (delta < 0) { delta += i8254_max_count; /* * Guard against i8254_max_count being wrong. * This shouldn't happen in normal operation, * but it may happen if set_i8254_freq() is * traced. */ if (delta < 0) delta = 0; } ticks_left -= delta; } #ifdef DELAYDEBUG if (state == 1) printf(" %d calls to getit() at %d usec each\n", getit_calls, (n + 5) / getit_calls); #endif } static void set_i8254_freq(int mode, uint32_t period) { int new_count, new_mode; mtx_lock_spin(&clock_lock); if (mode == MODE_STOP) { if (i8254_timecounter) { mode = MODE_PERIODIC; new_count = 0x10000; } else new_count = -1; } else { new_count = min(((uint64_t)i8254_freq * period + 0x80000000LLU) >> 32, 0x10000); } if (new_count == timer0_period) goto out; i8254_max_count = ((new_count & ~0xffff) != 0) ? 0xffff : new_count; timer0_period = (mode == MODE_PERIODIC) ? new_count : -1; switch (mode) { case MODE_STOP: new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT; outb(TIMER_MODE, new_mode); outb(TIMER_CNTR0, 0); outb(TIMER_CNTR0, 0); break; case MODE_PERIODIC: new_mode = TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT; outb(TIMER_MODE, new_mode); outb(TIMER_CNTR0, new_count & 0xff); outb(TIMER_CNTR0, new_count >> 8); break; case MODE_ONESHOT: if (new_count < 256 && timer0_last < 256) { new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_LSB; if (new_mode != timer0_mode) outb(TIMER_MODE, new_mode); outb(TIMER_CNTR0, new_count & 0xff); break; } new_mode = TIMER_SEL0 | TIMER_INTTC | TIMER_16BIT; if (new_mode != timer0_mode) outb(TIMER_MODE, new_mode); outb(TIMER_CNTR0, new_count & 0xff); outb(TIMER_CNTR0, new_count >> 8); break; default: panic("set_i8254_freq: unknown operational mode"); } timer0_mode = new_mode; timer0_last = new_count; out: mtx_unlock_spin(&clock_lock); } static void i8254_restore(void) { timer0_period = -2; timer0_mode = 0xffff; timer0_last = 0xffff; if (attimer_sc != NULL) set_i8254_freq(attimer_sc->mode, attimer_sc->period); else set_i8254_freq(MODE_STOP, 0); } #ifndef __amd64__ /* * Restore all the timers non-atomically (XXX: should be atomically). * * This function is called from pmtimer_resume() to restore all the timers. * This should not be necessary, but there are broken laptops that do not * restore all the timers on resume. The APM spec was at best vague on the * subject. * pmtimer is used only with the old APM power management, and not with * acpi, which is required for amd64, so skip it in that case. */ void timer_restore(void) { i8254_restore(); /* restore i8254_freq and hz */ atrtc_restore(); /* reenable RTC interrupts */ } #endif /* This is separate from startrtclock() so that it can be called early. */ void i8254_init(void) { set_i8254_freq(MODE_STOP, 0); } void startrtclock() { init_TSC(); } void cpu_initclocks(void) { #ifdef EARLY_AP_STARTUP struct thread *td; int i; td = curthread; cpu_initclocks_bsp(); CPU_FOREACH(i) { if (i == 0) continue; thread_lock(td); sched_bind(td, i); thread_unlock(td); cpu_initclocks_ap(); } thread_lock(td); if (sched_is_bound(td)) sched_unbind(td); thread_unlock(td); #else cpu_initclocks_bsp(); #endif } static int sysctl_machdep_i8254_freq(SYSCTL_HANDLER_ARGS) { int error; u_int freq; /* * Use `i8254' instead of `timer' in external names because `timer' * is too generic. Should use it everywhere. */ freq = i8254_freq; error = sysctl_handle_int(oidp, &freq, 0, req); if (error == 0 && req->newptr != NULL) { i8254_freq = freq; if (attimer_sc != NULL) { set_i8254_freq(attimer_sc->mode, attimer_sc->period); attimer_sc->tc.tc_frequency = freq; } else { set_i8254_freq(MODE_STOP, 0); } } return (error); } SYSCTL_PROC(_machdep, OID_AUTO, i8254_freq, CTLTYPE_INT | CTLFLAG_RW, 0, sizeof(u_int), sysctl_machdep_i8254_freq, "IU", "i8254 timer frequency"); static unsigned i8254_get_timecount(struct timecounter *tc) { device_t dev = (device_t)tc->tc_priv; struct attimer_softc *sc = device_get_softc(dev); register_t flags; uint16_t count; u_int high, low; if (sc->period == 0) return (i8254_max_count - getit()); #ifdef __amd64__ flags = read_rflags(); #else flags = read_eflags(); #endif mtx_lock_spin(&clock_lock); /* Select timer0 and latch counter value. */ outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); low = inb(TIMER_CNTR0); high = inb(TIMER_CNTR0); count = i8254_max_count - ((high << 8) | low); if (count < i8254_lastcount || (!i8254_ticked && (clkintr_pending || ((count < 20 || (!(flags & PSL_I) && count < i8254_max_count / 2u)) && i8254_pending != NULL && i8254_pending(i8254_intsrc))))) { i8254_ticked = 1; i8254_offset += i8254_max_count; } i8254_lastcount = count; count += i8254_offset; mtx_unlock_spin(&clock_lock); return (count); } static int attimer_start(struct eventtimer *et, sbintime_t first, sbintime_t period) { device_t dev = (device_t)et->et_priv; struct attimer_softc *sc = device_get_softc(dev); if (period != 0) { sc->mode = MODE_PERIODIC; sc->period = period; } else { sc->mode = MODE_ONESHOT; sc->period = first; } if (!sc->intr_en) { i8254_intsrc->is_pic->pic_enable_source(i8254_intsrc); sc->intr_en = 1; } set_i8254_freq(sc->mode, sc->period); return (0); } static int attimer_stop(struct eventtimer *et) { device_t dev = (device_t)et->et_priv; struct attimer_softc *sc = device_get_softc(dev); sc->mode = MODE_STOP; sc->period = 0; set_i8254_freq(sc->mode, sc->period); return (0); } #ifdef DEV_ISA /* * Attach to the ISA PnP descriptors for the timer */ static struct isa_pnp_id attimer_ids[] = { { 0x0001d041 /* PNP0100 */, "AT timer" }, { 0 } }; static int attimer_probe(device_t dev) { int result; result = ISA_PNP_PROBE(device_get_parent(dev), dev, attimer_ids); /* ENOENT means no PnP-ID, device is hinted. */ if (result == ENOENT) { device_set_desc(dev, "AT timer"); return (BUS_PROBE_LOW_PRIORITY); } return (result); } static int attimer_attach(device_t dev) { struct attimer_softc *sc; rman_res_t s; int i; attimer_sc = sc = device_get_softc(dev); bzero(sc, sizeof(struct attimer_softc)); if (!(sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT, &sc->port_rid, IO_TIMER1, IO_TIMER1 + 3, 4, RF_ACTIVE))) device_printf(dev,"Warning: Couldn't map I/O.\n"); i8254_intsrc = intr_lookup_source(0); if (i8254_intsrc != NULL) i8254_pending = i8254_intsrc->is_pic->pic_source_pending; resource_int_value(device_get_name(dev), device_get_unit(dev), "timecounter", &i8254_timecounter); set_i8254_freq(MODE_STOP, 0); if (i8254_timecounter) { sc->tc.tc_get_timecount = i8254_get_timecount; sc->tc.tc_counter_mask = 0xffff; sc->tc.tc_frequency = i8254_freq; sc->tc.tc_name = "i8254"; sc->tc.tc_quality = 0; sc->tc.tc_priv = dev; tc_init(&sc->tc); } if (resource_int_value(device_get_name(dev), device_get_unit(dev), "clock", &i) != 0 || i != 0) { sc->intr_rid = 0; while (bus_get_resource(dev, SYS_RES_IRQ, sc->intr_rid, &s, NULL) == 0 && s != 0) sc->intr_rid++; if (!(sc->intr_res = bus_alloc_resource(dev, SYS_RES_IRQ, &sc->intr_rid, 0, 0, 1, RF_ACTIVE))) { device_printf(dev,"Can't map interrupt.\n"); return (0); } /* Dirty hack, to make bus_setup_intr to not enable source. */ i8254_intsrc->is_handlers++; if ((bus_setup_intr(dev, sc->intr_res, INTR_MPSAFE | INTR_TYPE_CLK, (driver_filter_t *)clkintr, NULL, sc, &sc->intr_handler))) { device_printf(dev, "Can't setup interrupt.\n"); i8254_intsrc->is_handlers--; return (0); } i8254_intsrc->is_handlers--; i8254_intsrc->is_pic->pic_enable_intr(i8254_intsrc); sc->et.et_name = "i8254"; sc->et.et_flags = ET_FLAGS_PERIODIC; if (!i8254_timecounter) sc->et.et_flags |= ET_FLAGS_ONESHOT; sc->et.et_quality = 100; sc->et.et_frequency = i8254_freq; sc->et.et_min_period = (0x0002LLU << 32) / i8254_freq; sc->et.et_max_period = (0xfffeLLU << 32) / i8254_freq; sc->et.et_start = attimer_start; sc->et.et_stop = attimer_stop; sc->et.et_priv = dev; et_register(&sc->et); } return(0); } static int attimer_resume(device_t dev) { i8254_restore(); return (0); } static device_method_t attimer_methods[] = { /* Device interface */ DEVMETHOD(device_probe, attimer_probe), DEVMETHOD(device_attach, attimer_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, attimer_resume), { 0, 0 } }; static driver_t attimer_driver = { "attimer", attimer_methods, sizeof(struct attimer_softc), }; static devclass_t attimer_devclass; DRIVER_MODULE(attimer, isa, attimer_driver, attimer_devclass, 0, 0); DRIVER_MODULE(attimer, acpi, attimer_driver, attimer_devclass, 0, 0); +ISA_PNP_INFO(attimer_ids); #endif /* DEV_ISA */ Index: head/sys/x86/isa/isa_dma.c =================================================================== --- head/sys/x86/isa/isa_dma.c (revision 328523) +++ head/sys/x86/isa/isa_dma.c (revision 328524) @@ -1,614 +1,615 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 1991 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * William Jolitz. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)isa.c 7.2 (Berkeley) 5/13/91 */ #include __FBSDID("$FreeBSD$"); /* * code to manage AT bus * * 92/08/18 Frank P. MacLachlan (fpm@crash.cts.com): * Fixed uninitialized variable problem and added code to deal * with DMA page boundaries in isa_dmarangecheck(). Fixed word * mode DMA count compution and reorganized DMA setup code in * isa_dmastart() */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define ISARAM_END 0x1000000 static int isa_dmarangecheck(caddr_t va, u_int length, int chan); static caddr_t dma_bouncebuf[8]; static u_int dma_bouncebufsize[8]; static u_int8_t dma_bounced = 0; static u_int8_t dma_busy = 0; /* Used in isa_dmastart() */ static u_int8_t dma_inuse = 0; /* User for acquire/release */ static u_int8_t dma_auto_mode = 0; static struct mtx isa_dma_lock; MTX_SYSINIT(isa_dma_lock, &isa_dma_lock, "isa DMA lock", MTX_DEF); #define VALID_DMA_MASK (7) /* high byte of address is stored in this port for i-th dma channel */ static int dmapageport[8] = { 0x87, 0x83, 0x81, 0x82, 0x8f, 0x8b, 0x89, 0x8a }; /* * Setup a DMA channel's bounce buffer. */ int isa_dma_init(int chan, u_int bouncebufsize, int flag) { void *buf; int contig; #ifdef DIAGNOSTIC if (chan & ~VALID_DMA_MASK) panic("isa_dma_init: channel out of range"); #endif /* Try malloc() first. It works better if it works. */ buf = malloc(bouncebufsize, M_DEVBUF, flag); if (buf != NULL) { if (isa_dmarangecheck(buf, bouncebufsize, chan) != 0) { free(buf, M_DEVBUF); buf = NULL; } contig = 0; } if (buf == NULL) { buf = contigmalloc(bouncebufsize, M_DEVBUF, flag, 0ul, 0xfffffful, 1ul, chan & 4 ? 0x20000ul : 0x10000ul); contig = 1; } if (buf == NULL) return (ENOMEM); mtx_lock(&isa_dma_lock); /* * If a DMA channel is shared, both drivers have to call isa_dma_init * since they don't know that the other driver will do it. * Just return if we're already set up good. * XXX: this only works if they agree on the bouncebuf size. This * XXX: is typically the case since they are multiple instances of * XXX: the same driver. */ if (dma_bouncebuf[chan] != NULL) { if (contig) contigfree(buf, bouncebufsize, M_DEVBUF); else free(buf, M_DEVBUF); mtx_unlock(&isa_dma_lock); return (0); } dma_bouncebufsize[chan] = bouncebufsize; dma_bouncebuf[chan] = buf; mtx_unlock(&isa_dma_lock); return (0); } /* * Register a DMA channel's usage. Usually called from a device driver * in open() or during its initialization. */ int isa_dma_acquire(chan) int chan; { #ifdef DIAGNOSTIC if (chan & ~VALID_DMA_MASK) panic("isa_dma_acquire: channel out of range"); #endif mtx_lock(&isa_dma_lock); if (dma_inuse & (1 << chan)) { printf("isa_dma_acquire: channel %d already in use\n", chan); mtx_unlock(&isa_dma_lock); return (EBUSY); } dma_inuse |= (1 << chan); dma_auto_mode &= ~(1 << chan); mtx_unlock(&isa_dma_lock); return (0); } /* * Unregister a DMA channel's usage. Usually called from a device driver * during close() or during its shutdown. */ void isa_dma_release(chan) int chan; { #ifdef DIAGNOSTIC if (chan & ~VALID_DMA_MASK) panic("isa_dma_release: channel out of range"); mtx_lock(&isa_dma_lock); if ((dma_inuse & (1 << chan)) == 0) printf("isa_dma_release: channel %d not in use\n", chan); #else mtx_lock(&isa_dma_lock); #endif if (dma_busy & (1 << chan)) { dma_busy &= ~(1 << chan); /* * XXX We should also do "dma_bounced &= (1 << chan);" * because we are acting on behalf of isa_dmadone() which * was not called to end the last DMA operation. This does * not matter now, but it may in the future. */ } dma_inuse &= ~(1 << chan); dma_auto_mode &= ~(1 << chan); mtx_unlock(&isa_dma_lock); } /* * isa_dmacascade(): program 8237 DMA controller channel to accept * external dma control by a board. */ void isa_dmacascade(chan) int chan; { #ifdef DIAGNOSTIC if (chan & ~VALID_DMA_MASK) panic("isa_dmacascade: channel out of range"); #endif mtx_lock(&isa_dma_lock); /* set dma channel mode, and set dma channel mode */ if ((chan & 4) == 0) { outb(DMA1_MODE, DMA37MD_CASCADE | chan); outb(DMA1_SMSK, chan); } else { outb(DMA2_MODE, DMA37MD_CASCADE | (chan & 3)); outb(DMA2_SMSK, chan & 3); } mtx_unlock(&isa_dma_lock); } /* * isa_dmastart(): program 8237 DMA controller channel, avoid page alignment * problems by using a bounce buffer. */ void isa_dmastart(int flags, caddr_t addr, u_int nbytes, int chan) { vm_paddr_t phys; int waport; caddr_t newaddr; int dma_range_checked; dma_range_checked = isa_dmarangecheck(addr, nbytes, chan); #ifdef DIAGNOSTIC if (chan & ~VALID_DMA_MASK) panic("isa_dmastart: channel out of range"); if ((chan < 4 && nbytes > (1<<16)) || (chan >= 4 && (nbytes > (1<<17) || (uintptr_t)addr & 1))) panic("isa_dmastart: impossible request"); mtx_lock(&isa_dma_lock); if ((dma_inuse & (1 << chan)) == 0) printf("isa_dmastart: channel %d not acquired\n", chan); #else mtx_lock(&isa_dma_lock); #endif #if 0 /* * XXX This should be checked, but drivers like ad1848 only call * isa_dmastart() once because they use Auto DMA mode. If we * leave this in, drivers that do this will print this continuously. */ if (dma_busy & (1 << chan)) printf("isa_dmastart: channel %d busy\n", chan); #endif dma_busy |= (1 << chan); if (dma_range_checked) { if (dma_bouncebuf[chan] == NULL || dma_bouncebufsize[chan] < nbytes) panic("isa_dmastart: bad bounce buffer"); dma_bounced |= (1 << chan); newaddr = dma_bouncebuf[chan]; /* copy bounce buffer on write */ if (!(flags & ISADMA_READ)) bcopy(addr, newaddr, nbytes); addr = newaddr; } /* translate to physical */ phys = pmap_extract(kernel_pmap, (vm_offset_t)addr); if (flags & ISADMA_RAW) { dma_auto_mode |= (1 << chan); } else { dma_auto_mode &= ~(1 << chan); } if ((chan & 4) == 0) { /* * Program one of DMA channels 0..3. These are * byte mode channels. */ /* set dma channel mode, and reset address ff */ /* If ISADMA_RAW flag is set, then use autoinitialise mode */ if (flags & ISADMA_RAW) { if (flags & ISADMA_READ) outb(DMA1_MODE, DMA37MD_AUTO|DMA37MD_WRITE|chan); else outb(DMA1_MODE, DMA37MD_AUTO|DMA37MD_READ|chan); } else if (flags & ISADMA_READ) outb(DMA1_MODE, DMA37MD_SINGLE|DMA37MD_WRITE|chan); else outb(DMA1_MODE, DMA37MD_SINGLE|DMA37MD_READ|chan); outb(DMA1_FFC, 0); /* send start address */ waport = DMA1_CHN(chan); outb(waport, phys); outb(waport, phys>>8); outb(dmapageport[chan], phys>>16); /* send count */ outb(waport + 1, --nbytes); outb(waport + 1, nbytes>>8); /* unmask channel */ outb(DMA1_SMSK, chan); } else { /* * Program one of DMA channels 4..7. These are * word mode channels. */ /* set dma channel mode, and reset address ff */ /* If ISADMA_RAW flag is set, then use autoinitialise mode */ if (flags & ISADMA_RAW) { if (flags & ISADMA_READ) outb(DMA2_MODE, DMA37MD_AUTO|DMA37MD_WRITE|(chan&3)); else outb(DMA2_MODE, DMA37MD_AUTO|DMA37MD_READ|(chan&3)); } else if (flags & ISADMA_READ) outb(DMA2_MODE, DMA37MD_SINGLE|DMA37MD_WRITE|(chan&3)); else outb(DMA2_MODE, DMA37MD_SINGLE|DMA37MD_READ|(chan&3)); outb(DMA2_FFC, 0); /* send start address */ waport = DMA2_CHN(chan - 4); outb(waport, phys>>1); outb(waport, phys>>9); outb(dmapageport[chan], phys>>16); /* send count */ nbytes >>= 1; outb(waport + 2, --nbytes); outb(waport + 2, nbytes>>8); /* unmask channel */ outb(DMA2_SMSK, chan & 3); } mtx_unlock(&isa_dma_lock); } void isa_dmadone(int flags, caddr_t addr, int nbytes, int chan) { #ifdef DIAGNOSTIC if (chan & ~VALID_DMA_MASK) panic("isa_dmadone: channel out of range"); if ((dma_inuse & (1 << chan)) == 0) printf("isa_dmadone: channel %d not acquired\n", chan); #endif mtx_lock(&isa_dma_lock); if (((dma_busy & (1 << chan)) == 0) && (dma_auto_mode & (1 << chan)) == 0 ) printf("isa_dmadone: channel %d not busy\n", chan); if ((dma_auto_mode & (1 << chan)) == 0) outb(chan & 4 ? DMA2_SMSK : DMA1_SMSK, (chan & 3) | 4); if (dma_bounced & (1 << chan)) { /* copy bounce buffer on read */ if (flags & ISADMA_READ) bcopy(dma_bouncebuf[chan], addr, nbytes); dma_bounced &= ~(1 << chan); } dma_busy &= ~(1 << chan); mtx_unlock(&isa_dma_lock); } /* * Check for problems with the address range of a DMA transfer * (non-contiguous physical pages, outside of bus address space, * crossing DMA page boundaries). * Return true if special handling needed. */ static int isa_dmarangecheck(caddr_t va, u_int length, int chan) { vm_paddr_t phys, priorpage = 0; vm_offset_t endva; u_int dma_pgmsk = (chan & 4) ? ~(128*1024-1) : ~(64*1024-1); endva = (vm_offset_t)round_page((vm_offset_t)va + length); for (; va < (caddr_t) endva ; va += PAGE_SIZE) { phys = trunc_page(pmap_extract(kernel_pmap, (vm_offset_t)va)); if (phys == 0) panic("isa_dmacheck: no physical page present"); if (phys >= ISARAM_END) return (1); if (priorpage) { if (priorpage + PAGE_SIZE != phys) return (1); /* check if crossing a DMA page boundary */ if (((u_int)priorpage ^ (u_int)phys) & dma_pgmsk) return (1); } priorpage = phys; } return (0); } /* * Query the progress of a transfer on a DMA channel. * * To avoid having to interrupt a transfer in progress, we sample * each of the high and low databytes twice, and apply the following * logic to determine the correct count. * * Reads are performed with interrupts disabled, thus it is to be * expected that the time between reads is very small. At most * one rollover in the low count byte can be expected within the * four reads that are performed. * * There are three gaps in which a rollover can occur : * * - read low1 * gap1 * - read high1 * gap2 * - read low2 * gap3 * - read high2 * * If a rollover occurs in gap1 or gap2, the low2 value will be * greater than the low1 value. In this case, low2 and high2 are a * corresponding pair. * * In any other case, low1 and high1 can be considered to be correct. * * The function returns the number of bytes remaining in the transfer, * or -1 if the channel requested is not active. * */ static int isa_dmastatus_locked(int chan) { u_long cnt = 0; int ffport, waport; u_long low1, high1, low2, high2; mtx_assert(&isa_dma_lock, MA_OWNED); /* channel active? */ if ((dma_inuse & (1 << chan)) == 0) { printf("isa_dmastatus: channel %d not active\n", chan); return(-1); } /* channel busy? */ if (((dma_busy & (1 << chan)) == 0) && (dma_auto_mode & (1 << chan)) == 0 ) { printf("chan %d not busy\n", chan); return -2 ; } if (chan < 4) { /* low DMA controller */ ffport = DMA1_FFC; waport = DMA1_CHN(chan) + 1; } else { /* high DMA controller */ ffport = DMA2_FFC; waport = DMA2_CHN(chan - 4) + 2; } disable_intr(); /* no interrupts Mr Jones! */ outb(ffport, 0); /* clear register LSB flipflop */ low1 = inb(waport); high1 = inb(waport); outb(ffport, 0); /* clear again */ low2 = inb(waport); high2 = inb(waport); enable_intr(); /* enable interrupts again */ /* * Now decide if a wrap has tried to skew our results. * Note that after TC, the count will read 0xffff, while we want * to return zero, so we add and then mask to compensate. */ if (low1 >= low2) { cnt = (low1 + (high1 << 8) + 1) & 0xffff; } else { cnt = (low2 + (high2 << 8) + 1) & 0xffff; } if (chan >= 4) /* high channels move words */ cnt *= 2; return(cnt); } int isa_dmastatus(int chan) { int status; mtx_lock(&isa_dma_lock); status = isa_dmastatus_locked(chan); mtx_unlock(&isa_dma_lock); return (status); } /* * Reached terminal count yet ? */ int isa_dmatc(int chan) { if (chan < 4) return(inb(DMA1_STATUS) & (1 << chan)); else return(inb(DMA2_STATUS) & (1 << (chan & 3))); } /* * Stop a DMA transfer currently in progress. */ int isa_dmastop(int chan) { int status; mtx_lock(&isa_dma_lock); if ((dma_inuse & (1 << chan)) == 0) printf("isa_dmastop: channel %d not acquired\n", chan); if (((dma_busy & (1 << chan)) == 0) && ((dma_auto_mode & (1 << chan)) == 0)) { printf("chan %d not busy\n", chan); mtx_unlock(&isa_dma_lock); return -2 ; } if ((chan & 4) == 0) { outb(DMA1_SMSK, (chan & 3) | 4 /* disable mask */); } else { outb(DMA2_SMSK, (chan & 3) | 4 /* disable mask */); } status = isa_dmastatus_locked(chan); mtx_unlock(&isa_dma_lock); return (status); } /* * Attach to the ISA PnP descriptor for the AT DMA controller */ static struct isa_pnp_id atdma_ids[] = { { 0x0002d041 /* PNP0200 */, "AT DMA controller" }, { 0 } }; static int atdma_probe(device_t dev) { int result; if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, atdma_ids)) <= 0) device_quiet(dev); return(result); } static int atdma_attach(device_t dev) { return(0); } static device_method_t atdma_methods[] = { /* Device interface */ DEVMETHOD(device_probe, atdma_probe), DEVMETHOD(device_attach, atdma_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), { 0, 0 } }; static driver_t atdma_driver = { "atdma", atdma_methods, 1, /* no softc */ }; static devclass_t atdma_devclass; DRIVER_MODULE(atdma, isa, atdma_driver, atdma_devclass, 0, 0); DRIVER_MODULE(atdma, acpi, atdma_driver, atdma_devclass, 0, 0); +ISA_PNP_INFO(atdma_ids); Index: head/sys/x86/isa/orm.c =================================================================== --- head/sys/x86/isa/orm.c (revision 328523) +++ head/sys/x86/isa/orm.c (revision 328524) @@ -1,190 +1,191 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2000 Nikolai Saoukh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * Driver to take care of holes in ISA I/O memory occupied * by option rom(s) */ #include #include #include #include #include #include #include #include #include #include #include #define IOMEM_START 0x0a0000 #define IOMEM_STEP 0x000800 #define IOMEM_END 0x100000 #define ORM_ID 0x00004d3e static struct isa_pnp_id orm_ids[] = { { ORM_ID, NULL }, /* ORM0000 */ { 0, NULL }, }; #define MAX_ROMS 32 struct orm_softc { int rnum; int rid[MAX_ROMS]; struct resource *res[MAX_ROMS]; }; static int orm_probe(device_t dev) { return (ISA_PNP_PROBE(device_get_parent(dev), dev, orm_ids)); } static int orm_attach(device_t dev) { return (0); } static void orm_identify(driver_t* driver, device_t parent) { bus_space_handle_t bh; bus_space_tag_t bt; device_t child; u_int32_t chunk = IOMEM_START; struct resource *res; int rid; u_int32_t rom_size; struct orm_softc *sc; u_int8_t buf[3]; if (resource_disabled("orm", 0)) return; child = BUS_ADD_CHILD(parent, ISA_ORDER_SENSITIVE, "orm", -1); device_set_driver(child, driver); isa_set_logicalid(child, ORM_ID); isa_set_vendorid(child, ORM_ID); sc = device_get_softc(child); sc->rnum = 0; while (sc->rnum < MAX_ROMS && chunk < IOMEM_END) { bus_set_resource(child, SYS_RES_MEMORY, sc->rnum, chunk, IOMEM_STEP); rid = sc->rnum; res = bus_alloc_resource_any(child, SYS_RES_MEMORY, &rid, RF_ACTIVE); if (res == NULL) { bus_delete_resource(child, SYS_RES_MEMORY, sc->rnum); chunk += IOMEM_STEP; continue; } bt = rman_get_bustag(res); bh = rman_get_bushandle(res); bus_space_read_region_1(bt, bh, 0, buf, sizeof(buf)); /* * We need to release and delete the resource since we're * changing its size, or the rom isn't there. There * is a checksum field in the ROM to prevent false * positives. However, some common hardware (IBM thinkpads) * neglects to put a valid checksum in the ROM, so we do * not double check the checksum here. On the ISA bus * areas that have no hardware read back as 0xff, so the * tests to see if we have 0x55 followed by 0xaa are * generally sufficient. */ bus_release_resource(child, SYS_RES_MEMORY, rid, res); bus_delete_resource(child, SYS_RES_MEMORY, sc->rnum); if (buf[0] != 0x55 || buf[1] != 0xAA || (buf[2] & 0x03) != 0) { chunk += IOMEM_STEP; continue; } rom_size = buf[2] << 9; bus_set_resource(child, SYS_RES_MEMORY, sc->rnum, chunk, rom_size); rid = sc->rnum; res = bus_alloc_resource_any(child, SYS_RES_MEMORY, &rid, 0); if (res == NULL) { bus_delete_resource(child, SYS_RES_MEMORY, sc->rnum); chunk += IOMEM_STEP; continue; } sc->rid[sc->rnum] = rid; sc->res[sc->rnum] = res; sc->rnum++; chunk += rom_size; } if (sc->rnum == 0) device_delete_child(parent, child); else if (sc->rnum == 1) device_set_desc(child, "ISA Option ROM"); else device_set_desc(child, "ISA Option ROMs"); } static int orm_detach(device_t dev) { int i; struct orm_softc *sc = device_get_softc(dev); for (i = 0; i < sc->rnum; i++) bus_release_resource(dev, SYS_RES_MEMORY, sc->rid[i], sc->res[i]); return (0); } static device_method_t orm_methods[] = { /* Device interface */ DEVMETHOD(device_identify, orm_identify), DEVMETHOD(device_probe, orm_probe), DEVMETHOD(device_attach, orm_attach), DEVMETHOD(device_detach, orm_detach), { 0, 0 } }; static driver_t orm_driver = { "orm", orm_methods, sizeof (struct orm_softc) }; static devclass_t orm_devclass; DRIVER_MODULE(orm, isa, orm_driver, orm_devclass, 0, 0); +ISA_PNP_INFO(orm_ids); Index: head/sys/x86/pci/pci_bus.c =================================================================== --- head/sys/x86/pci/pci_bus.c (revision 328523) +++ head/sys/x86/pci/pci_bus.c (revision 328524) @@ -1,767 +1,767 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1997, Stefan Esser * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice unmodified, this list of conditions, and the following * disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include "opt_cpu.h" #include #include #include #include #include #include #include #include #include #include #include #include #ifdef CPU_ELAN #include #endif #include #include #include #include "pcib_if.h" int legacy_pcib_maxslots(device_t dev) { return 31; } /* read configuration space register */ uint32_t legacy_pcib_read_config(device_t dev, u_int bus, u_int slot, u_int func, u_int reg, int bytes) { return(pci_cfgregread(bus, slot, func, reg, bytes)); } /* write configuration space register */ void legacy_pcib_write_config(device_t dev, u_int bus, u_int slot, u_int func, u_int reg, uint32_t data, int bytes) { pci_cfgregwrite(bus, slot, func, reg, data, bytes); } /* route interrupt */ static int legacy_pcib_route_interrupt(device_t pcib, device_t dev, int pin) { #ifdef __HAVE_PIR return (pci_pir_route_interrupt(pci_get_bus(dev), pci_get_slot(dev), pci_get_function(dev), pin)); #else /* No routing possible */ return (PCI_INVALID_IRQ); #endif } /* Pass MSI requests up to the nexus. */ int legacy_pcib_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs) { device_t bus; bus = device_get_parent(pcib); return (PCIB_ALLOC_MSI(device_get_parent(bus), dev, count, maxcount, irqs)); } int legacy_pcib_alloc_msix(device_t pcib, device_t dev, int *irq) { device_t bus; bus = device_get_parent(pcib); return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq)); } int legacy_pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr, uint32_t *data) { device_t bus, hostb; int error, func, slot; bus = device_get_parent(pcib); error = PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data); if (error) return (error); slot = legacy_get_pcislot(pcib); func = legacy_get_pcifunc(pcib); if (slot == -1 || func == -1) return (0); hostb = pci_find_bsf(0, slot, func); KASSERT(hostb != NULL, ("%s: missing hostb for 0:%d:%d", __func__, slot, func)); pci_ht_map_msi(hostb, *addr); return (0); } static const char * legacy_pcib_is_host_bridge(int bus, int slot, int func, uint32_t id, uint8_t class, uint8_t subclass, uint8_t *busnum) { #ifdef __i386__ const char *s = NULL; static uint8_t pxb[4]; /* hack for 450nx */ *busnum = 0; switch (id) { case 0x12258086: s = "Intel 824?? host to PCI bridge"; /* XXX This is a guess */ /* *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x41, 1); */ *busnum = bus; break; case 0x71208086: s = "Intel 82810 (i810 GMCH) Host To Hub bridge"; break; case 0x71228086: s = "Intel 82810-DC100 (i810-DC100 GMCH) Host To Hub bridge"; break; case 0x71248086: s = "Intel 82810E (i810E GMCH) Host To Hub bridge"; break; case 0x11308086: s = "Intel 82815 (i815 GMCH) Host To Hub bridge"; break; case 0x71808086: s = "Intel 82443LX (440 LX) host to PCI bridge"; break; case 0x71908086: s = "Intel 82443BX (440 BX) host to PCI bridge"; break; case 0x71928086: s = "Intel 82443BX host to PCI bridge (AGP disabled)"; break; case 0x71948086: s = "Intel 82443MX host to PCI bridge"; break; case 0x71a08086: s = "Intel 82443GX host to PCI bridge"; break; case 0x71a18086: s = "Intel 82443GX host to AGP bridge"; break; case 0x71a28086: s = "Intel 82443GX host to PCI bridge (AGP disabled)"; break; case 0x84c48086: s = "Intel 82454KX/GX (Orion) host to PCI bridge"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x4a, 1); break; case 0x84ca8086: /* * For the 450nx chipset, there is a whole bundle of * things pretending to be host bridges. The MIOC will * be seen first and isn't really a pci bridge (the * actual buses are attached to the PXB's). We need to * read the registers of the MIOC to figure out the * bus numbers for the PXB channels. * * Since the MIOC doesn't have a pci bus attached, we * pretend it wasn't there. */ pxb[0] = legacy_pcib_read_config(0, bus, slot, func, 0xd0, 1); /* BUSNO[0] */ pxb[1] = legacy_pcib_read_config(0, bus, slot, func, 0xd1, 1) + 1; /* SUBA[0]+1 */ pxb[2] = legacy_pcib_read_config(0, bus, slot, func, 0xd3, 1); /* BUSNO[1] */ pxb[3] = legacy_pcib_read_config(0, bus, slot, func, 0xd4, 1) + 1; /* SUBA[1]+1 */ return NULL; case 0x84cb8086: switch (slot) { case 0x12: s = "Intel 82454NX PXB#0, Bus#A"; *busnum = pxb[0]; break; case 0x13: s = "Intel 82454NX PXB#0, Bus#B"; *busnum = pxb[1]; break; case 0x14: s = "Intel 82454NX PXB#1, Bus#A"; *busnum = pxb[2]; break; case 0x15: s = "Intel 82454NX PXB#1, Bus#B"; *busnum = pxb[3]; break; } break; case 0x1A308086: s = "Intel 82845 Host to PCI bridge"; break; /* AMD -- vendor 0x1022 */ case 0x30001022: s = "AMD Elan SC520 host to PCI bridge"; #ifdef CPU_ELAN init_AMD_Elan_sc520(); #else printf( "*** WARNING: missing CPU_ELAN -- timekeeping may be wrong\n"); #endif break; case 0x70061022: s = "AMD-751 host to PCI bridge"; break; case 0x700e1022: s = "AMD-761 host to PCI bridge"; break; /* SiS -- vendor 0x1039 */ case 0x04961039: s = "SiS 85c496"; break; case 0x04061039: s = "SiS 85c501"; break; case 0x06011039: s = "SiS 85c601"; break; case 0x55911039: s = "SiS 5591 host to PCI bridge"; break; case 0x00011039: s = "SiS 5591 host to AGP bridge"; break; /* VLSI -- vendor 0x1004 */ case 0x00051004: s = "VLSI 82C592 Host to PCI bridge"; break; /* XXX Here is MVP3, I got the datasheet but NO M/B to test it */ /* totally. Please let me know if anything wrong. -F */ /* XXX need info on the MVP3 -- any takers? */ case 0x05981106: s = "VIA 82C598MVP (Apollo MVP3) host bridge"; break; /* AcerLabs -- vendor 0x10b9 */ /* Funny : The datasheet told me vendor id is "10b8",sub-vendor */ /* id is '10b9" but the register always shows "10b9". -Foxfair */ case 0x154110b9: s = "AcerLabs M1541 (Aladdin-V) PCI host bridge"; break; /* OPTi -- vendor 0x1045 */ case 0xc7011045: s = "OPTi 82C700 host to PCI bridge"; break; case 0xc8221045: s = "OPTi 82C822 host to PCI Bridge"; break; /* ServerWorks -- vendor 0x1166 */ case 0x00051166: s = "ServerWorks NB6536 2.0HE host to PCI bridge"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x44, 1); break; case 0x00061166: /* FALLTHROUGH */ case 0x00081166: /* FALLTHROUGH */ case 0x02011166: /* FALLTHROUGH */ case 0x010f1014: /* IBM re-badged ServerWorks chipset */ s = "ServerWorks host to PCI bridge"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x44, 1); break; case 0x00091166: s = "ServerWorks NB6635 3.0LE host to PCI bridge"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x44, 1); break; case 0x00101166: s = "ServerWorks CIOB30 host to PCI bridge"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x44, 1); break; case 0x00111166: /* FALLTHROUGH */ case 0x03021014: /* IBM re-badged ServerWorks chipset */ s = "ServerWorks CMIC-HE host to PCI-X bridge"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x44, 1); break; /* XXX unknown chipset, but working */ case 0x00171166: /* FALLTHROUGH */ case 0x01011166: case 0x01101166: case 0x02251166: s = "ServerWorks host to PCI bridge(unknown chipset)"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0x44, 1); break; /* Compaq/HP -- vendor 0x0e11 */ case 0x60100e11: s = "Compaq/HP Model 6010 HotPlug PCI Bridge"; *busnum = legacy_pcib_read_config(0, bus, slot, func, 0xc8, 1); break; /* Integrated Micro Solutions -- vendor 0x10e0 */ case 0x884910e0: s = "Integrated Micro Solutions VL Bridge"; break; default: if (class == PCIC_BRIDGE && subclass == PCIS_BRIDGE_HOST) s = "Host to PCI bridge"; break; } return s; #else const char *s = NULL; *busnum = 0; if (class == PCIC_BRIDGE && subclass == PCIS_BRIDGE_HOST) s = "Host to PCI bridge"; return s; #endif } /* * Scan the first pci bus for host-pci bridges and add pcib instances * to the nexus for each bridge. */ static void legacy_pcib_identify(driver_t *driver, device_t parent) { int bus, slot, func; uint8_t hdrtype; int found = 0; int pcifunchigh; int found824xx = 0; int found_orion = 0; device_t child; devclass_t pci_devclass; if (pci_cfgregopen() == 0) return; /* * Check to see if we haven't already had a PCI bus added * via some other means. If we have, bail since otherwise * we're going to end up duplicating it. */ if ((pci_devclass = devclass_find("pci")) && devclass_get_device(pci_devclass, 0)) return; bus = 0; retry: for (slot = 0; slot <= PCI_SLOTMAX; slot++) { func = 0; hdrtype = legacy_pcib_read_config(0, bus, slot, func, PCIR_HDRTYPE, 1); /* * When enumerating bus devices, the standard says that * one should check the header type and ignore the slots whose * header types that the software doesn't know about. We use * this to filter out devices. */ if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE) continue; if ((hdrtype & PCIM_MFDEV) && (!found_orion || hdrtype != 0xff)) pcifunchigh = PCI_FUNCMAX; else pcifunchigh = 0; for (func = 0; func <= pcifunchigh; func++) { /* * Read the IDs and class from the device. */ uint32_t id; uint8_t class, subclass, busnum; const char *s; device_t *devs; int ndevs, i; id = legacy_pcib_read_config(0, bus, slot, func, PCIR_DEVVENDOR, 4); if (id == -1) continue; class = legacy_pcib_read_config(0, bus, slot, func, PCIR_CLASS, 1); subclass = legacy_pcib_read_config(0, bus, slot, func, PCIR_SUBCLASS, 1); s = legacy_pcib_is_host_bridge(bus, slot, func, id, class, subclass, &busnum); if (s == NULL) continue; /* * Check to see if the physical bus has already * been seen. Eg: hybrid 32 and 64 bit host * bridges to the same logical bus. */ if (device_get_children(parent, &devs, &ndevs) == 0) { for (i = 0; s != NULL && i < ndevs; i++) { if (strcmp(device_get_name(devs[i]), "pcib") != 0) continue; if (legacy_get_pcibus(devs[i]) == busnum) s = NULL; } free(devs, M_TEMP); } if (s == NULL) continue; /* * Add at priority 100 to make sure we * go after any motherboard resources */ child = BUS_ADD_CHILD(parent, 100, "pcib", busnum); device_set_desc(child, s); legacy_set_pcibus(child, busnum); legacy_set_pcislot(child, slot); legacy_set_pcifunc(child, func); found = 1; if (id == 0x12258086) found824xx = 1; if (id == 0x84c48086) found_orion = 1; } } if (found824xx && bus == 0) { bus++; goto retry; } /* * Make sure we add at least one bridge since some old * hardware doesn't actually have a host-pci bridge device. * Note that pci_cfgregopen() thinks we have PCI devices.. */ if (!found) { if (bootverbose) printf( "legacy_pcib_identify: no bridge found, adding pcib0 anyway\n"); child = BUS_ADD_CHILD(parent, 100, "pcib", 0); legacy_set_pcibus(child, 0); } } static int legacy_pcib_probe(device_t dev) { if (pci_cfgregopen() == 0) return ENXIO; return -100; } static int legacy_pcib_attach(device_t dev) { #ifdef __HAVE_PIR device_t pir; #endif int bus; bus = pcib_get_bus(dev); #ifdef __HAVE_PIR /* * Look for a PCI BIOS interrupt routing table as that will be * our method of routing interrupts if we have one. */ if (pci_pir_probe(bus, 0)) { pir = BUS_ADD_CHILD(device_get_parent(dev), 0, "pir", 0); if (pir != NULL) device_probe_and_attach(pir); } #endif device_add_child(dev, "pci", -1); return bus_generic_attach(dev); } int legacy_pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result) { switch (which) { case PCIB_IVAR_DOMAIN: *result = 0; return 0; case PCIB_IVAR_BUS: *result = legacy_get_pcibus(dev); return 0; } return ENOENT; } int legacy_pcib_write_ivar(device_t dev, device_t child, int which, uintptr_t value) { switch (which) { case PCIB_IVAR_DOMAIN: return EINVAL; case PCIB_IVAR_BUS: legacy_set_pcibus(dev, value); return 0; } return ENOENT; } /* * Helper routine for x86 Host-PCI bridge driver resource allocation. * This is used to adjust the start address of wildcard allocation * requests to avoid low addresses that are known to be problematic. * * If no memory preference is given, use upper 32MB slot most BIOSes * use for their memory window. This is typically only used on older * laptops that don't have PCI buses behind a PCI bridge, so assuming * > 32MB is likely OK. * * However, this can cause problems for other chipsets, so we make * this tunable by hw.pci.host_mem_start. */ SYSCTL_DECL(_hw_pci); static unsigned long host_mem_start = 0x80000000; SYSCTL_ULONG(_hw_pci, OID_AUTO, host_mem_start, CTLFLAG_RDTUN, &host_mem_start, 0, "Limit the host bridge memory to being above this address."); rman_res_t hostb_alloc_start(int type, rman_res_t start, rman_res_t end, rman_res_t count) { if (start + count - 1 != end) { if (type == SYS_RES_MEMORY && start < host_mem_start) start = host_mem_start; if (type == SYS_RES_IOPORT && start < 0x1000) start = 0x1000; } return (start); } struct resource * legacy_pcib_alloc_resource(device_t dev, device_t child, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) { #if defined(NEW_PCIB) && defined(PCI_RES_BUS) if (type == PCI_RES_BUS) return (pci_domain_alloc_bus(0, child, rid, start, end, count, flags)); #endif start = hostb_alloc_start(type, start, end, count); return (bus_generic_alloc_resource(dev, child, type, rid, start, end, count, flags)); } #if defined(NEW_PCIB) && defined(PCI_RES_BUS) int legacy_pcib_adjust_resource(device_t dev, device_t child, int type, struct resource *r, rman_res_t start, rman_res_t end) { if (type == PCI_RES_BUS) return (pci_domain_adjust_bus(0, child, r, start, end)); return (bus_generic_adjust_resource(dev, child, type, r, start, end)); } int legacy_pcib_release_resource(device_t dev, device_t child, int type, int rid, struct resource *r) { if (type == PCI_RES_BUS) return (pci_domain_release_bus(0, child, rid, r)); return (bus_generic_release_resource(dev, child, type, rid, r)); } #endif static device_method_t legacy_pcib_methods[] = { /* Device interface */ DEVMETHOD(device_identify, legacy_pcib_identify), DEVMETHOD(device_probe, legacy_pcib_probe), DEVMETHOD(device_attach, legacy_pcib_attach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), /* Bus interface */ DEVMETHOD(bus_read_ivar, legacy_pcib_read_ivar), DEVMETHOD(bus_write_ivar, legacy_pcib_write_ivar), DEVMETHOD(bus_alloc_resource, legacy_pcib_alloc_resource), #if defined(NEW_PCIB) && defined(PCI_RES_BUS) DEVMETHOD(bus_adjust_resource, legacy_pcib_adjust_resource), DEVMETHOD(bus_release_resource, legacy_pcib_release_resource), #else DEVMETHOD(bus_adjust_resource, bus_generic_adjust_resource), DEVMETHOD(bus_release_resource, bus_generic_release_resource), #endif DEVMETHOD(bus_activate_resource, bus_generic_activate_resource), DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource), DEVMETHOD(bus_setup_intr, bus_generic_setup_intr), DEVMETHOD(bus_teardown_intr, bus_generic_teardown_intr), /* pcib interface */ DEVMETHOD(pcib_maxslots, legacy_pcib_maxslots), DEVMETHOD(pcib_read_config, legacy_pcib_read_config), DEVMETHOD(pcib_write_config, legacy_pcib_write_config), DEVMETHOD(pcib_route_interrupt, legacy_pcib_route_interrupt), DEVMETHOD(pcib_alloc_msi, legacy_pcib_alloc_msi), DEVMETHOD(pcib_release_msi, pcib_release_msi), DEVMETHOD(pcib_alloc_msix, legacy_pcib_alloc_msix), DEVMETHOD(pcib_release_msix, pcib_release_msix), DEVMETHOD(pcib_map_msi, legacy_pcib_map_msi), DEVMETHOD(pcib_request_feature, pcib_request_feature_allow), DEVMETHOD_END }; static devclass_t hostb_devclass; DEFINE_CLASS_0(pcib, legacy_pcib_driver, legacy_pcib_methods, 1); DRIVER_MODULE(pcib, legacy, legacy_pcib_driver, hostb_devclass, 0, 0); /* * Install placeholder to claim the resources owned by the * PCI bus interface. This could be used to extract the * config space registers in the extreme case where the PnP * ID is available and the PCI BIOS isn't, but for now we just * eat the PnP ID and do nothing else. * - * XXX we should silence this probe, as it will generally confuse - * people. + * we silence this probe, as it will generally confuse people. */ static struct isa_pnp_id pcibus_pnp_ids[] = { { 0x030ad041 /* PNP0A03 */, "PCI Bus" }, { 0x080ad041 /* PNP0A08 */, "PCIe Bus" }, { 0 } }; static int pcibus_pnp_probe(device_t dev) { int result; if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, pcibus_pnp_ids)) <= 0) device_quiet(dev); return(result); } static int pcibus_pnp_attach(device_t dev) { return(0); } static device_method_t pcibus_pnp_methods[] = { /* Device interface */ DEVMETHOD(device_probe, pcibus_pnp_probe), DEVMETHOD(device_attach, pcibus_pnp_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), { 0, 0 } }; static devclass_t pcibus_pnp_devclass; DEFINE_CLASS_0(pcibus_pnp, pcibus_pnp_driver, pcibus_pnp_methods, 1); DRIVER_MODULE(pcibus_pnp, isa, pcibus_pnp_driver, pcibus_pnp_devclass, 0, 0); #ifdef __HAVE_PIR /* * Provide a PCI-PCI bridge driver for PCI buses behind PCI-PCI bridges * that appear in the PCIBIOS Interrupt Routing Table to use the routing * table for interrupt routing when possible. */ static int pcibios_pcib_probe(device_t bus); static device_method_t pcibios_pcib_pci_methods[] = { /* Device interface */ DEVMETHOD(device_probe, pcibios_pcib_probe), /* pcib interface */ DEVMETHOD(pcib_route_interrupt, legacy_pcib_route_interrupt), {0, 0} }; static devclass_t pcib_devclass; DEFINE_CLASS_1(pcib, pcibios_pcib_driver, pcibios_pcib_pci_methods, sizeof(struct pcib_softc), pcib_driver); DRIVER_MODULE(pcibios_pcib, pci, pcibios_pcib_driver, pcib_devclass, 0, 0); +ISA_PNP_INFO(pcibus_pnp_ids); static int pcibios_pcib_probe(device_t dev) { int bus; if ((pci_get_class(dev) != PCIC_BRIDGE) || (pci_get_subclass(dev) != PCIS_BRIDGE_PCI)) return (ENXIO); bus = pci_read_config(dev, PCIR_SECBUS_1, 1); if (bus == 0) return (ENXIO); if (!pci_pir_probe(bus, 1)) return (ENXIO); device_set_desc(dev, "PCIBIOS PCI-PCI bridge"); return (-2000); } #endif Index: head/sys/x86/x86/nexus.c =================================================================== --- head/sys/x86/x86/nexus.c (revision 328523) +++ head/sys/x86/x86/nexus.c (revision 328524) @@ -1,904 +1,905 @@ /*- * Copyright 1998 Massachusetts Institute of Technology * * Permission to use, copy, modify, and distribute this software and * its documentation for any purpose and without fee is hereby * granted, provided that both the above copyright notice and this * permission notice appear in all copies, that both the above * copyright notice and this permission notice appear in all * supporting documentation, and that the name of M.I.T. not be used * in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. M.I.T. makes * no representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied * warranty. * * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * This code implements a `root nexus' for Intel Architecture * machines. The function of the root nexus is to serve as an * attachment point for both processors and buses, and to manage * resources which are common to all of them. In particular, * this code implements the core resource managers for interrupt * requests, DMA requests (which rightfully should be a part of the * ISA code but it's easier to do it here for now), I/O port addresses, * and I/O memory address space. */ #ifdef __amd64__ #define DEV_APIC #else #include "opt_apic.h" #endif #include "opt_isa.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef DEV_APIC #include "pcib_if.h" #endif #ifdef DEV_ISA #include #include #endif #include #define ELF_KERN_STR ("elf"__XSTRING(__ELF_WORD_SIZE)" kernel") static MALLOC_DEFINE(M_NEXUSDEV, "nexusdev", "Nexus device"); #define DEVTONX(dev) ((struct nexus_device *)device_get_ivars(dev)) struct rman irq_rman, drq_rman, port_rman, mem_rman; static int nexus_probe(device_t); static int nexus_attach(device_t); static int nexus_print_all_resources(device_t dev); static int nexus_print_child(device_t, device_t); static device_t nexus_add_child(device_t bus, u_int order, const char *name, int unit); static struct resource *nexus_alloc_resource(device_t, device_t, int, int *, rman_res_t, rman_res_t, rman_res_t, u_int); static int nexus_adjust_resource(device_t, device_t, int, struct resource *, rman_res_t, rman_res_t); #ifdef SMP static int nexus_bind_intr(device_t, device_t, struct resource *, int); #endif static int nexus_config_intr(device_t, int, enum intr_trigger, enum intr_polarity); static int nexus_describe_intr(device_t dev, device_t child, struct resource *irq, void *cookie, const char *descr); static int nexus_activate_resource(device_t, device_t, int, int, struct resource *); static int nexus_deactivate_resource(device_t, device_t, int, int, struct resource *); static int nexus_map_resource(device_t bus, device_t child, int type, struct resource *r, struct resource_map_request *argsp, struct resource_map *map); static int nexus_unmap_resource(device_t bus, device_t child, int type, struct resource *r, struct resource_map *map); static int nexus_release_resource(device_t, device_t, int, int, struct resource *); static int nexus_setup_intr(device_t, device_t, struct resource *, int flags, driver_filter_t filter, void (*)(void *), void *, void **); static int nexus_teardown_intr(device_t, device_t, struct resource *, void *); static struct resource_list *nexus_get_reslist(device_t dev, device_t child); static int nexus_set_resource(device_t, device_t, int, int, rman_res_t, rman_res_t); static int nexus_get_resource(device_t, device_t, int, int, rman_res_t *, rman_res_t *); static void nexus_delete_resource(device_t, device_t, int, int); static int nexus_get_cpus(device_t, device_t, enum cpu_sets, size_t, cpuset_t *); #ifdef DEV_APIC static int nexus_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs); static int nexus_release_msi(device_t pcib, device_t dev, int count, int *irqs); static int nexus_alloc_msix(device_t pcib, device_t dev, int *irq); static int nexus_release_msix(device_t pcib, device_t dev, int irq); static int nexus_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr, uint32_t *data); #endif static device_method_t nexus_methods[] = { /* Device interface */ DEVMETHOD(device_probe, nexus_probe), DEVMETHOD(device_attach, nexus_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), /* Bus interface */ DEVMETHOD(bus_print_child, nexus_print_child), DEVMETHOD(bus_add_child, nexus_add_child), DEVMETHOD(bus_alloc_resource, nexus_alloc_resource), DEVMETHOD(bus_adjust_resource, nexus_adjust_resource), DEVMETHOD(bus_release_resource, nexus_release_resource), DEVMETHOD(bus_activate_resource, nexus_activate_resource), DEVMETHOD(bus_deactivate_resource, nexus_deactivate_resource), DEVMETHOD(bus_map_resource, nexus_map_resource), DEVMETHOD(bus_unmap_resource, nexus_unmap_resource), DEVMETHOD(bus_setup_intr, nexus_setup_intr), DEVMETHOD(bus_teardown_intr, nexus_teardown_intr), #ifdef SMP DEVMETHOD(bus_bind_intr, nexus_bind_intr), #endif DEVMETHOD(bus_config_intr, nexus_config_intr), DEVMETHOD(bus_describe_intr, nexus_describe_intr), DEVMETHOD(bus_get_resource_list, nexus_get_reslist), DEVMETHOD(bus_set_resource, nexus_set_resource), DEVMETHOD(bus_get_resource, nexus_get_resource), DEVMETHOD(bus_delete_resource, nexus_delete_resource), DEVMETHOD(bus_get_cpus, nexus_get_cpus), /* pcib interface */ #ifdef DEV_APIC DEVMETHOD(pcib_alloc_msi, nexus_alloc_msi), DEVMETHOD(pcib_release_msi, nexus_release_msi), DEVMETHOD(pcib_alloc_msix, nexus_alloc_msix), DEVMETHOD(pcib_release_msix, nexus_release_msix), DEVMETHOD(pcib_map_msi, nexus_map_msi), #endif { 0, 0 } }; DEFINE_CLASS_0(nexus, nexus_driver, nexus_methods, 1); static devclass_t nexus_devclass; DRIVER_MODULE(nexus, root, nexus_driver, nexus_devclass, 0, 0); static int nexus_probe(device_t dev) { device_quiet(dev); /* suppress attach message for neatness */ return (BUS_PROBE_GENERIC); } void nexus_init_resources(void) { int irq; /* * XXX working notes: * * - IRQ resource creation should be moved to the PIC/APIC driver. * - DRQ resource creation should be moved to the DMAC driver. * - The above should be sorted to probe earlier than any child buses. * * - Leave I/O and memory creation here, as child probes may need them. * (especially eg. ACPI) */ /* * IRQ's are on the mainboard on old systems, but on the ISA part * of PCI->ISA bridges. There would be multiple sets of IRQs on * multi-ISA-bus systems. PCI interrupts are routed to the ISA * component, so in a way, PCI can be a partial child of an ISA bus(!). * APIC interrupts are global though. */ irq_rman.rm_start = 0; irq_rman.rm_type = RMAN_ARRAY; irq_rman.rm_descr = "Interrupt request lines"; irq_rman.rm_end = NUM_IO_INTS - 1; if (rman_init(&irq_rman)) panic("nexus_init_resources irq_rman"); /* * We search for regions of existing IRQs and add those to the IRQ * resource manager. */ for (irq = 0; irq < NUM_IO_INTS; irq++) if (intr_lookup_source(irq) != NULL) if (rman_manage_region(&irq_rman, irq, irq) != 0) panic("nexus_init_resources irq_rman add"); /* * ISA DMA on PCI systems is implemented in the ISA part of each * PCI->ISA bridge and the channels can be duplicated if there are * multiple bridges. (eg: laptops with docking stations) */ drq_rman.rm_start = 0; drq_rman.rm_end = 7; drq_rman.rm_type = RMAN_ARRAY; drq_rman.rm_descr = "DMA request lines"; /* XXX drq 0 not available on some machines */ if (rman_init(&drq_rman) || rman_manage_region(&drq_rman, drq_rman.rm_start, drq_rman.rm_end)) panic("nexus_init_resources drq_rman"); /* * However, IO ports and Memory truely are global at this level, * as are APIC interrupts (however many IO APICS there turn out * to be on large systems..) */ port_rman.rm_start = 0; port_rman.rm_end = 0xffff; port_rman.rm_type = RMAN_ARRAY; port_rman.rm_descr = "I/O ports"; if (rman_init(&port_rman) || rman_manage_region(&port_rman, 0, 0xffff)) panic("nexus_init_resources port_rman"); mem_rman.rm_start = 0; #ifndef PAE mem_rman.rm_end = BUS_SPACE_MAXADDR; #else mem_rman.rm_end = ((1ULL << cpu_maxphyaddr) - 1); #endif mem_rman.rm_type = RMAN_ARRAY; mem_rman.rm_descr = "I/O memory addresses"; if (rman_init(&mem_rman) || rman_manage_region(&mem_rman, 0, mem_rman.rm_end)) panic("nexus_init_resources mem_rman"); } static int nexus_attach(device_t dev) { nexus_init_resources(); bus_generic_probe(dev); /* * Explicitly add the legacy0 device here. Other platform * types (such as ACPI), use their own nexus(4) subclass * driver to override this routine and add their own root bus. */ if (BUS_ADD_CHILD(dev, 10, "legacy", 0) == NULL) panic("legacy: could not attach"); bus_generic_attach(dev); return 0; } static int nexus_print_all_resources(device_t dev) { struct nexus_device *ndev = DEVTONX(dev); struct resource_list *rl = &ndev->nx_resources; int retval = 0; if (STAILQ_FIRST(rl)) retval += printf(" at"); retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#jx"); retval += resource_list_print_type(rl, "iomem", SYS_RES_MEMORY, "%#jx"); retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%jd"); return retval; } static int nexus_print_child(device_t bus, device_t child) { int retval = 0; retval += bus_print_child_header(bus, child); retval += nexus_print_all_resources(child); if (device_get_flags(child)) retval += printf(" flags %#x", device_get_flags(child)); retval += printf(" on motherboard\n"); /* XXX "motherboard", ick */ return (retval); } static device_t nexus_add_child(device_t bus, u_int order, const char *name, int unit) { device_t child; struct nexus_device *ndev; ndev = malloc(sizeof(struct nexus_device), M_NEXUSDEV, M_NOWAIT|M_ZERO); if (!ndev) return(0); resource_list_init(&ndev->nx_resources); child = device_add_child_ordered(bus, order, name, unit); /* should we free this in nexus_child_detached? */ device_set_ivars(child, ndev); return(child); } static struct rman * nexus_rman(int type) { switch (type) { case SYS_RES_IRQ: return (&irq_rman); case SYS_RES_DRQ: return (&drq_rman); case SYS_RES_IOPORT: return (&port_rman); case SYS_RES_MEMORY: return (&mem_rman); default: return (NULL); } } /* * Allocate a resource on behalf of child. NB: child is usually going to be a * child of one of our descendants, not a direct child of nexus0. * (Exceptions include npx.) */ static struct resource * nexus_alloc_resource(device_t bus, device_t child, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) { struct nexus_device *ndev = DEVTONX(child); struct resource *rv; struct resource_list_entry *rle; struct rman *rm; int needactivate = flags & RF_ACTIVE; /* * If this is an allocation of the "default" range for a given * RID, and we know what the resources for this device are * (ie. they aren't maintained by a child bus), then work out * the start/end values. */ if (RMAN_IS_DEFAULT_RANGE(start, end) && (count == 1)) { if (device_get_parent(child) != bus || ndev == NULL) return(NULL); rle = resource_list_find(&ndev->nx_resources, type, *rid); if (rle == NULL) return(NULL); start = rle->start; end = rle->end; count = rle->count; } flags &= ~RF_ACTIVE; rm = nexus_rman(type); if (rm == NULL) return (NULL); rv = rman_reserve_resource(rm, start, end, count, flags, child); if (rv == NULL) return 0; rman_set_rid(rv, *rid); if (needactivate) { if (bus_activate_resource(child, type, *rid, rv)) { rman_release_resource(rv); return 0; } } return rv; } static int nexus_adjust_resource(device_t bus, device_t child, int type, struct resource *r, rman_res_t start, rman_res_t end) { struct rman *rm; rm = nexus_rman(type); if (rm == NULL) return (ENXIO); if (!rman_is_region_manager(r, rm)) return (EINVAL); return (rman_adjust_resource(r, start, end)); } static int nexus_activate_resource(device_t bus, device_t child, int type, int rid, struct resource *r) { struct resource_map map; int error; error = rman_activate_resource(r); if (error != 0) return (error); if (!(rman_get_flags(r) & RF_UNMAPPED) && (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT)) { error = nexus_map_resource(bus, child, type, r, NULL, &map); if (error) { rman_deactivate_resource(r); return (error); } rman_set_mapping(r,&map); } return (0); } static int nexus_deactivate_resource(device_t bus, device_t child, int type, int rid, struct resource *r) { struct resource_map map; int error; error = rman_deactivate_resource(r); if (error) return (error); if (!(rman_get_flags(r) & RF_UNMAPPED) && (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT)) { rman_get_mapping(r, &map); nexus_unmap_resource(bus, child, type, r, &map); } return (0); } static int nexus_map_resource(device_t bus, device_t child, int type, struct resource *r, struct resource_map_request *argsp, struct resource_map *map) { struct resource_map_request args; rman_res_t end, length, start; /* Resources must be active to be mapped. */ if (!(rman_get_flags(r) & RF_ACTIVE)) return (ENXIO); /* Mappings are only supported on I/O and memory resources. */ switch (type) { case SYS_RES_IOPORT: case SYS_RES_MEMORY: break; default: return (EINVAL); } resource_init_map_request(&args); if (argsp != NULL) bcopy(argsp, &args, imin(argsp->size, args.size)); start = rman_get_start(r) + args.offset; if (args.length == 0) length = rman_get_size(r); else length = args.length; end = start + length - 1; if (start > rman_get_end(r) || start < rman_get_start(r)) return (EINVAL); if (end > rman_get_end(r) || end < start) return (EINVAL); /* * If this is a memory resource, map it into the kernel. */ switch (type) { case SYS_RES_IOPORT: map->r_bushandle = start; map->r_bustag = X86_BUS_SPACE_IO; map->r_size = length; map->r_vaddr = NULL; break; case SYS_RES_MEMORY: map->r_vaddr = pmap_mapdev_attr(start, length, args.memattr); map->r_bustag = X86_BUS_SPACE_MEM; map->r_size = length; /* * The handle is the virtual address. */ map->r_bushandle = (bus_space_handle_t)map->r_vaddr; break; } return (0); } static int nexus_unmap_resource(device_t bus, device_t child, int type, struct resource *r, struct resource_map *map) { /* * If this is a memory resource, unmap it. */ switch (type) { case SYS_RES_MEMORY: pmap_unmapdev((vm_offset_t)map->r_vaddr, map->r_size); /* FALLTHROUGH */ case SYS_RES_IOPORT: break; default: return (EINVAL); } return (0); } static int nexus_release_resource(device_t bus, device_t child, int type, int rid, struct resource *r) { if (rman_get_flags(r) & RF_ACTIVE) { int error = bus_deactivate_resource(child, type, rid, r); if (error) return error; } return (rman_release_resource(r)); } /* * Currently this uses the really grody interface from kern/kern_intr.c * (which really doesn't belong in kern/anything.c). Eventually, all of * the code in kern_intr.c and machdep_intr.c should get moved here, since * this is going to be the official interface. */ static int nexus_setup_intr(device_t bus, device_t child, struct resource *irq, int flags, driver_filter_t filter, void (*ihand)(void *), void *arg, void **cookiep) { int error; /* somebody tried to setup an irq that failed to allocate! */ if (irq == NULL) panic("nexus_setup_intr: NULL irq resource!"); *cookiep = NULL; if ((rman_get_flags(irq) & RF_SHAREABLE) == 0) flags |= INTR_EXCL; /* * We depend here on rman_activate_resource() being idempotent. */ error = rman_activate_resource(irq); if (error) return (error); error = intr_add_handler(device_get_nameunit(child), rman_get_start(irq), filter, ihand, arg, flags, cookiep); return (error); } static int nexus_teardown_intr(device_t dev, device_t child, struct resource *r, void *ih) { return (intr_remove_handler(ih)); } #ifdef SMP static int nexus_bind_intr(device_t dev, device_t child, struct resource *irq, int cpu) { return (intr_bind(rman_get_start(irq), cpu)); } #endif static int nexus_config_intr(device_t dev, int irq, enum intr_trigger trig, enum intr_polarity pol) { return (intr_config_intr(irq, trig, pol)); } static int nexus_describe_intr(device_t dev, device_t child, struct resource *irq, void *cookie, const char *descr) { return (intr_describe(rman_get_start(irq), cookie, descr)); } static struct resource_list * nexus_get_reslist(device_t dev, device_t child) { struct nexus_device *ndev = DEVTONX(child); return (&ndev->nx_resources); } static int nexus_set_resource(device_t dev, device_t child, int type, int rid, rman_res_t start, rman_res_t count) { struct nexus_device *ndev = DEVTONX(child); struct resource_list *rl = &ndev->nx_resources; /* XXX this should return a success/failure indicator */ resource_list_add(rl, type, rid, start, start + count - 1, count); return(0); } static int nexus_get_resource(device_t dev, device_t child, int type, int rid, rman_res_t *startp, rman_res_t *countp) { struct nexus_device *ndev = DEVTONX(child); struct resource_list *rl = &ndev->nx_resources; struct resource_list_entry *rle; rle = resource_list_find(rl, type, rid); if (!rle) return(ENOENT); if (startp) *startp = rle->start; if (countp) *countp = rle->count; return(0); } static void nexus_delete_resource(device_t dev, device_t child, int type, int rid) { struct nexus_device *ndev = DEVTONX(child); struct resource_list *rl = &ndev->nx_resources; resource_list_delete(rl, type, rid); } static int nexus_get_cpus(device_t dev, device_t child, enum cpu_sets op, size_t setsize, cpuset_t *cpuset) { switch (op) { #ifdef SMP case INTR_CPUS: if (setsize != sizeof(cpuset_t)) return (EINVAL); *cpuset = intr_cpus; return (0); #endif default: return (bus_generic_get_cpus(dev, child, op, setsize, cpuset)); } } /* Called from the MSI code to add new IRQs to the IRQ rman. */ void nexus_add_irq(u_long irq) { if (rman_manage_region(&irq_rman, irq, irq) != 0) panic("%s: failed", __func__); } #ifdef DEV_APIC static int nexus_alloc_msix(device_t pcib, device_t dev, int *irq) { return (msix_alloc(dev, irq)); } static int nexus_release_msix(device_t pcib, device_t dev, int irq) { return (msix_release(irq)); } static int nexus_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs) { return (msi_alloc(dev, count, maxcount, irqs)); } static int nexus_release_msi(device_t pcib, device_t dev, int count, int *irqs) { return (msi_release(irqs, count)); } static int nexus_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr, uint32_t *data) { return (msi_map(irq, addr, data)); } #endif /* Placeholder for system RAM. */ static void ram_identify(driver_t *driver, device_t parent) { if (resource_disabled("ram", 0)) return; if (BUS_ADD_CHILD(parent, 0, "ram", 0) == NULL) panic("ram_identify"); } static int ram_probe(device_t dev) { device_quiet(dev); device_set_desc(dev, "System RAM"); return (0); } static int ram_attach(device_t dev) { struct bios_smap *smapbase, *smap, *smapend; struct resource *res; vm_paddr_t *p; caddr_t kmdp; uint32_t smapsize; int error, rid; /* Retrieve the system memory map from the loader. */ kmdp = preload_search_by_type("elf kernel"); if (kmdp == NULL) kmdp = preload_search_by_type(ELF_KERN_STR); smapbase = (struct bios_smap *)preload_search_info(kmdp, MODINFO_METADATA | MODINFOMD_SMAP); if (smapbase != NULL) { smapsize = *((u_int32_t *)smapbase - 1); smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize); rid = 0; for (smap = smapbase; smap < smapend; smap++) { if (smap->type != SMAP_TYPE_MEMORY || smap->length == 0) continue; #ifdef __i386__ /* * Resources use long's to track resources, so * we can't include memory regions above 4GB. */ if (smap->base > ~0ul) continue; #endif error = bus_set_resource(dev, SYS_RES_MEMORY, rid, smap->base, smap->length); if (error) panic( "ram_attach: resource %d failed set with %d", rid, error); res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, 0); if (res == NULL) panic("ram_attach: resource %d failed to attach", rid); rid++; } return (0); } /* * If the system map is not available, fall back to using * dump_avail[]. We use the dump_avail[] array rather than * phys_avail[] for the memory map as phys_avail[] contains * holes for kernel memory, page 0, the message buffer, and * the dcons buffer. We test the end address in the loop * instead of the start since the start address for the first * segment is 0. */ for (rid = 0, p = dump_avail; p[1] != 0; rid++, p += 2) { #ifdef PAE /* * Resources use long's to track resources, so we can't * include memory regions above 4GB. */ if (p[0] > ~0ul) break; #endif error = bus_set_resource(dev, SYS_RES_MEMORY, rid, p[0], p[1] - p[0]); if (error) panic("ram_attach: resource %d failed set with %d", rid, error); res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, 0); if (res == NULL) panic("ram_attach: resource %d failed to attach", rid); } return (0); } static device_method_t ram_methods[] = { /* Device interface */ DEVMETHOD(device_identify, ram_identify), DEVMETHOD(device_probe, ram_probe), DEVMETHOD(device_attach, ram_attach), { 0, 0 } }; static driver_t ram_driver = { "ram", ram_methods, 1, /* no softc */ }; static devclass_t ram_devclass; DRIVER_MODULE(ram, nexus, ram_driver, ram_devclass, 0, 0); #ifdef DEV_ISA /* * Placeholder which claims PnP 'devices' which describe system * resources. */ static struct isa_pnp_id sysresource_ids[] = { { 0x010cd041 /* PNP0c01 */, "System Memory" }, { 0x020cd041 /* PNP0c02 */, "System Resource" }, { 0 } }; static int sysresource_probe(device_t dev) { int result; if ((result = ISA_PNP_PROBE(device_get_parent(dev), dev, sysresource_ids)) <= 0) { device_quiet(dev); } return(result); } static int sysresource_attach(device_t dev) { return(0); } static device_method_t sysresource_methods[] = { /* Device interface */ DEVMETHOD(device_probe, sysresource_probe), DEVMETHOD(device_attach, sysresource_attach), DEVMETHOD(device_detach, bus_generic_detach), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), { 0, 0 } }; static driver_t sysresource_driver = { "sysresource", sysresource_methods, 1, /* no softc */ }; static devclass_t sysresource_devclass; DRIVER_MODULE(sysresource, isa, sysresource_driver, sysresource_devclass, 0, 0); +ISA_PNP_INFO(sysresource_ids); #endif /* DEV_ISA */